@resolveio/server-lib 20.4.39 → 20.4.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/collections/flag-update.collection.d.ts +3 -0
- package/collections/flag-update.collection.js +2 -0
- package/collections/flag-update.collection.js.map +1 -0
- package/managers/method.manager.js +1 -1
- package/managers/method.manager.js.map +1 -1
- package/managers/subscription.manager.js +1 -1
- package/managers/subscription.manager.js.map +1 -1
- package/methods/flag-updates.d.ts +2 -0
- package/methods/flag-updates.js +2 -0
- package/methods/flag-updates.js.map +1 -0
- package/models/flag-update.model.d.ts +5 -0
- package/models/flag-update.model.js +2 -0
- package/models/flag-update.model.js.map +1 -0
- package/package.json +1 -1
- package/publications/flags-update.d.ts +2 -0
- package/publications/flags-update.js +2 -0
- package/publications/flags-update.js.map +1 -0
- package/publications/flags.js.map +1 -1
- package/publications.ts +3 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FlagUpdates=void 0;var index_1=require("../index"),mongo_manager_1=require("../managers/mongo.manager"),schema={_id:{type:String,optional:!0},__v:{type:Number,optional:!0},updatedAt:{type:Date,optional:!0},createdAt:{type:Date,optional:!0},type:{type:String},value:{type:Boolean,optional:!0}};function initializeCollection(){var e;index_1.ResolveIOServer&&index_1.ResolveIOServer.getMainDB()?(e=new mongo_manager_1.MongoManagerModel({collectionName:"flag-updates",schema:schema,useVersionCollection:!1,useReportBuilder:!1,reportBuilderLookupTables:[],timestamps:!0,createLogs:!1,checkSchema:!0,collectionOptions:null}),exports.FlagUpdates=e.collection_main,exports.FlagUpdates.createIndex({type:1},{unique:!0})):setTimeout(function(){initializeCollection()},0)}exports.FlagUpdates=null,initializeCollection();
|
|
2
|
+
//# sourceMappingURL=flag-update.collection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/collections/flag-update.collection.ts"],"names":["index_1","require","mongo_manager_1","schema","_id","type","String","optional","__v","Number","updatedAt","Date","createdAt","value","Boolean","initializeCollection","model","ResolveIOServer","getMainDB","MongoManagerModel","collectionName","useVersionCollection","useReportBuilder","reportBuilderLookupTables","timestamps","createLogs","checkSchema","collectionOptions","exports","FlagUpdates","collection_main","createIndex","unique","setTimeout"],"mappings":"+FAAA,IAAAA,QAAAC,QAAA,UAAA,EACAC,gBAAAD,QAAA,2BAAA,EAGIE,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,EAEXF,KAAM,CACLA,KAAMC,M,EAEPO,MAAO,CACNR,KAAMS,QACNP,SAAU,CAAA,C,GAQZ,SAASQ,uBACR,IACOC,EADHhB,QAAAiB,iBAAmBjB,QAAAiB,gBAAgBC,UAAS,GACzCF,EAAQ,IAAId,gBAAAiB,kBAAmC,CACpDC,eAAgB,eAChBjB,OAAQA,OACRkB,qBAAsB,CAAA,EACtBC,iBAAkB,CAAA,EAClBC,0BAA2B,GAC3BC,WAAY,CAAA,EACZC,WAAY,CAAA,EACZC,YAAa,CAAA,EACbC,kBAAmB,I,CACnB,EACDC,QAAAC,YAAcb,EAAMc,gBACpBF,QAAAC,YAAYE,YAAY,CAAC1B,KAAM,CAAC,EAAG,CAAC2B,OAAQ,CAAA,CAAI,CAAC,GAGjDC,WAAW,WACVlB,qBAAoB,CACrB,EAAG,CAAC,CAEN,CAzBWa,QAAAC,YAAuD,KAElEd,qBAAoB","file":"flag-update.collection.js","sourcesContent":["import { ResolveIOServer } from '../index';\nimport { MongoManagerCollection, MongoManagerModel } from '../managers/mongo.manager';\nimport { FlagUpdateModel } from '../models/flag-update.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\ttype: {\n\t\ttype: String\n\t},\n\tvalue: {\n\t\ttype: Boolean,\n\t\toptional: true\n\t}\n};\n\nexport let FlagUpdates: MongoManagerCollection<FlagUpdateModel> = null;\n\ninitializeCollection();\n\nfunction initializeCollection() {\n\tif (ResolveIOServer && ResolveIOServer.getMainDB()) {\n\t\tconst model = new MongoManagerModel<FlagUpdateModel>({\n\t\t\tcollectionName: 'flag-updates',\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: true,\n\t\t\tcollectionOptions: null\n\t\t});\n\t\tFlagUpdates = model.collection_main;\n\t\tFlagUpdates.createIndex({type: 1}, {unique: true});\n\t}\n\telse {\n\t\tsetTimeout(() => {\n\t\t\tinitializeCollection();\n\t\t}, 0);\n\t}\n}"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,i){return new(n=n||Promise)(function(o,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?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){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(o){return function(e){var t=[o,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=n.call(r,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 o="function"==typeof Symbol&&e[Symbol.iterator];if(!o)return e;var r,n,i=o.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(r=i.next()).done;)s.push(r.value)}catch(e){n={error:e}}finally{try{r&&!r.done&&(o=i.return)&&o.call(i)}finally{if(n)throw n.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,i=t.length;n<i;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,o,r,n,i){var s=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!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=o,this._monitorManagerFunction=r,this._isWorkersEnabled=n,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,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)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+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 i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,d,h=null;return 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?(c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),l=(0,mongo_manager_1.objectIdHexString)(),h=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":l}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(c),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:l,method:t,params:o,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),h=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(o),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(d),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),h}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,i,s,a){for(var c,e,l,d,t=this,h=[],o=5;o<arguments.length;o++)h[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<h.length||h[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),u={messageId:s,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,i,a,h,u);for(var u,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),m=0;m<h.length;m++)_[g[m]]=h[m];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}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?(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),e=(0,mongo_manager_1.objectIdHexString)(),(l=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==o.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(c),t=o.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,h,t),r?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:l.close(),e.label=3;case 3:return[2]}})})}),l.on("error",function(e){console.error("Error watching worker responses:",e),l.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:h,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],__read(h),!1)).then(function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(d),t={messageId:s,hasError:!1,data:o},this.sendWS(n,i,a,h,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(d),t.sendWS(n,i,a,h,{messageId:s,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"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(h,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),u={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,h,u),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,a,c="function"==typeof o[o.length-1]?o.slice(0,-1):o,l=null;return 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?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),s=(0,mongo_manager_1.objectIdHexString)(),l=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:c,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(a=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),l=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(c),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(a),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(a),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),o[o.length-1]&&"function"==typeof o[o.length-1]&&l.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==o&&"reportBuilderGetDistinctValue"!==o&&"reportBuilderBuildTree"!==o&&"generatePDF"!==o&&"getWOOfflineData"!==o&&"countQuery"!==o&&"countWithQuery"!==o&&"countCollectionWithQuery"!==o&&"find"!==o&&"findOne"!==o&&"findWithOptions"!==o&&"uploadFileAndSave"!==o&&"getDrivers"!==o&&"processAirdropDistribution"!==o&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r,n]))<2e5?JSON.stringify([r,n],null,2):"Too Big",method:o,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""})},MethodManager.prototype.sendEmail=function(r,n,i,s,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:i,html:s,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,i,s,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
|
|
1
|
+
"use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,i){return new(n=n||Promise)(function(o,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?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){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(o){return function(e){var t=[o,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=n.call(r,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 o="function"==typeof Symbol&&e[Symbol.iterator];if(!o)return e;var r,n,i=o.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(r=i.next()).done;)s.push(r.value)}catch(e){n={error:e}}finally{try{r&&!r.done&&(o=i.return)&&o.call(i)}finally{if(n)throw n.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,i=t.length;n<i;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),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,o,r,n,i){var s=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!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=o,this._monitorManagerFunction=r,this._isWorkersEnabled=n,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)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+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 i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,d,h=null;return 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?(c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),l=(0,mongo_manager_1.objectIdHexString)(),h=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":l}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(c),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:l,method:t,params:o,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),h=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(o),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(d),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),h}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,i,s,a){for(var c,e,l,d,t=this,h=[],o=5;o<arguments.length;o++)h[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<h.length||h[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),u={messageId:s,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,i,a,h,u);for(var u,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),m=0;m<h.length;m++)_[g[m]]=h[m];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}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?(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),e=(0,mongo_manager_1.objectIdHexString)(),(l=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==o.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(c),t=o.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,h,t),r?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:l.close(),e.label=3;case 3:return[2]}})})}),l.on("error",function(e){console.error("Error watching worker responses:",e),l.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:h,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],__read(h),!1)).then(function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(d),t={messageId:s,hasError:!1,data:o},this.sendWS(n,i,a,h,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(d),t.sendWS(n,i,a,h,{messageId:s,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"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(h,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),u={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,h,u),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,a,c="function"==typeof o[o.length-1]?o.slice(0,-1):o,l=null;return 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?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),s=(0,mongo_manager_1.objectIdHexString)(),l=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:c,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(a=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),l=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(c),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(a),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(a),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),o[o.length-1]&&"function"==typeof o[o.length-1]&&l.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==o&&"reportBuilderGetDistinctValue"!==o&&"reportBuilderBuildTree"!==o&&"generatePDF"!==o&&"getWOOfflineData"!==o&&"countQuery"!==o&&"countWithQuery"!==o&&"countCollectionWithQuery"!==o&&"find"!==o&&"findOne"!==o&&"findWithOptions"!==o&&"uploadFileAndSave"!==o&&"getDrivers"!==o&&"processAirdropDistribution"!==o&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r,n]))<2e5?JSON.stringify([r,n],null,2):"Too Big",method:o,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""})},MethodManager.prototype.sendEmail=function(r,n,i,s,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:i,html:s,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,i,s,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
|
|
2
2
|
//# sourceMappingURL=method.manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_isWorkersEnabled","_isWorkerInstance","_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","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","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","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","monitor_4","taskId","changeStream_1","monitor_5","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__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","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","__v","date","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"y9DACAA,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,EAEAc,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,EAIA0B,IAAA,WAKC,SAAAA,IAAYC,GAJJC,KAAAC,cAAgB,KAChBD,KAAAE,IAAU,KACVF,KAAAG,WAAiB,KAGxBH,KAAKC,cAAgBF,CACtB,CAwCD,OAtCQD,IAAAM,UAAAC,GAAP,WAcC,OAbIL,KAAKE,MAITF,KAAKE,IAAM,IAAIP,YAAAW,GAAG,CACjBC,YAAa,CACZC,YAAaC,QAAQC,IAAIC,eACzBC,gBAAiBH,QAAQC,IAAIG,qB,EAE9BC,OAAQL,QAAQC,IAAIK,WACpBC,WAAY,Y,CACZ,GAEMhB,KAAKE,GACb,EAEOJ,IAAAM,UAAAa,UAAP,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J,CAAC,CACF,EAEOvH,cAAAd,UAAA4M,UAAP,SAAiBJ,GAAjB,IAAAnL,EAAAzB,KACC,OAAO,IAAI0G,QAAQ,SAACC,EAASC,GACxBlI,GAAGmO,WAAWpO,KAAKqO,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjElO,GAAGiO,SAASlO,KAAKqO,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAACzC,EAAK1B,GACzE0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,EAGG/J,GAAGmO,WAAWpO,KAAKqO,KAAKrL,EAAKJ,UAAY,aAAeuL,CAAS,CAAC,GACrElO,GAAGiO,SAASlO,KAAKqO,KAAKrL,EAAKJ,UAAY,aAAeuL,CAAS,EAAG,SAAU,SAACzC,EAAK1B,GAC7E0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDvH,aAAA,EAAC,GA9tBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { MethodResponses } from '../collections/method-response.collection';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WorkerTaskRequests } from '../collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from '../collections/worker-task-response.collection';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\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 _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\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\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\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\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\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\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\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \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\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\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\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\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\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', error => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\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\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method: 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\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\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","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","_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","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","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","monitor_4","taskId","changeStream_1","monitor_5","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__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","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","__v","date","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"y9DACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,M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O,SAASpO,KAAKuO,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAACzC,EAAK1B,GACzE0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,EAGGjK,GAAGqO,WAAWtO,KAAKuO,KAAKtL,EAAKJ,UAAY,aAAewL,CAAS,CAAC,GACrEpO,GAAGmO,SAASpO,KAAKuO,KAAKtL,EAAKJ,UAAY,aAAewL,CAAS,EAAG,SAAU,SAACzC,EAAK1B,GAC7E0B,EACHvD,EAAOuD,CAAG,EAGVxD,EAAQ8B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDxH,aAAA,EAAC,GA/tBYC,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';\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 _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\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\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\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\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\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\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \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\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\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\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\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\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', error => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\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\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method: 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\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\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __awaiter=this&&this.__awaiter||function(e,n,o,r){return new(o=o||Promise)(function(i,t){function fulfilled(e){try{step(r.next(e))}catch(e){t(e)}}function rejected(e){try{step(r.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?i(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((r=r.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var r,s,a,u={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(i){return function(e){var t=[i,e];if(r)throw new TypeError("Generator is already executing.");for(;u=c&&t[c=0]?0:u;)try{if(r=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 u.label++,{value:t[1],done:!1};case 5:u.label++,s=t[1],t=[0];continue;case 7:t=u.ops.pop(),u.trys.pop();continue;default:if(!(a=0<(a=u.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){u=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))u.label=t[1];else if(6===t[0]&&u.label<a[1])u.label=a[1],a=t;else{if(!(a&&u.label<a[2])){a[2]&&u.ops.pop(),u.trys.pop();continue}u.label=a[2],u.ops.push(t)}}t=o.call(n,u)}catch(e){t=[6,e],s=0}finally{r=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.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.")},__read=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,o,r=i.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(n=r.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(o)throw o.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,o=0,r=t.length;o<r;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))},logs_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0,require("../publications/logs")),app_status_1=require("../publications/app-status"),files_1=require("../publications/files"),super_admin_1=require("../publications/super-admin"),logged_in_users_collection_1=require("../collections/logged-in-users.collection"),cron_jobs_1=require("../publications/cron-jobs"),flags_1=require("../publications/flags"),method_responses_1=require("../publications/method-responses"),index_1=require("../index"),notifications_1=require("../publications/notifications"),report_builder_reports_1=require("../publications/report-builder-reports"),report_builder_libraries_1=require("../publications/report-builder-libraries"),user_groups_1=require("../publications/user-groups"),user_guides_1=require("../publications/user-guides"),report_builder_dashboard_builders_1=require("../publications/report-builder-dashboard-builders"),mongo_manager_1=require("./mongo.manager"),common_1=require("../util/common"),NodeCache=require("node-cache"),flag_collection_1=require("../collections/flag.collection"),os_1=require("os"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(e,t,i,n){var o=this;this._publications={},this._subscriptions=[],this._loggedInUsers=[],this._mongoQueue=[],this._mongoQueueId=0,this._cacheId=1,this._heapSize=v8.getHeapStatistics()/numCPUs,this._enableDebug=!1,this._debugOplogCollections=[],this._debugOplogHits=0,this._debugSubCollections=[],this._debugSubHits=0,this._debugUnSubHits=0,this._debugUnSubAllHits=0,this._debugMongoQueueHits=0,this._debugMongoQueueCollections=[],this._debugSendQueueHits=0,this._debugRemoveCacheHits=0,this._oplogRetryCount=0,this.latencyBuffer=new Map,this.LATENCY_UPDATE_INTERVAL=6e4,this.LATENCY_UPDATE_THRESHOLD_MS=3e4,this._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this._monitorManagerFunction=n,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),setInterval(function(){return o.flushThrottledLatencyUpdates()},this.LATENCY_UPDATE_INTERVAL),this.serverConfig=i,this._wss=t,(0,super_admin_1.loadSuperAdminPublications)(this),(0,app_status_1.loadAppStatusPublications)(this),(0,logs_1.loadLogPublications)(this),(0,files_1.loadFilePublications)(this),(0,cron_jobs_1.loadCronJobPublications)(this),(0,flags_1.loadFlagsPublications)(this),(0,method_responses_1.loadMethodResponsePublications)(this),(0,notifications_1.loadNotificationPublications)(this),(0,report_builder_reports_1.loadReportBuilderReportPublications)(this),(0,report_builder_libraries_1.loadReportBuilderLibraryPublications)(this),(0,user_groups_1.loadUserGroupPublications)(this),(0,user_guides_1.loadUserGuidePublications)(this),(0,report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this),this.tailOpLog(),setInterval(function(){o._oplogRetryCount=0},15e3),setInterval(function(){o.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",o._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",o._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",o._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",o._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(o._debugMongoQueueCollections.sort(function(e,t){return e.collection.localeCompare(t.collection)||e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Oplog Hits",o._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(o._debugOplogCollections.sort(function(e,t){return e.collection.localeCompare(t.collection)||e.type.localeCompare(t.type)}),null,2)),console.log(new Date,"Sub Manager","Send Queue Hits",o._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",o._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(o._debugSubCollections.sort(function(e,t){return e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",o._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",o._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",o._debugRemoveCacheHits)),o._debugOplogHits=0,o._debugOplogCollections=[],o._debugSubCollections=[],o._debugMongoQueueHits=0,o._debugMongoQueueCollections=[],o._debugSendQueueHits=0,o._debugSubHits=0,o._debugUnSubHits=0,o._debugUnSubAllHits=0,o._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(o,void 0,void 0,function(){var t,n,i,o,r,s,a,u,c;return __generator(this,function(e){switch(e.label){case 0:return t=this,[4,logged_in_users_collection_1.LoggedInUsers.find()];case 1:for(t._loggedInUsers=e.sent(),n=(0,common_1.deepCopy)(this._loggedInUsers),i=function(e){var i=n[e];(!i.date||12e4<Date.now()-i.date.getTime())&&(o._websocketManager.getWebSocket(i.id_ws)?(o.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",o._websocketManager.getWebSocket(i.id_ws).user,o._websocketManager.getWebSocket(i.id_ws).id_socket,2),o.unsubscribeAll(o._websocketManager.getWebSocket(i.id_ws))):(o._subscriptions.forEach(function(e){for(var t=e.clients.length-1;0<=t;t--)e.clients[t].id_socket===i.id_ws&&e.clients.splice(t,1)}),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:i._id}),0<=o._loggedInUsers.findIndex(function(e){return e._id===i._id})&&o._loggedInUsers.splice(o._loggedInUsers.findIndex(function(e){return e._id===i._id}),1)))},r=(o=this)._loggedInUsers.length-1;0<=r;r--)i(r);for(r=0;r<this._subscriptions.length;r++)for(s=this._subscriptions[r],a=function(e){var t=s.clients[e];u._loggedInUsers.some(function(e){return e.id_ws===t.id_socket})||s.clients.splice(e,1)},u=this,c=s.clients.length-1;0<=c;c--)a(c);return[2]}})})},3e4),flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?o._enableDebug=!0:o._enableDebug=!1}),this.setCacheLimit()}return SubscriptionManager.prototype.setCacheLimit=function(){"true"===process.env.IS_WORKERS_ENABLED?this._heapLimit=.4*this._heapSize:this._heapLimit=.3*this._heapSize},SubscriptionManager.prototype.invalidatePubsCache=function(l,g){return __awaiter(this,void 0,void 0,function(){var t,i,o,n,r,s,a,u,c=this;return __generator(this,function(e){index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l),t=this._subscriptions.filter(function(e){return e.collections.includes(l)}),i=function(n){if(n.running)return n.runAgain=!0,"continue";o._publications[n.publication].user_specific?Promise.all(n.clients.map(function(i){return __awaiter(c,void 0,void 0,function(){var t;return __generator(this,function(e){if((t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN)try{this.sendDataToOneWithRetry(t,i.messageId,n,l,g)}catch(e){this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - User Specific - Socket: "+i.id_socket+", User: "+i.id_user+", MessageId: "+i.messageId+", Pub: "+n.publication+", Err: "+JSON.stringify(e,null,2))}return[2]})})})):o.sendDataToAllWithRetry(n,l,g)},o=this;try{for(n=__values(t),r=n.next();!r.done;r=n.next())s=r.value,i(s)}catch(e){a={error:e}}finally{try{r&&!r.done&&(u=n.return)&&u.call(n)}finally{if(a)throw a.error}}return[2]})})},SubscriptionManager.prototype.delay=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){return setTimeout(e,t)})]})})},SubscriptionManager.prototype.sendDataToAllWithRetry=function(t,i,n){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:t.running=!0,e.label=1;case 1:return t.runAgain=!1,[4,this.sendDataToAll(t,i,n)];case 2:return(e.sent(),t.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(t.runAgain)return[3,1];e.label=5;case 5:return t.running=!1,[2]}})})},SubscriptionManager.prototype.sendDataToOneWithRetry=function(t,i,n,o,r){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:n.running=!0,e.label=1;case 1:return n.runAgain=!1,[4,this.sendDataToOne(t,i,n,o,r)];case 2:return(e.sent(),n.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(n.runAgain)return[3,1];e.label=5;case 5:return n.running=!1,[2]}})})},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(t){var e,i,n,o=this._loggedInUsers.find(function(e){return e.id_ws===t.id_socket});o&&(e=new Date,i=this.latencyBuffer.get(t.id_socket),n=t.latency,!i||e.getTime()-i.lastUpdate.getTime()>=this.LATENCY_UPDATE_THRESHOLD_MS||100<Math.abs(n-i.latency))&&(o.date=e,this.latencyBuffer.set(t.id_socket,{latency:n,lastUpdate:e}))},SubscriptionManager.prototype.flushThrottledLatencyUpdates=function(){return __awaiter(this,void 0,void 0,function(){var t,i;return __generator(this,function(e){switch(e.label){case 0:if(0===this.latencyBuffer.size)return[2];t=Array.from(this.latencyBuffer.entries()).map(function(e){var e=__read(e,2),t=e[0],e=e[1];return{updateOne:{filter:{id_ws:t},update:{$set:{latency:e.latency,date:e.lastUpdate}}}}}),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,logged_in_users_collection_1.LoggedInUsers.bulkWrite(t)];case 2:return e.sent(),this.latencyBuffer.clear(),this.getEnableDebug()&&console.log(new Date,"Sub Manager","Throttled latency batch update successful",t.length),[3,4];case 3:return i=e.sent(),console.error(new Date,"Sub Manager","Throttled latency batch update failed",i),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.subscribe=function(t,e,i,n,o,r){var s=this,a=(this._debugSubHits+=1,this._debugSubCollections.some(function(e){return e.publication===o})?this._debugSubCollections.find(function(e){return e.publication===o}).hits+=1:this._debugSubCollections.push({publication:o,hits:1}),this._publications[o]);if(a){if(1<r.length||r[0]){if(!a.check)return void console.error(new Date,"No Check Function For Pub "+o);if(!a.check._schema)return void console.error(new Date,"No Check Schema For Pub "+o);for(var u={},c=Object.keys(a.check._schema).filter(function(e){return!e.includes(".")}),l=0;l<r.length;l++)u[c[l]]=r[l];try{a.check.validate(u)}catch(e){if(e)return void console.error(new Date,"Error in Pub Check ("+o+")",e)}}"Bypass"!==t&&(a=t.split("/"),g="",d=a[0],""===a[0]&&(g="/",d=a[1]),g+=d,1<a.length&&(g+="/"),(d=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===i.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==t&&!e.messageRoute.startsWith(g)})})).length)&&(this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Detected Undestroyed Subscription - "+this.serverConfig.CLIENT_NAME,"USER: "+i.user+" (Socket: "+i.id_socket+") is on route: "+t+" but has the following subscriptions on other routes:"+JSON.stringify(d,null,2)),d.forEach(function(t){t.clients.filter(function(e){return e.id_socket===i.id_socket}).forEach(function(e){s.unsubscribe(e.messageRoute,new Date,i,e.messageId,t.publication,t.subscriptionData)})}));var g,d,a=this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(r)});a?a.clients.some(function(e){return e.id_socket===i.id_socket&&e.messageId===n})||a.clients.push({id_user:i.id_user,messageId:n,id_socket:i.id_socket,messageRoute:t}):this._subscriptions.push({publication:o,subscriptionData:r,collections:this.getPublicationCollections(o),clients:[{id_user:i.id_user,messageId:n,id_socket:i.id_socket,messageRoute:t}],cacheId:0,running:!1,runAgain:!1}),a=a||this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(r)}),this.processSubscription(a,i,n)}else console.error(new Date,"No Publication: "+o)},SubscriptionManager.prototype.createLoggedInUser=function(n){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return[2,new Promise(function(i,e){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n))?(t={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:t.id_user,user:t.user,id_ws:t.id_socket},this._loggedInUsers.push(t),logged_in_users_collection_1.LoggedInUsers.insertOne(t),i(t)):i(null),[2]})})})]})})},SubscriptionManager.prototype.unsubscribe=function(e,t,i,n,o,r){if(this._debugUnSubHits+=1,this._publications[o]){var s=this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(r)});if(s)for(var a=s.clients.length-1;0<=a;a--)s.clients[a].id_user===i.id_user&&s.clients[a].messageId===n&&s.clients[a].id_socket===i.id_socket&&s.clients.splice(a,1)}else console.log("No Publication: "+o)},SubscriptionManager.prototype.unsubscribeAll=function(r){return __awaiter(this,void 0,void 0,function(){var t,i,n,o;return __generator(this,function(e){if(this._debugUnSubAllHits+=1,r){if(r.isUnsubscribed)return[2];for(r.isUnsubscribed=!0,0<=this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(r.id_socket)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(r.id_socket),1),logged_in_users_collection_1.LoggedInUsers.deleteOne({id_ws:r.id_socket}),t=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_user===r.id_user&&e.id_socket===r.id_socket})}),i=t.length-1;0<=i;i--)for(n=t[i],o=n.clients.length-1;0<=o;o--)n.clients[o].id_socket===r.id_socket&&n.clients.splice(o,1);this._websocketManager.removeWebSocket(r)}return[2]})})},SubscriptionManager.prototype.getActiveSubscriptions=function(){return this._subscriptions},SubscriptionManager.prototype.getPublicationCollections=function(e){return this._publications[e].collections},SubscriptionManager.prototype.tailOpLog=function(t){return __awaiter(this,void 0,void 0,function(){var i,n=this;return __generator(this,function(e){switch(e.label){case 0:return this._oplog$&&!this._oplog$.closed&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:if(e.sent(),!this._oplog$||this._oplog$.closed){if(this._oplogRetryCount+=1,5<this._oplogRetryCount&&(console.error("****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************"),process.exit(1)),t){i=t;try{this._oplog$=index_1.ResolveIOServer.getMainDB().watch([],{resumeAfter:t})}catch(e){return this._oplog$&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),this.tailOpLog(t),[2]}}else this._oplog$=index_1.ResolveIOServer.getMainDB().watch();console.log(new Date,"oplog started"),this._oplog$.on("change",function(t){var e;t.ns&&(e=t.ns.coll,n._debugOplogCollections.some(function(e){return e.collection===t.ns.coll&&e.type===t.operationType})?n._debugOplogCollections.find(function(e){return e.collection===t.ns.coll&&e.type===t.operationType}).hits+=1:n._debugOplogCollections.push({collection:t.ns.coll,type:t.operationType,hits:1}),!e||e.endsWith(".versions")||e.startsWith("monitor-")||"logs"===e||"log-method-latencies"===e||"log-subscriptions"===e||(n._debugOplogHits+=1,"insert"===t.operationType?("support-tickets"===e&&"https://resolveio.com"===n.serverConfig.ROOT_URL&&(n._mainServer.getMethodManager().callMethodInternal.call(n._mainServer.getMethodManager(),"sendSupportTicketEmail",t.documentKey._id),n.invalidatePubsCache(e,"insert")),"method-responses"!==e&&n.invalidatePubsCache(e,"insert")):"update"===t.operationType||"replace"===t.operationType?"method-responses"!==e&&n.invalidatePubsCache(e,"update"):"delete"===t.operationType&&"method-responses"!==e&&n.invalidatePubsCache(e,"delete")),"flags"===e&&flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?n._enableDebug=!0:n._enableDebug=!1}),i=t._id)}),this._oplog$.on("error",function(e){console.log(new Date,"oplog error",e),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(i)}),this._oplog$.on("end",function(){console.log(new Date,"oplog end"),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(i)}),this._oplog$.on("close",function(){console.log(new Date,"oplog close"),n._oplog$.removeAllListeners(),n._oplog$=null,n.tailOpLog(i)})}return[2]}})})},SubscriptionManager.prototype.processSubscription=function(n,o,r){return __awaiter(this,void 0,void 0,function(){var t,i;return __generator(this,function(e){if(this._publications[n.publication].user_specific){if(n.running)return[2];this.sendDataToOneWithRetry(o,r,n,"","newSub")}else if(n.cacheId)try{t=JSON.parse(this._nodeCache.get(n.cacheId),common_1.dateReviver),i={messageId:r,hasError:!1,data:t},this.sendWS(o,i)}catch(e){this._nodeCache.del(n.cacheId),n.cacheId=0,this.sendDataToAllWithRetry(n,"","newSub")}else{if(n.running)return[2];this.sendDataToAllWithRetry(n,"","newSub")}return[2]})})},SubscriptionManager.prototype.sendDataToOne=function(r,s,a,u,c){return __awaiter(this,void 0,void 0,function(){var t,i,n,o;return __generator(this,function(e){switch(e.label){case 0:t=this._monitorManagerFunction.startMonitorFunction("User Specific Publication",a.publication,"","",a.subscriptionData),e.label=1;case 1:return e.trys.push([1,3,,4]),this._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(),"insertSubscriptionLog",c,a.publication,u,JSON.stringify(a.subscriptionData)),[4,(o=this._publications[a.publication].function).call.apply(o,__spreadArray([Object.assign({},this,SubscriptionManager.prototype),r.id_user],__read(a.subscriptionData),!1))];case 2:return o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),n={messageId:s,hasError:!1,data:o},this.sendWS(r,n),[3,4];case 3:return i=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),n={messageId:s,hasError:!0,data:i},this.sendWS(r,n),this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+a.publication+" - (sendDataToOne - WS)\n\nData \n"+JSON.stringify(a.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(i,null,2)),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.sendDataToAll=function(g,d,_){return __awaiter(this,void 0,void 0,function(){var t,o,i,n,r,s,a,u,c,l=this;return __generator(this,function(e){switch(e.label){case 0:return g.clients.length?[3,1]:(g.cacheId&&(this._nodeCache.del(g.cacheId),g.cacheId=0),0<=(c=this._subscriptions.findIndex(function(e){return e.publication===g.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(g.subscriptionData)}))&&this._subscriptions.splice(c,1),[2]);case 1:t=this._monitorManagerFunction.startMonitorFunction("Publication",g.publication,"","",g.subscriptionData),e.label=2;case 2:return e.trys.push([2,4,,5]),"superadminAPM"!==g.publication&&"loggedInUsers"!==g.publication&&this._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(),"insertSubscriptionLog",_,g.publication,d,JSON.stringify(g.subscriptionData)),[4,(c=this._publications[g.publication].function).call.apply(c,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],__read(g.subscriptionData),!1))];case 3:if(o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),g.cacheId)try{i=JSON.parse(this._nodeCache.get(g.cacheId),common_1.dateReviver),JSON.stringify(i)!==JSON.stringify(o)&&(Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),this._nodeCache.del(g.cacheId),g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o)))}catch(e){Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),this._nodeCache.del(g.cacheId),g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o))}else if(Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o)),(n=this._nodeCache.getStats().vsize)>this._heapLimit){for(r=0,s=this._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),a=0;a<s.length&&(this._debugRemoveCacheHits+=1,this._nodeCache.del(s[a].cacheId),s[a].cacheId=0,r+=1,!(this._nodeCache.getStats().vsize<.75*this._heapLimit));a++);this._enableDebug&&console.log("Sub Cache: Too Big - "+g.publication+" - Deleted: "+r+" - "+n)}return[3,5];case 4:return u=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!0,data:u},this.sendWS(t,i)),[2]})})})),this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+g.publication+" - (sendPubData)\n\nData \n"+JSON.stringify(g.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(u,null,2)),[3,5];case 5:return[2]}})})},SubscriptionManager.prototype.sendWS=function(e,t){this._websocketManager.send(e,t)},SubscriptionManager.prototype.getEnableDebug=function(){return this._enableDebug},SubscriptionManager}();exports.SubscriptionManager=SubscriptionManager;
|
|
1
|
+
"use strict";var __awaiter=this&&this.__awaiter||function(e,n,o,s){return new(o=o||Promise)(function(i,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?i(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var s,r,a,u={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(i){return function(e){var t=[i,e];if(s)throw new TypeError("Generator is already executing.");for(;u=c&&t[c=0]?0:u;)try{if(s=1,r&&(a=2&t[0]?r.return:t[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,t[1])).done)return a;switch(r=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return u.label++,{value:t[1],done:!1};case 5:u.label++,r=t[1],t=[0];continue;case 7:t=u.ops.pop(),u.trys.pop();continue;default:if(!(a=0<(a=u.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){u=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))u.label=t[1];else if(6===t[0]&&u.label<a[1])u.label=a[1],a=t;else{if(!(a&&u.label<a[2])){a[2]&&u.ops.pop(),u.trys.pop();continue}u.label=a[2],u.ops.push(t)}}t=o.call(n,u)}catch(e){t=[6,e],r=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.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.")},__read=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,o,s=i.call(e),r=[];try{for(;(void 0===t||0<t--)&&!(n=s.next()).done;)r.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}return r},__spreadArray=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,o=0,s=t.length;o<s;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))},logs_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0,require("../publications/logs")),app_status_1=require("../publications/app-status"),files_1=require("../publications/files"),super_admin_1=require("../publications/super-admin"),logged_in_users_collection_1=require("../collections/logged-in-users.collection"),cron_jobs_1=require("../publications/cron-jobs"),flags_1=require("../publications/flags"),method_responses_1=require("../publications/method-responses"),index_1=require("../index"),notifications_1=require("../publications/notifications"),report_builder_reports_1=require("../publications/report-builder-reports"),report_builder_libraries_1=require("../publications/report-builder-libraries"),user_groups_1=require("../publications/user-groups"),user_guides_1=require("../publications/user-guides"),report_builder_dashboard_builders_1=require("../publications/report-builder-dashboard-builders"),mongo_manager_1=require("./mongo.manager"),common_1=require("../util/common"),NodeCache=require("node-cache"),flag_collection_1=require("../collections/flag.collection"),os_1=require("os"),flags_update_1=require("../publications/flags-update"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(e,t,i,n){var o=this;this._publications={},this._subscriptions=[],this._loggedInUsers=[],this._mongoQueue=[],this._mongoQueueId=0,this._cacheId=1,this._heapSize=v8.getHeapStatistics()/numCPUs,this._enableDebug=!1,this._debugOplogCollections=[],this._debugOplogHits=0,this._debugSubCollections=[],this._debugSubHits=0,this._debugUnSubHits=0,this._debugUnSubAllHits=0,this._debugMongoQueueHits=0,this._debugMongoQueueCollections=[],this._debugSendQueueHits=0,this._debugRemoveCacheHits=0,this._oplogRetryCount=0,this.latencyBuffer=new Map,this.LATENCY_UPDATE_INTERVAL=6e4,this.LATENCY_UPDATE_THRESHOLD_MS=3e4,this._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this._monitorManagerFunction=n,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),setInterval(function(){return o.flushThrottledLatencyUpdates()},this.LATENCY_UPDATE_INTERVAL),this.serverConfig=i,this._wss=t,(0,super_admin_1.loadSuperAdminPublications)(this),(0,app_status_1.loadAppStatusPublications)(this),(0,logs_1.loadLogPublications)(this),(0,files_1.loadFilePublications)(this),(0,cron_jobs_1.loadCronJobPublications)(this),(0,flags_update_1.loadFlagsUpdatePublications)(this),(0,flags_1.loadFlagsPublications)(this),(0,method_responses_1.loadMethodResponsePublications)(this),(0,notifications_1.loadNotificationPublications)(this),(0,report_builder_reports_1.loadReportBuilderReportPublications)(this),(0,report_builder_libraries_1.loadReportBuilderLibraryPublications)(this),(0,user_groups_1.loadUserGroupPublications)(this),(0,user_guides_1.loadUserGuidePublications)(this),(0,report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this),this.tailOpLog(),setInterval(function(){o._oplogRetryCount=0},15e3),setInterval(function(){o.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",o._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",o._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",o._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",o._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(o._debugMongoQueueCollections.sort(function(e,t){return e.collection.localeCompare(t.collection)||e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Oplog Hits",o._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(o._debugOplogCollections.sort(function(e,t){return e.collection.localeCompare(t.collection)||e.type.localeCompare(t.type)}),null,2)),console.log(new Date,"Sub Manager","Send Queue Hits",o._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",o._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(o._debugSubCollections.sort(function(e,t){return e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",o._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",o._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",o._debugRemoveCacheHits)),o._debugOplogHits=0,o._debugOplogCollections=[],o._debugSubCollections=[],o._debugMongoQueueHits=0,o._debugMongoQueueCollections=[],o._debugSendQueueHits=0,o._debugSubHits=0,o._debugUnSubHits=0,o._debugUnSubAllHits=0,o._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(o,void 0,void 0,function(){var t,n,i,o,s,r,a,u,c;return __generator(this,function(e){switch(e.label){case 0:return t=this,[4,logged_in_users_collection_1.LoggedInUsers.find()];case 1:for(t._loggedInUsers=e.sent(),n=(0,common_1.deepCopy)(this._loggedInUsers),i=function(e){var i=n[e];(!i.date||12e4<Date.now()-i.date.getTime())&&(o._websocketManager.getWebSocket(i.id_ws)?(o.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",o._websocketManager.getWebSocket(i.id_ws).user,o._websocketManager.getWebSocket(i.id_ws).id_socket,2),o.unsubscribeAll(o._websocketManager.getWebSocket(i.id_ws))):(o._subscriptions.forEach(function(e){for(var t=e.clients.length-1;0<=t;t--)e.clients[t].id_socket===i.id_ws&&e.clients.splice(t,1)}),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:i._id}),0<=o._loggedInUsers.findIndex(function(e){return e._id===i._id})&&o._loggedInUsers.splice(o._loggedInUsers.findIndex(function(e){return e._id===i._id}),1)))},s=(o=this)._loggedInUsers.length-1;0<=s;s--)i(s);for(s=0;s<this._subscriptions.length;s++)for(r=this._subscriptions[s],a=function(e){var t=r.clients[e];u._loggedInUsers.some(function(e){return e.id_ws===t.id_socket})||r.clients.splice(e,1)},u=this,c=r.clients.length-1;0<=c;c--)a(c);return[2]}})})},3e4),flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?o._enableDebug=!0:o._enableDebug=!1}),this.setCacheLimit()}return SubscriptionManager.prototype.setCacheLimit=function(){"true"===process.env.IS_WORKERS_ENABLED?this._heapLimit=.4*this._heapSize:this._heapLimit=.3*this._heapSize},SubscriptionManager.prototype.invalidatePubsCache=function(l,g){return __awaiter(this,void 0,void 0,function(){var t,i,o,n,s,r,a,u,c=this;return __generator(this,function(e){index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l),t=this._subscriptions.filter(function(e){return e.collections.includes(l)}),i=function(n){if(n.running)return n.runAgain=!0,"continue";o._publications[n.publication].user_specific?Promise.all(n.clients.map(function(i){return __awaiter(c,void 0,void 0,function(){var t;return __generator(this,function(e){if((t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN)try{this.sendDataToOneWithRetry(t,i.messageId,n,l,g)}catch(e){this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - User Specific - Socket: "+i.id_socket+", User: "+i.id_user+", MessageId: "+i.messageId+", Pub: "+n.publication+", Err: "+JSON.stringify(e,null,2))}return[2]})})})):o.sendDataToAllWithRetry(n,l,g)},o=this;try{for(n=__values(t),s=n.next();!s.done;s=n.next())r=s.value,i(r)}catch(e){a={error:e}}finally{try{s&&!s.done&&(u=n.return)&&u.call(n)}finally{if(a)throw a.error}}return[2]})})},SubscriptionManager.prototype.delay=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){return setTimeout(e,t)})]})})},SubscriptionManager.prototype.sendDataToAllWithRetry=function(t,i,n){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:t.running=!0,e.label=1;case 1:return t.runAgain=!1,[4,this.sendDataToAll(t,i,n)];case 2:return(e.sent(),t.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(t.runAgain)return[3,1];e.label=5;case 5:return t.running=!1,[2]}})})},SubscriptionManager.prototype.sendDataToOneWithRetry=function(t,i,n,o,s){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:n.running=!0,e.label=1;case 1:return n.runAgain=!1,[4,this.sendDataToOne(t,i,n,o,s)];case 2:return(e.sent(),n.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(n.runAgain)return[3,1];e.label=5;case 5:return n.running=!1,[2]}})})},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(t){var e,i,n,o=this._loggedInUsers.find(function(e){return e.id_ws===t.id_socket});o&&(e=new Date,i=this.latencyBuffer.get(t.id_socket),n=t.latency,!i||e.getTime()-i.lastUpdate.getTime()>=this.LATENCY_UPDATE_THRESHOLD_MS||100<Math.abs(n-i.latency))&&(o.date=e,this.latencyBuffer.set(t.id_socket,{latency:n,lastUpdate:e}))},SubscriptionManager.prototype.flushThrottledLatencyUpdates=function(){return __awaiter(this,void 0,void 0,function(){var t,i;return __generator(this,function(e){switch(e.label){case 0:if(0===this.latencyBuffer.size)return[2];t=Array.from(this.latencyBuffer.entries()).map(function(e){var e=__read(e,2),t=e[0],e=e[1];return{updateOne:{filter:{id_ws:t},update:{$set:{latency:e.latency,date:e.lastUpdate}}}}}),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,logged_in_users_collection_1.LoggedInUsers.bulkWrite(t)];case 2:return e.sent(),this.latencyBuffer.clear(),this.getEnableDebug()&&console.log(new Date,"Sub Manager","Throttled latency batch update successful",t.length),[3,4];case 3:return i=e.sent(),console.error(new Date,"Sub Manager","Throttled latency batch update failed",i),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.subscribe=function(t,e,i,n,o,s){var r=this,a=(this._debugSubHits+=1,this._debugSubCollections.some(function(e){return e.publication===o})?this._debugSubCollections.find(function(e){return e.publication===o}).hits+=1:this._debugSubCollections.push({publication:o,hits:1}),this._publications[o]);if(a){if(1<s.length||s[0]){if(!a.check)return void console.error(new Date,"No Check Function For Pub "+o);if(!a.check._schema)return void console.error(new Date,"No Check Schema For Pub "+o);for(var u={},c=Object.keys(a.check._schema).filter(function(e){return!e.includes(".")}),l=0;l<s.length;l++)u[c[l]]=s[l];try{a.check.validate(u)}catch(e){if(e)return void console.error(new Date,"Error in Pub Check ("+o+")",e)}}"Bypass"!==t&&(a=t.split("/"),g="",d=a[0],""===a[0]&&(g="/",d=a[1]),g+=d,1<a.length&&(g+="/"),(d=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===i.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==t&&!e.messageRoute.startsWith(g)})})).length)&&(this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Detected Undestroyed Subscription - "+this.serverConfig.CLIENT_NAME,"USER: "+i.user+" (Socket: "+i.id_socket+") is on route: "+t+" but has the following subscriptions on other routes:"+JSON.stringify(d,null,2)),d.forEach(function(t){t.clients.filter(function(e){return e.id_socket===i.id_socket}).forEach(function(e){r.unsubscribe(e.messageRoute,new Date,i,e.messageId,t.publication,t.subscriptionData)})}));var g,d,a=this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)});a?a.clients.some(function(e){return e.id_socket===i.id_socket&&e.messageId===n})||a.clients.push({id_user:i.id_user,messageId:n,id_socket:i.id_socket,messageRoute:t}):this._subscriptions.push({publication:o,subscriptionData:s,collections:this.getPublicationCollections(o),clients:[{id_user:i.id_user,messageId:n,id_socket:i.id_socket,messageRoute:t}],cacheId:0,running:!1,runAgain:!1}),a=a||this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)}),this.processSubscription(a,i,n)}else console.error(new Date,"No Publication: "+o)},SubscriptionManager.prototype.createLoggedInUser=function(n){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return[2,new Promise(function(i,e){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n))?(t={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:t.id_user,user:t.user,id_ws:t.id_socket},this._loggedInUsers.push(t),logged_in_users_collection_1.LoggedInUsers.insertOne(t),i(t)):i(null),[2]})})})]})})},SubscriptionManager.prototype.unsubscribe=function(e,t,i,n,o,s){if(this._debugUnSubHits+=1,this._publications[o]){var r=this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)});if(r)for(var a=r.clients.length-1;0<=a;a--)r.clients[a].id_user===i.id_user&&r.clients[a].messageId===n&&r.clients[a].id_socket===i.id_socket&&r.clients.splice(a,1)}else console.log("No Publication: "+o)},SubscriptionManager.prototype.unsubscribeAll=function(s){return __awaiter(this,void 0,void 0,function(){var t,i,n,o;return __generator(this,function(e){if(this._debugUnSubAllHits+=1,s){if(s.isUnsubscribed)return[2];for(s.isUnsubscribed=!0,0<=this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(s.id_socket)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(s.id_socket),1),logged_in_users_collection_1.LoggedInUsers.deleteOne({id_ws:s.id_socket}),t=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_user===s.id_user&&e.id_socket===s.id_socket})}),i=t.length-1;0<=i;i--)for(n=t[i],o=n.clients.length-1;0<=o;o--)n.clients[o].id_socket===s.id_socket&&n.clients.splice(o,1);this._websocketManager.removeWebSocket(s)}return[2]})})},SubscriptionManager.prototype.getActiveSubscriptions=function(){return this._subscriptions},SubscriptionManager.prototype.getPublicationCollections=function(e){return this._publications[e].collections},SubscriptionManager.prototype.tailOpLog=function(t){return __awaiter(this,void 0,void 0,function(){var i,n=this;return __generator(this,function(e){switch(e.label){case 0:return this._oplog$&&!this._oplog$.closed&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:if(e.sent(),!this._oplog$||this._oplog$.closed){if(this._oplogRetryCount+=1,5<this._oplogRetryCount&&(console.error("****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************"),process.exit(1)),t){i=t;try{this._oplog$=index_1.ResolveIOServer.getMainDB().watch([],{resumeAfter:t})}catch(e){return this._oplog$&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),this.tailOpLog(t),[2]}}else this._oplog$=index_1.ResolveIOServer.getMainDB().watch();console.log(new Date,"oplog started"),this._oplog$.on("change",function(t){var e;t.ns&&(e=t.ns.coll,n._debugOplogCollections.some(function(e){return e.collection===t.ns.coll&&e.type===t.operationType})?n._debugOplogCollections.find(function(e){return e.collection===t.ns.coll&&e.type===t.operationType}).hits+=1:n._debugOplogCollections.push({collection:t.ns.coll,type:t.operationType,hits:1}),!e||e.endsWith(".versions")||e.startsWith("monitor-")||"logs"===e||"log-method-latencies"===e||"log-subscriptions"===e||(n._debugOplogHits+=1,"insert"===t.operationType?("support-tickets"===e&&"https://resolveio.com"===n.serverConfig.ROOT_URL&&(n._mainServer.getMethodManager().callMethodInternal.call(n._mainServer.getMethodManager(),"sendSupportTicketEmail",t.documentKey._id),n.invalidatePubsCache(e,"insert")),"method-responses"!==e&&n.invalidatePubsCache(e,"insert")):"update"===t.operationType||"replace"===t.operationType?"method-responses"!==e&&n.invalidatePubsCache(e,"update"):"delete"===t.operationType&&"method-responses"!==e&&n.invalidatePubsCache(e,"delete")),"flags"===e&&flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?n._enableDebug=!0:n._enableDebug=!1}),i=t._id)}),this._oplog$.on("error",function(e){console.log(new Date,"oplog error",e),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(i)}),this._oplog$.on("end",function(){console.log(new Date,"oplog end"),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(i)}),this._oplog$.on("close",function(){console.log(new Date,"oplog close"),n._oplog$.removeAllListeners(),n._oplog$=null,n.tailOpLog(i)})}return[2]}})})},SubscriptionManager.prototype.processSubscription=function(n,o,s){return __awaiter(this,void 0,void 0,function(){var t,i;return __generator(this,function(e){if(this._publications[n.publication].user_specific){if(n.running)return[2];this.sendDataToOneWithRetry(o,s,n,"","newSub")}else if(n.cacheId)try{t=JSON.parse(this._nodeCache.get(n.cacheId),common_1.dateReviver),i={messageId:s,hasError:!1,data:t},this.sendWS(o,i)}catch(e){this._nodeCache.del(n.cacheId),n.cacheId=0,this.sendDataToAllWithRetry(n,"","newSub")}else{if(n.running)return[2];this.sendDataToAllWithRetry(n,"","newSub")}return[2]})})},SubscriptionManager.prototype.sendDataToOne=function(s,r,a,u,c){return __awaiter(this,void 0,void 0,function(){var t,i,n,o;return __generator(this,function(e){switch(e.label){case 0:t=this._monitorManagerFunction.startMonitorFunction("User Specific Publication",a.publication,"","",a.subscriptionData),e.label=1;case 1:return e.trys.push([1,3,,4]),this._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(),"insertSubscriptionLog",c,a.publication,u,JSON.stringify(a.subscriptionData)),[4,(o=this._publications[a.publication].function).call.apply(o,__spreadArray([Object.assign({},this,SubscriptionManager.prototype),s.id_user],__read(a.subscriptionData),!1))];case 2:return o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),n={messageId:r,hasError:!1,data:o},this.sendWS(s,n),[3,4];case 3:return i=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),n={messageId:r,hasError:!0,data:i},this.sendWS(s,n),this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+a.publication+" - (sendDataToOne - WS)\n\nData \n"+JSON.stringify(a.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(i,null,2)),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.sendDataToAll=function(g,d,_){return __awaiter(this,void 0,void 0,function(){var t,o,i,n,s,r,a,u,c,l=this;return __generator(this,function(e){switch(e.label){case 0:return g.clients.length?[3,1]:(g.cacheId&&(this._nodeCache.del(g.cacheId),g.cacheId=0),0<=(c=this._subscriptions.findIndex(function(e){return e.publication===g.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(g.subscriptionData)}))&&this._subscriptions.splice(c,1),[2]);case 1:t=this._monitorManagerFunction.startMonitorFunction("Publication",g.publication,"","",g.subscriptionData),e.label=2;case 2:return e.trys.push([2,4,,5]),"superadminAPM"!==g.publication&&"loggedInUsers"!==g.publication&&this._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(),"insertSubscriptionLog",_,g.publication,d,JSON.stringify(g.subscriptionData)),[4,(c=this._publications[g.publication].function).call.apply(c,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],__read(g.subscriptionData),!1))];case 3:if(o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),g.cacheId)try{i=JSON.parse(this._nodeCache.get(g.cacheId),common_1.dateReviver),JSON.stringify(i)!==JSON.stringify(o)&&(Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),this._nodeCache.del(g.cacheId),this._nodeCache.set(g.cacheId,JSON.stringify(o)))}catch(e){Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),this._nodeCache.del(g.cacheId),this._nodeCache.set(g.cacheId,JSON.stringify(o))}else if(Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o)),(n=this._nodeCache.getStats().vsize)>this._heapLimit){for(s=0,r=this._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),a=0;a<r.length&&(this._debugRemoveCacheHits+=1,this._nodeCache.del(r[a].cacheId),r[a].cacheId=0,s+=1,!(this._nodeCache.getStats().vsize<.75*this._heapLimit));a++);this._enableDebug&&console.log("Sub Cache: Too Big - "+g.publication+" - Deleted: "+s+" - "+n)}return[3,5];case 4:return u=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!0,data:u},this.sendWS(t,i)),[2]})})})),this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+g.publication+" - (sendPubData)\n\nData \n"+JSON.stringify(g.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(u,null,2)),[3,5];case 5:return[2]}})})},SubscriptionManager.prototype.sendWS=function(e,t){this._websocketManager.send(e,t)},SubscriptionManager.prototype.getEnableDebug=function(){return this._enableDebug},SubscriptionManager}();exports.SubscriptionManager=SubscriptionManager;
|
|
2
2
|
//# sourceMappingURL=subscription.manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/managers/subscription.manager.ts"],"names":["logs_1","require","app_status_1","files_1","super_admin_1","logged_in_users_collection_1","cron_jobs_1","flags_1","method_responses_1","index_1","notifications_1","report_builder_reports_1","report_builder_libraries_1","user_groups_1","user_guides_1","report_builder_dashboard_builders_1","mongo_manager_1","common_1","NodeCache","flag_collection_1","os_1","numCPUs","cpus","length","v8","SubscriptionManager","mainServer","wss","serverConfig","monitorManagerFunction","_this","this","_publications","_subscriptions","_loggedInUsers","_mongoQueue","_mongoQueueId","_cacheId","_heapSize","getHeapStatistics","_enableDebug","_debugOplogCollections","_debugOplogHits","_debugSubCollections","_debugSubHits","_debugUnSubHits","_debugUnSubAllHits","_debugMongoQueueHits","_debugMongoQueueCollections","_debugSendQueueHits","_debugRemoveCacheHits","_oplogRetryCount","latencyBuffer","Map","LATENCY_UPDATE_INTERVAL","LATENCY_UPDATE_THRESHOLD_MS","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","_nodeCache","stdTTL","checkperiod","setInterval","flushThrottledLatencyUpdates","_wss","loadSuperAdminPublications","loadAppStatusPublications","loadLogPublications","loadFilePublications","loadCronJobPublications","loadFlagsPublications","loadMethodResponsePublications","loadNotificationPublications","loadReportBuilderReportPublications","loadReportBuilderLibraryPublications","loadUserGroupPublications","loadUserGuidePublications","loadReportBuilderDashboardBuilderPublications","tailOpLog","getEnableDebug","console","log","Date","JSON","stringify","sort","a","b","collection","localeCompare","publication","type","__awaiter","_a","LoggedInUsers","find","_b","sent","userCopy","deepCopy","i","loggedInUser","date","now","getTime","this_1","getWebSocket","id_ws","unsubscribeAll","forEach","sub","j","clients","id_socket","splice","deleteOne","_id","findIndex","client","this_2","some","Flags","findOne","then","flag","value","setCacheLimit","prototype","process","env","IS_WORKERS_ENABLED","_heapLimit","invalidatePubsCache","ResolveIOServer","getMongoManager","invalidateQueryCache","collSubs","filter","collections","includes","running","runAgain","this_3","user_specific","Promise","all","map","ws","readyState","OPEN","sendDataToOneWithRetry","messageId","err","getMethodManager","sendEmail","id_user","sendDataToAllWithRetry","collSubs_1","__values","collSubs_1_1","next","done","delay","ms","resolve","setTimeout","sendDataToAll","sendDataToOne","publications","method","Object","assign","loggedInLatency","existingEntry","newLatency","get","lastUpdate","Math","abs","latency","set","size","updates","Array","from","entries","__read","_c","updateOne","update","$set","bulkWrite","clear","error","error_1","subscribe","messageRoute","messageDate","subscriptionData","pub","hits","push","check","_schema","valObj","rootKeys","keys","validate","errors","urlData","split","urlModule_1","urlNext","otherRouteSubs","startsWith","otherSub","unsubscribe","getPublicationCollections","cacheId","processSubscription","createLoggedInUser","reject","user","objectIdHexString","__v","insertOne","indexOf","userSubs","removeWebSocket","getActiveSubscriptions","resumeToken","_oplog$","closed","removeAllListeners","close","exit","lastResumeToken_1","getMainDB","watch","resumeAfter","errOp","on","doc","ns","coll","operationType","endsWith","callMethodInternal","call","documentKey","cacheData","parse","dateReviver","serverRes","hasError","data","sendWS","del","monitor","startMonitorFunction","function","apply","__spreadArray","res","finishMonitorFunction","err_1","subIndex","res_1","nodeCacheSize","getStats","vsize","deleteCount","subArr","zz","err_2","send","exports"],"mappings":"+xEAGAA,Q,0FAAAC,QAAA,sBAAA,GACAC,aAAAD,QAAA,4BAAA,EACAE,QAAAF,QAAA,uBAAA,EACAG,cAAAH,QAAA,6BAAA,EACAI,6BAAAJ,QAAA,2CAAA,EACAK,YAAAL,QAAA,2BAAA,EACAM,QAAAN,QAAA,uBAAA,EACAO,mBAAAP,QAAA,kCAAA,EAEAQ,QAAAR,QAAA,UAAA,EACAS,gBAAAT,QAAA,+BAAA,EACAU,yBAAAV,QAAA,wCAAA,EAIAW,2BAAAX,QAAA,0CAAA,EACAY,cAAAZ,QAAA,6BAAA,EACAa,cAAAb,QAAA,6BAAA,EACAc,oCAAAd,QAAA,mDAAA,EACAe,gBAAAf,QA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KAAMmB,C,EAGPpP,KAAKkO,OAAO7G,EAAI0G,CAAS,G,QAE1B,CAAC,EAGH/N,KAAKyB,YAAYkG,iBAAgB,EAAGC,UAAU,oBAAqB,6BAA+B5H,KAAKH,aAA0B,YAAG,sCAAwCmF,EAAIpB,YAAc,8BAAgCP,KAAKC,UAAU0B,EAAIwF,iBAAkB,KAAM,CAAC,EAAI,eAAiBnH,KAAKC,UAAU8L,EAAK,KAAM,CAAC,CAAC,E,6BAKtT1P,oBAAAuG,UAAAiI,OAAR,SAAe7G,EAAe4G,GAC7BjO,KAAK0B,kBAAkB2N,KAAKhI,EAAI4G,CAAI,CACrC,EAEOvO,oBAAAuG,UAAAhD,eAAP,WACC,OAAOjD,KAAKS,YACb,EACDf,mBAAA,EAAC,EAv2BY4P,QAAA5P,oBAAAA","file":"subscription.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { ActiveSubscriptionModel, SubscriptionModel } from '../models/subscription.model';\nimport * as WebSocket from 'ws';\nimport { loadLogPublications } from '../publications/logs';\nimport { loadAppStatusPublications } from '../publications/app-status';\nimport { loadFilePublications } from '../publications/files';\nimport { loadSuperAdminPublications } from '../publications/super-admin';\nimport { LoggedInUsers } from '../collections/logged-in-users.collection';\nimport { loadCronJobPublications } from '../publications/cron-jobs';\nimport { loadFlagsPublications } from '../publications/flags';\nimport { loadMethodResponsePublications } from '../publications/method-responses';\nimport ResolveIOMainServer from '../server-app';\nimport { ResolveIOServer } from '../index';\nimport { loadNotificationPublications } from '../publications/notifications';\nimport { loadReportBuilderReportPublications } from '../publications/report-builder-reports';\nimport { LoggedInUserModel } from '../models/logged-in-users.model';\n\nimport { ChangeStream, ChangeStreamDeleteDocument, ChangeStreamDocument, ChangeStreamInsertDocument, ChangeStreamReplaceDocument, ChangeStreamUpdateDocument, ResumeToken } from 'mongodb';\nimport { loadReportBuilderLibraryPublications } from '../publications/report-builder-libraries';\nimport { loadUserGroupPublications } from '../publications/user-groups';\nimport { loadUserGuidePublications } from '../publications/user-guides';\nimport { loadReportBuilderDashboardBuilderPublications } from '../publications/report-builder-dashboard-builders';\nimport { objectIdHexString } from './mongo.manager';\nimport { dateReviver, deepCopy } from '../util/common';\nimport * as NodeCache from 'node-cache';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { Flags } from '../collections/flag.collection';\nimport { cpus } from 'os';\nimport { WebSocketManager } from './websocket.manager';\nconst numCPUs = cpus().length;\nconst v8 = require('v8');\n\n// Performance Dependencies\n// import * as path from 'path';\n// import { Worker } from 'worker_threads';\n\ninterface MongoQueueModel {\n\t_id: number,\n\ttype: string;\n\tcollection: string;\n\tsubscription: ActiveSubscriptionModel;\n\trunning: boolean;\n\trun_again: boolean;\n}\n\n// interface CurrentPerformanceMonitor {\n// \t_id: number;\n// \tfunction: string;\n// \tpublication: string;\n// \tsubscriptionData: any[];\n// \tdate_start: Date;\n// \tdate_end: Date;\n// \tduration: number;\n// \tresult: string;\n// }\n\nexport class SubscriptionManager {\n\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _publications: SubscriptionModel = {};\n\tprivate _subscriptions: ActiveSubscriptionModel[] = [];\n\tprivate _wss: WebSocket.Server;\n\tprivate _loggedInUsers: LoggedInUserModel[] = [];\n\n\tprivate _mongoQueue: MongoQueueModel[] = [];\n\tprivate _mongoQueueId = 0;\n\t\n\tprivate _oplog$: ChangeStream;\n\n\tprivate _nodeCache;\n\tprivate _cacheId = 1;\n\n\tprivate _heapSize = v8.getHeapStatistics() / numCPUs;\n\tprivate _heapLimit: number;\n\n\tprivate serverConfig;\n\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _enableDebug = false;\n\tprivate _debugOplogCollections = [];\n\tprivate _debugOplogHits = 0;\n\tprivate _debugSubCollections = [];\n\tprivate _debugSubHits = 0;\n\tprivate _debugUnSubHits = 0;\n\tprivate _debugUnSubAllHits = 0;\n\tprivate _debugMongoQueueHits = 0;\n\tprivate _debugMongoQueueCollections = [];\n\tprivate _debugSendQueueHits = 0;\n\tprivate _debugRemoveCacheHits = 0;\n\n\tprivate _oplogRetryCount = 0;\n\n\t// Buffer to store throttled latency updates with timestamps\n\tprivate latencyBuffer = new Map<string, { latency: number, lastUpdate: Date }>();\n\n\t// Interval to flush latency updates in MongoDB\n\tprivate readonly LATENCY_UPDATE_INTERVAL = 60000;\n\n\t// Minimum time difference between two latency updates for the same user\n\tprivate readonly LATENCY_UPDATE_THRESHOLD_MS = 30000;\n\n\t// private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];\n\t// private idPerformance: number = 0;\n\t// private performanceThread;\n\n\tconstructor(mainServer, wss: WebSocket.Server, serverConfig, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._websocketManager = this._mainServer.getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\tthis._nodeCache = new NodeCache( { stdTTL: 0, checkperiod: 0 } );\n\n\t\tsetInterval(() => this.flushThrottledLatencyUpdates(), this.LATENCY_UPDATE_INTERVAL);\n\n\t\t// setTimeout(() => {\n\t\t// \tconsole.log('Setting up performance thread');\n\n\t\t// \tthis.performanceThread = new Worker(path.join(__dirname, './subscription.performance.js'));\n\n\t\t// \tthis.performanceThread.on('exit', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD EXITED!!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\n\t\t// \tthis.performanceThread.on('error', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD RECV ERROR !!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\t\t// }, 5000);\n\n\t\t// setInterval(() => {\n\t\t// \tconsole.log('Post thread msg');\n\t\t// \tthis.performanceThread.postMessage(this.currentPerfomanceMonitor);\n\t\t// \tthis.currentPerfomanceMonitor = [];\n\t\t// }, 10000);\n\n\t\tthis.serverConfig = serverConfig;\n\t\tthis._wss = wss;\n\n\t\t// Publications\n\t\tloadSuperAdminPublications(this);\n\t\tloadAppStatusPublications(this);\n\t\tloadLogPublications(this);\n\t\tloadFilePublications(this);\n\t\tloadCronJobPublications(this);\n\t\tloadFlagsPublications(this);\n\t\tloadMethodResponsePublications(this);\n\t\tloadNotificationPublications(this);\n\t\tloadReportBuilderReportPublications(this);\n\t\tloadReportBuilderLibraryPublications(this);\n\t\tloadUserGroupPublications(this);\n\t\tloadUserGuidePublications(this);\n\t\tloadReportBuilderDashboardBuilderPublications(this);\n\n\t\tthis.tailOpLog();\n\n\t\tsetInterval(() => {\n\t\t\tthis._oplogRetryCount = 0;\n\t\t}, 15000);\n\n\t\tsetInterval(() => {\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Subs', this._subscriptions.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Logged In Users', this._loggedInUsers.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue', this._mongoQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Hits', this._debugMongoQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Collections', JSON.stringify(this._debugMongoQueueCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Hits', this._debugOplogHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Collections', JSON.stringify(this._debugOplogCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.type.localeCompare(b.type)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Hits', this._debugSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Collections', JSON.stringify(this._debugSubCollections.sort((a, b) => a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub Hits', this._debugUnSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub All Hits', this._debugUnSubAllHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Cache Cleanup Hits', this._debugRemoveCacheHits);\n\t\t\t}\n\t\t\t\n\t\t\tthis._debugOplogHits = 0;\n\t\t\tthis._debugOplogCollections = [];\n\t\t\tthis._debugSubCollections = [];\n\t\t\tthis._debugMongoQueueHits = 0;\n\t\t\tthis._debugMongoQueueCollections = [];\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSubHits = 0;\n\t\t\tthis._debugUnSubHits = 0;\n\t\t\tthis._debugUnSubAllHits = 0;\n\t\t\tthis._debugRemoveCacheHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(async () => {\n\t\t\tthis._loggedInUsers = await LoggedInUsers.find();\n\t\n\t\t\tlet userCopy = deepCopy(this._loggedInUsers);\n\t\t\tfor (let i = this._loggedInUsers.length - 1; i >= 0; i--) {\n\t\t\t\tlet loggedInUser = userCopy[i];\n\n\t\t\t\tif (!loggedInUser.date || Date.now() - loggedInUser.date.getTime() > 120000) {\n\t\t\t\t\tif (this._websocketManager.getWebSocket(loggedInUser.id_ws)) {\n\t\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', this._websocketManager.getWebSocket(loggedInUser.id_ws)['user'], this._websocketManager.getWebSocket(loggedInUser.id_ws)['id_socket'], 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.unsubscribeAll(this._websocketManager.getWebSocket(loggedInUser.id_ws));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._subscriptions.forEach(sub => {\n\t\t\t\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\t\t\t\tif (client.id_socket === loggedInUser.id_ws) {\n\t\t\t\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tLoggedInUsers.deleteOne({_id: loggedInUser._id});\n\n\t\t\t\t\t\tif (this._loggedInUsers.findIndex(a => a._id === loggedInUser._id) >= 0) {\n\t\t\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.findIndex(a => a._id === loggedInUser._id), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (let i = 0; i < this._subscriptions.length; i++) {\n\t\t\t\tlet sub = this._subscriptions[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\tif (!this._loggedInUsers.some(a => a.id_ws === client.id_socket)) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, 30000);\n\n\t\tFlags.findOne({type: 'Enable Debug'}).then(flag => {\n\t\t\tif (flag && flag.value) {\n\t\t\t\tthis._enableDebug = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._enableDebug = false;\n\t\t\t}\n\t\t});\n\n\t\tthis.setCacheLimit();\n\t}\n\n\tprivate setCacheLimit() {\t\n\t\tif (process.env.IS_WORKERS_ENABLED === 'true') {\n\t\t\tthis._heapLimit = this._heapSize * 0.4;\n\t\t}\n\t\telse {\n\t\t\tthis._heapLimit = this._heapSize * 0.3; // Use 50% of total heap size\n\t\t}\n\t}\n\n\tpublic async invalidatePubsCache(collection: string, type: string) {\n\t\tResolveIOServer.getMongoManager().invalidateQueryCache(collection);\n\n\t\tlet collSubs = this._subscriptions.filter(a => a.collections.includes(collection));\n\n\t\tfor (let sub of collSubs) {\n\t\t\tif (sub.running) {\n\t\t\t\tsub.runAgain = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (this._publications[sub.publication].user_specific) {\n\t\t\t\tPromise.all(\n\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tthis.sendDataToOneWithRetry(ws, client.messageId, sub, collection, type);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t// Handle error\n\t\t\t\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During sendDataToOne - User Specific - Socket: ' + client.id_socket + ', User: ' + client.id_user + ', MessageId: ' + client.messageId + ', Pub: ' + sub.publication + ', Err: ' + JSON.stringify(err, null, 2));\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\telse {\n\t\t\t\tthis.sendDataToAllWithRetry(sub, collection, type);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async delay(ms: number) {\n\t\treturn new Promise(resolve => setTimeout(resolve, ms));\n\t}\n\n\tprivate async sendDataToAllWithRetry(sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tsub.running = true;\n\n\t\tdo {\n\t\t\tsub.runAgain = false;\n\t\t\tawait this.sendDataToAll(sub, collection, type);\n\n\t\t\tif (sub.runAgain) {\n\t\t\t\tawait this.delay(500); // delay, adjust as needed\n\t\t\t}\n\t\t} while (sub.runAgain);\n\t\tsub.running = false;\n\t}\n\n\tprivate async sendDataToOneWithRetry(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tsub.running = true;\n\n\t\tdo {\n\t\t\tsub.runAgain = false;\n\t\t\tawait this.sendDataToOne(ws, messageId, sub, collection, type);\n\n\t\t\tif (sub.runAgain) {\n\t\t\t\tawait this.delay(500); // delay, adjust as needed\n\t\t\t}\n\t\t} while (sub.runAgain);\n\t\tsub.running = false;\n\t}\n\n\t// Add all files to publications private object\n\tpublic publications(method: SubscriptionModel) {\n\t\tthis._publications = Object.assign(this._publications, method);\n\t}\n\n\t// Throttled `loggedInLatency` method\n\tpublic loggedInLatency(ws: WebSocket) {\n\t\tlet loggedInUser = this._loggedInUsers.find(a => a.id_ws === ws['id_socket']);\n\t\tif (!loggedInUser) return;\n\n\t\tconst now = new Date();\n\t\tconst existingEntry = this.latencyBuffer.get(ws['id_socket']);\n\t\tconst newLatency = ws['latency'];\n\n\t\t// Throttle updates: only update if time threshold has passed or latency has significantly changed\n\t\tif (\n\t\t\t!existingEntry || \n\t\t\t(now.getTime() - existingEntry.lastUpdate.getTime() >= this.LATENCY_UPDATE_THRESHOLD_MS) || \n\t\t\t(Math.abs(newLatency - existingEntry.latency) > 100) // Optional: log only significant changes\n\t\t) {\n\t\t\t// Update in-memory and buffer\n\t\t\tloggedInUser.date = now;\n\t\t\tthis.latencyBuffer.set(ws['id_socket'], { latency: newLatency, lastUpdate: now });\n\t\t}\n\t}\n\n\t// Method to flush buffered latency updates in bulk\n\tprivate async flushThrottledLatencyUpdates() {\n\t\tif (this.latencyBuffer.size === 0) return; // No updates to flush\n\n\t\tconst updates = Array.from(this.latencyBuffer.entries()).map(([id_ws, { latency, lastUpdate }]) => ({\n\t\t\tupdateOne: {\n\t\t\t\tfilter: { id_ws },\n\t\t\t\tupdate: { $set: { latency, date: lastUpdate } }\n\t\t\t}\n\t\t}));\n\n\t\ttry {\n\t\t\tawait LoggedInUsers.bulkWrite(updates);\n\t\t\tthis.latencyBuffer.clear(); // Clear buffer after successful update\n\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Throttled latency batch update successful', updates.length);\n\t\t\t}\n\t\t}\n\t\tcatch (error) {\n\t\t\tconsole.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error);\n\t\t\t// Optional: implement retry logic or logging for failed updates\n\t\t}\n\t}\n\n\t// Subscribe to publication\n\tpublic subscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugSubHits += 1;\n\n\t\tif (!this._debugSubCollections.some(a => a.publication === publication)) {\n\t\t\tthis._debugSubCollections.push({\n\t\t\t\tpublication: publication,\n\t\t\t\thits: 1\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tthis._debugSubCollections.find(a => a.publication === publication).hits += 1;\n\t\t}\n\n\t\tlet pub = this._publications[publication];\n\n\t\tif (!pub) {\n\t\t\tconsole.error(new Date(), 'No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tif (subscriptionData.length > 1 || subscriptionData[0]) {\n\t\t\t\tif (!pub.check) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Function For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (!pub.check._schema) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Schema For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet valObj = {};\n\t\t\t\t\tlet valKeys = Object.keys(pub.check._schema);\n\n\t\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\t\tfor (let i = 0; i < subscriptionData.length; i++) {\n\t\t\t\t\t\tvalObj[rootKeys[i]] = subscriptionData[i];\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpub.check.validate(valObj);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (errors) {\n\t\t\t\t\t\tif (errors) {\n\t\t\t\t\t\t\tconsole.error(new Date(), 'Error in Pub Check (' + publication + ')', errors);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (messageRoute !== 'Bypass') {\n\t\t\t\tlet urlData = messageRoute.split('/');\n\t\t\t\tlet urlModule = '';\n\t\t\t\tlet urlNext = urlData[0];\n\n\t\t\t\tif (urlData[0] === '') {\n\t\t\t\t\turlModule = '/';\n\t\t\t\t\turlNext = urlData[1];\n\t\t\t\t}\n\n\t\t\t\turlModule += urlNext;\n\n\t\t\t\tif (urlData.length > 1) {\n\t\t\t\t\turlModule += '/';\n\t\t\t\t}\n\n\t\t\t\tlet otherRouteSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_socket === ws['id_socket'] && b.messageRoute !== 'Bypass' && b.messageRoute !== '/' && b.messageRoute !== messageRoute && !b.messageRoute.startsWith(urlModule)));\n\n\t\t\t\tif (otherRouteSubs.length) {\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Detected Undestroyed Subscription - ' + this.serverConfig['CLIENT_NAME'], 'USER: ' + ws['user'] + ' (Socket: ' + ws['id_socket'] + ') ' + ' is on route: ' + messageRoute + ' but has the following subscriptions on other routes:' + JSON.stringify(otherRouteSubs, null, 2));\n\n\t\t\t\t\totherRouteSubs.forEach(otherSub => {\n\t\t\t\t\t\totherSub.clients.filter(a => a.id_socket === ws['id_socket']).forEach(client => {\n\t\t\t\t\t\t\tthis.unsubscribe(client.messageRoute, new Date(), ws, client.messageId, otherSub.publication, otherSub.subscriptionData);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet sub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\n\t\t\t// If sub found (another user watching same data), add client to same sub\n\t\t\tif (sub) {\n\t\t\t\tif (!sub.clients.some(a => a.id_socket === ws['id_socket'] && a.messageId === messageId)) {\n\t\t\t\t\tsub.clients.push({\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If sub not found, create new sub\n\t\t\telse {\n\t\t\t\tthis._subscriptions.push({\n\t\t\t\t\tpublication: publication,\n\t\t\t\t\tsubscriptionData: subscriptionData,\n\t\t\t\t\tcollections: this.getPublicationCollections(publication),\n\t\t\t\t\tclients: [{\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute,\n\t\t\t\t\t}],\n\t\t\t\t\tcacheId: 0,\n\t\t\t\t\trunning: false,\n\t\t\t\t\trunAgain: false\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!sub) {\n\t\t\t\tsub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\t\t\t}\n\n\t\t\t// Immediately send data to the new client\n\t\t\tthis.processSubscription(sub, ws, messageId);\n\t\t}\n\t}\n\n\tpublic async createLoggedInUser(id_ws: string): Promise<LoggedInUserModel> {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tlet ws = this._websocketManager.getWebSocket(id_ws);\n\n\t\t\tif (ws) {\n\t\t\t\tlet user = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tthis._loggedInUsers.push(user);\n\t\t\t\tLoggedInUsers.insertOne(user);\n\t\t\t\t\n\t\t\t\tresolve(user);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(null);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Unsubscribe from publication \n\tpublic unsubscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugUnSubHits += 1;\n\n\t\tif (!this._publications[publication]) {\n\t\t\tconsole.log('No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet sub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\n\t\t\tif (sub) {\n\t\t\t\tfor (let i = sub.clients.length - 1; i >= 0; i--) {\n\t\t\t\t\tif (sub.clients[i].id_user === ws['id_user'] && sub.clients[i].messageId === messageId && sub.clients[i].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(i, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// Unsubscribe from publication\n\tpublic async unsubscribeAll(ws: WebSocket) {\n\t\tthis._debugUnSubAllHits += 1;\n\n\t\tif (ws) {\n\t\t\t// Check if WebSocket has already been unsubscribed\n\t\t\tif (ws['isUnsubscribed']) {\n\t\t\t\treturn; // Skip if already unsubscribed\n\t\t\t}\n\t\t\t\n\t\t\t// Mark the WebSocket as unsubscribed to prevent further calls\n\t\t\tws['isUnsubscribed'] = true;\n\t\t\t\n\t\t\tif (this._loggedInUsers.map(a => a.id_ws).indexOf(ws['id_socket']) >= 0) {\n\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.map(a => a.id_ws).indexOf(ws['id_socket']), 1);\n\t\t\t}\n\t\t\tLoggedInUsers.deleteOne({ id_ws: ws['id_socket'] });\n\n\t\t\tlet userSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_user === ws['id_user'] && b.id_socket === ws['id_socket']));\n\n\t\t\tfor (let i = userSubs.length - 1; i >= 0; i--) {\n\t\t\t\tlet sub = userSubs[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tif (sub.clients[j].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._websocketManager.removeWebSocket(ws);\n\t\t}\n\t}\n\n\tpublic getActiveSubscriptions() {\n\t\treturn this._subscriptions;\n\t}\n\n\t// Get publication collection\n\tprivate getPublicationCollections(publication: string) {\n\t\treturn this._publications[publication].collections;\n\t}\n\n\t// Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)\n\tprivate async tailOpLog(resumeToken?: ResumeToken) {\n\t\tif (this._oplog$ && !this._oplog$.closed) {\n\t\t\tthis._oplog$.removeAllListeners();\n\t\t\tthis._oplog$.close();\n\t\t\tthis._oplog$ = null;\n\t\t}\n\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\n\t\tif (!this._oplog$ || this._oplog$.closed) {\n\t\t\tthis._oplogRetryCount += 1;\n\n\t\t\tif (this._oplogRetryCount > 5) {\n\t\t\t\tconsole.error('****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\tlet lastResumeToken: ResumeToken;\n\n\t\t\tif (resumeToken) {\n\t\t\t\tlastResumeToken = resumeToken;\n\t\t\t\ttry {\n\t\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch([], { resumeAfter: resumeToken });\n\t\t\t\t}\n\t\t\t\tcatch (errOp) {\n\t\t\t\t\tif (this._oplog$) {\n\t\t\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\t\t\tthis._oplog$.close();\n\t\t\t\t\t\tthis._oplog$ = null;\n\t\t\t\t\t}\n\t\t\t\t\tthis.tailOpLog(resumeToken);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch();\n\t\t\t}\n\n\t\t\tconsole.log(new Date(), 'oplog started');\n\n\t\t\tthis._oplog$.on('change', (doc: ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument) => {\n\t\t\t\tif (doc.ns) {\n\t\t\t\t\tlet collection = doc.ns.coll;\n\n\t\t\t\t\tif (!this._debugOplogCollections.some(a => a.collection === doc.ns.coll && a.type === doc.operationType)) {\n\t\t\t\t\t\tthis._debugOplogCollections.push({\n\t\t\t\t\t\t\tcollection: doc.ns.coll,\n\t\t\t\t\t\t\ttype: doc.operationType,\n\t\t\t\t\t\t\thits: 1\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._debugOplogCollections.find(a => a.collection === doc.ns.coll && a.type === doc.operationType).hits += 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection && !collection.endsWith('.versions') && !collection.startsWith('monitor-') && collection !== 'logs' && collection !== 'log-method-latencies' && collection !== 'log-subscriptions') {\n\t\t\t\t\t\tthis._debugOplogHits += 1;\n\n\t\t\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\t\t\tif (collection === 'support-tickets') {\n\t\t\t\t\t\t\t\tif (this.serverConfig['ROOT_URL'] === 'https://resolveio.com') {\n\t\t\t\t\t\t\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'sendSupportTicketEmail', doc.documentKey['_id']);\n\t\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'update' || doc.operationType === 'replace') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'update');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'delete');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection === 'flags') {\n\t\t\t\t\t\tFlags.findOne({ type: 'Enable Debug' }).then(flag => {\n\t\t\t\t\t\t\tif (flag && flag.value) {\n\t\t\t\t\t\t\t\tthis._enableDebug = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._enableDebug = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tlastResumeToken = doc._id;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tthis._oplog$.on('error', error => {\n\t\t\t\tconsole.log(new Date(), 'oplog error', error);\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('end', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog end');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog close');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async processSubscription(sub: ActiveSubscriptionModel, ws: WebSocket, messageId: number) {\n\t\tif (!this._publications[sub.publication].user_specific) {\t\t\t\n\t\t\tif (sub.cacheId) {\n\t\t\t\ttry {\n\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), dateReviver);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\tdata: cacheData\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\t\tsub.cacheId = 0;\n\n\t\t\t\t\tthis.sendDataToAllWithRetry(sub, '', 'newSub');\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (sub.running) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.sendDataToAllWithRetry(sub, '', 'newSub');\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (sub.running) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tthis.sendDataToOneWithRetry(ws, messageId, sub, '', 'newSub');\n\t\t}\n\t}\n\n\tprivate async sendDataToOne(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', sub.publication, '', '', sub.subscriptionData);\n\t\ttry {\n\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));\n\n\t\t\tlet res = await this._publications[sub.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ws['id_user'], ...sub.subscriptionData);\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: res\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, serverRes);\n\t\t}\n\t\tcatch (err) {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: err\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, serverRes);\n\n\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendDataToOne - WS)\\n\\nData \\n' + JSON.stringify(sub.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t}\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate async sendDataToAll(sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tif (!sub.clients.length) {\n\t\t\tif (sub.cacheId) {\n\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\tsub.cacheId = 0;\n\t\t\t}\n\n\t\t\tlet subIndex = this._subscriptions.findIndex(a => a.publication === sub.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(sub.subscriptionData));\n\t\t\tif (subIndex >= 0) {\n\t\t\t\tthis._subscriptions.splice(subIndex, 1);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Publication', sub.publication, '', '', sub.subscriptionData);\n\n\t\t\ttry {\n\t\t\t\tif (sub.publication !== 'superadminAPM' && sub.publication !== 'loggedInUsers') {\n\t\t\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));\n\t\t\t\t}\n\n\t\t\t\tlet res = await this._publications[sub.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ...sub.subscriptionData);\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tif (sub.cacheId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), dateReviver);\n\t\n\t\t\t\t\t\tif (JSON.stringify(cacheData) !== JSON.stringify(res)) {\n\t\t\t\t\t\t\tPromise.all(\n\t\t\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\t\t\t\tsub.cacheId = this._cacheId++;\n\t\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\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\tPromise.all(\n\t\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\t\t\tsub.cacheId = this._cacheId++;\n\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tPromise.all(\n\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t};\n\t\n\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tsub.cacheId = this._cacheId++;\n\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\n\t\t\t\t\tconst nodeCacheSize = this._nodeCache.getStats().vsize;\n\n\t\t\t\t\tif (nodeCacheSize > this._heapLimit) {\n\t\t\t\t\t\t// Evict cache entries as needed\n\t\t\t\t\t\tlet deleteCount = 0;\n\t\t\t\t\t\tconst subArr = this._subscriptions.filter(a => a.cacheId && !a.clients.length);\n\t\t\t\t\n\t\t\t\t\t\tfor (let zz = 0; zz < subArr.length; zz++) {\n\t\t\t\t\t\t\tthis._debugRemoveCacheHits += 1;\n\t\t\t\t\t\t\tthis._nodeCache.del(subArr[zz].cacheId);\n\t\t\t\t\t\t\tsubArr[zz].cacheId = 0;\n\t\t\t\t\t\t\tdeleteCount += 1;\n\t\t\t\t\t\t\tif (this._nodeCache.getStats().vsize < this._heapLimit * 0.75) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t'Sub Cache: ' +\n\t\t\t\t\t\t\t\t'Too Big - ' +\n\t\t\t\t\t\t\t\tsub.publication +\n\t\t\t\t\t\t\t\t' - Deleted: ' +\n\t\t\t\t\t\t\t\tdeleteCount +\n\t\t\t\t\t\t\t\t' - ' +\n\t\t\t\t\t\t\t\tnodeCacheSize\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\tcatch (err) {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tPromise.all(\n\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\t\tdata: err\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendPubData)\\n\\nData \\n' + JSON.stringify(sub.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate sendWS(ws: WebSocket, data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\t}\n\n\tpublic getEnableDebug() {\n\t\treturn this._enableDebug;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/managers/subscription.manager.ts"],"names":["logs_1","require","app_status_1","files_1","super_admin_1","logged_in_users_collection_1","cron_jobs_1","flags_1","method_responses_1","index_1","notifications_1","report_builder_reports_1","report_builder_libraries_1","user_groups_1","user_guides_1","report_builder_dashboard_builders_1","mongo_manager_1","common_1","NodeCache","flag_collection_1","os_1","flags_update_1","numCPUs","cpus","length","v8","SubscriptionManager","mainServer","wss","serverConfig","monitorManagerFunction","_this","this","_publications","_subscriptions","_loggedInUsers","_mongoQueue","_mongoQueueId","_cacheId","_heapSize","getHeapStatistics","_enableDebug","_debugOplogCollections","_debugOplogHits","_debugSubCollections","_debugSubHits","_debugUnSubHits","_debugUnSubAllHits","_debugMongoQueueHits","_debugMongoQueueCollections","_debugSendQueueHits","_debugRemoveCacheHits","_oplogRetryCount","latencyBuffer","Map","LATENCY_UPDATE_INTERVAL","LATENCY_UPDATE_THRESHOLD_MS","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","_nodeCache","stdTTL","checkperiod","setInterval","flushThrottledLatencyUpdates","_wss","loadSuperAdminPublications","loadAppStatusPublications","loadLogPublications","loadFilePublications","loadCronJobPublications","loadFlagsUpdatePublications","loadFlagsPublications","loadMethodResponsePublications","loadNotificationPublications","loadReportBuilderReportPublications","loadReportBuilderLibraryPublications","loadUserGroupPublications","loadUserGuidePublications","loadReportBuilderDashboardBuilderPublications","tailOpLog","getEnableDebug","console","log","Date","JSON","stringify","sort","a","b","collection","localeCompare","publication","type","__awaiter","_a","LoggedInUsers","find","_b","sent","userCopy","deepCopy","i","loggedInUser","date","now","getTime","this_1","getWebSocket","id_ws","unsubscribeAll","forEach","sub","j","clients","id_socket","splice","deleteOne","_id","findIndex","client","this_2","some","Flags","findOne","then","flag","value","setCacheLimit","prototype","process","env","IS_WORKERS_ENABLED","_heapLimit","invalidatePubsCache","ResolveIOServer","getMongoManager","invalidateQueryCache","collSubs","filter","collections","includes","running","runAgain","this_3","user_specific","Promise","all","map","ws","readyState","OPEN","sendDataToOneWithRetry","messageId","err","getMethodManager","sendEmail","id_user","sendDataToAllWithRetry","collSubs_1","__values","collSubs_1_1","next","done","delay","ms","resolve","setTimeout","sendDataToAll","sendDataToOne","publications","method","Object","assign","loggedInLatency","existingEntry","newLatency","get","lastUpdate","Math","abs","latency","set","size","updates","Array","from","entries","__read","_c","updateOne","update","$set","bulkWrite","clear","error","error_1","subscribe","messageRoute","messageDate","subscriptionData","pub","hits","push","check","_schema","valObj","rootKeys","keys","validate","errors","urlData","split","urlModule_1","urlNext","otherRouteSubs","startsWith","otherSub","unsubscribe","getPublicationCollections","cacheId","processSubscription","createLoggedInUser","reject","user","objectIdHexString","__v","insertOne","indexOf","userSubs","removeWebSocket","getActiveSubscriptions","resumeToken","_oplog$","closed","removeAllListeners","close","exit","lastResumeToken_1","getMainDB","watch","resumeAfter","errOp","on","doc","ns","coll","operationType","endsWith","callMethodInternal","call","documentKey","cacheData","parse","dateReviver","serverRes","hasError","data","sendWS","del","monitor","startMonitorFunction","function","apply","__spreadArray","res","finishMonitorFunction","err_1","subIndex","res_1","nodeCacheSize","getStats","vsize","deleteCount","subArr","zz","err_2","send","exports"],"mappings":"+xEAGAA,Q,0FAAAC,QAAA,sBAAA,GACAC,aAAAD,QAAA,4BAAA,EACAE,QAAAF,QAAA,uBAAA,EACAG,cAAAH,QAAA,6BAAA,EACAI,6BAAAJ,QAAA,2CAAA,EACAK,YAAAL,QAAA,2BAAA,EACAM,QAAAN,QAAA,uBAAA,EACAO,mBAAAP,QAAA,kCAAA,EAEAQ,QAAAR,QAAA,UAAA,EACAS,gBAAAT,QAAA,+BAAA,EACAU,yBAAAV,QAAA,wCAAA,EAIAW,2BAAAX,QAAA,0CAAA,EACAY,cAAAZ,QAAA,6BAAA,EACAa,cAAAb,QAAA,6BAAA,EACAc,oCAAAd,QAAA,mDAAA,EACAe,gBAAAf,QAAA,iBAAA,EACAgB,SAAAhB,QAAA,gBAAA,EACAiB,UAAAjB,QAAA,YAAA,EAEAkB,kBAAAlB,QAAA,gCAAA,EACAmB,KAAAnB,QAAA,IAAA,EAEAoB,eAAApB,QAAA,8BAAA,EACMqB,SAAU,EAAAF,KAAAG,MAAI,EAAGC,OACjBC,GAAKxB,QAAQ,IAAI,EA0BvByB,oB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AKC,UAAU8L,EAAK,KAAM,CAAC,CAAC,E,6BAKtT3P,oBAAAwG,UAAAiI,OAAR,SAAe7G,EAAe4G,GAC7BlO,KAAK0B,kBAAkB4N,KAAKhI,EAAI4G,CAAI,CACrC,EAEOxO,oBAAAwG,UAAAhD,eAAP,WACC,OAAOlD,KAAKS,YACb,EACDf,mBAAA,EAAC,EAv2BY6P,QAAA7P,oBAAAA","file":"subscription.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { ActiveSubscriptionModel, SubscriptionModel } from '../models/subscription.model';\nimport * as WebSocket from 'ws';\nimport { loadLogPublications } from '../publications/logs';\nimport { loadAppStatusPublications } from '../publications/app-status';\nimport { loadFilePublications } from '../publications/files';\nimport { loadSuperAdminPublications } from '../publications/super-admin';\nimport { LoggedInUsers } from '../collections/logged-in-users.collection';\nimport { loadCronJobPublications } from '../publications/cron-jobs';\nimport { loadFlagsPublications } from '../publications/flags';\nimport { loadMethodResponsePublications } from '../publications/method-responses';\nimport ResolveIOMainServer from '../server-app';\nimport { ResolveIOServer } from '../index';\nimport { loadNotificationPublications } from '../publications/notifications';\nimport { loadReportBuilderReportPublications } from '../publications/report-builder-reports';\nimport { LoggedInUserModel } from '../models/logged-in-users.model';\n\nimport { ChangeStream, ChangeStreamDeleteDocument, ChangeStreamDocument, ChangeStreamInsertDocument, ChangeStreamReplaceDocument, ChangeStreamUpdateDocument, ResumeToken } from 'mongodb';\nimport { loadReportBuilderLibraryPublications } from '../publications/report-builder-libraries';\nimport { loadUserGroupPublications } from '../publications/user-groups';\nimport { loadUserGuidePublications } from '../publications/user-guides';\nimport { loadReportBuilderDashboardBuilderPublications } from '../publications/report-builder-dashboard-builders';\nimport { objectIdHexString } from './mongo.manager';\nimport { dateReviver, deepCopy } from '../util/common';\nimport * as NodeCache from 'node-cache';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { Flags } from '../collections/flag.collection';\nimport { cpus } from 'os';\nimport { WebSocketManager } from './websocket.manager';\nimport { loadFlagsUpdatePublications } from '../publications/flags-update';\nconst numCPUs = cpus().length;\nconst v8 = require('v8');\n\n// Performance Dependencies\n// import * as path from 'path';\n// import { Worker } from 'worker_threads';\n\ninterface MongoQueueModel {\n\t_id: number,\n\ttype: string;\n\tcollection: string;\n\tsubscription: ActiveSubscriptionModel;\n\trunning: boolean;\n\trun_again: boolean;\n}\n\n// interface CurrentPerformanceMonitor {\n// \t_id: number;\n// \tfunction: string;\n// \tpublication: string;\n// \tsubscriptionData: any[];\n// \tdate_start: Date;\n// \tdate_end: Date;\n// \tduration: number;\n// \tresult: string;\n// }\n\nexport class SubscriptionManager {\n\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _publications: SubscriptionModel = {};\n\tprivate _subscriptions: ActiveSubscriptionModel[] = [];\n\tprivate _wss: WebSocket.Server;\n\tprivate _loggedInUsers: LoggedInUserModel[] = [];\n\n\tprivate _mongoQueue: MongoQueueModel[] = [];\n\tprivate _mongoQueueId = 0;\n\t\n\tprivate _oplog$: ChangeStream;\n\n\tprivate _nodeCache;\n\tprivate _cacheId = 1;\n\n\tprivate _heapSize = v8.getHeapStatistics() / numCPUs;\n\tprivate _heapLimit: number;\n\n\tprivate serverConfig;\n\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _enableDebug = false;\n\tprivate _debugOplogCollections = [];\n\tprivate _debugOplogHits = 0;\n\tprivate _debugSubCollections = [];\n\tprivate _debugSubHits = 0;\n\tprivate _debugUnSubHits = 0;\n\tprivate _debugUnSubAllHits = 0;\n\tprivate _debugMongoQueueHits = 0;\n\tprivate _debugMongoQueueCollections = [];\n\tprivate _debugSendQueueHits = 0;\n\tprivate _debugRemoveCacheHits = 0;\n\n\tprivate _oplogRetryCount = 0;\n\n\t// Buffer to store throttled latency updates with timestamps\n\tprivate latencyBuffer = new Map<string, { latency: number, lastUpdate: Date }>();\n\n\t// Interval to flush latency updates in MongoDB\n\tprivate readonly LATENCY_UPDATE_INTERVAL = 60000;\n\n\t// Minimum time difference between two latency updates for the same user\n\tprivate readonly LATENCY_UPDATE_THRESHOLD_MS = 30000;\n\n\t// private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];\n\t// private idPerformance: number = 0;\n\t// private performanceThread;\n\n\tconstructor(mainServer, wss: WebSocket.Server, serverConfig, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._websocketManager = this._mainServer.getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\tthis._nodeCache = new NodeCache( { stdTTL: 0, checkperiod: 0 } );\n\n\t\tsetInterval(() => this.flushThrottledLatencyUpdates(), this.LATENCY_UPDATE_INTERVAL);\n\n\t\t// setTimeout(() => {\n\t\t// \tconsole.log('Setting up performance thread');\n\n\t\t// \tthis.performanceThread = new Worker(path.join(__dirname, './subscription.performance.js'));\n\n\t\t// \tthis.performanceThread.on('exit', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD EXITED!!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\n\t\t// \tthis.performanceThread.on('error', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD RECV ERROR !!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\t\t// }, 5000);\n\n\t\t// setInterval(() => {\n\t\t// \tconsole.log('Post thread msg');\n\t\t// \tthis.performanceThread.postMessage(this.currentPerfomanceMonitor);\n\t\t// \tthis.currentPerfomanceMonitor = [];\n\t\t// }, 10000);\n\n\t\tthis.serverConfig = serverConfig;\n\t\tthis._wss = wss;\n\n\t\t// Publications\n\t\tloadSuperAdminPublications(this);\n\t\tloadAppStatusPublications(this);\n\t\tloadLogPublications(this);\n\t\tloadFilePublications(this);\n\t\tloadCronJobPublications(this);\n\t\tloadFlagsUpdatePublications(this);\n\t\tloadFlagsPublications(this);\n\t\tloadMethodResponsePublications(this);\n\t\tloadNotificationPublications(this);\n\t\tloadReportBuilderReportPublications(this);\n\t\tloadReportBuilderLibraryPublications(this);\n\t\tloadUserGroupPublications(this);\n\t\tloadUserGuidePublications(this);\n\t\tloadReportBuilderDashboardBuilderPublications(this);\n\n\t\tthis.tailOpLog();\n\n\t\tsetInterval(() => {\n\t\t\tthis._oplogRetryCount = 0;\n\t\t}, 15000);\n\n\t\tsetInterval(() => {\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Subs', this._subscriptions.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Logged In Users', this._loggedInUsers.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue', this._mongoQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Hits', this._debugMongoQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Collections', JSON.stringify(this._debugMongoQueueCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Hits', this._debugOplogHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Collections', JSON.stringify(this._debugOplogCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.type.localeCompare(b.type)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Hits', this._debugSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Collections', JSON.stringify(this._debugSubCollections.sort((a, b) => a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub Hits', this._debugUnSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub All Hits', this._debugUnSubAllHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Cache Cleanup Hits', this._debugRemoveCacheHits);\n\t\t\t}\n\t\t\t\n\t\t\tthis._debugOplogHits = 0;\n\t\t\tthis._debugOplogCollections = [];\n\t\t\tthis._debugSubCollections = [];\n\t\t\tthis._debugMongoQueueHits = 0;\n\t\t\tthis._debugMongoQueueCollections = [];\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSubHits = 0;\n\t\t\tthis._debugUnSubHits = 0;\n\t\t\tthis._debugUnSubAllHits = 0;\n\t\t\tthis._debugRemoveCacheHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(async () => {\n\t\t\tthis._loggedInUsers = await LoggedInUsers.find();\n\t\n\t\t\tlet userCopy = deepCopy(this._loggedInUsers);\n\t\t\tfor (let i = this._loggedInUsers.length - 1; i >= 0; i--) {\n\t\t\t\tlet loggedInUser = userCopy[i];\n\n\t\t\t\tif (!loggedInUser.date || Date.now() - loggedInUser.date.getTime() > 120000) {\n\t\t\t\t\tif (this._websocketManager.getWebSocket(loggedInUser.id_ws)) {\n\t\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', this._websocketManager.getWebSocket(loggedInUser.id_ws)['user'], this._websocketManager.getWebSocket(loggedInUser.id_ws)['id_socket'], 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.unsubscribeAll(this._websocketManager.getWebSocket(loggedInUser.id_ws));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._subscriptions.forEach(sub => {\n\t\t\t\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\t\t\t\tif (client.id_socket === loggedInUser.id_ws) {\n\t\t\t\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tLoggedInUsers.deleteOne({_id: loggedInUser._id});\n\n\t\t\t\t\t\tif (this._loggedInUsers.findIndex(a => a._id === loggedInUser._id) >= 0) {\n\t\t\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.findIndex(a => a._id === loggedInUser._id), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (let i = 0; i < this._subscriptions.length; i++) {\n\t\t\t\tlet sub = this._subscriptions[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\tif (!this._loggedInUsers.some(a => a.id_ws === client.id_socket)) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, 30000);\n\n\t\tFlags.findOne({type: 'Enable Debug'}).then(flag => {\n\t\t\tif (flag && flag.value) {\n\t\t\t\tthis._enableDebug = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._enableDebug = false;\n\t\t\t}\n\t\t});\n\n\t\tthis.setCacheLimit();\n\t}\n\n\tprivate setCacheLimit() {\t\n\t\tif (process.env.IS_WORKERS_ENABLED === 'true') {\n\t\t\tthis._heapLimit = this._heapSize * 0.4;\n\t\t}\n\t\telse {\n\t\t\tthis._heapLimit = this._heapSize * 0.3; // Use 50% of total heap size\n\t\t}\n\t}\n\n\tpublic async invalidatePubsCache(collection: string, type: string) {\n\t\tResolveIOServer.getMongoManager().invalidateQueryCache(collection);\n\n\t\tlet collSubs = this._subscriptions.filter(a => a.collections.includes(collection));\n\n\t\tfor (let sub of collSubs) {\n\t\t\tif (sub.running) {\n\t\t\t\tsub.runAgain = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (this._publications[sub.publication].user_specific) {\n\t\t\t\tPromise.all(\n\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tthis.sendDataToOneWithRetry(ws, client.messageId, sub, collection, type);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t// Handle error\n\t\t\t\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During sendDataToOne - User Specific - Socket: ' + client.id_socket + ', User: ' + client.id_user + ', MessageId: ' + client.messageId + ', Pub: ' + sub.publication + ', Err: ' + JSON.stringify(err, null, 2));\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\telse {\n\t\t\t\tthis.sendDataToAllWithRetry(sub, collection, type);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async delay(ms: number) {\n\t\treturn new Promise(resolve => setTimeout(resolve, ms));\n\t}\n\n\tprivate async sendDataToAllWithRetry(sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tsub.running = true;\n\n\t\tdo {\n\t\t\tsub.runAgain = false;\n\t\t\tawait this.sendDataToAll(sub, collection, type);\n\n\t\t\tif (sub.runAgain) {\n\t\t\t\tawait this.delay(500); // delay, adjust as needed\n\t\t\t}\n\t\t} while (sub.runAgain);\n\n\t\tsub.running = false;\n\t}\n\n\tprivate async sendDataToOneWithRetry(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tsub.running = true;\n\n\t\tdo {\n\t\t\tsub.runAgain = false;\n\t\t\tawait this.sendDataToOne(ws, messageId, sub, collection, type);\n\n\t\t\tif (sub.runAgain) {\n\t\t\t\tawait this.delay(500); // delay, adjust as needed\n\t\t\t}\n\t\t} while (sub.runAgain);\n\t\tsub.running = false;\n\t}\n\n\t// Add all files to publications private object\n\tpublic publications(method: SubscriptionModel) {\n\t\tthis._publications = Object.assign(this._publications, method);\n\t}\n\n\t// Throttled `loggedInLatency` method\n\tpublic loggedInLatency(ws: WebSocket) {\n\t\tlet loggedInUser = this._loggedInUsers.find(a => a.id_ws === ws['id_socket']);\n\t\tif (!loggedInUser) return;\n\n\t\tconst now = new Date();\n\t\tconst existingEntry = this.latencyBuffer.get(ws['id_socket']);\n\t\tconst newLatency = ws['latency'];\n\n\t\t// Throttle updates: only update if time threshold has passed or latency has significantly changed\n\t\tif (\n\t\t\t!existingEntry || \n\t\t\t(now.getTime() - existingEntry.lastUpdate.getTime() >= this.LATENCY_UPDATE_THRESHOLD_MS) || \n\t\t\t(Math.abs(newLatency - existingEntry.latency) > 100) // Optional: log only significant changes\n\t\t) {\n\t\t\t// Update in-memory and buffer\n\t\t\tloggedInUser.date = now;\n\t\t\tthis.latencyBuffer.set(ws['id_socket'], { latency: newLatency, lastUpdate: now });\n\t\t}\n\t}\n\n\t// Method to flush buffered latency updates in bulk\n\tprivate async flushThrottledLatencyUpdates() {\n\t\tif (this.latencyBuffer.size === 0) return; // No updates to flush\n\n\t\tconst updates = Array.from(this.latencyBuffer.entries()).map(([id_ws, { latency, lastUpdate }]) => ({\n\t\t\tupdateOne: {\n\t\t\t\tfilter: { id_ws },\n\t\t\t\tupdate: { $set: { latency, date: lastUpdate } }\n\t\t\t}\n\t\t}));\n\n\t\ttry {\n\t\t\tawait LoggedInUsers.bulkWrite(updates);\n\t\t\tthis.latencyBuffer.clear(); // Clear buffer after successful update\n\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Throttled latency batch update successful', updates.length);\n\t\t\t}\n\t\t}\n\t\tcatch (error) {\n\t\t\tconsole.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error);\n\t\t\t// Optional: implement retry logic or logging for failed updates\n\t\t}\n\t}\n\n\t// Subscribe to publication\n\tpublic subscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugSubHits += 1;\n\n\t\tif (!this._debugSubCollections.some(a => a.publication === publication)) {\n\t\t\tthis._debugSubCollections.push({\n\t\t\t\tpublication: publication,\n\t\t\t\thits: 1\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tthis._debugSubCollections.find(a => a.publication === publication).hits += 1;\n\t\t}\n\n\t\tlet pub = this._publications[publication];\n\n\t\tif (!pub) {\n\t\t\tconsole.error(new Date(), 'No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tif (subscriptionData.length > 1 || subscriptionData[0]) {\n\t\t\t\tif (!pub.check) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Function For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (!pub.check._schema) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Schema For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet valObj = {};\n\t\t\t\t\tlet valKeys = Object.keys(pub.check._schema);\n\n\t\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\t\tfor (let i = 0; i < subscriptionData.length; i++) {\n\t\t\t\t\t\tvalObj[rootKeys[i]] = subscriptionData[i];\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpub.check.validate(valObj);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (errors) {\n\t\t\t\t\t\tif (errors) {\n\t\t\t\t\t\t\tconsole.error(new Date(), 'Error in Pub Check (' + publication + ')', errors);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (messageRoute !== 'Bypass') {\n\t\t\t\tlet urlData = messageRoute.split('/');\n\t\t\t\tlet urlModule = '';\n\t\t\t\tlet urlNext = urlData[0];\n\n\t\t\t\tif (urlData[0] === '') {\n\t\t\t\t\turlModule = '/';\n\t\t\t\t\turlNext = urlData[1];\n\t\t\t\t}\n\n\t\t\t\turlModule += urlNext;\n\n\t\t\t\tif (urlData.length > 1) {\n\t\t\t\t\turlModule += '/';\n\t\t\t\t}\n\n\t\t\t\tlet otherRouteSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_socket === ws['id_socket'] && b.messageRoute !== 'Bypass' && b.messageRoute !== '/' && b.messageRoute !== messageRoute && !b.messageRoute.startsWith(urlModule)));\n\n\t\t\t\tif (otherRouteSubs.length) {\n\t\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Detected Undestroyed Subscription - ' + this.serverConfig['CLIENT_NAME'], 'USER: ' + ws['user'] + ' (Socket: ' + ws['id_socket'] + ') ' + ' is on route: ' + messageRoute + ' but has the following subscriptions on other routes:' + JSON.stringify(otherRouteSubs, null, 2));\n\n\t\t\t\t\totherRouteSubs.forEach(otherSub => {\n\t\t\t\t\t\totherSub.clients.filter(a => a.id_socket === ws['id_socket']).forEach(client => {\n\t\t\t\t\t\t\tthis.unsubscribe(client.messageRoute, new Date(), ws, client.messageId, otherSub.publication, otherSub.subscriptionData);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet sub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\n\t\t\t// If sub found (another user watching same data), add client to same sub\n\t\t\tif (sub) {\n\t\t\t\tif (!sub.clients.some(a => a.id_socket === ws['id_socket'] && a.messageId === messageId)) {\n\t\t\t\t\tsub.clients.push({\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If sub not found, create new sub\n\t\t\telse {\n\t\t\t\tthis._subscriptions.push({\n\t\t\t\t\tpublication: publication,\n\t\t\t\t\tsubscriptionData: subscriptionData,\n\t\t\t\t\tcollections: this.getPublicationCollections(publication),\n\t\t\t\t\tclients: [{\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute,\n\t\t\t\t\t}],\n\t\t\t\t\tcacheId: 0,\n\t\t\t\t\trunning: false,\n\t\t\t\t\trunAgain: false\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!sub) {\n\t\t\t\tsub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\t\t\t}\n\n\t\t\t// Immediately send data to the new client\n\t\t\tthis.processSubscription(sub, ws, messageId);\n\t\t}\n\t}\n\n\tpublic async createLoggedInUser(id_ws: string): Promise<LoggedInUserModel> {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tlet ws = this._websocketManager.getWebSocket(id_ws);\n\n\t\t\tif (ws) {\n\t\t\t\tlet user = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tthis._loggedInUsers.push(user);\n\t\t\t\tLoggedInUsers.insertOne(user);\n\t\t\t\t\n\t\t\t\tresolve(user);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(null);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Unsubscribe from publication \n\tpublic unsubscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugUnSubHits += 1;\n\n\t\tif (!this._publications[publication]) {\n\t\t\tconsole.log('No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet sub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\n\t\t\tif (sub) {\n\t\t\t\tfor (let i = sub.clients.length - 1; i >= 0; i--) {\n\t\t\t\t\tif (sub.clients[i].id_user === ws['id_user'] && sub.clients[i].messageId === messageId && sub.clients[i].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(i, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// Unsubscribe from publication\n\tpublic async unsubscribeAll(ws: WebSocket) {\n\t\tthis._debugUnSubAllHits += 1;\n\n\t\tif (ws) {\n\t\t\t// Check if WebSocket has already been unsubscribed\n\t\t\tif (ws['isUnsubscribed']) {\n\t\t\t\treturn; // Skip if already unsubscribed\n\t\t\t}\n\t\t\t\n\t\t\t// Mark the WebSocket as unsubscribed to prevent further calls\n\t\t\tws['isUnsubscribed'] = true;\n\t\t\t\n\t\t\tif (this._loggedInUsers.map(a => a.id_ws).indexOf(ws['id_socket']) >= 0) {\n\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.map(a => a.id_ws).indexOf(ws['id_socket']), 1);\n\t\t\t}\n\t\t\tLoggedInUsers.deleteOne({ id_ws: ws['id_socket'] });\n\n\t\t\tlet userSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_user === ws['id_user'] && b.id_socket === ws['id_socket']));\n\n\t\t\tfor (let i = userSubs.length - 1; i >= 0; i--) {\n\t\t\t\tlet sub = userSubs[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tif (sub.clients[j].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._websocketManager.removeWebSocket(ws);\n\t\t}\n\t}\n\n\tpublic getActiveSubscriptions() {\n\t\treturn this._subscriptions;\n\t}\n\n\t// Get publication collection\n\tprivate getPublicationCollections(publication: string) {\n\t\treturn this._publications[publication].collections;\n\t}\n\n\t// Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)\n\tprivate async tailOpLog(resumeToken?: ResumeToken) {\n\t\tif (this._oplog$ && !this._oplog$.closed) {\n\t\t\tthis._oplog$.removeAllListeners();\n\t\t\tthis._oplog$.close();\n\t\t\tthis._oplog$ = null;\n\t\t}\n\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\n\t\tif (!this._oplog$ || this._oplog$.closed) {\n\t\t\tthis._oplogRetryCount += 1;\n\n\t\t\tif (this._oplogRetryCount > 5) {\n\t\t\t\tconsole.error('****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\tlet lastResumeToken: ResumeToken;\n\n\t\t\tif (resumeToken) {\n\t\t\t\tlastResumeToken = resumeToken;\n\t\t\t\ttry {\n\t\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch([], { resumeAfter: resumeToken });\n\t\t\t\t}\n\t\t\t\tcatch (errOp) {\n\t\t\t\t\tif (this._oplog$) {\n\t\t\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\t\t\tthis._oplog$.close();\n\t\t\t\t\t\tthis._oplog$ = null;\n\t\t\t\t\t}\n\t\t\t\t\tthis.tailOpLog(resumeToken);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch();\n\t\t\t}\n\n\t\t\tconsole.log(new Date(), 'oplog started');\n\n\t\t\tthis._oplog$.on('change', (doc: ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument) => {\n\t\t\t\tif (doc.ns) {\n\t\t\t\t\tlet collection = doc.ns.coll;\n\n\t\t\t\t\tif (!this._debugOplogCollections.some(a => a.collection === doc.ns.coll && a.type === doc.operationType)) {\n\t\t\t\t\t\tthis._debugOplogCollections.push({\n\t\t\t\t\t\t\tcollection: doc.ns.coll,\n\t\t\t\t\t\t\ttype: doc.operationType,\n\t\t\t\t\t\t\thits: 1\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._debugOplogCollections.find(a => a.collection === doc.ns.coll && a.type === doc.operationType).hits += 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection && !collection.endsWith('.versions') && !collection.startsWith('monitor-') && collection !== 'logs' && collection !== 'log-method-latencies' && collection !== 'log-subscriptions') {\n\t\t\t\t\t\tthis._debugOplogHits += 1;\n\n\t\t\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\t\t\tif (collection === 'support-tickets') {\n\t\t\t\t\t\t\t\tif (this.serverConfig['ROOT_URL'] === 'https://resolveio.com') {\n\t\t\t\t\t\t\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'sendSupportTicketEmail', doc.documentKey['_id']);\n\t\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'update' || doc.operationType === 'replace') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'update');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'delete');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection === 'flags') {\n\t\t\t\t\t\tFlags.findOne({ type: 'Enable Debug' }).then(flag => {\n\t\t\t\t\t\t\tif (flag && flag.value) {\n\t\t\t\t\t\t\t\tthis._enableDebug = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._enableDebug = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tlastResumeToken = doc._id;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tthis._oplog$.on('error', error => {\n\t\t\t\tconsole.log(new Date(), 'oplog error', error);\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('end', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog end');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog close');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async processSubscription(sub: ActiveSubscriptionModel, ws: WebSocket, messageId: number) {\n\t\tif (!this._publications[sub.publication].user_specific) {\t\t\t\n\t\t\tif (sub.cacheId) {\n\t\t\t\ttry {\n\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), dateReviver);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\tdata: cacheData\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\t\tsub.cacheId = 0;\n\n\t\t\t\t\tthis.sendDataToAllWithRetry(sub, '', 'newSub');\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (sub.running) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.sendDataToAllWithRetry(sub, '', 'newSub');\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (sub.running) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tthis.sendDataToOneWithRetry(ws, messageId, sub, '', 'newSub');\n\t\t}\n\t}\n\n\tprivate async sendDataToOne(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', sub.publication, '', '', sub.subscriptionData);\n\t\ttry {\n\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));\n\n\t\t\tlet res = await this._publications[sub.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ws['id_user'], ...sub.subscriptionData);\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: res\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, serverRes);\n\t\t}\n\t\tcatch (err) {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: err\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, serverRes);\n\n\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendDataToOne - WS)\\n\\nData \\n' + JSON.stringify(sub.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t}\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate async sendDataToAll(sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tif (!sub.clients.length) {\n\t\t\tif (sub.cacheId) {\n\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\tsub.cacheId = 0;\n\t\t\t}\n\n\t\t\tlet subIndex = this._subscriptions.findIndex(a => a.publication === sub.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(sub.subscriptionData));\n\t\t\tif (subIndex >= 0) {\n\t\t\t\tthis._subscriptions.splice(subIndex, 1);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Publication', sub.publication, '', '', sub.subscriptionData);\n\n\t\t\ttry {\n\t\t\t\tif (sub.publication !== 'superadminAPM' && sub.publication !== 'loggedInUsers') {\n\t\t\t\t\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));\n\t\t\t\t}\n\n\t\t\t\tlet res = await this._publications[sub.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ...sub.subscriptionData);\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tif (sub.cacheId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), dateReviver);\n\t\n\t\t\t\t\t\tif (JSON.stringify(cacheData) !== JSON.stringify(res)) {\n\t\t\t\t\t\t\tPromise.all(\n\t\t\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\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\tPromise.all(\n\t\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tPromise.all(\n\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t};\n\t\n\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tsub.cacheId = this._cacheId++;\n\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\n\t\t\t\t\tconst nodeCacheSize = this._nodeCache.getStats().vsize;\n\n\t\t\t\t\tif (nodeCacheSize > this._heapLimit) {\n\t\t\t\t\t\t// Evict cache entries as needed\n\t\t\t\t\t\tlet deleteCount = 0;\n\t\t\t\t\t\tconst subArr = this._subscriptions.filter(a => a.cacheId && !a.clients.length);\n\t\t\t\t\n\t\t\t\t\t\tfor (let zz = 0; zz < subArr.length; zz++) {\n\t\t\t\t\t\t\tthis._debugRemoveCacheHits += 1;\n\t\t\t\t\t\t\tthis._nodeCache.del(subArr[zz].cacheId);\n\t\t\t\t\t\t\tsubArr[zz].cacheId = 0;\n\t\t\t\t\t\t\tdeleteCount += 1;\n\t\t\t\t\t\t\tif (this._nodeCache.getStats().vsize < this._heapLimit * 0.75) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t'Sub Cache: ' +\n\t\t\t\t\t\t\t\t'Too Big - ' +\n\t\t\t\t\t\t\t\tsub.publication +\n\t\t\t\t\t\t\t\t' - Deleted: ' +\n\t\t\t\t\t\t\t\tdeleteCount +\n\t\t\t\t\t\t\t\t' - ' +\n\t\t\t\t\t\t\t\tnodeCacheSize\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\tcatch (err) {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tPromise.all(\n\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\t\tdata: err\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tthis._mainServer.getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendPubData)\\n\\nData \\n' + JSON.stringify(sub.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate sendWS(ws: WebSocket, data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\t}\n\n\tpublic getEnableDebug() {\n\t\treturn this._enableDebug;\n\t}\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/methods/flag-updates.ts"],"names":["loadFlagUpdatesMethods","methodManager","methods","exports"],"mappings":"aAEA,SAAgBA,uBAAuBC,GACtCA,EAAcC,QAAQ,EAErB,CACF,C,6FAJAC,QAAAH,uBAAAA","file":"flag-updates.js","sourcesContent":["import { MethodManager } from '../managers/method.manager';\n\nexport function loadFlagUpdatesMethods(methodManager: MethodManager) {\n\tmethodManager.methods({\n\t\t\n\t});\n}"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flag-update.model.js","sources":["models/flag-update.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"}
|
package/package.json
CHANGED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.loadFlagsUpdatePublications=void 0;var simpl_schema_1=require("simpl-schema"),flag_update_collection_1=require("src/collections/flag-update.collection");function loadFlagsUpdatePublications(e){e.publications({flagUpdateWithType:{function:function(e){return flag_update_collection_1.FlagUpdates.findOne({type:e})},check:new simpl_schema_1.default({flagType:{type:String}}),collections:["flag-updates"]}})}exports.loadFlagsUpdatePublications=loadFlagsUpdatePublications;
|
|
2
|
+
//# sourceMappingURL=flags-update.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/publications/flags-update.ts"],"names":["simpl_schema_1","require","flag_update_collection_1","loadFlagsUpdatePublications","subscriptionManager","publications","flagUpdateWithType","function","flagType","FlagUpdates","findOne","type","check","default","String","collections","exports"],"mappings":"+GAAA,IAAAA,eAAAC,QAAA,cAAA,EAEAC,yBAAAD,QAAA,wCAAA,EAEA,SAAgBE,4BAA4BC,GAC3CA,EAAoBC,aAAa,CAChCC,mBAAoB,CACnBC,SAAU,SAASC,GAClB,OAAON,yBAAAO,YAAYC,QAAQ,CAACC,KAAMH,CAAQ,CAAC,CAC5C,EACAI,MAAO,IAAIZ,eAAAa,QAAa,CACvBL,SAAU,CACTG,KAAMG,M,EAEP,EACDC,YAAa,CAAC,e,EAEf,CACF,CAdAC,QAAAb,4BAAAA","file":"flags-update.js","sourcesContent":["import SimpleSchema from 'simpl-schema';\nimport { SubscriptionManager } from '../managers/subscription.manager';\nimport { FlagUpdates } from 'src/collections/flag-update.collection';\n\nexport function loadFlagsUpdatePublications(subscriptionManager: SubscriptionManager) {\n\tsubscriptionManager.publications({\n\t\tflagUpdateWithType: {\n\t\t\tfunction: function(flagType: string) {\n\t\t\t\treturn FlagUpdates.findOne({type: flagType});\n\t\t\t},\n\t\t\tcheck: new SimpleSchema({\n\t\t\t\tflagType: {\n\t\t\t\t\ttype: String\n\t\t\t\t}\n\t\t\t}),\n\t\t\tcollections: ['flag-updates']\n\t\t}\n\t});\n}"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/publications/flags.ts"],"names":["simpl_schema_1","require","flag_collection_1","loadFlagsPublications","subscriptionManager","publications","flagWithType","function","flagType","Flags","findOne","type","check","default","String","collections","exports"],"mappings":"yGAAA,IAAAA,eAAAC,QAAA,cAAA,EAEAC,kBAAAD,QAAA,gCAAA,
|
|
1
|
+
{"version":3,"sources":["../../src/publications/flags.ts"],"names":["simpl_schema_1","require","flag_collection_1","loadFlagsPublications","subscriptionManager","publications","flagWithType","function","flagType","Flags","findOne","type","check","default","String","collections","exports"],"mappings":"yGAAA,IAAAA,eAAAC,QAAA,cAAA,EAEAC,kBAAAD,QAAA,gCAAA,EAEA,SAAgBE,sBAAsBC,GACrCA,EAAoBC,aAAa,CAChCC,aAAc,CACbC,SAAU,SAASC,GAClB,OAAON,kBAAAO,MAAMC,QAAQ,CAACC,KAAMH,CAAQ,CAAC,CACtC,EACAI,MAAO,IAAIZ,eAAAa,QAAa,CACvBL,SAAU,CACTG,KAAMG,M,EAEP,EACDC,YAAa,CAAC,Q,EAEf,CACF,CAdAC,QAAAb,sBAAAA","file":"flags.js","sourcesContent":["import SimpleSchema from 'simpl-schema';\nimport { SubscriptionManager } from '../managers/subscription.manager';\nimport { Flags } from '../collections/flag.collection';\n\nexport function loadFlagsPublications(subscriptionManager: SubscriptionManager) {\n\tsubscriptionManager.publications({\n\t\tflagWithType: {\n\t\t\tfunction: function(flagType: string) {\n\t\t\t\treturn Flags.findOne({type: flagType});\n\t\t\t},\n\t\t\tcheck: new SimpleSchema({\n\t\t\t\tflagType: {\n\t\t\t\t\ttype: String\n\t\t\t\t}\n\t\t\t}),\n\t\t\tcollections: ['flags']\n\t\t}\n\t});\n}"]}
|
package/publications.ts
CHANGED
|
@@ -17,6 +17,9 @@ export function SERVER_PUBLICATIONS(resolveioServer) {
|
|
|
17
17
|
filesIn: (id_files: string[]) => {
|
|
18
18
|
return <Observable<any>> resolveioServer.subscribe('filesIn', id_files);
|
|
19
19
|
},
|
|
20
|
+
flagUpdateWithType: (flagType: string) => {
|
|
21
|
+
return <Observable<any>> resolveioServer.subscribe('flagUpdateWithType', flagType);
|
|
22
|
+
},
|
|
20
23
|
flagWithType: (flagType: string) => {
|
|
21
24
|
return <Observable<any>> resolveioServer.subscribe('flagWithType', flagType);
|
|
22
25
|
},
|