@resolveio/server-lib 20.3.1 → 20.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/collections/worker-task-request.collection.js +1 -1
- package/collections/worker-task-request.collection.js.map +1 -1
- package/collections/worker-task-response.collection.js +1 -1
- package/collections/worker-task-response.collection.js.map +1 -1
- package/managers/method.manager.js +1 -1
- package/managers/method.manager.js.map +1 -1
- package/managers/mongo.manager.js +1 -1
- package/managers/mongo.manager.js.map +1 -1
- package/package.json +1 -1
- package/server-app.js +1 -1
- package/server-app.js.map +1 -1
package/package.json
CHANGED
package/server-app.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.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((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,a,u={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(o)throw new TypeError("Generator is already executing.");for(;u=c&&r[c=0]?0:u;)try{if(o=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 u.label++,{value:r[1],done:!1};case 5:u.label++,i=r[1],r=[0];continue;case 7:r=u.ops.pop(),u.trys.pop();continue;default:if(!(a=0<(a=u.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){u=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))u.label=r[1];else if(6===r[0]&&u.label<a[1])u.label=a[1],a=r;else{if(!(a&&u.label<a[2])){a[2]&&u.ops.pop(),u.trys.pop();continue}u.label=a[2],u.ops.push(r)}}r=s.call(n,u)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!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"),mongo_manager_1=require("./managers/mongo.manager"),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"),method_response_collection_1=require("./collections/method-response.collection"),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"),index_1=require("./index"),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"),ResolveIOMainServer=function(){function ResolveIOMainServer(e,r,t,n,s,o,i){void 0===i&&(i=!1);var a=this;this._offlineUpdates=[],this._msgQueue=[],this._msgQueueRunning=!1,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._safeShutdown=!1,this._serverConfig=r,this._clientRoutes=t,this._clientDir=n,this.sesMail=s,this.standardProgram=o,this.publicProgram=i,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager(e,r),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){a._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Queue Length",a._msgQueue.length),console.log(new Date,"Server App","Msg Recv Hits",a._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",a._debugMsgQueue)),a._debugMsgQueue=0,a._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(n,s){return __awaiter(a,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n 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 - "+this._serverConfig.CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.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 n&&"MongoError"===n.name&&"not master"===n.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 - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.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 n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.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 - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:n&&"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(a,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 - "+this._serverConfig.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(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGTERM",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGQUIT",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.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,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager(this),this.startWorkerInstance()):(console.log("Running as a Server instance"),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager(this),this.listen())}return ResolveIOMainServer.prototype.startServerInstance=function(e){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||e.PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||e.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,e),(0,health_1.setupHealthRoutes)(this._app,e),"ResolveIO"!==e.CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,e),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){var r=this,t=(console.log("Worker instance started, watching worker-task-reqs..."),worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"}));t.on("change",function(s){return __awaiter(r,void 0,void 0,function(){var r,t,n;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==s.operationType?[3,7]:(r=s.fullDocument)?(console.log("Worker processing task:",r._id),[4,worker_task_request_collection_1.WorkerTaskRequests.findOneAndUpdate({_id:r._id,status:"pending"},{$set:{status:"processing"}})]):[3,7];case 1:if(!e.sent())return[3,7];e.label=2;case 2:return e.trys.push([2,4,,5]),[4,(n=this._methodManager).callMethodInternal.apply(n,__spreadArray([r.method],r.params,!1))];case 3:return n=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:r._id,has_error:!1,data:[n],id_user:r.id_user,user:r.user,id_ws:r.id_ws}),[3,5];case 4:return t=e.sent(),console.error("Worker failed to process task:",r._id,t),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:r._id,has_error:!0,data:[t.message],id_user:r.id_user,user:r.user,id_ws:r.id_ws}),[3,5];case 5:return[4,worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:r._id},{$set:{status:"complete"}})];case 6:e.sent(),e.label=7;case 7:return[2]}})})}),t.on("error",function(e){console.error("Error in change stream worker task requests:",e),t.close(),setTimeout(function(){return r.startWorkerInstance()},5e3)}),t.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return r.startWorkerInstance()},5e3)})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._msgQueue.length||this._msgQueueRunning||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._msgQueue.length,this._msgQueueRunning,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):index_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)})},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWS=function(r){return Array.from(this._serverWSS.clients).filter(function(e){return e.id_socket===r})[0]},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.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(o,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",o,i),r=o.req.headers["sec-websocket-protocol"].split(/,/),(o.origin===this._serverConfig.ROOT_URL||o.origin===this._serverConfig.SEC_ROOT_URL||o.origin===this._serverConfig.RESOLVEIO_URL||o.origin===this._serverConfig.RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,this._serverConfig.JWT_SECRET,function(t,n){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:o.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(o.req.user=r.fullname,o.req.user_readonly=r.readonly||!1,o.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 u=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",u._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",u._portWSS)}),this._serverWSS.on("connection",function(f,e){u.publicProgram||(f.id_user=e.id_user,f.user=e.user,f.user_readonly=e.user_readonly,f.doc_user=e.doc_user,"Admin"!==f.user&&"ResolveIO"!==u._serverConfig.CLIENT_NAME&&u.getMethodManager().callMethodInternal.call(u.getMethodManager(),"supportCreateBillingUser",{id_user:f.id_user,user:f.user,date:new Date,client:index_1.ResolveIOServer.getClientName()})),f.id_socket=(0,mongo_manager_1.objectIdHexString)(),f.retryCnt=0,u._subscriptionManager.createLoggedInUser(f.id_socket).then(function(){setTimeout(function(){f.pingTime=new Date,f.ping(function(){})},5e3)}),"DEBUG"===u.LOGGER&&console.log("Connection from: "+e.user),f.isAlive=!0,f.on("pong",function(){f.isAlive=!0,f.pongTime=new Date,f.latency=moment.duration(moment(f.pongTime).diff(f.pingTime)).asMilliseconds(),u._subscriptionManager.loggedInLatency(f)}).on("message",function(p){return __awaiter(u,void 0,void 0,function(){var r,t,n,s,o,i,a,u,c,l,_,g,h,d=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+f.user,p),this._debugMsgRecv+=1,u=!1,r=[];try{r=JSON.parse(p,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",p),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+this._serverConfig.CLIENT_NAME,JSON.stringify([p,e])),u=!0}if(!u){if("ping"===r[0])return f&&f.readyState===f.OPEN&&f.send("pong",function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),d.unsubscribeWS(f))}),[2];if(t=r[0],!this.publicProgram&&this._clientRoutes.some(function(e){return t.includes(e)})&&!f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return t.includes(e)||e.includes(t)})})&&!f.doc_user.roles.super_admin)return[2];if(u=r[1],n=r[2],"subscription"!==(s=r[3]))return[3,1];o=r[4],l=r[5],"sub"===o?this._subscriptionManager.subscribe(t,u,f,n,l,r.slice(6)):this._subscriptionManager.unsubscribe(t,u,f,n,l,r.slice(6))}return[3,11];case 1:if(this.publicProgram||"offline"!==s)return[3,10];o={messageId:n,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&f.send(JSON.stringify(o),function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Offline Ack Main"),d.unsubscribeWS(f))}),this._offlineUpdates.push(f),i=r[4],a=0,e.label=2;case 2:if(!(a<i.length))return[3,9];if(u=i[a],c=u.data,l={messageId:u.data[2],hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&f.send(JSON.stringify(l),function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Offline Ack Each"),d.unsubscribeWS(f))}),c.shift(),c.shift(),c.shift(),c.shift(),_=c.shift(),h=(0,mongo_manager_1.objectIdHexString)(),log_method_latency_collection_1.LogMethodLatencies.create({_id:h,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:_}),"reportBuilderGetResults"!==_&&"reportBuilderGetDistinctValue"!==_&&"reportBuilderBuildTree"!==_&&"generatePDF"!==_&&"getWOOfflineData"!==_&&"countQuery"!==_&&"countWithQuery"!==_&&"countCollectionWithQuery"!==_&&"find"!==_&&"findOne"!==_&&"findWithOptions"!==_&&"getDrivers"!==_&&"processAirdropDistribution"!==_&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_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:_,id_user:f.id_user||"",user:f.user||"",messageId:n,route:t}),!this._methodManager._methods[_])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,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),_],c,!1))];case 4:return e.sent(),[3,6];case 5:return g=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(g,null,2)),[3,6];case 6:return"updateDocumentOffline"!==_&&"updateDocumentPropsOffline"!==_||index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c[0]),[3,8];case 7:console.log("Offline - Could not find method: "+_),e.label=8;case 8:return a++,[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:this._msgQueue.splice(0,0,{ws:f,data:r}),e.label=11;case 11:return[2]}})})}).on("end",function(){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,f.user,f.id_socket,"WS Error")})}),setInterval(function(){u._serverWSS.clients.forEach(function(e){e.pingTime&&2e4<=Date.now()-e.pingTime.getTime()&&(!1===e.isAlive?(e.retryCnt++,3<=e.retryCnt?u.unsubscribeWS(e):(e.pingTime=new Date,e.ping(function(){}))):(e.retryCnt=0,e.isAlive=!1,e.pingTime=new Date,e.ping(function(){})))})},2e4),setInterval(function(){if(!u._msgQueueRunning&&u._msgQueue.length){u._msgQueueRunning=!0,u._debugMsgQueue+=1;var e=u._msgQueue.pop(),r=e.data,t=e.ws,e=r.shift(),n=r.shift(),s=r.shift(),o=r.shift();if("method"===o){var i=r.shift();if(t.user_readonly)return;var a=(0,mongo_manager_1.objectIdHexString)(),e=(log_method_latency_collection_1.LogMethodLatencies.create({_id:a,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:i}),"reportBuilderGetResults"!==i&&"reportBuilderGetDistinctValue"!==i&&"reportBuilderBuildTree"!==i&&"generatePDF"!==i&&"getWOOfflineData"!==i&&"countQuery"!==i&&"countWithQuery"!==i&&"countCollectionWithQuery"!==i&&"find"!==i&&"findOne"!==i&&"findWithOptions"!==i&&"getDrivers"!==i&&"processAirdropDistribution"!==i&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(r))<2e5?JSON.stringify(r,null,2):"Too Big",method:i,id_user:t.id_user||"",user:t.user||"",messageId:s,route:e}),{messageId:s,hasError:!1,data:"ACK"});t&&t.readyState===t.OPEN&&t.send(JSON.stringify(e),function(e){e&&u.unsubscribeWS(t)}),u._methodManager._methods[i]?(e=u._methodManager).callMethod.apply(e,__spreadArray([a,t,n,s,i],r,!1)):console.log("Could not find method: "+i)}else"methodResponse"===o&&(i=r.shift(),method_response_collection_1.MethodResponses.findOne({$and:[{id_user:t.id_user},{message_id:s},{method:i},{date:n}]}).then(function(e){e&&t&&t.readyState===t.OPEN&&t.send(JSON.stringify(e.response),function(e){e&&u.unsubscribeWS(t)})},function(e){}));u._msgQueueRunning=!1}},1)},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 this._serverConfig},ResolveIOMainServer}();exports.default=ResolveIOMainServer;
|
|
1
|
+
"use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.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((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,a,u={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(o)throw new TypeError("Generator is already executing.");for(;u=c&&r[c=0]?0:u;)try{if(o=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 u.label++,{value:r[1],done:!1};case 5:u.label++,i=r[1],r=[0];continue;case 7:r=u.ops.pop(),u.trys.pop();continue;default:if(!(a=0<(a=u.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){u=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))u.label=r[1];else if(6===r[0]&&u.label<a[1])u.label=a[1],a=r;else{if(!(a&&u.label<a[2])){a[2]&&u.ops.pop(),u.trys.pop();continue}u.label=a[2],u.ops.push(r)}}r=s.call(n,u)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!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"),mongo_manager_1=require("./managers/mongo.manager"),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"),method_response_collection_1=require("./collections/method-response.collection"),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"),index_1=require("./index"),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"),ResolveIOMainServer=function(){function ResolveIOMainServer(e,r,t,n,s,o,i){void 0===i&&(i=!1);var a=this;this._offlineUpdates=[],this._msgQueue=[],this._msgQueueRunning=!1,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._safeShutdown=!1,this._serverConfig=r,this._clientRoutes=t,this._clientDir=n,this.sesMail=s,this.standardProgram=o,this.publicProgram=i,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager(e,r),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){a._subscriptionManager&&a._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Queue Length",a._msgQueue.length),console.log(new Date,"Server App","Msg Recv Hits",a._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",a._debugMsgQueue)),a._debugMsgQueue=0,a._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(n,s){return __awaiter(a,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n 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 - "+this._serverConfig.CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.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 n&&"MongoError"===n.name&&"not master"===n.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 - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.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 n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.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 - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:n&&"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(a,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 - "+this._serverConfig.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(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGTERM",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGQUIT",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.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,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager(this),this.startWorkerInstance()):(console.log("Running as a Server instance"),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager(this),this.listen())}return ResolveIOMainServer.prototype.startServerInstance=function(e){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||e.PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||e.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,e),(0,health_1.setupHealthRoutes)(this._app,e),"ResolveIO"!==e.CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,e),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){var r=this,t=(console.log("Worker instance started, watching worker-task-reqs..."),worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"}));t.on("change",function(s){return __awaiter(r,void 0,void 0,function(){var r,t,n;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==s.operationType?[3,7]:(r=s.fullDocument)?(console.log("Worker processing task:",r._id),[4,worker_task_request_collection_1.WorkerTaskRequests.findOneAndUpdate({_id:r._id,status:"pending"},{$set:{status:"processing"}})]):[3,7];case 1:if(!e.sent())return[3,7];e.label=2;case 2:return e.trys.push([2,4,,5]),[4,(n=this._methodManager).callMethodInternal.apply(n,__spreadArray([r.method],r.params,!1))];case 3:return n=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:r._id,has_error:!1,data:[n],id_user:r.id_user,user:r.user,id_ws:r.id_ws}),[3,5];case 4:return t=e.sent(),console.error("Worker failed to process task:",r._id,t),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:r._id,has_error:!0,data:[t.message],id_user:r.id_user,user:r.user,id_ws:r.id_ws}),[3,5];case 5:return[4,worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:r._id},{$set:{status:"complete"}})];case 6:e.sent(),e.label=7;case 7:return[2]}})})}),t.on("error",function(e){console.error("Error in change stream worker task requests:",e),t.close(),setTimeout(function(){return r.startWorkerInstance()},5e3)}),t.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return r.startWorkerInstance()},5e3)})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._msgQueue.length||this._msgQueueRunning||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._msgQueue.length,this._msgQueueRunning,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):index_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)})},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWS=function(r){return Array.from(this._serverWSS.clients).filter(function(e){return e.id_socket===r})[0]},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.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(o,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",o,i),r=o.req.headers["sec-websocket-protocol"].split(/,/),(o.origin===this._serverConfig.ROOT_URL||o.origin===this._serverConfig.SEC_ROOT_URL||o.origin===this._serverConfig.RESOLVEIO_URL||o.origin===this._serverConfig.RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,this._serverConfig.JWT_SECRET,function(t,n){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:o.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(o.req.user=r.fullname,o.req.user_readonly=r.readonly||!1,o.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 u=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",u._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",u._portWSS)}),this._serverWSS.on("connection",function(f,e){u.publicProgram||(f.id_user=e.id_user,f.user=e.user,f.user_readonly=e.user_readonly,f.doc_user=e.doc_user,"Admin"!==f.user&&"ResolveIO"!==u._serverConfig.CLIENT_NAME&&u.getMethodManager().callMethodInternal.call(u.getMethodManager(),"supportCreateBillingUser",{id_user:f.id_user,user:f.user,date:new Date,client:index_1.ResolveIOServer.getClientName()})),f.id_socket=(0,mongo_manager_1.objectIdHexString)(),f.retryCnt=0,u._subscriptionManager.createLoggedInUser(f.id_socket).then(function(){setTimeout(function(){f.pingTime=new Date,f.ping(function(){})},5e3)}),"DEBUG"===u.LOGGER&&console.log("Connection from: "+e.user),f.isAlive=!0,f.on("pong",function(){f.isAlive=!0,f.pongTime=new Date,f.latency=moment.duration(moment(f.pongTime).diff(f.pingTime)).asMilliseconds(),u._subscriptionManager.loggedInLatency(f)}).on("message",function(p){return __awaiter(u,void 0,void 0,function(){var r,t,n,s,o,i,a,u,c,l,_,g,h,d=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+f.user,p),this._debugMsgRecv+=1,u=!1,r=[];try{r=JSON.parse(p,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",p),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+this._serverConfig.CLIENT_NAME,JSON.stringify([p,e])),u=!0}if(!u){if("ping"===r[0])return f&&f.readyState===f.OPEN&&f.send("pong",function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),d.unsubscribeWS(f))}),[2];if(t=r[0],!this.publicProgram&&this._clientRoutes.some(function(e){return t.includes(e)})&&!f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return t.includes(e)||e.includes(t)})})&&!f.doc_user.roles.super_admin)return[2];if(u=r[1],n=r[2],"subscription"!==(s=r[3]))return[3,1];o=r[4],l=r[5],"sub"===o?this._subscriptionManager.subscribe(t,u,f,n,l,r.slice(6)):this._subscriptionManager.unsubscribe(t,u,f,n,l,r.slice(6))}return[3,11];case 1:if(this.publicProgram||"offline"!==s)return[3,10];o={messageId:n,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&f.send(JSON.stringify(o),function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Offline Ack Main"),d.unsubscribeWS(f))}),this._offlineUpdates.push(f),i=r[4],a=0,e.label=2;case 2:if(!(a<i.length))return[3,9];if(u=i[a],c=u.data,l={messageId:u.data[2],hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&f.send(JSON.stringify(l),function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Offline Ack Each"),d.unsubscribeWS(f))}),c.shift(),c.shift(),c.shift(),c.shift(),_=c.shift(),h=(0,mongo_manager_1.objectIdHexString)(),log_method_latency_collection_1.LogMethodLatencies.create({_id:h,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:_}),"reportBuilderGetResults"!==_&&"reportBuilderGetDistinctValue"!==_&&"reportBuilderBuildTree"!==_&&"generatePDF"!==_&&"getWOOfflineData"!==_&&"countQuery"!==_&&"countWithQuery"!==_&&"countCollectionWithQuery"!==_&&"find"!==_&&"findOne"!==_&&"findWithOptions"!==_&&"getDrivers"!==_&&"processAirdropDistribution"!==_&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_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:_,id_user:f.id_user||"",user:f.user||"",messageId:n,route:t}),!this._methodManager._methods[_])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,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),_],c,!1))];case 4:return e.sent(),[3,6];case 5:return g=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(g,null,2)),[3,6];case 6:return"updateDocumentOffline"!==_&&"updateDocumentPropsOffline"!==_||index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c[0]),[3,8];case 7:console.log("Offline - Could not find method: "+_),e.label=8;case 8:return a++,[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:this._msgQueue.splice(0,0,{ws:f,data:r}),e.label=11;case 11:return[2]}})})}).on("end",function(){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,f.user,f.id_socket,"WS Error")})}),setInterval(function(){u._serverWSS.clients.forEach(function(e){e.pingTime&&2e4<=Date.now()-e.pingTime.getTime()&&(!1===e.isAlive?(e.retryCnt++,3<=e.retryCnt?u.unsubscribeWS(e):(e.pingTime=new Date,e.ping(function(){}))):(e.retryCnt=0,e.isAlive=!1,e.pingTime=new Date,e.ping(function(){})))})},2e4),setInterval(function(){if(!u._msgQueueRunning&&u._msgQueue.length){u._msgQueueRunning=!0,u._debugMsgQueue+=1;var e=u._msgQueue.pop(),r=e.data,t=e.ws,e=r.shift(),n=r.shift(),s=r.shift(),o=r.shift();if("method"===o){var i=r.shift();if(t.user_readonly)return;var a=(0,mongo_manager_1.objectIdHexString)(),e=(log_method_latency_collection_1.LogMethodLatencies.create({_id:a,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:i}),"reportBuilderGetResults"!==i&&"reportBuilderGetDistinctValue"!==i&&"reportBuilderBuildTree"!==i&&"generatePDF"!==i&&"getWOOfflineData"!==i&&"countQuery"!==i&&"countWithQuery"!==i&&"countCollectionWithQuery"!==i&&"find"!==i&&"findOne"!==i&&"findWithOptions"!==i&&"getDrivers"!==i&&"processAirdropDistribution"!==i&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(r))<2e5?JSON.stringify(r,null,2):"Too Big",method:i,id_user:t.id_user||"",user:t.user||"",messageId:s,route:e}),{messageId:s,hasError:!1,data:"ACK"});t&&t.readyState===t.OPEN&&t.send(JSON.stringify(e),function(e){e&&u.unsubscribeWS(t)}),u._methodManager._methods[i]?(e=u._methodManager).callMethod.apply(e,__spreadArray([a,t,n,s,i],r,!1)):console.log("Could not find method: "+i)}else"methodResponse"===o&&(i=r.shift(),method_response_collection_1.MethodResponses.findOne({$and:[{id_user:t.id_user},{message_id:s},{method:i},{date:n}]}).then(function(e){e&&t&&t.readyState===t.OPEN&&t.send(JSON.stringify(e.response),function(e){e&&u.unsubscribeWS(t)})},function(e){}));u._msgQueueRunning=!1}},1)},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 this._serverConfig},ResolveIOMainServer}();exports.default=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","mongo_manager_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","method_response_collection_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","index_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","ResolveIOMainServer","mainServer","serverConfig","clientRoutes","clientDir","sesMail","standardProgram","publicProgram","_this","this","_offlineUpdates","_msgQueue","_msgQueueRunning","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_serverConfig","_clientDir","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","length","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_methodManager","sendEmail","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","startServerInstance","SubscriptionManager","_serverWSS","listen","prototype","_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","_id","findOneAndUpdate","status","$set","_b","callMethodInternal","apply","__spreadArray","method","params","result","WorkerTaskResponses","create","id_request","has_error","data","id_user","user","id_ws","err_1","updateOne","getActiveMonitorFunctions","setImmediate","ResolveIOServer","getMongoConnection","then","getIsWorkersEnabled","getIsWorkerInstance","getWS","Array","from","clients","filter","a","getWSList","forEach","ws","push","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","fullname","readonly","call","date","client","getClientName","objectIdHexString","createLoggedInUser","ping","duration","asMilliseconds","loggedInLatency","parseErrorFound","socketData","parse","e","readyState","OPEN","send","unsubscribeWS","messageRoute_1","some","includes","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","serverResMethod","shift","methodLatencyId","LogMethodLatencies","__v","date_start","date_end","latency_ms","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","Object","assign","err_3","getMongoManager","invalidateQueryCache","splice","map","indexOf","now","getTime","msg","pop","ws_1","messageRoute","callMethod","MethodResponses","findOne","$and","message_id","response","unsubscribeAll","removeAllListeners","getApp","getServerConfig"],"mappings":"wqDAAAA,Q,uDAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL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AKI,iBAAmB,CAAA,C,CAG3B,EAAG,CAAC,CACL,EAEOZ,oBAAAqE,UAAAgH,cAAP,SAAqB7C,GAChB/H,KAAK0B,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIb,KAAQ,aAAc,WAAY+G,EAAS,KAAGA,EAAc,SAAC,EAE9E/H,KAAK0B,qBAAqB4M,eAAevG,CAAE,EAC3CA,EAAGwG,mBAAkB,CAEtB,EAEOhP,oBAAAqE,UAAA4K,OAAP,WACC,OAAOxO,KAAK6D,IACb,EAEOtE,oBAAAqE,UAAA6K,gBAAP,WACC,OAAOzO,KAAKa,aACb,EACDtB,mBAAA,EAAC","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';\n\nimport { dateReviver, getBinarySize, deepCopy } from './util/common';\n\nimport { objectIdHexString } from './managers/mongo.manager';\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';\n\nimport { MethodResponses } from './collections/method-response.collection';\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 { ResolveIOServer } from './index';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\n\nexport default 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 _serverConfig;\n\tprivate _clientDir;\n\tprivate _offlineUpdates = [];\n\tprivate _msgQueue = [];\n\tprivate _msgQueueRunning = false;\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 _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tconstructor(mainServer, serverConfig, clientRoutes, clientDir, sesMail, standardProgram, publicProgram = false) {\n\t\tthis._serverConfig = serverConfig;\n\t\tthis._clientRoutes = clientRoutes;\n\t\tthis._clientDir = clientDir;\n\t\tthis.sesMail = sesMail;\n\t\tthis.standardProgram = standardProgram;\n\t\tthis.publicProgram = publicProgram;\n\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager(mainServer, serverConfig);\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Length', this._msgQueue.length);\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\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 - ' + this._serverConfig['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 - ' + this._serverConfig['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 - ' + this._serverConfig['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 - ' + this._serverConfig['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 - ' + this._serverConfig['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\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\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, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager(this);\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n this.startServerInstance(serverConfig);\n\t\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n this.startServerInstance(serverConfig);\n\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n this._cronManager = new CronManager(this);\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance(serverConfig) {\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 || serverConfig['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || serverConfig['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', serverConfig['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, serverConfig);\n\t\tsetupHealthRoutes(this._app, serverConfig);\n\n\t\tif (serverConfig['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, serverConfig);\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\n\t\t\t\tif (task) {\n\t\t\t\t\tconsole.log('Worker processing task:', task._id);\n\n\t\t\t\t\t// Update the task status to 'processing'\n\t\t\t\t\tlet req = await WorkerTaskRequests.findOneAndUpdate({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } });\n\n\t\t\t\t\tif (req) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Run the actual method\n\t\t\t\t\t\t\tconst result = await this._methodManager.callMethodInternal(task.method, ...task.params);\n\n\t\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\t\t\tdata: [result],\n\t\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\n\t\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\t\t\tdata: [err.message],\n\t\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Mark the task as complete\n\t\t\t\t\t\tawait WorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tchangeStream.close();\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000); // Restart after a delay\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); // Restart after a delay\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._msgQueue.length &&\n\t\t\t!this._msgQueueRunning &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\tprocess.exit(0);\n\t\t\t}, () => {process.exit(1)});\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._msgQueue.length, \n\t\t\t\t\tthis._msgQueueRunning,\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 getWS(id_ws: string) {\n\t\treturn Array.from(this._serverWSS.clients).filter(a => a['id_socket'] === id_ws)[0];\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\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 !== this._serverConfig['ROOT_URL'] && info.origin !== this._serverConfig['SEC_ROOT_URL'] && info.origin !== this._serverConfig['RESOLVEIO_URL'] && info.origin !== this._serverConfig['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, this._serverConfig['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' && this._serverConfig['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._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.ping(() => {});\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('pong', () => {\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t})\n\t\t\t.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 - ' + this._serverConfig['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 (socketData[0] === '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\n\t\t\t\t\tlet messageRoute = socketData[0];\n\n\t\t\t\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\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet messageDate = socketData[1];\n\t\t\t\t\tlet messageId = socketData[2]\n\t\t\t\t\tlet type = socketData[3]\n\n\t\t\t\t\tif (type === 'subscription') {\n\t\t\t\t\t\tlet subType = socketData[4];\n\t\t\t\t\t\tlet pub = socketData[5];\n\t\t\n\t\t\t\t\t\t// Subscribe\n\t\t\t\t\t\tif (subType === 'sub') {\n\t\t\t\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Unsubscribe\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send(JSON.stringify(serverRes), (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 Offline Ack Main');\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\n\t\t\t\t\t\tthis._offlineUpdates.push(ws);\n\t\t\t\t\t\tlet offlineUpdates = socketData[4];\n\n\t\t\t\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\t\t\t\tlet update = offlineUpdates[i];\n\t\t\t\t\t\t\tlet data = update.data;\n\n\t\t\t\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\t\t\t\tmessageId: update.data[2],\n\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(serverResMethod), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Offline Ack Each');\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\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\n\t\t\t\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\t\t\t\tlet updateDate = data.shift();\n\t\t\t\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\t\t\t\tlet updateType = data.shift();\n\t\t\t\t\t\t\tlet method = data.shift();\n\t\t\t\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t\t});\n\t\t\t\n\t\t\t\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\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t\t\t\t}\n\t\t\t\t\telse { //methods\n\t\t\t\t\t\tthis._msgQueue.splice(0, 0, {\n\t\t\t\t\t\t\tws: ws,\n\t\t\t\t\t\t\tdata: socketData\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.ping(() => {});\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.ping(() => {});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._msgQueueRunning) {\t\t\t\t\n\t\t\t\tif (this._msgQueue.length) {\n\t\t\t\t\tthis._msgQueueRunning = true;\n\t\t\t\t\tthis._debugMsgQueue += 1;\n\n\t\t\t\t\tlet msg = this._msgQueue.pop();\n\t\t\t\t\tlet data = msg.data;\n\t\t\t\t\tlet ws = msg.ws;\n\t\t\n\t\t\t\t\tlet messageRoute: string = data.shift();\n\t\t\t\t\tlet messageDate: Date = data.shift();\n\t\t\t\t\tlet messageId: number = data.shift();\n\t\t\t\t\tlet type: string = data.shift();\n\t\t\n\t\t\t\t\t// Method call\n\t\t\t\t\tif (type === 'method') {\n\t\t\t\t\t\tlet method = data.shift();\n\n\t\t\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\t\t\tLogMethodLatencies.create({\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\n\t\t\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\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send(JSON.stringify(serverRes), (error) => {\n\t\t\t\t\t\t\t\tif (error) {\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\tif (this._methodManager._methods[method]) {\n\t\t\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (type === 'methodResponse') {\n\t\t\t\t\t\tlet method = data.shift();\n\t\t\n\t\t\t\t\t\tMethodResponses.findOne({$and: [\n\t\t\t\t\t\t\t{id_user: ws['id_user']}, \n\t\t\t\t\t\t\t{message_id: messageId},\n\t\t\t\t\t\t\t{method: method},\n\t\t\t\t\t\t\t{date: messageDate}\n\t\t\t\t\t\t]}).then(res => {\n\t\t\t\t\t\t\tif (res) {\n\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\tws.send(JSON.stringify(res.response), (error) => {\n\t\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\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}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}, err => {});\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tthis._msgQueueRunning = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1);\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 this._serverConfig;\n\t}\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","mongo_manager_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","method_response_collection_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","index_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","ResolveIOMainServer","mainServer","serverConfig","clientRoutes","clientDir","sesMail","standardProgram","publicProgram","_this","this","_offlineUpdates","_msgQueue","_msgQueueRunning","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_serverConfig","_clientDir","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","length","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_methodManager","sendEmail","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","startServerInstance","SubscriptionManager","_serverWSS","listen","prototype","_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","_id","findOneAndUpdate","status","$set","_b","callMethodInternal","apply","__spreadArray","method","params","result","WorkerTaskResponses","create","id_request","has_error","data","id_user","user","id_ws","err_1","updateOne","getActiveMonitorFunctions","setImmediate","ResolveIOServer","getMongoConnection","then","getIsWorkersEnabled","getIsWorkerInstance","getWS","Array","from","clients","filter","a","getWSList","forEach","ws","push","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","fullname","readonly","call","date","client","getClientName","objectIdHexString","createLoggedInUser","ping","duration","asMilliseconds","loggedInLatency","parseErrorFound","socketData","parse","e","readyState","OPEN","send","unsubscribeWS","messageRoute_1","some","includes","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","serverResMethod","shift","methodLatencyId","LogMethodLatencies","__v","date_start","date_end","latency_ms","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","Object","assign","err_3","getMongoManager","invalidateQueryCache","splice","map","indexOf","now","getTime","msg","pop","ws_1","messageRoute","callMethod","MethodResponses","findOne","$and","message_id","response","unsubscribeAll","removeAllListeners","getApp","getServerConfig"],"mappings":"wqDAAAA,Q,uDAAAC,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,EAEAO,SAAAP,QAAA,eAAA,EAEAQ,gBAAAR,QAAA,0BAAA,EACAS,eAAAT,QAAA,yBAAA,EACAU,iBAAAV,QAAA,2BAAA,EACAW,uBAAAX,QAAA,iCAAA,EACAY,kBAAAZ,QAAA,4BAAA,EAIAa,6BAAAb,QAAA,0CAAA,EACAc,iBAAAd,QAAA,8BAAA,EACAe,gCAAAf,QAAA,6CAAA,EACAgB,kBAAAhB,QAAA,+BAAA,EAEAiB,OAAAjB,QAAA,aAAA,EACAkB,OAAAlB,QAAA,aAAA,EACAmB,SAAAnB,QAAA,eAAA,EACAoB,QAAApB,QAAA,SAAA,EACAqB,UAAArB,QAAA,SAAA,EACAsB,iCAAAtB,QAAA,8CAAA,EACAuB,kCAAAvB,QAAA,+CAAA,EAEAwB,oBAAA,WAoCC,SAAAA,oBAAYC,EAAYC,EAAcC,EAAcC,EAAWC,EAASC,EAAiBC,GAAA,KAAA,IAAAA,IAAAA,EAAA,CAAA,GAAzF,IAAAC,EAAAC,KA5BQA,KAAAC,gBAAkB,GAClBD,KAAAE,UAAY,GACZF,KAAAG,iBAAmB,CAAA,EACpBH,KAAAJ,QAAU,CAAA,EACTI,KAAAH,gBAAkB,CAAA,EAClBG,KAAAF,cAAgB,CAAA,EAChBE,KAAAI,YAAc,CAAA,EAEdJ,KAAAK,OAAS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,gBAAgBC,QAAQ,CAACC,KAAM,CAC9B,CAACxH,QAASmH,EAAY,OAAC,EACvB,CAACM,WAAY9C,CAAS,EACtB,CAACnF,OAAQA,CAAM,EACf,CAACyD,KAAMyB,CAAW,EAClB,CAAC,EAAEjE,KAAK,SAAAxC,GACJA,GACCkJ,GAAMA,EAAGrD,aAAeqD,EAAGpD,MAC9BoD,EAAGnD,KAAKlI,KAAKC,UAAUkC,EAAIyJ,QAAQ,EAAG,SAACrM,GAClCA,GACHjC,EAAK6K,cAAckD,CAAE,CAEvB,CAAC,CAGJ,EAAG,SAAAzE,IAAS,GAGbtJ,EAAKI,iBAAmB,CAAA,C,CAG3B,EAAG,CAAC,CACL,EAEOZ,oBAAAqE,UAAAgH,cAAP,SAAqB7C,GAChB/H,KAAK0B,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIb,KAAQ,aAAc,WAAY+G,EAAS,KAAGA,EAAc,SAAC,EAE9E/H,KAAK0B,qBAAqB4M,eAAevG,CAAE,EAC3CA,EAAGwG,mBAAkB,CAEtB,EAEOhP,oBAAAqE,UAAA4K,OAAP,WACC,OAAOxO,KAAK6D,IACb,EAEOtE,oBAAAqE,UAAA6K,gBAAP,WACC,OAAOzO,KAAKa,aACb,EACDtB,mBAAA,EAAC","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';\n\nimport { dateReviver, getBinarySize, deepCopy } from './util/common';\n\nimport { objectIdHexString } from './managers/mongo.manager';\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';\n\nimport { MethodResponses } from './collections/method-response.collection';\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 { ResolveIOServer } from './index';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\n\nexport default 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 _serverConfig;\n\tprivate _clientDir;\n\tprivate _offlineUpdates = [];\n\tprivate _msgQueue = [];\n\tprivate _msgQueueRunning = false;\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 _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tconstructor(mainServer, serverConfig, clientRoutes, clientDir, sesMail, standardProgram, publicProgram = false) {\n\t\tthis._serverConfig = serverConfig;\n\t\tthis._clientRoutes = clientRoutes;\n\t\tthis._clientDir = clientDir;\n\t\tthis.sesMail = sesMail;\n\t\tthis.standardProgram = standardProgram;\n\t\tthis.publicProgram = publicProgram;\n\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager(mainServer, serverConfig);\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Length', this._msgQueue.length);\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\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 - ' + this._serverConfig['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 - ' + this._serverConfig['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 - ' + this._serverConfig['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 - ' + this._serverConfig['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 - ' + this._serverConfig['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\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\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, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager(this);\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n this.startServerInstance(serverConfig);\n\t\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n this.startServerInstance(serverConfig);\n\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n this._cronManager = new CronManager(this);\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance(serverConfig) {\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 || serverConfig['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || serverConfig['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', serverConfig['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, serverConfig);\n\t\tsetupHealthRoutes(this._app, serverConfig);\n\n\t\tif (serverConfig['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, serverConfig);\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\n\t\t\t\tif (task) {\n\t\t\t\t\tconsole.log('Worker processing task:', task._id);\n\n\t\t\t\t\t// Update the task status to 'processing'\n\t\t\t\t\tlet req = await WorkerTaskRequests.findOneAndUpdate({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } });\n\n\t\t\t\t\tif (req) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Run the actual method\n\t\t\t\t\t\t\tconst result = await this._methodManager.callMethodInternal(task.method, ...task.params);\n\n\t\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\t\t\tdata: [result],\n\t\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\n\t\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\t\t\tdata: [err.message],\n\t\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Mark the task as complete\n\t\t\t\t\t\tawait WorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tchangeStream.close();\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000); // Restart after a delay\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); // Restart after a delay\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._msgQueue.length &&\n\t\t\t!this._msgQueueRunning &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\tprocess.exit(0);\n\t\t\t}, () => {process.exit(1)});\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._msgQueue.length, \n\t\t\t\t\tthis._msgQueueRunning,\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 getWS(id_ws: string) {\n\t\treturn Array.from(this._serverWSS.clients).filter(a => a['id_socket'] === id_ws)[0];\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\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 !== this._serverConfig['ROOT_URL'] && info.origin !== this._serverConfig['SEC_ROOT_URL'] && info.origin !== this._serverConfig['RESOLVEIO_URL'] && info.origin !== this._serverConfig['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, this._serverConfig['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' && this._serverConfig['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._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.ping(() => {});\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('pong', () => {\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t})\n\t\t\t.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 - ' + this._serverConfig['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 (socketData[0] === '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\n\t\t\t\t\tlet messageRoute = socketData[0];\n\n\t\t\t\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\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet messageDate = socketData[1];\n\t\t\t\t\tlet messageId = socketData[2]\n\t\t\t\t\tlet type = socketData[3]\n\n\t\t\t\t\tif (type === 'subscription') {\n\t\t\t\t\t\tlet subType = socketData[4];\n\t\t\t\t\t\tlet pub = socketData[5];\n\t\t\n\t\t\t\t\t\t// Subscribe\n\t\t\t\t\t\tif (subType === 'sub') {\n\t\t\t\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Unsubscribe\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send(JSON.stringify(serverRes), (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 Offline Ack Main');\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\n\t\t\t\t\t\tthis._offlineUpdates.push(ws);\n\t\t\t\t\t\tlet offlineUpdates = socketData[4];\n\n\t\t\t\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\t\t\t\tlet update = offlineUpdates[i];\n\t\t\t\t\t\t\tlet data = update.data;\n\n\t\t\t\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\t\t\t\tmessageId: update.data[2],\n\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(serverResMethod), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Offline Ack Each');\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\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\n\t\t\t\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\t\t\t\tlet updateDate = data.shift();\n\t\t\t\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\t\t\t\tlet updateType = data.shift();\n\t\t\t\t\t\t\tlet method = data.shift();\n\t\t\t\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t\t});\n\t\t\t\n\t\t\t\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\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t\t\t\t}\n\t\t\t\t\telse { //methods\n\t\t\t\t\t\tthis._msgQueue.splice(0, 0, {\n\t\t\t\t\t\t\tws: ws,\n\t\t\t\t\t\t\tdata: socketData\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.ping(() => {});\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.ping(() => {});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._msgQueueRunning) {\t\t\t\t\n\t\t\t\tif (this._msgQueue.length) {\n\t\t\t\t\tthis._msgQueueRunning = true;\n\t\t\t\t\tthis._debugMsgQueue += 1;\n\n\t\t\t\t\tlet msg = this._msgQueue.pop();\n\t\t\t\t\tlet data = msg.data;\n\t\t\t\t\tlet ws = msg.ws;\n\t\t\n\t\t\t\t\tlet messageRoute: string = data.shift();\n\t\t\t\t\tlet messageDate: Date = data.shift();\n\t\t\t\t\tlet messageId: number = data.shift();\n\t\t\t\t\tlet type: string = data.shift();\n\t\t\n\t\t\t\t\t// Method call\n\t\t\t\t\tif (type === 'method') {\n\t\t\t\t\t\tlet method = data.shift();\n\n\t\t\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\t\t\tLogMethodLatencies.create({\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\n\t\t\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\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send(JSON.stringify(serverRes), (error) => {\n\t\t\t\t\t\t\t\tif (error) {\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\tif (this._methodManager._methods[method]) {\n\t\t\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (type === 'methodResponse') {\n\t\t\t\t\t\tlet method = data.shift();\n\t\t\n\t\t\t\t\t\tMethodResponses.findOne({$and: [\n\t\t\t\t\t\t\t{id_user: ws['id_user']}, \n\t\t\t\t\t\t\t{message_id: messageId},\n\t\t\t\t\t\t\t{method: method},\n\t\t\t\t\t\t\t{date: messageDate}\n\t\t\t\t\t\t]}).then(res => {\n\t\t\t\t\t\t\tif (res) {\n\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\tws.send(JSON.stringify(res.response), (error) => {\n\t\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\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}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}, err => {});\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tthis._msgQueueRunning = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1);\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 this._serverConfig;\n\t}\n}"]}
|