@resolveio/server-lib 20.5.9 → 20.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.5.9",
3
+ "version": "20.5.10",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",
package/server-app.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,o,s,n){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((n=n.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,s){var n,i,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(t){return function(e){var r=[t,e];if(n)throw new TypeError("Generator is already executing.");for(;l=c&&r[c=0]?0:l;)try{if(n=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return l.label++,{value:r[1],done:!1};case 5:l.label++,i=r[1],r=[0];continue;case 7:r=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){l=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))l.label=r[1];else if(6===r[0]&&l.label<a[1])l.label=a[1],a=r;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(r)}}r=s.call(o,l)}catch(e){r=[6,e],i=0}finally{n=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],o=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,s,n=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(o=n.next()).done;)i.push(o.value)}catch(e){s={error:e}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var o,s=0,n=r.length;s<n;s++)!o&&s in r||((o=o||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(o||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),log_method_latency_collection_1=require("./collections/log-method-latency.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),mongodb_1=require("mongodb"),worker_task_request_collection_1=require("./collections/worker-task-request.collection"),worker_task_response_collection_1=require("./collections/worker-task-response.collection"),websocket_manager_1=require("./managers/websocket.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._workerTasks=[],this._safeShutdown=!1,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction}return ResolveIOMainServer.prototype.initServerApp=function(){var e=this;this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){e._subscriptionManager&&e._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",e._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",e._debugMsgQueue)),e._debugMsgQueue=0,e._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(o,s){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return o&&"MongoError"===o.name&&48===o.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[o,s]),r=moment().diff(this._serverStartTime,"seconds"),o&&("MongoNetworkTimeoutError"===o.name||o instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:o.name,message:o.message,stack:o.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return o&&"MongoError"===o.name&&"not master"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return o&&"MongoError"===o.name&&"not master and slaveOk=false"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:o&&"StatusError"!==o.name&&""!==o.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(e,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGTERM",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGQUIT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager,this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager,this.listen())},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,t,o,s,n,i,a,l=this;return __generator(this,function(e){switch(e.label){case 0:return console.log("Worker instance started, watching worker-task-reqs..."),(r=worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"})).on("change",function(s){return __awaiter(l,void 0,void 0,function(){var r,t,o=this;return __generator(this,function(e){return"insert"===s.operationType?(r=s.fullDocument)&&setTimeout(function(){o.processTask(r)},25*this._workerTasks.length):"update"===s.operationType&&(t=s.fullDocument)&&"pending"===t.status&&setTimeout(function(){o.processTask(t)},25*this._workerTasks.length),[2]})})}),r.on("error",function(e){console.error("Error in change stream worker task requests:",e),r&&r.close()}),r.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return l.startWorkerInstance()},5e3)}),[4,worker_task_request_collection_1.WorkerTaskRequests.find({status:"pending"},{sort:{createdAt:1}})];case 1:t=e.sent();try{for(o=__values(t),s=o.next();!s.done;s=o.next())n=s.value,this.processTask(n)}catch(e){i={error:e}}finally{try{s&&!s.done&&(a=o.return)&&a.call(o)}finally{if(i)throw i.error}}return[2]}})})},ResolveIOMainServer.prototype.processTask=function(a){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){return this._workerTasks.includes(a._id)||worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:a._id,status:"pending"},{$set:{status:"processing"}}).then(function(i){return __awaiter(r,void 0,void 0,function(){var r,t,o,s,n=this;return __generator(this,function(e){switch(e.label){case 0:if(!i)return[3,4];this._workerTasks.push(a._id),r=!1,t=setTimeout(function(){r=!0,console.error("Worker timed out processing task:",a._id),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:a._id,has_error:!0,data:"Task timed out.",id_user:a.id_user,user:a.user,id_ws:a.id_ws}),n._workerTasks.includes(a._id)&&n._workerTasks.splice(n._workerTasks.indexOf(a._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:a._id},{$set:{status:"timeout"}})},12e4),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(s=this._methodManager.callMethodInternal).call.apply(s,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:a.id_user,user:a.user,id_ws:a.id_ws}),a.method],__read(a.params),!1))];case 2:return s=e.sent(),r||(clearTimeout(t),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:a._id,has_error:!1,data:s,id_user:a.id_user,user:a.user,id_ws:a.id_ws}),this._workerTasks.includes(a._id)&&this._workerTasks.splice(this._workerTasks.indexOf(a._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:a._id},{$set:{status:"complete"}})),[3,4];case 3:return o=e.sent(),r||(clearTimeout(t),console.error("Worker failed to process task:",a._id,o),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:a._id,has_error:!0,data:o.message,id_user:a.id_user,user:a.user,id_ws:a.id_ws}),this._workerTasks.includes(a._id)&&this._workerTasks.splice(this._workerTasks.indexOf(a._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:a._id},{$set:{status:"complete"}})),[3,4];case 4:return[2]}})})},function(){}),[2]})})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):resolveio_server_app_1.ResolveIOServer.getMongoConnection()?resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(n,i){return __awaiter(e,void 0,void 0,function(){var r,s=this;return __generator(this,function(e){return this._rebootFlag?i(!1,409,"Unable To Process"):("DEBUG"===this.LOGGER&&console.log("Verify Client",n,i),r=n.req.headers["sec-websocket-protocol"].split(/,/),(n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,o){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:n.req.id_user=o.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(o.id_user)];case 3:return(r=e.sent())?(n.req.user=r.fullname,n.req.user_readonly=r.readonly||!1,n.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")),[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var t=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",t._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",t._portWSS)}),this._serverWSS.on("connection",function(c,e){t.publicProgram||(c.id_user=e.id_user,c.user=e.user,c.user_readonly=e.user_readonly,c.doc_user=e.doc_user,"Admin"!==c.user&&"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&t.getMethodManager().callMethodInternal.call(t.getMethodManager(),"supportCreateBillingUser",{id_user:c.id_user,user:c.user,date:new Date,client:resolveio_server_app_1.ResolveIOServer.getClientName()})),c.id_socket=(0,common_1.objectIdHexString)(),c.retryCnt=0,t._websocketManager.addWebSocket(c),t._subscriptionManager.createLoggedInUser(c.id_socket).then(function(){setTimeout(function(){c.pingTime=new Date,c.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(c))})},5e3)}),"DEBUG"===t.LOGGER&&console.log("Connection from: "+e.user),c.isAlive=!0,c.on("message",function(l){return __awaiter(t,void 0,void 0,function(){var r,t,o,s,n,i,a=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+c.user,l),this._debugMsgRecv+=1,s=!1,r=[];try{r=JSON.parse(l,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",l),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([l,e])),s=!0}if(s)return[3,8];if("string"==typeof r&&"ping"===r)c&&c.readyState===c.OPEN&&c.send("pong",function(e){e&&(a._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),a.unsubscribeWS(c))});else if("string"==typeof r&&"pong"===r)c.isAlive=!0,c.pongTime=new Date,c.latency=moment.duration(moment(c.pongTime).diff(c.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(c);else{if(Array.isArray(r[0]))return[3,1];console.log("Invalid message format, expected array:",r)}return[2];case 1:e.trys.push([1,6,7,8]),t=__values(r),o=t.next(),e.label=2;case 2:return o.done?[3,5]:(s=o.value,[4,this.processSocketMessage(c,s)]);case 3:e.sent(),e.label=4;case 4:return o=t.next(),[3,2];case 5:return[3,8];case 6:return n=e.sent(),n={error:n},[3,8];case 7:try{o&&!o.done&&(i=t.return)&&i.call(t)}finally{if(n)throw n.error}return[7];case 8:return[2]}})})}).on("end",function(){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,c.user,c.id_socket,"WS Error")})}),setInterval(function(){t._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?t.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(f,m){return __awaiter(this,void 0,void 0,function(){var r,t,o,s,n,i,a,l,c,u,_,g,d,p,h,v;return __generator(this,function(e){switch(e.label){case 0:return(r=m[0],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||f.doc_user.roles.super_admin)?(a=m[1],t=m[2],"subscription"!==(o=m[3])?[3,1]:(i=m[4],l=m[5],"sub"===i?this._subscriptionManager.subscribe(r,a,f,t,l,m.slice(6)):this._subscriptionManager.unsubscribe(r,a,f,t,l,m.slice(6)),[3,11])):[2];case 1:if(this.publicProgram||"offline"!==o)return[3,10];p={messageId:t,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,p),this._offlineUpdates.push(f),s=m[4],n=0,e.label=2;case 2:if(!(n<s.length))return[3,9];if(i=s[n],c=i.data,c.shift(),c.shift(),a=c.shift(),c.shift(),g=c.shift(),d=(0,common_1.objectIdHexString)(),l={messageId:a,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,l),"insertDocument"===g&&"driver-gps"===c[0])return[3,8];if("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-method-latency",date:new Date,data:{_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}}):log_method_latency_collection_1.LogMethodLatencies.create({_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:t,route:r}),!this._methodManager._methods[g])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(h=this._methodManager.callMethodInternal).call.apply(h,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),g],__read(c),!1))];case 4:return e.sent(),[3,6];case 5:return h=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(h,null,2)),[3,6];case 6:return"updateDocumentOffline"!==g&&"updateDocumentPropsOffline"!==g||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c[0]),[3,8];case 7:console.log("Offline - Could not find method: "+g),e.label=8;case 8:return n++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(f.id_socket),1),[3,11];case 10:if(c=__spreadArray([],__read(m),!1),v=c.shift(),u=c.shift(),_=c.shift(),"method"===c.shift()){if(g=c.shift(),f.user_readonly)return[2];d=(0,common_1.objectIdHexString)(),"https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-method-latency",date:new Date,data:{_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}}):log_method_latency_collection_1.LogMethodLatencies.create({_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:_,route:v}),p={messageId:_,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,p),this._methodManager._methods[g]?(v=this._methodManager).callMethod.apply(v,__spreadArray([d,f,u,_,g],__read(c),!1)):console.log("Could not find method: "+g)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,o,s,n){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((n=n.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,s){var n,i,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(t){return function(e){var r=[t,e];if(n)throw new TypeError("Generator is already executing.");for(;l=c&&r[c=0]?0:l;)try{if(n=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return l.label++,{value:r[1],done:!1};case 5:l.label++,i=r[1],r=[0];continue;case 7:r=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){l=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))l.label=r[1];else if(6===r[0]&&l.label<a[1])l.label=a[1],a=r;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(r)}}r=s.call(o,l)}catch(e){r=[6,e],i=0}finally{n=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],o=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,s,n=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(o=n.next()).done;)i.push(o.value)}catch(e){s={error:e}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var o,s=0,n=r.length;s<n;s++)!o&&s in r||((o=o||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(o||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),log_method_latency_collection_1=require("./collections/log-method-latency.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),mongodb_1=require("mongodb"),worker_task_request_collection_1=require("./collections/worker-task-request.collection"),worker_task_response_collection_1=require("./collections/worker-task-response.collection"),websocket_manager_1=require("./managers/websocket.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._workerTasks=[],this._safeShutdown=!1,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction}return ResolveIOMainServer.prototype.initServerApp=function(){var e=this;this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){e._subscriptionManager&&e._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",e._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",e._debugMsgQueue)),e._debugMsgQueue=0,e._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(o,s){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return o&&"MongoError"===o.name&&48===o.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[o,s]),r=moment().diff(this._serverStartTime,"seconds"),o&&("MongoNetworkTimeoutError"===o.name||o instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:o.name,message:o.message,stack:o.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return o&&"MongoError"===o.name&&"not master"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return o&&"MongoError"===o.name&&"not master and slaveOk=false"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:o&&"StatusError"!==o.name&&""!==o.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(e,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGTERM",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGQUIT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager,this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager,this.listen())},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,t,o,s,n,i,a,l=this;return __generator(this,function(e){switch(e.label){case 0:return console.log("Worker instance started, watching worker-task-reqs..."),(r=worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{status:"pending"}}])).on("change",function(s){return __awaiter(l,void 0,void 0,function(){var r,t,o=this;return __generator(this,function(e){return"insert"===s.operationType?(r=s.fullDocument)&&setTimeout(function(){o.processTask(r)},25*this._workerTasks.length):"update"===s.operationType&&(t=s.fullDocument)&&"pending"===t.status&&setTimeout(function(){o.processTask(t)},25*this._workerTasks.length),[2]})})}),r.on("error",function(e){console.error("Error in change stream worker task requests:",e),r&&r.close()}),r.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return l.startWorkerInstance()},5e3)}),[4,worker_task_request_collection_1.WorkerTaskRequests.find({status:"pending"},{sort:{createdAt:1}})];case 1:t=e.sent();try{for(o=__values(t),s=o.next();!s.done;s=o.next())n=s.value,this.processTask(n)}catch(e){i={error:e}}finally{try{s&&!s.done&&(a=o.return)&&a.call(o)}finally{if(i)throw i.error}}return[2]}})})},ResolveIOMainServer.prototype.processTask=function(a){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){return this._workerTasks.includes(a._id)||worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:a._id,status:"pending"},{$set:{status:"processing"}}).then(function(i){return __awaiter(r,void 0,void 0,function(){var r,t,o,s,n=this;return __generator(this,function(e){switch(e.label){case 0:if(!i)return[3,4];this._workerTasks.push(a._id),r=!1,t=setTimeout(function(){r=!0,console.error("Worker timed out processing task:",a._id),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:a._id,has_error:!0,data:"Task timed out.",id_user:a.id_user,user:a.user,id_ws:a.id_ws}),n._workerTasks.includes(a._id)&&n._workerTasks.splice(n._workerTasks.indexOf(a._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:a._id},{$set:{status:"timeout"}})},12e4),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(s=this._methodManager.callMethodInternal).call.apply(s,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:a.id_user,user:a.user,id_ws:a.id_ws}),a.method],__read(a.params),!1))];case 2:return s=e.sent(),r||(clearTimeout(t),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:a._id,has_error:!1,data:s,id_user:a.id_user,user:a.user,id_ws:a.id_ws}),this._workerTasks.includes(a._id)&&this._workerTasks.splice(this._workerTasks.indexOf(a._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:a._id},{$set:{status:"complete"}})),[3,4];case 3:return o=e.sent(),r||(clearTimeout(t),console.error("Worker failed to process task:",a._id,o),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:a._id,has_error:!0,data:o.message,id_user:a.id_user,user:a.user,id_ws:a.id_ws}),this._workerTasks.includes(a._id)&&this._workerTasks.splice(this._workerTasks.indexOf(a._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:a._id},{$set:{status:"complete"}})),[3,4];case 4:return[2]}})})},function(){}),[2]})})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):resolveio_server_app_1.ResolveIOServer.getMongoConnection()?resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(n,i){return __awaiter(e,void 0,void 0,function(){var r,s=this;return __generator(this,function(e){return this._rebootFlag?i(!1,409,"Unable To Process"):("DEBUG"===this.LOGGER&&console.log("Verify Client",n,i),r=n.req.headers["sec-websocket-protocol"].split(/,/),(n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,o){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:n.req.id_user=o.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(o.id_user)];case 3:return(r=e.sent())?(n.req.user=r.fullname,n.req.user_readonly=r.readonly||!1,n.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")),[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var t=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",t._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",t._portWSS)}),this._serverWSS.on("connection",function(c,e){t.publicProgram||(c.id_user=e.id_user,c.user=e.user,c.user_readonly=e.user_readonly,c.doc_user=e.doc_user,"Admin"!==c.user&&"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&t.getMethodManager().callMethodInternal.call(t.getMethodManager(),"supportCreateBillingUser",{id_user:c.id_user,user:c.user,date:new Date,client:resolveio_server_app_1.ResolveIOServer.getClientName()})),c.id_socket=(0,common_1.objectIdHexString)(),c.retryCnt=0,t._websocketManager.addWebSocket(c),t._subscriptionManager.createLoggedInUser(c.id_socket).then(function(){setTimeout(function(){c.pingTime=new Date,c.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(c))})},5e3)}),"DEBUG"===t.LOGGER&&console.log("Connection from: "+e.user),c.isAlive=!0,c.on("message",function(l){return __awaiter(t,void 0,void 0,function(){var r,t,o,s,n,i,a=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+c.user,l),this._debugMsgRecv+=1,s=!1,r=[];try{r=JSON.parse(l,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",l),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([l,e])),s=!0}if(s)return[3,8];if("string"==typeof r&&"ping"===r)c&&c.readyState===c.OPEN&&c.send("pong",function(e){e&&(a._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),a.unsubscribeWS(c))});else if("string"==typeof r&&"pong"===r)c.isAlive=!0,c.pongTime=new Date,c.latency=moment.duration(moment(c.pongTime).diff(c.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(c);else{if(Array.isArray(r[0]))return[3,1];console.log("Invalid message format, expected array:",r)}return[2];case 1:e.trys.push([1,6,7,8]),t=__values(r),o=t.next(),e.label=2;case 2:return o.done?[3,5]:(s=o.value,[4,this.processSocketMessage(c,s)]);case 3:e.sent(),e.label=4;case 4:return o=t.next(),[3,2];case 5:return[3,8];case 6:return n=e.sent(),n={error:n},[3,8];case 7:try{o&&!o.done&&(i=t.return)&&i.call(t)}finally{if(n)throw n.error}return[7];case 8:return[2]}})})}).on("end",function(){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,c.user,c.id_socket,"WS Error")})}),setInterval(function(){t._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?t.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(f,m){return __awaiter(this,void 0,void 0,function(){var r,t,o,s,n,i,a,l,c,u,_,g,d,p,h,v;return __generator(this,function(e){switch(e.label){case 0:return(r=m[0],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||f.doc_user.roles.super_admin)?(a=m[1],t=m[2],"subscription"!==(o=m[3])?[3,1]:(i=m[4],l=m[5],"sub"===i?this._subscriptionManager.subscribe(r,a,f,t,l,m.slice(6)):this._subscriptionManager.unsubscribe(r,a,f,t,l,m.slice(6)),[3,11])):[2];case 1:if(this.publicProgram||"offline"!==o)return[3,10];p={messageId:t,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,p),this._offlineUpdates.push(f),s=m[4],n=0,e.label=2;case 2:if(!(n<s.length))return[3,9];if(i=s[n],c=i.data,c.shift(),c.shift(),a=c.shift(),c.shift(),g=c.shift(),d=(0,common_1.objectIdHexString)(),l={messageId:a,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,l),"insertDocument"===g&&"driver-gps"===c[0])return[3,8];if("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-method-latency",date:new Date,data:{_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}}):log_method_latency_collection_1.LogMethodLatencies.create({_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:t,route:r}),!this._methodManager._methods[g])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(h=this._methodManager.callMethodInternal).call.apply(h,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),g],__read(c),!1))];case 4:return e.sent(),[3,6];case 5:return h=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(h,null,2)),[3,6];case 6:return"updateDocumentOffline"!==g&&"updateDocumentPropsOffline"!==g||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c[0]),[3,8];case 7:console.log("Offline - Could not find method: "+g),e.label=8;case 8:return n++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(f.id_socket),1),[3,11];case 10:if(c=__spreadArray([],__read(m),!1),v=c.shift(),u=c.shift(),_=c.shift(),"method"===c.shift()){if(g=c.shift(),f.user_readonly)return[2];d=(0,common_1.objectIdHexString)(),"https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-method-latency",date:new Date,data:{_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}}):log_method_latency_collection_1.LogMethodLatencies.create({_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:_,route:v}),p={messageId:_,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,p),this._methodManager._methods[g]?(v=this._methodManager).callMethod.apply(v,__spreadArray([d,f,u,_,g],__read(c),!1)):console.log("Could not find method: "+g)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
2
2
  //# sourceMappingURL=server-app.js.map
package/server-app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_workerTasks","_safeShutdown","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","prototype","initServerApp","_this","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_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","changeStream","WorkerTaskRequests","watchCollection","$match","fullDocument.status","fullDocument","change","operationType","task_1","processTask","length","task_2","status","find","sort","createdAt","pendingTasks","_b","pendingTasks_1","__values","pendingTasks_1_1","done","task","value","includes","_id","updateOne","$set","then","resReq","push","timedOut_1","timeoutHandle","WorkerTaskResponses","create","id_request","has_error","data","id_user","user","id_ws","splice","indexOf","callMethodInternal","call","apply","__spreadArray","Object","assign","method","__read","params","result","clearTimeout","err_1","getActiveMonitorFunctions","setImmediate","getMongoConnection","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","ws","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","fullname","readonly","date","client","getClientName","objectIdHexString","addWebSocket","createLoggedInUser","send","unsubscribeWS","parseErrorFound","socketData","parse","e","readyState","OPEN","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","message_1","processSocketMessage","now","getTime","messageRoute","some","a","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","methodLatencyId","serverResMethod","getLocalLogManager","writeLog","__v","date_start","date_end","latency_ms","LogMethodLatencies","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","_c","err_3","getMongoManager","invalidateQueryCache","map","messageRoute_1","messageDate_1","messageId_1","callMethod","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,Q,0FAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EAEAM,OAAAN,QAAA,iBAAA,EACAO,SAAAP,QAAA,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oBAAAA","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\n// import * as SegfaultHandler from 'segfault-handler';\nimport * as moment from 'moment-timezone';\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\n\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { LogMethodLatencies } from './collections/log-method-latency.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\nimport { WorkerTaskRequestModel } from './models/worker-task-request.model';\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\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\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\tprivate _workerTasks: string[] = [];\n\n\tprivate _safeShutdown = false;\n\n\tconstructor() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\t}\n\n\tinitServerApp() {\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\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\t// if (error && error['name'] === 'MongoServerError') {\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\tthis._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', () => {\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\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\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\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\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\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n if (this._isWorkersEnabled) {\n if (this._isWorkerInstance) {\n console.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager();\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance();\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance();\n\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n this._cronManager = new CronManager();\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use body parser for http call (login)\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\n\t\t\t// Website you wish to allow to connect\n\t\t\t// res.setHeader('Access-Control-Allow-Origin', ResolveIOServer.getServerConfig()['ROOT_URL']);\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\n\t\t\t// Request methods you wish to allow\n\t\t\t// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\n\t\t\t// Request headers you wish to allow\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\n\t\t\t// Set to true if you need the website to include cookies in the requests sent\n\t\t\t// to the API (e.g. in case you use sessions)\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\n\t\t\t// Pass to next layer of middleware\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, ResolveIOServer.getServerConfig());\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 async startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\t\t\n\t\tlet changeStream = WorkerTaskRequests.watchCollection(\n\t\t\t[{ $match: { 'fullDocument.status': 'pending' } }],\n\t\t\t{ fullDocument: 'updateLookup' }\n\t\t);\n\t\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task) {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (change.operationType === 'update') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task && task.status === 'pending') {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tif (changeStream) {\n\t\t\t\tchangeStream.close();\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('close', () => {\n\t\t\tconsole.log('Change stream worker task requests closed. Restarting...');\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000);\n\t\t});\n\t\n\t\t// Process existing pending tasks\n\t\tconst pendingTasks = await WorkerTaskRequests.find({ status: 'pending' }, { sort: { createdAt: 1 } });\n\t\tfor (const task of pendingTasks) {\n\t\t\tthis.processTask(task);\n\t\t}\n\t}\n\t\n\tprivate async processTask(task: WorkerTaskRequestModel) {\n\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tWorkerTaskRequests.updateOne(\n\t\t\t{ _id: task._id, status: 'pending' },\n\t\t\t{ $set: { status: 'processing' } }\n\t\t).then(async resReq => {\n\t\t\tif (resReq) {\n\t\t\t\tthis._workerTasks.push(task._id);\n\t\n\t\t\t\tlet timedOut = false;\n\t\t\t\tlet timeoutHandle = setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tconsole.error('Worker timed out processing task:', task._id);\n\t\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\tdata: 'Task timed out.',\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\n\t\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t\t}\n\t\n\t\t\t\t\tWorkerTaskRequests.updateOne(\n\t\t\t\t\t\t{ _id: task._id },\n\t\t\t\t\t\t{ $set: { status: 'timeout' } }\n\t\t\t\t\t);\n\t\t\t\t}, 120000);\n\t\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await this._methodManager.callMethodInternal.call(\n\t\t\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttask.method,\n\t\t\t\t\t\t...task.params\n\t\t\t\t\t);\n\t\n\t\t\t\t\tif (!timedOut) {\n\t\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\n\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t});\n\t\n\t\t\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\tWorkerTaskRequests.updateOne(\n\t\t\t\t\t\t\t{ _id: task._id },\n\t\t\t\t\t\t\t{ $set: { status: 'complete' } }\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tif (!timedOut) {\n\t\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\n\t\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\t\n\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\t\tdata: err.message,\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t});\n\t\n\t\t\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\tWorkerTaskRequests.updateOne(\n\t\t\t\t\t\t\t{ _id: task._id },\n\t\t\t\t\t\t\t{ $set: { status: 'complete' } }\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\tprivate 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._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\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}, () => {process.exit(1)});\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(), \n\t\t\t\t\t'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length, \n\t\t\t\t\t// this._monitorManagerFunction.getLastCompletedMonitorFunction() ? this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime : '',\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.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\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\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\t// Start express server\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`\n\n\t\t// Start websocket server\n\t\t// Verify client with token before opening socket\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (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\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (info.origin !== ResolveIOServer.getServerConfig()['ROOT_URL'] && info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL'] && info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL'] && info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']) {\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 (err) {\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// Listen to port for websocket\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\t// On websocket connection (already verified)\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (!this.publicProgram) {\n\t\t\t\t// Get user from token\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\tif (ws['user'] !== 'Admin' && ResolveIOServer.getServerConfig()['CLIENT_NAME'] !== 'ResolveIO') {\n\t\t\t\t\tthis.getMethodManager().callMethodInternal.call(this.getMethodManager(), 'supportCreateBillingUser', {\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\tdate: new Date(),\n\t\t\t\t\t\tclient: ResolveIOServer.getClientName()\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\tws['retryCnt'] = 0;\n\n\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', (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\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\n\t\t\t});\n\n\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\tconsole.log('Connection from: ' + req['user']);\n\t\t\t}\n\t\t\t\n\t\t\t// Use for keeping connection alive (ping/pong)\n\t\t\tws['isAlive'] = true;\n\t\t\tws.on('message', async (message: string) => {\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Message from: ' + ws['user'], message);\n\t\t\t\t}\n\n\t\t\t\tthis._debugMsgRecv += 1;\n\n\t\t\t\tlet parseErrorFound = false;\n\n\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch(e) {\n\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\n\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([message, e]));\n\n\t\t\t\t\tparseErrorFound = true;\n\t\t\t\t}\n\n\t\t\t\tif (!parseErrorFound) {\n\t\t\t\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send('pong', (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 Pong');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.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\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!Array.isArray(socketData[0])) {\n\t\t\t\t\t\t// Not an array, invalid message\n\t\t\t\t\t\tconsole.log('Invalid message format, expected array:', socketData);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (let message of socketData) {\n\t\t\t\t\t\t\tawait this.processSocketMessage(ws, message);\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\t.on('end', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS End');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS Close');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', error => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), ws['user'], ws['id_socket'], 'WS Error');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t});\n\n\t\t// Keep alive timer to ping/pong\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\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\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.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', (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\tthis.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', (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\tthis.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\tlet messageRoute = socketData[0];\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\tlet messageDate = socketData[1];\n\t\tlet messageId = socketData[2];\n\t\tlet type = socketData[3];\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = socketData[4];\n\t\t\tlet pub = socketData[5];\n\n\t\t\t// Subscribe\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t\t// Unsubscribe\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.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 = socketData[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\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\t\t\t\tlet methodLatencyId = objectIdHexString();\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\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t) {\n\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\ttype: 'log-method-latency',\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\tmethod: method\n\t\t\t\t\t});\n\t\t\t\t}\n\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\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\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\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\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.callMethodInternal.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 { //methods\n\t\t\tlet data = [...socketData];\n\t\t\t\n\t\t\tlet messageRoute: string = data.shift();\n\t\t\tlet messageDate: Date = data.shift();\n\t\t\tlet messageId: number = data.shift();\n\t\t\tlet type: string = data.shift();\n\n\t\t\tif (type === 'method') {\n\t\t\t\tlet method = data.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\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t) {\n\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\ttype: 'log-method-latency',\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\tmethod: method\n\t\t\t\t\t});\n\t\t\t\t}\n\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\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\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\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\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, serverRes);\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else if (type === 'methodResponse') {\n\t\t\t// \tlet method = data.shift();\n\n\t\t\t// \tMethodResponses.findOne({ $and: [{ id_user: ws['id_user'] }, { message_id: messageId }, { method: method }, { date: messageDate }] }).then(\n\t\t\t// \t\tres => {\n\t\t\t// \t\t\tif (res) {\n\t\t\t// \t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t// \t\t\t\t\tthis._websocketManager.send(ws, res.response);\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\terr => {}\n\t\t\t// \t);\n\t\t\t// }\n\t\t}\n\t}\n\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._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":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_workerTasks","_safeShutdown","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","prototype","initServerApp","_this","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_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","changeStream","WorkerTaskRequests","watchCollection","$match","status","change","operationType","task_1","fullDocument","processTask","length","task_2","find","sort","createdAt","pendingTasks","_b","pendingTasks_1","__values","pendingTasks_1_1","done","task","value","includes","_id","updateOne","$set","then","resReq","push","timedOut_1","timeoutHandle","WorkerTaskResponses","create","id_request","has_error","data","id_user","user","id_ws","splice","indexOf","callMethodInternal","call","apply","__spreadArray","Object","assign","method","__read","params","result","clearTimeout","err_1","getActiveMonitorFunctions","setImmediate","getMongoConnection","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","ws","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","fullname","readonly","date","client","getClientName","objectIdHexString","addWebSocket","createLoggedInUser","send","unsubscribeWS","parseErrorFound","socketData","parse","e","readyState","OPEN","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","message_1","processSocketMessage","now","getTime","messageRoute","some","a","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","methodLatencyId","serverResMethod","getLocalLogManager","writeLog","__v","date_start","date_end","latency_ms","LogMethodLatencies","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","_c","err_3","getMongoManager","invalidateQueryCache","map","messageRoute_1","messageDate_1","messageId_1","callMethod","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,Q,0FAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EAEAM,OAAAN,QAAA,iBAAA,EACAO,SAAAP,QAAA,eAAA,EACAQ,eAAAR,QAAA,yBAAA,EACAS,iBAAAT,QAAA,2BAAA,EACAU,uBAAAV,QAAA,iCAAA,EACAW,kBAAAX,QAAA,4BAAA,EAGAY,iBAAAZ,QAAA,8BAAA,EACAa,gCAAAb,QAAA,6CAAA,EACAc,kBAAAd,QAAA,+BAAA,EAEAe,OAAAf,QAAA,aAAA,EACAgB,OAAAhB,QAAA,aAAA,EACAiB,SAAAjB,QAAA,eAAA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AAU6E,EAAM,KAAM,CAAC,EAAI,UACxFY,OAAQA,EACRX,QAASyB,EAAY,SAAK,GAC1BxB,KAAMwB,EAAS,MAAK,GACpB8D,UAAWsC,EACXT,MAAOO,C,CACP,EAGE7B,EAAiC,CACpCP,UAAWsC,EACX9B,SAAU,CAAA,EACVhG,KAAM,K,EAGH0B,GAAMA,EAAGwC,aAAexC,EAAGyC,MAC9B9L,KAAK4D,kBAAkB2H,KAAKlC,EAAIqE,CAAS,EAGtC1N,KAAKyC,eAAewM,SAAS1G,IAChChC,EAAAvG,KAAKyC,gBAAeiN,WAAUvH,MAAA5B,EAAA6B,cAAA,CAAC6F,EAAiB5E,EAAImG,EAAaC,EAAWlH,GAAMC,OAAKb,CAAI,EAAA,CAAA,CAAA,CAAA,EAG3F5F,QAAQC,IAAI,0BAA4BuG,CAAM,C,oCAoB3CxI,oBAAAsB,UAAAmK,cAAP,SAAqBnC,GAChBrJ,KAAK6B,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIhB,KAAQ,aAAc,WAAYqI,EAAS,KAAGA,EAAc,SAAC,EAE9ErJ,KAAK6B,qBAAqB8N,eAAetG,CAAE,EAC3CA,EAAGuG,mBAAkB,CAEtB,EAEO7P,oBAAAsB,UAAAwO,OAAP,WACC,OAAO7P,KAAKkE,IACb,EAEOnE,oBAAAsB,UAAAuB,gBAAP,WACC,OAAO9C,uBAAA6C,gBAAgBC,gBAAe,CACvC,EACD7C,mBAAA,EAAC,EAh9BY+P,QAAA/P,oBAAAA","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\n// import * as SegfaultHandler from 'segfault-handler';\nimport * as moment from 'moment-timezone';\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\n\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { LogMethodLatencies } from './collections/log-method-latency.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\nimport { WorkerTaskRequestModel } from './models/worker-task-request.model';\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\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\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\tprivate _workerTasks: string[] = [];\n\n\tprivate _safeShutdown = false;\n\n\tconstructor() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\t}\n\n\tinitServerApp() {\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\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\t// if (error && error['name'] === 'MongoServerError') {\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\tthis._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', () => {\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\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\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\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\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\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n if (this._isWorkersEnabled) {\n if (this._isWorkerInstance) {\n console.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager();\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance();\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance();\n\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n this._cronManager = new CronManager();\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use body parser for http call (login)\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\n\t\t\t// Website you wish to allow to connect\n\t\t\t// res.setHeader('Access-Control-Allow-Origin', ResolveIOServer.getServerConfig()['ROOT_URL']);\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\n\t\t\t// Request methods you wish to allow\n\t\t\t// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\n\t\t\t// Request headers you wish to allow\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\n\t\t\t// Set to true if you need the website to include cookies in the requests sent\n\t\t\t// to the API (e.g. in case you use sessions)\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\n\t\t\t// Pass to next layer of middleware\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, ResolveIOServer.getServerConfig());\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 async startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\t\t\n\t\tlet changeStream = WorkerTaskRequests.watchCollection(\n\t\t\t[{ $match: { 'status': 'pending' } }]\n\t\t);\n\t\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task) {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (change.operationType === 'update') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task && task.status === 'pending') {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tif (changeStream) {\n\t\t\t\tchangeStream.close();\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('close', () => {\n\t\t\tconsole.log('Change stream worker task requests closed. Restarting...');\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000);\n\t\t});\n\t\n\t\t// Process existing pending tasks\n\t\tconst pendingTasks = await WorkerTaskRequests.find({ status: 'pending' }, { sort: { createdAt: 1 } });\n\t\tfor (const task of pendingTasks) {\n\t\t\tthis.processTask(task);\n\t\t}\n\t}\n\t\n\tprivate async processTask(task: WorkerTaskRequestModel) {\n\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tWorkerTaskRequests.updateOne(\n\t\t\t{ _id: task._id, status: 'pending' },\n\t\t\t{ $set: { status: 'processing' } }\n\t\t).then(async resReq => {\n\t\t\tif (resReq) {\n\t\t\t\tthis._workerTasks.push(task._id);\n\t\n\t\t\t\tlet timedOut = false;\n\t\t\t\tlet timeoutHandle = setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tconsole.error('Worker timed out processing task:', task._id);\n\t\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\tdata: 'Task timed out.',\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\n\t\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t\t}\n\t\n\t\t\t\t\tWorkerTaskRequests.updateOne(\n\t\t\t\t\t\t{ _id: task._id },\n\t\t\t\t\t\t{ $set: { status: 'timeout' } }\n\t\t\t\t\t);\n\t\t\t\t}, 120000);\n\t\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await this._methodManager.callMethodInternal.call(\n\t\t\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttask.method,\n\t\t\t\t\t\t...task.params\n\t\t\t\t\t);\n\t\n\t\t\t\t\tif (!timedOut) {\n\t\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\n\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t});\n\t\n\t\t\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\tWorkerTaskRequests.updateOne(\n\t\t\t\t\t\t\t{ _id: task._id },\n\t\t\t\t\t\t\t{ $set: { status: 'complete' } }\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tif (!timedOut) {\n\t\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\n\t\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\t\n\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\t\tdata: err.message,\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t});\n\t\n\t\t\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\tWorkerTaskRequests.updateOne(\n\t\t\t\t\t\t\t{ _id: task._id },\n\t\t\t\t\t\t\t{ $set: { status: 'complete' } }\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\tprivate 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._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\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}, () => {process.exit(1)});\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(), \n\t\t\t\t\t'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length, \n\t\t\t\t\t// this._monitorManagerFunction.getLastCompletedMonitorFunction() ? this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime : '',\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.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\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\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\t// Start express server\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`\n\n\t\t// Start websocket server\n\t\t// Verify client with token before opening socket\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (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\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (info.origin !== ResolveIOServer.getServerConfig()['ROOT_URL'] && info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL'] && info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL'] && info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']) {\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 (err) {\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// Listen to port for websocket\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\t// On websocket connection (already verified)\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (!this.publicProgram) {\n\t\t\t\t// Get user from token\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\tif (ws['user'] !== 'Admin' && ResolveIOServer.getServerConfig()['CLIENT_NAME'] !== 'ResolveIO') {\n\t\t\t\t\tthis.getMethodManager().callMethodInternal.call(this.getMethodManager(), 'supportCreateBillingUser', {\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\tdate: new Date(),\n\t\t\t\t\t\tclient: ResolveIOServer.getClientName()\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\tws['retryCnt'] = 0;\n\n\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', (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\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\n\t\t\t});\n\n\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\tconsole.log('Connection from: ' + req['user']);\n\t\t\t}\n\t\t\t\n\t\t\t// Use for keeping connection alive (ping/pong)\n\t\t\tws['isAlive'] = true;\n\t\t\tws.on('message', async (message: string) => {\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Message from: ' + ws['user'], message);\n\t\t\t\t}\n\n\t\t\t\tthis._debugMsgRecv += 1;\n\n\t\t\t\tlet parseErrorFound = false;\n\n\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch(e) {\n\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\n\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([message, e]));\n\n\t\t\t\t\tparseErrorFound = true;\n\t\t\t\t}\n\n\t\t\t\tif (!parseErrorFound) {\n\t\t\t\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send('pong', (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 Pong');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.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\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!Array.isArray(socketData[0])) {\n\t\t\t\t\t\t// Not an array, invalid message\n\t\t\t\t\t\tconsole.log('Invalid message format, expected array:', socketData);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (let message of socketData) {\n\t\t\t\t\t\t\tawait this.processSocketMessage(ws, message);\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\t.on('end', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS End');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS Close');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', error => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), ws['user'], ws['id_socket'], 'WS Error');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t});\n\n\t\t// Keep alive timer to ping/pong\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\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\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.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', (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\tthis.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', (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\tthis.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\tlet messageRoute = socketData[0];\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\tlet messageDate = socketData[1];\n\t\tlet messageId = socketData[2];\n\t\tlet type = socketData[3];\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = socketData[4];\n\t\t\tlet pub = socketData[5];\n\n\t\t\t// Subscribe\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t\t// Unsubscribe\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.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 = socketData[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\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\t\t\t\tlet methodLatencyId = objectIdHexString();\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\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t) {\n\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\ttype: 'log-method-latency',\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\tmethod: method\n\t\t\t\t\t});\n\t\t\t\t}\n\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\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\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\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\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.callMethodInternal.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 { //methods\n\t\t\tlet data = [...socketData];\n\t\t\t\n\t\t\tlet messageRoute: string = data.shift();\n\t\t\tlet messageDate: Date = data.shift();\n\t\t\tlet messageId: number = data.shift();\n\t\t\tlet type: string = data.shift();\n\n\t\t\tif (type === 'method') {\n\t\t\t\tlet method = data.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\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t) {\n\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\ttype: 'log-method-latency',\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\tmethod: method\n\t\t\t\t\t});\n\t\t\t\t}\n\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\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\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\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\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, serverRes);\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else if (type === 'methodResponse') {\n\t\t\t// \tlet method = data.shift();\n\n\t\t\t// \tMethodResponses.findOne({ $and: [{ id_user: ws['id_user'] }, { message_id: messageId }, { method: method }, { date: messageDate }] }).then(\n\t\t\t// \t\tres => {\n\t\t\t// \t\t\tif (res) {\n\t\t\t// \t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t// \t\t\t\t\tthis._websocketManager.send(ws, res.response);\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\terr => {}\n\t\t\t// \t);\n\t\t\t// }\n\t\t}\n\t}\n\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._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}"]}