@resolveio/server-lib 20.13.3 → 20.13.5

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.
@@ -11,6 +11,7 @@ export interface WorkerConnection {
11
11
  method?: string;
12
12
  }[];
13
13
  workerIndex?: string;
14
+ workerInstance?: string;
14
15
  }
15
16
  export declare class WorkerDispatcherManager {
16
17
  private _websocketManager;
@@ -27,6 +28,7 @@ export declare class WorkerDispatcherManager {
27
28
  addWorker(ws: WebSocket.WebSocket): void;
28
29
  disconnectWorker(workerId: string): void;
29
30
  hasWorkers(): boolean;
31
+ hasWorkersForMethod(methodName: string): boolean;
30
32
  /**
31
33
  * Add a new task to our in-memory queue and try to dispatch.
32
34
  */
@@ -51,6 +53,9 @@ export declare class WorkerDispatcherManager {
51
53
  * Returns the worker with the fewest activeTasks that is under maxConcurrency and per-method limit.
52
54
  */
53
55
  private findWorkerForTask;
56
+ private normalizeWorkerIndex;
57
+ private getWorkerLoad;
58
+ private isWorkerZero;
54
59
  private assignTaskToWorker;
55
60
  /**
56
61
  * Handle messages coming back from a worker (like 'taskComplete').
@@ -29,7 +29,8 @@ var WorkerDispatcherManager = /** @class */ (function () {
29
29
  id: ws['id_worker'],
30
30
  ws: ws,
31
31
  activeTasks: [],
32
- workerIndex: ws['workerIndex']
32
+ workerIndex: ws['workerIndex'],
33
+ workerInstance: ws['workerInstance']
33
34
  });
34
35
  setInterval(function () {
35
36
  if (_this._methodManager.getEnableDebug()) {
@@ -51,6 +52,22 @@ var WorkerDispatcherManager = /** @class */ (function () {
51
52
  WorkerDispatcherManager.prototype.hasWorkers = function () {
52
53
  return this._workers.length > 0;
53
54
  };
55
+ WorkerDispatcherManager.prototype.hasWorkersForMethod = function (methodName) {
56
+ var _this = this;
57
+ if (!this._workers.length) {
58
+ return false;
59
+ }
60
+ var method = this._methodManager.getMethod(methodName);
61
+ var targetWorkerIndex = this.normalizeWorkerIndex(method === null || method === void 0 ? void 0 : method.targetWorkerIndex);
62
+ var targetWorkerInstance = this.normalizeWorkerIndex(method === null || method === void 0 ? void 0 : method.targetWorkerInstance);
63
+ if (!targetWorkerIndex && !targetWorkerInstance) {
64
+ return true;
65
+ }
66
+ return this._workers.some(function (worker) {
67
+ return (!targetWorkerIndex || _this.normalizeWorkerIndex(worker.workerIndex) === targetWorkerIndex) &&
68
+ (!targetWorkerInstance || _this.normalizeWorkerIndex(worker.workerInstance) === targetWorkerInstance);
69
+ });
70
+ };
54
71
  /**
55
72
  * Add a new task to our in-memory queue and try to dispatch.
56
73
  */
@@ -163,7 +180,16 @@ var WorkerDispatcherManager = /** @class */ (function () {
163
180
  var _this = this;
164
181
  var method = this._methodManager.getMethod(task.method);
165
182
  var methodLimit = method && method.maxConcurrency && method.maxConcurrency > 0 ? method.maxConcurrency : null;
183
+ var targetWorkerIndex = this.normalizeWorkerIndex(method === null || method === void 0 ? void 0 : method.targetWorkerIndex);
184
+ var targetWorkerInstance = this.normalizeWorkerIndex(method === null || method === void 0 ? void 0 : method.targetWorkerInstance);
185
+ var preferNonZero = !targetWorkerIndex;
166
186
  var candidates = this._workers.filter(function (x) { return x.activeTasks.length < _this.MAX_CONCURRENCY; });
187
+ if (targetWorkerIndex) {
188
+ candidates = candidates.filter(function (worker) { return _this.normalizeWorkerIndex(worker.workerIndex) === targetWorkerIndex; });
189
+ }
190
+ if (targetWorkerInstance) {
191
+ candidates = candidates.filter(function (worker) { return _this.normalizeWorkerIndex(worker.workerInstance) === targetWorkerInstance; });
192
+ }
167
193
  if (!candidates.length) {
168
194
  return null;
169
195
  }
@@ -184,12 +210,43 @@ var WorkerDispatcherManager = /** @class */ (function () {
184
210
  return null;
185
211
  }
186
212
  eligible.sort(function (x, y) {
187
- var totalX = x.activeTasks.map(function (a) { return a.weight; }).reduce(function (a, b) { return a + b; }, 0);
188
- var totalY = y.activeTasks.map(function (a) { return a.weight; }).reduce(function (a, b) { return a + b; }, 0);
189
- return totalX - totalY;
213
+ var totalX = _this.getWorkerLoad(x);
214
+ var totalY = _this.getWorkerLoad(y);
215
+ if (totalX !== totalY) {
216
+ return totalX - totalY;
217
+ }
218
+ if (preferNonZero) {
219
+ var xZero = _this.isWorkerZero(x) ? 1 : 0;
220
+ var yZero = _this.isWorkerZero(y) ? 1 : 0;
221
+ if (xZero !== yZero) {
222
+ return xZero - yZero;
223
+ }
224
+ }
225
+ var idxX = _this.normalizeWorkerIndex(x.workerIndex) || '';
226
+ var idxY = _this.normalizeWorkerIndex(y.workerIndex) || '';
227
+ var idxCompare = idxX.localeCompare(idxY, undefined, { numeric: true, sensitivity: 'base' });
228
+ if (idxCompare !== 0) {
229
+ return idxCompare;
230
+ }
231
+ var instX = _this.normalizeWorkerIndex(x.workerInstance) || '';
232
+ var instY = _this.normalizeWorkerIndex(y.workerInstance) || '';
233
+ return instX.localeCompare(instY, undefined, { numeric: true, sensitivity: 'base' });
190
234
  });
191
235
  return eligible[0];
192
236
  };
237
+ WorkerDispatcherManager.prototype.normalizeWorkerIndex = function (value) {
238
+ if (value === null || value === undefined) {
239
+ return null;
240
+ }
241
+ var normalized = String(value).trim();
242
+ return normalized.length ? normalized : null;
243
+ };
244
+ WorkerDispatcherManager.prototype.getWorkerLoad = function (worker) {
245
+ return worker.activeTasks.reduce(function (sum, task) { return sum + task.weight; }, 0);
246
+ };
247
+ WorkerDispatcherManager.prototype.isWorkerZero = function (worker) {
248
+ return this.normalizeWorkerIndex(worker.workerIndex) === '0';
249
+ };
193
250
  WorkerDispatcherManager.prototype.assignTaskToWorker = function (worker, task) {
194
251
  var _this = this;
195
252
  var method = this._methodManager.getMethod(task.method);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/worker-dispatcher.manager.ts"],"names":[],"mappings":";;;AAEA,yCAAgE;AAGhE,qCAAwC;AAoBxC;IAUC;QAPQ,aAAQ,GAAuB,EAAE,CAAC;QAClC,eAAU,GAAkB,EAAE,CAAC;QAC/B,oBAAe,GAAiC,EAAE,CAAC;QACnD,kBAAa,GAA6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;gBACjB,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;gBAClC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAEvC,IAAI,WAAW,CAAC,OAAO,EAAE,CAAC;oBACzB,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,kCAAkC,IAAG,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,QAAQ,EAAE,CAAA,CAAC,CAAC;gBAClF,CAAC;YACF,CAAC;QACF,CAAC;IACF,CAAC;IACF,8BAAC;AAAD,CA9eA,AA8eC,IAAA;AA9eY,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; method?: string }[];\n\tworkerIndex?: string;\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\tmethod?: string;\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\tworkerIndex: ws['workerIndex']\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 assigned = false;\n\n\t\t\tfor (let i = 0; i < this._taskQueue.length; i++) {\n\t\t\t\tlet task = this._taskQueue[i];\n\t\t\t\tlet targetWorker = this.findWorkerForTask(task);\n\n\t\t\t\tif (targetWorker) {\n\t\t\t\t\tthis._taskQueue.splice(i, 1);\n\t\t\t\t\tthis.assignTaskToWorker(targetWorker, task);\n\t\t\t\t\tassigned = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!assigned) {\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; // nothing can run right now due to per-worker limits\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency and per-method limit.\n\t */\n\tprivate findWorkerForTask(task: TaskPayload): WorkerConnection | null {\n\t\tlet method = this._methodManager.getMethod(task.method);\n\t\tlet methodLimit = method && method.maxConcurrency && method.maxConcurrency > 0 ? method.maxConcurrency : null;\n\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\tlet eligible = candidates.filter((worker) => {\n\t\t\tif (!methodLimit) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tlet idx = worker.workerIndex || 'unknown';\n\t\t\tlet current = 0;\n\n\t\t\tthis._workers.forEach((w) => {\n\t\t\t\tif ((w.workerIndex || 'unknown') === idx) {\n\t\t\t\t\tcurrent += w.activeTasks.filter(a => a.method === task.method).length;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn current < methodLimit;\n\t\t});\n\n\t\tif (!eligible.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\teligible.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 eligible[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\tmethod: task.method\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\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, method: task.method };\n\t\t}\n\t\telse {\n\t\t\texisting.method = task.method;\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\tlet unpackedResult = result;\n\n\t\t\tif (!error && unpackedResult === null && data['packedResult']) {\n\t\t\t\ttry {\n\t\t\t\t\tunpackedResult = unpack(data['packedResult']);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Failed to unpack worker result', err);\n\t\t\t\t}\n\t\t\t}\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(unpackedResult);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tpendingTask.promise.resolve(unpackedResult);\n\t\t\t\t\t}\n\t\t\t\t}\n\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\tif (!error && data['packedResult']) {\n\t\t\t\t\t\tthis._websocketManager.sendPackedBuffer(clientReqWS, messageId, false, data['packedResult'], data['encoding'] || 'msgpack');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._websocketManager.send(clientReqWS, res);\n\t\t\t\t\t}\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\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('Worker socket not open.');\n\t\t\t\t}\n\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"]}
1
+ {"version":3,"sources":["../../src/managers/worker-dispatcher.manager.ts"],"names":[],"mappings":";;;AAEA,yCAAgE;AAGhE,qCAAwC;AAqBxC;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;QACpE,OAAO,uBAAuB,CAAC;IAChC,CAAC;IAEM,4CAAU,GAAjB,UAAkB,gBAAkC,EAAE,aAA4B;QACjF,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C,CAAC;YACvC,EAAE,CAAC,KAAK,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,GAAG,CAAC,CAAC;YAEtD,IAAI,WAAW,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAEtD,IAAI,WAAW,EAAE,CAAC;gBACjB,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;gBAClC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAEvC,IAAI,WAAW,CAAC,OAAO,EAAE,CAAC;oBACzB,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,kCAAkC,IAAG,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,QAAQ,EAAE,CAAA,CAAC,CAAC;gBAClF,CAAC;YACF,CAAC;QACF,CAAC;IACF,CAAC;IACF,8BAAC;AAAD,CAjjBA,AAijBC,IAAA;AAjjBY,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; method?: string }[];\n\tworkerIndex?: string;\n\tworkerInstance?: string;\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\tmethod?: string;\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\tworkerIndex: ws['workerIndex'],\n\t\t\tworkerInstance: ws['workerInstance']\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\tpublic hasWorkersForMethod(methodName: string) {\n\t\tif (!this._workers.length) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst method = this._methodManager.getMethod(methodName);\n\t\tconst targetWorkerIndex = this.normalizeWorkerIndex(method?.targetWorkerIndex);\n\t\tconst targetWorkerInstance = this.normalizeWorkerIndex(method?.targetWorkerInstance);\n\n\t\tif (!targetWorkerIndex && !targetWorkerInstance) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn this._workers.some(worker =>\n\t\t\t(!targetWorkerIndex || this.normalizeWorkerIndex(worker.workerIndex) === targetWorkerIndex) &&\n\t\t\t(!targetWorkerInstance || this.normalizeWorkerIndex(worker.workerInstance) === targetWorkerInstance)\n\t\t);\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 assigned = false;\n\n\t\t\tfor (let i = 0; i < this._taskQueue.length; i++) {\n\t\t\t\tlet task = this._taskQueue[i];\n\t\t\t\tlet targetWorker = this.findWorkerForTask(task);\n\n\t\t\t\tif (targetWorker) {\n\t\t\t\t\tthis._taskQueue.splice(i, 1);\n\t\t\t\t\tthis.assignTaskToWorker(targetWorker, task);\n\t\t\t\t\tassigned = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!assigned) {\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; // nothing can run right now due to per-worker limits\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency and per-method limit.\n\t */\n\tprivate findWorkerForTask(task: TaskPayload): WorkerConnection | null {\n\t\tlet method = this._methodManager.getMethod(task.method);\n\t\tlet methodLimit = method && method.maxConcurrency && method.maxConcurrency > 0 ? method.maxConcurrency : null;\n\t\tlet targetWorkerIndex = this.normalizeWorkerIndex(method?.targetWorkerIndex);\n\t\tlet targetWorkerInstance = this.normalizeWorkerIndex(method?.targetWorkerInstance);\n\t\tconst preferNonZero = !targetWorkerIndex;\n\n\t\tlet candidates = this._workers.filter(x => x.activeTasks.length < this.MAX_CONCURRENCY);\n\t\tif (targetWorkerIndex) {\n\t\t\tcandidates = candidates.filter(worker => this.normalizeWorkerIndex(worker.workerIndex) === targetWorkerIndex);\n\t\t}\n\t\tif (targetWorkerInstance) {\n\t\t\tcandidates = candidates.filter(worker => this.normalizeWorkerIndex(worker.workerInstance) === targetWorkerInstance);\n\t\t}\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet eligible = candidates.filter((worker) => {\n\t\t\tif (!methodLimit) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tlet idx = worker.workerIndex || 'unknown';\n\t\t\tlet current = 0;\n\n\t\t\tthis._workers.forEach((w) => {\n\t\t\t\tif ((w.workerIndex || 'unknown') === idx) {\n\t\t\t\t\tcurrent += w.activeTasks.filter(a => a.method === task.method).length;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn current < methodLimit;\n\t\t});\n\n\t\tif (!eligible.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\teligible.sort((x, y) => {\n\t\t\tconst totalX = this.getWorkerLoad(x);\n\t\t\tconst totalY = this.getWorkerLoad(y);\n\t\t\tif (totalX !== totalY) {\n\t\t\t\treturn totalX - totalY;\n\t\t\t}\n\n\t\t\tif (preferNonZero) {\n\t\t\t\tconst xZero = this.isWorkerZero(x) ? 1 : 0;\n\t\t\t\tconst yZero = this.isWorkerZero(y) ? 1 : 0;\n\t\t\t\tif (xZero !== yZero) {\n\t\t\t\t\treturn xZero - yZero;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst idxX = this.normalizeWorkerIndex(x.workerIndex) || '';\n\t\t\tconst idxY = this.normalizeWorkerIndex(y.workerIndex) || '';\n\t\t\tconst idxCompare = idxX.localeCompare(idxY, undefined, { numeric: true, sensitivity: 'base' });\n\t\t\tif (idxCompare !== 0) {\n\t\t\t\treturn idxCompare;\n\t\t\t}\n\n\t\t\tconst instX = this.normalizeWorkerIndex(x.workerInstance) || '';\n\t\t\tconst instY = this.normalizeWorkerIndex(y.workerInstance) || '';\n\t\t\treturn instX.localeCompare(instY, undefined, { numeric: true, sensitivity: 'base' });\n\t\t});\n\n\t\treturn eligible[0];\n\t}\n\n\tprivate normalizeWorkerIndex(value?: string | number | null): string | null {\n\t\tif (value === null || value === undefined) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst normalized = String(value).trim();\n\t\treturn normalized.length ? normalized : null;\n\t}\n\n\tprivate getWorkerLoad(worker: WorkerConnection): number {\n\t\treturn worker.activeTasks.reduce((sum, task) => sum + task.weight, 0);\n\t}\n\n\tprivate isWorkerZero(worker: WorkerConnection): boolean {\n\t\treturn this.normalizeWorkerIndex(worker.workerIndex) === '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\tmethod: task.method\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\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, method: task.method };\n\t\t}\n\t\telse {\n\t\t\texisting.method = task.method;\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\tlet unpackedResult = result;\n\n\t\t\tif (!error && unpackedResult === null && data['packedResult']) {\n\t\t\t\ttry {\n\t\t\t\t\tunpackedResult = unpack(data['packedResult']);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Failed to unpack worker result', err);\n\t\t\t\t}\n\t\t\t}\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(unpackedResult);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tpendingTask.promise.resolve(unpackedResult);\n\t\t\t\t\t}\n\t\t\t\t}\n\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\tif (!error && data['packedResult']) {\n\t\t\t\t\t\tthis._websocketManager.sendPackedBuffer(clientReqWS, messageId, false, data['packedResult'], data['encoding'] || 'msgpack');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._websocketManager.send(clientReqWS, res);\n\t\t\t\t\t}\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\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('Worker socket not open.');\n\t\t\t\t}\n\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"]}
@@ -83,7 +83,9 @@ var WorkerServerManager = /** @class */ (function () {
83
83
  WorkerServerManager.prototype.startWorkerInstance = function () {
84
84
  var _this = this;
85
85
  console.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');
86
- var wsUrl = this._serverConfig['SERVER_URL'] + '/websocket?workerToken=' + this._serverConfig['WORKER_TOKEN'] + '&workerIndex=' + process.env.WORKER_INDEX;
86
+ var workerIndex = encodeURIComponent(String(process.env.WORKER_INDEX || ''));
87
+ var workerInstance = encodeURIComponent(String(process.env.NODE_APP_INSTANCE || ''));
88
+ var wsUrl = this._serverConfig['SERVER_URL'] + '/websocket?workerToken=' + this._serverConfig['WORKER_TOKEN'] + '&workerIndex=' + workerIndex + '&workerInstance=' + workerInstance;
87
89
  var ws = new WebSocket(wsUrl);
88
90
  var lastComm = null;
89
91
  var interval = null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/worker-server.manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAwC;AACxC,8BAAgC;AAEhC,yCAA6C;AAC7C,mDAAiD;AAEjD;IAKI;QAFQ,kBAAa,GAAG,EAAE,CAAC;IAEZ,CAAC;IAET,0BAAM,GAAb,UAAc,aAA4B,EAAE,YAAY;QACpD,IAAM,mBAAmB,GAAG,IAAI,mBAAmB,EAAE,CAAC;QACtD,mBAAmB,CAAC,UAAU,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;QAC5D,OAAO,mBAAmB,CAAC;IAC/B,CAAC;IAEM,wCAAU,GAAjB,UAAkB,aAA4B,EAAE,YAAY;QACxD,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;QACpC,IAAI,CA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AE,EAAE,CAAC;YAC1C,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,SAAS,EAAE,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;QACxF,CAAC;QAED,IAAI,EAAE,IAAI,EAAE,CAAC,UAAU,KAAK,EAAE,CAAC,IAAI,EAAE,CAAC;YACrC,IAAI,CAAC;gBACJ,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;oBACjC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBAClB,CAAC;qBACI,CAAC;oBACL,EAAE,CAAC,IAAI,CAAC,IAAA,eAAI,EAAC,OAAO,CAAC,CAAC,CAAC;gBACxB,CAAC;YACF,CAAC;YACD,OAAO,GAAG,EAAE,CAAC;gBACZ,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,GAAG,CAAC,CAAC;YACvD,CAAC;QACF,CAAC;aACI,IAAI,EAAE,EAAE,CAAC;YACb,EAAE,CAAC,KAAK,EAAE,CAAC;QACZ,CAAC;IACF,CAAC;IACF,0BAAC;AAAD,CA3SA,AA2SC,IAAA;AA3SY,kDAAmB","file":"worker-server.manager.js","sourcesContent":["import { pack, unpack } from 'msgpackr';\nimport * 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 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\tif (messageBuffer.length === 4) {\n\t\t\t\tlet heartbeat = messageBuffer.toString('utf8');\n\n\t\t\t\tif (heartbeat === 'ping') {\n\t\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Recv Ping (binary), Sending Pong');\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (heartbeat === 'pong') {\n\t\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Recv Pong (binary)');\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\treturn;\n\t\t\t\t}\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\t\t\tlet result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\t\t\tlet packedResult: Uint8Array | Buffer = null;\n\n\t\t\ttry {\n\t\t\t\tpackedResult = <Buffer>pack(result);\n\t\t\t}\n\t\t\tcatch (packErr) {\n\t\t\t\tconsole.error(new Date(), 'Worker pack error', packErr);\n\t\t\t}\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Finished method', method);\n\t\t\t}\n\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tconst payload: TaskResponse = {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\tmessageId,\n\t\t\t\t\terror: false,\n\t\t\t\t\tresult: packedResult ? null : result,\n\t\t\t\t\tpackedResult,\n\t\t\t\t\tencoding: 'msgpack'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWorkerResponse(ws, payload);\n\t\t\t}\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
+ {"version":3,"sources":["../../src/managers/worker-server.manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAwC;AACxC,8BAAgC;AAEhC,yCAA6C;AAC7C,mDAAiD;AAEjD;IAKI;QAFQ,kBAAa,GAAG,EAAE,CAAC;IAEZ,CAAC;IAET,0BAAM,GAAb,UAAc,aAA4B,EAAE,YAAY;QACpD,IAAM,mBAAmB,GAAG,IAAI,mBAAmB,EAAE,CAAC;QACtD,mBAAmB,CAAC,UAAU,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;QAC5D,OAAO,mBAAmB,CAAC;IAC/B,CAAC;IAEM,wCAAU,GAAjB,UAAkB,aAA4B,EAAE,YAAY;QACxD,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;QACpC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC/B,CAAC;IAEO,iDAAmB,GAA3B;QAAA,iBAwJC;QAvJG,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,qEAAqE,CAAC,CAAC;QAE/F,IAAM,WAAW,GAAG,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,EAAE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I,EAAE,EAAE,SAAS,EAAE,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;QACxF,CAAC;QAED,IAAI,EAAE,IAAI,EAAE,CAAC,UAAU,KAAK,EAAE,CAAC,IAAI,EAAE,CAAC;YACrC,IAAI,CAAC;gBACJ,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;oBACjC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBAClB,CAAC;qBACI,CAAC;oBACL,EAAE,CAAC,IAAI,CAAC,IAAA,eAAI,EAAC,OAAO,CAAC,CAAC,CAAC;gBACxB,CAAC;YACF,CAAC;YACD,OAAO,GAAG,EAAE,CAAC;gBACZ,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,GAAG,CAAC,CAAC;YACvD,CAAC;QACF,CAAC;aACI,IAAI,EAAE,EAAE,CAAC;YACb,EAAE,CAAC,KAAK,EAAE,CAAC;QACZ,CAAC;IACF,CAAC;IACF,0BAAC;AAAD,CA7SA,AA6SC,IAAA;AA7SY,kDAAmB","file":"worker-server.manager.js","sourcesContent":["import { pack, unpack } from 'msgpackr';\nimport * 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 const workerIndex = encodeURIComponent(String(process.env.WORKER_INDEX || ''));\n const workerInstance = encodeURIComponent(String(process.env.NODE_APP_INSTANCE || ''));\n let wsUrl = this._serverConfig['SERVER_URL'] + '/websocket?workerToken=' + this._serverConfig['WORKER_TOKEN'] + '&workerIndex=' + workerIndex + '&workerInstance=' + workerInstance;\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\tif (messageBuffer.length === 4) {\n\t\t\t\tlet heartbeat = messageBuffer.toString('utf8');\n\n\t\t\t\tif (heartbeat === 'ping') {\n\t\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Recv Ping (binary), Sending Pong');\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (heartbeat === 'pong') {\n\t\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Recv Pong (binary)');\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\treturn;\n\t\t\t\t}\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\t\t\tlet result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\t\t\tlet packedResult: Uint8Array | Buffer = null;\n\n\t\t\ttry {\n\t\t\t\tpackedResult = <Buffer>pack(result);\n\t\t\t}\n\t\t\tcatch (packErr) {\n\t\t\t\tconsole.error(new Date(), 'Worker pack error', packErr);\n\t\t\t}\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Finished method', method);\n\t\t\t}\n\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tconst payload: TaskResponse = {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\tmessageId,\n\t\t\t\t\terror: false,\n\t\t\t\t\tresult: packedResult ? null : result,\n\t\t\t\t\tpackedResult,\n\t\t\t\t\tencoding: 'msgpack'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWorkerResponse(ws, payload);\n\t\t\t}\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"]}
@@ -13,6 +13,8 @@ export interface MethodAllModel {
13
13
  skipValidation?: boolean;
14
14
  workerTaskWeight?: number;
15
15
  skipWorker?: boolean;
16
+ targetWorkerIndex?: string | number;
17
+ targetWorkerInstance?: string | number;
16
18
  bypassSession?: boolean;
17
19
  timeoutOverride?: number;
18
20
  maxConcurrency?: number;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/models/method.model.ts"],"names":[],"mappings":"","file":"method.model.js","sourcesContent":["import SimpleSchema from 'simpl-schema';\nimport { MethodManager } from '../managers/method.manager';\n\nexport interface MethodModel {\n\t[key: string]: MethodAllModel;\n}\n\nexport interface MethodAllModel {\n\tcheck?: SimpleSchema;\n\t// eslint-disable-next-line no-unused-vars\n\tfunction: (this: MethodManager & {id_ws: string, id_user: string, user: string}, ...parameters: any[]) => Promise<any | any[]>;\n\tskipValidation?: boolean;\n\tworkerTaskWeight?: number;\n\tskipWorker?: boolean;\n\tbypassSession?: boolean;\n\ttimeoutOverride?: number;\n\tmaxConcurrency?: number;\n}\n"]}
1
+ {"version":3,"sources":["../../src/models/method.model.ts"],"names":[],"mappings":"","file":"method.model.js","sourcesContent":["import SimpleSchema from 'simpl-schema';\nimport { MethodManager } from '../managers/method.manager';\n\nexport interface MethodModel {\n\t[key: string]: MethodAllModel;\n}\n\nexport interface MethodAllModel {\n\tcheck?: SimpleSchema;\n\t// eslint-disable-next-line no-unused-vars\n\tfunction: (this: MethodManager & {id_ws: string, id_user: string, user: string}, ...parameters: any[]) => Promise<any | any[]>;\n\tskipValidation?: boolean;\n\tworkerTaskWeight?: number;\n\tskipWorker?: boolean;\n\ttargetWorkerIndex?: string | number;\n\ttargetWorkerInstance?: string | number;\n\tbypassSession?: boolean;\n\ttimeoutOverride?: number;\n\tmaxConcurrency?: number;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.13.3",
3
+ "version": "20.13.5",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",
package/server-app.js CHANGED
@@ -684,10 +684,14 @@ var ResolveIOMainServer = /** @class */ (function () {
684
684
  }
685
685
  var workerToken = requestUrl.searchParams.get('workerToken') || '';
686
686
  var workerIndex = requestUrl.searchParams.get('workerIndex');
687
+ var workerInstance = requestUrl.searchParams.get('workerInstance');
687
688
  if (workerToken === resolveio_server_app_1.ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {
688
689
  if (workerIndex) {
689
690
  info.req['workerIndex'] = workerIndex;
690
691
  }
692
+ if (workerInstance) {
693
+ info.req['workerInstance'] = workerInstance;
694
+ }
691
695
  cb(true);
692
696
  }
693
697
  else {
@@ -755,7 +759,7 @@ var ResolveIOMainServer = /** @class */ (function () {
755
759
  console.log('Running HTTP/WS server on port %s', _this._portHTTP);
756
760
  });
757
761
  this._serverWSS.on('connection', function (ws, req) { return __awaiter(_this, void 0, void 0, function () {
758
- var workerId_1, workerIndex, rootUrl, requestUrl, workerIndexForLog, interval_1, lastComm_1;
762
+ var workerId_1, workerIndex, workerInstance, rootUrl, requestUrl, workerIndexForLog, workerInstanceForLog, interval_1, lastComm_1;
759
763
  var _this = this;
760
764
  return __generator(this, function (_a) {
761
765
  switch (_a.label) {
@@ -764,25 +768,35 @@ var ResolveIOMainServer = /** @class */ (function () {
764
768
  workerId_1 = (0, common_1.objectIdHexString)();
765
769
  ws['id_worker'] = workerId_1;
766
770
  workerIndex = null;
771
+ workerInstance = null;
767
772
  ws['supportsBinary'] = true;
768
773
  if (req.url) {
769
774
  rootUrl = resolveio_server_app_1.ResolveIOServer.getServerConfig()['ROOT_URL'] || 'http://localhost';
770
775
  try {
771
776
  requestUrl = new url_1.URL(req.url, rootUrl);
772
777
  workerIndex = requestUrl.searchParams.get('workerIndex');
778
+ workerInstance = requestUrl.searchParams.get('workerInstance');
773
779
  }
774
780
  catch (_b) {
775
781
  workerIndex = null;
782
+ workerInstance = null;
776
783
  }
777
784
  }
778
785
  if (!workerIndex && req['workerIndex']) {
779
786
  workerIndex = req['workerIndex'];
780
787
  }
788
+ if (!workerInstance && req['workerInstance']) {
789
+ workerInstance = req['workerInstance'];
790
+ }
781
791
  if (workerIndex !== null && workerIndex !== undefined) {
782
792
  ws['workerIndex'] = workerIndex;
783
793
  }
794
+ if (workerInstance !== null && workerInstance !== undefined) {
795
+ ws['workerInstance'] = workerInstance;
796
+ }
784
797
  workerIndexForLog = ws['workerIndex'] || 'UNKNOWN';
785
- console.log(new Date(), 'Worker Connected', workerIndexForLog, process.env.NODE_APP_INSTANCE);
798
+ workerInstanceForLog = ws['workerInstance'] || 'UNKNOWN';
799
+ console.log(new Date(), 'Worker Connected', workerIndexForLog, workerInstanceForLog);
786
800
  this._workerDispatcherManager.addWorker(ws);
787
801
  interval_1 = null;
788
802
  lastComm_1 = null;
@@ -1202,7 +1216,7 @@ var ResolveIOMainServer = /** @class */ (function () {
1202
1216
  };
1203
1217
  ResolveIOMainServer.prototype.handleClientMessage = function (ws, msg) {
1204
1218
  return __awaiter(this, void 0, void 0, function () {
1205
- var messageRoute, messageDate, messageId, type, subType, pub, serverRes, offlineUpdates, i, update, data, updateRoute, updateDate, updateMessageId, updateType, method, serverResMethod, err_2, dataCopy, route, date, msgId, msgType, methodName, ack, method;
1219
+ var messageRoute, messageDate, messageId, type, subType, pub, serverRes, offlineUpdates, i, update, data, updateRoute, updateDate, updateMessageId, updateType, method, serverResMethod, err_2, dataCopy, route, date, msgId, msgType, methodName, ack, method, targetWorkerIndex, hasWorkerForMethod, errorRes;
1206
1220
  var _a;
1207
1221
  return __generator(this, function (_b) {
1208
1222
  switch (_b.label) {
@@ -1386,11 +1400,24 @@ var ResolveIOMainServer = /** @class */ (function () {
1386
1400
  this._websocketManager.send(ws, ack);
1387
1401
  }
1388
1402
  method = this._methodManager.getMethod(methodName);
1403
+ targetWorkerIndex = this._isWorkersEnabled && method ? method.targetWorkerIndex : null;
1404
+ hasWorkerForMethod = this._workerDispatcherManager ? this._workerDispatcherManager.hasWorkersForMethod(methodName) : false;
1405
+ if (targetWorkerIndex && this._isWorkersEnabled && !hasWorkerForMethod) {
1406
+ errorRes = {
1407
+ messageId: msgId,
1408
+ hasError: true,
1409
+ data: "Target worker ".concat(targetWorkerIndex, " not available for method ").concat(methodName)
1410
+ };
1411
+ if (ws && ws.readyState === ws.OPEN) {
1412
+ this._websocketManager.send(ws, errorRes);
1413
+ }
1414
+ return [2 /*return*/];
1415
+ }
1389
1416
  if (!(method &&
1390
1417
  !method.skipWorker &&
1391
1418
  this._isWorkersEnabled &&
1392
1419
  this._workerDispatcherManager &&
1393
- this._workerDispatcherManager.hasWorkers() &&
1420
+ hasWorkerForMethod &&
1394
1421
  methodName !== 'find' &&
1395
1422
  methodName !== 'insertDocument' &&
1396
1423
  methodName !== 'countWithQuery' &&
package/server-app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server-app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAAmC;AACnC,kDAAoD;AACpD,6BAA4C;AAC5C,kCAAoC;AACpC,wCAA0C;AAC1C,qCAAkC;AAClC,2BAA0B;AAC1B,8BAAgC;AAEhC,+DAA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EAAA;;wBAAlD,SAAkD,CAAC;wBACnD,EAAE,CAAC,kBAAkB,EAAE,CAAC;wBACxB,EAAE,GAAG,IAAI,CAAC;;;;;KACV;IAEM,oCAAM,GAAb;QACC,OAAO,IAAI,CAAC,IAAI,CAAC;IAClB,CAAC;IAEM,6CAAe,GAAtB;QACC,OAAO,sCAAe,CAAC,eAAe,EAAE,CAAC;IAC1C,CAAC;IAEM,wDAA0B,GAAjC;QACC,OAAO,IAAI,CAAC,wBAAwB,CAAC;IACtC,CAAC;IAEM,oDAAsB,GAA7B;QACC,OAAO,IAAI,CAAC,oBAAoB,CAAC;IAClC,CAAC;IACF,0BAAC;AAAD,CA3wCA,AA2wCC,IAAA;AA3wCY,kDAAmB","file":"server-app.js","sourcesContent":["import * as express from 'express';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport { createServer, Server } from 'http';\nimport * as jwt from 'jsonwebtoken';\nimport * as moment from 'moment-timezone';\nimport { unpack } from 'msgpackr';\nimport { URL } from 'url';\nimport * as WebSocket from 'ws';\n\nimport { Logs } from './collections/log.collection';\nimport { Users } from './collections/user.collection';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { ServerResponseModel } from './models/server-message.model';\nimport { dateReviver, getBinarySize, isAllowedOrigin, objectIdHexString } from './util/common';\nimport { ErrorReporter } from './util/error-reporter';\nimport { ensureErrorWithCorrelation } from './util/error-tracking';\n\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { setupHomeRoutes } from './http/home';\nimport { setupSlowQueryPublicationRoutes } from './http/slow-query-publication';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { WorkerDispatcherManager } from './managers/worker-dispatcher.manager';\nimport { WorkerServerManager } from './managers/worker-server.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\tprivate _workerDispatcherManager: WorkerDispatcherManager;\n\tprivate _workerServerManager: WorkerServerManager;\n\tprivate _httpServerClosePromise: Promise<void> | null = null;\n\tprivate _websocketServerClosePromise: Promise<void> | null = null;\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tprivate readonly _clientHeartbeatIntervalMs = 20000;\n\tprivate readonly _clientHeartbeatInitialDelayMs = 5000;\n\tprivate readonly _clientHeartbeatBackpressureBytes = 5 * 1024 * 1024;\n\n\tconstructor() {}\n\n\tstatic async create() {\n\t\tconst resolveioMainServer = new ResolveIOMainServer();\n\t\tawait resolveioMainServer.initialize();\n\t\treturn resolveioMainServer;\n\t}\n\n\tprivate async initialize() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = await MonitorManager.create();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._methodManager && this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tprocess.removeAllListeners('unhandledRejection');\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\tconst { error: normalizedError, correlationId } = ensureErrorWithCorrelation(error);\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.error(new Date(), 'ERROR DETECTED w/ Debug Flag Active: unhandledRejection', [normalizedError, rej, { correlationId }]);\n\t\t\t}\n\n\t\t\t// Condition to filter out the MongoError with specific codes\n\t\t\tif (normalizedError && normalizedError['name'] === 'MongoError' && (normalizedError['code'] === 48 || normalizedError['code'] === 26 || normalizedError['code'] === 11000 || normalizedError['code'] === 251)) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\t// if (normalizedError && normalizedError['name'] === 'MongoServerError' && (!initServerFlag || normalizedError['code'] === 26 || normalizedError['code'] === 11000 || normalizedError['code'] === 86 || normalizedError['code'] === 251)) {\n\t\t\t// \treturn; // Simply return without doing anything further\n\t\t\t// }\n\n\t\t\tif (normalizedError && normalizedError['name'] === 'MongoServerError') {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconst errorDetails = {\n\t\t\t\tid: correlationId,\n\t\t\t\tname: normalizedError?.name,\n\t\t\t\tmessage: normalizedError?.message,\n\t\t\t\tstack: normalizedError?.stack,\n\t\t\t\tcode: normalizedError?.code,\n\t\t\t\tcodeName: normalizedError?.codeName\n\t\t\t};\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [errorDetails]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (normalizedError && (normalizedError['name'] === 'MongoNetworkTimeoutError' || normalizedError instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (normalizedError && normalizedError['name'] === 'MongoError' && normalizedError['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (normalizedError && normalizedError['name'] === 'MongoError' && normalizedError['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (normalizedError && normalizedError['name'] !== 'StatusError' && normalizedError['message'] !== '') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this.reportServerError(\n\t\t\t\t\t\t'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'],\n\t\t\t\t\t\tcorrelationId,\n\t\t\t\t\t\terrorDetails,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: 'unhandledRejection',\n\t\t\t\t\t\t\tscenario: 'General'\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconst { error: normalizedError, correlationId } = ensureErrorWithCorrelation(error);\n\t\t\tconsole.error(normalizedError, 'Uncaught Exception thrown', { correlationId });\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tconst errorDetails = {\n\t\t\t\t\tid: correlationId,\n\t\t\t\t\tname: normalizedError?.name,\n\t\t\t\t\tmessage: normalizedError?.message,\n\t\t\t\t\tstack: normalizedError?.stack,\n\t\t\t\t\tcode: normalizedError?.code,\n\t\t\t\t\tcodeName: normalizedError?.codeName\n\t\t\t\t};\n\n\t\t\t\tawait this.reportServerError(\n\t\t\t\t\t'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'],\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\terrorDetails,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext: 'uncaughtException'\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\ttry {\n\t\t\t\tawait this.shutdownNetworkServers();\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing network servers (SIGINT)', error);\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\ttry {\n\t\t\t\tawait this.shutdownNetworkServers();\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing network servers (SIGTERM)', error);\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\ttry {\n\t\t\t\tawait this.shutdownNetworkServers();\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing network servers (SIGQUIT)', error);\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\tif (this._isWorkersEnabled) {\n\t\t\tif (this._isWorkerInstance) {\n\t\t\t\tconsole.log('Running as a Worker instance', process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis._methodManager = MethodManager.create(null, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._workerServerManager = WorkerServerManager.create(this._methodManager, this.getServerConfig());\n\n\t\t\t\tif (process.env.WORKER_INDEX === '0') {\n\t\t\t\t\tthis._cronManager = CronManager.create();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance', process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._workerDispatcherManager = WorkerDispatcherManager.create(this._websocketManager, this._methodManager);\n\t\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis.listen();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Running with Workers Disabled', process.env.NODE_APP_INSTANCE);\n\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\tthis._cronManager = CronManager.create();\n\t\t\tthis.startServerInstance();\n\t\t\tthis.listen();\n\t\t}\n\t}\n\n\tprivate async shutdownNetworkServers() {\n\t\tawait this.closeWebSocketServerGracefully();\n\t\tawait this.closeHttpServerGracefully();\n\t}\n\n\tprivate async closeHttpServerGracefully() {\n\t\tif (!this._serverHTTP) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._httpServerClosePromise !== null) {\n\t\t\tawait this._httpServerClosePromise;\n\t\t\treturn;\n\t\t}\n\n\t\t// eslint-disable-next-line no-restricted-syntax\n\t\tthis._httpServerClosePromise = new Promise(resolve => {\n\t\t\ttry {\n\t\t\t\tthis._serverHTTP.close(error => {\n\t\t\t\t\tif (error && error['code'] !== 'ERR_SERVER_NOT_RUNNING') {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error closing HTTP server before shutdown', error);\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tif (error && error['code'] !== 'ERR_SERVER_NOT_RUNNING') {\n\t\t\t\t\tconsole.error(new Date(), 'Error closing HTTP server before shutdown', error);\n\t\t\t\t}\n\t\t\t\tresolve();\n\t\t\t}\n\t\t});\n\n\t\tawait this._httpServerClosePromise;\n\t}\n\n\tprivate async closeWebSocketServerGracefully() {\n\t\tif (!this._serverWSS) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._websocketServerClosePromise !== null) {\n\t\t\tawait this._websocketServerClosePromise;\n\t\t\treturn;\n\t\t}\n\n\t\tthis._serverWSS.clients.forEach(ws => {\n\t\t\ttry {\n\t\t\t\tws.close(1001, 'Server restarting');\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing WebSocket client before shutdown', error);\n\t\t\t}\n\t\t});\n\n\t\t// eslint-disable-next-line no-restricted-syntax\n\t\tthis._websocketServerClosePromise = new Promise(resolve => {\n\t\t\ttry {\n\t\t\t\tthis._serverWSS.close(error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error closing WebSocket server before shutdown', error);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing WebSocket server before shutdown', error);\n\t\t\t\tresolve();\n\t\t\t}\n\t\t});\n\n\t\tawait this._websocketServerClosePromise;\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use built-in express JSON parser\n\t\tthis._app.use(express.json({\n\t\t\tlimit: '50mb',\n\t\t\treviver: dateReviver // Note: 'reviver' is an option for JSON.parse, which can be passed here\n\t\t}));\n\n\t\t// Use built-in express URL-encoded parser\n\t\tthis._app.use(express.urlencoded({\n\t\t\tlimit: '50mb',\n\t\t\textended: true, // `extended` must be explicitly true or false\n\t\t\tparameterLimit: 1000000\n\t\t}));\n\n\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.NODE_APP_INSTANCE ? parseInt('808' + process.env.NODE_APP_INSTANCE) : 8080;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app);\n\t\tsetupSlowQueryPublicationRoutes(this._app);\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.publicProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length\n\t\t\t&& !this._offlineUpdates.length && (!this._workerDispatcherManager || this._workerDispatcherManager.isSafeShutdown())\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\ttry {\n\t\t\t\t\tawait ResolveIOServer.getMongoConnection().close(false);\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\tcatch { \n\t\t\t\t\tprocess.exit(1); \n\t\t\t\t};\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), 'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tprivate async reportServerError(\n\t\tsubject: string,\n\t\tcorrelationId: string,\n\t\tcontext: Record<string, any>,\n\t\tmeta?: Record<string, any>,\n\t\tseverity = 'error',\n\t\tstackOverride?: string\n\t) {\n\t\tconst config = ResolveIOServer.getServerConfig();\n\t\tconst metadata = Object.assign({}, meta || {});\n\t\tif (correlationId && !metadata.correlationId) {\n\t\t\tmetadata.correlationId = correlationId;\n\t\t}\n\n\t\tawait ErrorReporter.report({\n\t\t\tsourceApp: 'server-app',\n\t\t\tmessage: subject,\n\t\t\tenvironment: config?.ROOT_URL || process.env.NODE_ENV || 'unknown',\n\t\t\tclientSlug: ResolveIOServer.getClientName(),\n\t\t\tclientName: config?.CLIENT_NAME,\n\t\t\tseverity,\n\t\t\tstack: stackOverride || (typeof context?.stack === 'string' ? context.stack : undefined),\n\t\t\tcontext,\n\t\t\tmetadata,\n\t\t\tcorrelationId\n\t\t});\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000;\n\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tserver: this._serverHTTP,\n\t\t\tverifyClient: this.publicProgram ? null : (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\t// If it's a worker, we might skip token checks or do a simple check:\n\t\t\t\t\tif (info.req.url && info.req.url.includes('workerToken=')) {\n\t\t\t\t\t\tlet requestUrl: URL;\n\t\t\t\t\t\tlet rootUrl = ResolveIOServer.getServerConfig()['ROOT_URL'] || 'http://localhost';\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trequestUrl = new URL(info.req.url, rootUrl);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch {\n\t\t\t\t\t\t\tcb(false, 400, 'Bad Request');\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet workerToken = requestUrl.searchParams.get('workerToken') || '';\n\t\t\t\t\t\tlet workerIndex = requestUrl.searchParams.get('workerIndex');\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\n\t\t\t\t\t\t\tif (workerIndex) {\n\t\t\t\t\t\t\t\tinfo.req['workerIndex'] = workerIndex;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (!isAllowedOrigin(info.origin, ResolveIOServer.getServerConfig())) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\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}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Listen for connections from clients or workers.\n\t */\n\tprivate listen(): void {\n\t\tconst host = process.env.RESOLVEIO_BIND_HOST || '127.0.0.1';\n\t\tthis._serverHTTP.listen(this._portHTTP, host, () => {\n\t\t\tconsole.log('Running HTTP/WS server on port %s', this._portHTTP);\n\t\t});\n\n\t\t\tthis._serverWSS.on('connection', async (ws, req) => {\n\t\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t\t// It's a WORKER\n\t\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\t\tws['id_worker'] = workerId;\n\t\t\t\t\tlet workerIndex = null;\n\t\t\t\t\tws['supportsBinary'] = true;\n\n\t\t\t\t\tif (req.url) {\n\t\t\t\t\t\tlet rootUrl = ResolveIOServer.getServerConfig()['ROOT_URL'] || 'http://localhost';\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlet requestUrl = new URL(req.url, rootUrl);\n\t\t\t\t\t\t\tworkerIndex = requestUrl.searchParams.get('workerIndex');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch {\n\t\t\t\t\t\t\tworkerIndex = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!workerIndex && req['workerIndex']) {\n\t\t\t\t\t\tworkerIndex = req['workerIndex'];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (workerIndex !== null && workerIndex !== undefined) {\n\t\t\t\t\t\tws['workerIndex'] = workerIndex;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet workerIndexForLog = ws['workerIndex'] || 'UNKNOWN';\n\t\t\t\t\tconsole.log(new Date(), 'Worker Connected', workerIndexForLog, process.env.NODE_APP_INSTANCE);\n\n\t\t\t\t\tthis._workerDispatcherManager.addWorker(ws);\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'ping');\n\t\n\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'ping');\n\t\t\t\t\t}\n\t\t\t\t}, 30000);\n\n\t\t\t\t\tws.on('message', (message: WebSocket.RawData) => {\n\t\t\t\t\t\tif (typeof message === 'string') {\n\t\t\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'pong');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._workerDispatcherManager.handleWorkerMessage(ws['id_worker'], message);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet buffer: Buffer;\n\n\t\t\t\t\t\tif (Buffer.isBuffer(message)) {\n\t\t\t\t\t\t\tbuffer = message;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Array.isArray(message)) {\n\t\t\t\t\t\t\tconst chunks = message as unknown as ReadonlyArray<Uint8Array>;\n\t\t\t\t\t\t\tbuffer = Buffer.concat(chunks);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (message instanceof ArrayBuffer) {\n\t\t\t\t\t\t\tbuffer = Buffer.from(message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (ArrayBuffer.isView(message)) {\n\t\t\t\t\t\t\tconst view = message as NodeJS.ArrayBufferView;\n\t\t\t\t\t\t\tbuffer = Buffer.from(view.buffer, view.byteOffset, view.byteLength);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbuffer = Buffer.from(message as any);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (buffer.length === 4) {\n\t\t\t\t\t\t\tlet heartbeat = buffer.toString('utf8');\n\n\t\t\t\t\t\t\tif (heartbeat === 'ping') {\n\t\t\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'pong');\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (heartbeat === 'pong') {\n\t\t\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._workerDispatcherManager.handleWorkerMessage(ws['id_worker'], buffer);\n\t\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\t\n\t\t\t\t\tif (interval) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('error', (error) => {\n\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\n\t\t\t\t\tconsole.error('Error on WS Worker', error);\n\t\t\t\t\tws.close();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Normal client\n\t\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\t\tws['supportsBinary'] = true;\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\t\tawait this._subscriptionManager.createLoggedInUser(ws['id_socket']);\n\t\t\t\t\n\t\t\t\tsetTimeout(async () => {\n\t\t\t\t\tawait this.triggerClientHeartbeat(ws);\n\t\t\t\t}, this._clientHeartbeatInitialDelayMs);\n\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Connection from user: ' + req['user']);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\tws.on('pong', () => {\n\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\t\tif (ws['pingTime']) {\n\t\t\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('message', async (message: WebSocket.RawData) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\tlet usedBinary = false;\n\t\t\t\t\tlet bufferPayload: Buffer;\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (typeof message === 'string') {\n\t\t\t\t\t\t\tif (message === 'ping' || message === 'pong') {\n\t\t\t\t\t\t\t\tsocketData = message;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Buffer.isBuffer(message)) {\n\t\t\t\t\t\t\tbufferPayload = message;\n\t\t\t\t\t\t\tlet decodeResult = this.decodeBufferPayload(bufferPayload);\n\t\t\t\t\t\t\tsocketData = decodeResult.data;\n\t\t\t\t\t\t\tusedBinary = decodeResult.usedBinary;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Array.isArray(message)) {\n\t\t\t\t\t\t\tbufferPayload = Buffer.concat(message as unknown as ReadonlyArray<Uint8Array>);\n\t\t\t\t\t\t\tlet decodeResult = this.decodeBufferPayload(bufferPayload);\n\t\t\t\t\t\t\tsocketData = decodeResult.data;\n\t\t\t\t\t\t\tusedBinary = decodeResult.usedBinary;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (message instanceof ArrayBuffer) {\n\t\t\t\t\t\t\tbufferPayload = Buffer.from(message);\n\t\t\t\t\t\t\tlet decodeResult = this.decodeBufferPayload(bufferPayload);\n\t\t\t\t\t\t\tsocketData = decodeResult.data;\n\t\t\t\t\t\t\tusedBinary = decodeResult.usedBinary;\n\t\t\t\t\t\t}\n\t\t\t\t\telse if (ArrayBuffer.isView(message)) {\n\t\t\t\t\t\tconst view = message as NodeJS.ArrayBufferView;\n\t\t\t\t\t\tbufferPayload = Buffer.from(view.buffer, view.byteOffset, view.byteLength);\n\t\t\t\t\t\tlet decodeResult = this.decodeBufferPayload(bufferPayload);\n\t\t\t\t\t\tsocketData = decodeResult.data;\n\t\t\t\t\t\tusedBinary = decodeResult.usedBinary;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new Error('Unsupported WebSocket message type: ' + typeof message);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tconsole.log('Error - WS message parse', e);\n\t\t\t\t\tconst correlationId = objectIdHexString();\n\t\t\t\t\tconst context = {\n\t\t\t\t\t\trawBinary: bufferPayload ? bufferPayload.toString('base64') : undefined,\n\t\t\t\t\t\trawMessage: typeof message === 'string' ? message : undefined,\n\t\t\t\t\t\terror: e instanceof Error ? { name: e.name, message: e.message, stack: e.stack } : e\n\t\t\t\t\t};\n\t\t\t\t\tawait this.reportServerError(\n\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'],\n\t\t\t\t\t\tcorrelationId,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t{ context: 'websocket-message-parse' },\n\t\t\t\t\t\t'error',\n\t\t\t\t\t\te instanceof Error ? e.stack : undefined\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\tif (usedBinary) {\n\t\t\t\t\t\tws['supportsBinary'] = true;\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// call our existing processSocketMessage\n\t\t\t\t\tawait this.processSocketMessage(ws, socketData);\n\t\t\t\t})\n\t\t\t\t.on('end', () => {\n\t\t\t\t\tws.close();\n\t\t\t\t})\n\t\t\t\t.on('error', () => {\n\t\t\t\t\tws.close()\n\t\t\t\t})\n\t\t\t\t.on('close', async () => {\n\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\t// Keep alive timer\n\t\tsetInterval(async () => {\n\t\t\tfor (let ws of this._serverWSS.clients) {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= this._clientHeartbeatIntervalMs) {\n\t\t\t\t\tif (this.shouldDeferHeartbeat(ws)) {\n\t\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tawait this.triggerClientHeartbeat(ws);\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\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tawait this.triggerClientHeartbeat(ws);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, this._clientHeartbeatIntervalMs);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any) {\n\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tws.send('pong');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\tws['isAlive'] = true;\n\t\t\tws['pongTime'] = new Date();\n\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the top level is not an array, let's skip\n\t\tif (!Array.isArray(socketData[0])) {\n\t\t\tconsole.log('Invalid message format (expected array of arrays)', socketData);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle each sub-message\n\t\tfor (let message of socketData) {\n\t\t\tawait this.handleClientMessage(ws, message);\n\t\t}\n\t}\n\n\tprivate decodeBufferPayload(buffer: Buffer): { data: any; usedBinary: boolean } {\n\t\tconst textPayload = buffer.toString('utf8');\n\n\t\tif (this.looksLikeTextPayload(textPayload)) {\n\t\t\ttry {\n\t\t\t\treturn { data: this.parseTextFallback(textPayload), usedBinary: false };\n\t\t\t}\n\t\t\tcatch {\n\t\t\t\t// fall through to attempt MessagePack decode\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\treturn { data: unpack(buffer), usedBinary: true };\n\t\t}\n\t\tcatch (binaryErr) {\n\t\t\ttry {\n\t\t\t\treturn { data: this.parseTextFallback(textPayload), usedBinary: false };\n\t\t\t}\n\t\t\tcatch {\n\t\t\t\tthrow binaryErr;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate parseTextFallback(rawMessage: string): any {\n\t\tif (rawMessage === 'ping' || rawMessage === 'pong') {\n\t\t\treturn rawMessage;\n\t\t}\n\n\t\ttry {\n\t\t\treturn JSON.parse(rawMessage, dateReviver);\n\t\t}\n\t\tcatch (err) {\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprivate looksLikeTextPayload(text: string): boolean {\n\t\tif (!text) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst trimmed = text.trim();\n\t\tif (!trimmed) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst first = trimmed[0];\n\t\treturn first === '[' || first === '{' || first === '\"' || first === 'p' || first === 'P';\n\t}\n\n\tprivate async triggerClientHeartbeat(ws: WebSocket): Promise<void> {\n\t\tif (!ws || ws.readyState !== ws.OPEN) {\n\t\t\treturn;\n\t\t}\n\n\t\tws['pingTime'] = new Date();\n\n\t\ttry {\n\t\t\tif (typeof ws.ping === 'function') {\n\t\t\t\tws.ping();\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tif (this._methodManager?.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping Frame', err);\n\t\t\t}\n\t\t\tawait this.unsubscribeWS(ws);\n\t\t\treturn;\n\t\t}\n\n\t\tws.send('ping', async (error) => {\n\t\t\tif (error) {\n\t\t\t\tif (this._methodManager?.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t}\n\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate shouldDeferHeartbeat(ws: WebSocket): boolean {\n\t\tif (!ws || ws.readyState !== ws.OPEN) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst bufferedAmount = typeof ws.bufferedAmount === 'number' ? ws.bufferedAmount : 0;\n\t\treturn bufferedAmount >= this._clientHeartbeatBackpressureBytes;\n\t}\n\n\tprivate async handleClientMessage(ws: WebSocket, msg: any[]): Promise<void> {\n\t\t// This is basically your old logic from processSocketMessage,\n\t\t// but we'll insert our worker-queue logic for \"method\" calls.\n\n\t\tlet messageRoute = msg[0];\n\t\tlet messageDate = msg[1];\n\t\tlet messageId = msg[2];\n\t\tlet type = msg[3];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = msg[4];\n\t\t\tlet pub = msg[5];\n\n\t\t\tif (subType === 'sub') {\n\t\t\t\tawait this._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = msg[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution' && method !== 'qbHandleResponse') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([data])) < 1000000 ? JSON.stringify([data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || '0'\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\tawait Logs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([data])) < 1000000 ? JSON.stringify([data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || '0'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethod.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse {\n\t\t\t// It's presumably a 'method' or something else\n\t\t\tlet dataCopy = [...msg];\n\n\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\tlet route = dataCopy.shift();\n\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\tlet date = dataCopy.shift();\n\t\t\tlet msgId = dataCopy.shift();\n\t\t\tlet msgType = dataCopy.shift();\n\t\t\t\n\t\t\tif (msgType === 'method') {\n\t\t\t\tlet methodName = dataCopy.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (methodName !== 'reportBuilderGetResults' && methodName !== 'reportBuilderGetDistinctValue' && methodName !== 'reportBuilderBuildTree' && methodName !== 'generatePDF' && methodName !== 'getWOOfflineData' && methodName !== 'countQuery' && methodName !== 'countWithQuery' && methodName !== 'countCollectionWithQuery' && methodName !== 'find' && methodName !== 'findOne' && methodName !== 'findWithOptions' && methodName !== 'getDrivers' && methodName !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([dataCopy])) < 1000000 ? JSON.stringify([dataCopy], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || '0'\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\tawait Logs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([dataCopy])) < 1000000 ? JSON.stringify([dataCopy], null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || '0'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Immediately ACK\n\t\t\t\tlet ack: ServerResponseModel = {\n\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, ack);\n\t\t\t\t}\n\n\t\t\t\tlet method = this._methodManager.getMethod(methodName);\n\n\t\t\t\tif (method &&\n\t\t\t\t\t!method.skipWorker &&\n\t\t\t\t\tthis._isWorkersEnabled &&\n\t\t\t\t\tthis._workerDispatcherManager &&\n\t\t\t\t\tthis._workerDispatcherManager.hasWorkers() &&\n\t\t\t\t\tmethodName !== 'find' &&\n\t\t\t\t\tmethodName !== 'insertDocument' &&\n\t\t\t\t\tmethodName !== 'countWithQuery' &&\n\t\t\t\t\tmethodName !== 'findOne' &&\n\t\t\t\t\tmethodName !== 'updateDocumentProps' &&\n\t\t\t\t\tmethodName !== 'findWithOptions' &&\n\t\t\t\t\tmethodName !== 'updateDocument' &&\n\t\t\t\t\tmethodName !== 'insertErrorLog' &&\n\t\t\t\t\tmethodName !== 'removeDocument' &&\n\t\t\t\t\tmethodName !== 'supportCreateBillingUser' &&\n\t\t\t\t\tmethodName !== 'getSignedUrl' &&\n\t\t\t\t\tmethodName !== 'getSignedUrls' &&\n\t\t\t\t\tmethodName !== 'getSignedUrlWithId' &&\n\t\t\t\t\tmethodName !== 'incorrectUser' &&\n\t\t\t\t\tmethodName !== 'reloadWS' &&\n\t\t\t\t\tmethodName !== 'reconnectWS' &&\n\t\t\t\t\tmethodName !== 'disconnectWS'\n\t\t\t\t) {\n\t\t\t\t\tthis._workerDispatcherManager.sendClientTask(msgId, methodName, dataCopy, {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// No worker available: do method locally\n\t\t\t\t\tawait this.callMethodLocally(ws, msgId, methodName, dataCopy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * callMethodLocally is your old approach for invoking the method in-process.\n\t */\n\tprivate async callMethodLocally(ws: WebSocket, messageId: number, method: string, params: any[]) {\n\t\tlet serverRes: ServerResponseModel = {\n\t\t\tmessageId: messageId,\n\t\t\thasError: false,\n\t\t\tdata: null\n\t\t};\n\n\t\ttry {\n\t\t\t// You can keep your logging code (LogMethodLatencies, Logs.insertOne, etc.)\n\t\t\tlet result = await this._methodManager.callMethod.call(\n\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t}),\n\t\t\t\tmethod,\n\t\t\t\t...params\n\t\t\t);\n\n\t\t\tserverRes.data = result;\n\t\t}\n\t\tcatch (err) {\n\t\t\tserverRes.hasError = true;\n\t\t\tserverRes.data = err || 'Unknown error';\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t}\n\t}\n\n\t\n\n\t/**\n\t * Cleanly remove a client from the subscription manager, etc.\n\t */\n\tpublic async unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager && this._methodManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tawait this._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n\n\tpublic getWorkerDispatcherManager() {\n\t\treturn this._workerDispatcherManager;\n\t}\n\n\tpublic getWorkerServerManager() {\n\t\treturn this._workerServerManager;\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../../src/server-app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAAmC;AACnC,kDAAoD;AACpD,6BAA4C;AAC5C,kCAAoC;AACpC,wCAA0C;AAC1C,qCAAkC;AAClC,2BAA0B;AAC1B,8BAAgC;AAEhC,+DAAoD;AACpD,iEAAsD;AACtD,wDAAsD;AACtD,4DAA0D;AAC1D,8DAAoF;AACpF,wEAAsE;AAEtE,wCAA+F;AAC/F,wDAAsD;AACtD,wDAAmE;AAEnE,mCAAmD;AACnD,oCAA8C;AAC9C,wCAAkD;AAClD,oCAA8C;AAC9C,wEAAgF;AAEhF,kEAAgE;AAChE,kFAA+E;AAC/E,0EAAuE;AACvE,+DAAyD;AAEzD;IAuCC;QAlCQ,oBAAe,GAAG,EAAE,CAAC;QACtB,YAAO,GAAG,KAAK,CAAC;QACf,kBAAa,GAA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AC,wBAAwB,CAAC;IACtC,CAAC;IAEM,oDAAsB,GAA7B;QACC,OAAO,IAAI,CAAC,oBAAoB,CAAC;IAClC,CAAC;IACF,0BAAC;AAAD,CAzyCA,AAyyCC,IAAA;AAzyCY,kDAAmB","file":"server-app.js","sourcesContent":["import * as express from 'express';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport { createServer, Server } from 'http';\nimport * as jwt from 'jsonwebtoken';\nimport * as moment from 'moment-timezone';\nimport { unpack } from 'msgpackr';\nimport { URL } from 'url';\nimport * as WebSocket from 'ws';\n\nimport { Logs } from './collections/log.collection';\nimport { Users } from './collections/user.collection';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { ServerResponseModel } from './models/server-message.model';\nimport { dateReviver, getBinarySize, isAllowedOrigin, objectIdHexString } from './util/common';\nimport { ErrorReporter } from './util/error-reporter';\nimport { ensureErrorWithCorrelation } from './util/error-tracking';\n\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { setupHomeRoutes } from './http/home';\nimport { setupSlowQueryPublicationRoutes } from './http/slow-query-publication';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { WorkerDispatcherManager } from './managers/worker-dispatcher.manager';\nimport { WorkerServerManager } from './managers/worker-server.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\tprivate _workerDispatcherManager: WorkerDispatcherManager;\n\tprivate _workerServerManager: WorkerServerManager;\n\tprivate _httpServerClosePromise: Promise<void> | null = null;\n\tprivate _websocketServerClosePromise: Promise<void> | null = null;\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tprivate readonly _clientHeartbeatIntervalMs = 20000;\n\tprivate readonly _clientHeartbeatInitialDelayMs = 5000;\n\tprivate readonly _clientHeartbeatBackpressureBytes = 5 * 1024 * 1024;\n\n\tconstructor() {}\n\n\tstatic async create() {\n\t\tconst resolveioMainServer = new ResolveIOMainServer();\n\t\tawait resolveioMainServer.initialize();\n\t\treturn resolveioMainServer;\n\t}\n\n\tprivate async initialize() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = await MonitorManager.create();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._methodManager && this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tprocess.removeAllListeners('unhandledRejection');\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\tconst { error: normalizedError, correlationId } = ensureErrorWithCorrelation(error);\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.error(new Date(), 'ERROR DETECTED w/ Debug Flag Active: unhandledRejection', [normalizedError, rej, { correlationId }]);\n\t\t\t}\n\n\t\t\t// Condition to filter out the MongoError with specific codes\n\t\t\tif (normalizedError && normalizedError['name'] === 'MongoError' && (normalizedError['code'] === 48 || normalizedError['code'] === 26 || normalizedError['code'] === 11000 || normalizedError['code'] === 251)) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\t// if (normalizedError && normalizedError['name'] === 'MongoServerError' && (!initServerFlag || normalizedError['code'] === 26 || normalizedError['code'] === 11000 || normalizedError['code'] === 86 || normalizedError['code'] === 251)) {\n\t\t\t// \treturn; // Simply return without doing anything further\n\t\t\t// }\n\n\t\t\tif (normalizedError && normalizedError['name'] === 'MongoServerError') {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconst errorDetails = {\n\t\t\t\tid: correlationId,\n\t\t\t\tname: normalizedError?.name,\n\t\t\t\tmessage: normalizedError?.message,\n\t\t\t\tstack: normalizedError?.stack,\n\t\t\t\tcode: normalizedError?.code,\n\t\t\t\tcodeName: normalizedError?.codeName\n\t\t\t};\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [errorDetails]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (normalizedError && (normalizedError['name'] === 'MongoNetworkTimeoutError' || normalizedError instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (normalizedError && normalizedError['name'] === 'MongoError' && normalizedError['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (normalizedError && normalizedError['name'] === 'MongoError' && normalizedError['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (normalizedError && normalizedError['name'] !== 'StatusError' && normalizedError['message'] !== '') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this.reportServerError(\n\t\t\t\t\t\t'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'],\n\t\t\t\t\t\tcorrelationId,\n\t\t\t\t\t\terrorDetails,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: 'unhandledRejection',\n\t\t\t\t\t\t\tscenario: 'General'\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconst { error: normalizedError, correlationId } = ensureErrorWithCorrelation(error);\n\t\t\tconsole.error(normalizedError, 'Uncaught Exception thrown', { correlationId });\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tconst errorDetails = {\n\t\t\t\t\tid: correlationId,\n\t\t\t\t\tname: normalizedError?.name,\n\t\t\t\t\tmessage: normalizedError?.message,\n\t\t\t\t\tstack: normalizedError?.stack,\n\t\t\t\t\tcode: normalizedError?.code,\n\t\t\t\t\tcodeName: normalizedError?.codeName\n\t\t\t\t};\n\n\t\t\t\tawait this.reportServerError(\n\t\t\t\t\t'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'],\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\terrorDetails,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext: 'uncaughtException'\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\ttry {\n\t\t\t\tawait this.shutdownNetworkServers();\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing network servers (SIGINT)', error);\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\ttry {\n\t\t\t\tawait this.shutdownNetworkServers();\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing network servers (SIGTERM)', error);\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\ttry {\n\t\t\t\tawait this.shutdownNetworkServers();\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing network servers (SIGQUIT)', error);\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\tif (this._isWorkersEnabled) {\n\t\t\tif (this._isWorkerInstance) {\n\t\t\t\tconsole.log('Running as a Worker instance', process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis._methodManager = MethodManager.create(null, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._workerServerManager = WorkerServerManager.create(this._methodManager, this.getServerConfig());\n\n\t\t\t\tif (process.env.WORKER_INDEX === '0') {\n\t\t\t\t\tthis._cronManager = CronManager.create();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance', process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._workerDispatcherManager = WorkerDispatcherManager.create(this._websocketManager, this._methodManager);\n\t\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis.listen();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Running with Workers Disabled', process.env.NODE_APP_INSTANCE);\n\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\tthis._cronManager = CronManager.create();\n\t\t\tthis.startServerInstance();\n\t\t\tthis.listen();\n\t\t}\n\t}\n\n\tprivate async shutdownNetworkServers() {\n\t\tawait this.closeWebSocketServerGracefully();\n\t\tawait this.closeHttpServerGracefully();\n\t}\n\n\tprivate async closeHttpServerGracefully() {\n\t\tif (!this._serverHTTP) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._httpServerClosePromise !== null) {\n\t\t\tawait this._httpServerClosePromise;\n\t\t\treturn;\n\t\t}\n\n\t\t// eslint-disable-next-line no-restricted-syntax\n\t\tthis._httpServerClosePromise = new Promise(resolve => {\n\t\t\ttry {\n\t\t\t\tthis._serverHTTP.close(error => {\n\t\t\t\t\tif (error && error['code'] !== 'ERR_SERVER_NOT_RUNNING') {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error closing HTTP server before shutdown', error);\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tif (error && error['code'] !== 'ERR_SERVER_NOT_RUNNING') {\n\t\t\t\t\tconsole.error(new Date(), 'Error closing HTTP server before shutdown', error);\n\t\t\t\t}\n\t\t\t\tresolve();\n\t\t\t}\n\t\t});\n\n\t\tawait this._httpServerClosePromise;\n\t}\n\n\tprivate async closeWebSocketServerGracefully() {\n\t\tif (!this._serverWSS) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._websocketServerClosePromise !== null) {\n\t\t\tawait this._websocketServerClosePromise;\n\t\t\treturn;\n\t\t}\n\n\t\tthis._serverWSS.clients.forEach(ws => {\n\t\t\ttry {\n\t\t\t\tws.close(1001, 'Server restarting');\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing WebSocket client before shutdown', error);\n\t\t\t}\n\t\t});\n\n\t\t// eslint-disable-next-line no-restricted-syntax\n\t\tthis._websocketServerClosePromise = new Promise(resolve => {\n\t\t\ttry {\n\t\t\t\tthis._serverWSS.close(error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error closing WebSocket server before shutdown', error);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tconsole.error(new Date(), 'Error closing WebSocket server before shutdown', error);\n\t\t\t\tresolve();\n\t\t\t}\n\t\t});\n\n\t\tawait this._websocketServerClosePromise;\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use built-in express JSON parser\n\t\tthis._app.use(express.json({\n\t\t\tlimit: '50mb',\n\t\t\treviver: dateReviver // Note: 'reviver' is an option for JSON.parse, which can be passed here\n\t\t}));\n\n\t\t// Use built-in express URL-encoded parser\n\t\tthis._app.use(express.urlencoded({\n\t\t\tlimit: '50mb',\n\t\t\textended: true, // `extended` must be explicitly true or false\n\t\t\tparameterLimit: 1000000\n\t\t}));\n\n\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.NODE_APP_INSTANCE ? parseInt('808' + process.env.NODE_APP_INSTANCE) : 8080;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app);\n\t\tsetupSlowQueryPublicationRoutes(this._app);\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.publicProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length\n\t\t\t&& !this._offlineUpdates.length && (!this._workerDispatcherManager || this._workerDispatcherManager.isSafeShutdown())\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\ttry {\n\t\t\t\t\tawait ResolveIOServer.getMongoConnection().close(false);\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\tcatch { \n\t\t\t\t\tprocess.exit(1); \n\t\t\t\t};\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), 'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tprivate async reportServerError(\n\t\tsubject: string,\n\t\tcorrelationId: string,\n\t\tcontext: Record<string, any>,\n\t\tmeta?: Record<string, any>,\n\t\tseverity = 'error',\n\t\tstackOverride?: string\n\t) {\n\t\tconst config = ResolveIOServer.getServerConfig();\n\t\tconst metadata = Object.assign({}, meta || {});\n\t\tif (correlationId && !metadata.correlationId) {\n\t\t\tmetadata.correlationId = correlationId;\n\t\t}\n\n\t\tawait ErrorReporter.report({\n\t\t\tsourceApp: 'server-app',\n\t\t\tmessage: subject,\n\t\t\tenvironment: config?.ROOT_URL || process.env.NODE_ENV || 'unknown',\n\t\t\tclientSlug: ResolveIOServer.getClientName(),\n\t\t\tclientName: config?.CLIENT_NAME,\n\t\t\tseverity,\n\t\t\tstack: stackOverride || (typeof context?.stack === 'string' ? context.stack : undefined),\n\t\t\tcontext,\n\t\t\tmetadata,\n\t\t\tcorrelationId\n\t\t});\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000;\n\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tserver: this._serverHTTP,\n\t\t\tverifyClient: this.publicProgram ? null : (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\t// If it's a worker, we might skip token checks or do a simple check:\n\t\t\t\t\tif (info.req.url && info.req.url.includes('workerToken=')) {\n\t\t\t\t\t\tlet requestUrl: URL;\n\t\t\t\t\t\tlet rootUrl = ResolveIOServer.getServerConfig()['ROOT_URL'] || 'http://localhost';\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trequestUrl = new URL(info.req.url, rootUrl);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch {\n\t\t\t\t\t\t\tcb(false, 400, 'Bad Request');\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet workerToken = requestUrl.searchParams.get('workerToken') || '';\n\t\t\t\t\t\tlet workerIndex = requestUrl.searchParams.get('workerIndex');\n\t\t\t\t\t\tlet workerInstance = requestUrl.searchParams.get('workerInstance');\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\n\t\t\t\t\t\t\tif (workerIndex) {\n\t\t\t\t\t\t\t\tinfo.req['workerIndex'] = workerIndex;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (workerInstance) {\n\t\t\t\t\t\t\t\tinfo.req['workerInstance'] = workerInstance;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (!isAllowedOrigin(info.origin, ResolveIOServer.getServerConfig())) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\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}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Listen for connections from clients or workers.\n\t */\n\tprivate listen(): void {\n\t\tconst host = process.env.RESOLVEIO_BIND_HOST || '127.0.0.1';\n\t\tthis._serverHTTP.listen(this._portHTTP, host, () => {\n\t\t\tconsole.log('Running HTTP/WS server on port %s', this._portHTTP);\n\t\t});\n\n\t\t\tthis._serverWSS.on('connection', async (ws, req) => {\n\t\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t\t// It's a WORKER\n\t\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\t\tws['id_worker'] = workerId;\n\t\t\t\t\tlet workerIndex = null;\n\t\t\t\t\tlet workerInstance = null;\n\t\t\t\t\tws['supportsBinary'] = true;\n\n\t\t\t\t\tif (req.url) {\n\t\t\t\t\t\tlet rootUrl = ResolveIOServer.getServerConfig()['ROOT_URL'] || 'http://localhost';\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlet requestUrl = new URL(req.url, rootUrl);\n\t\t\t\t\t\t\tworkerIndex = requestUrl.searchParams.get('workerIndex');\n\t\t\t\t\t\t\tworkerInstance = requestUrl.searchParams.get('workerInstance');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch {\n\t\t\t\t\t\t\tworkerIndex = null;\n\t\t\t\t\t\t\tworkerInstance = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!workerIndex && req['workerIndex']) {\n\t\t\t\t\t\tworkerIndex = req['workerIndex'];\n\t\t\t\t\t}\n\t\t\t\t\tif (!workerInstance && req['workerInstance']) {\n\t\t\t\t\t\tworkerInstance = req['workerInstance'];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (workerIndex !== null && workerIndex !== undefined) {\n\t\t\t\t\t\tws['workerIndex'] = workerIndex;\n\t\t\t\t\t}\n\t\t\t\t\tif (workerInstance !== null && workerInstance !== undefined) {\n\t\t\t\t\t\tws['workerInstance'] = workerInstance;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet workerIndexForLog = ws['workerIndex'] || 'UNKNOWN';\n\t\t\t\t\tlet workerInstanceForLog = ws['workerInstance'] || 'UNKNOWN';\n\t\t\t\t\tconsole.log(new Date(), 'Worker Connected', workerIndexForLog, workerInstanceForLog);\n\n\t\t\t\t\tthis._workerDispatcherManager.addWorker(ws);\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'ping');\n\t\n\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'ping');\n\t\t\t\t\t}\n\t\t\t\t}, 30000);\n\n\t\t\t\t\tws.on('message', (message: WebSocket.RawData) => {\n\t\t\t\t\t\tif (typeof message === 'string') {\n\t\t\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'pong');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._workerDispatcherManager.handleWorkerMessage(ws['id_worker'], message);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet buffer: Buffer;\n\n\t\t\t\t\t\tif (Buffer.isBuffer(message)) {\n\t\t\t\t\t\t\tbuffer = message;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Array.isArray(message)) {\n\t\t\t\t\t\t\tconst chunks = message as unknown as ReadonlyArray<Uint8Array>;\n\t\t\t\t\t\t\tbuffer = Buffer.concat(chunks);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (message instanceof ArrayBuffer) {\n\t\t\t\t\t\t\tbuffer = Buffer.from(message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (ArrayBuffer.isView(message)) {\n\t\t\t\t\t\t\tconst view = message as NodeJS.ArrayBufferView;\n\t\t\t\t\t\t\tbuffer = Buffer.from(view.buffer, view.byteOffset, view.byteLength);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbuffer = Buffer.from(message as any);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (buffer.length === 4) {\n\t\t\t\t\t\t\tlet heartbeat = buffer.toString('utf8');\n\n\t\t\t\t\t\t\tif (heartbeat === 'ping') {\n\t\t\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'pong');\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (heartbeat === 'pong') {\n\t\t\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._workerDispatcherManager.handleWorkerMessage(ws['id_worker'], buffer);\n\t\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\t\n\t\t\t\t\tif (interval) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('error', (error) => {\n\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\n\t\t\t\t\tconsole.error('Error on WS Worker', error);\n\t\t\t\t\tws.close();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Normal client\n\t\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\t\tws['supportsBinary'] = true;\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\t\tawait this._subscriptionManager.createLoggedInUser(ws['id_socket']);\n\t\t\t\t\n\t\t\t\tsetTimeout(async () => {\n\t\t\t\t\tawait this.triggerClientHeartbeat(ws);\n\t\t\t\t}, this._clientHeartbeatInitialDelayMs);\n\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Connection from user: ' + req['user']);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\tws.on('pong', () => {\n\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\t\tif (ws['pingTime']) {\n\t\t\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('message', async (message: WebSocket.RawData) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\tlet usedBinary = false;\n\t\t\t\t\tlet bufferPayload: Buffer;\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (typeof message === 'string') {\n\t\t\t\t\t\t\tif (message === 'ping' || message === 'pong') {\n\t\t\t\t\t\t\t\tsocketData = message;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Buffer.isBuffer(message)) {\n\t\t\t\t\t\t\tbufferPayload = message;\n\t\t\t\t\t\t\tlet decodeResult = this.decodeBufferPayload(bufferPayload);\n\t\t\t\t\t\t\tsocketData = decodeResult.data;\n\t\t\t\t\t\t\tusedBinary = decodeResult.usedBinary;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Array.isArray(message)) {\n\t\t\t\t\t\t\tbufferPayload = Buffer.concat(message as unknown as ReadonlyArray<Uint8Array>);\n\t\t\t\t\t\t\tlet decodeResult = this.decodeBufferPayload(bufferPayload);\n\t\t\t\t\t\t\tsocketData = decodeResult.data;\n\t\t\t\t\t\t\tusedBinary = decodeResult.usedBinary;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (message instanceof ArrayBuffer) {\n\t\t\t\t\t\t\tbufferPayload = Buffer.from(message);\n\t\t\t\t\t\t\tlet decodeResult = this.decodeBufferPayload(bufferPayload);\n\t\t\t\t\t\t\tsocketData = decodeResult.data;\n\t\t\t\t\t\t\tusedBinary = decodeResult.usedBinary;\n\t\t\t\t\t\t}\n\t\t\t\t\telse if (ArrayBuffer.isView(message)) {\n\t\t\t\t\t\tconst view = message as NodeJS.ArrayBufferView;\n\t\t\t\t\t\tbufferPayload = Buffer.from(view.buffer, view.byteOffset, view.byteLength);\n\t\t\t\t\t\tlet decodeResult = this.decodeBufferPayload(bufferPayload);\n\t\t\t\t\t\tsocketData = decodeResult.data;\n\t\t\t\t\t\tusedBinary = decodeResult.usedBinary;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new Error('Unsupported WebSocket message type: ' + typeof message);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tconsole.log('Error - WS message parse', e);\n\t\t\t\t\tconst correlationId = objectIdHexString();\n\t\t\t\t\tconst context = {\n\t\t\t\t\t\trawBinary: bufferPayload ? bufferPayload.toString('base64') : undefined,\n\t\t\t\t\t\trawMessage: typeof message === 'string' ? message : undefined,\n\t\t\t\t\t\terror: e instanceof Error ? { name: e.name, message: e.message, stack: e.stack } : e\n\t\t\t\t\t};\n\t\t\t\t\tawait this.reportServerError(\n\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'],\n\t\t\t\t\t\tcorrelationId,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t{ context: 'websocket-message-parse' },\n\t\t\t\t\t\t'error',\n\t\t\t\t\t\te instanceof Error ? e.stack : undefined\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\tif (usedBinary) {\n\t\t\t\t\t\tws['supportsBinary'] = true;\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// call our existing processSocketMessage\n\t\t\t\t\tawait this.processSocketMessage(ws, socketData);\n\t\t\t\t})\n\t\t\t\t.on('end', () => {\n\t\t\t\t\tws.close();\n\t\t\t\t})\n\t\t\t\t.on('error', () => {\n\t\t\t\t\tws.close()\n\t\t\t\t})\n\t\t\t\t.on('close', async () => {\n\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\t// Keep alive timer\n\t\tsetInterval(async () => {\n\t\t\tfor (let ws of this._serverWSS.clients) {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= this._clientHeartbeatIntervalMs) {\n\t\t\t\t\tif (this.shouldDeferHeartbeat(ws)) {\n\t\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tawait this.triggerClientHeartbeat(ws);\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\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tawait this.triggerClientHeartbeat(ws);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, this._clientHeartbeatIntervalMs);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any) {\n\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tws.send('pong');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\tws['isAlive'] = true;\n\t\t\tws['pongTime'] = new Date();\n\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the top level is not an array, let's skip\n\t\tif (!Array.isArray(socketData[0])) {\n\t\t\tconsole.log('Invalid message format (expected array of arrays)', socketData);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle each sub-message\n\t\tfor (let message of socketData) {\n\t\t\tawait this.handleClientMessage(ws, message);\n\t\t}\n\t}\n\n\tprivate decodeBufferPayload(buffer: Buffer): { data: any; usedBinary: boolean } {\n\t\tconst textPayload = buffer.toString('utf8');\n\n\t\tif (this.looksLikeTextPayload(textPayload)) {\n\t\t\ttry {\n\t\t\t\treturn { data: this.parseTextFallback(textPayload), usedBinary: false };\n\t\t\t}\n\t\t\tcatch {\n\t\t\t\t// fall through to attempt MessagePack decode\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\treturn { data: unpack(buffer), usedBinary: true };\n\t\t}\n\t\tcatch (binaryErr) {\n\t\t\ttry {\n\t\t\t\treturn { data: this.parseTextFallback(textPayload), usedBinary: false };\n\t\t\t}\n\t\t\tcatch {\n\t\t\t\tthrow binaryErr;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate parseTextFallback(rawMessage: string): any {\n\t\tif (rawMessage === 'ping' || rawMessage === 'pong') {\n\t\t\treturn rawMessage;\n\t\t}\n\n\t\ttry {\n\t\t\treturn JSON.parse(rawMessage, dateReviver);\n\t\t}\n\t\tcatch (err) {\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprivate looksLikeTextPayload(text: string): boolean {\n\t\tif (!text) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst trimmed = text.trim();\n\t\tif (!trimmed) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst first = trimmed[0];\n\t\treturn first === '[' || first === '{' || first === '\"' || first === 'p' || first === 'P';\n\t}\n\n\tprivate async triggerClientHeartbeat(ws: WebSocket): Promise<void> {\n\t\tif (!ws || ws.readyState !== ws.OPEN) {\n\t\t\treturn;\n\t\t}\n\n\t\tws['pingTime'] = new Date();\n\n\t\ttry {\n\t\t\tif (typeof ws.ping === 'function') {\n\t\t\t\tws.ping();\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tif (this._methodManager?.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping Frame', err);\n\t\t\t}\n\t\t\tawait this.unsubscribeWS(ws);\n\t\t\treturn;\n\t\t}\n\n\t\tws.send('ping', async (error) => {\n\t\t\tif (error) {\n\t\t\t\tif (this._methodManager?.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t}\n\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate shouldDeferHeartbeat(ws: WebSocket): boolean {\n\t\tif (!ws || ws.readyState !== ws.OPEN) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst bufferedAmount = typeof ws.bufferedAmount === 'number' ? ws.bufferedAmount : 0;\n\t\treturn bufferedAmount >= this._clientHeartbeatBackpressureBytes;\n\t}\n\n\tprivate async handleClientMessage(ws: WebSocket, msg: any[]): Promise<void> {\n\t\t// This is basically your old logic from processSocketMessage,\n\t\t// but we'll insert our worker-queue logic for \"method\" calls.\n\n\t\tlet messageRoute = msg[0];\n\t\tlet messageDate = msg[1];\n\t\tlet messageId = msg[2];\n\t\tlet type = msg[3];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = msg[4];\n\t\t\tlet pub = msg[5];\n\n\t\t\tif (subType === 'sub') {\n\t\t\t\tawait this._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = msg[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution' && method !== 'qbHandleResponse') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([data])) < 1000000 ? JSON.stringify([data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || '0'\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\tawait Logs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([data])) < 1000000 ? JSON.stringify([data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || '0'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethod.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse {\n\t\t\t// It's presumably a 'method' or something else\n\t\t\tlet dataCopy = [...msg];\n\n\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\tlet route = dataCopy.shift();\n\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\tlet date = dataCopy.shift();\n\t\t\tlet msgId = dataCopy.shift();\n\t\t\tlet msgType = dataCopy.shift();\n\t\t\t\n\t\t\tif (msgType === 'method') {\n\t\t\t\tlet methodName = dataCopy.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (methodName !== 'reportBuilderGetResults' && methodName !== 'reportBuilderGetDistinctValue' && methodName !== 'reportBuilderBuildTree' && methodName !== 'generatePDF' && methodName !== 'getWOOfflineData' && methodName !== 'countQuery' && methodName !== 'countWithQuery' && methodName !== 'countCollectionWithQuery' && methodName !== 'find' && methodName !== 'findOne' && methodName !== 'findWithOptions' && methodName !== 'getDrivers' && methodName !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([dataCopy])) < 1000000 ? JSON.stringify([dataCopy], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || '0'\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\tawait Logs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([dataCopy])) < 1000000 ? JSON.stringify([dataCopy], null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || '0'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Immediately ACK\n\t\t\t\tlet ack: ServerResponseModel = {\n\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, ack);\n\t\t\t\t}\n\n\t\t\t\tlet method = this._methodManager.getMethod(methodName);\n\t\t\t\tconst targetWorkerIndex = this._isWorkersEnabled && method ? method.targetWorkerIndex : null;\n\t\t\t\tconst hasWorkerForMethod = this._workerDispatcherManager ? this._workerDispatcherManager.hasWorkersForMethod(methodName) : false;\n\n\t\t\t\tif (targetWorkerIndex && this._isWorkersEnabled && !hasWorkerForMethod) {\n\t\t\t\t\tconst errorRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\tdata: `Target worker ${targetWorkerIndex} not available for method ${methodName}`\n\t\t\t\t\t};\n\n\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\tthis._websocketManager.send(ws, errorRes);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (method &&\n\t\t\t\t\t!method.skipWorker &&\n\t\t\t\t\tthis._isWorkersEnabled &&\n\t\t\t\t\tthis._workerDispatcherManager &&\n\t\t\t\t\thasWorkerForMethod &&\n\t\t\t\t\tmethodName !== 'find' &&\n\t\t\t\t\tmethodName !== 'insertDocument' &&\n\t\t\t\t\tmethodName !== 'countWithQuery' &&\n\t\t\t\t\tmethodName !== 'findOne' &&\n\t\t\t\t\tmethodName !== 'updateDocumentProps' &&\n\t\t\t\t\tmethodName !== 'findWithOptions' &&\n\t\t\t\t\tmethodName !== 'updateDocument' &&\n\t\t\t\t\tmethodName !== 'insertErrorLog' &&\n\t\t\t\t\tmethodName !== 'removeDocument' &&\n\t\t\t\t\tmethodName !== 'supportCreateBillingUser' &&\n\t\t\t\t\tmethodName !== 'getSignedUrl' &&\n\t\t\t\t\tmethodName !== 'getSignedUrls' &&\n\t\t\t\t\tmethodName !== 'getSignedUrlWithId' &&\n\t\t\t\t\tmethodName !== 'incorrectUser' &&\n\t\t\t\t\tmethodName !== 'reloadWS' &&\n\t\t\t\t\tmethodName !== 'reconnectWS' &&\n\t\t\t\t\tmethodName !== 'disconnectWS'\n\t\t\t\t) {\n\t\t\t\t\tthis._workerDispatcherManager.sendClientTask(msgId, methodName, dataCopy, {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// No worker available: do method locally\n\t\t\t\t\tawait this.callMethodLocally(ws, msgId, methodName, dataCopy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * callMethodLocally is your old approach for invoking the method in-process.\n\t */\n\tprivate async callMethodLocally(ws: WebSocket, messageId: number, method: string, params: any[]) {\n\t\tlet serverRes: ServerResponseModel = {\n\t\t\tmessageId: messageId,\n\t\t\thasError: false,\n\t\t\tdata: null\n\t\t};\n\n\t\ttry {\n\t\t\t// You can keep your logging code (LogMethodLatencies, Logs.insertOne, etc.)\n\t\t\tlet result = await this._methodManager.callMethod.call(\n\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t}),\n\t\t\t\tmethod,\n\t\t\t\t...params\n\t\t\t);\n\n\t\t\tserverRes.data = result;\n\t\t}\n\t\tcatch (err) {\n\t\t\tserverRes.hasError = true;\n\t\t\tserverRes.data = err || 'Unknown error';\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t}\n\t}\n\n\t\n\n\t/**\n\t * Cleanly remove a client from the subscription manager, etc.\n\t */\n\tpublic async unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager && this._methodManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tawait this._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n\n\tpublic getWorkerDispatcherManager() {\n\t\treturn this._workerDispatcherManager;\n\t}\n\n\tpublic getWorkerServerManager() {\n\t\treturn this._workerServerManager;\n\t}\n}\n"]}