@resolveio/server-lib 20.7.21 → 20.7.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/collections/log.collection.js +1 -1
- package/collections/log.collection.js.map +1 -1
- package/fixtures/init.js +1 -1
- package/fixtures/init.js.map +1 -1
- package/managers/method.manager.js +1 -1
- package/managers/method.manager.js.map +1 -1
- package/managers/mongo.manager.js +1 -1
- package/managers/mongo.manager.js.map +1 -1
- package/managers/monitor.manager.js.map +1 -1
- package/methods/logs.js +1 -1
- package/methods/logs.js.map +1 -1
- package/package.json +1 -1
- package/resolveio-server-app.js +1 -1
- package/resolveio-server-app.js.map +1 -1
- package/server-app.d.ts +2 -2
- package/server-app.js +1 -1
- package/server-app.js.map +1 -1
package/server-app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server-app.ts"],"names":["bodyParser","require","express","xmlParser","http_1","jwt","moment","WebSocket","log_collection_1","user_collection_1","cron_manager_1","method_manager_1","monitor_manager_1","subscription_manager_1","common_1","mongodb_1","auth_1","health_1","home_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","_runningTasks","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_workers","_taskQueue","_inFlightRequests","create","resolveioMainServer","initialize","prototype","_this","initServerFlag","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","setTimeout","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","wsUrl","ws","lastComm","interval","WORKER_INDEX","NODE_APP_INSTANCE","sendWorkerResponse","rawData","toString","msg","parse","e","type","handleIncomingTask","clearInterval","err","data","taskId","method","params","userContext","push","timedOut","timeoutHandle","concat","callMethod","managerThis","Object","assign","id_user","user","id_ws","call","apply","__spreadArray","__read","result","_b","clearTimeout","filter","a","err_1","payload","readyState","OPEN","send","getActiveMonitorFunctions","length","getMongoConnection","setImmediate","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","token","url","includes","split","infoData","headers","origin","verify","decoded","Users","findById","fullname","readonly","workerId_1","objectIdHexString","id","activeTasks","maxConcurrency","lastComm_1","interval_1","handleWorkerMessage","w","addWebSocket","createLoggedInUser","unsubscribeWS","socketData","e_1","processSocketMessage","now","getTime","this_1","_e","__values","value","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","handleClientMessage","messageRoute","messageDate","messageId","some","roles","groups","views","b","super_admin","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","serverResMethod","getLocalLogManager","writeLog","_id","createdAt","collection","id_document","getBinarySize","route","Logs","insertOne","client","instance","instance_index","_methods","err_2","getMongoManager","invalidateQueryCache","splice","map","indexOf","dataCopy","msgId","methodName","ack","worker","findAvailableWorker","queueTask","callMethodLocally","err_3","dispatchQueue","item","assignTaskToWorker","candidates","x","sort","task","Math","max","unshift","workerId","messageStr","inflight","find","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,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nC,KAAKmC,qBAAqBC,eAAc,GACxEC,QAAQC,IAAI,IAAIb,KAAQ,aAAc,WAAYqE,EAAS,KAAGA,EAAc,SAAC,EAE9E,CAAA,EAAM9F,KAAKmC,qBAAqB2O,eAAehL,CAAE,G,cAAjDtC,EAAAC,KAAA,EACAqC,EAAGiL,mBAAkB,EACrBjL,EAAK,K,UAGC/F,oBAAAsB,UAAA2P,OAAP,WACC,OAAOhR,KAAKwE,IACb,EAEOzE,oBAAAsB,UAAA6B,gBAAP,WACC,OAAOpD,uBAAAmD,gBAAgBC,gBAAe,CACvC,EACDnD,mBAAA,EAAC,EAltCYkR,QAAAlR,oBAAAA","file":"server-app.js","sourcesContent":["import * as bodyParser from 'body-parser';\nimport * 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 * 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-response.model';\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\n\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { setupHomeRoutes } from './http/home';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\ninterface WorkerConnection {\n\tid: string;\n\tws: WebSocket;\n\tactiveTasks: number;\n\tmaxConcurrency: number;\n}\n\ninterface TaskQueueItem {\n\ttaskId: string;\n\tmethod: string;\n\tparams: any[];\n\tuserContext?: { id_user?: string; user?: string; id_ws?: string };\n}\n\ninterface InFlightRequest {\n\tws: WebSocket; // the client's WebSocket\n\tmessageId: number; // the ID so the client knows which call this corresponds to\n\tmethod: string;\n}\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\tprivate _runningTasks = [];\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\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 _workers: WorkerConnection[] = [];\n\tprivate _taskQueue: TaskQueueItem[] = [];\n\tprivate _inFlightRequests: { [taskId: string]: InFlightRequest } = {};\n\n\tconstructor() {}\n\n\tpublic static create() {\n\t\tconst resolveioMainServer = new ResolveIOMainServer();\n\t\tresolveioMainServer.initialize();\n\t\treturn resolveioMainServer;\n\t}\n\n\tprivate initialize() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\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._subscriptionManager && this._subscriptionManager.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\tlet initServerFlag = false;\n\n\t\tsetTimeout(() => {\n\t\t\tinitServerFlag = true;\n\t\t}, 5000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tif (error && error['name'] === 'MongoServerError' && !initServerFlag) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\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 (error && (error['name'] === 'MongoNetworkTimeoutError' || error 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// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\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 (error && error['name'] === 'MongoError' && error['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\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['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\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\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\tconsole.error(error, 'Uncaught Exception thrown');\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\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\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\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\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\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\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\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\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');\n\t\t\t\tthis._methodManager = MethodManager.create(null, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._cronManager = CronManager.create();\n\t\t\t\tthis.startWorkerInstance();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\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');\n\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\tthis.startServerInstance();\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.listen();\n\t\t}\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || ResolveIOServer.getServerConfig()['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || ResolveIOServer.getServerConfig()['PORT_WSS'] || 8081;\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\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\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 startWorkerInstance() {\n\t\tconsole.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');\n\n\t\tlet wsUrl = ResolveIOServer.getServerConfig()['SERVER_URL'] + '/websocket?workerToken=' + ResolveIOServer.getServerConfig()['WORKER_TOKEN'];\n\n\t\tconst ws = new WebSocket(wsUrl);\n\n\t\tlet lastComm = null;\n\t\tlet interval = null;\n\n\t\tws.on('open', () => {\n\t\t\tconsole.log(new Date(), 'Connected to main server as worker', process.env.WORKER_INDEX, process.env.NODE_APP_INSTANCE);\n\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\n\t\t\tinterval = setInterval(() => {\n\t\t\t\tif (!lastComm) {\n\t\t\t\t\tws.close();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlastComm = null;\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t}\n\t\t\t}, 15000);\n\t\t});\n\n\t\tws.on('message', async (rawData: any) => {\n\t\t\t// console.log(new Date(), 'Message Recv', rawData);\n\n\t\t\tif (typeof rawData !== 'string') {\n\t\t\t\trawData = rawData.toString();\n\t\t\t}\n\n\t\t\t// console.log(new Date(), 'String Message Recv', rawData);\n\n\t\t\tif (rawData === 'ping') {\n\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t}\n\t\t\telse if (rawData === 'pong') {\n\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\tlastComm = new Date();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet msg: any;\n\t\t\t\ttry {\n\t\t\t\t\tmsg = JSON.parse(rawData, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tconsole.error('Worker parse error', e);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// We expect: { type: 'task', taskId, method, params, userContext? }\n\t\t\t\tif (msg.type === 'task') {\n\t\t\t\t\tawait this.handleIncomingTask(ws, msg);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tws.on('close', () => {\n\t\t\tconsole.log(new Date(), 'Disconnected from main server. Reconnecting in 5s...');\n\t\t\tsetTimeout(this.startWorkerInstance, 5000);\n\n\t\t\tif (interval) {\n\t\t\t\tclearInterval(interval);\n\t\t\t}\n\t\t});\n\n\t\tws.on('error', (err) => {\n\t\t\tconsole.error(new Date(), 'Worker WS error:', err);\n\t\t\tws.close();\n\t\t});\n\t}\n\n\tprivate async handleIncomingTask(ws: WebSocket, data: any) {\n\t\tlet { taskId, method, params, userContext } = data;\n\t\tthis._runningTasks.push(taskId);\n\t\tif (!taskId || !method) {\n\t\t\tconsole.log('Invalid task message received', data);\n\t\t\treturn;\n\t\t}\n\n\t\tlet timedOut = false;\n\t\tlet timeoutHandle = setTimeout(async () => {\n\t\t\ttimedOut = true;\n\t\t\tconsole.error(new Date(), 'Worker timed out on task:', taskId, 'Method:', method);\n\n\t\t\tconsole.error(new Date(), `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n\n\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\ttype: 'taskComplete',\n\t\t\t\ttaskId,\n\t\t\t\terror: true,\n\t\t\t\tmessage: 'Task timed out'\n\t\t\t});\n\n\t\t\tawait this._methodManager.callMethod('insertErrorLog', `Timeout in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n\t\t}, 120000);\n\n\t\ttry {\n\t\t\tlet managerThis = Object.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\tid_user: userContext?.id_user || '',\n\t\t\t\tuser: userContext?.user || '',\n\t\t\t\tid_ws: userContext?.id_ws || ''\n\t\t\t});\n\n\t\t\tlet result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: false,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t\tcatch (err) {\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tconsole.error('Worker failed task:', taskId, 'Method:', method, err);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: true,\n\t\t\t\t\tmessage: err || 'Unknown error'\n\t\t\t\t});\n\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n\t\t\t\n\t\t\tawait this._methodManager.callMethod('insertErrorLog', `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n\t\t\t\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t}\n\n\tprivate sendWorkerResponse(ws: WebSocket, payload: any) {\n\t\tif (typeof payload !== 'string') {\n\t\t\tpayload = JSON.stringify(payload);\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\ttry {\n\t\t\t\tws.send(payload);\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\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._taskQueue.length && !this._runningTasks.length\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\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\tport: this._portWSS,\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 urlParts = info.req.url.split('workerToken='); \n\t\t\t\t\t\tlet workerToken = urlParts[1] || '';\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\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 (\n\t\t\t\t\t\tinfo.origin !== ResolveIOServer.getServerConfig()['ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']\n\t\t\t\t\t) {\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\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\tthis._serverWSS.on('connection', async (ws, req) => {\n\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t// It's a WORKER\n\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\tws['id_worker'] = workerId;\n\n\t\t\t\t// For demonstration, let each worker handle up to 2 tasks concurrently\n\t\t\t\tlet maxConcurrency = 2;\n\n\t\t\t\tthis._workers.push({\n\t\t\t\t\tid: workerId,\n\t\t\t\t\tws: ws,\n\t\t\t\t\tactiveTasks: 0,\n\t\t\t\t\tmaxConcurrency: maxConcurrency\n\t\t\t\t});\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tws.on('open', () => {\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\n\t\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\t\tws.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 15000);\n\t\t\t\t});\n\n\t\t\t\tconsole.log(new Date(), 'Worker connected:', workerId);\n\n\t\t\t\tws.on('message', (message: any) => {\n\t\t\t\t\t// console.log(new Date(), 'Message Recv', message);\n\n\t\t\t\t\tif (typeof message !== 'string') {\n\t\t\t\t\t\tmessage = message.toString();\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log(new Date(), 'String Message Recv', message);\n\n\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t\t}\n\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.handleWorkerMessage(workerId, message);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\tthis._workers = this._workers.filter(w => w.id !== 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\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['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(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\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\n\t\t\t\tws.on('message', async (message: string) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\tawait this._methodManager.sendEmail(\n\t\t\t\t\t\t\t'dev@resolveio.com', \n\t\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], \n\t\t\t\t\t\t\tJSON.stringify([message, e])\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\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() >= 20000) {\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\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\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\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\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\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}, 20000);\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 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') {\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)) < 200000 ? 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}\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)) < 200000 ? 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 || ''\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)) < 200000 ? 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}\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)) < 200000 ? 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 || ''\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\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\t// Check if we can offload to a worker\n\t\t\t\tlet worker = this.findAvailableWorker();\n\t\t\t\tif (this._isWorkersEnabled && \n\t\t\t\t\tworker &&\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\t// Offload to a worker\n\t\t\t\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\t\t\t\t// Store correlation so when worker finishes, we can respond\n\t\t\t\t\tthis._inFlightRequests[taskId] = {\n\t\t\t\t\t\tws,\n\t\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\t\tmethod: methodName\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.queueTask(taskId, 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\t * Add a new task to our in-memory queue and try to dispatch.\n\t */\n\tprivate queueTask(taskId: string, method: string, params: any[], userContext?: { id_user?: string; user?: string; id_ws?: string }) {\n\t\tthis._taskQueue.push({\n\t\t\ttaskId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tuserContext\n\t\t});\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\t// Try to assign tasks while we have them\n\t\tfor (let i = 0; i < 9999; i++) {\n\t\t\tlet item = this._taskQueue[0];\n\t\t\tif (!item) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet w = this.findAvailableWorker();\n\t\t\tif (!w) {\n\t\t\t\tbreak; // no worker can take more tasks\n\t\t\t}\n\n\t\t\t// Remove from queue\n\t\t\tthis._taskQueue.shift();\n\t\t\tthis.assignTaskToWorker(w, item);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency. Or null if none.\n\t */\n\tprivate findAvailableWorker(): WorkerConnection | null {\n\t\tlet candidates = this._workers.filter(x => x.activeTasks < x.maxConcurrency);\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sort by how busy they are\n\t\tcandidates.sort((a, b) => a.activeTasks - b.activeTasks);\n\t\treturn candidates[0];\n\t}\n\n\tprivate assignTaskToWorker(worker: WorkerConnection, task: TaskQueueItem) {\n\t\tworker.activeTasks++;\n\n\t\tlet payload = {\n\t\t\ttype: 'task',\n\t\t\ttaskId: task.taskId,\n\t\t\tmethod: task.method,\n\t\t\tparams: task.params,\n\t\t\tuserContext: task.userContext\n\t\t};\n\n\t\ttry {\n\t\t\tworker.ws.send(JSON.stringify(payload));\n\t\t\t// console.log('Assigned task', task.taskId, 'to worker', worker.id);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to send task to worker:', err);\n\t\t\tworker.activeTasks = Math.max(0, worker.activeTasks - 1);\n\t\t\t// Put task back at front\n\t\t\tthis._taskQueue.unshift(task);\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages coming back from a worker (like 'taskComplete').\n\t */\n\tprivate handleWorkerMessage(workerId: string, messageStr: string) {\n\t\tlet data: any;\n\t\ttry {\n\t\t\tdata = JSON.parse(messageStr, dateReviver);\n\t\t}\n\t\tcatch {\n\t\t\tconsole.error('Failed to parse worker message:', messageStr);\n\t\t\treturn;\n\t\t}\n\n\t\tif (data.type === 'taskComplete') {\n\t\t\tlet w = this._workers.find(x => x.id === workerId);\n\t\t\tif (!w) {\n\t\t\t\tconsole.error('Unknown worker for taskComplete:', workerId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tw.activeTasks = Math.max(0, w.activeTasks - 1);\n\n\t\t\tlet { taskId, error, message, result } = data;\n\n\t\t\t// Look up original request\n\t\t\tlet inflight = this._inFlightRequests[taskId];\n\t\t\tif (!inflight) {\n\t\t\t\tconsole.error('No in-flight request found for task:', taskId);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdelete this._inFlightRequests[taskId];\n\n\t\t\t\t// Send the final response to the client\n\t\t\t\tlet res: ServerResponseModel = {\n\t\t\t\t\tmessageId: inflight.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 = message;\n\t\t\t\t}\n\n\t\t\t\tif (inflight.ws && inflight.ws.readyState === inflight.ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(inflight.ws, res);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to dispatch more from the queue\n\t\t\tthis.dispatchQueue();\n\t\t}\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._subscriptionManager.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}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server-app.ts"],"names":["bodyParser","require","express","xmlParser","http_1","jwt","moment","WebSocket","log_collection_1","user_collection_1","cron_manager_1","method_manager_1","monitor_manager_1","subscription_manager_1","common_1","mongodb_1","auth_1","health_1","home_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","_runningTasks","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_workers","_taskQueue","_inFlightRequests","create","resolveioMainServer","initialize","_a","sent","prototype","_serverStartTime","Date","MonitorManager","_monitorManager","_b","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_this","_subscriptionManager","getEnableDebug","console","log","initServerFlag","setTimeout","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","wsUrl","ws","lastComm","interval","WORKER_INDEX","NODE_APP_INSTANCE","sendWorkerResponse","rawData","toString","msg","parse","e","type","handleIncomingTask","clearInterval","err","data","taskId","method","params","userContext","push","timedOut","timeoutHandle","concat","callMethod","managerThis","Object","assign","id_user","user","id_ws","call","apply","__spreadArray","__read","result","clearTimeout","filter","a","err_1","payload","readyState","OPEN","send","getActiveMonitorFunctions","length","getMongoConnection","setImmediate","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","token","url","includes","split","infoData","headers","origin","verify","decoded","Users","findById","fullname","readonly","workerId_1","objectIdHexString","id","activeTasks","maxConcurrency","lastComm_1","interval_1","handleWorkerMessage","w","addWebSocket","createLoggedInUser","unsubscribeWS","socketData","e_1","processSocketMessage","now","getTime","this_1","_e","__values","value","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","handleClientMessage","messageRoute","messageDate","messageId","some","roles","groups","views","b","super_admin","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","serverResMethod","getLocalLogManager","writeLog","_id","createdAt","collection","id_document","getBinarySize","route","Logs","insertOne","client","instance","instance_index","_methods","err_2","getMongoManager","invalidateQueryCache","splice","map","indexOf","dataCopy","msgId","methodName","ack","worker","findAvailableWorker","queueTask","callMethodLocally","err_3","dispatchQueue","item","assignTaskToWorker","candidates","x","sort","task","Math","max","unshift","workerId","messageStr","inflight","find","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,Y,0FAAAC,QAAA,aAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,UAAAF,QAAA,wBAAA,EACAG,OAAAH,QAAA,MAAA,EACAI,IAAAJ,QAAA,cAAA,EACAK,OAAAL,QAAA,iBAAA,EACAM,UAAAN,QAAA,IAAA,EAEAO,iBAAAP,QAAA,8BAAA,EACAQ,kBAAAR,QAAA,+BAAA,EACAS,eAAAT,QAAA,yBAAA,EACAU,iBAAAV,QAAA,2BAAA,EACAW,kBAAAX,QAAA,4BAAA,EACAY,uBAAAZ,QAAA,iCAAA,EAEAa,SAAAb,QAAA,eAAA,EAEAc,UAAAd,QAAA,SAAA,EACAe,OAAAf,QAAA,aAAA,EACAgB,SAAAhB,QAAA,eAAA,EACAiB,OAAAjB,QAAA,aAAA,EAEAkB,oBAAAlB,QAAA,8BAAA,EACAmB,uBAAAnB,QAAA,wBAAA,EAsBAoB,oBAAA,WAsCC,SAAAA,sBAhCQC,KAAAC,gBAAkB,GACnBD,KAAAE,QAAU,CAAA,EACTF,KAAAG,gBAAkB,CAAA,EAClBH,KAAAI,cAAgB,CAAA,EAChBJ,KAAAK,YAAc,CAAA,EACdL,KAAAM,cAAgB,GAEhBN,KAAAO,OAAS,QAQTP,KAAAQ,cAA0B,GAG1BR,KAAAS,cAAsB,KAEtBT,KAAAU,cAAgB,EAChBV,KAAAW,eAAiB,EAEjBX,KAAAY,kBAAoB,CAAA,E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AAKiB,kBAAkB8F,GAG1BvB,EAA2B,CAC9BuH,UAAW6D,EAAS7D,UACpBa,SAAU,CAAA,EACV9G,KAAMoB,C,EAGHtF,IACH4C,EAAIoI,SAAW,CAAA,EACfpI,EAAIsB,KAAOrD,GAGRmN,EAAS7K,IAAM6K,EAAS7K,GAAGyC,aAAeoI,EAAS7K,GAAG0C,MACzDzI,KAAKmE,kBAAkBuE,KAAKkI,EAAS7K,GAAIP,CAAG,GAlB7CjD,QAAQK,MAAM,uCAAwCmE,CAAM,EAuB7D/G,KAAKgQ,cAAa,GAlCjBzN,QAAQK,MAAM,mCAAoC8N,CAAQ,EAoC7D,EAKa3Q,oBAAAwB,UAAAoK,cAAb,SAA2B5F,G,0GAI1B,OAHI/F,KAAKqC,sBAAwBrC,KAAKqC,qBAAqBC,eAAc,GACxEC,QAAQC,IAAI,IAAIf,KAAQ,aAAc,WAAYsE,EAAS,KAAGA,EAAc,SAAC,EAE9E,CAAA,EAAM/F,KAAKqC,qBAAqByO,eAAe/K,CAAE,G,cAAjD1E,EAAAC,KAAA,EACAyE,EAAGgL,mBAAkB,EACrBhL,EAAK,K,UAGChG,oBAAAwB,UAAAyP,OAAP,WACC,OAAOhR,KAAKyE,IACb,EAEO1E,oBAAAwB,UAAA8B,gBAAP,WACC,OAAOvD,uBAAAsD,gBAAgBC,gBAAe,CACvC,EACDtD,mBAAA,EAAC,EAltCYkR,QAAAlR,oBAAAA","file":"server-app.js","sourcesContent":["import * as bodyParser from 'body-parser';\nimport * 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 * 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-response.model';\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\n\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { setupHomeRoutes } from './http/home';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\ninterface WorkerConnection {\n\tid: string;\n\tws: WebSocket;\n\tactiveTasks: number;\n\tmaxConcurrency: number;\n}\n\ninterface TaskQueueItem {\n\ttaskId: string;\n\tmethod: string;\n\tparams: any[];\n\tuserContext?: { id_user?: string; user?: string; id_ws?: string };\n}\n\ninterface InFlightRequest {\n\tws: WebSocket; // the client's WebSocket\n\tmessageId: number; // the ID so the client knows which call this corresponds to\n\tmethod: string;\n}\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\tprivate _runningTasks = [];\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\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 _workers: WorkerConnection[] = [];\n\tprivate _taskQueue: TaskQueueItem[] = [];\n\tprivate _inFlightRequests: { [taskId: string]: InFlightRequest } = {};\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._subscriptionManager && this._subscriptionManager.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\tlet initServerFlag = false;\n\n\t\tsetTimeout(() => {\n\t\t\tinitServerFlag = true;\n\t\t}, 5000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tif (error && error['name'] === 'MongoServerError' && !initServerFlag) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\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 (error && (error['name'] === 'MongoNetworkTimeoutError' || error 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// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\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 (error && error['name'] === 'MongoError' && error['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\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['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\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\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\tconsole.error(error, 'Uncaught Exception thrown');\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\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\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\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\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\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\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\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\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');\n\t\t\t\tthis._methodManager = MethodManager.create(null, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._cronManager = CronManager.create();\n\t\t\t\tthis.startWorkerInstance();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\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');\n\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\tthis.startServerInstance();\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.listen();\n\t\t}\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || ResolveIOServer.getServerConfig()['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || ResolveIOServer.getServerConfig()['PORT_WSS'] || 8081;\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\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\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\tstartWorkerInstance() {\n\t\tconsole.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');\n\n\t\tlet wsUrl = ResolveIOServer.getServerConfig()['SERVER_URL'] + '/websocket?workerToken=' + ResolveIOServer.getServerConfig()['WORKER_TOKEN'];\n\n\t\tconst ws = new WebSocket(wsUrl);\n\n\t\tlet lastComm = null;\n\t\tlet interval = null;\n\n\t\tws.on('open', () => {\n\t\t\tconsole.log(new Date(), 'Connected to main server as worker', process.env.WORKER_INDEX, process.env.NODE_APP_INSTANCE);\n\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\n\t\t\tinterval = setInterval(() => {\n\t\t\t\tif (!lastComm) {\n\t\t\t\t\tws.close();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlastComm = null;\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t}\n\t\t\t}, 15000);\n\t\t});\n\n\t\tws.on('message', async (rawData: any) => {\n\t\t\t// console.log(new Date(), 'Message Recv', rawData);\n\n\t\t\tif (typeof rawData !== 'string') {\n\t\t\t\trawData = rawData.toString();\n\t\t\t}\n\n\t\t\t// console.log(new Date(), 'String Message Recv', rawData);\n\n\t\t\tif (rawData === 'ping') {\n\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t}\n\t\t\telse if (rawData === 'pong') {\n\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\tlastComm = new Date();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet msg: any;\n\t\t\t\ttry {\n\t\t\t\t\tmsg = JSON.parse(rawData, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tconsole.error('Worker parse error', e);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// We expect: { type: 'task', taskId, method, params, userContext? }\n\t\t\t\tif (msg.type === 'task') {\n\t\t\t\t\tawait this.handleIncomingTask(ws, msg);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tws.on('close', () => {\n\t\t\tconsole.log(new Date(), 'Disconnected from main server. Reconnecting in 5s...');\n\t\t\tsetTimeout(() => this.startWorkerInstance, 5000);\n\n\t\t\tif (interval) {\n\t\t\t\tclearInterval(interval);\n\t\t\t}\n\t\t});\n\n\t\tws.on('error', (err) => {\n\t\t\tconsole.error(new Date(), 'Worker WS error:', err);\n\t\t\tws.close();\n\t\t});\n\t}\n\n\tprivate async handleIncomingTask(ws: WebSocket, data: any) {\n\t\tlet { taskId, method, params, userContext } = data;\n\t\tthis._runningTasks.push(taskId);\n\t\tif (!taskId || !method) {\n\t\t\tconsole.log('Invalid task message received', data);\n\t\t\treturn;\n\t\t}\n\n\t\tlet timedOut = false;\n\t\tlet timeoutHandle = setTimeout(async () => {\n\t\t\ttimedOut = true;\n\t\t\tconsole.error(new Date(), 'Worker timed out on task:', taskId, 'Method:', method);\n\n\t\t\tconsole.error(new Date(), `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n\n\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\ttype: 'taskComplete',\n\t\t\t\ttaskId,\n\t\t\t\terror: true,\n\t\t\t\tmessage: 'Task timed out'\n\t\t\t});\n\n\t\t\tawait this._methodManager.callMethod('insertErrorLog', `Timeout in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n\t\t}, 120000);\n\n\t\ttry {\n\t\t\tlet managerThis = Object.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\tid_user: userContext?.id_user || '',\n\t\t\t\tuser: userContext?.user || '',\n\t\t\t\tid_ws: userContext?.id_ws || ''\n\t\t\t});\n\n\t\t\tlet result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: false,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t\tcatch (err) {\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tconsole.error('Worker failed task:', taskId, 'Method:', method, err);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: true,\n\t\t\t\t\tmessage: err || 'Unknown error'\n\t\t\t\t});\n\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n\t\t\t\n\t\t\tawait this._methodManager.callMethod('insertErrorLog', `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n\t\t\t\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t}\n\n\tprivate sendWorkerResponse(ws: WebSocket, payload: any) {\n\t\tif (typeof payload !== 'string') {\n\t\t\tpayload = JSON.stringify(payload);\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\ttry {\n\t\t\t\tws.send(payload);\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\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._taskQueue.length && !this._runningTasks.length\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\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\tport: this._portWSS,\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 urlParts = info.req.url.split('workerToken='); \n\t\t\t\t\t\tlet workerToken = urlParts[1] || '';\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\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 (\n\t\t\t\t\t\tinfo.origin !== ResolveIOServer.getServerConfig()['ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']\n\t\t\t\t\t) {\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\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\tthis._serverWSS.on('connection', async (ws, req) => {\n\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t// It's a WORKER\n\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\tws['id_worker'] = workerId;\n\n\t\t\t\t// For demonstration, let each worker handle up to 2 tasks concurrently\n\t\t\t\tlet maxConcurrency = 2;\n\n\t\t\t\tthis._workers.push({\n\t\t\t\t\tid: workerId,\n\t\t\t\t\tws: ws,\n\t\t\t\t\tactiveTasks: 0,\n\t\t\t\t\tmaxConcurrency: maxConcurrency\n\t\t\t\t});\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tws.on('open', () => {\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\n\t\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\t\tws.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 15000);\n\t\t\t\t});\n\n\t\t\t\tconsole.log(new Date(), 'Worker connected:', workerId);\n\n\t\t\t\tws.on('message', (message: any) => {\n\t\t\t\t\t// console.log(new Date(), 'Message Recv', message);\n\n\t\t\t\t\tif (typeof message !== 'string') {\n\t\t\t\t\t\tmessage = message.toString();\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log(new Date(), 'String Message Recv', message);\n\n\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t\t}\n\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.handleWorkerMessage(workerId, message);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\tthis._workers = this._workers.filter(w => w.id !== 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\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['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(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\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\n\t\t\t\tws.on('message', async (message: string) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\tawait this._methodManager.sendEmail(\n\t\t\t\t\t\t\t'dev@resolveio.com', \n\t\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], \n\t\t\t\t\t\t\tJSON.stringify([message, e])\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\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() >= 20000) {\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\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\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\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\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\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}, 20000);\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 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') {\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])) < 200000 ? 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}\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])) < 200000 ? 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 || ''\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])) < 200000 ? 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}\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])) < 200000 ? 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 || ''\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\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\t// Check if we can offload to a worker\n\t\t\t\tlet worker = this.findAvailableWorker();\n\t\t\t\tif (this._isWorkersEnabled && \n\t\t\t\t\tworker &&\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\t// Offload to a worker\n\t\t\t\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\t\t\t\t// Store correlation so when worker finishes, we can respond\n\t\t\t\t\tthis._inFlightRequests[taskId] = {\n\t\t\t\t\t\tws,\n\t\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\t\tmethod: methodName\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.queueTask(taskId, 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\t * Add a new task to our in-memory queue and try to dispatch.\n\t */\n\tprivate queueTask(taskId: string, method: string, params: any[], userContext?: { id_user?: string; user?: string; id_ws?: string }) {\n\t\tthis._taskQueue.push({\n\t\t\ttaskId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tuserContext\n\t\t});\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\t// Try to assign tasks while we have them\n\t\tfor (let i = 0; i < 9999; i++) {\n\t\t\tlet item = this._taskQueue[0];\n\t\t\tif (!item) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet w = this.findAvailableWorker();\n\t\t\tif (!w) {\n\t\t\t\tbreak; // no worker can take more tasks\n\t\t\t}\n\n\t\t\t// Remove from queue\n\t\t\tthis._taskQueue.shift();\n\t\t\tthis.assignTaskToWorker(w, item);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency. Or null if none.\n\t */\n\tprivate findAvailableWorker(): WorkerConnection | null {\n\t\tlet candidates = this._workers.filter(x => x.activeTasks < x.maxConcurrency);\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sort by how busy they are\n\t\tcandidates.sort((a, b) => a.activeTasks - b.activeTasks);\n\t\treturn candidates[0];\n\t}\n\n\tprivate assignTaskToWorker(worker: WorkerConnection, task: TaskQueueItem) {\n\t\tworker.activeTasks++;\n\n\t\tlet payload = {\n\t\t\ttype: 'task',\n\t\t\ttaskId: task.taskId,\n\t\t\tmethod: task.method,\n\t\t\tparams: task.params,\n\t\t\tuserContext: task.userContext\n\t\t};\n\n\t\ttry {\n\t\t\tworker.ws.send(JSON.stringify(payload));\n\t\t\t// console.log('Assigned task', task.taskId, 'to worker', worker.id);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to send task to worker:', err);\n\t\t\tworker.activeTasks = Math.max(0, worker.activeTasks - 1);\n\t\t\t// Put task back at front\n\t\t\tthis._taskQueue.unshift(task);\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages coming back from a worker (like 'taskComplete').\n\t */\n\tprivate handleWorkerMessage(workerId: string, messageStr: string) {\n\t\tlet data: any;\n\t\ttry {\n\t\t\tdata = JSON.parse(messageStr, dateReviver);\n\t\t}\n\t\tcatch {\n\t\t\tconsole.error('Failed to parse worker message:', messageStr);\n\t\t\treturn;\n\t\t}\n\n\t\tif (data.type === 'taskComplete') {\n\t\t\tlet w = this._workers.find(x => x.id === workerId);\n\t\t\tif (!w) {\n\t\t\t\tconsole.error('Unknown worker for taskComplete:', workerId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tw.activeTasks = Math.max(0, w.activeTasks - 1);\n\n\t\t\tlet { taskId, error, message, result } = data;\n\n\t\t\t// Look up original request\n\t\t\tlet inflight = this._inFlightRequests[taskId];\n\t\t\tif (!inflight) {\n\t\t\t\tconsole.error('No in-flight request found for task:', taskId);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdelete this._inFlightRequests[taskId];\n\n\t\t\t\t// Send the final response to the client\n\t\t\t\tlet res: ServerResponseModel = {\n\t\t\t\t\tmessageId: inflight.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 = message;\n\t\t\t\t}\n\n\t\t\t\tif (inflight.ws && inflight.ws.readyState === inflight.ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(inflight.ws, res);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to dispatch more from the queue\n\t\t\tthis.dispatchQueue();\n\t\t}\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._subscriptionManager.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}"]}
|