@resolveio/server-lib 20.3.6 → 20.3.7

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 __awaiter=this&&this.__awaiter||function(e,r,n,s){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var s,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,i=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(r,c)}catch(e){t=[6,e],i=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,s=t.length;n<s;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},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"),method_response_collection_1=require("../collections/method-response.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),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"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}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,o,r,n,s){var i=this;this._methods={},this._sendQueue=[],this._runningQueue=!1,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this.serverConfig=t,this.clientDir=o,this._monitorManagerFunction=r,this._isWorkersEnabled=n,this._isWorkerInstance=s,(0,init_1.loadServerInit)(),(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,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?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:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),this._isWorkersEnabled&&!this._isWorkerInstance||(setInterval(function(){i._mainServer.getSubscriptionManager()&&i._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",i._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",i._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",i._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",i._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",i._debugCallMethodCronJobHits)),i._debugCallMethodInternalHits=0,i._debugCallMethodHits=0,i._debugCallMethodCronJobHits=0,i._debugSendQueueHits=0,i._debugSendQueueHits=0},6e4),setInterval(function(){if(!i._runningQueue&&i._sendQueue.length){i._runningQueue=!0;for(var e=i._sendQueue.length-1;0<=e;e--)!function(e){i._debugSendQueueHits+=1;var t,o=i._mainServer.getWS(i._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=i._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&i._mainServer.unsubscribeWS(o)}),"reportBuilderGetResults"!==t.method&&"reportBuilderGetDistinctValue"!==t.method&&"reportBuilderBuildTree"!==t.method&&"generatePDF"!==t.method&&"getWOOfflineData"!==t.method&&"countQuery"!==t.method&&"countWithQuery"!==t.method&&"countCollectionWithQuery"!==t.method&&"find"!==t.method&&"findOne"!==t.method&&"findWithOptions"!==t.method&&"uploadFileAndSave"!==t.method&&"getDrivers"!==t.method&&"processAirdropDistribution"!==t.method&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([t.methodData,t.data]))<2e5?JSON.stringify([t.methodData,t.data],null,2):"Too Big",method:t.method,id_user:o.id_user||"",user:o.user||"",messageId:t.data.messageId,route:""}),method_response_collection_1.MethodResponses.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,id_user:o.id_user||"",message_id:t.data.messageId,response:(0,common_1.getBinarySize)(JSON.stringify(t.data))<2e5?t.data:{error:"Too Big"},method:t.method,date:t.date})):i._sendQueue.splice(e,1)}(e);i._runningQueue=!1}},25))}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,o=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<r.length||r[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 - "+this.serverConfig.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 - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var s={},i=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<r.length;a++)s[i[a]]=r[a];try{this._methods[t].check.validate(s)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(s,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,d=null;return this._isWorkersEnabled&&!this._isWorkerInstance?(c=(0,mongo_manager_1.objectIdHexString)(),d=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":c}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:c,method:t,params:r,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(l=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],r,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(l),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(l),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),d}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,s,i,a){for(var e,t,o,c,l=this,d=[],h=5;h<arguments.length;h++)d[h-5]=arguments[h];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<d.length||d[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,s,a,d,u={messageId:i,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),u={messageId:i,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,s,a,d,u);for(var u,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),m=0;m<d.length;m++)_[g[m]]=d[m];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,s,a,d,u={messageId:i,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}this._isWorkersEnabled&&!this._isWorkerInstance?(t=(0,mongo_manager_1.objectIdHexString)(),console.log("Workers are enabled. Delegating task to worker.",t),(o=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":t}}],{fullDocument:"updateLookup"})).on("change",function(e){"insert"===e.operationType&&(e=e.fullDocument,console.log("Task response found",t,e.data),e={messageId:i,hasError:e.has_error,data:e.data},l.sendWS(n,s,a,d,e),console.log("Sent on WS",s,a,d,e),o.close())}),o.on("error",function(e){console.error("Error watching worker responses:",e),o.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:t,method:a,params:d,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",d),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],d,!1)).then(function(o){return __awaiter(l,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(c),t={messageId:i,hasError:!1,data:o},this.sendWS(n,s,a,d,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){l._monitorManagerFunction.finishMonitorFunction(c),l.sendWS(n,s,a,d,{messageId:i,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"processAirdropDistribution"!==a&&l.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+l.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(d,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),this.sendWS(n,s,a,d,u={messageId:i,hasError:!0,data:"Internal Error"}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,o=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<r.length||r[0]&&"function"!=typeof r[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&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r]))<2e5?JSON.stringify([r],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var s,i,a="function"==typeof r[r.length-1]?r.slice(0,-1):r,c=null;return this._isWorkersEnabled&&!this._isWorkerInstance?(s=(0,mongo_manager_1.objectIdHexString)(),c=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:a,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),c=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],a,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(i),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(i),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),r[r.length-1]&&"function"==typeof r[r.length-1]&&c.then(function(e){return r[r.length-1](null,e)},function(e){return r[r.length-1](e,null)}),c},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:r,data:n,date:t})},MethodManager.prototype.sendEmail=function(r,n,s,i,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:s,html:i,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,s,i,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,s){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var s,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,i=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(r,c)}catch(e){t=[6,e],i=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,s=t.length;n<s;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},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"),method_response_collection_1=require("../collections/method-response.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),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"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}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,o,r,n,s){var i=this;this._methods={},this._sendQueue=[],this._runningQueue=!1,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this.serverConfig=t,this.clientDir=o,this._monitorManagerFunction=r,this._isWorkersEnabled=n,this._isWorkerInstance=s,(0,init_1.loadServerInit)(),(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,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?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:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){i._mainServer.getSubscriptionManager()&&i._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",i._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",i._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",i._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",i._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",i._debugCallMethodCronJobHits)),i._debugCallMethodInternalHits=0,i._debugCallMethodHits=0,i._debugCallMethodCronJobHits=0,i._debugSendQueueHits=0,i._debugSendQueueHits=0},6e4),setInterval(function(){if(!i._runningQueue&&i._sendQueue.length){i._runningQueue=!0;for(var e=i._sendQueue.length-1;0<=e;e--)!function(e){i._debugSendQueueHits+=1;var t,o=i._mainServer.getWS(i._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=i._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&i._mainServer.unsubscribeWS(o)}),"reportBuilderGetResults"!==t.method&&"reportBuilderGetDistinctValue"!==t.method&&"reportBuilderBuildTree"!==t.method&&"generatePDF"!==t.method&&"getWOOfflineData"!==t.method&&"countQuery"!==t.method&&"countWithQuery"!==t.method&&"countCollectionWithQuery"!==t.method&&"find"!==t.method&&"findOne"!==t.method&&"findWithOptions"!==t.method&&"uploadFileAndSave"!==t.method&&"getDrivers"!==t.method&&"processAirdropDistribution"!==t.method&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([t.methodData,t.data]))<2e5?JSON.stringify([t.methodData,t.data],null,2):"Too Big",method:t.method,id_user:o.id_user||"",user:o.user||"",messageId:t.data.messageId,route:""}),method_response_collection_1.MethodResponses.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,id_user:o.id_user||"",message_id:t.data.messageId,response:(0,common_1.getBinarySize)(JSON.stringify(t.data))<2e5?t.data:{error:"Too Big"},method:t.method,date:t.date})):i._sendQueue.splice(e,1)}(e);i._runningQueue=!1}},1)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,o=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<r.length||r[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 - "+this.serverConfig.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 - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var s={},i=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<r.length;a++)s[i[a]]=r[a];try{this._methods[t].check.validate(s)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(s,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,d=null;return this._isWorkersEnabled&&!this._isWorkerInstance?(c=(0,mongo_manager_1.objectIdHexString)(),d=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":c}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:c,method:t,params:r,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(l=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],r,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(l),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(l),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),d}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,s,i,a){for(var e,t,c,l=this,d=[],o=5;o<arguments.length;o++)d[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<d.length||d[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,s,a,d,h={messageId:i,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),h={messageId:i,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,s,a,d,h);for(var h,u={},_=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),g=0;g<d.length;g++)u[_[g]]=d[g];try{this._methods[a].check.validate(u)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(u,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,s,a,d,h={messageId:i,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}this._isWorkersEnabled&&!this._isWorkerInstance?(e=(0,mongo_manager_1.objectIdHexString)(),(t=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(e){"insert"===e.operationType&&(e=e.fullDocument,e={messageId:i,hasError:e.has_error,data:e.data},l.sendWS(n,new Date,a,d,e),t.close())}),t.on("error",function(e){console.error("Error watching worker responses:",e),t.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:d,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",d),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],d,!1)).then(function(o){return __awaiter(l,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(c),t={messageId:i,hasError:!1,data:o},this.sendWS(n,s,a,d,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){l._monitorManagerFunction.finishMonitorFunction(c),l.sendWS(n,s,a,d,{messageId:i,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"processAirdropDistribution"!==a&&l.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+l.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(d,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),h={messageId:i,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,d,h),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,o=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<r.length||r[0]&&"function"!=typeof r[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&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r]))<2e5?JSON.stringify([r],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var s,i,a="function"==typeof r[r.length-1]?r.slice(0,-1):r,c=null;return this._isWorkersEnabled&&!this._isWorkerInstance?(s=(0,mongo_manager_1.objectIdHexString)(),c=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:a,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),c=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],a,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(i),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(i),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),r[r.length-1]&&"function"==typeof r[r.length-1]&&c.then(function(e){return r[r.length-1](null,e)},function(e){return r[r.length-1](e,null)}),c},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:r,data:n,date:t})},MethodManager.prototype.sendEmail=function(r,n,s,i,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:s,html:i,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,s,i,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(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","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_sendQueue","_runningQueue","_isWorkersEnabled","_isWorkerInstance","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","length","i","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","JSON","stringify","data","error","unsubscribeWS","method","Logs","insertOne","_id","objectIdHexString","type","collection","id_document","payload","getBinarySize","methodData","id_user","messageId","route","MethodResponses","create","__v","message_id","response","date","splice","getMainServer","methods","Object","assign","callMethodCron","_i","arguments","skipValidation","check","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","validate","errors","taskId_1","monitor_2","promise","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","taskResponse","has_error","close","WorkerTaskRequests","params","status","startMonitorFunction","_a","function","call","apply","__spreadArray","then","res","finishMonitorFunction","methodErrs","callMethod","id_methodLatency","messageDate","taskId_2","changeStream_1","monitor_3","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","taskId_3","monitor_4","functionMethodData","slice","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"wqDACAA,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,6BAAAd,QAAA,2CAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,iBAAAhB,QAAA,+BAAA,EAEAiB,gCAAAjB,QAAA,8CAAA,EACAkB,OAAAlB,QAAA,iBAAA,EACAmB,iBAAAnB,QAAA,2BAAA,EACAoB,UAAApB,QAAA,oBAAA,EACAqB,UAAArB,QAAA,oBAAA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,EAAG,QAAS,SAAC7B,EAAKxB,GAC5EwB,EACH/C,EAAO+C,CAAG,EAGVhD,EAAQwB,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEOvI,cAAAd,UAAA8M,UAAP,SAAiBJ,GAAjB,IAAArL,EAAAzB,KACC,OAAO,IAAIgI,QAAQ,SAACC,EAASC,GACxBzJ,GAAGsO,WAAWvO,KAAKwO,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjErO,GAAGoO,SAASrO,KAAKwO,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAAC7B,EAAKxB,GACzEwB,EACH/C,EAAO+C,CAAG,EAGVhD,EAAQwB,CAAG,CAEb,CAAC,EAGGhL,GAAGsO,WAAWvO,KAAKwO,KAAKvL,EAAKJ,UAAY,aAAeyL,CAAS,CAAC,GACrErO,GAAGoO,SAASrO,KAAKwO,KAAKvL,EAAKJ,UAAY,aAAeyL,CAAS,EAAG,SAAU,SAAC7B,EAAKxB,GAC7EwB,EACH/C,EAAO+C,CAAG,EAGVhD,EAAQwB,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDvI,aAAA,EAAC,GAlqBYC,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 { MethodResponses } from '../collections/method-response.collection';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WorkerTaskRequests } from '../collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from '../collections/worker-task-response.collection';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\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 _mainServer: ResolveIOMainServer;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._mainServer = mainServer;\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\t// Fixtures\n\t\tloadServerInit();\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\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\n\n\t\tif (mainServer.sesMail) {\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: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['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: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['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\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tsetInterval(() => {\n\t\t\t\tif (this._mainServer.getSubscriptionManager() && this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t\t}\n\n\t\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\t\tthis._debugCallMethodHits = 0;\n\t\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\t\tthis._debugSendQueueHits = 0;\n\t\t\t\tthis._debugSendQueueHits = 0;\n\t\t\t}, 60000);\n\n\t\t\tsetInterval(() => {\n\t\t\t\tif (!this._runningQueue) {\n\t\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tdate: sendItem.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\telse {\n\t\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, 25);\n\t\t}\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\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 - ' + this.serverConfig['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 - ' + this.serverConfig['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 - ' + this.serverConfig['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 - ' + this.serverConfig['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\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && !this._isWorkerInstance) {\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t}, methodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['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\t\treturn methodErrs;\n\t\t\t});\n\t\t}\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\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 - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\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 - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\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 - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\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\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['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\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\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\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && !this._isWorkerInstance) {\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\t\t\tconsole.log('Workers are enabled. Delegating task to worker.', taskId);\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\tconsole.log('Task response found', taskId, taskResponse.data);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\tconsole.log('Sent on WS', messageDate, method, methodData, serverRes);\n\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, err => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\t\t\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') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\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\tif (this._isWorkersEnabled && !this._isWorkerInstance) {\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: functionMethodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t}, methodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\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._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + 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}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\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\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\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(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./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(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./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","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_sendQueue","_runningQueue","_isWorkersEnabled","_isWorkerInstance","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","length","i","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","JSON","stringify","data","error","unsubscribeWS","method","Logs","insertOne","_id","objectIdHexString","type","collection","id_document","payload","getBinarySize","methodData","id_user","messageId","route","MethodResponses","create","__v","message_id","response","date","splice","getMainServer","methods","Object","assign","callMethodCron","_i","arguments","skipValidation","check","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","validate","errors","taskId_1","monitor_2","promise","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","taskResponse","has_error","close","WorkerTaskRequests","params","status","startMonitorFunction","_a","function","call","apply","__spreadArray","then","res","finishMonitorFunction","methodErrs","callMethod","id_methodLatency","messageDate","taskId","changeStream_1","monitor_3","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","taskId_2","monitor_4","functionMethodData","slice","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName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/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 { MethodResponses } from '../collections/method-response.collection';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WorkerTaskRequests } from '../collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from '../collections/worker-task-response.collection';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\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 _mainServer: ResolveIOMainServer;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._mainServer = mainServer;\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\t// Fixtures\n\t\tloadServerInit();\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\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\n\n\t\tif (mainServer.sesMail) {\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: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['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: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['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 (this._mainServer.getSubscriptionManager() && this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\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._debugCallMethodInternalHits);\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._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\tdate: sendItem.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\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1);\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\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 - ' + this.serverConfig['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 - ' + this.serverConfig['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 - ' + this.serverConfig['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 - ' + this.serverConfig['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\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && !this._isWorkerInstance) {\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t}, methodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['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\t\treturn methodErrs;\n\t\t\t});\n\t\t}\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\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 - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\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 - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\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 - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\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\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['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\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\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\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && !this._isWorkerInstance) {\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\t\t\t// console.log('Workers are enabled. Delegating task to worker.', taskId);\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t// console.log('Task response found', taskId, taskResponse.data);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\t// console.log('Sent on WS', ws['id_socket'], new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, err => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\t\t\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') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\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\tif (this._isWorkersEnabled && !this._isWorkerInstance) {\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: functionMethodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t}, methodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\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._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + 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}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\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\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\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(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./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(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./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,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,n,o,s){return new(o=o||Promise)(function(t,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s.throw(e))}catch(e){i(e)}}function step(e){var i;e.done?t(e.value):((i=e.value)instanceof o?i:new o(function(e){e(i)})).then(fulfilled,rejected)}step((s=s.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var s,r,u,c={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]},a={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function verb(t){return function(e){var i=[t,e];if(s)throw new TypeError("Generator is already executing.");for(;c=a&&i[a=0]?0:c;)try{if(s=1,r&&(u=2&i[0]?r.return:i[0]?r.throw||((u=r.return)&&u.call(r),0):r.next)&&!(u=u.call(r,i[1])).done)return u;switch(r=0,(i=u?[2&i[0],u.value]:i)[0]){case 0:case 1:u=i;break;case 4:return c.label++,{value:i[1],done:!1};case 5:c.label++,r=i[1],i=[0];continue;case 7:i=c.ops.pop(),c.trys.pop();continue;default:if(!(u=0<(u=c.trys).length&&u[u.length-1])&&(6===i[0]||2===i[0])){c=0;continue}if(3===i[0]&&(!u||i[1]>u[0]&&i[1]<u[3]))c.label=i[1];else if(6===i[0]&&c.label<u[1])c.label=u[1],u=i;else{if(!(u&&c.label<u[2])){u[2]&&c.ops.pop(),c.trys.pop();continue}c.label=u[2],c.ops.push(i)}}i=o.call(n,c)}catch(e){i=[6,e],r=0}finally{s=u=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,i,t){if(t||2===arguments.length)for(var n,o=0,s=i.length;o<s;o++)!n&&o in i||((n=n||Array.prototype.slice.call(i,0,o))[o]=i[o]);return e.concat(n||Array.prototype.slice.call(i))},logs_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0,require("../publications/logs")),app_status_1=require("../publications/app-status"),files_1=require("../publications/files"),super_admin_1=require("../publications/super-admin"),logged_in_users_collection_1=require("../collections/logged-in-users.collection"),cron_jobs_1=require("../publications/cron-jobs"),flags_1=require("../publications/flags"),method_responses_1=require("../publications/method-responses"),index_1=require("../index"),notifications_1=require("../publications/notifications"),report_builder_reports_1=require("../publications/report-builder-reports"),report_builder_libraries_1=require("../publications/report-builder-libraries"),user_groups_1=require("../publications/user-groups"),user_guides_1=require("../publications/user-guides"),report_builder_dashboard_builders_1=require("../publications/report-builder-dashboard-builders"),mongo_manager_1=require("./mongo.manager"),common_1=require("../util/common"),NodeCache=require("node-cache"),flag_collection_1=require("../collections/flag.collection"),os_1=require("os"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(e,i,t,n){var o=this;this._publications={},this._subscriptions=[],this._loggedInUsers=[],this._mongoQueue=[],this._mongoQueueId=0,this._sendQueue=[],this._runningQueue=!1,this._cacheId=1,this._heapStats=v8.getHeapStatistics(),this._heapLimit=this._heapStats.heap_size_limit/numCPUs/8,this._enableDebug=!1,this._debugOplogCollections=[],this._debugOplogHits=0,this._debugSubCollections=[],this._debugSubHits=0,this._debugUnSubHits=0,this._debugUnSubAllHits=0,this._debugMongoQueueHits=0,this._debugMongoQueueCollections=[],this._debugSendQueueHits=0,this._debugRemoveCacheHits=0,this._oplogRetryCount=0,this._mainServer=e,this._monitorManagerFunction=n,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),this.serverConfig=t,this._wss=i,(0,super_admin_1.loadSuperAdminPublications)(this),(0,app_status_1.loadAppStatusPublications)(this),(0,logs_1.loadLogPublications)(this),(0,files_1.loadFilePublications)(this),(0,cron_jobs_1.loadCronJobPublications)(this),(0,flags_1.loadFlagsPublications)(this),(0,method_responses_1.loadMethodResponsePublications)(this),(0,notifications_1.loadNotificationPublications)(this),(0,report_builder_reports_1.loadReportBuilderReportPublications)(this),(0,report_builder_libraries_1.loadReportBuilderLibraryPublications)(this),(0,user_groups_1.loadUserGroupPublications)(this),(0,user_guides_1.loadUserGuidePublications)(this),(0,report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this),this.tailOpLog(),setInterval(function(){o._oplogRetryCount=0},15e3),setInterval(function(){o.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",o._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",o._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",o._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",o._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(o._debugMongoQueueCollections.sort(function(e,i){return e.collection.localeCompare(i.collection)||e.publication.localeCompare(i.publication)}),null,2)),console.log(new Date,"Sub Manager","Oplog Hits",o._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(o._debugOplogCollections.sort(function(e,i){return e.collection.localeCompare(i.collection)||e.type.localeCompare(i.type)}),null,2)),console.log(new Date,"Sub Manager","Send Queue Hits",o._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",o._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(o._debugSubCollections.sort(function(e,i){return e.publication.localeCompare(i.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",o._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",o._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",o._debugRemoveCacheHits)),o._debugOplogHits=0,o._debugOplogCollections=[],o._debugSubCollections=[],o._debugMongoQueueHits=0,o._debugMongoQueueCollections=[],o._debugSendQueueHits=0,o._debugSubHits=0,o._debugUnSubHits=0,o._debugUnSubAllHits=0,o._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(o,void 0,void 0,function(){var i,n,o,t,s,r,u=this;return __generator(this,function(e){if(!this._runningQueue){if(this._runningQueue=!0,this._sendQueue.length)for(i=function(e){n._debugSendQueueHits+=1;var i,t=n._mainServer.getWS(n._sendQueue[e].id_ws);t&&t.readyState===t.OPEN?t.bufferedAmount<20480&&(i=n._sendQueue.pop(),t.send(JSON.stringify(i.data),function(e){e&&(u.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",t.user,t.id_socket,1),u.unsubscribeAll(t))})):n._sendQueue.splice(e,1)},r=(n=this)._sendQueue.length-1;0<=r;r--)i(r);if((o=this._mongoQueue.filter(function(e){return!e.running})).length)for(o.forEach(function(e){e.running=!0}),t=function(e){s._debugMongoQueueHits+=1;var t=o[e];if(s._debugMongoQueueCollections.some(function(e){return e.collection===t.collection&&e.publication===t.subscription.publication})?s._debugMongoQueueCollections.filter(function(e){return e.collection===t.collection&&e.publication===t.subscription.publication})[0].hits+=1:s._debugMongoQueueCollections.push({collection:t.collection,publication:t.subscription.publication,hits:1}),s._publications[t.subscription.publication].user_specific){for(var n=[],i=0;i<t.subscription.clients.length;i++)!function(e){var i=t.subscription.clients[e],e=s._mainServer.getWS(i.id_socket);e&&e.id_socket===i.id_socket&&n.push(s.sendDataToOne(e,i.messageId,t.subscription,t.type,t.collection).catch(function(e){return u._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+u.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - User Specific - Socket: "+i.id_socket+", User: "+i.id_user+", MessageId: "+i.messageId+", Pub: "+t.subscription.publication+", Err: "+JSON.stringify(e,null,2)),null}))}(i);Promise.all(n).then(function(){t.run_again?(t.running=!1,t.run_again=!1):0<=u._mongoQueue.map(function(e){return e._id}).indexOf(t._id)&&u._mongoQueue.splice(u._mongoQueue.map(function(e){return e._id}).indexOf(t._id),1)})}else s.sendDataToAll(t).then(function(){t.run_again?(t.running=!1,t.run_again=!1):0<=u._mongoQueue.map(function(e){return e._id}).indexOf(t._id)&&u._mongoQueue.splice(u._mongoQueue.map(function(e){return e._id}).indexOf(t._id),1)},function(){0<=u._mongoQueue.map(function(e){return e._id}).indexOf(t._id)&&u._mongoQueue.splice(u._mongoQueue.map(function(e){return e._id}).indexOf(t._id),1)})},s=this,r=o.length-1;0<=r;r--)t(r);this._runningQueue=!1}return[2]})})},25),setInterval(function(){return __awaiter(o,void 0,void 0,function(){var i,n,t,o,s,r,u,c,a;return __generator(this,function(e){switch(e.label){case 0:return i=this,[4,logged_in_users_collection_1.LoggedInUsers.find()];case 1:for(i._loggedInUsers=e.sent(),n=(0,common_1.deepCopy)(this._loggedInUsers),t=function(e){var t=n[e];(!t.date||12e4<Date.now()-t.date.getTime())&&(o._mainServer.getWS(t.id_ws)?(o.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",o._mainServer.getWS(t.id_ws).user,o._mainServer.getWS(t.id_ws).id_socket,2),o.unsubscribeAll(o._mainServer.getWS(t.id_ws))):(o._subscriptions.forEach(function(e){for(var i=e.clients.length-1;0<=i;i--)e.clients[i].id_socket===t.id_ws&&e.clients.splice(i,1)}),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:t._id}),0<=o._loggedInUsers.findIndex(function(e){return e._id===t._id})&&o._loggedInUsers.splice(o._loggedInUsers.findIndex(function(e){return e._id===t._id}),1)))},s=(o=this)._loggedInUsers.length-1;0<=s;s--)t(s);for(s=0;s<this._subscriptions.length;s++)for(r=this._subscriptions[s],u=function(e){var i=r.clients[e];c._loggedInUsers.some(function(e){return e.id_ws===i.id_socket})||r.clients.splice(e,1)},c=this,a=r.clients.length-1;0<=a;a--)u(a);return[2]}})})},3e4),flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?o._enableDebug=!0:o._enableDebug=!1})}return SubscriptionManager.prototype.addToQueue=function(i){var e=this._mongoQueue.filter(function(e){return e.subscription.publication===i.subscription.publication&&JSON.stringify(e.subscription.subscriptionData)===JSON.stringify(i.subscription.subscriptionData)})[0];e?e.running&&(e.run_again=!0):(i._id=this._mongoQueueId,this._mongoQueueId+=1,this._mongoQueue.splice(0,0,i))},SubscriptionManager.prototype.invalidatePubsCache=function(i,e){index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i);for(var t=this._subscriptions.filter(function(e){return e.collections.includes(i)}),n=t.length-1;0<=n;n--){var o=t[n];this.addToQueue({_id:0,type:e,collection:i,subscription:o,running:!1,run_again:!1})}},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(i){var t=this,e=this._loggedInUsers.filter(function(e){return e.id_ws===i.id_socket})[0];e&&(e.date=new Date,logged_in_users_collection_1.LoggedInUsers.updateOne({id_ws:i.id_socket},{$set:{latency:i.latency,date:e.date}}).then(function(e){e||(t.unsubscribeAll(i),t.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",i.user,i.id_socket,3))},function(){t.unsubscribeAll(i),t.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",i.user,i.id_socket,4)}))},SubscriptionManager.prototype.subscribe=function(i,e,t,n,o,s){var r=this,u=(this._debugSubHits+=1,this._debugSubCollections.some(function(e){return e.publication===o})?this._debugSubCollections.filter(function(e){return e.publication===o})[0].hits+=1:this._debugSubCollections.push({publication:o,hits:1}),this._publications[o]);if(u){if(1<s.length||s[0]){if(!u.check)return void console.error(new Date,"No Check Function For Pub "+o);if(!u.check._schema)return void console.error(new Date,"No Check Schema For Pub "+o);for(var c={},a=Object.keys(u.check._schema).filter(function(e){return!e.includes(".")}),l=0;l<s.length;l++)c[a[l]]=s[l];try{u.check.validate(c)}catch(e){if(e)return void console.error(new Date,"Error in Pub Check ("+o+")",e)}}"Bypass"!==i&&(u=i.split("/"),g="",d=u[0],""===u[0]&&(g="/",d=u[1]),g+=d,1<u.length&&(g+="/"),(d=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===t.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==i&&!e.messageRoute.startsWith(g)})})).length)&&(this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Detected Undestroyed Subscription - "+this.serverConfig.CLIENT_NAME,"USER: "+t.user+" (Socket: "+t.id_socket+") is on route: "+i+" but has the following subscriptions on other routes:"+JSON.stringify(d,null,2)),d.forEach(function(i){i.clients.filter(function(e){return e.id_socket===t.id_socket}).forEach(function(e){r.unsubscribe(e.messageRoute,new Date,t,e.messageId,i.publication,i.subscriptionData)})}));var g,d,_=this._subscriptions.filter(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)})[0];_?_.clients.some(function(e){return e.id_socket===t.id_socket&&e.messageId===n})||_.clients.push({id_user:t.id_user,messageId:n,id_socket:t.id_socket,messageRoute:i}):this._subscriptions.push({publication:o,subscriptionData:s,collections:this.getPublicationCollections(o),clients:[{id_user:t.id_user,messageId:n,id_socket:t.id_socket,messageRoute:i}],cacheId:0}),(_=_||this._subscriptions.filter(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)})[0]).cacheId||this._mongoQueue.some(function(e){return e.subscription.publication===_.publication&&JSON.stringify(e.subscription.subscriptionData)===JSON.stringify(_.subscriptionData)})?_.cacheId&&this.sendDataToOne(t,n,_,"newSub",o):this.addToQueue({_id:0,type:"newSub",collection:"",subscription:_,running:!1,run_again:!1})}else console.error(new Date,"No Publication: "+o)},SubscriptionManager.prototype.createLoggedInUser=function(n){return __awaiter(this,void 0,void 0,function(){var i=this;return __generator(this,function(e){return[2,new Promise(function(t,e){return __awaiter(i,void 0,void 0,function(){var i;return __generator(this,function(e){return(i=this._mainServer.getWS(n))?(i={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:i.id_user,user:i.user,id_ws:i.id_socket},this._loggedInUsers.push(i),logged_in_users_collection_1.LoggedInUsers.insertOne(i),t(i)):t(null),[2]})})})]})})},SubscriptionManager.prototype.unsubscribe=function(e,i,t,n,o,s){if(this._debugUnSubHits+=1,this._publications[o]){var r=this._subscriptions.filter(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)})[0];if(r)for(var u=r.clients.length-1;0<=u;u--)r.clients[u].id_user===t.id_user&&r.clients[u].messageId===n&&r.clients[u].id_socket===t.id_socket&&r.clients.splice(u,1)}else console.log("No Publication: "+o)},SubscriptionManager.prototype.unsubscribeAll=function(r){return __awaiter(this,void 0,void 0,function(){var i,t,n,o,s;return __generator(this,function(e){switch(e.label){case 0:return(this._debugUnSubAllHits+=1,r)?[4,logged_in_users_collection_1.LoggedInUsers.findOne({id_ws:r.id_socket})]:[3,2];case 1:for((i=e.sent())&&(0<=this._loggedInUsers.map(function(e){return e._id}).indexOf(i._id)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e._id}).indexOf(i._id),1),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:i._id})),t=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_user===r.id_user&&e.id_socket===r.id_socket})}),n=t.length-1;0<=n;n--)for(o=t[n],s=o.clients.length-1;0<=s;s--)o.clients[s].id_socket===r.id_socket&&o.clients.splice(s,1);r.close(),process.nextTick(function(){[r.OPEN,r.CLOSING].includes(r.readyState)&&r.terminate()}),e.label=2;case 2:return[2]}})})},SubscriptionManager.prototype.getActiveSubscriptions=function(){return this._subscriptions},SubscriptionManager.prototype.getPublicationCollections=function(e){return this._publications[e].collections},SubscriptionManager.prototype.tailOpLog=function(i){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(e){switch(e.label){case 0:return this._oplog$&&!this._oplog$.closed&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:if(e.sent(),!this._oplog$||this._oplog$.closed){if(this._oplogRetryCount+=1,5<this._oplogRetryCount&&(console.error("****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************"),process.exit(1)),i){t=i;try{this._oplog$=index_1.ResolveIOServer.getMainDB().watch([],{resumeAfter:i})}catch(e){return this._oplog$&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),this.tailOpLog(i),[2]}}else this._oplog$=index_1.ResolveIOServer.getMainDB().watch();console.log(new Date,"oplog started"),this._oplog$.on("change",function(i){var e;i.ns&&(e=i.ns.coll,n._debugOplogCollections.some(function(e){return e.collection===i.ns.coll&&e.type===i.operationType})?n._debugOplogCollections.filter(function(e){return e.collection===i.ns.coll&&e.type===i.operationType})[0].hits+=1:n._debugOplogCollections.push({collection:i.ns.coll,type:i.operationType,hits:1}),!e||e.endsWith(".versions")||e.startsWith("monitor-")||"logs"===e||"log-method-latencies"===e||"log-subscriptions"===e||(n._debugOplogHits+=1,"insert"===i.operationType?("support-tickets"===e&&"https://resolveio.com"===n.serverConfig.ROOT_URL&&(n._mainServer.getMethodManager().callMethodInternal.call(n._mainServer.getMethodManager(),"sendSupportTicketEmail",i.documentKey._id),n.invalidatePubsCache(e,"insert")),"method-responses"!==e&&n.invalidatePubsCache(e,"insert")):"update"===i.operationType||"replace"===i.operationType?"method-responses"!==e&&n.invalidatePubsCache(e,"update"):"delete"===i.operationType&&"method-responses"!==e&&n.invalidatePubsCache(e,"delete")),"flags"===e&&flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?n._enableDebug=!0:n._enableDebug=!1}),t=i._id)}),this._oplog$.on("error",function(e){console.log(new Date,"oplog error",e),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(t)}),this._oplog$.on("end",function(){console.log(new Date,"oplog end"),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(t)}),this._oplog$.on("close",function(){console.log(new Date,"oplog close"),n._oplog$.removeAllListeners(),n._oplog$=null,n.tailOpLog(t)})}return[2]}})})},SubscriptionManager.prototype.sendDataToOne=function(c,a,l,e,i){var t=this;return new Promise(function(r,u){return __awaiter(t,void 0,void 0,function(){var i,t,n,o,s=this;return __generator(this,function(e){if(this._publications[l.publication].user_specific)n=this._monitorManagerFunction.startMonitorFunction("User Specific Publication",l.publication,"","",l.subscriptionData),(o=this._publications[l.publication].function).call.apply(o,__spreadArray([Object.assign({},this,SubscriptionManager.prototype),c.id_user],l.subscriptionData,!1)).then(function(e){s._monitorManagerFunction.finishMonitorFunction(n),s.sendWS(c,{messageId:a,hasError:!1,data:e}),r(!0)},function(e){s._monitorManagerFunction.finishMonitorFunction(n),s.sendWS(c,{messageId:a,hasError:!0,data:e}),s._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+s.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+l.publication+" - (sendDataToOne - WS)\n\nData \n"+JSON.stringify(l.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),u(e)});else if(l.cacheId){try{i=JSON.parse(this._nodeCache.get(l.cacheId),common_1.dateReviver),t={messageId:a,hasError:!1,data:i},this.sendWS(c,t)}catch(e){this._nodeCache.del(l.cacheId),l.cacheId=0,this.addToQueue({_id:0,type:"newSub",collection:"",subscription:l,running:!1,run_again:!1})}r(!0)}else this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - No Cache! - "+l.publication+"\n\nData \n"+JSON.stringify(l.subscriptionData,null,2)),r(!1);return[2]})})})},SubscriptionManager.prototype.sendDataToAll=function(a){var e=this;return new Promise(function(c,n){return __awaiter(e,void 0,void 0,function(){var r,i,u=this;return __generator(this,function(e){return a.subscription.clients.length?("superadminAPM"!==a.subscription.publication&&"loggedInUsers"!==a.subscription.publication&&this._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(),"insertSubscriptionLog",a.type,a.subscription.publication,a.collection,JSON.stringify(a.subscription.subscriptionData)),r=this._monitorManagerFunction.startMonitorFunction("Publication",a.subscription.publication,"","",a.subscription.subscriptionData),(i=this._publications[a.subscription.publication].function).call.apply(i,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],a.subscription.subscriptionData,!1)).then(function(t){if(u._monitorManagerFunction.finishMonitorFunction(r),a.subscription.clients.length){if(!a.subscription.cacheId||u._nodeCache.get(a.subscription.cacheId)!==JSON.stringify(t)){if(a.subscription.clients.forEach(function(e){var i=u._mainServer.getWS(e.id_socket);i&&(e={messageId:e.messageId,hasError:!1,data:t},u.sendWS(i,e))}),(e=u._nodeCache.getStats().vsize)>u._heapLimit){for(i=0,n=u._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),o=0;o<n.length&&(u._nodeCache.del(n[o].cacheId),n[o].cacheId=0,i+=1,!((e=u._nodeCache.getStats().vsize)<.75*u._heapLimit));o++);console.log("Sub Cache: Too Big - "+a.subscription.publication+" - Deleted: "+i+" - "+e)}a.subscription.cacheId&&u._nodeCache.del(a.subscription.cacheId);s=u._cacheId;u._cacheId+=1,u._nodeCache.set(s,JSON.stringify(t)),a.subscription.cacheId=s}c(!0)}else{var e;if((e=u._nodeCache.getStats().vsize)>u._heapLimit){for(var i=0,n=u._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),o=0;o<n.length&&(u._debugRemoveCacheHits+=1,u._nodeCache.del(n[o].cacheId),n[o].cacheId=0,i+=1,!((e=u._nodeCache.getStats().vsize)<.75*u._heapLimit));o++);console.log("Sub Cache: Too Big - "+a.subscription.publication+" - Deleted: "+i+" - "+e)}a.subscription.cacheId&&u._nodeCache.del(a.subscription.cacheId);var s=u._cacheId;u._cacheId+=1,u._nodeCache.set(s,JSON.stringify(t)),a.subscription.cacheId=s,c(!1)}},function(t){u._monitorManagerFunction.finishMonitorFunction(r),u._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+u.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+a.subscription.publication+" - (sendPubData)\n\nData \n"+JSON.stringify(a.subscription.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(t,null,2)),a.subscription.clients.forEach(function(e){var i=u._mainServer.getWS(e.id_socket);i&&i.id_socket===e.id_socket&&(e={messageId:e.messageId,hasError:!0,data:t},u.sendWS(i,e))}),n(t)})):(a.subscription.cacheId&&this._nodeCache.del(a.subscription.cacheId),0<=this._subscriptions.findIndex(function(e){return e.publication===a.subscription.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(a.subscription.subscriptionData)})&&this._subscriptions.splice(this._subscriptions.findIndex(function(e){return e.publication===a.subscription.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(a.subscription.subscriptionData)}),1),c(!1)),[2]})})})},SubscriptionManager.prototype.sendWS=function(e,i){this._sendQueue.splice(0,0,{id_ws:e.id_socket,data:i})},SubscriptionManager.prototype.getEnableDebug=function(){return this._enableDebug},SubscriptionManager}();exports.SubscriptionManager=SubscriptionManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,n,o,s){return new(o=o||Promise)(function(t,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s.throw(e))}catch(e){i(e)}}function step(e){var i;e.done?t(e.value):((i=e.value)instanceof o?i:new o(function(e){e(i)})).then(fulfilled,rejected)}step((s=s.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var s,r,u,c={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]},a={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function verb(t){return function(e){var i=[t,e];if(s)throw new TypeError("Generator is already executing.");for(;c=a&&i[a=0]?0:c;)try{if(s=1,r&&(u=2&i[0]?r.return:i[0]?r.throw||((u=r.return)&&u.call(r),0):r.next)&&!(u=u.call(r,i[1])).done)return u;switch(r=0,(i=u?[2&i[0],u.value]:i)[0]){case 0:case 1:u=i;break;case 4:return c.label++,{value:i[1],done:!1};case 5:c.label++,r=i[1],i=[0];continue;case 7:i=c.ops.pop(),c.trys.pop();continue;default:if(!(u=0<(u=c.trys).length&&u[u.length-1])&&(6===i[0]||2===i[0])){c=0;continue}if(3===i[0]&&(!u||i[1]>u[0]&&i[1]<u[3]))c.label=i[1];else if(6===i[0]&&c.label<u[1])c.label=u[1],u=i;else{if(!(u&&c.label<u[2])){u[2]&&c.ops.pop(),c.trys.pop();continue}c.label=u[2],c.ops.push(i)}}i=o.call(n,c)}catch(e){i=[6,e],r=0}finally{s=u=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,i,t){if(t||2===arguments.length)for(var n,o=0,s=i.length;o<s;o++)!n&&o in i||((n=n||Array.prototype.slice.call(i,0,o))[o]=i[o]);return e.concat(n||Array.prototype.slice.call(i))},logs_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0,require("../publications/logs")),app_status_1=require("../publications/app-status"),files_1=require("../publications/files"),super_admin_1=require("../publications/super-admin"),logged_in_users_collection_1=require("../collections/logged-in-users.collection"),cron_jobs_1=require("../publications/cron-jobs"),flags_1=require("../publications/flags"),method_responses_1=require("../publications/method-responses"),index_1=require("../index"),notifications_1=require("../publications/notifications"),report_builder_reports_1=require("../publications/report-builder-reports"),report_builder_libraries_1=require("../publications/report-builder-libraries"),user_groups_1=require("../publications/user-groups"),user_guides_1=require("../publications/user-guides"),report_builder_dashboard_builders_1=require("../publications/report-builder-dashboard-builders"),mongo_manager_1=require("./mongo.manager"),common_1=require("../util/common"),NodeCache=require("node-cache"),flag_collection_1=require("../collections/flag.collection"),os_1=require("os"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(e,i,t,n){var o=this;this._publications={},this._subscriptions=[],this._loggedInUsers=[],this._mongoQueue=[],this._mongoQueueId=0,this._sendQueue=[],this._runningQueue=!1,this._cacheId=1,this._heapStats=v8.getHeapStatistics(),this._heapLimit=this._heapStats.heap_size_limit/numCPUs/8,this._enableDebug=!1,this._debugOplogCollections=[],this._debugOplogHits=0,this._debugSubCollections=[],this._debugSubHits=0,this._debugUnSubHits=0,this._debugUnSubAllHits=0,this._debugMongoQueueHits=0,this._debugMongoQueueCollections=[],this._debugSendQueueHits=0,this._debugRemoveCacheHits=0,this._oplogRetryCount=0,this._mainServer=e,this._monitorManagerFunction=n,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),this.serverConfig=t,this._wss=i,(0,super_admin_1.loadSuperAdminPublications)(this),(0,app_status_1.loadAppStatusPublications)(this),(0,logs_1.loadLogPublications)(this),(0,files_1.loadFilePublications)(this),(0,cron_jobs_1.loadCronJobPublications)(this),(0,flags_1.loadFlagsPublications)(this),(0,method_responses_1.loadMethodResponsePublications)(this),(0,notifications_1.loadNotificationPublications)(this),(0,report_builder_reports_1.loadReportBuilderReportPublications)(this),(0,report_builder_libraries_1.loadReportBuilderLibraryPublications)(this),(0,user_groups_1.loadUserGroupPublications)(this),(0,user_guides_1.loadUserGuidePublications)(this),(0,report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this),this.tailOpLog(),setInterval(function(){o._oplogRetryCount=0},15e3),setInterval(function(){o.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",o._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",o._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",o._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",o._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(o._debugMongoQueueCollections.sort(function(e,i){return e.collection.localeCompare(i.collection)||e.publication.localeCompare(i.publication)}),null,2)),console.log(new Date,"Sub Manager","Oplog Hits",o._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(o._debugOplogCollections.sort(function(e,i){return e.collection.localeCompare(i.collection)||e.type.localeCompare(i.type)}),null,2)),console.log(new Date,"Sub Manager","Send Queue Hits",o._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",o._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(o._debugSubCollections.sort(function(e,i){return e.publication.localeCompare(i.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",o._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",o._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",o._debugRemoveCacheHits)),o._debugOplogHits=0,o._debugOplogCollections=[],o._debugSubCollections=[],o._debugMongoQueueHits=0,o._debugMongoQueueCollections=[],o._debugSendQueueHits=0,o._debugSubHits=0,o._debugUnSubHits=0,o._debugUnSubAllHits=0,o._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(o,void 0,void 0,function(){var i,n,o,t,s,r,u=this;return __generator(this,function(e){if(!this._runningQueue){if(this._runningQueue=!0,this._sendQueue.length)for(i=function(e){n._debugSendQueueHits+=1;var i,t=n._mainServer.getWS(n._sendQueue[e].id_ws);t&&t.readyState===t.OPEN?t.bufferedAmount<20480&&(i=n._sendQueue.pop(),t.send(JSON.stringify(i.data),function(e){e&&(u.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",t.user,t.id_socket,1),u.unsubscribeAll(t))})):n._sendQueue.splice(e,1)},r=(n=this)._sendQueue.length-1;0<=r;r--)i(r);if((o=this._mongoQueue.filter(function(e){return!e.running})).length)for(o.forEach(function(e){e.running=!0}),t=function(e){s._debugMongoQueueHits+=1;var t=o[e];if(s._debugMongoQueueCollections.some(function(e){return e.collection===t.collection&&e.publication===t.subscription.publication})?s._debugMongoQueueCollections.filter(function(e){return e.collection===t.collection&&e.publication===t.subscription.publication})[0].hits+=1:s._debugMongoQueueCollections.push({collection:t.collection,publication:t.subscription.publication,hits:1}),s._publications[t.subscription.publication].user_specific){for(var n=[],i=0;i<t.subscription.clients.length;i++)!function(e){var i=t.subscription.clients[e],e=s._mainServer.getWS(i.id_socket);e&&e.id_socket===i.id_socket&&n.push(s.sendDataToOne(e,i.messageId,t.subscription,t.type,t.collection).catch(function(e){return u._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+u.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - User Specific - Socket: "+i.id_socket+", User: "+i.id_user+", MessageId: "+i.messageId+", Pub: "+t.subscription.publication+", Err: "+JSON.stringify(e,null,2)),null}))}(i);Promise.all(n).then(function(){t.run_again?(t.running=!1,t.run_again=!1):0<=u._mongoQueue.map(function(e){return e._id}).indexOf(t._id)&&u._mongoQueue.splice(u._mongoQueue.map(function(e){return e._id}).indexOf(t._id),1)})}else s.sendDataToAll(t).then(function(){t.run_again?(t.running=!1,t.run_again=!1):0<=u._mongoQueue.map(function(e){return e._id}).indexOf(t._id)&&u._mongoQueue.splice(u._mongoQueue.map(function(e){return e._id}).indexOf(t._id),1)},function(){0<=u._mongoQueue.map(function(e){return e._id}).indexOf(t._id)&&u._mongoQueue.splice(u._mongoQueue.map(function(e){return e._id}).indexOf(t._id),1)})},s=this,r=o.length-1;0<=r;r--)t(r);this._runningQueue=!1}return[2]})})},1),setInterval(function(){return __awaiter(o,void 0,void 0,function(){var i,n,t,o,s,r,u,c,a;return __generator(this,function(e){switch(e.label){case 0:return i=this,[4,logged_in_users_collection_1.LoggedInUsers.find()];case 1:for(i._loggedInUsers=e.sent(),n=(0,common_1.deepCopy)(this._loggedInUsers),t=function(e){var t=n[e];(!t.date||12e4<Date.now()-t.date.getTime())&&(o._mainServer.getWS(t.id_ws)?(o.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",o._mainServer.getWS(t.id_ws).user,o._mainServer.getWS(t.id_ws).id_socket,2),o.unsubscribeAll(o._mainServer.getWS(t.id_ws))):(o._subscriptions.forEach(function(e){for(var i=e.clients.length-1;0<=i;i--)e.clients[i].id_socket===t.id_ws&&e.clients.splice(i,1)}),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:t._id}),0<=o._loggedInUsers.findIndex(function(e){return e._id===t._id})&&o._loggedInUsers.splice(o._loggedInUsers.findIndex(function(e){return e._id===t._id}),1)))},s=(o=this)._loggedInUsers.length-1;0<=s;s--)t(s);for(s=0;s<this._subscriptions.length;s++)for(r=this._subscriptions[s],u=function(e){var i=r.clients[e];c._loggedInUsers.some(function(e){return e.id_ws===i.id_socket})||r.clients.splice(e,1)},c=this,a=r.clients.length-1;0<=a;a--)u(a);return[2]}})})},3e4),flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?o._enableDebug=!0:o._enableDebug=!1})}return SubscriptionManager.prototype.addToQueue=function(i){var e=this._mongoQueue.filter(function(e){return e.subscription.publication===i.subscription.publication&&JSON.stringify(e.subscription.subscriptionData)===JSON.stringify(i.subscription.subscriptionData)})[0];e?e.running&&(e.run_again=!0):(i._id=this._mongoQueueId,this._mongoQueueId+=1,this._mongoQueue.splice(0,0,i))},SubscriptionManager.prototype.invalidatePubsCache=function(i,e){index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i);for(var t=this._subscriptions.filter(function(e){return e.collections.includes(i)}),n=t.length-1;0<=n;n--){var o=t[n];this.addToQueue({_id:0,type:e,collection:i,subscription:o,running:!1,run_again:!1})}},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(i){var t=this,e=this._loggedInUsers.filter(function(e){return e.id_ws===i.id_socket})[0];e&&(e.date=new Date,logged_in_users_collection_1.LoggedInUsers.updateOne({id_ws:i.id_socket},{$set:{latency:i.latency,date:e.date}}).then(function(e){e||(t.unsubscribeAll(i),t.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",i.user,i.id_socket,3))},function(){t.unsubscribeAll(i),t.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",i.user,i.id_socket,4)}))},SubscriptionManager.prototype.subscribe=function(i,e,t,n,o,s){var r=this,u=(this._debugSubHits+=1,this._debugSubCollections.some(function(e){return e.publication===o})?this._debugSubCollections.filter(function(e){return e.publication===o})[0].hits+=1:this._debugSubCollections.push({publication:o,hits:1}),this._publications[o]);if(u){if(1<s.length||s[0]){if(!u.check)return void console.error(new Date,"No Check Function For Pub "+o);if(!u.check._schema)return void console.error(new Date,"No Check Schema For Pub "+o);for(var c={},a=Object.keys(u.check._schema).filter(function(e){return!e.includes(".")}),l=0;l<s.length;l++)c[a[l]]=s[l];try{u.check.validate(c)}catch(e){if(e)return void console.error(new Date,"Error in Pub Check ("+o+")",e)}}"Bypass"!==i&&(u=i.split("/"),g="",d=u[0],""===u[0]&&(g="/",d=u[1]),g+=d,1<u.length&&(g+="/"),(d=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===t.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==i&&!e.messageRoute.startsWith(g)})})).length)&&(this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Detected Undestroyed Subscription - "+this.serverConfig.CLIENT_NAME,"USER: "+t.user+" (Socket: "+t.id_socket+") is on route: "+i+" but has the following subscriptions on other routes:"+JSON.stringify(d,null,2)),d.forEach(function(i){i.clients.filter(function(e){return e.id_socket===t.id_socket}).forEach(function(e){r.unsubscribe(e.messageRoute,new Date,t,e.messageId,i.publication,i.subscriptionData)})}));var g,d,_=this._subscriptions.filter(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)})[0];_?_.clients.some(function(e){return e.id_socket===t.id_socket&&e.messageId===n})||_.clients.push({id_user:t.id_user,messageId:n,id_socket:t.id_socket,messageRoute:i}):this._subscriptions.push({publication:o,subscriptionData:s,collections:this.getPublicationCollections(o),clients:[{id_user:t.id_user,messageId:n,id_socket:t.id_socket,messageRoute:i}],cacheId:0}),(_=_||this._subscriptions.filter(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)})[0]).cacheId||this._mongoQueue.some(function(e){return e.subscription.publication===_.publication&&JSON.stringify(e.subscription.subscriptionData)===JSON.stringify(_.subscriptionData)})?_.cacheId&&this.sendDataToOne(t,n,_,"newSub",o):this.addToQueue({_id:0,type:"newSub",collection:"",subscription:_,running:!1,run_again:!1})}else console.error(new Date,"No Publication: "+o)},SubscriptionManager.prototype.createLoggedInUser=function(n){return __awaiter(this,void 0,void 0,function(){var i=this;return __generator(this,function(e){return[2,new Promise(function(t,e){return __awaiter(i,void 0,void 0,function(){var i;return __generator(this,function(e){return(i=this._mainServer.getWS(n))?(i={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:i.id_user,user:i.user,id_ws:i.id_socket},this._loggedInUsers.push(i),logged_in_users_collection_1.LoggedInUsers.insertOne(i),t(i)):t(null),[2]})})})]})})},SubscriptionManager.prototype.unsubscribe=function(e,i,t,n,o,s){if(this._debugUnSubHits+=1,this._publications[o]){var r=this._subscriptions.filter(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)})[0];if(r)for(var u=r.clients.length-1;0<=u;u--)r.clients[u].id_user===t.id_user&&r.clients[u].messageId===n&&r.clients[u].id_socket===t.id_socket&&r.clients.splice(u,1)}else console.log("No Publication: "+o)},SubscriptionManager.prototype.unsubscribeAll=function(r){return __awaiter(this,void 0,void 0,function(){var i,t,n,o,s;return __generator(this,function(e){switch(e.label){case 0:return(this._debugUnSubAllHits+=1,r)?[4,logged_in_users_collection_1.LoggedInUsers.findOne({id_ws:r.id_socket})]:[3,2];case 1:for((i=e.sent())&&(0<=this._loggedInUsers.map(function(e){return e._id}).indexOf(i._id)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e._id}).indexOf(i._id),1),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:i._id})),t=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_user===r.id_user&&e.id_socket===r.id_socket})}),n=t.length-1;0<=n;n--)for(o=t[n],s=o.clients.length-1;0<=s;s--)o.clients[s].id_socket===r.id_socket&&o.clients.splice(s,1);r.close(),process.nextTick(function(){[r.OPEN,r.CLOSING].includes(r.readyState)&&r.terminate()}),e.label=2;case 2:return[2]}})})},SubscriptionManager.prototype.getActiveSubscriptions=function(){return this._subscriptions},SubscriptionManager.prototype.getPublicationCollections=function(e){return this._publications[e].collections},SubscriptionManager.prototype.tailOpLog=function(i){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(e){switch(e.label){case 0:return this._oplog$&&!this._oplog$.closed&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:if(e.sent(),!this._oplog$||this._oplog$.closed){if(this._oplogRetryCount+=1,5<this._oplogRetryCount&&(console.error("****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************"),process.exit(1)),i){t=i;try{this._oplog$=index_1.ResolveIOServer.getMainDB().watch([],{resumeAfter:i})}catch(e){return this._oplog$&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),this.tailOpLog(i),[2]}}else this._oplog$=index_1.ResolveIOServer.getMainDB().watch();console.log(new Date,"oplog started"),this._oplog$.on("change",function(i){var e;i.ns&&(e=i.ns.coll,n._debugOplogCollections.some(function(e){return e.collection===i.ns.coll&&e.type===i.operationType})?n._debugOplogCollections.filter(function(e){return e.collection===i.ns.coll&&e.type===i.operationType})[0].hits+=1:n._debugOplogCollections.push({collection:i.ns.coll,type:i.operationType,hits:1}),!e||e.endsWith(".versions")||e.startsWith("monitor-")||"logs"===e||"log-method-latencies"===e||"log-subscriptions"===e||(n._debugOplogHits+=1,"insert"===i.operationType?("support-tickets"===e&&"https://resolveio.com"===n.serverConfig.ROOT_URL&&(n._mainServer.getMethodManager().callMethodInternal.call(n._mainServer.getMethodManager(),"sendSupportTicketEmail",i.documentKey._id),n.invalidatePubsCache(e,"insert")),"method-responses"!==e&&n.invalidatePubsCache(e,"insert")):"update"===i.operationType||"replace"===i.operationType?"method-responses"!==e&&n.invalidatePubsCache(e,"update"):"delete"===i.operationType&&"method-responses"!==e&&n.invalidatePubsCache(e,"delete")),"flags"===e&&flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?n._enableDebug=!0:n._enableDebug=!1}),t=i._id)}),this._oplog$.on("error",function(e){console.log(new Date,"oplog error",e),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(t)}),this._oplog$.on("end",function(){console.log(new Date,"oplog end"),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(t)}),this._oplog$.on("close",function(){console.log(new Date,"oplog close"),n._oplog$.removeAllListeners(),n._oplog$=null,n.tailOpLog(t)})}return[2]}})})},SubscriptionManager.prototype.sendDataToOne=function(c,a,l,e,i){var t=this;return new Promise(function(r,u){return __awaiter(t,void 0,void 0,function(){var i,t,n,o,s=this;return __generator(this,function(e){if(this._publications[l.publication].user_specific)n=this._monitorManagerFunction.startMonitorFunction("User Specific Publication",l.publication,"","",l.subscriptionData),(o=this._publications[l.publication].function).call.apply(o,__spreadArray([Object.assign({},this,SubscriptionManager.prototype),c.id_user],l.subscriptionData,!1)).then(function(e){s._monitorManagerFunction.finishMonitorFunction(n),s.sendWS(c,{messageId:a,hasError:!1,data:e}),r(!0)},function(e){s._monitorManagerFunction.finishMonitorFunction(n),s.sendWS(c,{messageId:a,hasError:!0,data:e}),s._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+s.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+l.publication+" - (sendDataToOne - WS)\n\nData \n"+JSON.stringify(l.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),u(e)});else if(l.cacheId){try{i=JSON.parse(this._nodeCache.get(l.cacheId),common_1.dateReviver),t={messageId:a,hasError:!1,data:i},this.sendWS(c,t)}catch(e){this._nodeCache.del(l.cacheId),l.cacheId=0,this.addToQueue({_id:0,type:"newSub",collection:"",subscription:l,running:!1,run_again:!1})}r(!0)}else this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - No Cache! - "+l.publication+"\n\nData \n"+JSON.stringify(l.subscriptionData,null,2)),r(!1);return[2]})})})},SubscriptionManager.prototype.sendDataToAll=function(a){var e=this;return new Promise(function(c,n){return __awaiter(e,void 0,void 0,function(){var r,i,u=this;return __generator(this,function(e){return a.subscription.clients.length?("superadminAPM"!==a.subscription.publication&&"loggedInUsers"!==a.subscription.publication&&this._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(),"insertSubscriptionLog",a.type,a.subscription.publication,a.collection,JSON.stringify(a.subscription.subscriptionData)),r=this._monitorManagerFunction.startMonitorFunction("Publication",a.subscription.publication,"","",a.subscription.subscriptionData),(i=this._publications[a.subscription.publication].function).call.apply(i,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],a.subscription.subscriptionData,!1)).then(function(t){if(u._monitorManagerFunction.finishMonitorFunction(r),a.subscription.clients.length){if(!a.subscription.cacheId||u._nodeCache.get(a.subscription.cacheId)!==JSON.stringify(t)){if(a.subscription.clients.forEach(function(e){var i=u._mainServer.getWS(e.id_socket);i&&(e={messageId:e.messageId,hasError:!1,data:t},u.sendWS(i,e))}),(e=u._nodeCache.getStats().vsize)>u._heapLimit){for(i=0,n=u._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),o=0;o<n.length&&(u._nodeCache.del(n[o].cacheId),n[o].cacheId=0,i+=1,!((e=u._nodeCache.getStats().vsize)<.75*u._heapLimit));o++);console.log("Sub Cache: Too Big - "+a.subscription.publication+" - Deleted: "+i+" - "+e)}a.subscription.cacheId&&u._nodeCache.del(a.subscription.cacheId);s=u._cacheId;u._cacheId+=1,u._nodeCache.set(s,JSON.stringify(t)),a.subscription.cacheId=s}c(!0)}else{var e;if((e=u._nodeCache.getStats().vsize)>u._heapLimit){for(var i=0,n=u._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),o=0;o<n.length&&(u._debugRemoveCacheHits+=1,u._nodeCache.del(n[o].cacheId),n[o].cacheId=0,i+=1,!((e=u._nodeCache.getStats().vsize)<.75*u._heapLimit));o++);console.log("Sub Cache: Too Big - "+a.subscription.publication+" - Deleted: "+i+" - "+e)}a.subscription.cacheId&&u._nodeCache.del(a.subscription.cacheId);var s=u._cacheId;u._cacheId+=1,u._nodeCache.set(s,JSON.stringify(t)),a.subscription.cacheId=s,c(!1)}},function(t){u._monitorManagerFunction.finishMonitorFunction(r),u._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+u.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+a.subscription.publication+" - (sendPubData)\n\nData \n"+JSON.stringify(a.subscription.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(t,null,2)),a.subscription.clients.forEach(function(e){var i=u._mainServer.getWS(e.id_socket);i&&i.id_socket===e.id_socket&&(e={messageId:e.messageId,hasError:!0,data:t},u.sendWS(i,e))}),n(t)})):(a.subscription.cacheId&&this._nodeCache.del(a.subscription.cacheId),0<=this._subscriptions.findIndex(function(e){return e.publication===a.subscription.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(a.subscription.subscriptionData)})&&this._subscriptions.splice(this._subscriptions.findIndex(function(e){return e.publication===a.subscription.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(a.subscription.subscriptionData)}),1),c(!1)),[2]})})})},SubscriptionManager.prototype.sendWS=function(e,i){this._sendQueue.splice(0,0,{id_ws:e.id_socket,data:i})},SubscriptionManager.prototype.getEnableDebug=function(){return this._enableDebug},SubscriptionManager}();exports.SubscriptionManager=SubscriptionManager;
2
2
  //# sourceMappingURL=subscription.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/subscription.manager.ts"],"names":["logs_1","require","app_status_1","files_1","super_admin_1","logged_in_users_collection_1","cron_jobs_1","flags_1","method_responses_1","index_1","notifications_1","report_builder_reports_1","report_builder_libraries_1","user_groups_1","user_guides_1","report_builder_dashboard_builders_1","mongo_manager_1","common_1","NodeCache","flag_collection_1","os_1","numCPUs","cpus","length","v8","SubscriptionManager","mainServer","wss","serverConfig","monitorManagerFunction","_this","this","_publications","_subscriptions","_loggedInUsers","_mongoQueue","_mongoQueueId","_sendQueue","_runningQueue","_cacheId","_heapStats","getHeapStatistics","_heapLimit","heap_size_limit","_enableDebug","_debugOplogCollections","_debugOplogHits","_debugSubCollections","_debugSubHits","_debugUnSubHits","_debugUnSubAllHits","_debugMongoQueueHits","_debugMongoQueueCollections","_debugSendQueueHits","_debugRemoveCacheHits","_oplogRetryCount","_mainServer","_monitorManagerFunction","_nodeCache","stdTTL","checkperiod","_wss","loadSuperAdminPublications","loadAppStatusPublications","loadLogPublications","loadFilePublications","loadCronJobPublications","loadFlagsPublications","loadMethodResponsePublications","loadNotificationPublications","loadReportBuilderReportPublications","loadReportBuilderLibraryPublications","loadUserGroupPublications","loadUserGuidePublications","loadReportBuilderDashboardBuilderPublications","tailOpLog","setInterval","getEnableDebug","console","log","Date","JSON","stringify","sort","a","b","collection","localeCompare","publication","type","__awaiter","i","this_1","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","data","error","unsubscribeAll","splice","queueArr","filter","running","forEach","entry","this_2","mongoQueue","some","subscription","hits","push","user_specific","promises","j","clients","client","id_socket","sendDataToOne","messageId","catch","err","getMethodManager","sendEmail","id_user","Promise","all","then","run_again","map","_id","indexOf","sendDataToAll","_a","LoggedInUsers","find","_b","sent","userCopy","deepCopy","loggedInUser","date","now","getTime","this_3","sub","deleteOne","findIndex","this_4","Flags","findOne","flag","value","prototype","addToQueue","subscriptionData","invalidatePubsCache","ResolveIOServer","getMongoManager","invalidateQueryCache","collSubs","collections","includes","publications","method","Object","assign","loggedInLatency","updateOne","$set","latency","res","subscribe","messageRoute","messageDate","pub","check","_schema","valObj","rootKeys","keys","validate","errors","urlData","split","urlModule_1","urlNext","otherRouteSubs","startsWith","otherSub","unsubscribe","sub_1","getPublicationCollections","cacheId","createLoggedInUser","resolve","reject","user","objectIdHexString","__v","insertOne","userSubs","close","process","nextTick","CLOSING","terminate","getActiveSubscriptions","resumeToken","_oplog$","closed","removeAllListeners","setTimeout","exit","lastResumeToken_1","getMainDB","watch","resumeAfter","errOp","on","doc","ns","coll","operationType","endsWith","callMethodInternal","call","documentKey","monitor_1","startMonitorFunction","function","apply","__spreadArray","finishMonitorFunction","sendWS","hasError","cacheData","parse","get","dateReviver","serverRes","del","monitor_2","nodeCacheSize","getStats","vsize","deleteCount","subArr","zz","set","exports"],"mappings":"wqDAGAA,Q,0FAAAC,QAAA,sBAAA,GACAC,aAAAD,QAAA,4BAAA,EACAE,QAAAF,QAAA,uBAAA,EACAG,cAAAH,QAAA,6BAAA,EACAI,6BAAAJ,QAAA,2CAAA,EACAK,YAAAL,QAAA,2BAAA,EACAM,QAAAN,QAAA,uBAAA,EACAO,mBAAAP,QAAA,kCAAA,EAEAQ,QAAAR,QAAA,UAAA,EACAS,gBAAAT,QAAA,+BAAA,EACAU,yBAAAV,QAAA,wCAAA,EAIAW,2BAAAX,QAAA,0CAAA,EACAY,cAAAZ,QAAA,6BAAA,EACAa,cAAAb,QAAA,6BAAA,EACAc,oCAAAd,QAAA,mDAAA,EACAe,gBAAAf,QAAA,iBAAA,EACAgB,SAAAhB,QAAA,gBAAA,EACAiB,UAAAjB,QAAA,YAAA,EAEAkB,kBAAAlB,QAAA,gCAAA,EACAmB,KAAAnB,QAAA,IAAA,EACMoB,SAAU,EAAAD,KAAAE,MAAI,EAAGC,OACjBC,GAAKvB,QAAQ,IAAI,EA0BvBwB,oBAAA,WA4CC,SAAAA,oBAAYC,EAAYC,EAAuBC,EAAcC,GAA7D,IAAAC,EAAAC,KAzCQA,KAAAC,cAAmC,GACnCD,KAAAE,eAA4C,GAE5CF,KAAAG,eAAsC,GAEtCH,KAAAI,YAAiC,GACjCJ,KAAAK,cAAgB,EAEhBL,KAAAM,WAAa,GACbN,KAAAO,cAAgB,CAAA,EAKhBP,KAAAQ,SAAW,EAIXR,KAAAS,WAAahB,GAAGiB,kBAAiB,EACjCV,KAAAW,WAAaX,KAAKS,WAAWG,gBAAkBtB,QAAU,EAIzDU,KAAAa,aAAe,CAAA,EACfb,KAAAc,uBAAyB,GACzBd,KAAAe,gBAAkB,EAClBf,KAAAgB,qBAAuB,G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AAUE,EAAE4E,gBAAgB,IAAM/E,KAAKC,UAAU8B,EAAWE,aAAa8C,gBAAgB,CAAvJ,CAAwJ,GAC9LjI,KAAKE,eAAewE,OAAO1E,KAAKE,eAAeuH,UAAU,SAAApE,GAAK,OAAAA,EAAEI,cAAgBwB,EAAWE,aAAa1B,aAAeP,KAAKC,UAAUE,EAAE4E,gBAAgB,IAAM/E,KAAKC,UAAU8B,EAAWE,aAAa8C,gBAAgB,CAAvJ,CAAwJ,EAAG,CAAC,EAG3NwC,EAAQ,CAAA,CAAK,G,QAsJd,CACF,EAEQ/K,oBAAAqI,UAAAiF,OAAR,SAAejJ,EAAeQ,GAC7BvE,KAAKM,WAAWoE,OAAO,EAAG,EAAG,CAC5BT,MAAOF,EAAc,UACrBQ,KAAMA,C,CACN,CACF,EAEO7E,oBAAAqI,UAAAjF,eAAP,WACC,OAAO9C,KAAKa,YACb,EACDnB,mBAAA,EAAC,EA/nCYsO,QAAAtO,oBAAAA","file":"subscription.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { ActiveSubscriptionModel, SubscriptionModel } from '../models/subscription.model';\nimport * as WebSocket from 'ws';\nimport { loadLogPublications } from '../publications/logs';\nimport { loadAppStatusPublications } from '../publications/app-status';\nimport { loadFilePublications } from '../publications/files';\nimport { loadSuperAdminPublications } from '../publications/super-admin';\nimport { LoggedInUsers } from '../collections/logged-in-users.collection';\nimport { loadCronJobPublications } from '../publications/cron-jobs';\nimport { loadFlagsPublications } from '../publications/flags';\nimport { loadMethodResponsePublications } from '../publications/method-responses';\nimport ResolveIOMainServer from '../server-app';\nimport { ResolveIOServer } from '../index';\nimport { loadNotificationPublications } from '../publications/notifications';\nimport { loadReportBuilderReportPublications } from '../publications/report-builder-reports';\nimport { LoggedInUserModel } from '../models/logged-in-users.model';\n\nimport { ChangeStream, ChangeStreamDeleteDocument, ChangeStreamDocument, ChangeStreamInsertDocument, ChangeStreamReplaceDocument, ChangeStreamUpdateDocument, ResumeToken } from 'mongodb';\nimport { loadReportBuilderLibraryPublications } from '../publications/report-builder-libraries';\nimport { loadUserGroupPublications } from '../publications/user-groups';\nimport { loadUserGuidePublications } from '../publications/user-guides';\nimport { loadReportBuilderDashboardBuilderPublications } from '../publications/report-builder-dashboard-builders';\nimport { objectIdHexString } from './mongo.manager';\nimport { dateReviver, deepCopy } from '../util/common';\nimport * as NodeCache from 'node-cache';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { Flags } from '../collections/flag.collection';\nimport { cpus } from 'os';\nconst numCPUs = cpus().length;\nconst v8 = require('v8');\n\n// Performance Dependencies\n// import * as path from 'path';\n// import { Worker } from 'worker_threads';\n\ninterface MongoQueueModel {\n\t_id: number,\n\ttype: string;\n\tcollection: string;\n\tsubscription: ActiveSubscriptionModel;\n\trunning: boolean;\n\trun_again: boolean;\n}\n\n// interface CurrentPerformanceMonitor {\n// \t_id: number;\n// \tfunction: string;\n// \tpublication: string;\n// \tsubscriptionData: any[];\n// \tdate_start: Date;\n// \tdate_end: Date;\n// \tduration: number;\n// \tresult: string;\n// }\n\nexport class SubscriptionManager {\n\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _publications: SubscriptionModel = {};\n\tprivate _subscriptions: ActiveSubscriptionModel[] = [];\n\tprivate _wss: WebSocket.Server;\n\tprivate _loggedInUsers: LoggedInUserModel[] = [];\n\n\tprivate _mongoQueue: MongoQueueModel[] = [];\n\tprivate _mongoQueueId = 0;\n\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\t\n\tprivate _oplog$: ChangeStream;\n\n\tprivate _nodeCache;\n\tprivate _cacheId = 1;\n\n\tprivate serverConfig;\n\n\tprivate _heapStats = v8.getHeapStatistics();\n\tprivate _heapLimit = this._heapStats.heap_size_limit / numCPUs / 8;\n\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _enableDebug = false;\n\tprivate _debugOplogCollections = [];\n\tprivate _debugOplogHits = 0;\n\tprivate _debugSubCollections = [];\n\tprivate _debugSubHits = 0;\n\tprivate _debugUnSubHits = 0;\n\tprivate _debugUnSubAllHits = 0;\n\tprivate _debugMongoQueueHits = 0;\n\tprivate _debugMongoQueueCollections = [];\n\tprivate _debugSendQueueHits = 0;\n\tprivate _debugRemoveCacheHits = 0;\n\n\tprivate _oplogRetryCount = 0;\n\n\t// private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];\n\t// private idPerformance: number = 0;\n\t// private performanceThread;\n\n\tconstructor(mainServer, wss: WebSocket.Server, serverConfig, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\tthis._nodeCache = new NodeCache( { stdTTL: 0, checkperiod: 0 } );\n\n\t\t// setTimeout(() => {\n\t\t// \tconsole.log('Setting up performance thread');\n\n\t\t// \tthis.performanceThread = new Worker(path.join(__dirname, './subscription.performance.js'));\n\n\t\t// \tthis.performanceThread.on('exit', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD EXITED!!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\n\t\t// \tthis.performanceThread.on('error', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD RECV ERROR !!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\t\t// }, 5000);\n\n\t\t// setInterval(() => {\n\t\t// \tconsole.log('Post thread msg');\n\t\t// \tthis.performanceThread.postMessage(this.currentPerfomanceMonitor);\n\t\t// \tthis.currentPerfomanceMonitor = [];\n\t\t// }, 10000);\n\n\t\tthis.serverConfig = serverConfig;\n\t\tthis._wss = wss;\n\n\t\t// Publications\n\t\tloadSuperAdminPublications(this);\n\t\tloadAppStatusPublications(this);\n\t\tloadLogPublications(this);\n\t\tloadFilePublications(this);\n\t\tloadCronJobPublications(this);\n\t\tloadFlagsPublications(this);\n\t\tloadMethodResponsePublications(this);\n\t\tloadNotificationPublications(this);\n\t\tloadReportBuilderReportPublications(this);\n\t\tloadReportBuilderLibraryPublications(this);\n\t\tloadUserGroupPublications(this);\n\t\tloadUserGuidePublications(this);\n\t\tloadReportBuilderDashboardBuilderPublications(this);\n\n\t\tthis.tailOpLog();\n\n\t\tsetInterval(() => {\n\t\t\tthis._oplogRetryCount = 0;\n\t\t}, 15000);\n\n\t\tsetInterval(() => {\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Subs', this._subscriptions.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Logged In Users', this._loggedInUsers.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue', this._mongoQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Hits', this._debugMongoQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Collections', JSON.stringify(this._debugMongoQueueCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Hits', this._debugOplogHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Collections', JSON.stringify(this._debugOplogCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.type.localeCompare(b.type)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Hits', this._debugSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Collections', JSON.stringify(this._debugSubCollections.sort((a, b) => a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub Hits', this._debugUnSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub All Hits', this._debugUnSubAllHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Cache Cleanup Hits', this._debugRemoveCacheHits);\n\t\t\t}\n\t\t\t\n\t\t\tthis._debugOplogHits = 0;\n\t\t\tthis._debugOplogCollections = [];\n\t\t\tthis._debugSubCollections = [];\n\t\t\tthis._debugMongoQueueHits = 0;\n\t\t\tthis._debugMongoQueueCollections = [];\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSubHits = 0;\n\t\t\tthis._debugUnSubHits = 0;\n\t\t\tthis._debugUnSubAllHits = 0;\n\t\t\tthis._debugRemoveCacheHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(async () => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\t// let startDate = new Date();\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 1);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t// \tfunction: 'sendInterval',\n\t\t\t\t\t// \tpublication: '',\n\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t// \tresult: 'Done'\n\t\t\t\t\t// });\n\t\t\t\t}\n\n\t\t\t\tconst queueArr = this._mongoQueue.filter(a => !a.running);\n\t\t\t\tif (queueArr.length) {\n\t\t\t\t\tqueueArr.forEach(entry => {\n\t\t\t\t\t\tentry.running = true;\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (let i = queueArr.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugMongoQueueHits += 1;\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet mongoQueue = queueArr[i];\n\n\t\t\t\t\t\tif (!this._debugMongoQueueCollections.some(a => a.collection === mongoQueue.collection && a.publication === mongoQueue.subscription.publication)) {\n\t\t\t\t\t\t\tthis._debugMongoQueueCollections.push({\n\t\t\t\t\t\t\t\tcollection: mongoQueue.collection,\n\t\t\t\t\t\t\t\tpublication: mongoQueue.subscription.publication,\n\t\t\t\t\t\t\t\thits: 1\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._debugMongoQueueCollections.filter(a => a.collection === mongoQueue.collection && a.publication === mongoQueue.subscription.publication)[0].hits += 1;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (this._publications[mongoQueue.subscription.publication].user_specific) {\n\t\t\t\t\t\t\tlet promises = [];\n\t\t\t\t\t\t\tfor (let j = 0; j < mongoQueue.subscription.clients.length; j++) {\n\t\t\t\t\t\t\t\tlet client = mongoQueue.subscription.clients[j];\n\t\t\t\t\t\t\t\tlet ws = this._mainServer.getWS(client.id_socket);\n\t\t\t\t\t\t\t\tif (ws && ws['id_socket'] === client.id_socket) {\n\t\t\t\t\t\t\t\t\tpromises.push(this.sendDataToOne(ws, client.messageId, mongoQueue.subscription, mongoQueue.type, mongoQueue.collection).catch((err) => {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During sendDataToOne - User Specific - Socket: ' + client.id_socket + ', User: ' + client.id_user + ', MessageId: ' + client.messageId + ', Pub: ' + mongoQueue.subscription.publication + ', Err: ' + JSON.stringify(err, null, 2));\n\t\t\t\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tPromise.all(promises).then(() => {\n\t\t\t\t\t\t\t\tif (mongoQueue.run_again) {\n\t\t\t\t\t\t\t\t\tmongoQueue.running = false;\n\t\t\t\t\t\t\t\t\tmongoQueue.run_again = false;\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\tif (this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id) >= 0) {\n\t\t\t\t\t\t\t\t\t\tthis._mongoQueue.splice(this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id), 1);\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\telse {\n\t\t\t\t\t\t\tthis.sendDataToAll(mongoQueue).then(() => {\n\t\t\t\t\t\t\t\tif (mongoQueue.run_again) {\n\t\t\t\t\t\t\t\t\tmongoQueue.running = false;\n\t\t\t\t\t\t\t\t\tmongoQueue.run_again = false;\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\tif (this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id) >= 0) {\n\t\t\t\t\t\t\t\t\t\tthis._mongoQueue.splice(this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id), 1);\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\t\tif (this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id) >= 0) {\n\t\t\t\t\t\t\t\t\tthis._mongoQueue.splice(this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id), 1);\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\n\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\n\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t// \tfunction: 'mongoQueue',\n\t\t\t\t\t// \tpublication: '',\n\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t// \tresult: 'Done'\n\t\t\t\t\t// });\n\t\t\t\t}\t\n\n\t\t\t\tthis._runningQueue = false;\n\t\t\t}\n\t\t}, 25);\n\n\t\tsetInterval(async () => {\n\t\t\tthis._loggedInUsers = await LoggedInUsers.find();\n\t\n\t\t\tlet userCopy = deepCopy(this._loggedInUsers);\n\t\t\tfor (let i = this._loggedInUsers.length - 1; i >= 0; i--) {\n\t\t\t\tlet loggedInUser = userCopy[i];\n\n\t\t\t\tif (!loggedInUser.date || Date.now() - loggedInUser.date.getTime() > 120000) {\n\t\t\t\t\tif (this._mainServer.getWS(loggedInUser.id_ws)) {\n\t\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', this._mainServer.getWS(loggedInUser.id_ws)['user'], this._mainServer.getWS(loggedInUser.id_ws)['id_socket'], 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.unsubscribeAll(this._mainServer.getWS(loggedInUser.id_ws));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._subscriptions.forEach(sub => {\n\t\t\t\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\t\t\t\tif (client.id_socket === loggedInUser.id_ws) {\n\t\t\t\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tLoggedInUsers.deleteOne({_id: loggedInUser._id});\n\n\t\t\t\t\t\tif (this._loggedInUsers.findIndex(a => a._id === loggedInUser._id) >= 0) {\n\t\t\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.findIndex(a => a._id === loggedInUser._id), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (let i = 0; i < this._subscriptions.length; i++) {\n\t\t\t\tlet sub = this._subscriptions[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\tif (!this._loggedInUsers.some(a => a.id_ws === client.id_socket)) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, 30000);\n\n\t\tFlags.findOne({type: 'Enable Debug'}).then(flag => {\n\t\t\tif (flag && flag.value) {\n\t\t\t\tthis._enableDebug = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._enableDebug = false;\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate addToQueue(mongoQueue: MongoQueueModel) {\n\t\t// let startDate = new Date();\n\n\t\tlet _mongoQueue = this._mongoQueue.filter(a => a.subscription.publication === mongoQueue.subscription.publication && JSON.stringify(a.subscription.subscriptionData) === JSON.stringify(mongoQueue.subscription.subscriptionData))[0];\n\t\t\n\t\tif (_mongoQueue) {\n\t\t\tif (_mongoQueue.running) {\n\t\t\t\t_mongoQueue.run_again = true;\n\n\t\t\t\t// let endDate = new Date();\n\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t// \tfunction: 'addToQueue',\n\t\t\t\t// \tpublication: mongoQueue.subscription.publication,\n\t\t\t\t// // \tsubscriptionData: mongoQueue.subscription.subscriptionData,\n\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t// \tresult: 'Run Again'\n\t\t\t\t// });\n\t\t\t}\n\t\t\t// else {\n\t\t\t// \tlet endDate = new Date();\n\t\t\t// \tthis.currentPerfomanceMonitor.push({\n\t\t\t// \t\t_id: this.idPerformance++,\n\t\t\t// \t\tfunction: 'addToQueue',\n\t\t\t// \t\tpublication: mongoQueue.subscription.publication,\n\t\t\t// // \tsubscriptionData: mongoQueue.subscription.subscriptionData,\n\t\t\t// \t\tsubscriptionData: [],\n\t\t\t// \t\tdate_start: startDate,\n\t\t\t// \t\tdate_end: endDate,\n\t\t\t// \t\tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t// \t\tresult: 'Not Running Yet'\n\t\t\t// \t});\n\t\t\t// }\n\t\t}\n\t\telse {\n\t\t\tmongoQueue._id = this._mongoQueueId;\n\t\t\tthis._mongoQueueId += 1;\n\n\t\t\tthis._mongoQueue.splice(0, 0, mongoQueue);\n\t\t\t\n\t\t\t// let endDate = new Date();\n\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t// \t_id: this.idPerformance++,\n\t\t\t// \tfunction: 'addToQueue',\n\t\t\t// \tpublication: mongoQueue.subscription.publication,\n\t\t\t// // \tsubscriptionData: mongoQueue.subscription.subscriptionData,\n\t\t\t// \tsubscriptionData: [],\n\t\t\t// \tdate_start: startDate,\n\t\t\t// \tdate_end: endDate,\n\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t// \tresult: 'Add to Queue'\n\t\t\t// });\n\t\t}\n\t}\n\n\tpublic invalidatePubsCache(collection, type) {\n\t\t// let startDate = new Date();\n\n\t\tResolveIOServer.getMongoManager().invalidateQueryCache(collection);\n\t\t\n\t\tlet collSubs = this._subscriptions.filter(a => a.collections.includes(collection));\n\n\t\tfor (let i = collSubs.length - 1; i >= 0; i--) {\n\t\t\tlet sub = collSubs[i];\n\t\t\t\n\t\t\tthis.addToQueue({\n\t\t\t\t_id: 0,\n\t\t\t\ttype: type,\n\t\t\t\tcollection: collection,\n\t\t\t\tsubscription: sub,\n\t\t\t\trunning: false,\n\t\t\t\trun_again: false\n\t\t\t});\n\t\t}\n\n\t\t// let endDate = new Date();\n\t\t// this.currentPerfomanceMonitor.push({\n\t\t// \t_id: this.idPerformance++,\n\t\t// \tfunction: 'invalidatePubsCache',\n\t\t// \tpublication: collection,\n\t\t// \tsubscriptionData: [],\n\t\t// \tdate_start: startDate,\n\t\t// \tdate_end: endDate,\n\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t// \tresult: 'Done'\n\t\t// });\n\t}\n\n\t// Add all files to publications private object\n\tpublic publications(method: SubscriptionModel) {\n\t\tthis._publications = Object.assign(this._publications, method);\n\t}\n\n\tpublic loggedInLatency(ws: WebSocket) {\n\t\tlet loggedInUser = this._loggedInUsers.filter(a => a.id_ws === ws['id_socket'])[0];\n\n\t\tif (loggedInUser) {\n\t\t\tloggedInUser.date = new Date();\n\n\t\t\tLoggedInUsers.updateOne({id_ws: ws['id_socket']}, {$set: {latency: ws['latency'], date: loggedInUser.date}}).then(res => {\n\t\t\t\tif (!res) {\n\t\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 3);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, () => {\n\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 4);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Subscribe to publication\n\tpublic subscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\t// let startDate = new Date();\n\t\tthis._debugSubHits += 1;\n\n\t\tif (!this._debugSubCollections.some(a => a.publication === publication)) {\n\t\t\tthis._debugSubCollections.push({\n\t\t\t\tpublication: publication,\n\t\t\t\thits: 1\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tthis._debugSubCollections.filter(a => a.publication === publication)[0].hits += 1;\n\t\t}\n\n\t\tlet pub = this._publications[publication];\n\n\t\tif (!pub) {\n\t\t\tconsole.error(new Date(), 'No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tif (subscriptionData.length > 1 || subscriptionData[0]) {\n\t\t\t\tif (!pub.check) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Function For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (!pub.check._schema) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Schema For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet valObj = {};\n\t\t\t\t\tlet valKeys = Object.keys(pub.check._schema);\n\n\t\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\t\n\t\t\t\t\tfor (let i = 0; i < subscriptionData.length; i++) {\n\t\t\t\t\t\tvalObj[rootKeys[i]] = subscriptionData[i];\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpub.check.validate(valObj);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (errors) {\n\t\t\t\t\t\tif (errors) {\n\t\t\t\t\t\t\tconsole.error(new Date(), 'Error in Pub Check (' + publication + ')', errors);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (messageRoute !== 'Bypass') {\n\t\t\t\tlet urlData = messageRoute.split('/');\n\t\t\t\tlet urlModule = '';\n\t\t\t\tlet urlNext = urlData[0];\n\t\t\t\t\n\t\t\t\tif (urlData[0] === '') {\n\t\t\t\t\turlModule = '/';\n\t\t\t\t\turlNext = urlData[1];\n\t\t\t\t}\n\n\t\t\t\turlModule += urlNext;\n\n\t\t\t\tif (urlData.length > 1) {\n\t\t\t\t\turlModule += '/';\n\t\t\t\t}\n\n\t\t\t\tlet otherRouteSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_socket === ws['id_socket'] && b.messageRoute !== 'Bypass' && b.messageRoute !== '/' && b.messageRoute !== messageRoute && !b.messageRoute.startsWith(urlModule)));\n\t\t\t\n\t\t\t\tif (otherRouteSubs.length) {\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Detected Undestroyed Subscription - ' + this.serverConfig['CLIENT_NAME'], 'USER: ' + ws['user'] + ' (Socket: ' + ws['id_socket'] + ') ' + ' is on route: ' + messageRoute + ' but has the following subscriptions on other routes:' + JSON.stringify(otherRouteSubs, null, 2));\n\n\t\t\t\t\totherRouteSubs.forEach(otherSub => {\n\t\t\t\t\t\totherSub.clients.filter(a => a.id_socket === ws['id_socket']).forEach(client => {\n\t\t\t\t\t\t\tthis.unsubscribe(client.messageRoute, new Date(), ws, client.messageId, otherSub.publication, otherSub.subscriptionData);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet sub = this._subscriptions.filter(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData))[0];\n\n\t\t\t// If sub found (another user watching same data), add client to same sub\n\t\t\tif (sub) {\n\t\t\t\tif (!sub.clients.some(a => a.id_socket === ws['id_socket'] && a.messageId === messageId)) {\n\t\t\t\t\tsub.clients.push({\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If sub not found, create new sub\n\t\t\telse {\n\t\t\t\tthis._subscriptions.push({\n\t\t\t\t\tpublication: publication,\n\t\t\t\t\tsubscriptionData: subscriptionData,\n\t\t\t\t\tcollections: this.getPublicationCollections(publication),\n\t\t\t\t\tclients: [{\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute\n\t\t\t\t\t}],\n\t\t\t\t\tcacheId: 0\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!sub) {\n\t\t\t\tsub = this._subscriptions.filter(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData))[0];\n\t\t\t}\n\n\t\t\tif (!sub.cacheId && !this._mongoQueue.some(a => a.subscription.publication === sub.publication && JSON.stringify(a.subscription.subscriptionData) === JSON.stringify(sub.subscriptionData))) {\n\t\t\t\tthis.addToQueue({\n\t\t\t\t\t_id: 0,\n\t\t\t\t\ttype: 'newSub',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tsubscription: sub,\n\t\t\t\t\trunning: false,\n\t\t\t\t\trun_again: false\n\t\t\t\t});\n\n\t\t\t\t// let endDate = new Date();\n\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t// \tfunction: 'subscribe',\n\t\t\t\t// \tpublication: publication,\n\t\t\t\t// // \tsubscriptionData: subscriptionData,\n\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t// \tresult: 'Add to Queue'\n\t\t\t\t// });\n\t\t\t}\n\t\t\telse if (sub.cacheId) {\n\t\t\t\tthis.sendDataToOne(ws, messageId, sub, 'newSub', publication);\n\n\t\t\t\t// let endDate = new Date();\n\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t// \tfunction: 'subscribe',\n\t\t\t\t// \tpublication: publication,\n\t\t\t\t// // \tsubscriptionData: subscriptionData,\n\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t// \tresult: 'Send Pub Data Once'\n\t\t\t\t// });\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async createLoggedInUser(id_ws: string): Promise<LoggedInUserModel> {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tlet ws = this._mainServer.getWS(id_ws);\n\n\t\t\tif (ws) {\n\t\t\t\tlet user = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\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\t\n\t\t\t\tthis._loggedInUsers.push(user);\n\t\t\t\tLoggedInUsers.insertOne(user);\n\t\t\t\t\n\t\t\t\tresolve(user);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(null);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Unsubscribe from publication \n\tpublic unsubscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugUnSubHits += 1;\n\t\t// let startDate = new Date();\n\t\t// console.log('Before');\n\t\t// console.dir(this._subscriptions.map(a => a.publication));\n\n\t\tif (!this._publications[publication]) {\n\t\t\tconsole.log('No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet sub = this._subscriptions.filter(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData))[0];\n\n\t\t\tif (sub) {\n\t\t\t\tfor (let i = sub.clients.length - 1; i >= 0; i--) {\n\t\t\t\t\tif (sub.clients[i].id_user === ws['id_user'] && sub.clients[i].messageId === messageId && sub.clients[i].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(i, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// let endDate = new Date();\n\t\t// this.currentPerfomanceMonitor.push({\n\t\t// \t_id: this.idPerformance++,\n\t\t// \tfunction: 'unsubscribe',\n\t\t// \tpublication: publication,\n\t\t// // \tsubscriptionData: subscriptionData,\n\t\t// \tsubscriptionData: [],\n\t\t// \tdate_start: startDate,\n\t\t// \tdate_end: endDate,\n\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t// \tresult: 'Done'\n\t\t// });\n\t}\n\n\t// Unsubscribe from publication\n\tpublic async unsubscribeAll(ws: WebSocket) {\n\t\tthis._debugUnSubAllHits += 1;\n\t\t// console.log('Before');\n\t\t// console.dir(this._subscriptions.map(a => a.publication));\n\n\t\t// let startDate = new Date();\n\n\t\tif (ws) {\n\t\t\tlet loggedInUser = await LoggedInUsers.findOne({id_ws: ws['id_socket']});\n\n\t\t\tif (loggedInUser) {\t\n\t\t\t\tif (this._loggedInUsers.map(a => a._id).indexOf(loggedInUser._id) >= 0) {\n\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.map(a => a._id).indexOf(loggedInUser._id), 1);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tLoggedInUsers.deleteOne({_id: loggedInUser._id});\n\t\t\t}\n\n\t\t\tlet userSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_user === ws['id_user'] && b.id_socket === ws['id_socket']));\n\n\t\t\tfor (let i = userSubs.length - 1; i >= 0; i--) {\n\t\t\t\tlet sub = userSubs[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tif (sub.clients[j].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws.close();\n\n\t\t\tprocess.nextTick(() => {\n\t\t\t\tif ([ws.OPEN, ws.CLOSING].includes(<any>ws.readyState)) {\n\t\t\t\t\t// Socket still hangs, hard close\n\t\t\t\t\tws.terminate();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// let endDate = new Date();\n\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t// \t_id: this.idPerformance++,\n\t\t\t// \tfunction: 'unsubscribeAll',\n\t\t\t// \tpublication: '',\n\t\t\t// \tsubscriptionData: [],\n\t\t\t// \tdate_start: startDate,\n\t\t\t// \tdate_end: endDate,\n\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t// \tresult: 'Done'\n\t\t\t// });\n\t\t}\n\n\t\t// console.log('After');\n\t\t// console.dir(this._subscriptions.map(a => a.publication));\n\t}\n\n\tpublic getActiveSubscriptions() {\n\t\treturn this._subscriptions;\n\t}\n\n\t// Get publication collection\n\tprivate getPublicationCollections(publication: string) {\n\t\treturn this._publications[publication].collections;\n\t}\n\n\t// Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)\n\tprivate async tailOpLog(resumeToken?: ResumeToken) {\n\t\tif (this._oplog$ && !this._oplog$.closed) {\n\t\t\tthis._oplog$.removeAllListeners();\n\t\t\tthis._oplog$.close();\n\t\t\tthis._oplog$ = null;\n\t\t}\n\t\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\n\t\tif (!this._oplog$ || this._oplog$.closed) {\n\t\t\tthis._oplogRetryCount += 1;\n\n\t\t\tif (this._oplogRetryCount > 5) {\n\t\t\t\tconsole.error('****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************')\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\tlet lastResumeToken: ResumeToken;\n\n\t\t\tif (resumeToken) {\n\t\t\t\tlastResumeToken = resumeToken;\n\t\t\t\ttry {\n\t\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch([], {resumeAfter: resumeToken});\n\t\t\t\t}\n\t\t\t\tcatch(errOp) {\n\t\t\t\t\tif (this._oplog$) {\n\t\t\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\t\t\tthis._oplog$.close();\n\t\t\t\t\t\tthis._oplog$ = null;\n\t\t\t\t\t}\n\t\t\t\t\tthis.tailOpLog(resumeToken);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch();\n\t\t\t}\n\n\t\t\tconsole.log(new Date(), 'oplog started');\n\n\t\t\tthis._oplog$.on('change', (doc: ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument) => {\n\t\t\t\t// let startDate = new Date();\n\n\t\t\t\tif (doc.ns) {\n\t\t\t\t\tlet collection = doc.ns.coll;\n\n\t\t\t\t\tif (!this._debugOplogCollections.some(a => a.collection === doc.ns.coll && a.type === doc.operationType)) {\n\t\t\t\t\t\tthis._debugOplogCollections.push({\n\t\t\t\t\t\t\tcollection: doc.ns.coll,\n\t\t\t\t\t\t\ttype: doc.operationType,\n\t\t\t\t\t\t\thits: 1\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\tthis._debugOplogCollections.filter(a => a.collection === doc.ns.coll && a.type === doc.operationType)[0].hits += 1;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// console.log(new Date(), 'Op log doc', doc.operationType, collection);\n\n\t\t\t\t\tif (collection && !collection.endsWith('.versions') && !collection.startsWith('monitor-') && collection !== 'logs' && collection !== 'log-method-latencies' && collection !== 'log-subscriptions') {\n\t\t\t\t\t\tthis._debugOplogHits += 1;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\t\t\tif (collection === 'support-tickets') {\n\t\t\t\t\t\t\t\tif (this.serverConfig['ROOT_URL'] === 'https://resolveio.com') {\n\t\t\t\t\t\t\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'sendSupportTicketEmail', doc.documentKey['_id']);\n\t\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t\t// \tfunction: 'oplog',\n\t\t\t\t\t\t\t// \tpublication: collection,\n\t\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t\t// \tresult: 'Insert'\n\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'update' || doc.operationType === 'replace') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'update');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t\t// \tfunction: 'oplog',\n\t\t\t\t\t\t\t// \tpublication: collection,\n\t\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t\t// \tresult: 'Update'\n\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'delete');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t\t// \tfunction: 'oplog',\n\t\t\t\t\t\t\t// \tpublication: collection,\n\t\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t\t// \tresult: 'Delete'\n\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection === 'flags') {\n\t\t\t\t\t\tFlags.findOne({type: 'Enable Debug'}).then(flag => {\n\t\t\t\t\t\t\tif (flag && flag.value) {\n\t\t\t\t\t\t\t\tthis._enableDebug = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._enableDebug = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tlastResumeToken = doc._id;\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\tthis._oplog$.on('error', error => {\n\t\t\t\tconsole.log(new Date(), 'oplog error', error);\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('end', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog end');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog close');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\t\t}\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate sendDataToOne(ws: WebSocket, messageId: number, subscription: ActiveSubscriptionModel, type: string, collection: string) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// let startDate = new Date();\n\n\t\t\tif (!this._publications[subscription.publication].user_specific) { // Same pub for all users\n\t\t\t\tif (subscription.cacheId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(subscription.cacheId), dateReviver);\n\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: cacheData\n\t\t\t\t\t\t};\n\t\n\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t}\n\t\t\t\t\tcatch(err) {\n\t\t\t\t\t\tthis._nodeCache.del(subscription.cacheId);\n\t\t\t\t\t\tsubscription.cacheId = 0;\n\n\t\t\t\t\t\tthis.addToQueue({\n\t\t\t\t\t\t\t_id: 0,\n\t\t\t\t\t\t\ttype: 'newSub',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tsubscription: subscription,\n\t\t\t\t\t\t\trunning: false,\n\t\t\t\t\t\t\trun_again: false\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t// \tfunction: 'sendDataToOne',\n\t\t\t\t\t// \tpublication: subscription.publication,\n\t\t\t\t\t// // \tsubscriptionData: subscription.subscriptionData,\n\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t// \tresult: 'Send cache'\n\t\t\t\t\t// });\n\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During sendDataToOne - No Cache! - ' + subscription.publication + '\\n\\nData \\n' + JSON.stringify(subscription.subscriptionData, null, 2));\n\n\t\t\t\t\tresolve(false);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // Pub is different for each user (Look at users publication) [MUCH SLOWER, RE-RUNS FOR EACH USER]\n\t\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', subscription.publication, '', '', subscription.subscriptionData);\n\t\t\t\tthis._publications[subscription.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ws['id_user'], ...subscription.subscriptionData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\tdata: res\n\t\t\t\t\t};\n\n\t\t\t\t\t// console.log('Send Pub Data Once 2', new Date(), 'Success', subscription);\n\n\t\t\t\t\tthis.sendWS(ws, serverRes);\n\n\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t// \tfunction: 'sendDataToOne',\n\t\t\t\t\t// \tpublication: subscription.publication,\n\t\t\t\t\t// // \tsubscriptionData: subscription.subscriptionData,\n\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t// \tresult: 'Send ws spec data'\n\t\t\t\t\t// });\n\n\t\t\t\t\tresolve(true);\n\n\t\t\t\t}, err => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\t\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\tdata: err\n\t\t\t\t\t};\n\n\t\t\t\t\t// console.log('Send Pub Data Once 2', new Date(), 'Error', subscription);\n\n\t\t\t\t\tthis.sendWS(ws, serverRes);\n\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + subscription.publication + ' - (sendDataToOne - WS)\\n\\nData \\n' + JSON.stringify(subscription.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\n\t\t\t\t\treject(err);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate sendDataToAll(mongoQueue: MongoQueueModel) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// let startDate = new Date();\n\t\t\tif (!mongoQueue.subscription.clients.length) {\t\t\t\t\n\t\t\t\tif (mongoQueue.subscription.cacheId) {\n\t\t\t\t\tthis._nodeCache.del(mongoQueue.subscription.cacheId);\n\t\t\t\t}\n\n\t\t\t\tif (this._subscriptions.findIndex(a => a.publication === mongoQueue.subscription.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(mongoQueue.subscription.subscriptionData)) >= 0) {\n\t\t\t\t\tthis._subscriptions.splice(this._subscriptions.findIndex(a => a.publication === mongoQueue.subscription.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(mongoQueue.subscription.subscriptionData)), 1);\n\t\t\t\t}\n\n\t\t\t\tresolve(false);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (mongoQueue.subscription.publication !== 'superadminAPM' && mongoQueue.subscription.publication !== 'loggedInUsers') {\n\t\t\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'insertSubscriptionLog', mongoQueue.type, mongoQueue.subscription.publication, mongoQueue.collection, JSON.stringify(mongoQueue.subscription.subscriptionData));\n\t\t\t\t}\n\n\t\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Publication', mongoQueue.subscription.publication, '', '', mongoQueue.subscription.subscriptionData);\n\t\t\t\tthis._publications[mongoQueue.subscription.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ...mongoQueue.subscription.subscriptionData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tif (!mongoQueue.subscription.clients.length) {\n\t\t\t\t\t\tlet nodeCacheSize = this._nodeCache.getStats().vsize;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (nodeCacheSize > this._heapLimit) {\n\t\t\t\t\t\t\tlet deleteCount = 0;\n\n\t\t\t\t\t\t\tconst subArr = this._subscriptions.filter(a => a.cacheId && !a.clients.length);\n\n\t\t\t\t\t\t\tfor (let zz = 0; zz < subArr.length; zz++) {\n\t\t\t\t\t\t\t\tthis._debugRemoveCacheHits += 1;\n\n\t\t\t\t\t\t\t\tthis._nodeCache.del(subArr[zz].cacheId);\n\t\t\t\t\t\t\t\tsubArr[zz].cacheId = 0;\n\n\t\t\t\t\t\t\t\tdeleteCount += 1;\n\n\t\t\t\t\t\t\t\tnodeCacheSize = this._nodeCache.getStats().vsize;\n\n\t\t\t\t\t\t\t\tif (nodeCacheSize < this._heapLimit * 0.75) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tconsole.log('Sub Cache: ' + 'Too Big - ' + mongoQueue.subscription.publication + ' - Deleted: ' + deleteCount + ' - ' + nodeCacheSize);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (mongoQueue.subscription.cacheId) {\n\t\t\t\t\t\t\tthis._nodeCache.del(mongoQueue.subscription.cacheId);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet cacheId = this._cacheId;\n\t\t\t\t\t\tthis._cacheId += 1;\n\n\t\t\t\t\t\tthis._nodeCache.set(cacheId, JSON.stringify(res));\n\t\t\t\t\t\tmongoQueue.subscription.cacheId = cacheId;\n\n\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t// \tfunction: 'sendPubData',\n\t\t\t\t\t\t// \tpublication: subscription.publication,\n\t\t\t\t\t\t// // \tsubscriptionData: subscription.subscriptionData,\n\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t// \tresult: 'No clients'\n\t\t\t\t\t\t// });\n\n\t\t\t\t\t\tresolve(false);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (!mongoQueue.subscription.cacheId || this._nodeCache.get(mongoQueue.subscription.cacheId) !== JSON.stringify(res)) {\n\t\t\t\t\t\t\tmongoQueue.subscription.clients.forEach(client => {\n\t\t\t\t\t\t\t\tlet ws = this._mainServer.getWS(client.id_socket);\n\n\t\t\t\t\t\t\t\tif (ws) {\n\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\n\t\t\t\t\t\t\tlet nodeCacheSize = this._nodeCache.getStats().vsize;\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (nodeCacheSize > this._heapLimit) {\n\t\t\t\t\t\t\t\tlet deleteCount = 0;\n\n\t\t\t\t\t\t\t\tconst subArr = this._subscriptions.filter(a => a.cacheId && !a.clients.length);\n\t\n\t\t\t\t\t\t\t\tfor (let zz = 0; zz < subArr.length; zz++) {\n\t\t\t\t\t\t\t\t\tthis._nodeCache.del(subArr[zz].cacheId);\n\t\t\t\t\t\t\t\t\tsubArr[zz].cacheId = 0;\n\t\n\t\t\t\t\t\t\t\t\tdeleteCount += 1;\n\n\t\t\t\t\t\t\t\t\tnodeCacheSize = this._nodeCache.getStats().vsize;\n\t\n\t\t\t\t\t\t\t\t\tif (nodeCacheSize < this._heapLimit * 0.75) {\n\t\t\t\t\t\t\t\t\t\tbreak;\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\t\n\t\t\t\t\t\t\t\tconsole.log('Sub Cache: ' + 'Too Big - ' + mongoQueue.subscription.publication + ' - Deleted: ' + deleteCount + ' - ' + nodeCacheSize);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (mongoQueue.subscription.cacheId) {\n\t\t\t\t\t\t\t\tthis._nodeCache.del(mongoQueue.subscription.cacheId);\n\t\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\t\tlet cacheId = this._cacheId;\n\t\t\t\t\t\t\tthis._cacheId += 1;\n\n\t\t\t\t\t\t\tthis._nodeCache.set(cacheId, JSON.stringify(res));\n\t\t\t\t\t\t\tmongoQueue.subscription.cacheId = cacheId;\n\n\t\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t\t// \tfunction: 'sendPubData',\n\t\t\t\t\t\t\t// \tpublication: subscription.publication,\n\t\t\t\t\t\t\t// // \tsubscriptionData: subscription.subscriptionData,\n\t\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t\t// \tresult: 'Same data'\n\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tresolve(true);\n\t\t\t\t\t}\n\t\t\t\t}, err => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + mongoQueue.subscription.publication + ' - (sendPubData)\\n\\nData \\n' + JSON.stringify(mongoQueue.subscription.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\n\t\t\t\t\tmongoQueue.subscription.clients.forEach(client => {\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(client.id_socket);\n\n\t\t\t\t\t\tif (ws) {\n\t\t\t\t\t\t\tif (ws['id_socket'] === client.id_socket) {\n\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\t\t\tdata: err\n\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\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\treject(err);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate sendWS(ws: WebSocket, data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tdata: data\n\t\t});\n\t}\n\n\tpublic getEnableDebug() {\n\t\treturn this._enableDebug;\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../../src/managers/subscription.manager.ts"],"names":["logs_1","require","app_status_1","files_1","super_admin_1","logged_in_users_collection_1","cron_jobs_1","flags_1","method_responses_1","index_1","notifications_1","report_builder_reports_1","report_builder_libraries_1","user_groups_1","user_guides_1","report_builder_dashboard_builders_1","mongo_manager_1","common_1","NodeCache","flag_collection_1","os_1","numCPUs","cpus","length","v8","SubscriptionManager","mainServer","wss","serverConfig","monitorManagerFunction","_this","this","_publications","_subscriptions","_loggedInUsers","_mongoQueue","_mongoQueueId","_sendQueue","_runningQueue","_cacheId","_heapStats","getHeapStatistics","_heapLimit","heap_size_limit","_enableDebug","_debugOplogCollections","_debugOplogHits","_debugSubCollections","_debugSubHits","_debugUnSubHits","_debugUnSubAllHits","_debugMongoQueueHits","_debugMongoQueueCollections","_debugSendQueueHits","_debugRemoveCacheHits","_oplogRetryCount","_mainServer","_monitorManagerFunction","_nodeCache","stdTTL","checkperiod","_wss","loadSuperAdminPublications","loadAppStatusPublications","loadLogPublications","loadFilePublications","loadCronJobPublications","loadFlagsPublications","loadMethodResponsePublications","loadNotificationPublications","loadReportBuilderReportPublications","loadReportBuilderLibraryPublications","loadUserGroupPublications","loadUserGuidePublications","loadReportBuilderDashboardBuilderPublications","tailOpLog","setInterval","getEnableDebug","console","log","Date","JSON","stringify","sort","a","b","collection","localeCompare","publication","type","__awaiter","i","this_1","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","data","error","unsubscribeAll","splice","queueArr","filter","running","forEach","entry","this_2","mongoQueue","some","subscription","hits","push","user_specific","promises","j","clients","client","id_socket","sendDataToOne","messageId","catch","err","getMethodManager","sendEmail","id_user","Promise","all","then","run_again","map","_id","indexOf","sendDataToAll","_a","LoggedInUsers","find","_b","sent","userCopy","deepCopy","loggedInUser","date","now","getTime","this_3","sub","deleteOne","findIndex","this_4","Flags","findOne","flag","value","prototype","addToQueue","subscriptionData","invalidatePubsCache","ResolveIOServer","getMongoManager","invalidateQueryCache","collSubs","collections","includes","publications","method","Object","assign","loggedInLatency","updateOne","$set","latency","res","subscribe","messageRoute","messageDate","pub","check","_schema","valObj","rootKeys","keys","validate","errors","urlData","split","urlModule_1","urlNext","otherRouteSubs","startsWith","otherSub","unsubscribe","sub_1","getPublicationCollections","cacheId","createLoggedInUser","resolve","reject","user","objectIdHexString","__v","insertOne","userSubs","close","process","nextTick","CLOSING","terminate","getActiveSubscriptions","resumeToken","_oplog$","closed","removeAllListeners","setTimeout","exit","lastResumeToken_1","getMainDB","watch","resumeAfter","errOp","on","doc","ns","coll","operationType","endsWith","callMethodInternal","call","documentKey","monitor_1","startMonitorFunction","function","apply","__spreadArray","finishMonitorFunction","sendWS","hasError","cacheData","parse","get","dateReviver","serverRes","del","monitor_2","nodeCacheSize","getStats","vsize","deleteCount","subArr","zz","set","exports"],"mappings":"wqDAGAA,Q,0FAAAC,QAAA,s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AAgBwB,EAAWE,aAAa1B,aAAeP,KAAKC,UAAUE,EAAE4E,gBAAgB,IAAM/E,KAAKC,UAAU8B,EAAWE,aAAa8C,gBAAgB,CAAvJ,CAAwJ,EAAG,CAAC,EAG3NwC,EAAQ,CAAA,CAAK,G,QAsJd,CACF,EAEQ/K,oBAAAqI,UAAAiF,OAAR,SAAejJ,EAAeQ,GAC7BvE,KAAKM,WAAWoE,OAAO,EAAG,EAAG,CAC5BT,MAAOF,EAAc,UACrBQ,KAAMA,C,CACN,CACF,EAEO7E,oBAAAqI,UAAAjF,eAAP,WACC,OAAO9C,KAAKa,YACb,EACDnB,mBAAA,EAAC,EA/nCYsO,QAAAtO,oBAAAA","file":"subscription.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { ActiveSubscriptionModel, SubscriptionModel } from '../models/subscription.model';\nimport * as WebSocket from 'ws';\nimport { loadLogPublications } from '../publications/logs';\nimport { loadAppStatusPublications } from '../publications/app-status';\nimport { loadFilePublications } from '../publications/files';\nimport { loadSuperAdminPublications } from '../publications/super-admin';\nimport { LoggedInUsers } from '../collections/logged-in-users.collection';\nimport { loadCronJobPublications } from '../publications/cron-jobs';\nimport { loadFlagsPublications } from '../publications/flags';\nimport { loadMethodResponsePublications } from '../publications/method-responses';\nimport ResolveIOMainServer from '../server-app';\nimport { ResolveIOServer } from '../index';\nimport { loadNotificationPublications } from '../publications/notifications';\nimport { loadReportBuilderReportPublications } from '../publications/report-builder-reports';\nimport { LoggedInUserModel } from '../models/logged-in-users.model';\n\nimport { ChangeStream, ChangeStreamDeleteDocument, ChangeStreamDocument, ChangeStreamInsertDocument, ChangeStreamReplaceDocument, ChangeStreamUpdateDocument, ResumeToken } from 'mongodb';\nimport { loadReportBuilderLibraryPublications } from '../publications/report-builder-libraries';\nimport { loadUserGroupPublications } from '../publications/user-groups';\nimport { loadUserGuidePublications } from '../publications/user-guides';\nimport { loadReportBuilderDashboardBuilderPublications } from '../publications/report-builder-dashboard-builders';\nimport { objectIdHexString } from './mongo.manager';\nimport { dateReviver, deepCopy } from '../util/common';\nimport * as NodeCache from 'node-cache';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { Flags } from '../collections/flag.collection';\nimport { cpus } from 'os';\nconst numCPUs = cpus().length;\nconst v8 = require('v8');\n\n// Performance Dependencies\n// import * as path from 'path';\n// import { Worker } from 'worker_threads';\n\ninterface MongoQueueModel {\n\t_id: number,\n\ttype: string;\n\tcollection: string;\n\tsubscription: ActiveSubscriptionModel;\n\trunning: boolean;\n\trun_again: boolean;\n}\n\n// interface CurrentPerformanceMonitor {\n// \t_id: number;\n// \tfunction: string;\n// \tpublication: string;\n// \tsubscriptionData: any[];\n// \tdate_start: Date;\n// \tdate_end: Date;\n// \tduration: number;\n// \tresult: string;\n// }\n\nexport class SubscriptionManager {\n\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _publications: SubscriptionModel = {};\n\tprivate _subscriptions: ActiveSubscriptionModel[] = [];\n\tprivate _wss: WebSocket.Server;\n\tprivate _loggedInUsers: LoggedInUserModel[] = [];\n\n\tprivate _mongoQueue: MongoQueueModel[] = [];\n\tprivate _mongoQueueId = 0;\n\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\t\n\tprivate _oplog$: ChangeStream;\n\n\tprivate _nodeCache;\n\tprivate _cacheId = 1;\n\n\tprivate serverConfig;\n\n\tprivate _heapStats = v8.getHeapStatistics();\n\tprivate _heapLimit = this._heapStats.heap_size_limit / numCPUs / 8;\n\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _enableDebug = false;\n\tprivate _debugOplogCollections = [];\n\tprivate _debugOplogHits = 0;\n\tprivate _debugSubCollections = [];\n\tprivate _debugSubHits = 0;\n\tprivate _debugUnSubHits = 0;\n\tprivate _debugUnSubAllHits = 0;\n\tprivate _debugMongoQueueHits = 0;\n\tprivate _debugMongoQueueCollections = [];\n\tprivate _debugSendQueueHits = 0;\n\tprivate _debugRemoveCacheHits = 0;\n\n\tprivate _oplogRetryCount = 0;\n\n\t// private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];\n\t// private idPerformance: number = 0;\n\t// private performanceThread;\n\n\tconstructor(mainServer, wss: WebSocket.Server, serverConfig, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\tthis._nodeCache = new NodeCache( { stdTTL: 0, checkperiod: 0 } );\n\n\t\t// setTimeout(() => {\n\t\t// \tconsole.log('Setting up performance thread');\n\n\t\t// \tthis.performanceThread = new Worker(path.join(__dirname, './subscription.performance.js'));\n\n\t\t// \tthis.performanceThread.on('exit', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD EXITED!!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\n\t\t// \tthis.performanceThread.on('error', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD RECV ERROR !!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\t\t// }, 5000);\n\n\t\t// setInterval(() => {\n\t\t// \tconsole.log('Post thread msg');\n\t\t// \tthis.performanceThread.postMessage(this.currentPerfomanceMonitor);\n\t\t// \tthis.currentPerfomanceMonitor = [];\n\t\t// }, 10000);\n\n\t\tthis.serverConfig = serverConfig;\n\t\tthis._wss = wss;\n\n\t\t// Publications\n\t\tloadSuperAdminPublications(this);\n\t\tloadAppStatusPublications(this);\n\t\tloadLogPublications(this);\n\t\tloadFilePublications(this);\n\t\tloadCronJobPublications(this);\n\t\tloadFlagsPublications(this);\n\t\tloadMethodResponsePublications(this);\n\t\tloadNotificationPublications(this);\n\t\tloadReportBuilderReportPublications(this);\n\t\tloadReportBuilderLibraryPublications(this);\n\t\tloadUserGroupPublications(this);\n\t\tloadUserGuidePublications(this);\n\t\tloadReportBuilderDashboardBuilderPublications(this);\n\n\t\tthis.tailOpLog();\n\n\t\tsetInterval(() => {\n\t\t\tthis._oplogRetryCount = 0;\n\t\t}, 15000);\n\n\t\tsetInterval(() => {\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Subs', this._subscriptions.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Logged In Users', this._loggedInUsers.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue', this._mongoQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Hits', this._debugMongoQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Collections', JSON.stringify(this._debugMongoQueueCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Hits', this._debugOplogHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Collections', JSON.stringify(this._debugOplogCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.type.localeCompare(b.type)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Hits', this._debugSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Collections', JSON.stringify(this._debugSubCollections.sort((a, b) => a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub Hits', this._debugUnSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub All Hits', this._debugUnSubAllHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Cache Cleanup Hits', this._debugRemoveCacheHits);\n\t\t\t}\n\t\t\t\n\t\t\tthis._debugOplogHits = 0;\n\t\t\tthis._debugOplogCollections = [];\n\t\t\tthis._debugSubCollections = [];\n\t\t\tthis._debugMongoQueueHits = 0;\n\t\t\tthis._debugMongoQueueCollections = [];\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSubHits = 0;\n\t\t\tthis._debugUnSubHits = 0;\n\t\t\tthis._debugUnSubAllHits = 0;\n\t\t\tthis._debugRemoveCacheHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(async () => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\t// let startDate = new Date();\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 1);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t// \tfunction: 'sendInterval',\n\t\t\t\t\t// \tpublication: '',\n\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t// \tresult: 'Done'\n\t\t\t\t\t// });\n\t\t\t\t}\n\n\t\t\t\tconst queueArr = this._mongoQueue.filter(a => !a.running);\n\t\t\t\tif (queueArr.length) {\n\t\t\t\t\tqueueArr.forEach(entry => {\n\t\t\t\t\t\tentry.running = true;\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (let i = queueArr.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugMongoQueueHits += 1;\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet mongoQueue = queueArr[i];\n\n\t\t\t\t\t\tif (!this._debugMongoQueueCollections.some(a => a.collection === mongoQueue.collection && a.publication === mongoQueue.subscription.publication)) {\n\t\t\t\t\t\t\tthis._debugMongoQueueCollections.push({\n\t\t\t\t\t\t\t\tcollection: mongoQueue.collection,\n\t\t\t\t\t\t\t\tpublication: mongoQueue.subscription.publication,\n\t\t\t\t\t\t\t\thits: 1\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._debugMongoQueueCollections.filter(a => a.collection === mongoQueue.collection && a.publication === mongoQueue.subscription.publication)[0].hits += 1;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (this._publications[mongoQueue.subscription.publication].user_specific) {\n\t\t\t\t\t\t\tlet promises = [];\n\t\t\t\t\t\t\tfor (let j = 0; j < mongoQueue.subscription.clients.length; j++) {\n\t\t\t\t\t\t\t\tlet client = mongoQueue.subscription.clients[j];\n\t\t\t\t\t\t\t\tlet ws = this._mainServer.getWS(client.id_socket);\n\t\t\t\t\t\t\t\tif (ws && ws['id_socket'] === client.id_socket) {\n\t\t\t\t\t\t\t\t\tpromises.push(this.sendDataToOne(ws, client.messageId, mongoQueue.subscription, mongoQueue.type, mongoQueue.collection).catch((err) => {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During sendDataToOne - User Specific - Socket: ' + client.id_socket + ', User: ' + client.id_user + ', MessageId: ' + client.messageId + ', Pub: ' + mongoQueue.subscription.publication + ', Err: ' + JSON.stringify(err, null, 2));\n\t\t\t\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tPromise.all(promises).then(() => {\n\t\t\t\t\t\t\t\tif (mongoQueue.run_again) {\n\t\t\t\t\t\t\t\t\tmongoQueue.running = false;\n\t\t\t\t\t\t\t\t\tmongoQueue.run_again = false;\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\tif (this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id) >= 0) {\n\t\t\t\t\t\t\t\t\t\tthis._mongoQueue.splice(this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id), 1);\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\telse {\n\t\t\t\t\t\t\tthis.sendDataToAll(mongoQueue).then(() => {\n\t\t\t\t\t\t\t\tif (mongoQueue.run_again) {\n\t\t\t\t\t\t\t\t\tmongoQueue.running = false;\n\t\t\t\t\t\t\t\t\tmongoQueue.run_again = false;\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\tif (this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id) >= 0) {\n\t\t\t\t\t\t\t\t\t\tthis._mongoQueue.splice(this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id), 1);\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\t\tif (this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id) >= 0) {\n\t\t\t\t\t\t\t\t\tthis._mongoQueue.splice(this._mongoQueue.map(a => a._id).indexOf(mongoQueue._id), 1);\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\n\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\n\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t// \tfunction: 'mongoQueue',\n\t\t\t\t\t// \tpublication: '',\n\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t// \tresult: 'Done'\n\t\t\t\t\t// });\n\t\t\t\t}\t\n\n\t\t\t\tthis._runningQueue = false;\n\t\t\t}\n\t\t}, 1);\n\n\t\tsetInterval(async () => {\n\t\t\tthis._loggedInUsers = await LoggedInUsers.find();\n\t\n\t\t\tlet userCopy = deepCopy(this._loggedInUsers);\n\t\t\tfor (let i = this._loggedInUsers.length - 1; i >= 0; i--) {\n\t\t\t\tlet loggedInUser = userCopy[i];\n\n\t\t\t\tif (!loggedInUser.date || Date.now() - loggedInUser.date.getTime() > 120000) {\n\t\t\t\t\tif (this._mainServer.getWS(loggedInUser.id_ws)) {\n\t\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', this._mainServer.getWS(loggedInUser.id_ws)['user'], this._mainServer.getWS(loggedInUser.id_ws)['id_socket'], 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.unsubscribeAll(this._mainServer.getWS(loggedInUser.id_ws));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._subscriptions.forEach(sub => {\n\t\t\t\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\t\t\t\tif (client.id_socket === loggedInUser.id_ws) {\n\t\t\t\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tLoggedInUsers.deleteOne({_id: loggedInUser._id});\n\n\t\t\t\t\t\tif (this._loggedInUsers.findIndex(a => a._id === loggedInUser._id) >= 0) {\n\t\t\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.findIndex(a => a._id === loggedInUser._id), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (let i = 0; i < this._subscriptions.length; i++) {\n\t\t\t\tlet sub = this._subscriptions[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\tif (!this._loggedInUsers.some(a => a.id_ws === client.id_socket)) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, 30000);\n\n\t\tFlags.findOne({type: 'Enable Debug'}).then(flag => {\n\t\t\tif (flag && flag.value) {\n\t\t\t\tthis._enableDebug = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._enableDebug = false;\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate addToQueue(mongoQueue: MongoQueueModel) {\n\t\t// let startDate = new Date();\n\n\t\tlet _mongoQueue = this._mongoQueue.filter(a => a.subscription.publication === mongoQueue.subscription.publication && JSON.stringify(a.subscription.subscriptionData) === JSON.stringify(mongoQueue.subscription.subscriptionData))[0];\n\t\t\n\t\tif (_mongoQueue) {\n\t\t\tif (_mongoQueue.running) {\n\t\t\t\t_mongoQueue.run_again = true;\n\n\t\t\t\t// let endDate = new Date();\n\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t// \tfunction: 'addToQueue',\n\t\t\t\t// \tpublication: mongoQueue.subscription.publication,\n\t\t\t\t// // \tsubscriptionData: mongoQueue.subscription.subscriptionData,\n\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t// \tresult: 'Run Again'\n\t\t\t\t// });\n\t\t\t}\n\t\t\t// else {\n\t\t\t// \tlet endDate = new Date();\n\t\t\t// \tthis.currentPerfomanceMonitor.push({\n\t\t\t// \t\t_id: this.idPerformance++,\n\t\t\t// \t\tfunction: 'addToQueue',\n\t\t\t// \t\tpublication: mongoQueue.subscription.publication,\n\t\t\t// // \tsubscriptionData: mongoQueue.subscription.subscriptionData,\n\t\t\t// \t\tsubscriptionData: [],\n\t\t\t// \t\tdate_start: startDate,\n\t\t\t// \t\tdate_end: endDate,\n\t\t\t// \t\tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t// \t\tresult: 'Not Running Yet'\n\t\t\t// \t});\n\t\t\t// }\n\t\t}\n\t\telse {\n\t\t\tmongoQueue._id = this._mongoQueueId;\n\t\t\tthis._mongoQueueId += 1;\n\n\t\t\tthis._mongoQueue.splice(0, 0, mongoQueue);\n\t\t\t\n\t\t\t// let endDate = new Date();\n\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t// \t_id: this.idPerformance++,\n\t\t\t// \tfunction: 'addToQueue',\n\t\t\t// \tpublication: mongoQueue.subscription.publication,\n\t\t\t// // \tsubscriptionData: mongoQueue.subscription.subscriptionData,\n\t\t\t// \tsubscriptionData: [],\n\t\t\t// \tdate_start: startDate,\n\t\t\t// \tdate_end: endDate,\n\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t// \tresult: 'Add to Queue'\n\t\t\t// });\n\t\t}\n\t}\n\n\tpublic invalidatePubsCache(collection, type) {\n\t\t// let startDate = new Date();\n\n\t\tResolveIOServer.getMongoManager().invalidateQueryCache(collection);\n\t\t\n\t\tlet collSubs = this._subscriptions.filter(a => a.collections.includes(collection));\n\n\t\tfor (let i = collSubs.length - 1; i >= 0; i--) {\n\t\t\tlet sub = collSubs[i];\n\t\t\t\n\t\t\tthis.addToQueue({\n\t\t\t\t_id: 0,\n\t\t\t\ttype: type,\n\t\t\t\tcollection: collection,\n\t\t\t\tsubscription: sub,\n\t\t\t\trunning: false,\n\t\t\t\trun_again: false\n\t\t\t});\n\t\t}\n\n\t\t// let endDate = new Date();\n\t\t// this.currentPerfomanceMonitor.push({\n\t\t// \t_id: this.idPerformance++,\n\t\t// \tfunction: 'invalidatePubsCache',\n\t\t// \tpublication: collection,\n\t\t// \tsubscriptionData: [],\n\t\t// \tdate_start: startDate,\n\t\t// \tdate_end: endDate,\n\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t// \tresult: 'Done'\n\t\t// });\n\t}\n\n\t// Add all files to publications private object\n\tpublic publications(method: SubscriptionModel) {\n\t\tthis._publications = Object.assign(this._publications, method);\n\t}\n\n\tpublic loggedInLatency(ws: WebSocket) {\n\t\tlet loggedInUser = this._loggedInUsers.filter(a => a.id_ws === ws['id_socket'])[0];\n\n\t\tif (loggedInUser) {\n\t\t\tloggedInUser.date = new Date();\n\n\t\t\tLoggedInUsers.updateOne({id_ws: ws['id_socket']}, {$set: {latency: ws['latency'], date: loggedInUser.date}}).then(res => {\n\t\t\t\tif (!res) {\n\t\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 3);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, () => {\n\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 4);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Subscribe to publication\n\tpublic subscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\t// let startDate = new Date();\n\t\tthis._debugSubHits += 1;\n\n\t\tif (!this._debugSubCollections.some(a => a.publication === publication)) {\n\t\t\tthis._debugSubCollections.push({\n\t\t\t\tpublication: publication,\n\t\t\t\thits: 1\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tthis._debugSubCollections.filter(a => a.publication === publication)[0].hits += 1;\n\t\t}\n\n\t\tlet pub = this._publications[publication];\n\n\t\tif (!pub) {\n\t\t\tconsole.error(new Date(), 'No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tif (subscriptionData.length > 1 || subscriptionData[0]) {\n\t\t\t\tif (!pub.check) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Function For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (!pub.check._schema) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Schema For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet valObj = {};\n\t\t\t\t\tlet valKeys = Object.keys(pub.check._schema);\n\n\t\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\t\n\t\t\t\t\tfor (let i = 0; i < subscriptionData.length; i++) {\n\t\t\t\t\t\tvalObj[rootKeys[i]] = subscriptionData[i];\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpub.check.validate(valObj);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (errors) {\n\t\t\t\t\t\tif (errors) {\n\t\t\t\t\t\t\tconsole.error(new Date(), 'Error in Pub Check (' + publication + ')', errors);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (messageRoute !== 'Bypass') {\n\t\t\t\tlet urlData = messageRoute.split('/');\n\t\t\t\tlet urlModule = '';\n\t\t\t\tlet urlNext = urlData[0];\n\t\t\t\t\n\t\t\t\tif (urlData[0] === '') {\n\t\t\t\t\turlModule = '/';\n\t\t\t\t\turlNext = urlData[1];\n\t\t\t\t}\n\n\t\t\t\turlModule += urlNext;\n\n\t\t\t\tif (urlData.length > 1) {\n\t\t\t\t\turlModule += '/';\n\t\t\t\t}\n\n\t\t\t\tlet otherRouteSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_socket === ws['id_socket'] && b.messageRoute !== 'Bypass' && b.messageRoute !== '/' && b.messageRoute !== messageRoute && !b.messageRoute.startsWith(urlModule)));\n\t\t\t\n\t\t\t\tif (otherRouteSubs.length) {\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Detected Undestroyed Subscription - ' + this.serverConfig['CLIENT_NAME'], 'USER: ' + ws['user'] + ' (Socket: ' + ws['id_socket'] + ') ' + ' is on route: ' + messageRoute + ' but has the following subscriptions on other routes:' + JSON.stringify(otherRouteSubs, null, 2));\n\n\t\t\t\t\totherRouteSubs.forEach(otherSub => {\n\t\t\t\t\t\totherSub.clients.filter(a => a.id_socket === ws['id_socket']).forEach(client => {\n\t\t\t\t\t\t\tthis.unsubscribe(client.messageRoute, new Date(), ws, client.messageId, otherSub.publication, otherSub.subscriptionData);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet sub = this._subscriptions.filter(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData))[0];\n\n\t\t\t// If sub found (another user watching same data), add client to same sub\n\t\t\tif (sub) {\n\t\t\t\tif (!sub.clients.some(a => a.id_socket === ws['id_socket'] && a.messageId === messageId)) {\n\t\t\t\t\tsub.clients.push({\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If sub not found, create new sub\n\t\t\telse {\n\t\t\t\tthis._subscriptions.push({\n\t\t\t\t\tpublication: publication,\n\t\t\t\t\tsubscriptionData: subscriptionData,\n\t\t\t\t\tcollections: this.getPublicationCollections(publication),\n\t\t\t\t\tclients: [{\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute\n\t\t\t\t\t}],\n\t\t\t\t\tcacheId: 0\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!sub) {\n\t\t\t\tsub = this._subscriptions.filter(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData))[0];\n\t\t\t}\n\n\t\t\tif (!sub.cacheId && !this._mongoQueue.some(a => a.subscription.publication === sub.publication && JSON.stringify(a.subscription.subscriptionData) === JSON.stringify(sub.subscriptionData))) {\n\t\t\t\tthis.addToQueue({\n\t\t\t\t\t_id: 0,\n\t\t\t\t\ttype: 'newSub',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tsubscription: sub,\n\t\t\t\t\trunning: false,\n\t\t\t\t\trun_again: false\n\t\t\t\t});\n\n\t\t\t\t// let endDate = new Date();\n\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t// \tfunction: 'subscribe',\n\t\t\t\t// \tpublication: publication,\n\t\t\t\t// // \tsubscriptionData: subscriptionData,\n\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t// \tresult: 'Add to Queue'\n\t\t\t\t// });\n\t\t\t}\n\t\t\telse if (sub.cacheId) {\n\t\t\t\tthis.sendDataToOne(ws, messageId, sub, 'newSub', publication);\n\n\t\t\t\t// let endDate = new Date();\n\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t// \tfunction: 'subscribe',\n\t\t\t\t// \tpublication: publication,\n\t\t\t\t// // \tsubscriptionData: subscriptionData,\n\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t// \tresult: 'Send Pub Data Once'\n\t\t\t\t// });\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async createLoggedInUser(id_ws: string): Promise<LoggedInUserModel> {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tlet ws = this._mainServer.getWS(id_ws);\n\n\t\t\tif (ws) {\n\t\t\t\tlet user = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\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\t\n\t\t\t\tthis._loggedInUsers.push(user);\n\t\t\t\tLoggedInUsers.insertOne(user);\n\t\t\t\t\n\t\t\t\tresolve(user);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(null);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Unsubscribe from publication \n\tpublic unsubscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugUnSubHits += 1;\n\t\t// let startDate = new Date();\n\t\t// console.log('Before');\n\t\t// console.dir(this._subscriptions.map(a => a.publication));\n\n\t\tif (!this._publications[publication]) {\n\t\t\tconsole.log('No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet sub = this._subscriptions.filter(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData))[0];\n\n\t\t\tif (sub) {\n\t\t\t\tfor (let i = sub.clients.length - 1; i >= 0; i--) {\n\t\t\t\t\tif (sub.clients[i].id_user === ws['id_user'] && sub.clients[i].messageId === messageId && sub.clients[i].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(i, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// let endDate = new Date();\n\t\t// this.currentPerfomanceMonitor.push({\n\t\t// \t_id: this.idPerformance++,\n\t\t// \tfunction: 'unsubscribe',\n\t\t// \tpublication: publication,\n\t\t// // \tsubscriptionData: subscriptionData,\n\t\t// \tsubscriptionData: [],\n\t\t// \tdate_start: startDate,\n\t\t// \tdate_end: endDate,\n\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t// \tresult: 'Done'\n\t\t// });\n\t}\n\n\t// Unsubscribe from publication\n\tpublic async unsubscribeAll(ws: WebSocket) {\n\t\tthis._debugUnSubAllHits += 1;\n\t\t// console.log('Before');\n\t\t// console.dir(this._subscriptions.map(a => a.publication));\n\n\t\t// let startDate = new Date();\n\n\t\tif (ws) {\n\t\t\tlet loggedInUser = await LoggedInUsers.findOne({id_ws: ws['id_socket']});\n\n\t\t\tif (loggedInUser) {\t\n\t\t\t\tif (this._loggedInUsers.map(a => a._id).indexOf(loggedInUser._id) >= 0) {\n\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.map(a => a._id).indexOf(loggedInUser._id), 1);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tLoggedInUsers.deleteOne({_id: loggedInUser._id});\n\t\t\t}\n\n\t\t\tlet userSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_user === ws['id_user'] && b.id_socket === ws['id_socket']));\n\n\t\t\tfor (let i = userSubs.length - 1; i >= 0; i--) {\n\t\t\t\tlet sub = userSubs[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tif (sub.clients[j].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws.close();\n\n\t\t\tprocess.nextTick(() => {\n\t\t\t\tif ([ws.OPEN, ws.CLOSING].includes(<any>ws.readyState)) {\n\t\t\t\t\t// Socket still hangs, hard close\n\t\t\t\t\tws.terminate();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// let endDate = new Date();\n\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t// \t_id: this.idPerformance++,\n\t\t\t// \tfunction: 'unsubscribeAll',\n\t\t\t// \tpublication: '',\n\t\t\t// \tsubscriptionData: [],\n\t\t\t// \tdate_start: startDate,\n\t\t\t// \tdate_end: endDate,\n\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t// \tresult: 'Done'\n\t\t\t// });\n\t\t}\n\n\t\t// console.log('After');\n\t\t// console.dir(this._subscriptions.map(a => a.publication));\n\t}\n\n\tpublic getActiveSubscriptions() {\n\t\treturn this._subscriptions;\n\t}\n\n\t// Get publication collection\n\tprivate getPublicationCollections(publication: string) {\n\t\treturn this._publications[publication].collections;\n\t}\n\n\t// Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)\n\tprivate async tailOpLog(resumeToken?: ResumeToken) {\n\t\tif (this._oplog$ && !this._oplog$.closed) {\n\t\t\tthis._oplog$.removeAllListeners();\n\t\t\tthis._oplog$.close();\n\t\t\tthis._oplog$ = null;\n\t\t}\n\t\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\n\t\tif (!this._oplog$ || this._oplog$.closed) {\n\t\t\tthis._oplogRetryCount += 1;\n\n\t\t\tif (this._oplogRetryCount > 5) {\n\t\t\t\tconsole.error('****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************')\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\tlet lastResumeToken: ResumeToken;\n\n\t\t\tif (resumeToken) {\n\t\t\t\tlastResumeToken = resumeToken;\n\t\t\t\ttry {\n\t\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch([], {resumeAfter: resumeToken});\n\t\t\t\t}\n\t\t\t\tcatch(errOp) {\n\t\t\t\t\tif (this._oplog$) {\n\t\t\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\t\t\tthis._oplog$.close();\n\t\t\t\t\t\tthis._oplog$ = null;\n\t\t\t\t\t}\n\t\t\t\t\tthis.tailOpLog(resumeToken);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch();\n\t\t\t}\n\n\t\t\tconsole.log(new Date(), 'oplog started');\n\n\t\t\tthis._oplog$.on('change', (doc: ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument) => {\n\t\t\t\t// let startDate = new Date();\n\n\t\t\t\tif (doc.ns) {\n\t\t\t\t\tlet collection = doc.ns.coll;\n\n\t\t\t\t\tif (!this._debugOplogCollections.some(a => a.collection === doc.ns.coll && a.type === doc.operationType)) {\n\t\t\t\t\t\tthis._debugOplogCollections.push({\n\t\t\t\t\t\t\tcollection: doc.ns.coll,\n\t\t\t\t\t\t\ttype: doc.operationType,\n\t\t\t\t\t\t\thits: 1\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\tthis._debugOplogCollections.filter(a => a.collection === doc.ns.coll && a.type === doc.operationType)[0].hits += 1;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// console.log(new Date(), 'Op log doc', doc.operationType, collection);\n\n\t\t\t\t\tif (collection && !collection.endsWith('.versions') && !collection.startsWith('monitor-') && collection !== 'logs' && collection !== 'log-method-latencies' && collection !== 'log-subscriptions') {\n\t\t\t\t\t\tthis._debugOplogHits += 1;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\t\t\tif (collection === 'support-tickets') {\n\t\t\t\t\t\t\t\tif (this.serverConfig['ROOT_URL'] === 'https://resolveio.com') {\n\t\t\t\t\t\t\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'sendSupportTicketEmail', doc.documentKey['_id']);\n\t\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t\t// \tfunction: 'oplog',\n\t\t\t\t\t\t\t// \tpublication: collection,\n\t\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t\t// \tresult: 'Insert'\n\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'update' || doc.operationType === 'replace') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'update');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t\t// \tfunction: 'oplog',\n\t\t\t\t\t\t\t// \tpublication: collection,\n\t\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t\t// \tresult: 'Update'\n\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'delete');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t\t// \tfunction: 'oplog',\n\t\t\t\t\t\t\t// \tpublication: collection,\n\t\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t\t// \tresult: 'Delete'\n\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection === 'flags') {\n\t\t\t\t\t\tFlags.findOne({type: 'Enable Debug'}).then(flag => {\n\t\t\t\t\t\t\tif (flag && flag.value) {\n\t\t\t\t\t\t\t\tthis._enableDebug = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._enableDebug = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tlastResumeToken = doc._id;\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\tthis._oplog$.on('error', error => {\n\t\t\t\tconsole.log(new Date(), 'oplog error', error);\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('end', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog end');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog close');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\t\t}\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate sendDataToOne(ws: WebSocket, messageId: number, subscription: ActiveSubscriptionModel, type: string, collection: string) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// let startDate = new Date();\n\n\t\t\tif (!this._publications[subscription.publication].user_specific) { // Same pub for all users\n\t\t\t\tif (subscription.cacheId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(subscription.cacheId), dateReviver);\n\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: cacheData\n\t\t\t\t\t\t};\n\t\n\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t}\n\t\t\t\t\tcatch(err) {\n\t\t\t\t\t\tthis._nodeCache.del(subscription.cacheId);\n\t\t\t\t\t\tsubscription.cacheId = 0;\n\n\t\t\t\t\t\tthis.addToQueue({\n\t\t\t\t\t\t\t_id: 0,\n\t\t\t\t\t\t\ttype: 'newSub',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tsubscription: subscription,\n\t\t\t\t\t\t\trunning: false,\n\t\t\t\t\t\t\trun_again: false\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t// \tfunction: 'sendDataToOne',\n\t\t\t\t\t// \tpublication: subscription.publication,\n\t\t\t\t\t// // \tsubscriptionData: subscription.subscriptionData,\n\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t// \tresult: 'Send cache'\n\t\t\t\t\t// });\n\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During sendDataToOne - No Cache! - ' + subscription.publication + '\\n\\nData \\n' + JSON.stringify(subscription.subscriptionData, null, 2));\n\n\t\t\t\t\tresolve(false);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // Pub is different for each user (Look at users publication) [MUCH SLOWER, RE-RUNS FOR EACH USER]\n\t\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', subscription.publication, '', '', subscription.subscriptionData);\n\t\t\t\tthis._publications[subscription.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ws['id_user'], ...subscription.subscriptionData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\tdata: res\n\t\t\t\t\t};\n\n\t\t\t\t\t// console.log('Send Pub Data Once 2', new Date(), 'Success', subscription);\n\n\t\t\t\t\tthis.sendWS(ws, serverRes);\n\n\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t// \tfunction: 'sendDataToOne',\n\t\t\t\t\t// \tpublication: subscription.publication,\n\t\t\t\t\t// // \tsubscriptionData: subscription.subscriptionData,\n\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t// \tresult: 'Send ws spec data'\n\t\t\t\t\t// });\n\n\t\t\t\t\tresolve(true);\n\n\t\t\t\t}, err => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\t\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\tdata: err\n\t\t\t\t\t};\n\n\t\t\t\t\t// console.log('Send Pub Data Once 2', new Date(), 'Error', subscription);\n\n\t\t\t\t\tthis.sendWS(ws, serverRes);\n\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + subscription.publication + ' - (sendDataToOne - WS)\\n\\nData \\n' + JSON.stringify(subscription.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\n\t\t\t\t\treject(err);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate sendDataToAll(mongoQueue: MongoQueueModel) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// let startDate = new Date();\n\t\t\tif (!mongoQueue.subscription.clients.length) {\t\t\t\t\n\t\t\t\tif (mongoQueue.subscription.cacheId) {\n\t\t\t\t\tthis._nodeCache.del(mongoQueue.subscription.cacheId);\n\t\t\t\t}\n\n\t\t\t\tif (this._subscriptions.findIndex(a => a.publication === mongoQueue.subscription.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(mongoQueue.subscription.subscriptionData)) >= 0) {\n\t\t\t\t\tthis._subscriptions.splice(this._subscriptions.findIndex(a => a.publication === mongoQueue.subscription.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(mongoQueue.subscription.subscriptionData)), 1);\n\t\t\t\t}\n\n\t\t\t\tresolve(false);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (mongoQueue.subscription.publication !== 'superadminAPM' && mongoQueue.subscription.publication !== 'loggedInUsers') {\n\t\t\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'insertSubscriptionLog', mongoQueue.type, mongoQueue.subscription.publication, mongoQueue.collection, JSON.stringify(mongoQueue.subscription.subscriptionData));\n\t\t\t\t}\n\n\t\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Publication', mongoQueue.subscription.publication, '', '', mongoQueue.subscription.subscriptionData);\n\t\t\t\tthis._publications[mongoQueue.subscription.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ...mongoQueue.subscription.subscriptionData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tif (!mongoQueue.subscription.clients.length) {\n\t\t\t\t\t\tlet nodeCacheSize = this._nodeCache.getStats().vsize;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (nodeCacheSize > this._heapLimit) {\n\t\t\t\t\t\t\tlet deleteCount = 0;\n\n\t\t\t\t\t\t\tconst subArr = this._subscriptions.filter(a => a.cacheId && !a.clients.length);\n\n\t\t\t\t\t\t\tfor (let zz = 0; zz < subArr.length; zz++) {\n\t\t\t\t\t\t\t\tthis._debugRemoveCacheHits += 1;\n\n\t\t\t\t\t\t\t\tthis._nodeCache.del(subArr[zz].cacheId);\n\t\t\t\t\t\t\t\tsubArr[zz].cacheId = 0;\n\n\t\t\t\t\t\t\t\tdeleteCount += 1;\n\n\t\t\t\t\t\t\t\tnodeCacheSize = this._nodeCache.getStats().vsize;\n\n\t\t\t\t\t\t\t\tif (nodeCacheSize < this._heapLimit * 0.75) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tconsole.log('Sub Cache: ' + 'Too Big - ' + mongoQueue.subscription.publication + ' - Deleted: ' + deleteCount + ' - ' + nodeCacheSize);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (mongoQueue.subscription.cacheId) {\n\t\t\t\t\t\t\tthis._nodeCache.del(mongoQueue.subscription.cacheId);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet cacheId = this._cacheId;\n\t\t\t\t\t\tthis._cacheId += 1;\n\n\t\t\t\t\t\tthis._nodeCache.set(cacheId, JSON.stringify(res));\n\t\t\t\t\t\tmongoQueue.subscription.cacheId = cacheId;\n\n\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t// \tfunction: 'sendPubData',\n\t\t\t\t\t\t// \tpublication: subscription.publication,\n\t\t\t\t\t\t// // \tsubscriptionData: subscription.subscriptionData,\n\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t// \tresult: 'No clients'\n\t\t\t\t\t\t// });\n\n\t\t\t\t\t\tresolve(false);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (!mongoQueue.subscription.cacheId || this._nodeCache.get(mongoQueue.subscription.cacheId) !== JSON.stringify(res)) {\n\t\t\t\t\t\t\tmongoQueue.subscription.clients.forEach(client => {\n\t\t\t\t\t\t\t\tlet ws = this._mainServer.getWS(client.id_socket);\n\n\t\t\t\t\t\t\t\tif (ws) {\n\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\n\t\t\t\t\t\t\tlet nodeCacheSize = this._nodeCache.getStats().vsize;\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (nodeCacheSize > this._heapLimit) {\n\t\t\t\t\t\t\t\tlet deleteCount = 0;\n\n\t\t\t\t\t\t\t\tconst subArr = this._subscriptions.filter(a => a.cacheId && !a.clients.length);\n\t\n\t\t\t\t\t\t\t\tfor (let zz = 0; zz < subArr.length; zz++) {\n\t\t\t\t\t\t\t\t\tthis._nodeCache.del(subArr[zz].cacheId);\n\t\t\t\t\t\t\t\t\tsubArr[zz].cacheId = 0;\n\t\n\t\t\t\t\t\t\t\t\tdeleteCount += 1;\n\n\t\t\t\t\t\t\t\t\tnodeCacheSize = this._nodeCache.getStats().vsize;\n\t\n\t\t\t\t\t\t\t\t\tif (nodeCacheSize < this._heapLimit * 0.75) {\n\t\t\t\t\t\t\t\t\t\tbreak;\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\t\n\t\t\t\t\t\t\t\tconsole.log('Sub Cache: ' + 'Too Big - ' + mongoQueue.subscription.publication + ' - Deleted: ' + deleteCount + ' - ' + nodeCacheSize);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (mongoQueue.subscription.cacheId) {\n\t\t\t\t\t\t\t\tthis._nodeCache.del(mongoQueue.subscription.cacheId);\n\t\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\t\tlet cacheId = this._cacheId;\n\t\t\t\t\t\t\tthis._cacheId += 1;\n\n\t\t\t\t\t\t\tthis._nodeCache.set(cacheId, JSON.stringify(res));\n\t\t\t\t\t\t\tmongoQueue.subscription.cacheId = cacheId;\n\n\t\t\t\t\t\t\t// let endDate = new Date();\n\t\t\t\t\t\t\t// this.currentPerfomanceMonitor.push({\n\t\t\t\t\t\t\t// \t_id: this.idPerformance++,\n\t\t\t\t\t\t\t// \tfunction: 'sendPubData',\n\t\t\t\t\t\t\t// \tpublication: subscription.publication,\n\t\t\t\t\t\t\t// // \tsubscriptionData: subscription.subscriptionData,\n\t\t\t\t\t\t\t// \tsubscriptionData: [],\n\t\t\t\t\t\t\t// \tdate_start: startDate,\n\t\t\t\t\t\t\t// \tdate_end: endDate,\n\t\t\t\t\t\t\t// \tduration: moment(endDate).diff(moment(startDate), 'milliseconds', false),\n\t\t\t\t\t\t\t// \tresult: 'Same data'\n\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tresolve(true);\n\t\t\t\t\t}\n\t\t\t\t}, err => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + mongoQueue.subscription.publication + ' - (sendPubData)\\n\\nData \\n' + JSON.stringify(mongoQueue.subscription.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\n\t\t\t\t\tmongoQueue.subscription.clients.forEach(client => {\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(client.id_socket);\n\n\t\t\t\t\t\tif (ws) {\n\t\t\t\t\t\t\tif (ws['id_socket'] === client.id_socket) {\n\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\t\t\tdata: err\n\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\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\treject(err);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate sendWS(ws: WebSocket, data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tdata: data\n\t\t});\n\t}\n\n\tpublic getEnableDebug() {\n\t\treturn this._enableDebug;\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.3.6",
3
+ "version": "20.3.7",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",