@resolveio/server-lib 20.4.79 → 20.4.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,n,o,i){return new(o=o||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var i,s,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(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=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=o.call(n,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||((n=n||Array.prototype.slice.call(t,0,o))[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),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"),flag_updates_1=require("../methods/flag-updates"),worker_task_data_chunk_collection_1=require("../collections/worker-task-data-chunk.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,r,n,o,i){var s=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this.serverConfig=t,this.clientDir=r,this._monitorManagerFunction=n,this._isWorkersEnabled=o,this._isWorkerInstance=i,"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(t),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(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(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}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 o=this,r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];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 n={},i=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),s=0;s<r.length;s++)n[i[s]]=r[s];try{this._methods[t].check.validate(n)}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(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var a=null;if(this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t){var c=JSON.stringify(r);if(8388608<Buffer.byteLength(c,"utf8")){for(var l=[],u=Buffer.from(c,"utf8"),d=[],s=0;s<u.length;s+=2097152){var h=u.slice(s,s+2097152),h={_id:(0,mongo_manager_1.objectIdHexString)(),data:h.toString("base64")};d.push(h),l.push(h._id)}r=[{__largeDataRef:!0,chunks:l}],worker_task_data_chunk_collection_1.WorkerTaskDataChunks.create(d)}var _=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),f=(0,mongo_manager_1.objectIdHexString)(),a=new Promise(function(t,r){var n=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":f}}],{fullDocument:"updateLookup"});n.on("change",function(e){"insert"===e.operationType&&(o._monitorManagerFunction.finishMonitorFunction(_),((e=e.fullDocument).has_error?r:t)(e.data),n.close())}),n.on("error",function(e){console.error("Error watching worker responses:",e),r(e),n.close()})});worker_task_request_collection_1.WorkerTaskRequests.create({_id:f,method:t,params:r,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})}else{var g=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r);a=(c=this._methods[t].function).call.apply(c,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(r),!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(g),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(g),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})}return a}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(n,o,i,s,a){for(var t=this,c=[],e=5;e<arguments.length;e++)c[e-5]=arguments[e];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<c.length||c[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(o,i,a,c,r={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}));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),r={messageId:s,hasError:!0,data:"Internal Error"},n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),void this.sendWS(o,i,a,c,r);for(var r,l={},u=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),d=0;d<c.length;d++)l[u[d]]=c[d];try{this._methods[a].check.validate(l)}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(l,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(o,i,a,c,r={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}))}}if(this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a&&"incorrectUser"!==a&&"reloadWS"!==a&&"reconnectWS"!==a&&"disconnectWS"!==a){var h=JSON.stringify(c);if(8388608<Buffer.byteLength(h,"utf8")){for(var _=[],f=Buffer.from(h,"utf8"),g=[],d=0;d<f.length;d+=2097152){var m=f.slice(d,d+2097152),m={_id:(0,mongo_manager_1.objectIdHexString)(),data:m.toString("base64")};g.push(m),_.push(m._id)}c=[{__largeDataRef:!0,chunks:_}],worker_task_data_chunk_collection_1.WorkerTaskDataChunks.create(g)}var p=this._monitorManagerFunction.startMonitorFunction("Method",a,o.user||"",o.id_socket||"",c),h=(0,mongo_manager_1.objectIdHexString)(),v=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":h}}],{fullDocument:"updateLookup"});v.on("change",function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==r.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(p),t=r.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(o,new Date,a,c,t),n?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:v.close(),e.label=3;case 3:return[2]}})})}),v.on("error",function(e){console.error("Error watching worker responses:",e),v.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:h,method:a,params:c,status:"pending",id_user:o.id_user,user:o.user,id_ws:o.id_socket})}else{var M=this._monitorManagerFunction.startMonitorFunction("Method",a,o.user||"",o.id_socket||"",c);(h=this._methods[a].function).call.apply(h,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:o.id_user,user:o.user,id_ws:o.id_socket})],__read(c),!1)).then(function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(M),t={messageId:s,hasError:!1,data:r},this.sendWS(o,i,a,c,t),n)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(M),t.sendWS(o,i,a,c,{messageId:s,hasError:!0,data:e}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(c,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),r={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(o,new Date,a,c,r),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n})},MethodManager.prototype.callMethodInternal=function(t){for(var o=this,r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];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&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==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 n="function"==typeof r[r.length-1]?r.slice(0,-1):r,i=null;if(this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t){var s=JSON.stringify(n);if(8388608<Buffer.byteLength(s,"utf8")){for(var a=[],c=Buffer.from(s,"utf8"),l=[],u=0;u<c.length;u+=2097152){var d=c.slice(u,u+2097152),d={_id:(0,mongo_manager_1.objectIdHexString)(),data:d.toString("base64")};l.push(d),a.push(d._id)}n=[{__largeDataRef:!0,chunks:a}],worker_task_data_chunk_collection_1.WorkerTaskDataChunks.create(l)}var h=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",n),_=(0,mongo_manager_1.objectIdHexString)(),i=new Promise(function(t,r){var n=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":_}}],{fullDocument:"updateLookup"});n.on("change",function(e){"insert"===e.operationType&&(o._monitorManagerFunction.finishMonitorFunction(h),((e=e.fullDocument).has_error?r:t)(e.data),n.close())}),n.on("error",function(e){console.error("Error watching worker responses:",e),r(e),n.close()})});worker_task_request_collection_1.WorkerTaskRequests.create({_id:_,method:t,params:n,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})}else{var f=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",n);i=(s=this._methods[t].function).call.apply(s,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(n),!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(f),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(f),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})}return r[r.length-1]&&"function"==typeof r[r.length-1]&&i.then(function(e){return r[r.length-1](null,e)},function(e){return r[r.length-1](e,null)}),i},MethodManager.prototype.sendWS=function(e,t,r,n,o){this._websocketManager.send(e,o),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([n,o]))<2e5?JSON.stringify([n,o],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:o.messageId,route:""})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(e){switch(e.label){case 0:return(t=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(n,void 0,void 0,function(){var t;return __generator(this,function(e){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){n.setupEmailWatcher()}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,n,o,i,s;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),n=r.next();!n.done;n=r.next())o=n.value,this.emailQueue.add(o._id.toString())}catch(e){i={error:e}}finally{try{n&&!n.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,d,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,7]),t=function(){var n,t,r,o,i,s,a,c,l,u;return __generator(this,function(e){switch(e.label){case 0:return i=d.emailQueue.values().next().value,d.emailQueue.delete(i),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:i,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(n=e.sent()))return[2,"continue"];if(!(n.attachments&&0<n.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),l=void 0,t=__values(n.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(o=r.value).path&&o.path.startsWith("http")?[4,fetch(o.path)]:[3,7];case 5:if((i=e.sent()).ok)return[4,i.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(o.path));case 6:s=e.sent(),s=Buffer.from(s),s.length<=20971520&&(o.content=s,delete o.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return s=e.sent(),l={error:s},[3,11];case 10:try{r&&!r.done&&(u=t.return)&&u.call(t)}finally{if(l)throw l.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof a?a:d.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(c={replyTo:n.reply_to||d.serverConfig.MAIL_REPLY_TO||void 0,from:n.send_from||d.serverConfig.MAIL_FROM,to:n.email,subject:(d.serverConfig.ROOT_URL.match(/https:\/\/dev\./)||d.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+n.subject,text:"string"==typeof n.text?n.text:"",html:"string"==typeof n.html?n.html:"",attachments:n.attachments||[]}).attachments&&0<c.attachments.length&&(c.attachments=c.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),[4,new Promise(function(r){h._mailer.sendMail(c,function(t,e){return __awaiter(h,void 0,void 0,function(){return __generator(this,function(e){try{t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})):"dev@resolveio.com"===n.email?email_history_collection_1.EmailHistories.deleteOne({_id:n._id}):email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"completed",completedAt:new Date}})}catch(e){console.error("Error in sendMail callback:",e),email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof e?e:this.safeStringify(e),completedAt:new Date}})}finally{r()}return[2]})})})})];case 15:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 16:return e.sent(),[2]}})},d=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,7];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(o,i,s,a,c,l,u,d){var e=this;return void 0===d&&(d=!1),new Promise(function(r,n){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(o=!this.serverConfig.ROOT_URL.match(/https:\/\/dev\./)&&!this.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||o.match(/\@resolveio\.com/)?o:"dev@resolveio.com")?"http://localhost:4200"!==this.serverConfig.ROOT_URL||d?(c=c||[],c=(c=Array.isArray(c)?c:[c]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:o,subject:i||"",text:s||"",html:a||"",attachments:c||[],send_from:l||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),n(e)})):(console.log("Send email",o,i,s,a,c,l),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(r,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?n(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?n(e):r(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(r,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?n(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?n(e):r(t)})})},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,n,o,i){return new(o=o||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var i,s,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(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=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=o.call(n,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||((n=n||Array.prototype.slice.call(t,0,o))[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),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"),flag_updates_1=require("../methods/flag-updates"),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,r,n,o,i){var s=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this.serverConfig=t,this.clientDir=r,this._monitorManagerFunction=n,this._isWorkersEnabled=o,this._isWorkerInstance=i,"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(t),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(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(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}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 o=this,r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];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 n={},i=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),s=0;s<r.length;s++)n[i[s]]=r[s];try{this._methods[t].check.validate(n)}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(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var a,c,l,u=null,d=JSON.stringify(r);return this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(d,"utf8")<8388608&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(a=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),c=(0,mongo_manager_1.objectIdHexString)(),u=new Promise(function(t,r){var n=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":c}}],{fullDocument:"updateLookup"});n.on("change",function(e){"insert"===e.operationType&&(o._monitorManagerFunction.finishMonitorFunction(a),((e=e.fullDocument).has_error?r:t)(e.data),n.close())}),n.on("error",function(e){console.error("Error watching worker responses:",e),r(e),n.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),u=(d=this._methods[t].function).call.apply(d,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(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})),u}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(n,o,i,s,a){for(var t=this,c=[],e=5;e<arguments.length;e++)c[e-5]=arguments[e];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<c.length||c[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(o,i,a,c,r={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}));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),r={messageId:s,hasError:!0,data:"Internal Error"},n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),void this.sendWS(o,i,a,c,r);for(var r,l={},u=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),d=0;d<c.length;d++)l[u[d]]=c[d];try{this._methods[a].check.validate(l)}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(l,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(o,i,a,c,r={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}))}}var h,_,f,g=JSON.stringify(c);this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(g,"utf8")<8388608&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a&&"incorrectUser"!==a&&"reloadWS"!==a&&"reconnectWS"!==a&&"disconnectWS"!==a?(h=this._monitorManagerFunction.startMonitorFunction("Method",a,o.user||"",o.id_socket||"",c),g=(0,mongo_manager_1.objectIdHexString)(),(_=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":g}}],{fullDocument:"updateLookup"})).on("change",function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==r.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(h),t=r.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(o,new Date,a,c,t),n?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:_.close(),e.label=3;case 3:return[2]}})})}),_.on("error",function(e){console.error("Error watching worker responses:",e),_.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:g,method:a,params:c,status:"pending",id_user:o.id_user,user:o.user,id_ws:o.id_socket})):(f=this._monitorManagerFunction.startMonitorFunction("Method",a,o.user||"",o.id_socket||"",c),(g=this._methods[a].function).call.apply(g,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:o.id_user,user:o.user,id_ws:o.id_socket})],__read(c),!1)).then(function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(f),t={messageId:s,hasError:!1,data:r},this.sendWS(o,i,a,c,t),n)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(f),t.sendWS(o,i,a,c,{messageId:s,hasError:!0,data:e}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(c,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),r={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(o,new Date,a,c,r),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n})},MethodManager.prototype.callMethodInternal=function(t){for(var o=this,r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];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&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==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 i,s,n,a="function"==typeof r[r.length-1]?r.slice(0,-1):r,c=null,l=JSON.stringify(a);return this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(l,"utf8")<8388608&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),s=(0,mongo_manager_1.objectIdHexString)(),c=new Promise(function(t,r){var n=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});n.on("change",function(e){"insert"===e.operationType&&(o._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?r:t)(e.data),n.close())}),n.on("error",function(e){console.error("Error watching worker responses:",e),r(e),n.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})):(n=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),c=(l=this._methods[t].function).call.apply(l,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(a),!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(n),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(n),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,r,n,o){this._websocketManager.send(e,o),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([n,o]))<2e5?JSON.stringify([n,o],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:o.messageId,route:""})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(e){switch(e.label){case 0:return(t=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(n,void 0,void 0,function(){var t;return __generator(this,function(e){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){n.setupEmailWatcher()}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,n,o,i,s;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),n=r.next();!n.done;n=r.next())o=n.value,this.emailQueue.add(o._id.toString())}catch(e){i={error:e}}finally{try{n&&!n.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,d,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,7]),t=function(){var n,t,r,o,i,s,a,c,l,u;return __generator(this,function(e){switch(e.label){case 0:return i=d.emailQueue.values().next().value,d.emailQueue.delete(i),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:i,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(n=e.sent()))return[2,"continue"];if(!(n.attachments&&0<n.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),l=void 0,t=__values(n.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(o=r.value).path&&o.path.startsWith("http")?[4,fetch(o.path)]:[3,7];case 5:if((i=e.sent()).ok)return[4,i.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(o.path));case 6:s=e.sent(),s=Buffer.from(s),s.length<=20971520&&(o.content=s,delete o.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return s=e.sent(),l={error:s},[3,11];case 10:try{r&&!r.done&&(u=t.return)&&u.call(t)}finally{if(l)throw l.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof a?a:d.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(c={replyTo:n.reply_to||d.serverConfig.MAIL_REPLY_TO||void 0,from:n.send_from||d.serverConfig.MAIL_FROM,to:n.email,subject:(d.serverConfig.ROOT_URL.match(/https:\/\/dev\./)||d.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+n.subject,text:"string"==typeof n.text?n.text:"",html:"string"==typeof n.html?n.html:"",attachments:n.attachments||[]}).attachments&&0<c.attachments.length&&(c.attachments=c.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),[4,new Promise(function(r){h._mailer.sendMail(c,function(t,e){return __awaiter(h,void 0,void 0,function(){return __generator(this,function(e){try{t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})):"dev@resolveio.com"===n.email?email_history_collection_1.EmailHistories.deleteOne({_id:n._id}):email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"completed",completedAt:new Date}})}catch(e){console.error("Error in sendMail callback:",e),email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof e?e:this.safeStringify(e),completedAt:new Date}})}finally{r()}return[2]})})})})];case 15:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 16:return e.sent(),[2]}})},d=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,7];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(o,i,s,a,c,l,u,d){var e=this;return void 0===d&&(d=!1),new Promise(function(r,n){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(o=!this.serverConfig.ROOT_URL.match(/https:\/\/dev\./)&&!this.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||o.match(/\@resolveio\.com/)?o:"dev@resolveio.com")?"http://localhost:4200"!==this.serverConfig.ROOT_URL||d?(c=c||[],c=(c=Array.isArray(c)?c:[c]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:o,subject:i||"",text:s||"",html:a||"",attachments:c||[],send_from:l||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),n(e)})):(console.log("Send email",o,i,s,a,c,l),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(r,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?n(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?n(e):r(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(r,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?n(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?n(e):r(t)})})},MethodManager}());exports.MethodManager=MethodManager;
2
2
  //# sourceMappingURL=method.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","common_1","log_collection_1","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","flag_updates_1","worker_task_data_chunk_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","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","console","log","Date","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","setupEmailWatcher","getMainServer","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","skipValidation","check","error","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","i","validate","errors","JSON","stringify","promise","serializedData","Buffer","byteLength","chunkedReferences","methodDataBuffer","from","newChunks","chunk","slice","chunkDoc","_id","objectIdHexString","data","toString","push","__largeDataRef","chunks","WorkerTaskDataChunks","create","monitor_2","startMonitorFunction","taskId_1","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","finishMonitorFunction","taskResponse","has_error","close","WorkerTaskRequests","params","status","id_user","id_ws","monitor_3","_a","function","call","apply","__spreadArray","__read","then","res","methodErrs","callMethod","id_methodLatency","ws","messageDate","messageId","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","monitor_4","taskId","changeStream_1","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","monitor_5","err","callMethodInternal","Logs","insertOne","type","collection","id_document","payload","getBinarySize","route","functionMethodData","monitor_6","taskId_2","monitor_7","send","EmailHistories","add","tryProcessEmail","updatedEmail","has","delete","loadPendingEmails","find","sort","pendingEmails","_b","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","processingAt","emailHistory","_e","attachments","e_2","_c","att","startsWith","fetch","response","ok","arrayBuffer","Error","concat","buffer","content","err_2","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","sendMail","info","err_1","obj","getCircularReplacer","e","message","seen","WeakSet","key","sendTo","local_override","Array","isArray","isBuffer","__v","date","history","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"ihFACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,SAAAd,QAAA,gBAAA,EACAe,iBAAAf,QAAA,+BAAA,EAEAgB,gCAAAhB,QAAA,8CAAA,EACAiB,OAAAjB,QAAA,iBAAA,EACAkB,iBAAAlB,QAAA,2BAAA,EACAmB,UAAAnB,QAAA,oBAAA,EACAoB,UAAApB,QAAA,oBAAA,EACAqB,2BAAArB,QAAA,yCAAA,EACAsB,gBAAAtB,QAAA,iBAAA,EAEAuB,YAAAvB,QAAA,oBAAA,EACAwB,iCAAAxB,QAAA,+CAAA,EACAyB,kCAAAzB,QAAA,gDAAA,EAGA0B,eAAA1B,QAAA,yBAAA,EAEA2B,oCAAA3B,QAAA,kDAAA,EAGA4B,IAAA,WAKC,SAAAA,IAAYC,GAJJC,KAAAC,cAAgB,KAChBD,KAAAE,IAAU,KACVF,KAAAG,WAAiB,KAGxBH,KAAKC,cAA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Eb,CAAC,CAGJ,CAAC,CACF,EAEO3I,cAAAd,UAAAqR,UAAP,SAAiBJ,GAAjB,IAAA5P,EAAAzB,KACC,OAAO,IAAIgI,QAAQ,SAACC,EAASC,GACxB1J,GAAG8S,WAAW/S,KAAKgT,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjE7S,GAAG4S,SAAS7S,KAAKgT,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAAC9F,EAAK1B,GACzE0B,EACHrD,EAAOqD,CAAG,EAGVtD,EAAQ4B,CAAG,CAEb,CAAC,EAGGrL,GAAG8S,WAAW/S,KAAKgT,KAAK9P,EAAKJ,UAAY,aAAegQ,CAAS,CAAC,GACrE7S,GAAG4S,SAAS7S,KAAKgT,KAAK9P,EAAKJ,UAAY,aAAegQ,CAAS,EAAG,SAAU,SAAC9F,EAAK1B,GAC7E0B,EACHrD,EAAOqD,CAAG,EAGVtD,EAAQ4B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACD3I,aAAA,EAAC,GA7jCYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { getBinarySize } 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';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { EmailHistoryModel } from '../models/email-history.model';\nimport { WorkerTaskDataChunks } from '../collections/worker-task-data-chunk.collection';\nimport { WorkerTaskDataChunkModel } from '../models/worker-task-data-chunk.model';\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\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _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._websocketManager = this._mainServer.getWebSocketManager();\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\tif (process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tloadServerInit(serverConfig);\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadFlagUpdatesMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(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 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}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tthis.setupEmailWatcher();\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 && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\n\t\t\t// To prevent extremely large data being inserted, let's split it up into references if needed\n\t\t\t// For example, if `methodData` is huge, we can store large arrays/objects into a separate collection\n\t\t\t// and only store references in the worker-task-requests doc. This avoids hitting the 16MB BSON limit.\n\t\t\tlet MAX_DOCUMENT_SIZE = 1024 * 1024 * 8; // 8MB as a threshold before we chunk (just an example threshold)\n\t\t\tlet serializedData = JSON.stringify(methodData);\n\t\t\tif (Buffer.byteLength(serializedData, 'utf8') > MAX_DOCUMENT_SIZE) {\n\t\t\t\tlet chunkedReferences = [];\n\t\t\t\tlet chunkSize = 1024 * 1024 * 2; // 2MB chunks\n\t\t\t\tlet methodDataBuffer = Buffer.from(serializedData, 'utf8');\n\t\t\t\tlet newChunks: WorkerTaskDataChunkModel[] = [];\n\n\t\t\t\tfor (let i = 0; i < methodDataBuffer.length; i += chunkSize) {\n\t\t\t\t\tlet chunk = methodDataBuffer.slice(i, i + chunkSize);\n\t\t\t\t\tlet chunkDoc: WorkerTaskDataChunkModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tdata: chunk.toString('base64')\n\t\t\t\t\t};\n\t\t\t\t\tnewChunks.push(chunkDoc);\n\t\t\t\t\tchunkedReferences.push(chunkDoc._id);\n\t\t\t\t}\n\t\t\t\tmethodData = [{__largeDataRef: true, chunks: chunkedReferences}];\n\t\t\t\tWorkerTaskDataChunks.create(newChunks);\n\t\t\t}\n\t\t\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\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\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\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\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\tpromise = 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\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\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\t\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\t\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\t\n\t\t\treturn;\n\t\t}\n\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\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\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\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\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\t\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\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\t\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\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\t\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\t\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\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\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\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\t\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\t\n\t\t\t// To prevent extremely large data being inserted, let's split it up into references if needed\n\t\t\t// For example, if `methodData` is huge, we can store large arrays/objects into a separate collection\n\t\t\t// and only store references in the worker-task-requests doc. This avoids hitting the 16MB BSON limit.\n\t\t\tlet MAX_DOCUMENT_SIZE = 1024 * 1024 * 8; // 8MB as a threshold before we chunk (just an example threshold)\n\t\t\tlet serializedData = JSON.stringify(methodData);\n\t\t\tif (Buffer.byteLength(serializedData, 'utf8') > MAX_DOCUMENT_SIZE) {\n\t\t\t\tlet chunkedReferences = [];\n\t\t\t\tlet chunkSize = 1024 * 1024 * 2; // 2MB chunks\n\t\t\t\tlet methodDataBuffer = Buffer.from(serializedData, 'utf8');\n\t\t\t\tlet newChunks: WorkerTaskDataChunkModel[] = [];\n\n\t\t\t\tfor (let i = 0; i < methodDataBuffer.length; i += chunkSize) {\n\t\t\t\t\tlet chunk = methodDataBuffer.slice(i, i + chunkSize);\n\t\t\t\t\tlet chunkDoc: WorkerTaskDataChunkModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tdata: chunk.toString('base64')\n\t\t\t\t\t};\n\t\t\t\t\tnewChunks.push(chunkDoc);\n\t\t\t\t\tchunkedReferences.push(chunkDoc._id);\n\t\t\t\t}\n\t\t\t\tmethodData = [{__largeDataRef: true, chunks: chunkedReferences}];\n\t\t\t\tWorkerTaskDataChunks.create(newChunks);\n\t\t\t}\n\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\tconst taskId = objectIdHexString();\n\t\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\t\n\t\t\tchangeStream.on('change', async change => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\t\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\t\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\t\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\t\t\t\t\t\tif (latency) {\n\t\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\t}\n\t\t\t\t\t}\n\t\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t}\n\t\t\t});\n\t\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\t\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\t\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\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\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},\n\t\t\terr => {\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\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\t\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: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution' && method !== 'incCounter' && method !== 'supportCreateBillingUser' && method !== 'countCollectionWithQuery') {\n\t\t\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 && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\n\t\t\t// To prevent extremely large data being inserted, let's split it up into references if needed\n\t\t\t// For example, if `methodData` is huge, we can store large arrays/objects into a separate collection\n\t\t\t// and only store references in the worker-task-requests doc. This avoids hitting the 16MB BSON limit.\n\t\t\tlet MAX_DOCUMENT_SIZE = 1024 * 1024 * 8; // 8MB as a threshold before we chunk (just an example threshold)\n\t\t\tlet serializedData = JSON.stringify(functionMethodData);\n\t\t\tif (Buffer.byteLength(serializedData, 'utf8') > MAX_DOCUMENT_SIZE) {\n\t\t\t\tlet chunkedReferences = [];\n\t\t\t\tlet chunkSize = 1024 * 1024 * 2; // 2MB chunks\n\t\t\t\tlet methodDataBuffer = Buffer.from(serializedData, 'utf8');\n\t\t\t\tlet newChunks: WorkerTaskDataChunkModel[] = [];\n\n\t\t\t\tfor (let i = 0; i < methodDataBuffer.length; i += chunkSize) {\n\t\t\t\t\tlet chunk = methodDataBuffer.slice(i, i + chunkSize);\n\t\t\t\t\tlet chunkDoc: WorkerTaskDataChunkModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tdata: chunk.toString('base64')\n\t\t\t\t\t};\n\t\t\t\t\tnewChunks.push(chunkDoc);\n\t\t\t\t\tchunkedReferences.push(chunkDoc._id);\n\t\t\t\t}\n\t\t\t\tfunctionMethodData = [{__largeDataRef: true, chunks: chunkedReferences}];\n\t\t\t\tWorkerTaskDataChunks.create(newChunks);\n\t\t\t}\n\t\t\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\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\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\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\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},\n\t\t\t\tmethodErrs => {\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._websocketManager.send(ws, data);\n\n\t\tif (\n\t\t\tmethod !== 'reportBuilderGetResults' &&\n\t\t\tmethod !== 'reportBuilderGetDistinctValue' &&\n\t\t\tmethod !== 'reportBuilderBuildTree' &&\n\t\t\tmethod !== 'generatePDF' &&\n\t\t\tmethod !== 'getWOOfflineData' &&\n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'countCollectionWithQuery' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'uploadFileAndSave' &&\n\t\t\tmethod !== 'getDrivers' &&\n\t\t\tmethod !== 'processAirdropDistribution'\n\t\t) {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'client-response',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload:\n\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t: 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\tuser: ws['user'] || '',\n\t\t\t\tmessageId: data.messageId,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\t// MethodResponses.create({\n\t\t// \t_id: objectIdHexString(),\n\t\t// \t__v: 0,\n\t\t// \tid_user: ws['id_user'] || '',\n\t\t// \tmessage_id: data.messageId,\n\t\t// \tresponse: getBinarySize(JSON.stringify(data)) < 200000 ? data : { error: 'Too Big' },\n\t\t// \tmethod: method,\n\t\t// \tdate: messageDate\n\t\t// });\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tchangeStream.close();\n\t\t})\n\t\t.on('close', () => {\n\t\t\tthis.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tthis.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// Fetch and process attachments\n\t\t\t\tif (emailHistory.attachments && emailHistory.attachments.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (let att of emailHistory.attachments) {\n\t\t\t\t\t\t\tif (att.path && att.path.startsWith('http')) {\n\t\t\t\t\t\t\t\tconst response = await fetch(att.path);\n\t\t\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Failed to fetch attachment: ${att.path}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t\t\t\t\tconst buffer = Buffer.from(arrayBuffer);\n\t\n\t\t\t\t\t\t\t\t// Check the size of the attachment\n\t\t\t\t\t\t\t\tconst maxSize = 20 * 1024 * 1024; // 20MB in bytes\n\t\t\t\t\t\t\t\tif (buffer.length <= maxSize) {\n\t\t\t\t\t\t\t\t\t// Attachment is within size limits, include it\n\t\t\t\t\t\t\t\t\tatt.content = buffer;\n\t\t\t\t\t\t\t\t\tdelete att.path;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Failed to fetch attachment:', err);\n\t\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// Skip to the next email\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (this.serverConfig['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || this.serverConfig.MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(this.serverConfig['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tthis.serverConfig['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./)\n\t\t\t\t\t\t\t? '(DEV SERVER) - '\n\t\t\t\t\t\t\t: '') + emailHistory.subject,\n\t\t\t\t\ttext: typeof emailHistory.text === 'string' ? emailHistory.text : '',\n\t\t\t\t\thtml: typeof emailHistory.html === 'string' ? emailHistory.html : '',\n\t\t\t\t\tattachments: emailHistory.attachments || [],\n\t\t\t\t};\n\t\n\t\t\t\t// Process attachments before sending\n\t\t\t\tif (mailOptions.attachments && mailOptions.attachments.length > 0) {\n\t\t\t\t\tmailOptions.attachments = mailOptions.attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\t// Handle attachments stored as BinData or Buffer\n\t\t\t\t\t\tif (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {\n\t\t\t\t\t\t\t// Convert MongoDB's Binary data to Buffer\n\t\t\t\t\t\t\tif (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content.buffer);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Handle other types if necessary\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Handle attachments stored as Base64 strings\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content, 'base64');\n\t\t\t\t\t\t\tdelete newAtt.encoding;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Ensure the content is a Buffer\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\t// Send the email\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tthis._mailer.sendMail(mailOptions, async (err, info) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\t\tEmailHistories.deleteOne({ _id: emailHistory._id });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\terror: typeof error === 'string' ? error : this.safeStringify(error),\n\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tresolve(); // Continue processing the queue\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\n\t\t\t\t// Wait for at least one second before sending the next email\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// Modify sendTo in development environments\n\t\t\tif (\n\t\t\t\t(this.serverConfig['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\tthis.serverConfig['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\t\tthis.serverConfig['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t\t) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\t\n\t\t\tif (sendTo) {\n\t\t\t\tif (\n\t\t\t\t\tthis.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\t\tlocal_override\n\t\t\t\t) {\n\t\t\t\t\tif (!attachments) {\n\t\t\t\t\t\tattachments = [];\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\t\tattachments = [attachments];\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// Process attachments before saving\n\t\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\n\t\t\t\t\t// Queue the email in MongoDB\n\t\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\t\ttext: text || '',\n\t\t\t\t\t\thtml: html || '',\n\t\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t\terror: ''\n\t\t\t\t\t};\n\t\n\t\t\t\t\tEmailHistories.insertOne(emailHistory).then(\n\t\t\t\t\t\t(history) => resolve(history),\n\t\t\t\t\t\t(err) => {\n\t\t\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t'Send email',\n\t\t\t\t\t\tsendTo,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\thtml,\n\t\t\t\t\t\tattachments,\n\t\t\t\t\t\tsend_from\n\t\t\t\t\t);\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(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","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","flag_updates_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","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","console","log","Date","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","setupEmailWatcher","getMainServer","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","skipValidation","check","error","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","i","validate","errors","JSON","stringify","monitor_2","taskId_1","monitor_3","promise","serializedData","Buffer","byteLength","startMonitorFunction","objectIdHexString","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","finishMonitorFunction","taskResponse","has_error","data","close","WorkerTaskRequests","create","_id","params","status","id_user","id_ws","_a","function","call","apply","__spreadArray","__read","then","res","methodErrs","callMethod","id_methodLatency","ws","messageDate","messageId","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","monitor_4","changeStream_1","monitor_5","taskId","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","Logs","insertOne","type","collection","id_document","payload","getBinarySize","route","monitor_6","taskId_2","monitor_7","functionMethodData","slice","send","EmailHistories","add","toString","tryProcessEmail","updatedEmail","has","delete","loadPendingEmails","find","sort","pendingEmails","_b","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","processingAt","emailHistory","_e","attachments","e_2","_c","att","startsWith","fetch","response","ok","arrayBuffer","Error","concat","buffer","from","content","err_2","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","sendMail","info","err_1","obj","getCircularReplacer","e","message","seen","WeakSet","key","sendTo","local_override","Array","isArray","isBuffer","__v","date","history","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"ihFACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,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C,EAASC,GACxB3I,GAAGoS,WAAWrS,KAAKsS,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEnS,GAAGkS,SAASnS,KAAKsS,KAAKC,UAAY,cAAgBH,CAAS,EAAG,QAAS,SAACjG,EAAK1B,GACxE0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,EAGGxK,GAAGoS,WAAWrS,KAAKsS,KAAKrP,EAAKJ,UAAY,aAAeuP,CAAS,CAAC,GACrEnS,GAAGkS,SAASnS,KAAKsS,KAAKrP,EAAKJ,UAAY,aAAeuP,CAAS,EAAG,QAAS,SAACjG,EAAK1B,GAC5E0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEO/H,cAAAd,UAAA4Q,UAAP,SAAiBJ,GAAjB,IAAAnP,EAAAzB,KACC,OAAO,IAAIkH,QAAQ,SAACC,EAASC,GACxB3I,GAAGoS,WAAWrS,KAAKsS,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEnS,GAAGkS,SAASnS,KAAKsS,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAACjG,EAAK1B,GACzE0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,EAGGxK,GAAGoS,WAAWrS,KAAKsS,KAAKrP,EAAKJ,UAAY,aAAeuP,CAAS,CAAC,GACrEnS,GAAGkS,SAASnS,KAAKsS,KAAKrP,EAAKJ,UAAY,aAAeuP,CAAS,EAAG,SAAU,SAACjG,EAAK1B,GAC7E0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACD/H,aAAA,EAAC,GA3gCYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { getBinarySize } 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';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { EmailHistoryModel } from '../models/email-history.model';\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\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _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._websocketManager = this._mainServer.getWebSocketManager();\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\tif (process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tloadServerInit(serverConfig);\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadFlagUpdatesMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(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 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}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tthis.setupEmailWatcher();\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// To prevent extremely large data being inserted, let's split it up into references if needed\n\t\t// For example, if `methodData` is huge, we can store large arrays/objects into a separate collection\n\t\t// and only store references in the worker-task-requests doc. This avoids hitting the 16MB BSON limit.\n\t\tlet MAX_DOCUMENT_SIZE = 1024 * 1024 * 8; // 8MB as a threshold before we chunk (just an example threshold)\n\t\tlet serializedData = JSON.stringify(methodData);\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tBuffer.byteLength(serializedData, 'utf8') < MAX_DOCUMENT_SIZE &&\n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\t\t\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\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\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\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\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\tpromise = 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\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\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\t\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\t\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\t\n\t\t\treturn;\n\t\t}\n\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\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\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\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\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\t\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\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\t\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\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\t\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\t\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\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\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\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// To prevent extremely large data being inserted, let's split it up into references if needed\n\t\t// For example, if `methodData` is huge, we can store large arrays/objects into a separate collection\n\t\t// and only store references in the worker-task-requests doc. This avoids hitting the 16MB BSON limit.\n\t\tlet MAX_DOCUMENT_SIZE = 1024 * 1024 * 8; // 8MB as a threshold before we chunk (just an example threshold)\n\t\tlet serializedData = JSON.stringify(methodData);\n\t\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tBuffer.byteLength(serializedData, 'utf8') < MAX_DOCUMENT_SIZE &&\n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\t\n\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\tconst taskId = objectIdHexString();\n\t\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\t\n\t\t\tchangeStream.on('change', async change => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\t\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\t\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\t\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\t\t\t\t\t\tif (latency) {\n\t\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\t}\n\t\t\t\t\t}\n\t\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t}\n\t\t\t});\n\t\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\t\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\t\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\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\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},\n\t\t\terr => {\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\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\t\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: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution' && method !== 'incCounter' && method !== 'supportCreateBillingUser' && method !== 'countCollectionWithQuery') {\n\t\t\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\t// To prevent extremely large data being inserted, let's split it up into references if needed\n\t\t// For example, if `methodData` is huge, we can store large arrays/objects into a separate collection\n\t\t// and only store references in the worker-task-requests doc. This avoids hitting the 16MB BSON limit.\n\t\tlet MAX_DOCUMENT_SIZE = 1024 * 1024 * 8; // 8MB as a threshold before we chunk (just an example threshold)\n\t\tlet serializedData = JSON.stringify(functionMethodData);\n\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tBuffer.byteLength(serializedData, 'utf8') < MAX_DOCUMENT_SIZE &&\n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\t\t\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\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\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\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\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},\n\t\t\t\tmethodErrs => {\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._websocketManager.send(ws, data);\n\n\t\tif (\n\t\t\tmethod !== 'reportBuilderGetResults' &&\n\t\t\tmethod !== 'reportBuilderGetDistinctValue' &&\n\t\t\tmethod !== 'reportBuilderBuildTree' &&\n\t\t\tmethod !== 'generatePDF' &&\n\t\t\tmethod !== 'getWOOfflineData' &&\n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'countCollectionWithQuery' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'uploadFileAndSave' &&\n\t\t\tmethod !== 'getDrivers' &&\n\t\t\tmethod !== 'processAirdropDistribution'\n\t\t) {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'client-response',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload:\n\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t: 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\tuser: ws['user'] || '',\n\t\t\t\tmessageId: data.messageId,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\t// MethodResponses.create({\n\t\t// \t_id: objectIdHexString(),\n\t\t// \t__v: 0,\n\t\t// \tid_user: ws['id_user'] || '',\n\t\t// \tmessage_id: data.messageId,\n\t\t// \tresponse: getBinarySize(JSON.stringify(data)) < 200000 ? data : { error: 'Too Big' },\n\t\t// \tmethod: method,\n\t\t// \tdate: messageDate\n\t\t// });\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tchangeStream.close();\n\t\t})\n\t\t.on('close', () => {\n\t\t\tthis.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tthis.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// Fetch and process attachments\n\t\t\t\tif (emailHistory.attachments && emailHistory.attachments.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (let att of emailHistory.attachments) {\n\t\t\t\t\t\t\tif (att.path && att.path.startsWith('http')) {\n\t\t\t\t\t\t\t\tconst response = await fetch(att.path);\n\t\t\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Failed to fetch attachment: ${att.path}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t\t\t\t\tconst buffer = Buffer.from(arrayBuffer);\n\t\n\t\t\t\t\t\t\t\t// Check the size of the attachment\n\t\t\t\t\t\t\t\tconst maxSize = 20 * 1024 * 1024; // 20MB in bytes\n\t\t\t\t\t\t\t\tif (buffer.length <= maxSize) {\n\t\t\t\t\t\t\t\t\t// Attachment is within size limits, include it\n\t\t\t\t\t\t\t\t\tatt.content = buffer;\n\t\t\t\t\t\t\t\t\tdelete att.path;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Failed to fetch attachment:', err);\n\t\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// Skip to the next email\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (this.serverConfig['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || this.serverConfig.MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(this.serverConfig['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tthis.serverConfig['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./)\n\t\t\t\t\t\t\t? '(DEV SERVER) - '\n\t\t\t\t\t\t\t: '') + emailHistory.subject,\n\t\t\t\t\ttext: typeof emailHistory.text === 'string' ? emailHistory.text : '',\n\t\t\t\t\thtml: typeof emailHistory.html === 'string' ? emailHistory.html : '',\n\t\t\t\t\tattachments: emailHistory.attachments || [],\n\t\t\t\t};\n\t\n\t\t\t\t// Process attachments before sending\n\t\t\t\tif (mailOptions.attachments && mailOptions.attachments.length > 0) {\n\t\t\t\t\tmailOptions.attachments = mailOptions.attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\t// Handle attachments stored as BinData or Buffer\n\t\t\t\t\t\tif (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {\n\t\t\t\t\t\t\t// Convert MongoDB's Binary data to Buffer\n\t\t\t\t\t\t\tif (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content.buffer);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Handle other types if necessary\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Handle attachments stored as Base64 strings\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content, 'base64');\n\t\t\t\t\t\t\tdelete newAtt.encoding;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Ensure the content is a Buffer\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\t// Send the email\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tthis._mailer.sendMail(mailOptions, async (err, info) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\t\tEmailHistories.deleteOne({ _id: emailHistory._id });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\t\tEmailHistories.updateOne(\n\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\terror: typeof error === 'string' ? error : this.safeStringify(error),\n\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tresolve(); // Continue processing the queue\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\n\t\t\t\t// Wait for at least one second before sending the next email\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tthis.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t// Modify sendTo in development environments\n\t\t\tif (\n\t\t\t\t(this.serverConfig['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\tthis.serverConfig['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\t\tthis.serverConfig['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t\t) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\t\n\t\t\tif (sendTo) {\n\t\t\t\tif (\n\t\t\t\t\tthis.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\t\tlocal_override\n\t\t\t\t) {\n\t\t\t\t\tif (!attachments) {\n\t\t\t\t\t\tattachments = [];\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\t\tattachments = [attachments];\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// Process attachments before saving\n\t\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\n\t\t\t\t\t// Queue the email in MongoDB\n\t\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\t\ttext: text || '',\n\t\t\t\t\t\thtml: html || '',\n\t\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t\terror: ''\n\t\t\t\t\t};\n\t\n\t\t\t\t\tEmailHistories.insertOne(emailHistory).then(\n\t\t\t\t\t\t(history) => resolve(history),\n\t\t\t\t\t\t(err) => {\n\t\t\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t'Send email',\n\t\t\t\t\t\tsendTo,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\thtml,\n\t\t\t\t\t\tattachments,\n\t\t\t\t\t\tsend_from\n\t\t\t\t\t);\n\t\t\t\t\tresolve(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(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}"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.4.79",
3
+ "version": "20.4.80",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",
package/server-app.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function verb(t){return function(e){var r=[t,e];if(o)throw new TypeError("Generator is already executing.");for(;c=u&&r[u=0]?0:c;)try{if(o=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))c.label=r[1];else if(6===r[0]&&c.label<a[1])c.label=a[1],a=r;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(r)}}r=s.call(n,c)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,s,o=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(n=o.next()).done;)i.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(t=o.return)&&t.call(o)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),mongo_manager_1=require("./managers/mongo.manager"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),log_method_latency_collection_1=require("./collections/log-method-latency.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),index_1=require("./index"),mongodb_1=require("mongodb"),worker_task_request_collection_1=require("./collections/worker-task-request.collection"),worker_task_response_collection_1=require("./collections/worker-task-response.collection"),websocket_manager_1=require("./managers/websocket.manager"),worker_task_data_chunk_collection_1=require("./collections/worker-task-data-chunk.collection"),ResolveIOMainServer=function(){function ResolveIOMainServer(e,r,t,n,s,o,i){void 0===i&&(i=!1);var a=this;this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._workerTasks=[],this._safeShutdown=!1,this._serverConfig=r,this._clientRoutes=t,this._clientDir=n,this.sesMail=s,this.standardProgram=o,this.publicProgram=i,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager(e,r),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){a._subscriptionManager&&a._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",a._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",a._debugMsgQueue)),a._debugMsgQueue=0,a._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(n,s){return __awaiter(a,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:n&&"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(a,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+this._serverConfig.CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){a._rebootFlag=!0,a._serverHTTP&&a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGTERM",function(){a._rebootFlag=!0,a._serverHTTP&&a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGQUIT",function(){a._rebootFlag=!0,a._serverHTTP&&a._serverHTTP.close(),a.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager(this),this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager(this),this.listen())}return ResolveIOMainServer.prototype.startServerInstance=function(e){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||e.PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||e.PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,e),(0,health_1.setupHealthRoutes)(this._app,e),"ResolveIO"!==e.CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,e),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c=this;return __generator(this,function(e){switch(e.label){case 0:return console.log("Worker instance started, watching worker-task-reqs..."),(r=worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"})).on("change",function(s){return __awaiter(c,void 0,void 0,function(){var r,t,n=this;return __generator(this,function(e){return"insert"===s.operationType?(r=s.fullDocument)&&setTimeout(function(){n.processTask(r)},25*this._workerTasks.length):"update"===s.operationType&&(t=s.fullDocument)&&"pending"===t.status&&setTimeout(function(){n.processTask(t)},25*this._workerTasks.length),[2]})})}),r.on("error",function(e){console.error("Error in change stream worker task requests:",e),r&&r.close(),setTimeout(function(){return c.startWorkerInstance()},5e3)}),r.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return c.startWorkerInstance()},5e3)}),[4,worker_task_request_collection_1.WorkerTaskRequests.find({status:"pending"},{sort:{createdAt:1}})];case 1:t=e.sent();try{for(n=__values(t),s=n.next();!s.done;s=n.next())o=s.value,this.processTask(o)}catch(e){i={error:e}}finally{try{s&&!s.done&&(a=n.return)&&a.call(n)}finally{if(i)throw i.error}}return[2]}})})},ResolveIOMainServer.prototype.processTask=function(_){return __awaiter(this,void 0,void 0,function(){var s,r,t,n,o,i,a,c,u,l=this;return __generator(this,function(e){switch(e.label){case 0:if(this._workerTasks.includes(_._id))return[2];if(!((s=_.params)&&s[0]&&s[0].__largeDataRef))return[3,9];r=s[0].chunks,t=[],e.label=1;case 1:e.trys.push([1,6,7,8]),n=__values(r),o=n.next(),e.label=2;case 2:return o.done?[3,5]:(i=o.value,[4,worker_task_data_chunk_collection_1.WorkerTaskDataChunks.findById(i)]);case 3:(i=e.sent())&&i.data&&t.push(Buffer.from(i.data,"base64")),e.label=4;case 4:return o=n.next(),[3,2];case 5:return[3,8];case 6:return c=e.sent(),c={error:c},[3,8];case 7:try{o&&!o.done&&(u=n.return)&&u.call(n)}finally{if(c)throw c.error}return[7];case 8:a=Buffer.concat(t),s=JSON.parse(a.toString("utf8")),e.label=9;case 9:return worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:_._id,status:"pending"},{$set:{status:"processing"}}).then(function(n){return __awaiter(l,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:if(!n)return[3,5];this._workerTasks.push(_._id),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(t=this._methodManager.callMethodInternal).call.apply(t,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:_.id_user,user:_.user,id_ws:_.id_ws}),_.method],__read(s),!1))];case 2:return t=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:_._id,has_error:!1,data:t,id_user:_.id_user,user:_.user,id_ws:_.id_ws}),[3,4];case 3:return r=e.sent(),console.error("Worker failed to process task:",_._id,r),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:_._id,has_error:!0,data:r.message,id_user:_.id_user,user:_.user,id_ws:_.id_ws}),[3,4];case 4:this._workerTasks.includes(_._id)&&this._workerTasks.splice(this._workerTasks.indexOf(_._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:_._id},{$set:{status:"complete"}}),e.label=5;case 5:return[2]}})})},function(){}),[2]}})})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):index_1.ResolveIOServer.getMongoConnection()?index_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(o,i){return __awaiter(e,void 0,void 0,function(){var r,s=this;return __generator(this,function(e){return this._rebootFlag?i(!1,409,"Unable To Process"):("DEBUG"===this.LOGGER&&console.log("Verify Client",o,i),r=o.req.headers["sec-websocket-protocol"].split(/,/),(o.origin===this._serverConfig.ROOT_URL||o.origin===this._serverConfig.SEC_ROOT_URL||o.origin===this._serverConfig.RESOLVEIO_URL||o.origin===this._serverConfig.RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,this._serverConfig.JWT_SECRET,function(t,n){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:o.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(o.req.user=r.fullname,o.req.user_readonly=r.readonly||!1,o.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")),[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var t=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",t._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",t._portWSS)}),this._serverWSS.on("connection",function(u,e){t.publicProgram||(u.id_user=e.id_user,u.user=e.user,u.user_readonly=e.user_readonly,u.doc_user=e.doc_user,"Admin"!==u.user&&"ResolveIO"!==t._serverConfig.CLIENT_NAME&&t.getMethodManager().callMethodInternal.call(t.getMethodManager(),"supportCreateBillingUser",{id_user:u.id_user,user:u.user,date:new Date,client:index_1.ResolveIOServer.getClientName()})),u.id_socket=(0,mongo_manager_1.objectIdHexString)(),u.retryCnt=0,t._websocketManager.addWebSocket(u),t._subscriptionManager.createLoggedInUser(u.id_socket).then(function(){setTimeout(function(){u.pingTime=new Date,u.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(u))})},5e3)}),"DEBUG"===t.LOGGER&&console.log("Connection from: "+e.user),u.isAlive=!0,u.on("message",function(c){return __awaiter(t,void 0,void 0,function(){var r,t,n,s,o,i,a=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+u.user,c),this._debugMsgRecv+=1,s=!1,r=[];try{r=JSON.parse(c,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",c),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+this._serverConfig.CLIENT_NAME,JSON.stringify([c,e])),s=!0}if(s)return[3,8];if("string"==typeof r&&"ping"===r)u&&u.readyState===u.OPEN&&u.send("pong",function(e){e&&(a._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),a.unsubscribeWS(u))});else if("string"==typeof r&&"pong"===r)u.isAlive=!0,u.pongTime=new Date,u.latency=moment.duration(moment(u.pongTime).diff(u.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(u);else{if(Array.isArray(r[0]))return[3,1];console.log("Invalid message format, expected array:",r)}return[2];case 1:e.trys.push([1,6,7,8]),t=__values(r),n=t.next(),e.label=2;case 2:return n.done?[3,5]:(s=n.value,[4,this.processSocketMessage(u,s)]);case 3:e.sent(),e.label=4;case 4:return n=t.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),o={error:o},[3,8];case 7:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 8:return[2]}})})}).on("end",function(){t.unsubscribeWS(u),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){t.unsubscribeWS(u),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){t.unsubscribeWS(u),t._subscriptionManager.getEnableDebug()&&console.log(new Date,u.user,u.id_socket,"WS Error")})}),setInterval(function(){t._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?t.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(m,v){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c,u,l,_,g,h,d,p,f;return __generator(this,function(e){switch(e.label){case 0:return(r=v[0],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||m.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||m.doc_user.roles.super_admin)?(a=v[1],t=v[2],"subscription"!==(n=v[3])?[3,1]:(i=v[4],c=v[5],"sub"===i?this._subscriptionManager.subscribe(r,a,m,t,c,v.slice(6)):this._subscriptionManager.unsubscribe(r,a,m,t,c,v.slice(6)),[3,11])):[2];case 1:if(this.publicProgram||"offline"!==n)return[3,10];d={messageId:t,hasError:!1,data:"ACK"},m&&m.readyState===m.OPEN&&this._websocketManager.send(m,d),this._offlineUpdates.push(m),s=v[4],o=0,e.label=2;case 2:if(!(o<s.length))return[3,9];if(i=s[o],u=i.data,u.shift(),u.shift(),a=u.shift(),u.shift(),g=u.shift(),h=(0,mongo_manager_1.objectIdHexString)(),c={messageId:a,hasError:!1,data:"ACK"},m&&m.readyState===m.OPEN&&this._websocketManager.send(m,c),"insertDocument"===g&&"driver-gps"===u[0])return[3,8];if(log_method_latency_collection_1.LogMethodLatencies.create({_id:h,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(u))<2e5?JSON.stringify(u,null,2):"Too Big",method:g,id_user:m.id_user||"",user:m.user||"",messageId:t,route:r}),!this._methodManager._methods[g])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(p=this._methodManager.callMethodInternal).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:m.id_user,user:m.user,id_ws:m.id_socket}),g],__read(u),!1))];case 4:return e.sent(),[3,6];case 5:return p=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(p,null,2)),[3,6];case 6:return"updateDocumentOffline"!==g&&"updateDocumentPropsOffline"!==g||index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u[0]),[3,8];case 7:console.log("Offline - Could not find method: "+g),e.label=8;case 8:return o++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(m.id_socket),1),[3,11];case 10:if(u=__spreadArray([],__read(v),!1),f=u.shift(),l=u.shift(),_=u.shift(),"method"===u.shift()){if(g=u.shift(),m.user_readonly)return[2];h=(0,mongo_manager_1.objectIdHexString)(),log_method_latency_collection_1.LogMethodLatencies.create({_id:h,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(u))<2e5?JSON.stringify(u,null,2):"Too Big",method:g,id_user:m.id_user||"",user:m.user||"",messageId:_,route:f}),d={messageId:_,hasError:!1,data:"ACK"},m&&m.readyState===m.OPEN&&this._websocketManager.send(m,d),this._methodManager._methods[g]?(f=this._methodManager).callMethod.apply(f,__spreadArray([h,m,l,_,g],__read(u),!1)):console.log("Could not find method: "+g)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return this._serverConfig},ResolveIOMainServer}();exports.default=ResolveIOMainServer;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function verb(t){return function(e){var r=[t,e];if(o)throw new TypeError("Generator is already executing.");for(;c=u&&r[u=0]?0:c;)try{if(o=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))c.label=r[1];else if(6===r[0]&&c.label<a[1])c.label=a[1],a=r;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(r)}}r=s.call(n,c)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,s,o=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(n=o.next()).done;)i.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(t=o.return)&&t.call(o)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),mongo_manager_1=require("./managers/mongo.manager"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),log_method_latency_collection_1=require("./collections/log-method-latency.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),index_1=require("./index"),mongodb_1=require("mongodb"),worker_task_request_collection_1=require("./collections/worker-task-request.collection"),worker_task_response_collection_1=require("./collections/worker-task-response.collection"),websocket_manager_1=require("./managers/websocket.manager"),ResolveIOMainServer=function(){function ResolveIOMainServer(e,r,t,n,s,o,i){void 0===i&&(i=!1);var a=this;this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._workerTasks=[],this._safeShutdown=!1,this._serverConfig=r,this._clientRoutes=t,this._clientDir=n,this.sesMail=s,this.standardProgram=o,this.publicProgram=i,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager(e,r),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){a._subscriptionManager&&a._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",a._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",a._debugMsgQueue)),a._debugMsgQueue=0,a._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(n,s){return __awaiter(a,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:n&&"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(a,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+this._serverConfig.CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){a._rebootFlag=!0,a._serverHTTP&&a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGTERM",function(){a._rebootFlag=!0,a._serverHTTP&&a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGQUIT",function(){a._rebootFlag=!0,a._serverHTTP&&a._serverHTTP.close(),a.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager(this),this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager(this),this.listen())}return ResolveIOMainServer.prototype.startServerInstance=function(e){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||e.PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||e.PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,e),(0,health_1.setupHealthRoutes)(this._app,e),"ResolveIO"!==e.CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,e),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c=this;return __generator(this,function(e){switch(e.label){case 0:return console.log("Worker instance started, watching worker-task-reqs..."),(r=worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"})).on("change",function(s){return __awaiter(c,void 0,void 0,function(){var r,t,n=this;return __generator(this,function(e){return"insert"===s.operationType?(r=s.fullDocument)&&setTimeout(function(){n.processTask(r)},25*this._workerTasks.length):"update"===s.operationType&&(t=s.fullDocument)&&"pending"===t.status&&setTimeout(function(){n.processTask(t)},25*this._workerTasks.length),[2]})})}),r.on("error",function(e){console.error("Error in change stream worker task requests:",e),r&&r.close(),setTimeout(function(){return c.startWorkerInstance()},5e3)}),r.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return c.startWorkerInstance()},5e3)}),[4,worker_task_request_collection_1.WorkerTaskRequests.find({status:"pending"},{sort:{createdAt:1}})];case 1:t=e.sent();try{for(n=__values(t),s=n.next();!s.done;s=n.next())o=s.value,this.processTask(o)}catch(e){i={error:e}}finally{try{s&&!s.done&&(a=n.return)&&a.call(n)}finally{if(i)throw i.error}}return[2]}})})},ResolveIOMainServer.prototype.processTask=function(s){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){return this._workerTasks.includes(s._id)||worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:s._id,status:"pending"},{$set:{status:"processing"}}).then(function(n){return __awaiter(r,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:if(!n)return[3,5];this._workerTasks.push(s._id),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(t=this._methodManager.callMethodInternal).call.apply(t,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:s.id_user,user:s.user,id_ws:s.id_ws}),s.method],__read(s.params),!1))];case 2:return t=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:s._id,has_error:!1,data:t,id_user:s.id_user,user:s.user,id_ws:s.id_ws}),[3,4];case 3:return r=e.sent(),console.error("Worker failed to process task:",s._id,r),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:s._id,has_error:!0,data:r.message,id_user:s.id_user,user:s.user,id_ws:s.id_ws}),[3,4];case 4:this._workerTasks.includes(s._id)&&this._workerTasks.splice(this._workerTasks.indexOf(s._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:s._id},{$set:{status:"complete"}}),e.label=5;case 5:return[2]}})})},function(){}),[2]})})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):index_1.ResolveIOServer.getMongoConnection()?index_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(o,i){return __awaiter(e,void 0,void 0,function(){var r,s=this;return __generator(this,function(e){return this._rebootFlag?i(!1,409,"Unable To Process"):("DEBUG"===this.LOGGER&&console.log("Verify Client",o,i),r=o.req.headers["sec-websocket-protocol"].split(/,/),(o.origin===this._serverConfig.ROOT_URL||o.origin===this._serverConfig.SEC_ROOT_URL||o.origin===this._serverConfig.RESOLVEIO_URL||o.origin===this._serverConfig.RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,this._serverConfig.JWT_SECRET,function(t,n){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:o.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(o.req.user=r.fullname,o.req.user_readonly=r.readonly||!1,o.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")),[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var t=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",t._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",t._portWSS)}),this._serverWSS.on("connection",function(u,e){t.publicProgram||(u.id_user=e.id_user,u.user=e.user,u.user_readonly=e.user_readonly,u.doc_user=e.doc_user,"Admin"!==u.user&&"ResolveIO"!==t._serverConfig.CLIENT_NAME&&t.getMethodManager().callMethodInternal.call(t.getMethodManager(),"supportCreateBillingUser",{id_user:u.id_user,user:u.user,date:new Date,client:index_1.ResolveIOServer.getClientName()})),u.id_socket=(0,mongo_manager_1.objectIdHexString)(),u.retryCnt=0,t._websocketManager.addWebSocket(u),t._subscriptionManager.createLoggedInUser(u.id_socket).then(function(){setTimeout(function(){u.pingTime=new Date,u.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(u))})},5e3)}),"DEBUG"===t.LOGGER&&console.log("Connection from: "+e.user),u.isAlive=!0,u.on("message",function(c){return __awaiter(t,void 0,void 0,function(){var r,t,n,s,o,i,a=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+u.user,c),this._debugMsgRecv+=1,s=!1,r=[];try{r=JSON.parse(c,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",c),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+this._serverConfig.CLIENT_NAME,JSON.stringify([c,e])),s=!0}if(s)return[3,8];if("string"==typeof r&&"ping"===r)u&&u.readyState===u.OPEN&&u.send("pong",function(e){e&&(a._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),a.unsubscribeWS(u))});else if("string"==typeof r&&"pong"===r)u.isAlive=!0,u.pongTime=new Date,u.latency=moment.duration(moment(u.pongTime).diff(u.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(u);else{if(Array.isArray(r[0]))return[3,1];console.log("Invalid message format, expected array:",r)}return[2];case 1:e.trys.push([1,6,7,8]),t=__values(r),n=t.next(),e.label=2;case 2:return n.done?[3,5]:(s=n.value,[4,this.processSocketMessage(u,s)]);case 3:e.sent(),e.label=4;case 4:return n=t.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),o={error:o},[3,8];case 7:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 8:return[2]}})})}).on("end",function(){t.unsubscribeWS(u),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){t.unsubscribeWS(u),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){t.unsubscribeWS(u),t._subscriptionManager.getEnableDebug()&&console.log(new Date,u.user,u.id_socket,"WS Error")})}),setInterval(function(){t._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?t.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(m,v){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c,u,l,_,g,h,d,p,f;return __generator(this,function(e){switch(e.label){case 0:return(r=v[0],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||m.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||m.doc_user.roles.super_admin)?(a=v[1],t=v[2],"subscription"!==(n=v[3])?[3,1]:(i=v[4],c=v[5],"sub"===i?this._subscriptionManager.subscribe(r,a,m,t,c,v.slice(6)):this._subscriptionManager.unsubscribe(r,a,m,t,c,v.slice(6)),[3,11])):[2];case 1:if(this.publicProgram||"offline"!==n)return[3,10];d={messageId:t,hasError:!1,data:"ACK"},m&&m.readyState===m.OPEN&&this._websocketManager.send(m,d),this._offlineUpdates.push(m),s=v[4],o=0,e.label=2;case 2:if(!(o<s.length))return[3,9];if(i=s[o],u=i.data,u.shift(),u.shift(),a=u.shift(),u.shift(),g=u.shift(),h=(0,mongo_manager_1.objectIdHexString)(),c={messageId:a,hasError:!1,data:"ACK"},m&&m.readyState===m.OPEN&&this._websocketManager.send(m,c),"insertDocument"===g&&"driver-gps"===u[0])return[3,8];if(log_method_latency_collection_1.LogMethodLatencies.create({_id:h,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(u))<2e5?JSON.stringify(u,null,2):"Too Big",method:g,id_user:m.id_user||"",user:m.user||"",messageId:t,route:r}),!this._methodManager._methods[g])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(p=this._methodManager.callMethodInternal).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:m.id_user,user:m.user,id_ws:m.id_socket}),g],__read(u),!1))];case 4:return e.sent(),[3,6];case 5:return p=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(p,null,2)),[3,6];case 6:return"updateDocumentOffline"!==g&&"updateDocumentPropsOffline"!==g||index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u[0]),[3,8];case 7:console.log("Offline - Could not find method: "+g),e.label=8;case 8:return o++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(m.id_socket),1),[3,11];case 10:if(u=__spreadArray([],__read(v),!1),f=u.shift(),l=u.shift(),_=u.shift(),"method"===u.shift()){if(g=u.shift(),m.user_readonly)return[2];h=(0,mongo_manager_1.objectIdHexString)(),log_method_latency_collection_1.LogMethodLatencies.create({_id:h,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(u))<2e5?JSON.stringify(u,null,2):"Too Big",method:g,id_user:m.id_user||"",user:m.user||"",messageId:_,route:f}),d={messageId:_,hasError:!1,data:"ACK"},m&&m.readyState===m.OPEN&&this._websocketManager.send(m,d),this._methodManager._methods[g]?(f=this._methodManager).callMethod.apply(f,__spreadArray([h,m,l,_,g],__read(u),!1)):console.log("Could not find method: "+g)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return this._serverConfig},ResolveIOMainServer}();exports.default=ResolveIOMainServer;
2
2
  //# sourceMappingURL=server-app.js.map
package/server-app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","mongo_manager_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","index_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","websocket_manager_1","worker_task_data_chunk_collection_1","ResolveIOMainServer","mainServer","serverConfig","clientRoutes","clientDir","sesMail","standardProgram","publicProgram","_this","this","_offlineUpdates","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_workerTasks","_safeShutdown","_serverConfig","_clientDir","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_methodManager","sendEmail","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","prototype","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","changeStream","WorkerTaskRequests","watchCollection","$match","fullDocument.status","fullDocument","change","operationType","task_1","processTask","length","task_2","status","find","sort","createdAt","pendingTasks","_b","pendingTasks_1","__values","pendingTasks_1_1","done","task","value","includes","_id","originalParams","params","__largeDataRef","chunks","buffers","chunks_1","chunks_1_1","cId","WorkerTaskDataChunks","findById","chunkDoc","data","push","Buffer","from","combinedBuffer","concat","parse","toString","updateOne","$set","then","resReq","callMethodInternal","call","apply","__spreadArray","Object","assign","id_user","user","id_ws","method","__read","result","WorkerTaskResponses","create","id_request","has_error","err_1","splice","indexOf","getActiveMonitorFunctions","setImmediate","ResolveIOServer","getMongoConnection","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","ws","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","fullname","readonly","date","client","getClientName","objectIdHexString","addWebSocket","createLoggedInUser","send","unsubscribeWS","parseErrorFound","socketData","e","readyState","OPEN","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","message_1","processSocketMessage","now","getTime","messageRoute","some","a","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","methodLatencyId","serverResMethod","LogMethodLatencies","__v","date_start","date_end","latency_ms","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","_c","err_3","getMongoManager","invalidateQueryCache","map","messageRoute_1","messageDate_1","messageId_1","callMethod","unsubscribeAll","removeAllListeners","getApp","getServerConfig"],"mappings":"+xEAAAA,Q,uDAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EAEAM,OAAAN,QAAA,iBAAA,EAEAO,SAAAP,QAAA,eAAA,EAEAQ,gBAAAR,QAAA,0BAAA,EACAS,eAAAT,QAAA,yBAAA,EACAU,iBAAAV,QAAA,2BAAA,EACAW,uBAAAX,QAAA,iCAAA,EACAY,kBAAAZ,QAAA,4BAAA,EAGAa,iBAAAb,QAAA,8BAAA,EACAc,gCAAAd,QAAA,6CAAA,EACAe,kBAAAf,QAAA,+BAAA,EAEAgB,OAAAhB,QAAA,aAAA,EACAiB,OAAAjB,QAAA,aAAA,EACAkB,SAAAlB,QAAA,eAAA,EACAmB,QAAAnB,QAAA,SAAA,EACAoB,UAAApB,QAAA,SAAA,EACAqB,iCAAArB,QAAA,8CAAA,EACAsB,kCAAAtB,QAAA,+CAAA,EAEAuB,oBAAAvB,QAAA,8BAA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AgC,YAAXA,GAAmC,oBAAXA,GAA2C,eAAXA,GAAsC,+BAAXA,GACxYjK,iBAAAqQ,KAAKC,UAAU,CACdtI,KAAK,EAAArI,gBAAAuN,mBAAiB,EACtB+B,KAAM,iBACNsB,WAAY,GACZC,YAAa,GACbC,SAAS,EAAA/Q,SAAAgR,eAAc9M,KAAKC,UAAU+E,CAAI,CAAC,EAAI,IAAShF,KAAKC,UAAU+E,EAAM,KAAM,CAAC,EAAI,UACxFqB,OAAQA,EACRH,QAASsB,EAAY,SAAK,GAC1BrB,KAAMqB,EAAS,MAAK,GACpB4D,UAAWoC,EACXT,MAAOO,C,CACP,EAGE3B,EAAiC,CACpCP,UAAWoC,EACX5B,SAAU,CAAA,EACV5G,KAAM,K,EAGHwC,GAAMA,EAAGsC,aAAetC,EAAGuC,MAC9BtM,KAAKsD,kBAAkB0I,KAAKjC,EAAImE,CAAS,EAGtClO,KAAKqC,eAAekN,SAAS3G,IAChCzC,EAAAnG,KAAKqC,gBAAe2N,WAAU3H,MAAAlC,EAAAmC,cAAA,CAACmG,EAAiB1E,EAAI+F,EAAaC,EAAWnH,GAAMC,OAAKtB,CAAI,EAAA,CAAA,CAAA,CAAA,EAG3F5F,QAAQC,IAAI,0BAA4BgH,CAAM,C,oCAoB3CrJ,oBAAAqE,UAAAqI,cAAP,SAAqBlC,GAChB/J,KAAKyB,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIb,KAAQ,aAAc,WAAYgJ,EAAS,KAAGA,EAAc,SAAC,EAE9E/J,KAAKyB,qBAAqBwO,eAAelG,CAAE,EAC3CA,EAAGmG,mBAAkB,CAEtB,EAEO3Q,oBAAAqE,UAAAuM,OAAP,WACC,OAAOnQ,KAAK6D,IACb,EAEOtE,oBAAAqE,UAAAwM,gBAAP,WACC,OAAOpQ,KAAKY,aACb,EACDrB,mBAAA,EAAC","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\n// import * as SegfaultHandler from 'segfault-handler';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize, deepCopy } from './util/common';\n\nimport { objectIdHexString } from './managers/mongo.manager';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\n\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { LogMethodLatencies } from './collections/log-method-latency.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { ResolveIOServer } from './index';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\nimport { WorkerTaskRequestModel } from './models/worker-task-request.model';\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { WorkerTaskDataChunks } from './collections/worker-task-data-chunk.collection';\n\nexport default class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _serverConfig;\n\tprivate _clientDir;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\tprivate _workerTasks: string[] = [];\n\n\tprivate _safeShutdown = false;\n\n\tconstructor(mainServer, serverConfig, clientRoutes, clientDir, sesMail, standardProgram, publicProgram = false) {\n\t\tthis._serverConfig = serverConfig;\n\t\tthis._clientRoutes = clientRoutes;\n\t\tthis._clientDir = clientDir;\n\t\tthis.sesMail = sesMail;\n\t\tthis.standardProgram = standardProgram;\n\t\tthis.publicProgram = publicProgram;\n\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager(mainServer, serverConfig);\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n if (this._isWorkersEnabled) {\n if (this._isWorkerInstance) {\n console.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager(this);\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance(serverConfig);\n\t\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance(serverConfig);\n\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n this._cronManager = new CronManager(this);\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance(serverConfig) {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use body parser for http call (login)\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || serverConfig['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || serverConfig['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\n\t\t\t// Website you wish to allow to connect\n\t\t\t// res.setHeader('Access-Control-Allow-Origin', serverConfig['ROOT_URL']);\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\n\t\t\t// Request methods you wish to allow\n\t\t\t// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\n\t\t\t// Request headers you wish to allow\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\n\t\t\t// Set to true if you need the website to include cookies in the requests sent\n\t\t\t// to the API (e.g. in case you use sessions)\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\n\t\t\t// Pass to next layer of middleware\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, serverConfig);\n\t\tsetupHealthRoutes(this._app, serverConfig);\n\n\t\tif (serverConfig['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, serverConfig);\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\t\t\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\t\t\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task) {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (change.operationType === 'update') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task && task.status === 'pending') {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tif (changeStream) {\n\t\t\t\tchangeStream.close();\n\t\t\t}\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000);\n\t\t});\n\t\t\n\t\tchangeStream.on('close', () => {\n\t\t\tconsole.log('Change stream worker task requests closed. Restarting...');\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000);\n\t\t});\n\t\n\t\tconst pendingTasks = await WorkerTaskRequests.find({ status: 'pending' }, {sort: {createdAt: 1}});\n\t\tfor (const task of pendingTasks) {\n\t\t\tthis.processTask(task);\n\t\t}\n\t}\n\t\n\t// Process a task (handles both existing and new tasks)\n\tprivate async processTask(task: WorkerTaskRequestModel) {\n\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\treturn;\n\t\t}\n\t\n\t\t// If there is a large data reference, reconstruct the data\n\t\tlet originalParams = task.params;\n\t\tif (originalParams && originalParams[0] && originalParams[0].__largeDataRef) {\n\t\t\tlet chunks = originalParams[0].chunks;\n\t\t\tlet buffers = [];\n\t\t\tfor (let cId of chunks) {\n\t\t\t\tlet chunkDoc = await WorkerTaskDataChunks.findById(cId);\n\t\t\t\tif (chunkDoc && chunkDoc.data) {\n\t\t\t\t\tbuffers.push(Buffer.from(chunkDoc.data, 'base64'));\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet combinedBuffer = Buffer.concat(buffers);\n\t\t\toriginalParams = JSON.parse(combinedBuffer.toString('utf8'));\n\t\t}\n\t\n\t\tWorkerTaskRequests.updateOne({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } }).then(async resReq => {\n\t\t\tif (resReq) {\n\t\t\t\tthis._workerTasks.push(task._id);\n\t\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, { id_user: task.id_user, user: task.user, id_ws: task.id_ws }), task.method, ...originalParams);\n\t\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\t\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\tdata: err.message,\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t}\n\t\n\t\t\t\tWorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\t\t\t}\n\t\t}, () => {});\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length && \n\t\t\t// (!this._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}, () => {process.exit(1)});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), \n\t\t\t\t\t'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length, \n\t\t\t\t\t// this._monitorManagerFunction.getLastCompletedMonitorFunction() ? this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime : '',\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\t// Start express server\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`\n\n\t\t// Start websocket server\n\t\t// Verify client with token before opening socket\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (info.origin !== this._serverConfig['ROOT_URL'] && info.origin !== this._serverConfig['SEC_ROOT_URL'] && info.origin !== this._serverConfig['RESOLVEIO_URL'] && info.origin !== this._serverConfig['RESOLVEIO_SECONDARY_URL']) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, this._serverConfig['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// Listen to port for websocket\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\t// On websocket connection (already verified)\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (!this.publicProgram) {\n\t\t\t\t// Get user from token\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tif (ws['user'] !== 'Admin' && this._serverConfig['CLIENT_NAME'] !== 'ResolveIO') {\n\t\t\t\t\tthis.getMethodManager().callMethodInternal.call(this.getMethodManager(), 'supportCreateBillingUser', {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tclient: ResolveIOServer.getClientName()\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\tws['retryCnt'] = 0;\n\n\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\n\t\t\t});\n\n\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\tconsole.log('Connection from: ' + req['user']);\n\t\t\t}\n\t\t\t\n\t\t\t// Use for keeping connection alive (ping/pong)\n\t\t\tws['isAlive'] = true;\n\t\t\tws.on('message', async (message: string) => {\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Message from: ' + ws['user'], message);\n\t\t\t\t}\n\n\t\t\t\tthis._debugMsgRecv += 1;\n\n\t\t\t\tlet parseErrorFound = false;\n\n\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch(e) {\n\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\n\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([message, e]));\n\n\t\t\t\t\tparseErrorFound = true;\n\t\t\t\t}\n\n\t\t\t\tif (!parseErrorFound) {\n\t\t\t\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send('pong', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Pong');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!Array.isArray(socketData[0])) {\n\t\t\t\t\t\t// Not an array, invalid message\n\t\t\t\t\t\tconsole.log('Invalid message format, expected array:', socketData);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (let message of socketData) {\n\t\t\t\t\t\t\tawait this.processSocketMessage(ws, message);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS End');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS Close');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', error => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), ws['user'], ws['id_socket'], 'WS Error');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t});\n\n\t\t// Keep alive timer to ping/pong\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any[]) {\n\t\tlet messageRoute = socketData[0];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet messageDate = socketData[1];\n\t\tlet messageId = socketData[2];\n\t\tlet type = socketData[3];\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = socketData[4];\n\t\t\tlet pub = socketData[5];\n\n\t\t\t// Subscribe\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t\t// Unsubscribe\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = socketData[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\tdate_end: null,\n\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\tmethod: method\n\t\t\t\t});\n\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse { //methods\n\t\t\tlet data = [...socketData];\n\t\t\t\n\t\t\tlet messageRoute: string = data.shift();\n\t\t\tlet messageDate: Date = data.shift();\n\t\t\tlet messageId: number = data.shift();\n\t\t\tlet type: string = data.shift();\n\n\t\t\tif (type === 'method') {\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\tdate_end: null,\n\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\tmethod: method\n\t\t\t\t});\n\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else if (type === 'methodResponse') {\n\t\t\t// \tlet method = data.shift();\n\n\t\t\t// \tMethodResponses.findOne({ $and: [{ id_user: ws['id_user'] }, { message_id: messageId }, { method: method }, { date: messageDate }] }).then(\n\t\t\t// \t\tres => {\n\t\t\t// \t\t\tif (res) {\n\t\t\t// \t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t// \t\t\t\t\tthis._websocketManager.send(ws, res.response);\n\t\t\t// \t\t\t\t}\n\t\t\t// \t\t\t}\n\t\t\t// \t\t},\n\t\t\t// \t\terr => {}\n\t\t\t// \t);\n\t\t\t// }\n\t\t}\n\t}\n\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn this._serverConfig;\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","mongo_manager_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","index_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","websocket_manager_1","ResolveIOMainServer","mainServer","serverConfig","clientRoutes","clientDir","sesMail","standardProgram","publicProgram","_this","this","_offlineUpdates","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_workerTasks","_safeShutdown","_serverConfig","_clientDir","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_methodManager","sendEmail","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","prototype","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","changeStream","WorkerTaskRequests","watchCollection","$match","fullDocument.status","fullDocument","change","operationType","task_1","processTask","length","task_2","status","find","sort","createdAt","pendingTasks","_b","pendingTasks_1","__values","pendingTasks_1_1","done","task","value","includes","_id","updateOne","$set","then","resReq","push","callMethodInternal","call","apply","__spreadArray","Object","assign","id_user","user","id_ws","method","__read","params","result","WorkerTaskResponses","create","id_request","has_error","data","err_1","splice","indexOf","getActiveMonitorFunctions","setImmediate","ResolveIOServer","getMongoConnection","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","ws","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","fullname","readonly","date","client","getClientName","objectIdHexString","addWebSocket","createLoggedInUser","send","unsubscribeWS","parseErrorFound","socketData","parse","e","readyState","OPEN","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","message_1","processSocketMessage","now","getTime","messageRoute","some","a","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","methodLatencyId","serverResMethod","LogMethodLatencies","__v","date_start","date_end","latency_ms","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","_c","err_3","getMongoManager","invalidateQueryCache","map","messageRoute_1","messageDate_1","messageId_1","callMethod","unsubscribeAll","removeAllListeners","getAp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EAEOtE,oBAAAqE,UAAA0L,gBAAP,WACC,OAAOtP,KAAKY,aACb,EACDrB,mBAAA,EAAC","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\n// import * as SegfaultHandler from 'segfault-handler';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize, deepCopy } from './util/common';\n\nimport { objectIdHexString } from './managers/mongo.manager';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\n\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { LogMethodLatencies } from './collections/log-method-latency.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { ResolveIOServer } from './index';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\nimport { WorkerTaskRequestModel } from './models/worker-task-request.model';\nimport { WebSocketManager } from './managers/websocket.manager';\n\nexport default class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _serverConfig;\n\tprivate _clientDir;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\tprivate _workerTasks: string[] = [];\n\n\tprivate _safeShutdown = false;\n\n\tconstructor(mainServer, serverConfig, clientRoutes, clientDir, sesMail, standardProgram, publicProgram = false) {\n\t\tthis._serverConfig = serverConfig;\n\t\tthis._clientRoutes = clientRoutes;\n\t\tthis._clientDir = clientDir;\n\t\tthis.sesMail = sesMail;\n\t\tthis.standardProgram = standardProgram;\n\t\tthis.publicProgram = publicProgram;\n\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager(mainServer, serverConfig);\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n if (this._isWorkersEnabled) {\n if (this._isWorkerInstance) {\n console.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager(this);\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance(serverConfig);\n\t\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance(serverConfig);\n\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n this._cronManager = new CronManager(this);\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance(serverConfig) {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use body parser for http call (login)\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || serverConfig['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || serverConfig['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\n\t\t\t// Website you wish to allow to connect\n\t\t\t// res.setHeader('Access-Control-Allow-Origin', serverConfig['ROOT_URL']);\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\n\t\t\t// Request methods you wish to allow\n\t\t\t// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\n\t\t\t// Request headers you wish to allow\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\n\t\t\t// Set to true if you need the website to include cookies in the requests sent\n\t\t\t// to the API (e.g. in case you use sessions)\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\n\t\t\t// Pass to next layer of middleware\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, serverConfig);\n\t\tsetupHealthRoutes(this._app, serverConfig);\n\n\t\tif (serverConfig['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, serverConfig);\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\t\n\t\t// Now, set up the change stream to watch for new tasks\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\t\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task) {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (change.operationType === 'update') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task && task.status === 'pending') {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tif (changeStream) {\n\t\t\t\tchangeStream.close();\n\t\t\t}\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000); // Restart after a delay\n\t\t});\n\t\n\t\tchangeStream.on('close', () => {\n\t\t\tconsole.log('Change stream worker task requests closed. Restarting...');\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000); // Restart after a delay\n\t\t});\n\n\t\t// First, process any existing pending tasks in the database\n\t\tconst pendingTasks = await WorkerTaskRequests.find({ status: 'pending' }, {sort: {createdAt: 1}});\n\n\t\tfor (const task of pendingTasks) {\n\t\t\tthis.processTask(task);\n\t\t}\n\t}\n\t\n\t// Process a task (handles both existing and new tasks)\n\tprivate async processTask(task: WorkerTaskRequestModel) {\n\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\treturn;\n\t\t}\n\t\t\t\n\t\tWorkerTaskRequests.updateOne({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } }).then(async resReq => {\n\t\t\tif (resReq) {\n\t\t\t\tthis._workerTasks.push(task._id);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Run the actual method\n\t\t\t\t\tconst result = await this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, { id_user: task.id_user, user: task.user, id_ws: task.id_ws }), task.method, ...task.params);\n\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\tdata: err.message,\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t}\n\n\t\t\t\t// Mark the task as complete\n\t\t\t\tWorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\n\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Complete Task', 'Current Jobs: ' + this._workerTasks.length);\n\t\t\t}\n\t\t}, () => {});\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length && \n\t\t\t// (!this._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}, () => {process.exit(1)});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), \n\t\t\t\t\t'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length, \n\t\t\t\t\t// this._monitorManagerFunction.getLastCompletedMonitorFunction() ? this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime : '',\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\t// Start express server\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`\n\n\t\t// Start websocket server\n\t\t// Verify client with token before opening socket\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (info.origin !== this._serverConfig['ROOT_URL'] && info.origin !== this._serverConfig['SEC_ROOT_URL'] && info.origin !== this._serverConfig['RESOLVEIO_URL'] && info.origin !== this._serverConfig['RESOLVEIO_SECONDARY_URL']) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, this._serverConfig['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// Listen to port for websocket\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\t// On websocket connection (already verified)\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (!this.publicProgram) {\n\t\t\t\t// Get user from token\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tif (ws['user'] !== 'Admin' && this._serverConfig['CLIENT_NAME'] !== 'ResolveIO') {\n\t\t\t\t\tthis.getMethodManager().callMethodInternal.call(this.getMethodManager(), 'supportCreateBillingUser', {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tclient: ResolveIOServer.getClientName()\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\tws['retryCnt'] = 0;\n\n\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\n\t\t\t});\n\n\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\tconsole.log('Connection from: ' + req['user']);\n\t\t\t}\n\t\t\t\n\t\t\t// Use for keeping connection alive (ping/pong)\n\t\t\tws['isAlive'] = true;\n\t\t\tws.on('message', async (message: string) => {\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Message from: ' + ws['user'], message);\n\t\t\t\t}\n\n\t\t\t\tthis._debugMsgRecv += 1;\n\n\t\t\t\tlet parseErrorFound = false;\n\n\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch(e) {\n\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\n\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([message, e]));\n\n\t\t\t\t\tparseErrorFound = true;\n\t\t\t\t}\n\n\t\t\t\tif (!parseErrorFound) {\n\t\t\t\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send('pong', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Pong');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!Array.isArray(socketData[0])) {\n\t\t\t\t\t\t// Not an array, invalid message\n\t\t\t\t\t\tconsole.log('Invalid message format, expected array:', socketData);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (let message of socketData) {\n\t\t\t\t\t\t\tawait this.processSocketMessage(ws, message);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS End');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS Close');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', error => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), ws['user'], ws['id_socket'], 'WS Error');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t});\n\n\t\t// Keep alive timer to ping/pong\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any[]) {\n\t\tlet messageRoute = socketData[0];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet messageDate = socketData[1];\n\t\tlet messageId = socketData[2];\n\t\tlet type = socketData[3];\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = socketData[4];\n\t\t\tlet pub = socketData[5];\n\n\t\t\t// Subscribe\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t\t// Unsubscribe\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = socketData[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\tdate_end: null,\n\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\tmethod: method\n\t\t\t\t});\n\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse { //methods\n\t\t\tlet data = [...socketData];\n\t\t\t\n\t\t\tlet messageRoute: string = data.shift();\n\t\t\tlet messageDate: Date = data.shift();\n\t\t\tlet messageId: number = data.shift();\n\t\t\tlet type: string = data.shift();\n\n\t\t\tif (type === 'method') {\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\tdate_end: null,\n\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\tmethod: method\n\t\t\t\t});\n\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else if (type === 'methodResponse') {\n\t\t\t// \tlet method = data.shift();\n\n\t\t\t// \tMethodResponses.findOne({ $and: [{ id_user: ws['id_user'] }, { message_id: messageId }, { method: method }, { date: messageDate }] }).then(\n\t\t\t// \t\tres => {\n\t\t\t// \t\t\tif (res) {\n\t\t\t// \t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t// \t\t\t\t\tthis._websocketManager.send(ws, res.response);\n\t\t\t// \t\t\t\t}\n\t\t\t// \t\t\t}\n\t\t\t// \t\t},\n\t\t\t// \t\terr => {}\n\t\t\t// \t);\n\t\t\t// }\n\t\t}\n\t}\n\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn this._serverConfig;\n\t}\n}"]}
@@ -1,3 +0,0 @@
1
- import { MongoManagerCollection } from '../managers/mongo.manager';
2
- import { WorkerTaskDataChunkModel } from '../models/worker-task-data-chunk.model';
3
- export declare let WorkerTaskDataChunks: MongoManagerCollection<WorkerTaskDataChunkModel>;
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WorkerTaskDataChunks=void 0;var index_1=require("../index"),mongo_manager_1=require("../managers/mongo.manager"),simpl_schema_1=require("simpl-schema"),schema={_id:{type:String,optional:!0},__v:{type:Number,optional:!0},updatedAt:{type:Date,optional:!0},createdAt:{type:Date,optional:!0},id_request:{type:String},data:{type:Array},"data.$":{type:simpl_schema_1.default.oneOf(Object,String,Number,Boolean,Date),blackbox:!0},id_user:{type:String},user:{type:String},id_ws:{type:String}};function initializeCollection(){var e;index_1.ResolveIOServer&&index_1.ResolveIOServer.getMainDB()?(e=new mongo_manager_1.MongoManagerModel({collectionName:"worker-task-data-chunks",schema:schema,useVersionCollection:!1,useReportBuilder:!1,reportBuilderLookupTables:[],timestamps:!0,createLogs:!1,checkSchema:!1,collectionOptions:null}),exports.WorkerTaskDataChunks=e.collection_main,exports.WorkerTaskDataChunks.createIndex({createdAt:1},{expireAfterSeconds:1296e3})):setTimeout(function(){initializeCollection()},0)}exports.WorkerTaskDataChunks=null,initializeCollection();
2
- //# sourceMappingURL=worker-task-data-chunk.collection.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/collections/worker-task-data-chunk.collection.ts"],"names":["index_1","require","mongo_manager_1","simpl_schema_1","schema","_id","type","String","optional","__v","Number","updatedAt","Date","createdAt","id_request","data","Array","data.$","default","oneOf","Object","Boolean","blackbox","id_user","user","id_ws","initializeCollection","model","ResolveIOServer","getMainDB","MongoManagerModel","collectionName","useVersionCollection","useReportBuilder","reportBuilderLookupTables","timestamps","createLogs","checkSchema","collectionOptions","exports","WorkerTaskDataChunks","collection_main","createIndex","expireAfterSeconds","setTimeout"],"mappings":"wGAAA,IAAAA,QAAAC,QAAA,UAAA,EACAC,gBAAAD,QAAA,2BAAA,EACAE,eAAAF,QAAA,cAAA,EAGIG,OAAc,CACjBC,IAAK,CACJC,KAAMC,OACNC,SAAU,CAAA,C,EAEXC,IAAK,CACJH,KAAMI,OACNF,SAAU,CAAA,C,EAEXG,UAAW,CACVL,KAAMM,KACNJ,SAAU,CAAA,C,EAEXK,UAAW,CACVP,KAAMM,KACNJ,SAAU,CAAA,C,EAEXM,WAAY,CACXR,KAAMC,M,EAEPQ,KAAM,CACLT,KAAMU,K,EAEPC,SAAU,CACTX,KAAMH,eAAAe,QAAaC,MAAMC,OAAQb,OAAQG,OAAQW,QAAST,IAAI,EAC9DU,SAAU,CAAA,C,EAEXC,QAAS,CACRjB,KAAMC,M,EAEPiB,KAAM,CACLlB,KAAMC,M,EAEPkB,MAAO,CACNnB,KAAMC,M,GAQR,SAASmB,uBACR,IACOC,EADH3B,QAAA4B,iBAAmB5B,QAAA4B,gBAAgBC,UAAS,GACzCF,EAAQ,IAAIzB,gBAAA4B,kBAA4C,CAC7DC,eAAgB,0BAChB3B,OAAQA,OACR4B,qBAAsB,CAAA,EACtBC,iBAAkB,CAAA,EAClBC,0BAA2B,GAC3BC,WAAY,CAAA,EACZC,WAAY,CAAA,EACZC,YAAa,CAAA,EACbC,kBAAmB,I,CACnB,EACDC,QAAAC,qBAAuBb,EAAMc,gBAC7BF,QAAAC,qBAAqBE,YAAY,CAAC7B,UAAW,CAAC,EAAG,CAAC8B,mBAAoB,MAAiB,CAAC,GAGxFC,WAAW,WACVlB,qBAAoB,CACrB,EAAG,CAAC,CAEN,CAzBWa,QAAAC,qBAAyE,KAEpFd,qBAAoB","file":"worker-task-data-chunk.collection.js","sourcesContent":["import { ResolveIOServer } from '../index';\nimport { MongoManagerCollection, MongoManagerModel } from '../managers/mongo.manager';\nimport SimpleSchema from 'simpl-schema';\nimport { WorkerTaskDataChunkModel } from '../models/worker-task-data-chunk.model';\n\nlet schema: any = {\n\t_id: {\n\t\ttype: String,\n\t\toptional: true\n\t},\n\t__v: {\n\t\ttype: Number,\n\t\toptional: true\n\t},\n\tupdatedAt: {\n\t\ttype: Date,\n\t\toptional: true\n\t},\n\tcreatedAt: {\n\t\ttype: Date,\n\t\toptional: true\n\t},\n\tid_request: {\n\t\ttype: String\n\t},\n\tdata: {\n\t\ttype: Array, // Declaring params as an array\n\t},\n\t'data.$': {\n\t\ttype: SimpleSchema.oneOf(Object, String, Number, Boolean, Date), // Allowing multiple types\n\t\tblackbox: true // Blackbox for the object type\n\t},\n\tid_user: {\n\t\ttype: String\n\t},\n\tuser: {\n\t\ttype: String\n\t},\n\tid_ws: {\n\t\ttype: String\n\t}\n};\n\nexport let WorkerTaskDataChunks: MongoManagerCollection<WorkerTaskDataChunkModel> = null;\n\ninitializeCollection();\n\nfunction initializeCollection() {\n\tif (ResolveIOServer && ResolveIOServer.getMainDB()) {\n\t\tconst model = new MongoManagerModel<WorkerTaskDataChunkModel>({\n\t\t\tcollectionName: 'worker-task-data-chunks',\n\t\t\tschema: schema,\n\t\t\tuseVersionCollection: false,\n\t\t\tuseReportBuilder: false,\n\t\t\treportBuilderLookupTables: [],\n\t\t\ttimestamps: true,\n\t\t\tcreateLogs: false,\n\t\t\tcheckSchema: false,\n\t\t\tcollectionOptions: null\n\t\t});\n\t\tWorkerTaskDataChunks = model.collection_main;\n\t\tWorkerTaskDataChunks.createIndex({createdAt: 1}, {expireAfterSeconds: 60 * 60 * 24 * 15});\n\t}\n\telse {\n\t\tsetTimeout(() => {\n\t\t\tinitializeCollection();\n\t\t}, 0);\n\t}\n}"]}
@@ -1,4 +0,0 @@
1
- import { CollectionDocument } from './collection-document.model';
2
- export interface WorkerTaskDataChunkModel extends CollectionDocument {
3
- data: string;
4
- }
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});
2
- //# sourceMappingURL=worker-task-data-chunk.model.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"worker-task-data-chunk.model.js","sources":["models/worker-task-data-chunk.model.js"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n"],"names":["Object","defineProperty","exports","value"],"mappings":"AAAA,aACAA,OAAOC,eAAeC,QAAS,aAAc,CAAEC,MAAO,CAAA,CAAK,CAAC"}