@resolveio/server-lib 20.2.22 → 20.3.1

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.
@@ -0,0 +1,3 @@
1
+ import { WorkerTaskRequestModel } from '../models/worker-task-request.model';
2
+ import { MongoManagerCollection } from '../managers/mongo.manager';
3
+ export declare let WorkerTaskRequests: MongoManagerCollection<WorkerTaskRequestModel>;
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WorkerTaskRequests=void 0;var index_1=require("../index"),mongo_manager_1=require("../managers/mongo.manager"),simpl_schema_1=require("simpl-schema"),schema={_id:{type:String,optional:!0},__v:{type:Number,optional:!0},updatedAt:{type:Date,optional:!0},createdAt:{type:Date,optional:!0},method:{type:String},params:{type:Array},"params.$":{type:simpl_schema_1.default.oneOf(Object,String,Number,Boolean,Date),blackbox:!0},status:{type:String},id_user:{type:String},user:{type:String},id_ws:{type:String}};function initializeCollection(){var e;index_1.ResolveIOServer&&index_1.ResolveIOServer.getMainDB()?(e=new mongo_manager_1.MongoManagerModel({collectionName:"worker-task-requests",schema:schema,useVersionCollection:!1,useReportBuilder:!1,reportBuilderLookupTables:[],timestamps:!0,createLogs:!1,checkSchema:!0,collectionOptions:null}),exports.WorkerTaskRequests=e.collection_main,exports.WorkerTaskRequests.createIndex({createdAt:1},{expireAfterSeconds:7776e3})):setTimeout(function(){initializeCollection()},0)}exports.WorkerTaskRequests=null,initializeCollection();
2
+ //# sourceMappingURL=worker-task-request.collection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/collections/worker-task-request.collection.ts"],"names":["index_1","require","mongo_manager_1","simpl_schema_1","schema","_id","type","String","optional","__v","Number","updatedAt","Date","createdAt","method","params","Array","params.$","default","oneOf","Object","Boolean","blackbox","status","id_user","user","id_ws","initializeCollection","model","ResolveIOServer","getMainDB","MongoManagerModel","collectionName","useVersionCollection","useReportBuilder","reportBuilderLookupTables","timestamps","createLogs","checkSchema","collectionOptions","exports","WorkerTaskRequests","collection_main","createIndex","expireAfterSeconds","setTimeout"],"mappings":"sGACA,IAAAA,QAAAC,QAAA,UAAA,EACAC,gBAAAD,QAAA,2BAAA,EACAE,eAAAF,QAAA,cAAA,EAEIG,OAAc,CACjBC,IAAK,CACJC,KAAMC,OACNC,SAAU,CAAA,C,EAEXC,IAAK,CACJH,KAAMI,OACNF,SAAU,CAAA,C,EAEXG,UAAW,CACVL,KAAMM,KACNJ,SAAU,CAAA,C,EAEXK,UAAW,CACVP,KAAMM,KACNJ,SAAU,CAAA,C,EAEXM,OAAQ,CACPR,KAAMC,M,EAEPQ,OAAQ,CACPT,KAAMU,K,EAEPC,WAAY,CACXX,KAAMH,eAAAe,QAAaC,MAAMC,OAAQb,OAAQG,OAAQW,QAAST,IAAI,EAC9DU,SAAU,CAAA,C,EAEXC,OAAQ,CACPjB,KAAMC,M,EAEPiB,QAAS,CACRlB,KAAMC,M,EAEPkB,KAAM,CACLnB,KAAMC,M,EAEPmB,MAAO,CACNpB,KAAMC,M,GAQR,SAASoB,uBACR,IACOC,EADH5B,QAAA6B,iBAAmB7B,QAAA6B,gBAAgBC,UAAS,GACzCF,EAAQ,IAAI1B,gBAAA6B,kBAA0C,CAC3DC,eAAgB,uBAChB5B,OAAQA,OACR6B,qBAAsB,CAAA,EACtBC,iBAAkB,CAAA,EAClBC,0BAA2B,GAC3BC,WAAY,CAAA,EACZC,WAAY,CAAA,EACZC,YAAa,CAAA,EACbC,kBAAmB,I,CACnB,EACDC,QAAAC,mBAAqBb,EAAMc,gBAC3BF,QAAAC,mBAAmBE,YAAY,CAAC9B,UAAW,CAAC,EAAG,CAAC+B,mBAAoB,MAAiB,CAAC,GAGtFC,WAAW,WACVlB,qBAAoB,CACrB,EAAG,CAAC,CAEN,CAzBWa,QAAAC,mBAAqE,KAEhFd,qBAAoB","file":"worker-task-request.collection.js","sourcesContent":["import { WorkerTaskRequestModel } from '../models/worker-task-request.model';\nimport { ResolveIOServer } from '../index';\nimport { MongoManagerCollection, MongoManagerModel } from '../managers/mongo.manager';\nimport SimpleSchema from 'simpl-schema';\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\tmethod: {\n\t\ttype: String\n\t},\n\tparams: {\n\t\ttype: Array, // Declaring params as an array\n\t},\n\t'params.$': {\n\t\ttype: SimpleSchema.oneOf(Object, String, Number, Boolean, Date), // Allowing multiple types\n\t\tblackbox: true // Blackbox for the object type\n\t},\n\tstatus: {\n\t\ttype: String\n\t},\n\tid_user: {\n\t\ttype: String\n\t},\n\tuser: {\n\t\ttype: String\n\t},\n\tid_ws: {\n\t\ttype: String\n\t}\n};\n\nexport let WorkerTaskRequests: MongoManagerCollection<WorkerTaskRequestModel> = null;\n\ninitializeCollection();\n\nfunction initializeCollection() {\n\tif (ResolveIOServer && ResolveIOServer.getMainDB()) {\n\t\tconst model = new MongoManagerModel<WorkerTaskRequestModel>({\n\t\t\tcollectionName: 'worker-task-requests',\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\tWorkerTaskRequests = model.collection_main;\n\t\tWorkerTaskRequests.createIndex({createdAt: 1}, {expireAfterSeconds: 60 * 60 * 24 * 90});\n\t}\n\telse {\n\t\tsetTimeout(() => {\n\t\t\tinitializeCollection();\n\t\t}, 0);\n\t}\n}"]}
@@ -0,0 +1,3 @@
1
+ import { WorkerTaskResponseModel } from '../models/worker-task-response.model';
2
+ import { MongoManagerCollection } from '../managers/mongo.manager';
3
+ export declare let WorkerTaskResponses: MongoManagerCollection<WorkerTaskResponseModel>;
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WorkerTaskResponses=void 0;var index_1=require("../index"),mongo_manager_1=require("../managers/mongo.manager"),simpl_schema_1=require("simpl-schema"),schema={_id:{type:String,optional:!0},__v:{type:Number,optional:!0},updatedAt:{type:Date,optional:!0},createdAt:{type:Date,optional:!0},id_request:{type:String},data:{type:Array},"data.$":{type:simpl_schema_1.default.oneOf(Object,String,Number,Boolean,Date),blackbox:!0},id_user:{type:String},user:{type:String},id_ws:{type:String}};function initializeCollection(){var e;index_1.ResolveIOServer&&index_1.ResolveIOServer.getMainDB()?(e=new mongo_manager_1.MongoManagerModel({collectionName:"worker-task-responses",schema:schema,useVersionCollection:!1,useReportBuilder:!1,reportBuilderLookupTables:[],timestamps:!0,createLogs:!1,checkSchema:!0,collectionOptions:null}),exports.WorkerTaskResponses=e.collection_main,exports.WorkerTaskResponses.createIndex({createdAt:1},{expireAfterSeconds:7776e3})):setTimeout(function(){initializeCollection()},0)}exports.WorkerTaskResponses=null,initializeCollection();
2
+ //# sourceMappingURL=worker-task-response.collection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/collections/worker-task-response.collection.ts"],"names":["index_1","require","mongo_manager_1","simpl_schema_1","schema","_id","type","String","optional","__v","Number","updatedAt","Date","createdAt","id_request","data","Array","data.$","default","oneOf","Object","Boolean","blackbox","id_user","user","id_ws","initializeCollection","model","ResolveIOServer","getMainDB","MongoManagerModel","collectionName","useVersionCollection","useReportBuilder","reportBuilderLookupTables","timestamps","createLogs","checkSchema","collectionOptions","exports","WorkerTaskResponses","collection_main","createIndex","expireAfterSeconds","setTimeout"],"mappings":"uGACA,IAAAA,QAAAC,QAAA,UAAA,EACAC,gBAAAD,QAAA,2BAAA,EACAE,eAAAF,QAAA,cAAA,EAEIG,OAAc,CACjBC,IAAK,CACJC,KAAMC,OACNC,SAAU,CAAA,C,EAEXC,IAAK,CACJH,KAAMI,OACNF,SAAU,CAAA,C,EAEXG,UAAW,CACVL,KAAMM,KACNJ,SAAU,CAAA,C,EAEXK,UAAW,CACVP,KAAMM,KACNJ,SAAU,CAAA,C,EAEXM,WAAY,CACXR,KAAMC,M,EAEPQ,KAAM,CACLT,KAAMU,K,EAEPC,SAAU,CACTX,KAAMH,eAAAe,QAAaC,MAAMC,OAAQb,OAAQG,OAAQW,QAAST,IAAI,EAC9DU,SAAU,CAAA,C,EAEXC,QAAS,CACRjB,KAAMC,M,EAEPiB,KAAM,CACLlB,KAAMC,M,EAEPkB,MAAO,CACNnB,KAAMC,M,GAQR,SAASmB,uBACR,IACOC,EADH3B,QAAA4B,iBAAmB5B,QAAA4B,gBAAgBC,UAAS,GACzCF,EAAQ,IAAIzB,gBAAA4B,kBAA2C,CAC5DC,eAAgB,wBAChB3B,OAAQA,OACR4B,qBAAsB,CAAA,EACtBC,iBAAkB,CAAA,EAClBC,0BAA2B,GAC3BC,WAAY,CAAA,EACZC,WAAY,CAAA,EACZC,YAAa,CAAA,EACbC,kBAAmB,I,CACnB,EACDC,QAAAC,oBAAsBb,EAAMc,gBAC5BF,QAAAC,oBAAoBE,YAAY,CAAC7B,UAAW,CAAC,EAAG,CAAC8B,mBAAoB,MAAiB,CAAC,GAGvFC,WAAW,WACVlB,qBAAoB,CACrB,EAAG,CAAC,CAEN,CAzBWa,QAAAC,oBAAuE,KAElFd,qBAAoB","file":"worker-task-response.collection.js","sourcesContent":["import { WorkerTaskResponseModel } from '../models/worker-task-response.model';\nimport { ResolveIOServer } from '../index';\nimport { MongoManagerCollection, MongoManagerModel } from '../managers/mongo.manager';\nimport SimpleSchema from 'simpl-schema';\n\nlet schema: any = {\n\t_id: {\n\t\ttype: String,\n\t\toptional: true\n\t},\n\t__v: {\n\t\ttype: Number,\n\t\toptional: true\n\t},\n\tupdatedAt: {\n\t\ttype: Date,\n\t\toptional: true\n\t},\n\tcreatedAt: {\n\t\ttype: Date,\n\t\toptional: true\n\t},\n\tid_request: {\n\t\ttype: String\n\t},\n\tdata: {\n\t\ttype: Array, // Declaring params as an array\n\t},\n\t'data.$': {\n\t\ttype: SimpleSchema.oneOf(Object, String, Number, Boolean, Date), // Allowing multiple types\n\t\tblackbox: true // Blackbox for the object type\n\t},\n\tid_user: {\n\t\ttype: String\n\t},\n\tuser: {\n\t\ttype: String\n\t},\n\tid_ws: {\n\t\ttype: String\n\t}\n};\n\nexport let WorkerTaskResponses: MongoManagerCollection<WorkerTaskResponseModel> = null;\n\ninitializeCollection();\n\nfunction initializeCollection() {\n\tif (ResolveIOServer && ResolveIOServer.getMainDB()) {\n\t\tconst model = new MongoManagerModel<WorkerTaskResponseModel>({\n\t\t\tcollectionName: 'worker-task-responses',\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\tWorkerTaskResponses = model.collection_main;\n\t\tWorkerTaskResponses.createIndex({createdAt: 1}, {expireAfterSeconds: 60 * 60 * 24 * 90});\n\t}\n\telse {\n\t\tsetTimeout(() => {\n\t\t\tinitializeCollection();\n\t\t}, 0);\n\t}\n}"]}
@@ -20,11 +20,13 @@ export declare class MethodManager {
20
20
  private _sendQueue;
21
21
  private _runningQueue;
22
22
  private _monitorManagerFunction;
23
+ private _isWorkersEnabled;
24
+ private _isWorkerInstance;
23
25
  private _debugCallMethodInternalHits;
24
26
  private _debugCallMethodHits;
25
27
  private _debugCallMethodCronJobHits;
26
28
  private _debugSendQueueHits;
27
- constructor(mainServer: any, serverConfig: any, clientDir: any, monitorManagerFunction: MonitorManagerFunction);
29
+ constructor(mainServer: any, serverConfig: any, clientDir: any, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled: any, isWorkerInstance: any);
28
30
  getMainServer(): ResolveIOMainServer;
29
31
  methods(method: MethodModel): void;
30
32
  callMethodCron(method: string, ...methodData: any[]): any;
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,n,r,i){return new(r=r||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 r?t:new r(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,r){var i,s,a,d={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(;d=l&&t[l=0]?0:d;)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 d.label++,{value:t[1],done:!1};case 5:d.label++,s=t[1],t=[0];continue;case 7:t=d.ops.pop(),d.trys.pop();continue;default:if(!(a=0<(a=d.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){d=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))d.label=t[1];else if(6===t[0]&&d.label<a[1])d.label=a[1],a=t;else{if(!(a&&d.label<a[2])){a[2]&&d.ops.pop(),d.trys.pop();continue}d.label=a[2],d.ops.push(t)}}t=r.call(n,d)}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}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var n,r=0,i=t.length;r<i;r++)!n&&r in t||((n=n||Array.prototype.slice.call(t,0,r))[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),method_response_collection_1=require("../collections/method-response.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),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,n){var r=this;this._methods={},this._sendQueue=[],this._runningQueue=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this.serverConfig=t,this.clientDir=o,this._monitorManagerFunction=n,(0,init_1.loadServerInit)(),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){r._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",r._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",r._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",r._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",r._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",r._debugCallMethodCronJobHits)),r._debugCallMethodInternalHits=0,r._debugCallMethodHits=0,r._debugCallMethodCronJobHits=0,r._debugSendQueueHits=0,r._debugSendQueueHits=0},6e4),setInterval(function(){if(!r._runningQueue&&r._sendQueue.length){r._runningQueue=!0;for(var e=r._sendQueue.length-1;0<=e;e--)!function(e){r._debugSendQueueHits+=1;var t,o=r._mainServer.getWS(r._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=r._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&r._mainServer.unsubscribeWS(o)}),"reportBuilderGetResults"!==t.method&&"reportBuilderGetDistinctValue"!==t.method&&"reportBuilderBuildTree"!==t.method&&"generatePDF"!==t.method&&"getWOOfflineData"!==t.method&&"countQuery"!==t.method&&"countWithQuery"!==t.method&&"countCollectionWithQuery"!==t.method&&"find"!==t.method&&"findOne"!==t.method&&"findWithOptions"!==t.method&&"uploadFileAndSave"!==t.method&&"getDrivers"!==t.method&&"processAirdropDistribution"!==t.method&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([t.methodData,t.data]))<2e5?JSON.stringify([t.methodData,t.data],null,2):"Too Big",method:t.method,id_user:o.id_user||"",user:o.user||"",messageId:t.data.messageId,route:""}),method_response_collection_1.MethodResponses.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,id_user:o.id_user||"",message_id:t.data.messageId,response:(0,common_1.getBinarySize)(JSON.stringify(t.data))<2e5?t.data:{error:"Too Big"},method:t.method,date:t.date})):r._sendQueue.splice(e,1)}(e);r._runningQueue=!1}},25)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,o=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<n.length||n[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<n.length;a++)i[s[a]]=n[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 d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",n);return(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],n,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(d),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(n,r,i,s,a){for(var e,t=this,d=[],o=5;o<arguments.length;o++)d[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<d.length||d[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),l={messageId:s,hasError:!0,data:"Internal Error"},n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),void this.sendWS(r,i,a,d,l);for(var l,c={},h=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),u=0;u<d.length;u++)c[h[u]]=d[u];try{this._methods[a].check.validate(c)}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(c,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}))}}var _=this._monitorManagerFunction.startMonitorFunction("Method",a,r.user||"",r.id_socket||"",d);(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:r.id_user,user:r.user,id_ws:r.id_socket})],d,!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(_),t={messageId:s,hasError:!1,data:o},this.sendWS(r,i,a,d,t),n)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(_),t.sendWS(r,i,a,d,{messageId:s,hasError:!0,data:e}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(d,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))})}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n})},MethodManager.prototype.callMethodInternal=function(t){for(var o=this,n=[],e=1;e<arguments.length;e++)n[e-1]=arguments[e];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<n.length||n[0]&&"function"!=typeof n[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([n]))<2e5?JSON.stringify([n],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var r="function"==typeof n[n.length-1]?n.slice(0,-1):n,i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",r),s=(s=this._methods[t].function).call.apply(s,__spreadArray([Object.assign({},this,MethodManager.prototype)],r,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(i),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(i),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e});return n[n.length-1]&&"function"==typeof n[n.length-1]&&s.then(function(e){return n[n.length-1](null,e)},function(e){return n[n.length-1](e,null)}),s},MethodManager.prototype.sendWS=function(e,t,o,n,r){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:n,data:r,date:t})},MethodManager.prototype.sendEmail=function(n,r,i,s,a,d,l,c){var o=this;return void 0===c&&(c=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(n=!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||n.match(new RegExp(/\@resolveio\.com/))?n:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||c?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:d||this.serverConfig.MAIL_FROM,to:n,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+r,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:n,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:n,success:!0,verified:!1})}):console.log("Send email",n,r,i,s,a,d),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?n(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?n(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?n(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?n(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,s){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var s,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,i=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(r,c)}catch(e){t=[6,e],i=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,s=t.length;n<s;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),method_response_collection_1=require("../collections/method-response.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,o,r,n,s){var i=this;this._methods={},this._sendQueue=[],this._runningQueue=!1,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this.serverConfig=t,this.clientDir=o,this._monitorManagerFunction=r,this._isWorkersEnabled=n,this._isWorkerInstance=s,(0,init_1.loadServerInit)(),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),this._isWorkersEnabled&&!this._isWorkerInstance||(setInterval(function(){i._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",i._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",i._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",i._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",i._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",i._debugCallMethodCronJobHits)),i._debugCallMethodInternalHits=0,i._debugCallMethodHits=0,i._debugCallMethodCronJobHits=0,i._debugSendQueueHits=0,i._debugSendQueueHits=0},6e4),setInterval(function(){if(!i._runningQueue&&i._sendQueue.length){i._runningQueue=!0;for(var e=i._sendQueue.length-1;0<=e;e--)!function(e){i._debugSendQueueHits+=1;var t,o=i._mainServer.getWS(i._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=i._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&i._mainServer.unsubscribeWS(o)}),"reportBuilderGetResults"!==t.method&&"reportBuilderGetDistinctValue"!==t.method&&"reportBuilderBuildTree"!==t.method&&"generatePDF"!==t.method&&"getWOOfflineData"!==t.method&&"countQuery"!==t.method&&"countWithQuery"!==t.method&&"countCollectionWithQuery"!==t.method&&"find"!==t.method&&"findOne"!==t.method&&"findWithOptions"!==t.method&&"uploadFileAndSave"!==t.method&&"getDrivers"!==t.method&&"processAirdropDistribution"!==t.method&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([t.methodData,t.data]))<2e5?JSON.stringify([t.methodData,t.data],null,2):"Too Big",method:t.method,id_user:o.id_user||"",user:o.user||"",messageId:t.data.messageId,route:""}),method_response_collection_1.MethodResponses.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,id_user:o.id_user||"",message_id:t.data.messageId,response:(0,common_1.getBinarySize)(JSON.stringify(t.data))<2e5?t.data:{error:"Too Big"},method:t.method,date:t.date})):i._sendQueue.splice(e,1)}(e);i._runningQueue=!1}},25))}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,o=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<r.length||r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var s={},i=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<r.length;a++)s[i[a]]=r[a];try{this._methods[t].check.validate(s)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(s,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r);return(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],r,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(c),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(c),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,s,i,a){for(var e,t,o,c,l=this,d=[],h=5;h<arguments.length;h++)d[h-5]=arguments[h];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<d.length||d[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,s,a,d,u={messageId:i,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),u={messageId:i,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,s,a,d,u);for(var u,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),m=0;m<d.length;m++)_[g[m]]=d[m];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,s,a,d,u={messageId:i,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}this._isWorkersEnabled&&!this._isWorkerInstance?(console.log("Workers are enabled. Delegating task to worker."),t=(0,mongo_manager_1.objectIdHexString)(),worker_task_request_collection_1.WorkerTaskRequests.create({_id:t,method:a,params:d,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket}),(o=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":t}}],{fullDocument:"updateLookup"})).on("change",function(e){"insert"===e.operationType&&(e=e.fullDocument,e={messageId:i,hasError:e.has_error,data:e.data},l.sendWS(n,s,a,d,e),o.close())}),o.on("error",function(e){console.error("Error watching worker responses:",e),o.close()}),o.on("close",function(){console.log("Change stream closed for task:",t)})):(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",d),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],d,!1)).then(function(o){return __awaiter(l,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(c),t={messageId:i,hasError:!1,data:o},this.sendWS(n,s,a,d,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){l._monitorManagerFunction.finishMonitorFunction(c),l.sendWS(n,s,a,d,{messageId:i,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"processAirdropDistribution"!==a&&l.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+l.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(d,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),this.sendWS(n,s,a,d,u={messageId:i,hasError:!0,data:"Internal Error"}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,o=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<r.length||r[0]&&"function"!=typeof r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r]))<2e5?JSON.stringify([r],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var s,i,a="function"==typeof r[r.length-1]?r.slice(0,-1):r,c=null;return c=this._isWorkersEnabled&&!this._isWorkerInstance?(s=(0,mongo_manager_1.objectIdHexString)(),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:a,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket}),new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()}),r.on("close",function(){console.log("Change stream closed for task:",s)})})):(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],a,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(i),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(i),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),r[r.length-1]&&"function"==typeof r[r.length-1]&&c.then(function(e){return r[r.length-1](null,e)},function(e){return r[r.length-1](e,null)}),c},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:r,data:n,date:t})},MethodManager.prototype.sendEmail=function(r,n,s,i,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:s,html:i,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,s,i,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
2
2
  //# sourceMappingURL=method.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","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","_this","_methods","_sendQueue","_runningQueue","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","length","i","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","JSON","stringify","data","error","unsubscribeWS","method","Logs","insertOne","_id","objectIdHexString","type","collection","id_document","payload","getBinarySize","methodData","id_user","messageId","route","MethodResponses","create","__v","message_id","response","date","splice","getMainServer","methods","Object","assign","callMethodCron","_i","arguments","skipValidation","check","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","validate","errors","monitor","startMonitorFunction","_a","function","call","apply","__spreadArray","then","res","finishMonitorFunction","methodErrs","callMethod","id_methodLatency","messageDate","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","functionMethodData","slice","promise","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","Promise","resolve","reject","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"wqDACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,Q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EAAG,QAAS,SAAC/B,EAAKrB,GACxEqB,EACHe,EAAOf,CAAG,EAGVc,EAAQnC,CAAG,CAEb,CAAC,EAGGtJ,GAAG2M,WAAW5M,KAAK6M,KAAKhK,EAAKF,UAAY,aAAegK,CAAS,CAAC,GACrE1M,GAAGyM,SAAS1M,KAAK6M,KAAKhK,EAAKF,UAAY,aAAegK,CAAS,EAAG,QAAS,SAAC/B,EAAKrB,GAC5EqB,EACHe,EAAOf,CAAG,EAGVc,EAAQnC,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEO/G,cAAAd,UAAAqL,UAAP,SAAiBJ,GAAjB,IAAA9J,EAAAvB,KACC,OAAO,IAAImK,QAAQ,SAACC,EAASC,GACxB1L,GAAG2M,WAAW5M,KAAK6M,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjE1M,GAAGyM,SAAS1M,KAAK6M,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAAC/B,EAAKrB,GACzEqB,EACHe,EAAOf,CAAG,EAGVc,EAAQnC,CAAG,CAEb,CAAC,EAGGtJ,GAAG2M,WAAW5M,KAAK6M,KAAKhK,EAAKF,UAAY,aAAegK,CAAS,CAAC,GACrE1M,GAAGyM,SAAS1M,KAAK6M,KAAKhK,EAAKF,UAAY,aAAegK,CAAS,EAAG,SAAU,SAAC/B,EAAKrB,GAC7EqB,EACHe,EAAOf,CAAG,EAGVc,EAAQnC,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACD/G,aAAA,EAAC,GA9gBYC,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';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\n\t}\n\n\tpublic s3() : S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1() : S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\t// Fixtures\n\t\tloadServerInit();\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\t\t\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().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\tdate: sendItem.date\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 25);\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\t\t\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + 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\treturn methodErrs;\n\t\t});\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\t\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\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\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\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\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.then(async (res) => {\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, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\tif (latency) {\n\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}\n\t\t\t}\n\t\t}, err => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\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, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\tif (method !== 'processAirdropDistribution') {\n\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}\n\t\t});\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof(methodData[0]) !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + 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\treturn methodErrs;\n\t\t});\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_sendQueue","_runningQueue","_isWorkersEnabled","_isWorkerInstance","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","length","i","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","JSON","stringify","data","error","unsubscribeWS","method","Logs","insertOne","_id","objectIdHexString","type","collection","id_document","payload","getBinarySize","methodData","id_user","messageId","route","MethodResponses","create","__v","message_id","response","date","splice","getMainServer","methods","Object","assign","callMethodCron","_i","arguments","skipValidation","check","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","validate","errors","monitor","startMonitorFunction","_a","function","call","apply","__spreadArray","then","res","finishMonitorFunction","methodErrs","callMethod","id_methodLatency","messageDate","taskId_1","changeStream_1","monitor_2","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","WorkerTaskRequests","params","status","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","taskResponse","has_error","close","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","taskId_2","monitor_3","functionMethodData","slice","promise","Promise","resolve","reject","changeStream","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"wqDACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,6BAAAd,QAAA,2CAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,iBAAAhB,QAAA,+BAAA,EAEAiB,gCAAAjB,QAAA,8CAAA,EACAkB,OAAAlB,QAAA,iBAAA,EACAmB,iBAAAnB,QAAA,2BAAA,EACAoB,UAAApB,QAAA,oBAAA,EACAqB,UAAArB,QAAA,oBAAA,EACAsB,2BAAAtB,QAAA,yCAAA,EACAuB,gBAAAvB,QAAA,iBAAA,EAEAwB,YAAAxB,QAAA,oBAAA,EACAyB,iCAAAzB,QAAA,+CAAA,EACA0B,kCAAA1B,QAAA,gDAAA,EAEA2B,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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,SAASpO,KAAKuO,KAAKtL,EAAKJ,UAAY,aAAewL,CAAS,EAAG,QAAS,SAAClC,EAAKtC,GAC5EsC,EACHS,EAAOT,CAAG,EAGVQ,EAAQ9C,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEOnH,cAAAd,UAAA6M,UAAP,SAAiBJ,GAAjB,IAAApL,EAAAzB,KACC,OAAO,IAAIkL,QAAQ,SAACC,EAASC,GACxB3M,GAAGqO,WAAWtO,KAAKuO,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEpO,GAAGmO,SAASpO,KAAKuO,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAAClC,EAAKtC,GACzEsC,EACHS,EAAOT,CAAG,EAGVQ,EAAQ9C,CAAG,CAEb,CAAC,EAGG5J,GAAGqO,WAAWtO,KAAKuO,KAAKtL,EAAKJ,UAAY,aAAewL,CAAS,CAAC,GACrEpO,GAAGmO,SAASpO,KAAKuO,KAAKtL,EAAKJ,UAAY,aAAewL,CAAS,EAAG,SAAU,SAAClC,EAAKtC,GAC7EsC,EACHS,EAAOT,CAAG,EAGVQ,EAAQ9C,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDnH,aAAA,EAAC,GA/mBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { MethodResponses } from '../collections/method-response.collection';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WorkerTaskRequests } from '../collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from '../collections/worker-task-response.collection';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\n\t}\n\n\tpublic s3() : S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1() : S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._mainServer = mainServer;\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\t// Fixtures\n\t\tloadServerInit();\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\n\n\t\tif (mainServer.sesMail) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tsetInterval(() => {\n\t\t\t\tif (this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t\t}\n\n\t\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\t\tthis._debugCallMethodHits = 0;\n\t\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\t\tthis._debugSendQueueHits = 0;\n\t\t\t\tthis._debugSendQueueHits = 0;\n\t\t\t}, 60000);\n\n\t\t\tsetInterval(() => {\n\t\t\t\tif (!this._runningQueue) {\n\t\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tdate: sendItem.date\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, 25);\n\t\t}\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + 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\treturn methodErrs;\n\t\t});\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && !this._isWorkerInstance) {\n\t\t\tconsole.log('Workers are enabled. Delegating task to worker.');\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\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\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\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\tchangeStream.on('close', () => {\n\t\t\t\tconsole.log('Change stream closed for task:', taskId);\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, err => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof(methodData[0]) !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\t\tlet promise = null;\n\n\t\tif (this._isWorkersEnabled && !this._isWorkerInstance) {\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\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\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('close', () => {\n\t\t\t\t\tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t}, methodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\t\t\t});\n\t\t}\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
@@ -0,0 +1,10 @@
1
+ import { CollectionDocument } from './collection-document.model';
2
+ export interface WorkerTaskRequestModel extends CollectionDocument {
3
+ method: string;
4
+ params: any;
5
+ status: WorkerTaskRequestStatusType;
6
+ id_user: string;
7
+ user: string;
8
+ id_ws: string;
9
+ }
10
+ export type WorkerTaskRequestStatusType = 'pending' | 'processing' | 'complete';
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});
2
+ //# sourceMappingURL=worker-task-request.model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-task-request.model.js","sources":["models/worker-task-request.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"}
@@ -0,0 +1,9 @@
1
+ import { CollectionDocument } from './collection-document.model';
2
+ export interface WorkerTaskResponseModel extends CollectionDocument {
3
+ id_request: string;
4
+ has_error: boolean;
5
+ data: any;
6
+ id_user: string;
7
+ user: string;
8
+ id_ws: string;
9
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});
2
+ //# sourceMappingURL=worker-task-response.model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-task-response.model.js","sources":["models/worker-task-response.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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.2.22",
3
+ "version": "20.3.1",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",
package/server-app.d.ts CHANGED
@@ -32,9 +32,15 @@ export default class ResolveIOMainServer {
32
32
  private _lastErrorMsg;
33
33
  private _debugMsgRecv;
34
34
  private _debugMsgQueue;
35
+ private _isWorkersEnabled;
36
+ private _isWorkerInstance;
35
37
  private _safeShutdown;
36
38
  constructor(mainServer: any, serverConfig: any, clientRoutes: any, clientDir: any, sesMail: any, standardProgram: any, publicProgram?: boolean);
39
+ private startServerInstance;
40
+ private startWorkerInstance;
37
41
  private safeShutdown;
42
+ getIsWorkersEnabled(): boolean;
43
+ getIsWorkerInstance(): boolean;
38
44
  getWS(id_ws: string): WebSocket.WebSocket;
39
45
  getWSList(): any[];
40
46
  getWSUserList(): any[];
@@ -45,7 +51,6 @@ export default class ResolveIOMainServer {
45
51
  getMonitorManager(): MonitorManager;
46
52
  getRebootFlag(): boolean;
47
53
  private createServer;
48
- private setUpMongo;
49
54
  private listen;
50
55
  unsubscribeWS(ws: WebSocket): void;
51
56
  getApp(): express.Application;
package/server-app.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,n,o,s){return new(o=o||Promise)(function(r,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?r(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,i,a,u={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(r){return function(e){var t=[r,e];if(s)throw new TypeError("Generator is already executing.");for(;u=l&&t[l=0]?0:u;)try{if(s=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return u.label++,{value:t[1],done:!1};case 5:u.label++,i=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],i=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||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))},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),mongo_manager_1=require("./managers/mongo.manager"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),method_response_collection_1=require("./collections/method-response.collection"),log_collection_1=require("./collections/log.collection"),log_method_latency_collection_1=require("./collections/log-method-latency.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),index_1=require("./index"),mongodb_1=require("mongodb"),ResolveIOMainServer=function(){function ResolveIOMainServer(e,t,r,n,o,s,i){void 0===i&&(i=!1);var a=this;this._offlineUpdates=[],this._msgQueue=[],this._msgQueueRunning=!1,this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._safeShutdown=!1,this._serverConfig=t,this._clientRoutes=r,this._clientDir=n,this.sesMail=o,this.standardProgram=s,this.publicProgram=i,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager(e,t),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,setInterval(function(){a._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Queue Length",a._msgQueue.length),console.log(new Date,"Server App","Msg Recv Hits",a._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",a._debugMsgQueue)),a._debugMsgQueue=0,a._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(n,o){return __awaiter(a,void 0,void 0,function(){var t,r=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,o]),t=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<t&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<t&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<t&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:n&&"StatusError"!==n.name&&""!==n.message&&60<t&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(r){return __awaiter(a,void 0,void 0,function(){var t=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(r,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+this._serverConfig.CLIENT_NAME,JSON.stringify([r.name,r.message,r.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGTERM",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGQUIT",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||t.PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||t.PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,t,r){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST"),t.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),t.setHeader("Access-Control-Allow-Credentials","false"),r()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,t),(0,health_1.setupHealthRoutes)(this._app,t),"ResolveIO"!==t.CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,t),"DEBUG"===this.LOGGER&&console.log("Setup express routes")}return ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._msgQueue.length||this._msgQueueRunning||this._offlineUpdates.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._msgQueue.length,this._msgQueueRunning,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):index_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)})},ResolveIOMainServer.prototype.getWS=function(t){return Array.from(this._serverWSS.clients).filter(function(e){return e.id_socket===t})[0]},ResolveIOMainServer.prototype.getWSList=function(){var t=[];return this._serverWSS.clients.forEach(function(e){t.push(e.id_socket)}),t},ResolveIOMainServer.prototype.getWSUserList=function(){var t=[];return this._serverWSS.clients.forEach(function(e){t.push(e.id_user)}),t},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(s,i){return __awaiter(e,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){return this._rebootFlag?i(!1,409,"Unable To Process"):("DEBUG"===this.LOGGER&&console.log("Verify Client",s,i),t=s.req.headers["sec-websocket-protocol"].split(/,/),(s.origin===this._serverConfig.ROOT_URL||s.origin===this._serverConfig.SEC_ROOT_URL||s.origin===this._serverConfig.RESOLVEIO_URL||s.origin===this._serverConfig.RESOLVEIO_SECONDARY_URL)&&(t=t[0])?jwt.verify(t,this._serverConfig.JWT_SECRET,function(r,n){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return r?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:s.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(t=e.sent())?(s.req.user=t.fullname,s.req.user_readonly=t.readonly||!1,s.req.doc_user=t,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")),[2]})})}}),this.setUpMongo()},ResolveIOMainServer.prototype.setUpMongo=function(){"DEBUG"===this.LOGGER&&console.log("Start Managers"),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager(this),"DEBUG"===this.LOGGER&&console.log("End Managers"),this.listen()},ResolveIOMainServer.prototype.listen=function(){var u=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",u._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",u._portWSS)}),this._serverWSS.on("connection",function(f,e){u.publicProgram||(f.id_user=e.id_user,f.user=e.user,f.user_readonly=e.user_readonly,f.doc_user=e.doc_user,"Admin"!==f.user&&"ResolveIO"!==u._serverConfig.CLIENT_NAME&&u.getMethodManager().callMethodInternal.call(u.getMethodManager(),"supportCreateBillingUser",{id_user:f.id_user,user:f.user,date:new Date,client:index_1.ResolveIOServer.getClientName()})),f.id_socket=(0,mongo_manager_1.objectIdHexString)(),f.retryCnt=0,u._subscriptionManager.createLoggedInUser(f.id_socket).then(function(){setTimeout(function(){f.pingTime=new Date,f.ping(function(){})},5e3)}),"DEBUG"===u.LOGGER&&console.log("Connection from: "+e.user),f.isAlive=!0,f.on("pong",function(){f.isAlive=!0,f.pongTime=new Date,f.latency=moment.duration(moment(f.pongTime).diff(f.pingTime)).asMilliseconds(),u._subscriptionManager.loggedInLatency(f)}).on("message",function(p){return __awaiter(u,void 0,void 0,function(){var t,r,n,o,s,i,a,u,l,c,g,_,h,d=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+f.user,p),this._debugMsgRecv+=1,u=!1,t=[];try{t=JSON.parse(p,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",p),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+this._serverConfig.CLIENT_NAME,JSON.stringify([p,e])),u=!0}if(!u){if("ping"===t[0])return f&&f.readyState===f.OPEN&&f.send("pong",function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),d.unsubscribeWS(f))}),[2];if(r=t[0],!this.publicProgram&&this._clientRoutes.some(function(e){return r.includes(e)})&&!f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})&&!f.doc_user.roles.super_admin)return[2];if(u=t[1],n=t[2],"subscription"!==(o=t[3]))return[3,1];s=t[4],c=t[5],"sub"===s?this._subscriptionManager.subscribe(r,u,f,n,c,t.slice(6)):this._subscriptionManager.unsubscribe(r,u,f,n,c,t.slice(6))}return[3,11];case 1:if(this.publicProgram||"offline"!==o)return[3,10];s={messageId:n,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&f.send(JSON.stringify(s),function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Offline Ack Main"),d.unsubscribeWS(f))}),this._offlineUpdates.push(f),i=t[4],a=0,e.label=2;case 2:if(!(a<i.length))return[3,9];if(u=i[a],l=u.data,c={messageId:u.data[2],hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&f.send(JSON.stringify(c),function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Offline Ack Each"),d.unsubscribeWS(f))}),l.shift(),l.shift(),l.shift(),l.shift(),g=l.shift(),h=(0,mongo_manager_1.objectIdHexString)(),log_method_latency_collection_1.LogMethodLatencies.create({_id:h,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r}),!this._methodManager._methods[g])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(h=this._methodManager.callMethodInternal).call.apply(h,__spreadArray([Object.assign({},this._methodManager,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),g],l,!1))];case 4:return e.sent(),[3,6];case 5:return _=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(_,null,2)),[3,6];case 6:return"updateDocumentOffline"!==g&&"updateDocumentPropsOffline"!==g||index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,8];case 7:console.log("Offline - Could not find method: "+g),e.label=8;case 8:return a++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(f.id_socket),1),[3,11];case 10:this._msgQueue.splice(0,0,{ws:f,data:t}),e.label=11;case 11:return[2]}})})}).on("end",function(){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,f.user,f.id_socket,"WS Error")})}),setInterval(function(){u._serverWSS.clients.forEach(function(e){e.pingTime&&2e4<=Date.now()-e.pingTime.getTime()&&(!1===e.isAlive?(e.retryCnt++,3<=e.retryCnt?u.unsubscribeWS(e):(e.pingTime=new Date,e.ping(function(){}))):(e.retryCnt=0,e.isAlive=!1,e.pingTime=new Date,e.ping(function(){})))})},2e4),setInterval(function(){if(!u._msgQueueRunning&&u._msgQueue.length){u._msgQueueRunning=!0,u._debugMsgQueue+=1;var e=u._msgQueue.pop(),t=e.data,r=e.ws,e=t.shift(),n=t.shift(),o=t.shift(),s=t.shift();if("method"===s){var i=t.shift();if(r.user_readonly)return;var a=(0,mongo_manager_1.objectIdHexString)(),e=(log_method_latency_collection_1.LogMethodLatencies.create({_id:a,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:i}),"reportBuilderGetResults"!==i&&"reportBuilderGetDistinctValue"!==i&&"reportBuilderBuildTree"!==i&&"generatePDF"!==i&&"getWOOfflineData"!==i&&"countQuery"!==i&&"countWithQuery"!==i&&"countCollectionWithQuery"!==i&&"find"!==i&&"findOne"!==i&&"findWithOptions"!==i&&"getDrivers"!==i&&"processAirdropDistribution"!==i&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(t))<2e5?JSON.stringify(t,null,2):"Too Big",method:i,id_user:r.id_user||"",user:r.user||"",messageId:o,route:e}),{messageId:o,hasError:!1,data:"ACK"});r&&r.readyState===r.OPEN&&r.send(JSON.stringify(e),function(e){e&&u.unsubscribeWS(r)}),u._methodManager._methods[i]?(e=u._methodManager).callMethod.apply(e,__spreadArray([a,r,n,o,i],t,!1)):console.log("Could not find method: "+i)}else"methodResponse"===s&&(i=t.shift(),method_response_collection_1.MethodResponses.findOne({$and:[{id_user:r.id_user},{message_id:o},{method:i},{date:n}]}).then(function(e){e&&r&&r.readyState===r.OPEN&&r.send(JSON.stringify(e.response),function(e){e&&u.unsubscribeWS(r)})},function(e){}));u._msgQueueRunning=!1}},25)},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return this._serverConfig},ResolveIOMainServer}();exports.default=ResolveIOMainServer;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,a,u={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(t){return function(e){var r=[t,e];if(o)throw new TypeError("Generator is already executing.");for(;u=c&&r[c=0]?0:u;)try{if(o=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return u.label++,{value:r[1],done:!1};case 5:u.label++,i=r[1],r=[0];continue;case 7:r=u.ops.pop(),u.trys.pop();continue;default:if(!(a=0<(a=u.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){u=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))u.label=r[1];else if(6===r[0]&&u.label<a[1])u.label=a[1],a=r;else{if(!(a&&u.label<a[2])){a[2]&&u.ops.pop(),u.trys.pop();continue}u.label=a[2],u.ops.push(r)}}r=s.call(n,u)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),mongo_manager_1=require("./managers/mongo.manager"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),method_response_collection_1=require("./collections/method-response.collection"),log_collection_1=require("./collections/log.collection"),log_method_latency_collection_1=require("./collections/log-method-latency.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),index_1=require("./index"),mongodb_1=require("mongodb"),worker_task_request_collection_1=require("./collections/worker-task-request.collection"),worker_task_response_collection_1=require("./collections/worker-task-response.collection"),ResolveIOMainServer=function(){function ResolveIOMainServer(e,r,t,n,s,o,i){void 0===i&&(i=!1);var a=this;this._offlineUpdates=[],this._msgQueue=[],this._msgQueueRunning=!1,this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._safeShutdown=!1,this._serverConfig=r,this._clientRoutes=t,this._clientDir=n,this.sesMail=s,this.standardProgram=o,this.publicProgram=i,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager(e,r),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){a._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Queue Length",a._msgQueue.length),console.log(new Date,"Server App","Msg Recv Hits",a._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",a._debugMsgQueue)),a._debugMsgQueue=0,a._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(n,s){return __awaiter(a,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:n&&"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+this._serverConfig.CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(a,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+this._serverConfig.CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGTERM",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),process.on("SIGQUIT",function(){a._rebootFlag=!0,a._serverHTTP.close(),a.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager(this),this.startWorkerInstance()):(console.log("Running as a Server instance"),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this.startServerInstance(r),this._methodManager=new method_manager_1.MethodManager(this,this._serverConfig,this._clientDir,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this,this._serverWSS,this._serverConfig,this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager(this),this.listen())}return ResolveIOMainServer.prototype.startServerInstance=function(e){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||e.PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||e.PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,e),(0,health_1.setupHealthRoutes)(this._app,e),"ResolveIO"!==e.CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,e),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){var r=this,t=(console.log("Worker instance started, watching worker-task-reqs..."),worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"}));t.on("change",function(s){return __awaiter(r,void 0,void 0,function(){var r,t,n;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==s.operationType?[3,7]:(r=s.fullDocument)?(console.log("Worker processing task:",r._id),[4,worker_task_request_collection_1.WorkerTaskRequests.findOneAndUpdate({_id:r._id,status:"pending"},{$set:{status:"processing"}})]):[3,7];case 1:if(!e.sent())return[3,7];e.label=2;case 2:return e.trys.push([2,4,,5]),[4,(n=this._methodManager).callMethodInternal.apply(n,__spreadArray([r.method],r.params,!1))];case 3:return n=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:r._id,has_error:!1,data:[n],id_user:r.id_user,user:r.user,id_ws:r.id_ws}),[3,5];case 4:return t=e.sent(),console.error("Worker failed to process task:",r._id,t),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:r._id,has_error:!0,data:[t.message],id_user:r.id_user,user:r.user,id_ws:r.id_ws}),[3,5];case 5:return[4,worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:r._id},{$set:{status:"complete"}})];case 6:e.sent(),e.label=7;case 7:return[2]}})})}),t.on("error",function(e){console.error("Error in change stream worker task requests:",e),t.close(),setTimeout(function(){return r.startWorkerInstance()},5e3)}),t.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return r.startWorkerInstance()},5e3)})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._msgQueue.length||this._msgQueueRunning||this._offlineUpdates.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._msgQueue.length,this._msgQueueRunning,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):index_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)})},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWS=function(r){return Array.from(this._serverWSS.clients).filter(function(e){return e.id_socket===r})[0]},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(o,i){return __awaiter(e,void 0,void 0,function(){var r,s=this;return __generator(this,function(e){return this._rebootFlag?i(!1,409,"Unable To Process"):("DEBUG"===this.LOGGER&&console.log("Verify Client",o,i),r=o.req.headers["sec-websocket-protocol"].split(/,/),(o.origin===this._serverConfig.ROOT_URL||o.origin===this._serverConfig.SEC_ROOT_URL||o.origin===this._serverConfig.RESOLVEIO_URL||o.origin===this._serverConfig.RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,this._serverConfig.JWT_SECRET,function(t,n){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:o.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(o.req.user=r.fullname,o.req.user_readonly=r.readonly||!1,o.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")),[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var u=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",u._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",u._portWSS)}),this._serverWSS.on("connection",function(f,e){u.publicProgram||(f.id_user=e.id_user,f.user=e.user,f.user_readonly=e.user_readonly,f.doc_user=e.doc_user,"Admin"!==f.user&&"ResolveIO"!==u._serverConfig.CLIENT_NAME&&u.getMethodManager().callMethodInternal.call(u.getMethodManager(),"supportCreateBillingUser",{id_user:f.id_user,user:f.user,date:new Date,client:index_1.ResolveIOServer.getClientName()})),f.id_socket=(0,mongo_manager_1.objectIdHexString)(),f.retryCnt=0,u._subscriptionManager.createLoggedInUser(f.id_socket).then(function(){setTimeout(function(){f.pingTime=new Date,f.ping(function(){})},5e3)}),"DEBUG"===u.LOGGER&&console.log("Connection from: "+e.user),f.isAlive=!0,f.on("pong",function(){f.isAlive=!0,f.pongTime=new Date,f.latency=moment.duration(moment(f.pongTime).diff(f.pingTime)).asMilliseconds(),u._subscriptionManager.loggedInLatency(f)}).on("message",function(p){return __awaiter(u,void 0,void 0,function(){var r,t,n,s,o,i,a,u,c,l,_,g,h,d=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+f.user,p),this._debugMsgRecv+=1,u=!1,r=[];try{r=JSON.parse(p,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",p),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+this._serverConfig.CLIENT_NAME,JSON.stringify([p,e])),u=!0}if(!u){if("ping"===r[0])return f&&f.readyState===f.OPEN&&f.send("pong",function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),d.unsubscribeWS(f))}),[2];if(t=r[0],!this.publicProgram&&this._clientRoutes.some(function(e){return t.includes(e)})&&!f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return t.includes(e)||e.includes(t)})})&&!f.doc_user.roles.super_admin)return[2];if(u=r[1],n=r[2],"subscription"!==(s=r[3]))return[3,1];o=r[4],l=r[5],"sub"===o?this._subscriptionManager.subscribe(t,u,f,n,l,r.slice(6)):this._subscriptionManager.unsubscribe(t,u,f,n,l,r.slice(6))}return[3,11];case 1:if(this.publicProgram||"offline"!==s)return[3,10];o={messageId:n,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&f.send(JSON.stringify(o),function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Offline Ack Main"),d.unsubscribeWS(f))}),this._offlineUpdates.push(f),i=r[4],a=0,e.label=2;case 2:if(!(a<i.length))return[3,9];if(u=i[a],c=u.data,l={messageId:u.data[2],hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&f.send(JSON.stringify(l),function(e){e&&(d._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Offline Ack Each"),d.unsubscribeWS(f))}),c.shift(),c.shift(),c.shift(),c.shift(),_=c.shift(),h=(0,mongo_manager_1.objectIdHexString)(),log_method_latency_collection_1.LogMethodLatencies.create({_id:h,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:_}),"reportBuilderGetResults"!==_&&"reportBuilderGetDistinctValue"!==_&&"reportBuilderBuildTree"!==_&&"generatePDF"!==_&&"getWOOfflineData"!==_&&"countQuery"!==_&&"countWithQuery"!==_&&"countCollectionWithQuery"!==_&&"find"!==_&&"findOne"!==_&&"findWithOptions"!==_&&"getDrivers"!==_&&"processAirdropDistribution"!==_&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:_,id_user:f.id_user||"",user:f.user||"",messageId:n,route:t}),!this._methodManager._methods[_])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(h=this._methodManager.callMethodInternal).call.apply(h,__spreadArray([Object.assign({},this._methodManager,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),_],c,!1))];case 4:return e.sent(),[3,6];case 5:return g=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(g,null,2)),[3,6];case 6:return"updateDocumentOffline"!==_&&"updateDocumentPropsOffline"!==_||index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c[0]),[3,8];case 7:console.log("Offline - Could not find method: "+_),e.label=8;case 8:return a++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(f.id_socket),1),[3,11];case 10:this._msgQueue.splice(0,0,{ws:f,data:r}),e.label=11;case 11:return[2]}})})}).on("end",function(){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){u.unsubscribeWS(f),u._subscriptionManager.getEnableDebug()&&console.log(new Date,f.user,f.id_socket,"WS Error")})}),setInterval(function(){u._serverWSS.clients.forEach(function(e){e.pingTime&&2e4<=Date.now()-e.pingTime.getTime()&&(!1===e.isAlive?(e.retryCnt++,3<=e.retryCnt?u.unsubscribeWS(e):(e.pingTime=new Date,e.ping(function(){}))):(e.retryCnt=0,e.isAlive=!1,e.pingTime=new Date,e.ping(function(){})))})},2e4),setInterval(function(){if(!u._msgQueueRunning&&u._msgQueue.length){u._msgQueueRunning=!0,u._debugMsgQueue+=1;var e=u._msgQueue.pop(),r=e.data,t=e.ws,e=r.shift(),n=r.shift(),s=r.shift(),o=r.shift();if("method"===o){var i=r.shift();if(t.user_readonly)return;var a=(0,mongo_manager_1.objectIdHexString)(),e=(log_method_latency_collection_1.LogMethodLatencies.create({_id:a,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:i}),"reportBuilderGetResults"!==i&&"reportBuilderGetDistinctValue"!==i&&"reportBuilderBuildTree"!==i&&"generatePDF"!==i&&"getWOOfflineData"!==i&&"countQuery"!==i&&"countWithQuery"!==i&&"countCollectionWithQuery"!==i&&"find"!==i&&"findOne"!==i&&"findWithOptions"!==i&&"getDrivers"!==i&&"processAirdropDistribution"!==i&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(r))<2e5?JSON.stringify(r,null,2):"Too Big",method:i,id_user:t.id_user||"",user:t.user||"",messageId:s,route:e}),{messageId:s,hasError:!1,data:"ACK"});t&&t.readyState===t.OPEN&&t.send(JSON.stringify(e),function(e){e&&u.unsubscribeWS(t)}),u._methodManager._methods[i]?(e=u._methodManager).callMethod.apply(e,__spreadArray([a,t,n,s,i],r,!1)):console.log("Could not find method: "+i)}else"methodResponse"===o&&(i=r.shift(),method_response_collection_1.MethodResponses.findOne({$and:[{id_user:t.id_user},{message_id:s},{method:i},{date:n}]}).then(function(e){e&&t&&t.readyState===t.OPEN&&t.send(JSON.stringify(e.response),function(e){e&&u.unsubscribeWS(t)})},function(e){}));u._msgQueueRunning=!1}},1)},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return this._serverConfig},ResolveIOMainServer}();exports.default=ResolveIOMainServer;
2
2
  //# sourceMappingURL=server-app.js.map
package/server-app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","mongo_manager_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","method_response_collection_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","index_1","mongodb_1","ResolveIOMainServer","mainServer","serverConfig","clientRoutes","clientDir","sesMail","standardProgram","publicProgram","_this","this","_offlineUpdates","_msgQueue","_msgQueueRunning","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_safeShutdown","_serverConfig","_clientDir","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","setInterval","_subscriptionManager","getEnableDebug","console","log","length","process","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_methodManager","sendEmail","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","env","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","prototype","getActiveMonitorFunctions","setImmediate","ResolveIOServer","getMongoConnection","then","getWS","id_ws","Array","from","_serverWSS","clients","filter","a","getWSList","forEach","ws","push","getWSUserList","getHTTPServer","getCronManager","_cronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","user","fullname","readonly","setUpMongo","SubscriptionManager","MethodManager","CronManager","listen","callMethodInternal","call","id_user","date","client","getClientName","objectIdHexString","createLoggedInUser","ping","duration","asMilliseconds","loggedInLatency","parseErrorFound","socketData","parse","e","readyState","OPEN","send","unsubscribeWS","messageRoute_1","some","includes","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","data","offlineUpdates","i","update","serverResMethod","shift","method","methodLatencyId","LogMethodLatencies","create","_id","__v","date_start","date_end","latency_ms","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","apply","__spreadArray","Object","assign","_b","err_2","getMongoManager","invalidateQueryCache","splice","map","indexOf","now","getTime","msg","pop","ws_1","messageRoute","callMethod","MethodResponses","findOne","$and","message_id","response","unsubscribeAll","removeAllListeners","getApp","getServerConfig"],"mappings":"wqDAAAA,Q,uDAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EAEAM,OAAAN,QAAA,iBAAA,EAEAO,SAAAP,QAAA,eAAA,EAEAQ,gBAAAR,QAAA,0BAAA,EACAS,eAAAT,QAAA,yBAAA,EACAU,iBAAAV,QAAA,2BAAA,EACAW,uBAAAX,QAAA,iCAAA,EACAY,kBAAAZ,QAAA,4BAAA,EAIAa,6BAAAb,QAAA,0CAAA,EACAc,iBAAAd,QAAA,8BAAA,EACAe,gCAAAf,QAAA,6CAAA,EACAgB,kBAAAhB,QAAA,+BAAA,EAEAiB,OAAAjB,QAAA,aAAA,EACAkB,OAAAlB,QAAA,aAAA,EACAmB,SAAAnB,QAAA,eAAA,EACAoB,QAAApB,QAAA,SAAA,EACAqB,UAAArB,QAAA,SAAA,EAEAsB,oBAAA,WAiCC,SAAAA,oBAAYC,EAAYC,EAAcC,EAAcC,EAAWC,EAASC,EAAiBC,GAAA,KAAA,IAAAA,IAAAA,EAAA,CAAA,GAAzF,IAAAC,EAAAC,KAzBQA,KAAAC,gBAAkB,GAClBD,KAAAE,UAAY,GACZF,KAAAG,iBAAmB,CAAA,EACpBH,KAAAJ,QAAU,CAAA,EACTI,KAAA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e,OAAQA,CAAM,EACf,CAACzC,KAAMyB,CAAW,EAClB,CAAC,EAAE1E,KAAK,SAAAX,GACJA,GACCqI,GAAMA,EAAG5D,aAAe4D,EAAG3D,MAC9B2D,EAAG1D,KAAKtG,KAAKC,UAAU0B,EAAI4I,QAAQ,EAAG,SAAChL,GAClCA,GACH5B,EAAK4I,cAAcyD,CAAE,CAEvB,CAAC,CAGJ,EAAG,SAAAxF,IAAS,GAGb7G,EAAKI,iBAAmB,CAAA,C,CAG3B,EAAG,EAAE,CACN,EAEOZ,oBAAA8E,UAAAsE,cAAP,SAAqBtD,GAChBrF,KAAKoB,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIT,KAAQ,aAAc,WAAYuE,EAAS,KAAGA,EAAc,SAAC,EAE9ErF,KAAKoB,qBAAqBwL,eAAevH,CAAE,EAC3CA,EAAGwH,mBAAkB,CAEtB,EAEOtN,oBAAA8E,UAAAyI,OAAP,WACC,OAAO9M,KAAK+C,IACb,EAEOxD,oBAAA8E,UAAA0I,gBAAP,WACC,OAAO/M,KAAKW,aACb,EACDpB,mBAAA,EAAC","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\n// import * as SegfaultHandler from 'segfault-handler';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize, deepCopy } from './util/common';\n\nimport { objectIdHexString } from './managers/mongo.manager';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\n\nimport { ServerResponseModel } from './models/server-response.model';\n\nimport { MethodResponses } from './collections/method-response.collection';\nimport { Logs } from './collections/log.collection';\nimport { LogMethodLatencies } from './collections/log-method-latency.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { ResolveIOServer } from './index';\nimport { MongoNetworkTimeoutError } from 'mongodb';\n\nexport default class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _serverConfig;\n\tprivate _clientDir;\n\tprivate _offlineUpdates = [];\n\tprivate _msgQueue = [];\n\tprivate _msgQueueRunning = false;\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _safeShutdown = false;\n\n\tconstructor(mainServer, serverConfig, clientRoutes, clientDir, sesMail, standardProgram, publicProgram = false) {\n\t\tthis._serverConfig = serverConfig;\n\t\tthis._clientRoutes = clientRoutes;\n\t\tthis._clientDir = clientDir;\n\t\tthis.sesMail = sesMail;\n\t\tthis.standardProgram = standardProgram;\n\t\tthis.publicProgram = publicProgram;\n\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager(mainServer, serverConfig);\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Length', this._msgQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use body parser for http call (login)\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || serverConfig['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || serverConfig['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\t\t\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\n\t\t\t// Website you wish to allow to connect\n\t\t\t// res.setHeader('Access-Control-Allow-Origin', serverConfig['ROOT_URL']);\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\n\t\t\t// Request methods you wish to allow\n\t\t\t// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\n\t\t\t// Request headers you wish to allow\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\n\t\t\t// Set to true if you need the website to include cookies in the requests sent\n\t\t\t// to the API (e.g. in case you use sessions)\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\n\t\t\t// Pass to next layer of middleware\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, serverConfig);\n\t\tsetupHealthRoutes(this._app, serverConfig);\n\n\t\tif (serverConfig['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, serverConfig);\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length && \n\t\t\t// (!this._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._msgQueue.length &&\n\t\t\t!this._msgQueueRunning &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\tprocess.exit(0);\n\t\t\t}, () => {process.exit(1)});\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), \n\t\t\t\t\t'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length, \n\t\t\t\t\t// this._monitorManagerFunction.getLastCompletedMonitorFunction() ? this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime : '',\n\t\t\t\t\tthis._msgQueue.length, \n\t\t\t\t\tthis._msgQueueRunning,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic getWS(id_ws: string) {\n\t\treturn Array.from(this._serverWSS.clients).filter(a => a['id_socket'] === id_ws)[0];\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tprivate createServer(): void {\n\t\t// Start express server\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`\n\n\t\t// Start websocket server\n\t\t// Verify client with token before opening socket\n\t\tthis._serverWSS = new WebSocket.Server({ \n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (info.origin !== this._serverConfig['ROOT_URL'] && info.origin !== this._serverConfig['SEC_ROOT_URL'] && info.origin !== this._serverConfig['RESOLVEIO_URL'] && info.origin !== this._serverConfig['RESOLVEIO_SECONDARY_URL']) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, this._serverConfig['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// Start MongoDB Connection\n\t\tthis.setUpMongo();\n\t}\n\n\tprivate setUpMongo() {\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Start Managers');\n\t\t}\n\n\t\t// Start Managers\n\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction);\n\t\tthis._cronManager = new CronManager(this);\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('End Managers');\n\t\t}\n\n\t\tthis.listen();\n\t}\n\n\t// Listen to port for websocket\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\t// On websocket connection (already verified)\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (!this.publicProgram) {\n\t\t\t\t// Get user from token\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tif (ws['user'] !== 'Admin' && this._serverConfig['CLIENT_NAME'] !== 'ResolveIO') {\n\t\t\t\t\tthis.getMethodManager().callMethodInternal.call(this.getMethodManager(), 'supportCreateBillingUser', {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tclient: ResolveIOServer.getClientName()\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\tws['retryCnt'] = 0;\n\n\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.ping(() => {});\n\t\t\t\t}, 5000);\n\t\t\t});\n\n\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\tconsole.log('Connection from: ' + req['user']);\n\t\t\t}\n\t\t\t\n\t\t\t// Use for keeping connection alive (ping/pong)\n\t\t\tws['isAlive'] = true;\n\t\t\tws.on('pong', () => {\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t})\n\t\t\t.on('message', async (message: string) => {\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Message from: ' + ws['user'], message);\n\t\t\t\t}\n\n\t\t\t\tthis._debugMsgRecv += 1;\n\n\t\t\t\tlet parseErrorFound = false;\n\n\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch(e) {\n\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\n\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([message, e]));\n\n\t\t\t\t\tparseErrorFound = true;\n\t\t\t\t}\n\n\t\t\t\tif (!parseErrorFound) {\n\t\t\t\t\tif (socketData[0] === 'ping') {\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send('pong', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Pong');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet messageRoute = socketData[0];\n\n\t\t\t\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet messageDate = socketData[1];\n\t\t\t\t\tlet messageId = socketData[2]\n\t\t\t\t\tlet type = socketData[3]\n\n\t\t\t\t\tif (type === 'subscription') {\n\t\t\t\t\t\tlet subType = socketData[4];\n\t\t\t\t\t\tlet pub = socketData[5];\n\t\t\n\t\t\t\t\t\t// Subscribe\n\t\t\t\t\t\tif (subType === 'sub') {\n\t\t\t\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Unsubscribe\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send(JSON.stringify(serverRes), (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Offline Ack Main');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._offlineUpdates.push(ws);\n\t\t\t\t\t\tlet offlineUpdates = socketData[4];\n\n\t\t\t\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\t\t\t\tlet update = offlineUpdates[i];\n\t\t\t\t\t\t\tlet data = update.data;\n\n\t\t\t\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\t\t\t\tmessageId: update.data[2],\n\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(serverResMethod), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Offline Ack Each');\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\t\t\t\tlet updateDate = data.shift();\n\t\t\t\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\t\t\t\tlet updateType = data.shift();\n\t\t\t\t\t\t\tlet method = data.shift();\n\t\t\t\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t\t});\n\t\t\t\n\t\t\t\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t\t\t\t}\n\t\t\t\t\telse { //methods\n\t\t\t\t\t\tthis._msgQueue.splice(0, 0, {\n\t\t\t\t\t\t\tws: ws,\n\t\t\t\t\t\t\tdata: socketData\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS End');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS Close');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', error => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), ws['user'], ws['id_socket'], 'WS Error');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t});\n\n\t\t// Keep alive timer to ping/pong\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.ping(() => {});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.ping(() => {});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._msgQueueRunning) {\t\t\t\t\n\t\t\t\tif (this._msgQueue.length) {\n\t\t\t\t\tthis._msgQueueRunning = true;\n\t\t\t\t\tthis._debugMsgQueue += 1;\n\n\t\t\t\t\tlet msg = this._msgQueue.pop();\n\t\t\t\t\tlet data = msg.data;\n\t\t\t\t\tlet ws = msg.ws;\n\t\t\n\t\t\t\t\tlet messageRoute: string = data.shift();\n\t\t\t\t\tlet messageDate: Date = data.shift();\n\t\t\t\t\tlet messageId: number = data.shift();\n\t\t\t\t\tlet type: string = data.shift();\n\t\t\n\t\t\t\t\t// Method call\n\t\t\t\t\tif (type === 'method') {\n\t\t\t\t\t\tlet method = data.shift();\n\n\t\t\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t});\n\t\t\n\t\t\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send(JSON.stringify(serverRes), (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (type === 'methodResponse') {\n\t\t\t\t\t\tlet method = data.shift();\n\t\t\n\t\t\t\t\t\tMethodResponses.findOne({$and: [\n\t\t\t\t\t\t\t{id_user: ws['id_user']}, \n\t\t\t\t\t\t\t{message_id: messageId},\n\t\t\t\t\t\t\t{method: method},\n\t\t\t\t\t\t\t{date: messageDate}\n\t\t\t\t\t\t]}).then(res => {\n\t\t\t\t\t\t\tif (res) {\n\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\tws.send(JSON.stringify(res.response), (error) => {\n\t\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}, err => {});\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tthis._msgQueueRunning = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 25);\n\t}\n\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn this._serverConfig;\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","mongo_manager_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","method_response_collection_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","index_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","ResolveIOMainServer","mainServer","serverConfig","clientRoutes","clientDir","sesMail","standardProgram","publicProgram","_this","this","_offlineUpdates","_msgQueue","_msgQueueRunning","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_serverConfig","_clientDir","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","length","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_methodManager","sendEmail","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","startServerInstance","SubscriptionManager","_serverWSS","listen","prototype","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","changeStream","WorkerTaskRequests","watchCollection","$match","fullDocument.status","fullDocument","change","operationType","task","_id","findOneAndUpdate","status","$set","_b","callMethodInternal","apply","__spreadArray","method","params","result","WorkerTaskResponses","create","id_request","has_error","data","id_user","user","id_ws","err_1","updateOne","getActiveMonitorFunctions","setImmediate","ResolveIOServer","getMongoConnection","then","getIsWorkersEnabled","getIsWorkerInstance","getWS","Array","from","clients","filter","a","getWSList","forEach","ws","push","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","fullname","readonly","call","date","client","getClientName","objectIdHexString","createLoggedInUser","ping","duration","asMilliseconds","loggedInLatency","parseErrorFound","socketData","parse","e","readyState","OPEN","send","unsubscribeWS","messageRoute_1","some","includes","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","serverResMethod","shift","methodLatencyId","LogMethodLatencies","__v","date_start","date_end","latency_ms","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","Object","assign","err_3","getMongoManager","invalidateQueryCache","splice","map","indexOf","now","getTime","msg","pop","ws_1","messageRoute","callMethod","MethodResponses","findOne","$and","message_id","response","unsubscribeAll","removeAllListeners","getApp","getServerConfig"],"mappings":"wqDAAAA,Q,uDAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EAEAM,OAAAN,QAAA,iBAAA,EAEAO,SAAAP,QAAA,eAAA,EAEAQ,gBAAAR,QAAA,0BAAA,EACAS,eAAAT,QAAA,yBAAA,EACAU,iBAAAV,QAAA,2BAAA,EACAW,uBAAAX,QAAA,iCAAA,EACAY,kBAAAZ,QAAA,4BAAA,EAIAa,6BAAAb,QAAA,0CAAA,EACAc,iBAAAd,QAAA,8BAAA,EACAe,gCAAAf,QAAA,6CAAA,EACAgB,kBAAAhB,QAAA,+BAAA,EAEAiB,OAAAjB,QAA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AqE,UAAA6K,gBAAP,WACC,OAAOzO,KAAKa,aACb,EACDtB,mBAAA,EAAC","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\n// import * as SegfaultHandler from 'segfault-handler';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize, deepCopy } from './util/common';\n\nimport { objectIdHexString } from './managers/mongo.manager';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\n\nimport { ServerResponseModel } from './models/server-response.model';\n\nimport { MethodResponses } from './collections/method-response.collection';\nimport { Logs } from './collections/log.collection';\nimport { LogMethodLatencies } from './collections/log-method-latency.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { ResolveIOServer } from './index';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\n\nexport default class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _serverConfig;\n\tprivate _clientDir;\n\tprivate _offlineUpdates = [];\n\tprivate _msgQueue = [];\n\tprivate _msgQueueRunning = false;\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tconstructor(mainServer, serverConfig, clientRoutes, clientDir, sesMail, standardProgram, publicProgram = false) {\n\t\tthis._serverConfig = serverConfig;\n\t\tthis._clientRoutes = clientRoutes;\n\t\tthis._clientDir = clientDir;\n\t\tthis.sesMail = sesMail;\n\t\tthis.standardProgram = standardProgram;\n\t\tthis.publicProgram = publicProgram;\n\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager(mainServer, serverConfig);\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Length', this._msgQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tthis._serverHTTP.close();\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n if (this._isWorkersEnabled) {\n if (this._isWorkerInstance) {\n console.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager(this);\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n this.startServerInstance(serverConfig);\n\t\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n this.startServerInstance(serverConfig);\n\t\t\tthis._methodManager = new MethodManager(this, this._serverConfig, this._clientDir, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this, this._serverWSS, this._serverConfig, this._monitorManagerFunction);\n this._cronManager = new CronManager(this);\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance(serverConfig) {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use body parser for http call (login)\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || serverConfig['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || serverConfig['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\n\t\t\t// Website you wish to allow to connect\n\t\t\t// res.setHeader('Access-Control-Allow-Origin', serverConfig['ROOT_URL']);\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\n\t\t\t// Request methods you wish to allow\n\t\t\t// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\n\t\t\t// Request headers you wish to allow\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\n\t\t\t// Set to true if you need the website to include cookies in the requests sent\n\t\t\t// to the API (e.g. in case you use sessions)\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\n\t\t\t// Pass to next layer of middleware\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, serverConfig);\n\t\tsetupHealthRoutes(this._app, serverConfig);\n\n\t\tif (serverConfig['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, serverConfig);\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\n\t\t\t\tif (task) {\n\t\t\t\t\tconsole.log('Worker processing task:', task._id);\n\n\t\t\t\t\t// Update the task status to 'processing'\n\t\t\t\t\tlet req = await WorkerTaskRequests.findOneAndUpdate({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } });\n\n\t\t\t\t\tif (req) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Run the actual method\n\t\t\t\t\t\t\tconst result = await this._methodManager.callMethodInternal(task.method, ...task.params);\n\n\t\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\t\t\tdata: [result],\n\t\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\n\t\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\t\t\tdata: [err.message],\n\t\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Mark the task as complete\n\t\t\t\t\t\tawait WorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tchangeStream.close();\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000); // Restart after a delay\n\t\t});\n\t\n\t\tchangeStream.on('close', () => {\n\t\t\tconsole.log('Change stream worker task requests closed. Restarting...');\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000); // Restart after a delay\n\t\t});\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length && \n\t\t\t// (!this._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._msgQueue.length &&\n\t\t\t!this._msgQueueRunning &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\tprocess.exit(0);\n\t\t\t}, () => {process.exit(1)});\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), \n\t\t\t\t\t'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length, \n\t\t\t\t\t// this._monitorManagerFunction.getLastCompletedMonitorFunction() ? this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime : '',\n\t\t\t\t\tthis._msgQueue.length, \n\t\t\t\t\tthis._msgQueueRunning,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWS(id_ws: string) {\n\t\treturn Array.from(this._serverWSS.clients).filter(a => a['id_socket'] === id_ws)[0];\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tprivate createServer(): void {\n\t\t// Start express server\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`\n\n\t\t// Start websocket server\n\t\t// Verify client with token before opening socket\n\t\tthis._serverWSS = new WebSocket.Server({ \n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (info.origin !== this._serverConfig['ROOT_URL'] && info.origin !== this._serverConfig['SEC_ROOT_URL'] && info.origin !== this._serverConfig['RESOLVEIO_URL'] && info.origin !== this._serverConfig['RESOLVEIO_SECONDARY_URL']) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, this._serverConfig['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// Listen to port for websocket\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\t// On websocket connection (already verified)\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (!this.publicProgram) {\n\t\t\t\t// Get user from token\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tif (ws['user'] !== 'Admin' && this._serverConfig['CLIENT_NAME'] !== 'ResolveIO') {\n\t\t\t\t\tthis.getMethodManager().callMethodInternal.call(this.getMethodManager(), 'supportCreateBillingUser', {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tclient: ResolveIOServer.getClientName()\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\tws['retryCnt'] = 0;\n\n\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.ping(() => {});\n\t\t\t\t}, 5000);\n\t\t\t});\n\n\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\tconsole.log('Connection from: ' + req['user']);\n\t\t\t}\n\t\t\t\n\t\t\t// Use for keeping connection alive (ping/pong)\n\t\t\tws['isAlive'] = true;\n\t\t\tws.on('pong', () => {\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t})\n\t\t\t.on('message', async (message: string) => {\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Message from: ' + ws['user'], message);\n\t\t\t\t}\n\n\t\t\t\tthis._debugMsgRecv += 1;\n\n\t\t\t\tlet parseErrorFound = false;\n\n\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch(e) {\n\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\n\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([message, e]));\n\n\t\t\t\t\tparseErrorFound = true;\n\t\t\t\t}\n\n\t\t\t\tif (!parseErrorFound) {\n\t\t\t\t\tif (socketData[0] === 'ping') {\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send('pong', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Pong');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet messageRoute = socketData[0];\n\n\t\t\t\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet messageDate = socketData[1];\n\t\t\t\t\tlet messageId = socketData[2]\n\t\t\t\t\tlet type = socketData[3]\n\n\t\t\t\t\tif (type === 'subscription') {\n\t\t\t\t\t\tlet subType = socketData[4];\n\t\t\t\t\t\tlet pub = socketData[5];\n\t\t\n\t\t\t\t\t\t// Subscribe\n\t\t\t\t\t\tif (subType === 'sub') {\n\t\t\t\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Unsubscribe\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send(JSON.stringify(serverRes), (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Offline Ack Main');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._offlineUpdates.push(ws);\n\t\t\t\t\t\tlet offlineUpdates = socketData[4];\n\n\t\t\t\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\t\t\t\tlet update = offlineUpdates[i];\n\t\t\t\t\t\t\tlet data = update.data;\n\n\t\t\t\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\t\t\t\tmessageId: update.data[2],\n\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(serverResMethod), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Offline Ack Each');\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\t\t\t\tlet updateDate = data.shift();\n\t\t\t\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\t\t\t\tlet updateType = data.shift();\n\t\t\t\t\t\t\tlet method = data.shift();\n\t\t\t\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t\t});\n\t\t\t\n\t\t\t\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t\t\t\t}\n\t\t\t\t\telse { //methods\n\t\t\t\t\t\tthis._msgQueue.splice(0, 0, {\n\t\t\t\t\t\t\tws: ws,\n\t\t\t\t\t\t\tdata: socketData\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS End');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS Close');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', error => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), ws['user'], ws['id_socket'], 'WS Error');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t});\n\n\t\t// Keep alive timer to ping/pong\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.ping(() => {});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.ping(() => {});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._msgQueueRunning) {\t\t\t\t\n\t\t\t\tif (this._msgQueue.length) {\n\t\t\t\t\tthis._msgQueueRunning = true;\n\t\t\t\t\tthis._debugMsgQueue += 1;\n\n\t\t\t\t\tlet msg = this._msgQueue.pop();\n\t\t\t\t\tlet data = msg.data;\n\t\t\t\t\tlet ws = msg.ws;\n\t\t\n\t\t\t\t\tlet messageRoute: string = data.shift();\n\t\t\t\t\tlet messageDate: Date = data.shift();\n\t\t\t\t\tlet messageId: number = data.shift();\n\t\t\t\t\tlet type: string = data.shift();\n\t\t\n\t\t\t\t\t// Method call\n\t\t\t\t\tif (type === 'method') {\n\t\t\t\t\t\tlet method = data.shift();\n\n\t\t\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t});\n\t\t\n\t\t\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\tdata: 'ACK'\n\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send(JSON.stringify(serverRes), (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (type === 'methodResponse') {\n\t\t\t\t\t\tlet method = data.shift();\n\t\t\n\t\t\t\t\t\tMethodResponses.findOne({$and: [\n\t\t\t\t\t\t\t{id_user: ws['id_user']}, \n\t\t\t\t\t\t\t{message_id: messageId},\n\t\t\t\t\t\t\t{method: method},\n\t\t\t\t\t\t\t{date: messageDate}\n\t\t\t\t\t\t]}).then(res => {\n\t\t\t\t\t\t\tif (res) {\n\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\tws.send(JSON.stringify(res.response), (error) => {\n\t\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}, err => {});\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tthis._msgQueueRunning = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1);\n\t}\n\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn this._serverConfig;\n\t}\n}"]}