@resolveio/server-lib 20.3.25 → 20.3.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";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:!1,collectionOptions:null}),exports.WorkerTaskRequests=e.collection_main,exports.WorkerTaskRequests.createIndex({createdAt:1},{expireAfterSeconds:7776e3}),exports.WorkerTaskRequests.createIndex({status:1,createdAt:1}),exports.WorkerTaskRequests.createIndex({_id:1,status:1})):setTimeout(function(){initializeCollection()},0)}exports.WorkerTaskRequests=null,initializeCollection();
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:!1,collectionOptions:null}),exports.WorkerTaskRequests=e.collection_main,exports.WorkerTaskRequests.createIndex({createdAt:1},{expireAfterSeconds:7776e3}),exports.WorkerTaskRequests.createIndex({status:1,createdAt:1}),exports.WorkerTaskRequests.createIndex({_id:1,status:1}),exports.WorkerTaskRequests.createIndex({user:1,createdAt:-1})):setTimeout(function(){initializeCollection()},0)}exports.WorkerTaskRequests=null,initializeCollection();
2
2
  //# sourceMappingURL=worker-task-request.collection.js.map
@@ -1 +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,EACtFJ,QAAAC,mBAAmBE,YAAY,CAACpB,OAAQ,EAAGV,UAAW,CAAC,CAAC,EACxD2B,QAAAC,mBAAmBE,YAAY,CAACtC,IAAK,EAAGkB,OAAQ,CAAC,CAAC,GAGlDsB,WAAW,WACVlB,qBAAoB,CACrB,EAAG,CAAC,CAEN,CA3BWa,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: false,\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\tWorkerTaskRequests.createIndex({status: 1, createdAt: 1});\n\t\tWorkerTaskRequests.createIndex({_id: 1, status: 1});\n\t}\n\telse {\n\t\tsetTimeout(() => {\n\t\t\tinitializeCollection();\n\t\t}, 0);\n\t}\n}"]}
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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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: false,\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\tWorkerTaskRequests.createIndex({status: 1, createdAt: 1});\n\t\tWorkerTaskRequests.createIndex({_id: 1, status: 1});\n\t\tWorkerTaskRequests.createIndex({user: 1, createdAt: -1});\n\t}\n\telse {\n\t\tsetTimeout(() => {\n\t\t\tinitializeCollection();\n\t\t}, 0);\n\t}\n}"]}
@@ -1,2 +1,2 @@
1
- "use strict";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:!1,collectionOptions:null}),exports.WorkerTaskResponses=e.collection_main,exports.WorkerTaskResponses.createIndex({createdAt:1},{expireAfterSeconds:7776e3})):setTimeout(function(){initializeCollection()},0)}exports.WorkerTaskResponses=null,initializeCollection();
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:!1,collectionOptions:null}),exports.WorkerTaskResponses=e.collection_main,exports.WorkerTaskResponses.createIndex({createdAt:1},{expireAfterSeconds:7776e3}),exports.WorkerTaskResponses.createIndex({id_request:1})):setTimeout(function(){initializeCollection()},0)}exports.WorkerTaskResponses=null,initializeCollection();
2
2
  //# sourceMappingURL=worker-task-response.collection.js.map
@@ -1 +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: false,\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}"]}
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,EACvFJ,QAAAC,oBAAoBE,YAAY,CAAC5B,WAAY,CAAC,CAAC,GAG/C8B,WAAW,WACVlB,qBAAoB,CACrB,EAAG,CAAC,CAEN,CA1BWa,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: false,\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\tWorkerTaskResponses.createIndex({id_request: 1});\n\t}\n\telse {\n\t\tsetTimeout(() => {\n\t\t\tinitializeCollection();\n\t\t}, 0);\n\t}\n}"]}
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,i){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var i,s,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(r,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,i=t.length;n<i;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),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,i){var s=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=i,(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(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",s._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0,s._debugSendQueueHits=0},6e4),setInterval(function(){if(!s._runningQueue&&s._sendQueue.length){s._runningQueue=!0;for(var e=s._sendQueue.length-1;0<=e;e--)!function(e){s._debugSendQueueHits+=1;var t,o=s._mainServer.getWS(s._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=s._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&s._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})):s._sendQueue.splice(e,1)}(e);s._runningQueue=!1}},1)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,d,h=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t?(c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),l=(0,mongo_manager_1.objectIdHexString)(),h=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":l}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(c),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:l,method:t,params:o,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],o,!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(d),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),h}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,i,s,a){for(var c,e,l,d,t=this,h=[],o=5;o<arguments.length;o++)h[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<h.length||h[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),u={messageId:s,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,i,a,h,u);for(var u,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),m=0;m<h.length;m++)_[g[m]]=h[m];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a?(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),e=(0,mongo_manager_1.objectIdHexString)(),(l=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==o.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(c),t=o.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,h,t),r?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:l.close(),e.label=3;case 3:return[2]}})})}),l.on("error",function(e){console.error("Error watching worker responses:",e),l.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:h,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],h,!1)).then(function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(d),t={messageId:s,hasError:!1,data:o},this.sendWS(n,i,a,h,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(d),t.sendWS(n,i,a,h,{messageId:s,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(h,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),u={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,h,u),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,a,c="function"==typeof o[o.length-1]?o.slice(0,-1):o,l=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),s=(0,mongo_manager_1.objectIdHexString)(),l=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:c,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(a=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),l=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],c,!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(a),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(a),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),o[o.length-1]&&"function"==typeof o[o.length-1]&&l.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:r,data:n,date:t})},MethodManager.prototype.sendEmail=function(r,n,i,s,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:i,html:s,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,i,s,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,i){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var i,s,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(r,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,i=t.length;n<i;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),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,i){var s=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=i,(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(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",s._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0,s._debugSendQueueHits=0},6e4),setInterval(function(){if(!s._runningQueue&&s._sendQueue.length){s._runningQueue=!0;for(var e=s._sendQueue.length-1;0<=e;e--)!function(e){s._debugSendQueueHits+=1;var t,o=s._mainServer.getWS(s._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=s._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&s._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})):s._sendQueue.splice(e,1)}(e);s._runningQueue=!1}},1)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,d,h=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t?(c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),l=(0,mongo_manager_1.objectIdHexString)(),h=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":l}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(c),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:l,method:t,params:o,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],o,!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(d),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),h}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,i,s,a){for(var c,e,l,d,t=this,h=[],o=5;o<arguments.length;o++)h[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<h.length||h[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),u={messageId:s,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,i,a,h,u);for(var u,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),m=0;m<h.length;m++)_[g[m]]=h[m];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a?(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),e=(0,mongo_manager_1.objectIdHexString)(),(l=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==o.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(c),t=o.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,h,t),r?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:l.close(),e.label=3;case 3:return[2]}})})}),l.on("error",function(e){console.error("Error watching worker responses:",e),l.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:h,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],h,!1)).then(function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(d),t={messageId:s,hasError:!1,data:o},this.sendWS(n,i,a,h,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(d),t.sendWS(n,i,a,h,{messageId:s,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(h,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),u={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,h,u),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,a,c="function"==typeof o[o.length-1]?o.slice(0,-1):o,l=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),s=(0,mongo_manager_1.objectIdHexString)(),l=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:c,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(a=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),l=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],c,!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(a),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(a),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),o[o.length-1]&&"function"==typeof o[o.length-1]&&l.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:r,data:n,date:t})},MethodManager.prototype.sendEmail=function(r,n,i,s,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:i,html:s,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,i,s,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
2
2
  //# sourceMappingURL=method.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","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_2","taskId_1","monitor_3","promise","startMonitorFunction","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","finishMonitorFunction","taskResponse","has_error","close","WorkerTaskRequests","params","status","_a","function","call","apply","__spreadArray","then","res","methodErrs","callMethod","id_methodLatency","messageDate","monitor_4","taskId","changeStream_1","monitor_5","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","monitor_6","taskId_2","monitor_7","functionMethodData","slice","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"wqDACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,6BAAAd,QAAA,2CAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,iBAAAhB,QAAA,+BAAA,EAEAiB,gCAAAjB,QAAA,8CAAA,EACAkB,OAAAlB,QAAA,iBAAA,EACAmB,iBAAAnB,QAAA,2BAAA,EACAoB,UAAApB,QAAA,oBAAA,EACAqB,UAAArB,QAAA,oBAAA,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,I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J,CAAC,CACF,EACDzI,aAAA,EAAC,GAnrBYC,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\tsetInterval(() => {\n\t\t\tif (this._mainServer.getSubscriptionManager() && this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\tdate: sendItem.date\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1);\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && !this._isWorkerInstance && method !== 'insertSubscriptionLog' && method !== 'countQuery' && method !== 'incCounter' && method !== 'supportCreateBillingUser') {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\t\t\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t}, methodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\treturn methodErrs;\n\t\t\t});\n\t\t}\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && !this._isWorkerInstance && method !== 'insertSubscriptionLog' && method !== 'countQuery' && method !== 'incCounter' && method !== 'supportCreateBillingUser') {\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\t\t\t// console.log('Workers are enabled. Delegating task to worker.', taskId);\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', async (change) => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t// console.log('Task response found', taskId, taskResponse.data);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\t\n\t\t\t\t\t\tif (latency) {\n\t\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log('Sent on WS', ws['id_socket'], new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, err => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method: string, ...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 && method !== 'insertSubscriptionLog' && method !== 'countQuery' && method !== 'incCounter' && method !== 'supportCreateBillingUser') {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: functionMethodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t}, methodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\t\t\t});\n\t\t}\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_sendQueue","_runningQueue","_isWorkersEnabled","_isWorkerInstance","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","length","i","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","JSON","stringify","data","error","unsubscribeWS","method","Logs","insertOne","_id","objectIdHexString","type","collection","id_document","payload","getBinarySize","methodData","id_user","messageId","route","MethodResponses","create","__v","message_id","response","date","splice","getMainServer","methods","Object","assign","callMethodCron","_i","arguments","skipValidation","check","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","validate","errors","monitor_2","taskId_1","monitor_3","promise","startMonitorFunction","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","finishMonitorFunction","taskResponse","has_error","close","WorkerTaskRequests","params","status","_a","function","call","apply","__spreadArray","then","res","methodErrs","callMethod","id_methodLatency","messageDate","monitor_4","taskId","changeStream_1","monitor_5","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","monitor_6","taskId_2","monitor_7","functionMethodData","slice","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","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KAAK1L,EAAKJ,UAAY,aAAe4L,CAAS,EAAG,SAAU,SAAC9B,EAAKxB,GAC7EwB,EACH/C,EAAO+C,CAAG,EAGVhD,EAAQwB,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDzI,aAAA,EAAC,GAtuBYC,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\tsetInterval(() => {\n\t\t\tif (this._mainServer.getSubscriptionManager() && this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\tdate: sendItem.date\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1);\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\t\t\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t}, methodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\treturn methodErrs;\n\t\t\t});\n\t\t}\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId'\n\t\t) {\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\t\t\t// console.log('Workers are enabled. Delegating task to worker.', taskId);\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', async (change) => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t// console.log('Task response found', taskId, taskResponse.data);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\t\n\t\t\t\t\t\tif (latency) {\n\t\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log('Sent on WS', ws['id_socket'], new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, err => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method: string, ...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 && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: functionMethodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t}, methodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\t\t\t});\n\t\t}\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.3.25",
3
+ "version": "20.3.27",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",
package/server-app.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,a,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._workerQueue=[],this._workerTasks=[],this._workerBusy=!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&&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(){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,u=this;return __generator(this,function(e){switch(e.label){case 0:return console.log("Worker instance started, watching worker-task-reqs..."),setInterval(function(){!u._workerBusy&&u._workerQueue.length&&(u._workerBusy=!0,u._workerTasks.length?setTimeout(function(){u._workerQueue.length&&u.processTask()},50*u._workerTasks.length):u.processTask())},10),(r=worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"})).on("change",function(n){return __awaiter(u,void 0,void 0,function(){var r,t;return __generator(this,function(e){return"insert"===n.operationType?(r=n.fullDocument)&&!this._workerQueue.some(function(e){return e._id===r._id})&&this._workerQueue.splice(0,0,r):"update"===n.operationType&&(t=n.fullDocument)&&"pending"!==t.status&&this._workerQueue.some(function(e){return e._id===t._id})&&this._workerQueue.splice(this._workerQueue.findIndex(function(e){return e._id===t._id}),1),[2]})})}),r.on("error",function(e){console.error("Error in change stream worker task requests:",e),r.close(),setTimeout(function(){return u.startWorkerInstance()},5e3)}),r.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return u.startWorkerInstance()},5e3)}),[4,worker_task_request_collection_1.WorkerTaskRequests.find({status:"pending"},{sort:{createdAt:1}})];case 1:for(t=e.sent(),n=function(r){s._workerQueue.some(function(e){return e._id===r._id})||s._workerQueue.splice(0,0,r)},s=this,o=0,i=t;o<i.length;o++)a=i[o],n(a);return[2]}})})},ResolveIOMainServer.prototype.processTask=function(){return __awaiter(this,void 0,void 0,function(){var s,r=this;return __generator(this,function(e){return(s=this._workerQueue.pop())&&worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:s._id,status:"pending"},{$set:{status:"processing"}}).then(function(n){return __awaiter(r,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:if(this._workerBusy=!1,!n)return[3,5];this._workerTasks.push(s._id),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(t=this._methodManager.callMethodInternal).call.apply(t,__spreadArray([Object.assign({},this._methodManager,{id_user:s.id_user,user:s.user,id_ws:s.id_ws}),s.method],s.params,!1))];case 2:return t=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:s._id,has_error:!1,data:t,id_user:s.id_user,user:s.user,id_ws:s.id_ws}),[3,4];case 3:return r=e.sent(),console.error("Worker failed to process task:",s._id,r),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:s._id,has_error:!0,data:r.message,id_user:s.id_user,user:s.user,id_ws:s.id_ws}),[3,4];case 4:this._workerTasks.includes(s._id)&&this._workerTasks.splice(this._workerTasks.indexOf(s._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:s._id},{$set:{status:"complete"}}),e.label=5;case 5:return[2]}})})},function(){r._workerBusy=!1}),[2]})})},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}},10)},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._workerQueue=[],this._workerTasks=[],this._workerBusy=!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&&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(){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,u=this;return __generator(this,function(e){switch(e.label){case 0:return console.log("Worker instance started, watching worker-task-reqs..."),setInterval(function(){!u._workerBusy&&u._workerQueue.length&&(u._workerBusy=!0,u._workerTasks.length?setTimeout(function(){u._workerQueue.length&&u.processTask()},50*u._workerTasks.length):u.processTask())},10),(r=worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"})).on("change",function(n){return __awaiter(u,void 0,void 0,function(){var r,t;return __generator(this,function(e){return"insert"===n.operationType?(r=n.fullDocument)&&!this._workerQueue.some(function(e){return e._id===r._id})&&this._workerQueue.splice(0,0,r):"update"===n.operationType&&(t=n.fullDocument)&&"pending"!==t.status&&this._workerQueue.some(function(e){return e._id===t._id})&&this._workerQueue.splice(this._workerQueue.findIndex(function(e){return e._id===t._id}),1),[2]})})}),r.on("error",function(e){console.error("Error in change stream worker task requests:",e),r.close(),setTimeout(function(){return u.startWorkerInstance()},5e3)}),r.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return u.startWorkerInstance()},5e3)}),[4,worker_task_request_collection_1.WorkerTaskRequests.find({status:"pending"},{sort:{createdAt:1}})];case 1:for(t=e.sent(),n=function(r){s._workerQueue.some(function(e){return e._id===r._id})||s._workerQueue.splice(0,0,r)},s=this,o=0,i=t;o<i.length;o++)a=i[o],n(a);return[2]}})})},ResolveIOMainServer.prototype.processTask=function(){return __awaiter(this,void 0,void 0,function(){var s,r=this;return __generator(this,function(e){return(s=this._workerQueue.pop())&&worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:s._id,status:"pending"},{$set:{status:"processing"}}).then(function(n){return __awaiter(r,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:if(this._workerBusy=!1,!n)return[3,5];this._workerTasks.push(s._id),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(t=this._methodManager.callMethodInternal).call.apply(t,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:s.id_user,user:s.user,id_ws:s.id_ws}),s.method],s.params,!1))];case 2:return t=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:s._id,has_error:!1,data:t,id_user:s.id_user,user:s.user,id_ws:s.id_ws}),[3,4];case 3:return r=e.sent(),console.error("Worker failed to process task:",s._id,r),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:s._id,has_error:!0,data:r.message,id_user:s.id_user,user:s.user,id_ws:s.id_ws}),[3,4];case 4:this._workerTasks.includes(s._id)&&this._workerTasks.splice(this._workerTasks.indexOf(s._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:s._id},{$set:{status:"complete"}}),e.label=5;case 5:return[2]}})})},function(){r._workerBusy=!1}),[2]})})},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}},10)},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","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","_workerQueue","_workerTasks","_workerBusy","_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","processTask","changeStream","WorkerTaskRequests","watchCollection","$match","fullDocument.status","fullDocument","change","operationType","task_1","some","a","_id","splice","task_2","status","findIndex","find","sort","createdAt","pendingTasks","task","this_1","_i","pendingTasks_1","pop","updateOne","$set","then","resReq","push","callMethodInternal","call","apply","__spreadArray","Object","assign","id_user","user","id_ws","method","params","result","_b","WorkerTaskResponses","create","id_request","has_error","data","err_1","includes","indexOf","getActiveMonitorFunctions","setImmediate","ResolveIOServer","getMongoConnection","getIsWorkersEnabled","getIsWorkerInstance","getWS","Array","from","clients","filter","getWSList","forEach","ws","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","date","client","getClientName","objectIdHexString","createLoggedInUser","ping","duration","asMilliseconds","loggedInLatency","parseErrorFound","socketData","parse","e","readyState","OPEN","send","unsubscribeWS","messageRoute_1","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","err_3","getMongoManager","invalidateQueryCache","map","now","getTime","msg","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,EAEA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AAC,EACvB,CAACM,WAAYzC,CAAS,EACtB,CAAC5E,OAAQA,CAAM,EACf,CAACoD,KAAMuB,CAAW,EAClB,CAAC,EAAEvF,KAAK,SAAAlC,GACJA,GACC6J,GAAMA,EAAG9C,aAAe8C,EAAG7C,MAC9B6C,EAAG5C,KAAKpJ,KAAKC,UAAUkC,EAAIoK,QAAQ,EAAG,SAAChN,GAClCA,GACHpC,EAAKkM,cAAc2C,CAAE,CAEvB,CAAC,CAGJ,EAAG,SAAAjE,IAAS,GAGb5K,EAAKI,iBAAmB,CAAA,C,CAG3B,EAAG,EAAE,CACN,EAEOZ,oBAAAwE,UAAAkI,cAAP,SAAqB3C,GAChBtJ,KAAK6B,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIb,KAAQ,aAAc,WAAYmI,EAAS,KAAGA,EAAc,SAAC,EAE9EtJ,KAAK6B,qBAAqBuN,eAAe9F,CAAE,EAC3CA,EAAG+F,mBAAkB,CAEtB,EAEO9P,oBAAAwE,UAAAuL,OAAP,WACC,OAAOtP,KAAKgE,IACb,EAEOzE,oBAAAwE,UAAAwL,gBAAP,WACC,OAAOvP,KAAKgB,aACb,EACDzB,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';\nimport { WorkerTaskRequestModel } from './models/worker-task-request.model';\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\tprivate _workerQueue: WorkerTaskRequestModel[] = [];\n\tprivate _workerTasks: string[] = [];\n\tprivate _workerBusy = 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 && 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 async startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._workerBusy && this._workerQueue.length) {\n\t\t\t\tthis._workerBusy = true;\n\n\t\t\t\tif (this._workerTasks.length) {\n\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'New Task', 'Current Jobs: ' + this._workerTasks.length, 'Delay: ' + this._workerTasks.length * 50 + ' ms');\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tif (this._workerQueue.length) {\n\t\t\t\t\t\t\tthis.processTask();\n\t\t\t\t\t\t}\n\t\t\t\t\t}, this._workerTasks.length * 50);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'New Task', 'No Jobs');\n\t\t\t\t\tthis.processTask();\n\t\t\t\t}\n\t\t\t}\n\t\t}, 10);\n\t\n\t\t// Now, set up the change stream to watch for new tasks\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\t\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\t\n\t\t\t\tif (task) {\n\t\t\t\t\tif (!this._workerQueue.some(a => a._id === task._id)) {\n\t\t\t\t\t\tthis._workerQueue.splice(0, 0, task);\n\t\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Add To Queue', this._workerQueue.length);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (change.operationType === 'update') {\n\t\t\t\tconst task = change.fullDocument;\n\t\n\t\t\t\tif (task && task.status !== 'pending' && this._workerQueue.some(a => a._id === task._id)) {\n\t\t\t\t\tthis._workerQueue.splice(this._workerQueue.findIndex(a => a._id === task._id), 1);\n\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Remove From Queue', this._workerQueue.length);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\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\n\t\t// First, process any existing pending tasks in the database\n\t\tconst pendingTasks = await WorkerTaskRequests.find({ status: 'pending' }, {sort: {createdAt: 1}});\n\n\t\tfor (const task of pendingTasks) {\n\t\t\tif (!this._workerQueue.some(a => a._id === task._id)) {\n\t\t\t\tthis._workerQueue.splice(0, 0, task);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Process a task (handles both existing and new tasks)\n\tprivate async processTask() {\n\t\tlet task = this._workerQueue.pop();\n\n\t\tif (task) {\n\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Process Task', this._workerQueue.length);\n\t\t\t\n\t\t\tWorkerTaskRequests.updateOne({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } }).then(async resReq => {\n\t\t\t\tthis._workerBusy = false;\n\n\t\t\t\tif (resReq) {\n\t\t\t\t\tthis._workerTasks.push(task._id);\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Run the actual method\n\t\t\t\t\t\tconst result = await this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, { id_user: task.id_user, user: task.user, id_ws: task.id_ws }), task.method, ...task.params);\n\n\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\n\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\t\tdata: err.message,\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Mark the task as complete\n\t\t\t\t\tWorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\n\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Complete Task', 'Current Jobs: ' + this._workerTasks.length);\n\t\t\t\t}\n\t\t\t}, () => {\n\t\t\t\tthis._workerBusy = false;\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length && \n\t\t\t// (!this._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._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}, 10);\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","_workerQueue","_workerTasks","_workerBusy","_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","processTask","changeStream","WorkerTaskRequests","watchCollection","$match","fullDocument.status","fullDocument","change","operationType","task_1","some","a","_id","splice","task_2","status","findIndex","find","sort","createdAt","pendingTasks","task","this_1","_i","pendingTasks_1","pop","updateOne","$set","then","resReq","push","callMethodInternal","call","apply","__spreadArray","Object","assign","id_user","user","id_ws","method","params","result","_b","WorkerTaskResponses","create","id_request","has_error","data","err_1","includes","indexOf","getActiveMonitorFunctions","setImmediate","ResolveIOServer","getMongoConnection","getIsWorkersEnabled","getIsWorkerInstance","getWS","Array","from","clients","filter","getWSList","forEach","ws","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","date","client","getClientName","objectIdHexString","createLoggedInUser","ping","duration","asMilliseconds","loggedInLatency","parseErrorFound","socketData","parse","e","readyState","OPEN","send","unsubscribeWS","messageRoute_1","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","err_3","getMongoManager","invalidateQueryCache","map","now","getTime","msg","ws_1","messageRoute","callMethod","MethodResponses","findOne","$and","message_id","response","unsubscribeAll","removeAllListeners","getApp","getServerConfig"],"mappings":"wqDAAAA,Q,uDAAAC,QAAA,MAAA,G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,QAAQC,IAAI,0BAA4B6F,CAAM,C,KAG9B,mBAAT6E,IACJ7E,EAASQ,EAAKiF,MAAK,EAEvB1O,6BAAAmQ,gBAAgBC,QAAQ,CAACC,KAAM,CAC9B,CAACvH,QAASkH,EAAY,OAAC,EACvB,CAACM,WAAYzC,CAAS,EACtB,CAAC5E,OAAQA,CAAM,EACf,CAACoD,KAAMuB,CAAW,EAClB,CAAC,EAAEvF,KAAK,SAAAlC,GACJA,GACC6J,GAAMA,EAAG9C,aAAe8C,EAAG7C,MAC9B6C,EAAG5C,KAAKpJ,KAAKC,UAAUkC,EAAIoK,QAAQ,EAAG,SAAChN,GAClCA,GACHpC,EAAKkM,cAAc2C,CAAE,CAEvB,CAAC,CAGJ,EAAG,SAAAjE,IAAS,GAGb5K,EAAKI,iBAAmB,CAAA,C,CAG3B,EAAG,EAAE,CACN,EAEOZ,oBAAAwE,UAAAkI,cAAP,SAAqB3C,GAChBtJ,KAAK6B,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIb,KAAQ,aAAc,WAAYmI,EAAS,KAAGA,EAAc,SAAC,EAE9EtJ,KAAK6B,qBAAqBuN,eAAe9F,CAAE,EAC3CA,EAAG+F,mBAAkB,CAEtB,EAEO9P,oBAAAwE,UAAAuL,OAAP,WACC,OAAOtP,KAAKgE,IACb,EAEOzE,oBAAAwE,UAAAwL,gBAAP,WACC,OAAOvP,KAAKgB,aACb,EACDzB,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';\nimport { WorkerTaskRequestModel } from './models/worker-task-request.model';\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\tprivate _workerQueue: WorkerTaskRequestModel[] = [];\n\tprivate _workerTasks: string[] = [];\n\tprivate _workerBusy = 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 && 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 async startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._workerBusy && this._workerQueue.length) {\n\t\t\t\tthis._workerBusy = true;\n\n\t\t\t\tif (this._workerTasks.length) {\n\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'New Task', 'Current Jobs: ' + this._workerTasks.length, 'Delay: ' + this._workerTasks.length * 50 + ' ms');\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tif (this._workerQueue.length) {\n\t\t\t\t\t\t\tthis.processTask();\n\t\t\t\t\t\t}\n\t\t\t\t\t}, this._workerTasks.length * 50);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'New Task', 'No Jobs');\n\t\t\t\t\tthis.processTask();\n\t\t\t\t}\n\t\t\t}\n\t\t}, 10);\n\t\n\t\t// Now, set up the change stream to watch for new tasks\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\t\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\t\n\t\t\t\tif (task) {\n\t\t\t\t\tif (!this._workerQueue.some(a => a._id === task._id)) {\n\t\t\t\t\t\tthis._workerQueue.splice(0, 0, task);\n\t\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Add To Queue', this._workerQueue.length);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (change.operationType === 'update') {\n\t\t\t\tconst task = change.fullDocument;\n\t\n\t\t\t\tif (task && task.status !== 'pending' && this._workerQueue.some(a => a._id === task._id)) {\n\t\t\t\t\tthis._workerQueue.splice(this._workerQueue.findIndex(a => a._id === task._id), 1);\n\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Remove From Queue', this._workerQueue.length);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\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\n\t\t// First, process any existing pending tasks in the database\n\t\tconst pendingTasks = await WorkerTaskRequests.find({ status: 'pending' }, {sort: {createdAt: 1}});\n\n\t\tfor (const task of pendingTasks) {\n\t\t\tif (!this._workerQueue.some(a => a._id === task._id)) {\n\t\t\t\tthis._workerQueue.splice(0, 0, task);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Process a task (handles both existing and new tasks)\n\tprivate async processTask() {\n\t\tlet task = this._workerQueue.pop();\n\n\t\tif (task) {\n\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Process Task', this._workerQueue.length);\n\t\t\t\n\t\t\tWorkerTaskRequests.updateOne({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } }).then(async resReq => {\n\t\t\t\tthis._workerBusy = false;\n\n\t\t\t\tif (resReq) {\n\t\t\t\t\tthis._workerTasks.push(task._id);\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Run the actual method\n\t\t\t\t\t\tconst result = await this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, { id_user: task.id_user, user: task.user, id_ws: task.id_ws }), task.method, ...task.params);\n\n\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\n\t\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\t\tdata: err.message,\n\t\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Mark the task as complete\n\t\t\t\t\tWorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\n\t\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Complete Task', 'Current Jobs: ' + this._workerTasks.length);\n\t\t\t\t}\n\t\t\t}, () => {\n\t\t\t\tthis._workerBusy = false;\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length && \n\t\t\t// (!this._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._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}, 10);\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}"]}