@resolveio/server-lib 20.6.26 → 20.6.28
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.
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,i){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var i,s,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;l=c&&t[c=0]?0:l;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return l.label++,{value:t[1],done:!1};case 5:l.label++,s=t[1],t=[0];continue;case 7:t=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){l=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))l.label=t[1];else if(6===t[0]&&l.label<a[1])l.label=a[1],a=t;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(t)}}t=n.call(o,l)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)s.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),client_s3_1=require("@aws-sdk/client-s3"),flag_updates_1=require("../methods/flag-updates"),resolveio_server_app_1=require("../resolveio-server-app"),AWS=function(){function AWS(){this._s3=null,this._s3USEast1=null}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,r){var o=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugcallMethodHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this.clientDir="",this.serverConfig="",this._websocketManager=resolveio_server_app_1.ResolveIOServer.getMainServer().getWebSocketManager(),this._monitorManagerFunction=e,this._isWorkersEnabled=t,this._isWorkerInstance=r,this.clientDir=resolveio_server_app_1.ResolveIOServer.getClientDir(),this.serverConfig=resolveio_server_app_1.ResolveIOServer.getServerConfig(),"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS,resolveio_server_app_1.ResolveIOServer.getSESMail()?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_HOST,port:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PORT,secure:!1,auth:{user:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_USERNAME,pass:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",o._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",o._debugcallMethodHits),console.log(new Date,"Method Manager","Call Method Hits",o._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",o._debugCallMethodCronJobHits)),o._debugcallMethodHits=0,o._debugCallMethodHits=0,o._debugCallMethodCronJobHits=0,o._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}return MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,r=this,o=[],n=1;n<arguments.length;n++)o[n-1]=arguments[n];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var l=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o);return(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(o),!1)).then(function(e){return r._monitorManagerFunction.finishMonitorFunction(l),e},function(e){return r._monitorManagerFunction.finishMonitorFunction(l),r.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(t){for(var e,r=this,o=[],n=1;n<arguments.length;n++)o[n-1]=arguments[n];if(this._debugcallMethodHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com"}));var i="function"==typeof o[o.length-1]?o.slice(0,-1):o,s=null,a=this._monitorManagerFunction.startMonitorFunction("Method",t,this.user||"","",i),s=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(i),!1)).then(function(e){return r._monitorManagerFunction.finishMonitorFunction(a),e},function(e){throw r._monitorManagerFunction.finishMonitorFunction(a),r.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethod)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e});return o[o.length-1]&&"function"==typeof o[o.length-1]&&s.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),s},MethodManager.prototype.sendWS=function(e,t,r,o,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:"",client:"ResolveIO",instance:"backend.resolveio.com"}))},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){switch(e.label){case 0:return(t=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){o.setupEmailWatcher()}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,n,i,s;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),o=r.next();!o.done;o=r.next())n=o.value,this.emailQueue.add(n._id.toString())}catch(e){i={error:e}}finally{try{o&&!o.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,_,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,7]),t=function(){var o,t,r,n,i,s,a,l,c,u;return __generator(this,function(e){switch(e.label){case 0:return i=_.emailQueue.values().next().value,_.emailQueue.delete(i),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:i,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(o=e.sent()))return[2,"continue"];if(!(o.attachments&&0<o.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),c=void 0,t=__values(o.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(n=r.value).path&&n.path.startsWith("http")?[4,fetch(n.path)]:[3,7];case 5:if((i=e.sent()).ok)return[4,i.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(n.path));case 6:s=e.sent(),s=Buffer.from(s),s.length<=20971520&&(n.content=s,delete n.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return s=e.sent(),c={error:s},[3,11];case 10:try{r&&!r.done&&(u=t.return)&&u.call(t)}finally{if(c)throw c.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof a?a:_.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(l={replyTo:o.reply_to||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_REPLY_TO||void 0,from:o.send_from||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_FROM,to:o.email,subject:(resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)||resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+o.subject,text:"string"==typeof o.text?o.text:"",html:"string"==typeof o.html?o.html:"",attachments:o.attachments||[]}).attachments&&0<l.attachments.length&&(l.attachments=l.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),[4,new Promise(function(r){h._mailer.sendMail(l,function(t,e){return __awaiter(h,void 0,void 0,function(){return __generator(this,function(e){try{t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})):"dev@resolveio.com"===o.email?email_history_collection_1.EmailHistories.deleteOne({_id:o._id}):email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}})}catch(e){console.error("Error in sendMail callback:",e),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof e?e:this.safeStringify(e),completedAt:new Date}})}finally{r()}return[2]})})})})];case 15:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 16:return e.sent(),[2]}})},_=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,7];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(n,i,s,a,l,c,u,_){var e=this;return void 0===_&&(_=!1),new Promise(function(r,o){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(n=!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)&&!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||n.match(/\@resolveio\.com/)?n:"dev@resolveio.com")?"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||_?(l=l||[],l=(l=Array.isArray(l)?l:[l]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:n,subject:i||"",text:s||"",html:a||"",attachments:l||[],send_from:c||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),o(e)})):(console.log("Send email",n,i,s,a,l,c),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8",function(e,t){e?o(e):r(t)})})},MethodManager.prototype.readImage=function(e){return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"base64",function(e,t){e?o(e):r(t)})})},MethodManager}());exports.MethodManager=MethodManager;
|
|
1
|
+
"use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,i){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var i,s,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;l=c&&t[c=0]?0:l;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return l.label++,{value:t[1],done:!1};case 5:l.label++,s=t[1],t=[0];continue;case 7:t=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){l=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))l.label=t[1];else if(6===t[0]&&l.label<a[1])l.label=a[1],a=t;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(t)}}t=n.call(o,l)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)s.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),client_s3_1=require("@aws-sdk/client-s3"),flag_updates_1=require("../methods/flag-updates"),resolveio_server_app_1=require("../resolveio-server-app"),AWS=function(){function AWS(){this._s3=null,this._s3USEast1=null}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,r){var o=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugcallMethodHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this.clientDir="",this.serverConfig="",this._websocketManager=resolveio_server_app_1.ResolveIOServer.getMainServer().getWebSocketManager(),this._monitorManagerFunction=e,this._isWorkersEnabled=t,this._isWorkerInstance=r,this.clientDir=resolveio_server_app_1.ResolveIOServer.getClientDir(),this.serverConfig=resolveio_server_app_1.ResolveIOServer.getServerConfig(),"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS,resolveio_server_app_1.ResolveIOServer.getSESMail()?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_HOST,port:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PORT,secure:!1,auth:{user:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_USERNAME,pass:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",o._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",o._debugcallMethodHits),console.log(new Date,"Method Manager","Call Method Hits",o._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",o._debugCallMethodCronJobHits)),o._debugcallMethodHits=0,o._debugCallMethodHits=0,o._debugCallMethodCronJobHits=0,o._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}return MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,r=this,o=[],n=1;n<arguments.length;n++)o[n-1]=arguments[n];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var l=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o);return(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(o),!1)).then(function(e){return r._monitorManagerFunction.finishMonitorFunction(l),e},function(e){throw r._monitorManagerFunction.finishMonitorFunction(l),r.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(t){for(var e,r=this,o=[],n=1;n<arguments.length;n++)o[n-1]=arguments[n];if(this._debugcallMethodHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com"}));var i="function"==typeof o[o.length-1]?o.slice(0,-1):o,s=null,a=this._monitorManagerFunction.startMonitorFunction("Method",t,this.user||"","",i),s=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(i),!1)).then(function(e){return r._monitorManagerFunction.finishMonitorFunction(a),e},function(e){throw r._monitorManagerFunction.finishMonitorFunction(a),r.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethod)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e});return o[o.length-1]&&"function"==typeof o[o.length-1]&&s.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),s},MethodManager.prototype.sendWS=function(e,t,r,o,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:"",client:"ResolveIO",instance:"backend.resolveio.com"}))},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){switch(e.label){case 0:return(t=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){o.setupEmailWatcher()}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,n,i,s;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),o=r.next();!o.done;o=r.next())n=o.value,this.emailQueue.add(n._id.toString())}catch(e){i={error:e}}finally{try{o&&!o.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,_,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,7]),t=function(){var o,t,r,n,i,s,a,l,c,u;return __generator(this,function(e){switch(e.label){case 0:return i=_.emailQueue.values().next().value,_.emailQueue.delete(i),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:i,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(o=e.sent()))return[2,"continue"];if(!(o.attachments&&0<o.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),c=void 0,t=__values(o.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(n=r.value).path&&n.path.startsWith("http")?[4,fetch(n.path)]:[3,7];case 5:if((i=e.sent()).ok)return[4,i.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(n.path));case 6:s=e.sent(),s=Buffer.from(s),s.length<=20971520&&(n.content=s,delete n.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return s=e.sent(),c={error:s},[3,11];case 10:try{r&&!r.done&&(u=t.return)&&u.call(t)}finally{if(c)throw c.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof a?a:_.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(l={replyTo:o.reply_to||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_REPLY_TO||void 0,from:o.send_from||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_FROM,to:o.email,subject:(resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)||resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+o.subject,text:"string"==typeof o.text?o.text:"",html:"string"==typeof o.html?o.html:"",attachments:o.attachments||[]}).attachments&&0<l.attachments.length&&(l.attachments=l.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),[4,new Promise(function(r){h._mailer.sendMail(l,function(t,e){return __awaiter(h,void 0,void 0,function(){return __generator(this,function(e){try{t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})):"dev@resolveio.com"===o.email?email_history_collection_1.EmailHistories.deleteOne({_id:o._id}):email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}})}catch(e){console.error("Error in sendMail callback:",e),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof e?e:this.safeStringify(e),completedAt:new Date}})}finally{r()}return[2]})})})})];case 15:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 16:return e.sent(),[2]}})},_=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,7];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(n,i,s,a,l,c,u,_){var e=this;return void 0===_&&(_=!1),new Promise(function(r,o){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(n=!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)&&!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||n.match(/\@resolveio\.com/)?n:"dev@resolveio.com")?"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||_?(l=l||[],l=(l=Array.isArray(l)?l:[l]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:n,subject:i||"",text:s||"",html:a||"",attachments:l||[],send_from:c||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),o(e)})):(console.log("Send email",n,i,s,a,l,c),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8",function(e,t){e?o(e):r(t)})})},MethodManager.prototype.readImage=function(e){return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"base64",function(e,t){e?o(e):r(t)})})},MethodManager}());exports.MethodManager=MethodManager;
|
|
2
2
|
//# sourceMappingURL=method.manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","common_1","log_collection_1","report_builder_1","support_1","monitor_1","email_history_collection_1","client_s3_1","flag_updates_1","resolveio_server_app_1","AWS","this","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugcallMethodHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","clientDir","serverConfig","_websocketManager","ResolveIOServer","getMainServer","getWebSocketManager","_monitorManagerFunction","getClientDir","getServerConfig","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","console","log","Date","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","getSESMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","setupEmailWatcher","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","skipValidation","check","error","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","i","validate","errors","JSON","stringify","monitor","startMonitorFunction","_a","function","call","apply","__spreadArray","id_user","id_ws","__read","then","res","finishMonitorFunction","methodErrs","callMethod","getLocalLogManager","writeLog","type","data","_id","objectIdHexString","createdAt","collection","id_document","payload","getBinarySize","messageId","route","Logs","insertOne","client","instance","functionMethodData","slice","promise","err","sendWS","ws","messageDate","send","changeStream","EmailHistories","watchCollection","on","change","__awaiter","operationType","fullDocument","status","add","toString","tryProcessEmail","updatedEmail","has","delete","close","loadPendingEmails","sent","find","sort","pendingEmails","_b","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","$set","processingAt","emailHistory","_e","attachments","e_2","_c","att","startsWith","fetch","response","ok","arrayBuffer","Error","concat","buffer","Buffer","from","content","err_2","updateOne","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","Promise","resolve","sendMail","info","deleteOne","err_1","obj","getCircularReplacer","e","message","seen","WeakSet","key","sendTo","local_override","reject","Array","isArray","isBuffer","__v","date","history","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"ihFACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAA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gBI,aAAY,EAAK,aAAe4M,CAAS,CAAC,GACrFtQ,GAAGqQ,SAAStQ,KAAKyQ,KAAKxP,uBAAAsC,gBAAgBI,aAAY,EAAK,aAAe4M,CAAS,EAAG,QAAS,SAACvG,EAAKxB,GAC5FwB,EACH8F,EAAO9F,CAAG,EAGVgF,EAAQxG,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEOpG,cAAAd,UAAAqP,UAAP,SAAiBJ,GAChB,OAAO,IAAIxB,QAAQ,SAACC,EAASc,GACxB7P,GAAGuQ,WAAWxQ,KAAKyQ,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEtQ,GAAGqQ,SAAStQ,KAAKyQ,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAACvG,EAAKxB,GACzEwB,EACH8F,EAAO9F,CAAG,EAGVgF,EAAQxG,CAAG,CAEb,CAAC,EAGGvI,GAAGuQ,WAAWxQ,KAAKyQ,KAAKxP,uBAAAsC,gBAAgBI,aAAY,EAAK,aAAe4M,CAAS,CAAC,GACrFtQ,GAAGqQ,SAAStQ,KAAKyQ,KAAKxP,uBAAAsC,gBAAgBI,aAAY,EAAK,aAAe4M,CAAS,EAAG,SAAU,SAACvG,EAAKxB,GAC7FwB,EACH8F,EAAO9F,CAAG,EAGVgF,EAAQxG,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDpG,aAAA,EAAC,GA7sBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { getBinarySize, objectIdHexString } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { EmailHistoryModel } from '../models/email-history.model';\nimport { ResolveIOServer } from '../resolveio-server-app';\n\nexport class AWS {\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor() {\n\n\t}\n\n\tpublic s3(): S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1(): S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _debugcallMethodHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tpublic clientDir = '';\n\tpublic serverConfig = '';\n\n\tconstructor(monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._websocketManager = ResolveIOServer.getMainServer().getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\tthis.clientDir = ResolveIOServer.getClientDir();\n\t\tthis.serverConfig = ResolveIOServer.getServerConfig();\n\n\t\t// Fixtures\n\t\tif (process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tloadServerInit();\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadFlagUpdatesMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS();\n\n\t\tif (ResolveIOServer.getSESMail()) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: ResolveIOServer.getServerConfig()['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: ResolveIOServer.getServerConfig()['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: ResolveIOServer.getServerConfig()['MAIL_USERNAME'],\n\t\t\t\t\tpass: ResolveIOServer.getServerConfig()['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (ResolveIOServer.getMainServer().getSubscriptionManager() && ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugcallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugcallMethodHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tthis.setupEmailWatcher();\n\t\t}\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\treturn methodErrs;\n\t\t});\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethod(method: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugcallMethodHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution' && method !== 'incCounter' && method !== 'supportCreateBillingUser' && method !== 'countCollectionWithQuery') {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\ttype: 'log',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\troute: ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\tmethod: method,\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\tmessageId: 0,\n\t\t\t\t\troute: '',\n\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\t\tlet promise = null;\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, this['user'] || '', '', functionMethodData);\n\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t},\n\t\t\tmethodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\tthrow methodErrs;\n\t\t\t}\n\t\t);\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\n\t\tif (\n\t\t\tmethod !== 'reportBuilderGetResults' &&\n\t\t\tmethod !== 'reportBuilderGetDistinctValue' &&\n\t\t\tmethod !== 'reportBuilderBuildTree' &&\n\t\t\tmethod !== 'generatePDF' &&\n\t\t\tmethod !== 'getWOOfflineData' &&\n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'countCollectionWithQuery' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'uploadFileAndSave' &&\n\t\t\tmethod !== 'getDrivers' &&\n\t\t\tmethod !== 'processAirdropDistribution'\n\t\t) {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\ttype: 'log',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload:\n\t\t\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t\t\t: 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: data.messageId,\n\t\t\t\t\t\troute: ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload:\n\t\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t\t: 'Too Big',\n\t\t\t\t\tmethod: method,\n\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\tmessageId: data.messageId,\n\t\t\t\t\troute: '',\n\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// MethodResponses.create({\n\t\t// \t_id: objectIdHexString(),\n\t\t// \t__v: 0,\n\t\t// \tid_user: ws['id_user'] || '',\n\t\t// \tmessage_id: data.messageId,\n\t\t// \tresponse: getBinarySize(JSON.stringify(data)) < 200000 ? data : { error: 'Too Big' },\n\t\t// \tmethod: method,\n\t\t// \tdate: messageDate\n\t\t// });\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tchangeStream.close();\n\t\t})\n\t\t.on('close', () => {\n\t\t\tthis.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tthis.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// Fetch and process attachments\n\t\t\t\tif (emailHistory.attachments && emailHistory.attachments.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (let att of emailHistory.attachments) {\n\t\t\t\t\t\t\tif (att.path && att.path.startsWith('http')) {\n\t\t\t\t\t\t\t\tconst response = await fetch(att.path);\n\t\t\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Failed to fetch attachment: ${att.path}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t\t\t\t\tconst buffer = Buffer.from(arrayBuffer);\n\t\n\t\t\t\t\t\t\t\t// Check the size of the attachment\n\t\t\t\t\t\t\t\tconst maxSize = 20 * 1024 * 1024; // 20MB in bytes\n\t\t\t\t\t\t\t\tif (buffer.length <= maxSize) {\n\t\t\t\t\t\t\t\t\t// Attachment is within size limits, include it\n\t\t\t\t\t\t\t\t\tatt.content = buffer;\n\t\t\t\t\t\t\t\t\tdelete att.path;\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\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Failed to fetch attachment:', err);\n\t\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\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\t// Skip to the next email\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (ResolveIOServer.getServerConfig()['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || ResolveIOServer.getServerConfig().MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./)\n\t\t\t\t\t\t\t? '(DEV SERVER) - '\n\t\t\t\t\t\t\t: '') + emailHistory.subject,\n\t\t\t\t\ttext: typeof emailHistory.text === 'string' ? emailHistory.text : '',\n\t\t\t\t\thtml: typeof emailHistory.html === 'string' ? emailHistory.html : '',\n\t\t\t\t\tattachments: emailHistory.attachments || [],\n\t\t\t\t};\n\t\n\t\t\t\t// Process attachments before sending\n\t\t\t\tif (mailOptions.attachments && mailOptions.attachments.length > 0) {\n\t\t\t\t\tmailOptions.attachments = mailOptions.attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\t// Handle attachments stored as BinData or Buffer\n\t\t\t\t\t\tif (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {\n\t\t\t\t\t\t\t// Convert MongoDB's Binary data to Buffer\n\t\t\t\t\t\t\tif (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content.buffer);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Handle other types if necessary\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Handle attachments stored as Base64 strings\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content, 'base64');\n\t\t\t\t\t\t\tdelete newAtt.encoding;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Ensure the content is a Buffer\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\t// Send the email\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tthis._mailer.sendMail(mailOptions, async (err, info) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\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\telse {\n\t\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\t\tEmailHistories.deleteOne({ _id: emailHistory._id });\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\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t\t},\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}\n\t\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\terror: typeof error === 'string' ? error : this.safeStringify(error),\n\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\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} finally {\n\t\t\t\t\t\t\tresolve(); // Continue processing the queue\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\n\t\t\t\t// Wait for at least one second before sending the next email\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// Modify sendTo in development environments\n\t\t\tif (\n\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t\t) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\t\n\t\t\tif (sendTo) {\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\t\tlocal_override\n\t\t\t\t) {\n\t\t\t\t\tif (!attachments) {\n\t\t\t\t\t\tattachments = [];\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\t\tattachments = [attachments];\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// Process attachments before saving\n\t\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\n\t\t\t\t\t// Queue the email in MongoDB\n\t\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\t\ttext: text || '',\n\t\t\t\t\t\thtml: html || '',\n\t\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t\terror: ''\n\t\t\t\t\t};\n\t\n\t\t\t\t\tEmailHistories.insertOne(emailHistory).then(\n\t\t\t\t\t\t(history) => resolve(history),\n\t\t\t\t\t\t(err) => {\n\t\t\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t'Send email',\n\t\t\t\t\t\tsendTo,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\thtml,\n\t\t\t\t\t\tattachments,\n\t\t\t\t\t\tsend_from\n\t\t\t\t\t);\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\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\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\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}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","common_1","log_collection_1","report_builder_1","support_1","monitor_1","email_history_collection_1","client_s3_1","flag_updates_1","resolveio_server_app_1","AWS","this","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugcallMethodHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","clientDir","serverConfig","_websocketManager","ResolveIOServer","getMainServer","getWebSocketManager","_monitorManagerFunction","getClientDir","getServerConfig","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","console","log","Date","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","getSESMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","setupEmailWatcher","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","skipValidation","check","error","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","i","validate","errors","JSON","stringify","monitor","startMonitorFunction","_a","function","call","apply","__spreadArray","id_user","id_ws","__read","then","res","finishMonitorFunction","methodErrs","callMethod","getLocalLogManager","writeLog","type","data","_id","objectIdHexString","createdAt","collection","id_document","payload","getBinarySize","messageId","route","Logs","insertOne","client","instance","functionMethodData","slice","promise","err","sendWS","ws","messageDate","send","changeStream","EmailHistories","watchCollection","on","change","__awaiter","operationType","fullDocument","status","add","toString","tryProcessEmail","updatedEmail","has","delete","close","loadPendingEmails","sent","find","sort","pendingEmails","_b","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","$set","processingAt","emailHistory","_e","attachments","e_2","_c","att","startsWith","fetch","response","ok","arrayBuffer","Error","concat","buffer","Buffer","from","content","err_2","updateOne","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","Promise","resolve","sendMail","info","deleteOne","err_1","obj","getCircularReplacer","e","message","seen","WeakSet","key","sendTo","local_override","reject","Array","isArray","isBuffer","__v","date","history","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"ihFACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,SAAAd,QAAA,gBAAA,EACAe,iBAAAf,QAAA,+BAAA,EACAgB,iB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,GAAGqQ,SAAStQ,KAAKyQ,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAACvG,EAAKxB,GACzEwB,EACH8F,EAAO9F,CAAG,EAGVgF,EAAQxG,CAAG,CAEb,CAAC,EAGGvI,GAAGuQ,WAAWxQ,KAAKyQ,KAAKxP,uBAAAsC,gBAAgBI,aAAY,EAAK,aAAe4M,CAAS,CAAC,GACrFtQ,GAAGqQ,SAAStQ,KAAKyQ,KAAKxP,uBAAAsC,gBAAgBI,aAAY,EAAK,aAAe4M,CAAS,EAAG,SAAU,SAACvG,EAAKxB,GAC7FwB,EACH8F,EAAO9F,CAAG,EAGVgF,EAAQxG,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDpG,aAAA,EAAC,GA7sBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { getBinarySize, objectIdHexString } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { EmailHistoryModel } from '../models/email-history.model';\nimport { ResolveIOServer } from '../resolveio-server-app';\n\nexport class AWS {\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor() {\n\n\t}\n\n\tpublic s3(): S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1(): S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _debugcallMethodHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tpublic clientDir = '';\n\tpublic serverConfig = '';\n\n\tconstructor(monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._websocketManager = ResolveIOServer.getMainServer().getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\tthis.clientDir = ResolveIOServer.getClientDir();\n\t\tthis.serverConfig = ResolveIOServer.getServerConfig();\n\n\t\t// Fixtures\n\t\tif (process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tloadServerInit();\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadFlagUpdatesMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS();\n\n\t\tif (ResolveIOServer.getSESMail()) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: ResolveIOServer.getServerConfig()['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: ResolveIOServer.getServerConfig()['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: ResolveIOServer.getServerConfig()['MAIL_USERNAME'],\n\t\t\t\t\tpass: ResolveIOServer.getServerConfig()['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (ResolveIOServer.getMainServer().getSubscriptionManager() && ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugcallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugcallMethodHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tthis.setupEmailWatcher();\n\t\t}\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\tthrow methodErrs;\n\t\t});\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethod(method: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugcallMethodHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution' && method !== 'incCounter' && method !== 'supportCreateBillingUser' && method !== 'countCollectionWithQuery') {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\ttype: 'log',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\troute: ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\tmethod: method,\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\tmessageId: 0,\n\t\t\t\t\troute: '',\n\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\t\tlet promise = null;\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, this['user'] || '', '', functionMethodData);\n\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t},\n\t\t\tmethodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\tthrow methodErrs;\n\t\t\t}\n\t\t);\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\n\t\tif (\n\t\t\tmethod !== 'reportBuilderGetResults' &&\n\t\t\tmethod !== 'reportBuilderGetDistinctValue' &&\n\t\t\tmethod !== 'reportBuilderBuildTree' &&\n\t\t\tmethod !== 'generatePDF' &&\n\t\t\tmethod !== 'getWOOfflineData' &&\n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'countCollectionWithQuery' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'uploadFileAndSave' &&\n\t\t\tmethod !== 'getDrivers' &&\n\t\t\tmethod !== 'processAirdropDistribution'\n\t\t) {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\ttype: 'log',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload:\n\t\t\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t\t\t: 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: data.messageId,\n\t\t\t\t\t\troute: ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload:\n\t\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t\t: 'Too Big',\n\t\t\t\t\tmethod: method,\n\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\tmessageId: data.messageId,\n\t\t\t\t\troute: '',\n\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// MethodResponses.create({\n\t\t// \t_id: objectIdHexString(),\n\t\t// \t__v: 0,\n\t\t// \tid_user: ws['id_user'] || '',\n\t\t// \tmessage_id: data.messageId,\n\t\t// \tresponse: getBinarySize(JSON.stringify(data)) < 200000 ? data : { error: 'Too Big' },\n\t\t// \tmethod: method,\n\t\t// \tdate: messageDate\n\t\t// });\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tchangeStream.close();\n\t\t})\n\t\t.on('close', () => {\n\t\t\tthis.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tthis.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// Fetch and process attachments\n\t\t\t\tif (emailHistory.attachments && emailHistory.attachments.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (let att of emailHistory.attachments) {\n\t\t\t\t\t\t\tif (att.path && att.path.startsWith('http')) {\n\t\t\t\t\t\t\t\tconst response = await fetch(att.path);\n\t\t\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Failed to fetch attachment: ${att.path}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t\t\t\t\tconst buffer = Buffer.from(arrayBuffer);\n\t\n\t\t\t\t\t\t\t\t// Check the size of the attachment\n\t\t\t\t\t\t\t\tconst maxSize = 20 * 1024 * 1024; // 20MB in bytes\n\t\t\t\t\t\t\t\tif (buffer.length <= maxSize) {\n\t\t\t\t\t\t\t\t\t// Attachment is within size limits, include it\n\t\t\t\t\t\t\t\t\tatt.content = buffer;\n\t\t\t\t\t\t\t\t\tdelete att.path;\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\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Failed to fetch attachment:', err);\n\t\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\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\t// Skip to the next email\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (ResolveIOServer.getServerConfig()['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || ResolveIOServer.getServerConfig().MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./)\n\t\t\t\t\t\t\t? '(DEV SERVER) - '\n\t\t\t\t\t\t\t: '') + emailHistory.subject,\n\t\t\t\t\ttext: typeof emailHistory.text === 'string' ? emailHistory.text : '',\n\t\t\t\t\thtml: typeof emailHistory.html === 'string' ? emailHistory.html : '',\n\t\t\t\t\tattachments: emailHistory.attachments || [],\n\t\t\t\t};\n\t\n\t\t\t\t// Process attachments before sending\n\t\t\t\tif (mailOptions.attachments && mailOptions.attachments.length > 0) {\n\t\t\t\t\tmailOptions.attachments = mailOptions.attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\t// Handle attachments stored as BinData or Buffer\n\t\t\t\t\t\tif (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {\n\t\t\t\t\t\t\t// Convert MongoDB's Binary data to Buffer\n\t\t\t\t\t\t\tif (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content.buffer);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Handle other types if necessary\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Handle attachments stored as Base64 strings\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content, 'base64');\n\t\t\t\t\t\t\tdelete newAtt.encoding;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Ensure the content is a Buffer\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\t// Send the email\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tthis._mailer.sendMail(mailOptions, async (err, info) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\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\telse {\n\t\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\t\tEmailHistories.deleteOne({ _id: emailHistory._id });\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\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t\t},\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}\n\t\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\terror: typeof error === 'string' ? error : this.safeStringify(error),\n\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\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} finally {\n\t\t\t\t\t\t\tresolve(); // Continue processing the queue\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\n\t\t\t\t// Wait for at least one second before sending the next email\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// Modify sendTo in development environments\n\t\t\tif (\n\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t\t) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\t\n\t\t\tif (sendTo) {\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\t\tlocal_override\n\t\t\t\t) {\n\t\t\t\t\tif (!attachments) {\n\t\t\t\t\t\tattachments = [];\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\t\tattachments = [attachments];\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// Process attachments before saving\n\t\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\n\t\t\t\t\t// Queue the email in MongoDB\n\t\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\t\ttext: text || '',\n\t\t\t\t\t\thtml: html || '',\n\t\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t\terror: ''\n\t\t\t\t\t};\n\t\n\t\t\t\t\tEmailHistories.insertOne(emailHistory).then(\n\t\t\t\t\t\t(history) => resolve(history),\n\t\t\t\t\t\t(err) => {\n\t\t\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t'Send email',\n\t\t\t\t\t\tsendTo,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\thtml,\n\t\t\t\t\t\tattachments,\n\t\t\t\t\t\tsend_from\n\t\t\t\t\t);\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\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\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\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}"]}
|
package/package.json
CHANGED
package/server-app.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __awaiter=this&&this.__awaiter||function(e,o,n,s){return new(n=n||Promise)(function(t,r){function fulfilled(e){try{step(s.next(e))}catch(e){r(e)}}function rejected(e){try{step(s.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof n?r:new n(function(e){e(r)})).then(fulfilled,rejected)}step((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var s,i,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function verb(t){return function(e){var r=[t,e];if(s)throw new TypeError("Generator is already executing.");for(;l=u&&r[u=0]?0:l;)try{if(s=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return l.label++,{value:r[1],done:!1};case 5:l.label++,i=r[1],r=[0];continue;case 7:r=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){l=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))l.label=r[1];else if(6===r[0]&&l.label<a[1])l.label=a[1],a=r;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(r)}}r=n.call(o,l)}catch(e){r=[6,e],i=0}finally{s=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,n,s=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(o=s.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var o,n=0,s=r.length;n<s;n++)!o&&n in r||((o=o||Array.prototype.slice.call(r,0,n))[n]=r[n]);return e.concat(o||Array.prototype.slice.call(r))},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],o=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),mongodb_1=require("mongodb"),websocket_manager_1=require("./managers/websocket.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this._runningTasks=[],this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._safeShutdown=!1,this._workers=[],this._taskQueue=[],this._inFlightRequests={},this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction}return ResolveIOMainServer.prototype.initServerApp=function(){var e=this,s=(this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){e._subscriptionManager&&e._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",e._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",e._debugMsgQueue)),e._debugMsgQueue=0,e._debugMsgRecv=0},6e4),!1);setTimeout(function(){s=!0},5e3),process.on("unhandledRejection",function(o,n){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return o&&"MongoError"===o.name&&48===o.code?[2]:o&&"MongoServerError"===o.name&&!s?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[o,n]),r=moment().diff(this._serverStartTime,"seconds"),o&&("MongoNetworkTimeoutError"===o.name||o instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:o.name,message:o.message,stack:o.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return o&&"MongoError"===o.name&&"not master"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return o&&"MongoError"===o.name&&"not master and slaveOk=false"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:o&&"StatusError"!==o.name&&""!==o.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(e,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGTERM",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGQUIT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager,this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager,this.listen())},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,n,s=this;return __generator(this,function(e){return console.log(new Date,"Worker instance started, connecting to main server via WebSocket..."),r=resolveio_server_app_1.ResolveIOServer.getServerConfig().SERVER_URL+"/websocket?workerToken="+resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN,(n=function(){var t=new WebSocket(r),o=null,e=null;t.on("open",function(){console.log(new Date,"Connected to main server as worker",process.env.WORKER_INDEX,process.env.NODE_APP_INSTANCE),s.sendWorkerResponse(t,"ping"),e=setInterval(function(){o?(o=null,s.sendWorkerResponse(t,"ping")):t.close()},15e3)}),t.on("message",function(e){if("ping"===(e="string"!=typeof e?e.toString():e))s.sendWorkerResponse(t,"pong");else if("pong"===e)o=new Date;else{var r=void 0;try{r=JSON.parse(e,common_1.dateReviver)}catch(e){return void console.error("Worker parse error",e)}"task"===r.type&&s.handleIncomingTask(t,r)}}),t.on("close",function(){console.log(new Date,"Disconnected from main server. Reconnecting in 5s..."),setTimeout(n,5e3),e&&clearInterval(e)}),t.on("error",function(e){console.error(new Date,"Worker WS error:",e),t.close()})})(),[2]})})},ResolveIOMainServer.prototype.handleIncomingTask=function(c,_){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s,i,a,l,u=this;return __generator(this,function(e){switch(e.label){case 0:if(r=_.taskId,t=_.method,o=_.params,n=_.userContext,this._runningTasks.push(r),!r||!t)return console.log("Invalid task message received",_),[2];s=!1,i=setTimeout(function(){s=!0,console.error("Worker timed out on task:",r),u.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!0,message:"Task timed out"})},12e4),e.label=1;case 1:return e.trys.push([1,3,,4]),a=Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:(null==n?void 0:n.id_user)||"",user:(null==n?void 0:n.user)||"",id_ws:(null==n?void 0:n.id_ws)||""}),[4,(l=this._methodManager.callMethod).call.apply(l,__spreadArray([a,t],__read(o),!1))];case 2:return l=e.sent(),s||(clearTimeout(i),this.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!1,result:l})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,4];case 3:return a=e.sent(),s||(clearTimeout(i),console.error("Worker failed task:",r,a),this.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!0,message:a.message||"Unknown error"})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,4];case 4:return[2]}})})},ResolveIOMainServer.prototype.sendWorkerResponse=function(e,r){if("string"!=typeof r&&(r=JSON.stringify(r)),e&&e.readyState===e.OPEN)try{e.send(r)}catch(e){console.error("Failed to send worker response:",e)}else e&&e.close()},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length||this._taskQueue.length||this._runningTasks.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):resolveio_server_app_1.ResolveIOServer.getMongoConnection()?resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(s,i){return __awaiter(e,void 0,void 0,function(){var r,t,n=this;return __generator(this,function(e){if(this._rebootFlag)i(!1,409,"Unable To Process");else{if("DEBUG"===this.LOGGER&&console.log("Verify Client",s,i),s.req.url&&s.req.url.includes("workerToken="))return r=s.req.url.split("workerToken="),(r[1]||"")===resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN?i(!0):i(!1,401,"Unauthorized"),[2];r=s.req.headers["sec-websocket-protocol"].split(/,/),(s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(t=r[0])?jwt.verify(t,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,o){return __awaiter(n,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:s.req.id_user=o.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(o.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.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")}return[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var s=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",s._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",s._portWSS)}),this._serverWSS.on("connection",function(o,e){var r,t,n;e.url&&e.url.includes("workerToken=")?(r=(0,common_1.objectIdHexString)(),o.id_worker=r,s._workers.push({id:r,ws:o,activeTasks:0,maxConcurrency:2}),n=t=null,o.on("open",function(){s.sendWorkerResponse(o,"ping"),t=setInterval(function(){n?(n=null,s.sendWorkerResponse(o,"ping")):o.close()},15e3)}),console.log(new Date,"Worker connected:",r),o.on("message",function(e){"ping"===(e="string"!=typeof e?e.toString():e)?s.sendWorkerResponse(o,"pong"):"pong"===e?n=new Date:s.handleWorkerMessage(r,e)}),o.on("close",function(){console.log(new Date,"Worker disconnected:",r),s._workers=s._workers.filter(function(e){return e.id!==r}),t&&clearInterval(t)}),o.on("error",function(e){console.error("Error on WS Worker",e),o.close()})):(o.id_socket=(0,common_1.objectIdHexString)(),o.id_user=e.id_user,o.user=e.user,o.user_readonly=e.user_readonly,o.doc_user=e.doc_user,s._websocketManager.addWebSocket(o),s._subscriptionManager.createLoggedInUser(o.id_socket).then(function(){setTimeout(function(){o.pingTime=new Date,o.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(o))})},5e3)}),"DEBUG"===s.LOGGER&&console.log("Connection from user: "+e.user),o.isAlive=!0,o.retryCnt=0,o.on("message",function(t){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){this._debugMsgRecv+=1,r=[];try{r=JSON.parse(t,common_1.dateReviver)}catch(e){return console.log("Error - JSON.parse",t),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t,e])),[2]}return this.processSocketMessage(o,r),[2]})})}).on("end",function(){s.unsubscribeWS(o)}).on("close",function(){s.unsubscribeWS(o)}).on("error",function(e){s.unsubscribeWS(o)}))}),setInterval(function(){s._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?s.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(i,a){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s;return __generator(this,function(e){switch(e.label){case 0:if("string"==typeof a&&"ping"===a)return i&&i.readyState===i.OPEN&&i.send("pong"),[2];if("string"==typeof a&&"pong"===a)return i.isAlive=!0,i.pongTime=new Date,i.latency=moment.duration(moment(i.pongTime).diff(i.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(i),[2];if(!Array.isArray(a[0]))return console.log("Invalid message format (expected array of arrays)",a),[2];e.label=1;case 1:e.trys.push([1,6,7,8]),r=__values(a),t=r.next(),e.label=2;case 2:return t.done?[3,5]:(o=t.value,[4,this.handleClientMessage(i,o)]);case 3:e.sent(),e.label=4;case 4:return t=r.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),n={error:o},[3,8];case 7:try{t&&!t.done&&(s=r.return)&&s.call(r)}finally{if(n)throw n.error}return[7];case 8:return[2]}})})},ResolveIOMainServer.prototype.handleClientMessage=function(h,f){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s,i,a,l,u,c,_,g,v,d,p;return __generator(this,function(e){switch(e.label){case 0:return(r=f[0],a=f[1],t=f[2],o=f[3],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||h.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||h.doc_user.roles.super_admin)?"subscription"!==o?[3,1]:(n=f[4],u=f[5],"sub"===n?this._subscriptionManager.subscribe(r,a,h,t,u,f.slice(6)):this._subscriptionManager.unsubscribe(r,a,h,t,u,f.slice(6)),[3,11]):[2];case 1:if(this.publicProgram||"offline"!==o)return[3,10];n={messageId:t,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,n),this._offlineUpdates.push(h),s=f[4],i=0,e.label=2;case 2:if(!(i<s.length))return[3,9];if(a=s[i],l=a.data,l.shift(),l.shift(),u=l.shift(),l.shift(),c=l.shift(),p={messageId:u,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,p),"insertDocument"===c&&"driver-gps"===l[0])return[3,8];if("reportBuilderGetResults"!==c&&"reportBuilderGetDistinctValue"!==c&&"reportBuilderBuildTree"!==c&&"generatePDF"!==c&&"getWOOfflineData"!==c&&"countQuery"!==c&&"countWithQuery"!==c&&"countCollectionWithQuery"!==c&&"find"!==c&&"findOne"!==c&&"findWithOptions"!==c&&"getDrivers"!==c&&"processAirdropDistribution"!==c&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:c,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:c,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r,client:"ResolveIO",instance:"backend.resolveio.com"})),!this._methodManager._methods[c])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(p=this._methodManager.callMethod).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:h.id_user,user:h.user,id_ws:h.id_socket}),c],__read(l),!1))];case 4:return e.sent(),[3,6];case 5:return _=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(_,null,2)),[3,6];case 6:return"updateDocumentOffline"!==c&&"updateDocumentPropsOffline"!==c||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,8];case 7:console.log("Offline - Could not find method: "+c),e.label=8;case 8:return i++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(h.id_socket),1),[3,11];case 10:if(_=__spreadArray([],__read(f),!1),_.shift(),_.shift(),g=_.shift(),"method"===_.shift()){if(v=_.shift(),h.user_readonly)return[2];"reportBuilderGetResults"!==v&&"reportBuilderGetDistinctValue"!==v&&"reportBuilderBuildTree"!==v&&"generatePDF"!==v&&"getWOOfflineData"!==v&&"countQuery"!==v&&"countWithQuery"!==v&&"countCollectionWithQuery"!==v&&"find"!==v&&"findOne"!==v&&"findWithOptions"!==v&&"getDrivers"!==v&&"processAirdropDistribution"!==v&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(_))<2e5?JSON.stringify(_,null,2):"Too Big",method:v,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(_))<2e5?JSON.stringify(_,null,2):"Too Big",method:v,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r,client:"ResolveIO",instance:"backend.resolveio.com"})),d={messageId:g,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,d),d=this.findAvailableWorker(),this._isWorkersEnabled&&d&&"find"!==v&&"insertDocument"!==v&&"countWithQuery"!==v&&"findOne"!==v&&"updateDocumentProps"!==v&&"findWithOptions"!==v&&"updateDocument"!==v&&"insertErrorLog"!==v&&"removeDocument"!==v&&"supportCreateBillingUser"!==v&&"getSignedUrl"!==v&&"getSignedUrls"!==v&&"getSignedUrlWithId"!==v&&"incorrectUser"!==v&&"reloadWS"!==v&&"reconnectWS"!==v&&"disconnectWS"!==v?(d="task-"+(0,common_1.objectIdHexString)(),this._inFlightRequests[d]={ws:h,messageId:g,method:v},this.queueTask(d,v,_,{id_user:h.id_user,user:h.user,id_ws:h.id_socket})):this.callMethodLocally(h,g,v,_)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.callMethodLocally=function(n,s,i,a){return __awaiter(this,void 0,void 0,function(){var r,t,o;return __generator(this,function(e){switch(e.label){case 0:r={messageId:s,hasError:!1,data:null},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(o=this._methodManager.callMethod).call.apply(o,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket}),i],__read(a),!1))];case 2:return o=e.sent(),r.data=o,[3,4];case 3:return t=e.sent(),r.hasError=!0,r.data=t.message||"Unknown error",[3,4];case 4:return n&&n.readyState===n.OPEN&&this._websocketManager.send(n,r),[2]}})})},ResolveIOMainServer.prototype.queueTask=function(e,r,t,o){this._taskQueue.push({taskId:e,method:r,params:t,userContext:o}),this.dispatchQueue()},ResolveIOMainServer.prototype.dispatchQueue=function(){if(this._taskQueue.length)for(var e=0;e<9999;e++){var r=this._taskQueue[0];if(!r)break;var t=this.findAvailableWorker();if(!t)break;this._taskQueue.shift(),this.assignTaskToWorker(t,r)}},ResolveIOMainServer.prototype.findAvailableWorker=function(){var e=this._workers.filter(function(e){return e.activeTasks<e.maxConcurrency});return e.length?(e.sort(function(e,r){return e.activeTasks-r.activeTasks}),e[0]):null},ResolveIOMainServer.prototype.assignTaskToWorker=function(r,t){r.activeTasks++;var e={type:"task",taskId:t.taskId,method:t.method,params:t.params,userContext:t.userContext};try{r.ws.send(JSON.stringify(e))}catch(e){console.error("Failed to send task to worker:",e),r.activeTasks=Math.max(0,r.activeTasks-1),this._taskQueue.unshift(t)}},ResolveIOMainServer.prototype.handleWorkerMessage=function(r,t){var e,o,n,s;try{s=JSON.parse(t,common_1.dateReviver)}catch(e){return void console.error("Failed to parse worker message:",t)}"taskComplete"===s.type&&((t=this._workers.find(function(e){return e.id===r}))?(t.activeTasks=Math.max(0,t.activeTasks-1),t=s.taskId,e=s.error,o=s.message,s=s.result,(n=this._inFlightRequests[t])?(delete this._inFlightRequests[t],s={messageId:n.messageId,hasError:!1,data:s},e&&(s.hasError=!0,s.data=o),n.ws&&n.ws.readyState===n.ws.OPEN&&this._websocketManager.send(n.ws,s)):console.error("No in-flight request found for task:",t),this.dispatchQueue()):console.error("Unknown worker for taskComplete:",r))},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager&&this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
|
|
1
|
+
"use strict";var __awaiter=this&&this.__awaiter||function(e,o,n,s){return new(n=n||Promise)(function(t,r){function fulfilled(e){try{step(s.next(e))}catch(e){r(e)}}function rejected(e){try{step(s.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof n?r:new n(function(e){e(r)})).then(fulfilled,rejected)}step((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var s,i,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function verb(t){return function(e){var r=[t,e];if(s)throw new TypeError("Generator is already executing.");for(;l=u&&r[u=0]?0:l;)try{if(s=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return l.label++,{value:r[1],done:!1};case 5:l.label++,i=r[1],r=[0];continue;case 7:r=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){l=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))l.label=r[1];else if(6===r[0]&&l.label<a[1])l.label=a[1],a=r;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(r)}}r=n.call(o,l)}catch(e){r=[6,e],i=0}finally{s=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,n,s=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(o=s.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var o,n=0,s=r.length;n<s;n++)!o&&n in r||((o=o||Array.prototype.slice.call(r,0,n))[n]=r[n]);return e.concat(o||Array.prototype.slice.call(r))},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],o=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),mongodb_1=require("mongodb"),websocket_manager_1=require("./managers/websocket.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this._runningTasks=[],this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._safeShutdown=!1,this._workers=[],this._taskQueue=[],this._inFlightRequests={},this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction}return ResolveIOMainServer.prototype.initServerApp=function(){var e=this,s=(this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){e._subscriptionManager&&e._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",e._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",e._debugMsgQueue)),e._debugMsgQueue=0,e._debugMsgRecv=0},6e4),!1);setTimeout(function(){s=!0},5e3),process.on("unhandledRejection",function(o,n){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return o&&"MongoError"===o.name&&48===o.code?[2]:o&&"MongoServerError"===o.name&&!s?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[o,n]),r=moment().diff(this._serverStartTime,"seconds"),o&&("MongoNetworkTimeoutError"===o.name||o instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:o.name,message:o.message,stack:o.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return o&&"MongoError"===o.name&&"not master"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return o&&"MongoError"===o.name&&"not master and slaveOk=false"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:o&&"StatusError"!==o.name&&""!==o.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(e,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGTERM",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGQUIT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager,this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager,this.listen())},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,n,s=this;return __generator(this,function(e){return console.log(new Date,"Worker instance started, connecting to main server via WebSocket..."),r=resolveio_server_app_1.ResolveIOServer.getServerConfig().SERVER_URL+"/websocket?workerToken="+resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN,(n=function(){var t=new WebSocket(r),o=null,e=null;t.on("open",function(){console.log(new Date,"Connected to main server as worker",process.env.WORKER_INDEX,process.env.NODE_APP_INSTANCE),s.sendWorkerResponse(t,"ping"),e=setInterval(function(){o?(o=null,s.sendWorkerResponse(t,"ping")):t.close()},15e3)}),t.on("message",function(e){if("ping"===(e="string"!=typeof e?e.toString():e))s.sendWorkerResponse(t,"pong");else if("pong"===e)o=new Date;else{var r=void 0;try{r=JSON.parse(e,common_1.dateReviver)}catch(e){return void console.error("Worker parse error",e)}"task"===r.type&&s.handleIncomingTask(t,r)}}),t.on("close",function(){console.log(new Date,"Disconnected from main server. Reconnecting in 5s..."),setTimeout(n,5e3),e&&clearInterval(e)}),t.on("error",function(e){console.error(new Date,"Worker WS error:",e),t.close()})})(),[2]})})},ResolveIOMainServer.prototype.handleIncomingTask=function(c,_){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s,i,a,l,u=this;return __generator(this,function(e){switch(e.label){case 0:if(r=_.taskId,t=_.method,o=_.params,n=_.userContext,this._runningTasks.push(r),!r||!t)return console.log("Invalid task message received",_),[2];s=!1,i=setTimeout(function(){s=!0,console.error("Worker timed out on task:",r),u.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!0,message:"Task timed out"})},12e4),e.label=1;case 1:return e.trys.push([1,3,,4]),a=Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:(null==n?void 0:n.id_user)||"",user:(null==n?void 0:n.user)||"",id_ws:(null==n?void 0:n.id_ws)||""}),[4,(l=this._methodManager.callMethod).call.apply(l,__spreadArray([a,t],__read(o),!1))];case 2:return l=e.sent(),s||(clearTimeout(i),this.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!1,result:l})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,4];case 3:return a=e.sent(),s||(clearTimeout(i),console.error("Worker failed task:",r,a),this.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!0,message:a||"Unknown error"})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,4];case 4:return[2]}})})},ResolveIOMainServer.prototype.sendWorkerResponse=function(e,r){if("string"!=typeof r&&(r=JSON.stringify(r)),e&&e.readyState===e.OPEN)try{e.send(r)}catch(e){console.error("Failed to send worker response:",e)}else e&&e.close()},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length||this._taskQueue.length||this._runningTasks.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):resolveio_server_app_1.ResolveIOServer.getMongoConnection()?resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(s,i){return __awaiter(e,void 0,void 0,function(){var r,t,n=this;return __generator(this,function(e){if(this._rebootFlag)i(!1,409,"Unable To Process");else{if("DEBUG"===this.LOGGER&&console.log("Verify Client",s,i),s.req.url&&s.req.url.includes("workerToken="))return r=s.req.url.split("workerToken="),(r[1]||"")===resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN?i(!0):i(!1,401,"Unauthorized"),[2];r=s.req.headers["sec-websocket-protocol"].split(/,/),(s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(t=r[0])?jwt.verify(t,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,o){return __awaiter(n,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:s.req.id_user=o.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(o.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.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")}return[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var s=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",s._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",s._portWSS)}),this._serverWSS.on("connection",function(o,e){var r,t,n;e.url&&e.url.includes("workerToken=")?(r=(0,common_1.objectIdHexString)(),o.id_worker=r,s._workers.push({id:r,ws:o,activeTasks:0,maxConcurrency:2}),n=t=null,o.on("open",function(){s.sendWorkerResponse(o,"ping"),t=setInterval(function(){n?(n=null,s.sendWorkerResponse(o,"ping")):o.close()},15e3)}),console.log(new Date,"Worker connected:",r),o.on("message",function(e){"ping"===(e="string"!=typeof e?e.toString():e)?s.sendWorkerResponse(o,"pong"):"pong"===e?n=new Date:s.handleWorkerMessage(r,e)}),o.on("close",function(){console.log(new Date,"Worker disconnected:",r),s._workers=s._workers.filter(function(e){return e.id!==r}),t&&clearInterval(t)}),o.on("error",function(e){console.error("Error on WS Worker",e),o.close()})):(o.id_socket=(0,common_1.objectIdHexString)(),o.id_user=e.id_user,o.user=e.user,o.user_readonly=e.user_readonly,o.doc_user=e.doc_user,s._websocketManager.addWebSocket(o),s._subscriptionManager.createLoggedInUser(o.id_socket).then(function(){setTimeout(function(){o.pingTime=new Date,o.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(o))})},5e3)}),"DEBUG"===s.LOGGER&&console.log("Connection from user: "+e.user),o.isAlive=!0,o.retryCnt=0,o.on("message",function(t){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){this._debugMsgRecv+=1,r=[];try{r=JSON.parse(t,common_1.dateReviver)}catch(e){return console.log("Error - JSON.parse",t),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t,e])),[2]}return this.processSocketMessage(o,r),[2]})})}).on("end",function(){s.unsubscribeWS(o)}).on("close",function(){s.unsubscribeWS(o)}).on("error",function(e){s.unsubscribeWS(o)}))}),setInterval(function(){s._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?s.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(i,a){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s;return __generator(this,function(e){switch(e.label){case 0:if("string"==typeof a&&"ping"===a)return i&&i.readyState===i.OPEN&&i.send("pong"),[2];if("string"==typeof a&&"pong"===a)return i.isAlive=!0,i.pongTime=new Date,i.latency=moment.duration(moment(i.pongTime).diff(i.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(i),[2];if(!Array.isArray(a[0]))return console.log("Invalid message format (expected array of arrays)",a),[2];e.label=1;case 1:e.trys.push([1,6,7,8]),r=__values(a),t=r.next(),e.label=2;case 2:return t.done?[3,5]:(o=t.value,[4,this.handleClientMessage(i,o)]);case 3:e.sent(),e.label=4;case 4:return t=r.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),n={error:o},[3,8];case 7:try{t&&!t.done&&(s=r.return)&&s.call(r)}finally{if(n)throw n.error}return[7];case 8:return[2]}})})},ResolveIOMainServer.prototype.handleClientMessage=function(h,f){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s,i,a,l,u,c,_,g,v,d,p;return __generator(this,function(e){switch(e.label){case 0:return(r=f[0],a=f[1],t=f[2],o=f[3],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||h.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||h.doc_user.roles.super_admin)?"subscription"!==o?[3,1]:(n=f[4],u=f[5],"sub"===n?this._subscriptionManager.subscribe(r,a,h,t,u,f.slice(6)):this._subscriptionManager.unsubscribe(r,a,h,t,u,f.slice(6)),[3,11]):[2];case 1:if(this.publicProgram||"offline"!==o)return[3,10];n={messageId:t,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,n),this._offlineUpdates.push(h),s=f[4],i=0,e.label=2;case 2:if(!(i<s.length))return[3,9];if(a=s[i],l=a.data,l.shift(),l.shift(),u=l.shift(),l.shift(),c=l.shift(),p={messageId:u,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,p),"insertDocument"===c&&"driver-gps"===l[0])return[3,8];if("reportBuilderGetResults"!==c&&"reportBuilderGetDistinctValue"!==c&&"reportBuilderBuildTree"!==c&&"generatePDF"!==c&&"getWOOfflineData"!==c&&"countQuery"!==c&&"countWithQuery"!==c&&"countCollectionWithQuery"!==c&&"find"!==c&&"findOne"!==c&&"findWithOptions"!==c&&"getDrivers"!==c&&"processAirdropDistribution"!==c&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:c,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:c,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r,client:"ResolveIO",instance:"backend.resolveio.com"})),!this._methodManager._methods[c])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(p=this._methodManager.callMethod).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:h.id_user,user:h.user,id_ws:h.id_socket}),c],__read(l),!1))];case 4:return e.sent(),[3,6];case 5:return _=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(_,null,2)),[3,6];case 6:return"updateDocumentOffline"!==c&&"updateDocumentPropsOffline"!==c||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,8];case 7:console.log("Offline - Could not find method: "+c),e.label=8;case 8:return i++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(h.id_socket),1),[3,11];case 10:if(_=__spreadArray([],__read(f),!1),_.shift(),_.shift(),g=_.shift(),"method"===_.shift()){if(v=_.shift(),h.user_readonly)return[2];"reportBuilderGetResults"!==v&&"reportBuilderGetDistinctValue"!==v&&"reportBuilderBuildTree"!==v&&"generatePDF"!==v&&"getWOOfflineData"!==v&&"countQuery"!==v&&"countWithQuery"!==v&&"countCollectionWithQuery"!==v&&"find"!==v&&"findOne"!==v&&"findWithOptions"!==v&&"getDrivers"!==v&&"processAirdropDistribution"!==v&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(_))<2e5?JSON.stringify(_,null,2):"Too Big",method:v,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(_))<2e5?JSON.stringify(_,null,2):"Too Big",method:v,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r,client:"ResolveIO",instance:"backend.resolveio.com"})),d={messageId:g,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,d),d=this.findAvailableWorker(),this._isWorkersEnabled&&d&&"find"!==v&&"insertDocument"!==v&&"countWithQuery"!==v&&"findOne"!==v&&"updateDocumentProps"!==v&&"findWithOptions"!==v&&"updateDocument"!==v&&"insertErrorLog"!==v&&"removeDocument"!==v&&"supportCreateBillingUser"!==v&&"getSignedUrl"!==v&&"getSignedUrls"!==v&&"getSignedUrlWithId"!==v&&"incorrectUser"!==v&&"reloadWS"!==v&&"reconnectWS"!==v&&"disconnectWS"!==v?(d="task-"+(0,common_1.objectIdHexString)(),this._inFlightRequests[d]={ws:h,messageId:g,method:v},this.queueTask(d,v,_,{id_user:h.id_user,user:h.user,id_ws:h.id_socket})):this.callMethodLocally(h,g,v,_)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.callMethodLocally=function(n,s,i,a){return __awaiter(this,void 0,void 0,function(){var r,t,o;return __generator(this,function(e){switch(e.label){case 0:r={messageId:s,hasError:!1,data:null},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(o=this._methodManager.callMethod).call.apply(o,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket}),i],__read(a),!1))];case 2:return o=e.sent(),r.data=o,[3,4];case 3:return t=e.sent(),r.hasError=!0,r.data=t||"Unknown error",[3,4];case 4:return n&&n.readyState===n.OPEN&&this._websocketManager.send(n,r),[2]}})})},ResolveIOMainServer.prototype.queueTask=function(e,r,t,o){this._taskQueue.push({taskId:e,method:r,params:t,userContext:o}),this.dispatchQueue()},ResolveIOMainServer.prototype.dispatchQueue=function(){if(this._taskQueue.length)for(var e=0;e<9999;e++){var r=this._taskQueue[0];if(!r)break;var t=this.findAvailableWorker();if(!t)break;this._taskQueue.shift(),this.assignTaskToWorker(t,r)}},ResolveIOMainServer.prototype.findAvailableWorker=function(){var e=this._workers.filter(function(e){return e.activeTasks<e.maxConcurrency});return e.length?(e.sort(function(e,r){return e.activeTasks-r.activeTasks}),e[0]):null},ResolveIOMainServer.prototype.assignTaskToWorker=function(r,t){r.activeTasks++;var e={type:"task",taskId:t.taskId,method:t.method,params:t.params,userContext:t.userContext};try{r.ws.send(JSON.stringify(e))}catch(e){console.error("Failed to send task to worker:",e),r.activeTasks=Math.max(0,r.activeTasks-1),this._taskQueue.unshift(t)}},ResolveIOMainServer.prototype.handleWorkerMessage=function(r,t){var e,o,n,s;try{s=JSON.parse(t,common_1.dateReviver)}catch(e){return void console.error("Failed to parse worker message:",t)}"taskComplete"===s.type&&((t=this._workers.find(function(e){return e.id===r}))?(t.activeTasks=Math.max(0,t.activeTasks-1),t=s.taskId,e=s.error,o=s.message,s=s.result,(n=this._inFlightRequests[t])?(delete this._inFlightRequests[t],s={messageId:n.messageId,hasError:!1,data:s},e&&(s.hasError=!0,s.data=o),n.ws&&n.ws.readyState===n.ws.OPEN&&this._websocketManager.send(n.ws,s)):console.error("No in-flight request found for task:",t),this.dispatchQueue()):console.error("Unknown worker for taskComplete:",r))},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager&&this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
|
|
2
2
|
//# sourceMappingURL=server-app.js.map
|
package/server-app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","user_collection_1","home_1","auth_1","health_1","mongodb_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","_runningTasks","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_workers","_taskQueue","_inFlightRequests","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","prototype","initServerApp","_this","initServerFlag","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","setTimeout","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","wsUrl","connect","ws","lastComm","interval","WORKER_INDEX","NODE_APP_INSTANCE","sendWorkerResponse","rawData","toString","msg","parse","e","type","handleIncomingTask","clearInterval","err","data","taskId","method","params","userContext","push","timedOut","timeoutHandle","managerThis","Object","assign","id_user","user","id_ws","callMethod","call","apply","__spreadArray","__read","result","_b","clearTimeout","filter","a","err_1","payload","readyState","OPEN","send","getActiveMonitorFunctions","length","setImmediate","getMongoConnection","then","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","url","includes","urlParts","split","infoData","headers","origin","token","verify","decoded","Users","findById","fullname","readonly","workerId_1","interval_1","lastComm_1","objectIdHexString","id","activeTasks","maxConcurrency","handleWorkerMessage","w","addWebSocket","createLoggedInUser","unsubscribeWS","socketData","processSocketMessage","now","getTime","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","__values","socketData_1_1","value","handleClientMessage","messageRoute","messageDate","messageId","some","roles","groups","views","b","super_admin","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","serverResMethod","getLocalLogManager","writeLog","_id","createdAt","collection","id_document","getBinarySize","route","Logs","insertOne","client","instance","_methods","err_3","getMongoManager","invalidateQueryCache","splice","map","indexOf","dataCopy","msgId","methodName","ack","worker","findAvailableWorker","queueTask","callMethodLocally","err_4","dispatchQueue","item","assignTaskToWorker","candidates","x","sort","task","Math","max","unshift","workerId","messageStr","inflight","find","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,Q,0FAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EACAM,OAAAN,QAAA,iBAAA,EAEAO,SAAAP,QAAA,eAAA,EACAQ,eAAAR,QAAA,yBAAA,EACAS,iBAAAT,QAAA,2BAAA,EACAU,uBAAAV,QAAA,iCAAA,EACAW,kBAAAX,QAAA,4BAAA,EAEAY,iBAAAZ,QAAA,8BAAA,EACAa,kBAAAb,QAAA,+BAAA,EAEAc,OAAAd,QAAA,aAAA,EACAe,OAAAf,QAAA,aAAA,EACAgB,SAAAhB,QAAA,eAAA,EACAiB,UAAAjB,QAAA,SAAA,EAEAkB,oBAAAlB,QAAA,8BAAA,EACAmB,uBAAAnB,QAAA,wBAAA,EAsBAoB,oBAAA,WAsCC,SAAAA,sBAhCQC,KAAAC,gBAAkB,GACnBD,KAAAE,QAAU,CAAA,EACTF,KAAAG,gBAAkB,CAAA,EAClBH,KAAAI,cAAgB,CAAA,EAChBJ,KAAAK,YAAc,CAAA,EACdL,KAAAM,cAAgB,GAEhBN,KAAAO,OAAS,QAQT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5D,UACpBa,SAAU,CAAA,EACV7G,KAAMmB,C,EAGHxF,IACH8C,EAAIoI,SAAW,CAAA,EACfpI,EAAIuB,KAAOxD,GAGRoN,EAAS3K,IAAM2K,EAAS3K,GAAGyC,aAAekI,EAAS3K,GAAG0C,MACzDvI,KAAKgE,kBAAkBwE,KAAKgI,EAAS3K,GAAIR,CAAG,GAlB7ClD,QAAQI,MAAM,uCAAwCsE,CAAM,EAuB7D7G,KAAK4P,cAAa,GAlCjBzN,QAAQI,MAAM,mCAAoC+N,CAAQ,EAoC7D,EAKOvQ,oBAAAyB,UAAAmK,cAAP,SAAqB9F,GAChB7F,KAAKiC,sBAAwBjC,KAAKiC,qBAAqBC,eAAc,GACxEC,QAAQC,IAAI,IAAIjB,KAAQ,aAAc,WAAY0E,EAAS,KAAGA,EAAc,SAAC,EAE9E7F,KAAKiC,qBAAqByO,eAAe7K,CAAE,EAC3CA,EAAG8K,mBAAkB,CAEtB,EAEO5Q,oBAAAyB,UAAAoP,OAAP,WACC,OAAO5Q,KAAKsE,IACb,EAEOvE,oBAAAyB,UAAAwB,gBAAP,WACC,OAAOlD,uBAAAiD,gBAAgBC,gBAAe,CACvC,EACDjD,mBAAA,EAAC,EA5rCY8Q,QAAA9Q,oBAAAA","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { MongoNetworkTimeoutError } from 'mongodb';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\ninterface WorkerConnection {\n\tid: string;\n\tws: WebSocket;\n\tactiveTasks: number;\n\tmaxConcurrency: number;\n}\n\ninterface TaskQueueItem {\n\ttaskId: string;\n\tmethod: string;\n\tparams: any[];\n\tuserContext?: { id_user?: string; user?: string; id_ws?: string };\n}\n\ninterface InFlightRequest {\n\tws: WebSocket; // the client's WebSocket\n\tmessageId: number; // the ID so the client knows which call this corresponds to\n\tmethod: string;\n}\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\tprivate _runningTasks = [];\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tprivate _workers: WorkerConnection[] = [];\n\tprivate _taskQueue: TaskQueueItem[] = [];\n\tprivate _inFlightRequests: { [taskId: string]: InFlightRequest } = {};\n\n\tconstructor() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\t}\n\n\tinitServerApp() {\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tlet initServerFlag = false;\n\n\t\tsetTimeout(() => {\n\t\t\tinitServerFlag = true;\n\t\t}, 5000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tif (error && error['name'] === 'MongoServerError' && !initServerFlag) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\tif (this._isWorkersEnabled) {\n\t\t\tif (this._isWorkerInstance) {\n\t\t\t\tconsole.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._cronManager = new CronManager();\n\t\t\t\tthis.startWorkerInstance();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n\t\t\tthis.startServerInstance();\n\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\tthis._cronManager = new CronManager();\n\t\t\tthis.listen();\n\t\t}\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || ResolveIOServer.getServerConfig()['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || ResolveIOServer.getServerConfig()['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app, ResolveIOServer.getServerConfig());\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async startWorkerInstance() {\n\t\tconsole.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');\n\n\t\tlet wsUrl = ResolveIOServer.getServerConfig()['SERVER_URL'] + '/websocket?workerToken=' + ResolveIOServer.getServerConfig()['WORKER_TOKEN'];\n\n\t\tconst connect = () => {\n\t\t\tconst ws = new WebSocket(wsUrl);\n\n\t\t\tlet lastComm = null;\n\t\t\tlet interval = null;\n\n\t\t\tws.on('open', () => {\n\t\t\t\tconsole.log(new Date(), 'Connected to main server as worker', process.env.WORKER_INDEX, process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\n\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t}\n\t\t\t\t}, 15000);\n\t\t\t});\n\n\t\t\tws.on('message', (rawData: any) => {\n\t\t\t\t// console.log(new Date(), 'Message Recv', rawData);\n\n\t\t\t\tif (typeof rawData !== 'string') {\n\t\t\t\t\trawData = rawData.toString();\n\t\t\t\t}\n\n\t\t\t\t// console.log(new Date(), 'String Message Recv', rawData);\n\n\t\t\t\tif (rawData === 'ping') {\n\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t}\n\t\t\t\telse if (rawData === 'pong') {\n\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\tlastComm = new Date();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet msg: any;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmsg = JSON.parse(rawData, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.error('Worker parse error', e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// We expect: { type: 'task', taskId, method, params, userContext? }\n\t\t\t\t\tif (msg.type === 'task') {\n\t\t\t\t\t\tthis.handleIncomingTask(ws, msg);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'Disconnected from main server. Reconnecting in 5s...');\n\t\t\t\tsetTimeout(connect, 5000);\n\n\t\t\t\tif (interval) {\n\t\t\t\t\tclearInterval(interval);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.on('error', (err) => {\n\t\t\t\tconsole.error(new Date(), 'Worker WS error:', err);\n\t\t\t\tws.close();\n\t\t\t});\n\t\t};\n\n\t\tconnect();\n\t}\n\n\tprivate async handleIncomingTask(ws: WebSocket, data: any) {\n\t\tlet { taskId, method, params, userContext } = data;\n\t\tthis._runningTasks.push(taskId);\n\t\tif (!taskId || !method) {\n\t\t\tconsole.log('Invalid task message received', data);\n\t\t\treturn;\n\t\t}\n\n\t\tlet timedOut = false;\n\t\tlet timeoutHandle = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tconsole.error('Worker timed out on task:', taskId);\n\n\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\ttype: 'taskComplete',\n\t\t\t\ttaskId,\n\t\t\t\terror: true,\n\t\t\t\tmessage: 'Task timed out'\n\t\t\t});\n\t\t}, 120000);\n\n\t\ttry {\n\t\t\tlet managerThis = Object.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\tid_user: userContext?.id_user || '',\n\t\t\t\tuser: userContext?.user || '',\n\t\t\t\tid_ws: userContext?.id_ws || ''\n\t\t\t});\n\n\t\t\tlet result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: false,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t\tcatch (err) {\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tconsole.error('Worker failed task:', taskId, err);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: true,\n\t\t\t\t\tmessage: err.message || 'Unknown error'\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t}\n\n\tprivate sendWorkerResponse(ws: WebSocket, payload: any) {\n\t\tif (typeof payload !== 'string') {\n\t\t\tpayload = JSON.stringify(payload);\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\ttry {\n\t\t\t\tws.send(payload);\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tconsole.error('Failed to send worker response:', err);\n\t\t\t}\n\t\t}\n\t\telse if (ws) {\n\t\t\tws.close();\n\t\t}\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length\n\t\t\t&& !this._offlineUpdates.length && !this._taskQueue.length && !this._runningTasks.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}, () => { process.exit(1); });\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), 'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000;\n\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : 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\t// If it's a worker, we might skip token checks or do a simple check:\n\t\t\t\t\tif (info.req.url && info.req.url.includes('workerToken=')) {\n\t\t\t\t\t\tlet urlParts = info.req.url.split('workerToken='); \n\t\t\t\t\t\tlet workerToken = urlParts[1] || '';\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\n\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tinfo.origin !== ResolveIOServer.getServerConfig()['ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']\n\t\t\t\t\t) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (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/**\n\t * Listen for connections from clients or workers.\n\t */\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t// It's a WORKER\n\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\tws['id_worker'] = workerId;\n\n\t\t\t\t// For demonstration, let each worker handle up to 2 tasks concurrently\n\t\t\t\tlet maxConcurrency = 2;\n\n\t\t\t\tthis._workers.push({\n\t\t\t\t\tid: workerId,\n\t\t\t\t\tws: ws,\n\t\t\t\t\tactiveTasks: 0,\n\t\t\t\t\tmaxConcurrency: maxConcurrency\n\t\t\t\t});\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tws.on('open', () => {\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\n\t\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\t\tws.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 15000);\n\t\t\t\t});\n\n\t\t\t\tconsole.log(new Date(), 'Worker connected:', workerId);\n\n\t\t\t\tws.on('message', (message: any) => {\n\t\t\t\t\t// console.log(new Date(), 'Message Recv', message);\n\n\t\t\t\t\tif (typeof message !== 'string') {\n\t\t\t\t\t\tmessage = message.toString();\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log(new Date(), 'String Message Recv', message);\n\n\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t\t}\n\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.handleWorkerMessage(workerId, message);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\tthis._workers = this._workers.filter(w => w.id !== workerId);\n\t\t\t\t\t\n\t\t\t\t\tif (interval) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error on WS Worker', error);\n\t\t\t\t\tws.close();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Normal client\n\t\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}, 5000);\n\t\t\t\t});\n\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Connection from user: ' + req['user']);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['retryCnt'] = 0;\n\n\t\t\t\tws.on('message', async (message: string) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\tthis._methodManager.sendEmail(\n\t\t\t\t\t\t\t'dev@resolveio.com', \n\t\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], \n\t\t\t\t\t\t\tJSON.stringify([message, e])\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// call our existing processSocketMessage\n\t\t\t\t\tthis.processSocketMessage(ws, socketData);\n\t\t\t\t})\n\t\t\t\t.on('end', () => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t})\n\t\t\t\t.on('close', () => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t})\n\t\t\t\t.on('error', error => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\t// Keep alive timer\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\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any) {\n\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tws.send('pong');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\tws['isAlive'] = true;\n\t\t\tws['pongTime'] = new Date();\n\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the top level is not an array, let's skip\n\t\tif (!Array.isArray(socketData[0])) {\n\t\t\tconsole.log('Invalid message format (expected array of arrays)', socketData);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle each sub-message\n\t\tfor (let message of socketData) {\n\t\t\tawait this.handleClientMessage(ws, message);\n\t\t}\n\t}\n\n\tprivate async handleClientMessage(ws: WebSocket, msg: any[]): Promise<void> {\n\t\t// This is basically your old logic from processSocketMessage,\n\t\t// but we'll insert our worker-queue logic for \"method\" calls.\n\n\t\tlet messageRoute = msg[0];\n\t\tlet messageDate = msg[1];\n\t\tlet messageId = msg[2];\n\t\tlet type = msg[3];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = msg[4];\n\t\t\tlet pub = msg[5];\n\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = msg[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethod.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse {\n\t\t\t// It's presumably a 'method' or something else\n\t\t\tlet dataCopy = [...msg];\n\n\t\t\tlet route = dataCopy.shift();\n\t\t\tlet date = dataCopy.shift();\n\t\t\tlet msgId = dataCopy.shift();\n\t\t\tlet msgType = dataCopy.shift();\n\t\t\t\n\t\t\tif (msgType === 'method') {\n\t\t\t\tlet methodName = dataCopy.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (methodName !== 'reportBuilderGetResults' && methodName !== 'reportBuilderGetDistinctValue' && methodName !== 'reportBuilderBuildTree' && methodName !== 'generatePDF' && methodName !== 'getWOOfflineData' && methodName !== 'countQuery' && methodName !== 'countWithQuery' && methodName !== 'countCollectionWithQuery' && methodName !== 'find' && methodName !== 'findOne' && methodName !== 'findWithOptions' && methodName !== 'getDrivers' && methodName !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(dataCopy)) < 200000 ? JSON.stringify(dataCopy, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(dataCopy)) < 200000 ? JSON.stringify(dataCopy, null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Immediately ACK\n\t\t\t\tlet ack: ServerResponseModel = {\n\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, ack);\n\t\t\t\t}\n\n\t\t\t\t// Check if we can offload to a worker\n\t\t\t\tlet worker = this.findAvailableWorker();\n\t\t\t\tif (this._isWorkersEnabled && \n\t\t\t\t\tworker &&\n\t\t\t\t\tmethodName !== 'find' &&\n\t\t\t\t\tmethodName !== 'insertDocument' &&\n\t\t\t\t\tmethodName !== 'countWithQuery' &&\n\t\t\t\t\tmethodName !== 'findOne' &&\n\t\t\t\t\tmethodName !== 'updateDocumentProps' &&\n\t\t\t\t\tmethodName !== 'findWithOptions' &&\n\t\t\t\t\tmethodName !== 'updateDocument' &&\n\t\t\t\t\tmethodName !== 'insertErrorLog' &&\n\t\t\t\t\tmethodName !== 'removeDocument' &&\n\t\t\t\t\tmethodName !== 'supportCreateBillingUser' &&\n\t\t\t\t\tmethodName !== 'getSignedUrl' &&\n\t\t\t\t\tmethodName !== 'getSignedUrls' &&\n\t\t\t\t\tmethodName !== 'getSignedUrlWithId' &&\n\t\t\t\t\tmethodName !== 'incorrectUser' &&\n\t\t\t\t\tmethodName !== 'reloadWS' &&\n\t\t\t\t\tmethodName !== 'reconnectWS' &&\n\t\t\t\t\tmethodName !== 'disconnectWS'\n\t\t\t\t) {\n\t\t\t\t\t// Offload to a worker\n\t\t\t\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\t\t\t\t// Store correlation so when worker finishes, we can respond\n\t\t\t\t\tthis._inFlightRequests[taskId] = {\n\t\t\t\t\t\tws,\n\t\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\t\tmethod: methodName\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.queueTask(taskId, methodName, dataCopy, {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// No worker available: do method locally\n\t\t\t\t\tthis.callMethodLocally(ws, msgId, methodName, dataCopy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * callMethodLocally is your old approach for invoking the method in-process.\n\t */\n\tprivate async callMethodLocally(ws: WebSocket, messageId: number, method: string, params: any[]) {\n\t\tlet serverRes: ServerResponseModel = {\n\t\t\tmessageId: messageId,\n\t\t\thasError: false,\n\t\t\tdata: null\n\t\t};\n\n\t\ttry {\n\t\t\t// You can keep your logging code (LogMethodLatencies, Logs.insertOne, etc.)\n\t\t\tlet result = await this._methodManager.callMethod.call(\n\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t}),\n\t\t\t\tmethod,\n\t\t\t\t...params\n\t\t\t);\n\n\t\t\tserverRes.data = result;\n\t\t}\n\t\tcatch (err) {\n\t\t\tserverRes.hasError = true;\n\t\t\tserverRes.data = err.message || 'Unknown error';\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t}\n\t}\n\n\t/**\n\t * Add a new task to our in-memory queue and try to dispatch.\n\t */\n\tprivate queueTask(taskId: string, method: string, params: any[], userContext?: { id_user?: string; user?: string; id_ws?: string }) {\n\t\tthis._taskQueue.push({\n\t\t\ttaskId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tuserContext\n\t\t});\n\t\tthis.dispatchQueue();\n\t}\n\n\t/**\n\t * The main loop that assigns tasks from _taskQueue to any worker that has capacity.\n\t */\n\tprivate dispatchQueue() {\n\t\tif (!this._taskQueue.length) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Try to assign tasks while we have them\n\t\tfor (let i = 0; i < 9999; i++) {\n\t\t\tlet item = this._taskQueue[0];\n\t\t\tif (!item) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet w = this.findAvailableWorker();\n\t\t\tif (!w) {\n\t\t\t\tbreak; // no worker can take more tasks\n\t\t\t}\n\n\t\t\t// Remove from queue\n\t\t\tthis._taskQueue.shift();\n\t\t\tthis.assignTaskToWorker(w, item);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency. Or null if none.\n\t */\n\tprivate findAvailableWorker(): WorkerConnection | null {\n\t\tlet candidates = this._workers.filter(x => x.activeTasks < x.maxConcurrency);\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sort by how busy they are\n\t\tcandidates.sort((a, b) => a.activeTasks - b.activeTasks);\n\t\treturn candidates[0];\n\t}\n\n\tprivate assignTaskToWorker(worker: WorkerConnection, task: TaskQueueItem) {\n\t\tworker.activeTasks++;\n\n\t\tlet payload = {\n\t\t\ttype: 'task',\n\t\t\ttaskId: task.taskId,\n\t\t\tmethod: task.method,\n\t\t\tparams: task.params,\n\t\t\tuserContext: task.userContext\n\t\t};\n\n\t\ttry {\n\t\t\tworker.ws.send(JSON.stringify(payload));\n\t\t\t// console.log('Assigned task', task.taskId, 'to worker', worker.id);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to send task to worker:', err);\n\t\t\tworker.activeTasks = Math.max(0, worker.activeTasks - 1);\n\t\t\t// Put task back at front\n\t\t\tthis._taskQueue.unshift(task);\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages coming back from a worker (like 'taskComplete').\n\t */\n\tprivate handleWorkerMessage(workerId: string, messageStr: string) {\n\t\tlet data: any;\n\t\ttry {\n\t\t\tdata = JSON.parse(messageStr, dateReviver);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to parse worker message:', messageStr);\n\t\t\treturn;\n\t\t}\n\n\t\tif (data.type === 'taskComplete') {\n\t\t\tlet w = this._workers.find(x => x.id === workerId);\n\t\t\tif (!w) {\n\t\t\t\tconsole.error('Unknown worker for taskComplete:', workerId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tw.activeTasks = Math.max(0, w.activeTasks - 1);\n\n\t\t\tlet { taskId, error, message, result } = data;\n\n\t\t\t// Look up original request\n\t\t\tlet inflight = this._inFlightRequests[taskId];\n\t\t\tif (!inflight) {\n\t\t\t\tconsole.error('No in-flight request found for task:', taskId);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdelete this._inFlightRequests[taskId];\n\n\t\t\t\t// Send the final response to the client\n\t\t\t\tlet res: ServerResponseModel = {\n\t\t\t\t\tmessageId: inflight.messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: result\n\t\t\t\t};\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.hasError = true;\n\t\t\t\t\tres.data = message;\n\t\t\t\t}\n\n\t\t\t\tif (inflight.ws && inflight.ws.readyState === inflight.ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(inflight.ws, res);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to dispatch more from the queue\n\t\t\tthis.dispatchQueue();\n\t\t}\n\t}\n\n\t/**\n\t * Cleanly remove a client from the subscription manager, etc.\n\t */\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","user_collection_1","home_1","auth_1","health_1","mongodb_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","_runningTasks","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_workers","_taskQueue","_inFlightRequests","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","prototype","initServerApp","_this","initServerFlag","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","setTimeout","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","wsUrl","connect","ws","lastComm","interval","WORKER_INDEX","NODE_APP_INSTANCE","sendWorkerResponse","rawData","toString","msg","parse","e","type","handleIncomingTask","clearInterval","err","data","taskId","method","params","userContext","push","timedOut","timeoutHandle","managerThis","Object","assign","id_user","user","id_ws","callMethod","call","apply","__spreadArray","__read","result","_b","clearTimeout","filter","a","err_1","payload","readyState","OPEN","send","getActiveMonitorFunctions","length","setImmediate","getMongoConnection","then","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","url","includes","urlParts","split","infoData","headers","origin","token","verify","decoded","Users","findById","fullname","readonly","workerId_1","interval_1","lastComm_1","objectIdHexString","id","activeTasks","maxConcurrency","handleWorkerMessage","w","addWebSocket","createLoggedInUser","unsubscribeWS","socketData","processSocketMessage","now","getTime","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","__values","socketData_1_1","value","handleClientMessage","messageRoute","messageDate","messageId","some","roles","groups","views","b","super_admin","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","serverResMethod","getLocalLogManager","writeLog","_id","createdAt","collection","id_document","getBinarySize","route","Logs","insertOne","client","instance","_methods","err_3","getMongoManager","invalidateQueryCache","splice","map","indexOf","dataCopy","msgId","methodName","ack","worker","findAvailableWorker","queueTask","callMethodLocally","err_4","dispatchQueue","item","assignTaskToWorker","candidates","x","sort","task","Math","max","unshift","workerId","messageStr","inflight","find","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,Q,0FAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EACAM,OAAAN,QAAA,iBAAA,EAEAO,SAAAP,QAAA,eAAA,EACAQ,eAAAR,QAAA,yBAAA,EACAS,iBAAAT,QAAA,2BAAA,EACAU,uBAAAV,QAAA,iCAAA,EACAW,kBAAAX,QAAA,4BAAA,EAEAY,iBAAAZ,QAAA,8BAAA,EACAa,kBAAAb,QAAA,+BAAA,EAEAc,OAAAd,QAAA,aAAA,EACAe,OAAAf,QAAA,aAAA,EACAgB,SAAAhB,QAAA,eAAA,EACAiB,UAAAjB,QAAA,SAAA,EAEAkB,oBAAAlB,QAAA,8BAAA,EACAmB,uBAAAnB,QAAA,wBAAA,EAsBAoB,oBAAA,WAsCC,SAAAA,sBAhCQC,KAAAC,gBAAkB,GACnBD,KAAAE,QAAU,CAAA,EACTF,KAAAG,gBAAkB,CAAA,EAClBH,KAAAI,cAAgB,CAAA,EAChBJ,KAAAK,YAAc,CAAA,EACdL,KAAAM,cAAgB,GAEhBN,KAAAO,OAAS,QAQTP,KAAAQ,cAA0B,GAG1BR,KAAAS,cAAsB,KAEtBT,KAAAU,cAAgB,EAChBV,KAAAW,eAAiB,EAEjBX,KAAAY,kBAAoB,CAAA,EACpBZ,KAAAa,kBAAoB,CAAA,EAEpBb,KAAAc,cAAgB,CAAA,EAEhBd,KAAAe,SAA+B,GAC/Bf,KAAAgB,WAA8B,GAC9BhB,KAAAiB,kBAA2D,GAGlEjB,KAAKkB,iBAAmB,IAAIC,KAC5BnB,KAAKS,cAAgB,KACrBT,KAAKoB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7D,EAKOvQ,oBAAAyB,UAAAmK,cAAP,SAAqB9F,GAChB7F,KAAKiC,sBAAwBjC,KAAKiC,qBAAqBC,eAAc,GACxEC,QAAQC,IAAI,IAAIjB,KAAQ,aAAc,WAAY0E,EAAS,KAAGA,EAAc,SAAC,EAE9E7F,KAAKiC,qBAAqByO,eAAe7K,CAAE,EAC3CA,EAAG8K,mBAAkB,CAEtB,EAEO5Q,oBAAAyB,UAAAoP,OAAP,WACC,OAAO5Q,KAAKsE,IACb,EAEOvE,oBAAAyB,UAAAwB,gBAAP,WACC,OAAOlD,uBAAAiD,gBAAgBC,gBAAe,CACvC,EACDjD,mBAAA,EAAC,EA5rCY8Q,QAAA9Q,oBAAAA","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { MongoNetworkTimeoutError } from 'mongodb';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\ninterface WorkerConnection {\n\tid: string;\n\tws: WebSocket;\n\tactiveTasks: number;\n\tmaxConcurrency: number;\n}\n\ninterface TaskQueueItem {\n\ttaskId: string;\n\tmethod: string;\n\tparams: any[];\n\tuserContext?: { id_user?: string; user?: string; id_ws?: string };\n}\n\ninterface InFlightRequest {\n\tws: WebSocket; // the client's WebSocket\n\tmessageId: number; // the ID so the client knows which call this corresponds to\n\tmethod: string;\n}\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\tprivate _runningTasks = [];\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tprivate _workers: WorkerConnection[] = [];\n\tprivate _taskQueue: TaskQueueItem[] = [];\n\tprivate _inFlightRequests: { [taskId: string]: InFlightRequest } = {};\n\n\tconstructor() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\t}\n\n\tinitServerApp() {\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tlet initServerFlag = false;\n\n\t\tsetTimeout(() => {\n\t\t\tinitServerFlag = true;\n\t\t}, 5000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tif (error && error['name'] === 'MongoServerError' && !initServerFlag) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\tif (this._isWorkersEnabled) {\n\t\t\tif (this._isWorkerInstance) {\n\t\t\t\tconsole.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._cronManager = new CronManager();\n\t\t\t\tthis.startWorkerInstance();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n\t\t\tthis.startServerInstance();\n\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\tthis._cronManager = new CronManager();\n\t\t\tthis.listen();\n\t\t}\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || ResolveIOServer.getServerConfig()['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || ResolveIOServer.getServerConfig()['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app, ResolveIOServer.getServerConfig());\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async startWorkerInstance() {\n\t\tconsole.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');\n\n\t\tlet wsUrl = ResolveIOServer.getServerConfig()['SERVER_URL'] + '/websocket?workerToken=' + ResolveIOServer.getServerConfig()['WORKER_TOKEN'];\n\n\t\tconst connect = () => {\n\t\t\tconst ws = new WebSocket(wsUrl);\n\n\t\t\tlet lastComm = null;\n\t\t\tlet interval = null;\n\n\t\t\tws.on('open', () => {\n\t\t\t\tconsole.log(new Date(), 'Connected to main server as worker', process.env.WORKER_INDEX, process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\n\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t}\n\t\t\t\t}, 15000);\n\t\t\t});\n\n\t\t\tws.on('message', (rawData: any) => {\n\t\t\t\t// console.log(new Date(), 'Message Recv', rawData);\n\n\t\t\t\tif (typeof rawData !== 'string') {\n\t\t\t\t\trawData = rawData.toString();\n\t\t\t\t}\n\n\t\t\t\t// console.log(new Date(), 'String Message Recv', rawData);\n\n\t\t\t\tif (rawData === 'ping') {\n\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t}\n\t\t\t\telse if (rawData === 'pong') {\n\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\tlastComm = new Date();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet msg: any;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmsg = JSON.parse(rawData, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.error('Worker parse error', e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// We expect: { type: 'task', taskId, method, params, userContext? }\n\t\t\t\t\tif (msg.type === 'task') {\n\t\t\t\t\t\tthis.handleIncomingTask(ws, msg);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'Disconnected from main server. Reconnecting in 5s...');\n\t\t\t\tsetTimeout(connect, 5000);\n\n\t\t\t\tif (interval) {\n\t\t\t\t\tclearInterval(interval);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.on('error', (err) => {\n\t\t\t\tconsole.error(new Date(), 'Worker WS error:', err);\n\t\t\t\tws.close();\n\t\t\t});\n\t\t};\n\n\t\tconnect();\n\t}\n\n\tprivate async handleIncomingTask(ws: WebSocket, data: any) {\n\t\tlet { taskId, method, params, userContext } = data;\n\t\tthis._runningTasks.push(taskId);\n\t\tif (!taskId || !method) {\n\t\t\tconsole.log('Invalid task message received', data);\n\t\t\treturn;\n\t\t}\n\n\t\tlet timedOut = false;\n\t\tlet timeoutHandle = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tconsole.error('Worker timed out on task:', taskId);\n\n\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\ttype: 'taskComplete',\n\t\t\t\ttaskId,\n\t\t\t\terror: true,\n\t\t\t\tmessage: 'Task timed out'\n\t\t\t});\n\t\t}, 120000);\n\n\t\ttry {\n\t\t\tlet managerThis = Object.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\tid_user: userContext?.id_user || '',\n\t\t\t\tuser: userContext?.user || '',\n\t\t\t\tid_ws: userContext?.id_ws || ''\n\t\t\t});\n\n\t\t\tlet result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: false,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t\tcatch (err) {\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tconsole.error('Worker failed task:', taskId, err);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: true,\n\t\t\t\t\tmessage: err || 'Unknown error'\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t}\n\n\tprivate sendWorkerResponse(ws: WebSocket, payload: any) {\n\t\tif (typeof payload !== 'string') {\n\t\t\tpayload = JSON.stringify(payload);\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\ttry {\n\t\t\t\tws.send(payload);\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tconsole.error('Failed to send worker response:', err);\n\t\t\t}\n\t\t}\n\t\telse if (ws) {\n\t\t\tws.close();\n\t\t}\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length\n\t\t\t&& !this._offlineUpdates.length && !this._taskQueue.length && !this._runningTasks.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}, () => { process.exit(1); });\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), 'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000;\n\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : 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\t// If it's a worker, we might skip token checks or do a simple check:\n\t\t\t\t\tif (info.req.url && info.req.url.includes('workerToken=')) {\n\t\t\t\t\t\tlet urlParts = info.req.url.split('workerToken='); \n\t\t\t\t\t\tlet workerToken = urlParts[1] || '';\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\n\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tinfo.origin !== ResolveIOServer.getServerConfig()['ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']\n\t\t\t\t\t) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (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/**\n\t * Listen for connections from clients or workers.\n\t */\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t// It's a WORKER\n\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\tws['id_worker'] = workerId;\n\n\t\t\t\t// For demonstration, let each worker handle up to 2 tasks concurrently\n\t\t\t\tlet maxConcurrency = 2;\n\n\t\t\t\tthis._workers.push({\n\t\t\t\t\tid: workerId,\n\t\t\t\t\tws: ws,\n\t\t\t\t\tactiveTasks: 0,\n\t\t\t\t\tmaxConcurrency: maxConcurrency\n\t\t\t\t});\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tws.on('open', () => {\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\n\t\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\t\tws.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 15000);\n\t\t\t\t});\n\n\t\t\t\tconsole.log(new Date(), 'Worker connected:', workerId);\n\n\t\t\t\tws.on('message', (message: any) => {\n\t\t\t\t\t// console.log(new Date(), 'Message Recv', message);\n\n\t\t\t\t\tif (typeof message !== 'string') {\n\t\t\t\t\t\tmessage = message.toString();\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log(new Date(), 'String Message Recv', message);\n\n\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t\t}\n\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.handleWorkerMessage(workerId, message);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\tthis._workers = this._workers.filter(w => w.id !== workerId);\n\t\t\t\t\t\n\t\t\t\t\tif (interval) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error on WS Worker', error);\n\t\t\t\t\tws.close();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Normal client\n\t\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}, 5000);\n\t\t\t\t});\n\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Connection from user: ' + req['user']);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['retryCnt'] = 0;\n\n\t\t\t\tws.on('message', async (message: string) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\tthis._methodManager.sendEmail(\n\t\t\t\t\t\t\t'dev@resolveio.com', \n\t\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], \n\t\t\t\t\t\t\tJSON.stringify([message, e])\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// call our existing processSocketMessage\n\t\t\t\t\tthis.processSocketMessage(ws, socketData);\n\t\t\t\t})\n\t\t\t\t.on('end', () => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t})\n\t\t\t\t.on('close', () => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t})\n\t\t\t\t.on('error', error => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\t// Keep alive timer\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\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any) {\n\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tws.send('pong');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\tws['isAlive'] = true;\n\t\t\tws['pongTime'] = new Date();\n\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the top level is not an array, let's skip\n\t\tif (!Array.isArray(socketData[0])) {\n\t\t\tconsole.log('Invalid message format (expected array of arrays)', socketData);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle each sub-message\n\t\tfor (let message of socketData) {\n\t\t\tawait this.handleClientMessage(ws, message);\n\t\t}\n\t}\n\n\tprivate async handleClientMessage(ws: WebSocket, msg: any[]): Promise<void> {\n\t\t// This is basically your old logic from processSocketMessage,\n\t\t// but we'll insert our worker-queue logic for \"method\" calls.\n\n\t\tlet messageRoute = msg[0];\n\t\tlet messageDate = msg[1];\n\t\tlet messageId = msg[2];\n\t\tlet type = msg[3];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = msg[4];\n\t\t\tlet pub = msg[5];\n\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = msg[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethod.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse {\n\t\t\t// It's presumably a 'method' or something else\n\t\t\tlet dataCopy = [...msg];\n\n\t\t\tlet route = dataCopy.shift();\n\t\t\tlet date = dataCopy.shift();\n\t\t\tlet msgId = dataCopy.shift();\n\t\t\tlet msgType = dataCopy.shift();\n\t\t\t\n\t\t\tif (msgType === 'method') {\n\t\t\t\tlet methodName = dataCopy.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (methodName !== 'reportBuilderGetResults' && methodName !== 'reportBuilderGetDistinctValue' && methodName !== 'reportBuilderBuildTree' && methodName !== 'generatePDF' && methodName !== 'getWOOfflineData' && methodName !== 'countQuery' && methodName !== 'countWithQuery' && methodName !== 'countCollectionWithQuery' && methodName !== 'find' && methodName !== 'findOne' && methodName !== 'findWithOptions' && methodName !== 'getDrivers' && methodName !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(dataCopy)) < 200000 ? JSON.stringify(dataCopy, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(dataCopy)) < 200000 ? JSON.stringify(dataCopy, null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Immediately ACK\n\t\t\t\tlet ack: ServerResponseModel = {\n\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, ack);\n\t\t\t\t}\n\n\t\t\t\t// Check if we can offload to a worker\n\t\t\t\tlet worker = this.findAvailableWorker();\n\t\t\t\tif (this._isWorkersEnabled && \n\t\t\t\t\tworker &&\n\t\t\t\t\tmethodName !== 'find' &&\n\t\t\t\t\tmethodName !== 'insertDocument' &&\n\t\t\t\t\tmethodName !== 'countWithQuery' &&\n\t\t\t\t\tmethodName !== 'findOne' &&\n\t\t\t\t\tmethodName !== 'updateDocumentProps' &&\n\t\t\t\t\tmethodName !== 'findWithOptions' &&\n\t\t\t\t\tmethodName !== 'updateDocument' &&\n\t\t\t\t\tmethodName !== 'insertErrorLog' &&\n\t\t\t\t\tmethodName !== 'removeDocument' &&\n\t\t\t\t\tmethodName !== 'supportCreateBillingUser' &&\n\t\t\t\t\tmethodName !== 'getSignedUrl' &&\n\t\t\t\t\tmethodName !== 'getSignedUrls' &&\n\t\t\t\t\tmethodName !== 'getSignedUrlWithId' &&\n\t\t\t\t\tmethodName !== 'incorrectUser' &&\n\t\t\t\t\tmethodName !== 'reloadWS' &&\n\t\t\t\t\tmethodName !== 'reconnectWS' &&\n\t\t\t\t\tmethodName !== 'disconnectWS'\n\t\t\t\t) {\n\t\t\t\t\t// Offload to a worker\n\t\t\t\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\t\t\t\t// Store correlation so when worker finishes, we can respond\n\t\t\t\t\tthis._inFlightRequests[taskId] = {\n\t\t\t\t\t\tws,\n\t\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\t\tmethod: methodName\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.queueTask(taskId, methodName, dataCopy, {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// No worker available: do method locally\n\t\t\t\t\tthis.callMethodLocally(ws, msgId, methodName, dataCopy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * callMethodLocally is your old approach for invoking the method in-process.\n\t */\n\tprivate async callMethodLocally(ws: WebSocket, messageId: number, method: string, params: any[]) {\n\t\tlet serverRes: ServerResponseModel = {\n\t\t\tmessageId: messageId,\n\t\t\thasError: false,\n\t\t\tdata: null\n\t\t};\n\n\t\ttry {\n\t\t\t// You can keep your logging code (LogMethodLatencies, Logs.insertOne, etc.)\n\t\t\tlet result = await this._methodManager.callMethod.call(\n\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t}),\n\t\t\t\tmethod,\n\t\t\t\t...params\n\t\t\t);\n\n\t\t\tserverRes.data = result;\n\t\t}\n\t\tcatch (err) {\n\t\t\tserverRes.hasError = true;\n\t\t\tserverRes.data = err || 'Unknown error';\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t}\n\t}\n\n\t/**\n\t * Add a new task to our in-memory queue and try to dispatch.\n\t */\n\tprivate queueTask(taskId: string, method: string, params: any[], userContext?: { id_user?: string; user?: string; id_ws?: string }) {\n\t\tthis._taskQueue.push({\n\t\t\ttaskId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tuserContext\n\t\t});\n\t\tthis.dispatchQueue();\n\t}\n\n\t/**\n\t * The main loop that assigns tasks from _taskQueue to any worker that has capacity.\n\t */\n\tprivate dispatchQueue() {\n\t\tif (!this._taskQueue.length) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Try to assign tasks while we have them\n\t\tfor (let i = 0; i < 9999; i++) {\n\t\t\tlet item = this._taskQueue[0];\n\t\t\tif (!item) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet w = this.findAvailableWorker();\n\t\t\tif (!w) {\n\t\t\t\tbreak; // no worker can take more tasks\n\t\t\t}\n\n\t\t\t// Remove from queue\n\t\t\tthis._taskQueue.shift();\n\t\t\tthis.assignTaskToWorker(w, item);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency. Or null if none.\n\t */\n\tprivate findAvailableWorker(): WorkerConnection | null {\n\t\tlet candidates = this._workers.filter(x => x.activeTasks < x.maxConcurrency);\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sort by how busy they are\n\t\tcandidates.sort((a, b) => a.activeTasks - b.activeTasks);\n\t\treturn candidates[0];\n\t}\n\n\tprivate assignTaskToWorker(worker: WorkerConnection, task: TaskQueueItem) {\n\t\tworker.activeTasks++;\n\n\t\tlet payload = {\n\t\t\ttype: 'task',\n\t\t\ttaskId: task.taskId,\n\t\t\tmethod: task.method,\n\t\t\tparams: task.params,\n\t\t\tuserContext: task.userContext\n\t\t};\n\n\t\ttry {\n\t\t\tworker.ws.send(JSON.stringify(payload));\n\t\t\t// console.log('Assigned task', task.taskId, 'to worker', worker.id);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to send task to worker:', err);\n\t\t\tworker.activeTasks = Math.max(0, worker.activeTasks - 1);\n\t\t\t// Put task back at front\n\t\t\tthis._taskQueue.unshift(task);\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages coming back from a worker (like 'taskComplete').\n\t */\n\tprivate handleWorkerMessage(workerId: string, messageStr: string) {\n\t\tlet data: any;\n\t\ttry {\n\t\t\tdata = JSON.parse(messageStr, dateReviver);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to parse worker message:', messageStr);\n\t\t\treturn;\n\t\t}\n\n\t\tif (data.type === 'taskComplete') {\n\t\t\tlet w = this._workers.find(x => x.id === workerId);\n\t\t\tif (!w) {\n\t\t\t\tconsole.error('Unknown worker for taskComplete:', workerId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tw.activeTasks = Math.max(0, w.activeTasks - 1);\n\n\t\t\tlet { taskId, error, message, result } = data;\n\n\t\t\t// Look up original request\n\t\t\tlet inflight = this._inFlightRequests[taskId];\n\t\t\tif (!inflight) {\n\t\t\t\tconsole.error('No in-flight request found for task:', taskId);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdelete this._inFlightRequests[taskId];\n\n\t\t\t\t// Send the final response to the client\n\t\t\t\tlet res: ServerResponseModel = {\n\t\t\t\t\tmessageId: inflight.messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: result\n\t\t\t\t};\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.hasError = true;\n\t\t\t\t\tres.data = message;\n\t\t\t\t}\n\n\t\t\t\tif (inflight.ws && inflight.ws.readyState === inflight.ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(inflight.ws, res);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to dispatch more from the queue\n\t\t\tthis.dispatchQueue();\n\t\t}\n\t}\n\n\t/**\n\t * Cleanly remove a client from the subscription manager, etc.\n\t */\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n}"]}
|