@resolveio/server-lib 20.4.83 → 20.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/fixtures/init.d.ts +1 -1
  2. package/fixtures/init.js +1 -1
  3. package/fixtures/init.js.map +1 -1
  4. package/index.d.ts +8 -0
  5. package/index.js +1 -1
  6. package/index.js.map +1 -1
  7. package/managers/cron.manager.d.ts +1 -2
  8. package/managers/cron.manager.js +1 -1
  9. package/managers/cron.manager.js.map +1 -1
  10. package/managers/local-log.manager.d.ts +16 -0
  11. package/managers/local-log.manager.js +2 -0
  12. package/managers/local-log.manager.js.map +1 -0
  13. package/managers/method.manager.d.ts +2 -8
  14. package/managers/method.manager.js +1 -1
  15. package/managers/method.manager.js.map +1 -1
  16. package/managers/mongo.manager.d.ts +1 -2
  17. package/managers/mongo.manager.js +1 -1
  18. package/managers/mongo.manager.js.map +1 -1
  19. package/managers/monitor.manager.d.ts +2 -3
  20. package/managers/monitor.manager.js +1 -1
  21. package/managers/monitor.manager.js.map +1 -1
  22. package/managers/subscription.manager.d.ts +1 -2
  23. package/managers/subscription.manager.js +1 -1
  24. package/managers/subscription.manager.js.map +1 -1
  25. package/managers/websocket.manager.js.map +1 -1
  26. package/methods/logs.js +1 -1
  27. package/methods/logs.js.map +1 -1
  28. package/package.json +1 -1
  29. package/server-app.d.ts +1 -3
  30. package/server-app.js +1 -1
  31. package/server-app.js.map +1 -1
  32. package/collections/log-ts.collection.d.ts +0 -3
  33. package/collections/log-ts.collection.js +0 -2
  34. package/collections/log-ts.collection.js.map +0 -1
  35. package/managers/subscription.performance.d.ts +0 -1
  36. package/managers/subscription.performance.js +0 -2
  37. package/managers/subscription.performance.js.map +0 -1
@@ -1 +1 @@
1
- export declare function loadServerInit(serverConfig: any): Promise<void>;
1
+ export declare function loadServerInit(): Promise<void>;
package/fixtures/init.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,l,r,o){return new(r=r||Promise)(function(n,t){function fulfilled(e){try{step(o.next(e))}catch(e){t(e)}}function rejected(e){try{step(o.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?n(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(fulfilled,rejected)}step((o=o.apply(e,l||[])).next())})},__generator=this&&this.__generator||function(l,r){var o,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function verb(n){return function(e){var t=[n,e];if(o)throw new TypeError("Generator is already executing.");for(;c=s&&t[s=0]?0:c;)try{if(o=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,i=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=r.call(l,c)}catch(e){t=[6,e],i=0}finally{o=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},flag_collection_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.loadServerInit=void 0,require("../collections/flag.collection")),email_history_collection_1=require("../collections/email-history.collection");function loadServerInit(n){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return email_history_collection_1.EmailHistories.updateMany({status:"processing"},{$set:{status:"pending"}}),[4,flag_collection_1.Flags.findOne({type:"Enable Debug"})];case 1:return e.sent()||flag_collection_1.Flags.insertOne({type:"Enable Debug",value:!1}),[4,flag_collection_1.Flags.findOne({type:"Enable Debug PDF"})];case 2:return(t=e.sent())?t.value&&"http://localhost:4200"!==n.ROOT_URL&&flag_collection_1.Flags.updateOne({_id:t._id},{$set:{value:!1}}):flag_collection_1.Flags.insertOne({type:"Enable Debug PDF",value:!1}),[2]}})})}exports.loadServerInit=loadServerInit;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,r,l,o){return new(l=l||Promise)(function(n,t){function fulfilled(e){try{step(o.next(e))}catch(e){t(e)}}function rejected(e){try{step(o.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?n(e.value):((t=e.value)instanceof l?t:new l(function(e){e(t)})).then(fulfilled,rejected)}step((o=o.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,l){var o,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function verb(n){return function(e){var t=[n,e];if(o)throw new TypeError("Generator is already executing.");for(;c=s&&t[s=0]?0:c;)try{if(o=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,i=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=l.call(r,c)}catch(e){t=[6,e],i=0}finally{o=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},flag_collection_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.loadServerInit=void 0,require("../collections/flag.collection")),email_history_collection_1=require("../collections/email-history.collection"),__1=require("..");function loadServerInit(){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return email_history_collection_1.EmailHistories.updateMany({status:"processing"},{$set:{status:"pending"}}),[4,flag_collection_1.Flags.findOne({type:"Enable Debug"})];case 1:return e.sent()||flag_collection_1.Flags.insertOne({type:"Enable Debug",value:!1}),[4,flag_collection_1.Flags.findOne({type:"Enable Debug PDF"})];case 2:return(t=e.sent())?t.value&&"http://localhost:4200"!==__1.ResolveIOServer.getServerConfig().ROOT_URL&&flag_collection_1.Flags.updateOne({_id:t._id},{$set:{value:!1}}):flag_collection_1.Flags.insertOne({type:"Enable Debug PDF",value:!1}),[2]}})})}exports.loadServerInit=loadServerInit;
2
2
  //# sourceMappingURL=init.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/fixtures/init.ts"],"names":["flag_collection_1","require","email_history_collection_1","loadServerInit","serverConfig","EmailHistories","updateMany","status","$set","Flags","findOne","type","_a","sent","insertOne","value","enableDebugFlagPDF","updateOne","_id","exports"],"mappings":"k8CACAA,mB,qFAAAC,QAAA,gCAAA,GACAC,2BAAAD,QAAA,yCAAA,EAEA,SAAsBE,eAAeC,G,gHAGd,OAFtBF,2BAAAG,eAAeC,WAAW,CAACC,OAAQ,YAAY,EAAG,CAACC,KAAM,CAACD,OAAQ,SAAS,CAAC,CAAC,EAEvD,CAAA,EAAMP,kBAAAS,MAAMC,QAAQ,CAACC,KAAM,cAAc,CAAC,G,OAMvC,OANHC,EAAAC,KAAA,GAGrBb,kBAAAS,MAAMK,UAAU,CAACH,KAAM,eAAgBI,MAAO,CAAA,CAAK,CAAC,EAG5B,CAAA,EAAMf,kBAAAS,MAAMC,QAAQ,CAACC,KAAM,kBAAkB,CAAC,G,cAAnEK,EAAqBJ,EAAAC,KAAA,GAKhBG,EAAmBD,OAAsC,0BAA7BX,EAAuB,UAC3DJ,kBAAAS,MAAMQ,UAAU,CAACC,IAAKF,EAAmBE,GAAG,EAAG,CAACV,KAAM,CAACO,MAAO,CAAA,CAAK,CAAC,CAAC,EAHrEf,kBAAAS,MAAMK,UAAU,CAACH,KAAM,mBAAoBI,MAAO,CAAA,CAAK,CAAC,E,SAZ1DI,QAAAhB,eAAAA","file":"init.js","sourcesContent":["import { objectIdHexString } from '../managers/mongo.manager';\nimport { Flags } from '../collections/flag.collection';\nimport { EmailHistories } from '../collections/email-history.collection';\n\nexport async function loadServerInit(serverConfig) {\n\tEmailHistories.updateMany({status: 'processing'}, {$set: {status: 'pending'}});\n\n\tlet enableDebugFlag = await Flags.findOne({type: 'Enable Debug'});\n\n\tif (!enableDebugFlag) {\n\t\tFlags.insertOne({type: 'Enable Debug', value: false});\n\t}\n\n\tlet enableDebugFlagPDF = await Flags.findOne({type: 'Enable Debug PDF'});\n\n\tif (!enableDebugFlagPDF) {\n\t\tFlags.insertOne({type: 'Enable Debug PDF', value: false});\n\t}\n\telse if (enableDebugFlagPDF.value && serverConfig['ROOT_URL'] !== 'http://localhost:4200') {\n\t\tFlags.updateOne({_id: enableDebugFlagPDF._id}, {$set: {value: false}});\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/fixtures/init.ts"],"names":["flag_collection_1","require","email_history_collection_1","__1","loadServerInit","EmailHistories","updateMany","status","$set","Flags","findOne","type","_a","sent","insertOne","value","enableDebugFlagPDF","ResolveIOServer","getServerConfig","updateOne","_id","exports"],"mappings":"k8CACAA,mB,qFAAAC,QAAA,gCAAA,GACAC,2BAAAD,QAAA,yCAAA,EACAE,IAAAF,QAAA,IAAA,EAEA,SAAsBG,iB,gHAGC,OAFtBF,2BAAAG,eAAeC,WAAW,CAACC,OAAQ,YAAY,EAAG,CAACC,KAAM,CAACD,OAAQ,SAAS,CAAC,CAAC,EAEvD,CAAA,EAAMP,kBAAAS,MAAMC,QAAQ,CAACC,KAAM,cAAc,CAAC,G,OAMvC,OANHC,EAAAC,KAAA,GAGrBb,kBAAAS,MAAMK,UAAU,CAACH,KAAM,eAAgBI,MAAO,CAAA,CAAK,CAAC,EAG5B,CAAA,EAAMf,kBAAAS,MAAMC,QAAQ,CAACC,KAAM,kBAAkB,CAAC,G,cAAnEK,EAAqBJ,EAAAC,KAAA,GAKhBG,EAAmBD,OAA2D,0BAAlDZ,IAAAc,gBAAgBC,gBAAe,EAAa,UAChFlB,kBAAAS,MAAMU,UAAU,CAACC,IAAKJ,EAAmBI,GAAG,EAAG,CAACZ,KAAM,CAACO,MAAO,CAAA,CAAK,CAAC,CAAC,EAHrEf,kBAAAS,MAAMK,UAAU,CAACH,KAAM,mBAAoBI,MAAO,CAAA,CAAK,CAAC,E,SAZ1DM,QAAAjB,eAAAA","file":"init.js","sourcesContent":["import { objectIdHexString } from '../managers/mongo.manager';\nimport { Flags } from '../collections/flag.collection';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { ResolveIOServer } from '..';\n\nexport async function loadServerInit() {\n\tEmailHistories.updateMany({status: 'processing'}, {$set: {status: 'pending'}});\n\n\tlet enableDebugFlag = await Flags.findOne({type: 'Enable Debug'});\n\n\tif (!enableDebugFlag) {\n\t\tFlags.insertOne({type: 'Enable Debug', value: false});\n\t}\n\n\tlet enableDebugFlagPDF = await Flags.findOne({type: 'Enable Debug PDF'});\n\n\tif (!enableDebugFlagPDF) {\n\t\tFlags.insertOne({type: 'Enable Debug PDF', value: false});\n\t}\n\telse if (enableDebugFlagPDF.value && ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200') {\n\t\tFlags.updateOne({_id: enableDebugFlagPDF._id}, {$set: {value: false}});\n\t}\n}"]}
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Db, MongoClient } from 'mongodb';
2
+ import { LocalLogManager } from './managers/local-log.manager';
2
3
  import { MongoManager } from './managers/mongo.manager';
3
4
  import ResolveIOMainServer from './server-app';
4
5
  export declare class ResolveIOServer {
@@ -7,6 +8,7 @@ export declare class ResolveIOServer {
7
8
  private static _mongoConnection;
8
9
  private static _mainDB;
9
10
  private static _mainServer;
11
+ private static _localLogManager;
10
12
  private static _mongoManager;
11
13
  private static _client;
12
14
  private static _clientDir;
@@ -19,5 +21,11 @@ export declare class ResolveIOServer {
19
21
  static getMongoConnection(): MongoClient;
20
22
  static getMainDB(): Db;
21
23
  static getMongoManager(): MongoManager;
24
+ static getLocalLogManager(): LocalLogManager;
25
+ static getServerConfig(): any;
26
+ static getClientRoutes(): any[];
27
+ static getClientDir(): string;
28
+ static getSESMail(): boolean;
29
+ static getStandardProgram(): boolean;
22
30
  }
23
31
  export * from './public_api';
package/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,r,n,o){void 0===o&&(o=n);var t=Object.getOwnPropertyDescriptor(r,n);t&&("get"in t?r.__esModule:!t.writable&&!t.configurable)||(t={enumerable:!0,get:function(){return r[n]}}),Object.defineProperty(e,o,t)}:function(e,r,n,o){e[o=void 0===o?n:o]=r[n]}),__exportStar=this&&this.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||__createBinding(r,e,n)},__awaiter=this&&this.__awaiter||function(e,o,t,i){return new(t=t||Promise)(function(n,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?n(e.value):((r=e.value)instanceof t?r:new t(function(e){e(r)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,t){var i,l,s,v={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},a={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function verb(n){return function(e){var r=[n,e];if(i)throw new TypeError("Generator is already executing.");for(;v=a&&r[a=0]?0:v;)try{if(i=1,l&&(s=2&r[0]?l.return:r[0]?l.throw||((s=l.return)&&s.call(l),0):l.next)&&!(s=s.call(l,r[1])).done)return s;switch(l=0,(r=s?[2&r[0],s.value]:r)[0]){case 0:case 1:s=r;break;case 4:return v.label++,{value:r[1],done:!1};case 5:v.label++,l=r[1],r=[0];continue;case 7:r=v.ops.pop(),v.trys.pop();continue;default:if(!(s=0<(s=v.trys).length&&s[s.length-1])&&(6===r[0]||2===r[0])){v=0;continue}if(3===r[0]&&(!s||r[1]>s[0]&&r[1]<s[3]))v.label=r[1];else if(6===r[0]&&v.label<s[1])v.label=s[1],s=r;else{if(!(s&&v.label<s[2])){s[2]&&v.ops.pop(),v.trys.pop();continue}v.label=s[2],v.ops.push(r)}}r=t.call(o,v)}catch(e){r=[6,e],l=0}finally{i=s=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},mongodb_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOServer=void 0,require("mongodb")),mongo_manager_1=require("./managers/mongo.manager"),ResolveIOServer=function(){function ResolveIOServer(e,r,n,o,t,i){void 0===t&&(t=!0),void 0===i&&(i=!1),ResolveIOServer._serverConfig=e,ResolveIOServer._clientRoutes=r,ResolveIOServer._client=n,ResolveIOServer._clientDir=o,ResolveIOServer._sesMail=t,ResolveIOServer._standardProgram=i}return ResolveIOServer.connectAndRun=function(){var o=this;return new Promise(function(n,r){mongodb_1.MongoClient.connect(ResolveIOServer._serverConfig.MONGO_URL).then(function(e){ResolveIOServer._mongoConnection=e,ResolveIOServer._mainDB=e.db(ResolveIOServer._serverConfig.DATABASE),ResolveIOServer._mongoManager=new mongo_manager_1.MongoManager(ResolveIOServer._serverConfig),setTimeout(function(){return __awaiter(o,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return[4,Promise.resolve().then(function(){return require("./server-app")})];case 1:return r=e.sent().default,ResolveIOServer._mainServer=new r(this,ResolveIOServer._serverConfig,ResolveIOServer._clientRoutes,this._clientDir,this._sesMail,this._standardProgram),n(!0),[2]}})})},1)},function(e){console.error(new Date,"MONGO CLIENT CONNECT FAILED",JSON.stringify(e,null,2)),r(),process.exit(1)})})},ResolveIOServer.getClientName=function(){return this._client},ResolveIOServer.getMainServer=function(){return ResolveIOServer._mainServer},ResolveIOServer.getMongoConnection=function(){return ResolveIOServer._mongoConnection},ResolveIOServer.getMainDB=function(){return ResolveIOServer._mainDB},ResolveIOServer.getMongoManager=function(){return ResolveIOServer._mongoManager},ResolveIOServer._serverConfig=null,ResolveIOServer._clientRoutes=[],ResolveIOServer._mongoConnection=null,ResolveIOServer._mainDB=null,ResolveIOServer._mainServer=null,ResolveIOServer._mongoManager=null,ResolveIOServer._client="",ResolveIOServer._clientDir="",ResolveIOServer._sesMail=!0,ResolveIOServer._standardProgram=!1,ResolveIOServer}();exports.ResolveIOServer=ResolveIOServer,__exportStar(require("./public_api"),exports);
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,r,n,o){void 0===o&&(o=n);var t=Object.getOwnPropertyDescriptor(r,n);t&&("get"in t?r.__esModule:!t.writable&&!t.configurable)||(t={enumerable:!0,get:function(){return r[n]}}),Object.defineProperty(e,o,t)}:function(e,r,n,o){e[o=void 0===o?n:o]=r[n]}),__exportStar=this&&this.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||__createBinding(r,e,n)},__awaiter=this&&this.__awaiter||function(e,o,t,l){return new(t=t||Promise)(function(n,r){function fulfilled(e){try{step(l.next(e))}catch(e){r(e)}}function rejected(e){try{step(l.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?n(e.value):((r=e.value)instanceof t?r:new t(function(e){e(r)})).then(fulfilled,rejected)}step((l=l.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,t){var l,i,a,v={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function verb(n){return function(e){var r=[n,e];if(l)throw new TypeError("Generator is already executing.");for(;v=s&&r[s=0]?0:v;)try{if(l=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 v.label++,{value:r[1],done:!1};case 5:v.label++,i=r[1],r=[0];continue;case 7:r=v.ops.pop(),v.trys.pop();continue;default:if(!(a=0<(a=v.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){v=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))v.label=r[1];else if(6===r[0]&&v.label<a[1])v.label=a[1],a=r;else{if(!(a&&v.label<a[2])){a[2]&&v.ops.pop(),v.trys.pop();continue}v.label=a[2],v.ops.push(r)}}r=t.call(o,v)}catch(e){r=[6,e],i=0}finally{l=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},mongodb_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOServer=void 0,require("mongodb")),local_log_manager_1=require("./managers/local-log.manager"),mongo_manager_1=require("./managers/mongo.manager"),ResolveIOServer=function(){function ResolveIOServer(e,r,n,o,t,l){void 0===t&&(t=!0),void 0===l&&(l=!1),ResolveIOServer._serverConfig=e,ResolveIOServer._clientRoutes=r,ResolveIOServer._client=n,ResolveIOServer._clientDir=o,ResolveIOServer._sesMail=t,ResolveIOServer._standardProgram=l}return ResolveIOServer.connectAndRun=function(){var o=this;return new Promise(function(n,r){o._localLogManager=new local_log_manager_1.LocalLogManager,mongodb_1.MongoClient.connect(ResolveIOServer._serverConfig.MONGO_URL).then(function(e){ResolveIOServer._mongoConnection=e,ResolveIOServer._mainDB=e.db(ResolveIOServer._serverConfig.DATABASE),ResolveIOServer._mongoManager=new mongo_manager_1.MongoManager,setTimeout(function(){return __awaiter(o,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return[4,Promise.resolve().then(function(){return require("./server-app")})];case 1:return r=e.sent().default,ResolveIOServer._mainServer=new r,n(!0),[2]}})})},1)},function(e){console.error(new Date,"MONGO CLIENT CONNECT FAILED",JSON.stringify(e,null,2)),r(),process.exit(1)})})},ResolveIOServer.getClientName=function(){return this._client},ResolveIOServer.getMainServer=function(){return ResolveIOServer._mainServer},ResolveIOServer.getMongoConnection=function(){return ResolveIOServer._mongoConnection},ResolveIOServer.getMainDB=function(){return ResolveIOServer._mainDB},ResolveIOServer.getMongoManager=function(){return ResolveIOServer._mongoManager},ResolveIOServer.getLocalLogManager=function(){return ResolveIOServer._localLogManager},ResolveIOServer.getServerConfig=function(){return ResolveIOServer._serverConfig},ResolveIOServer.getClientRoutes=function(){return ResolveIOServer._clientRoutes},ResolveIOServer.getClientDir=function(){return ResolveIOServer._clientDir},ResolveIOServer.getSESMail=function(){return ResolveIOServer._sesMail},ResolveIOServer.getStandardProgram=function(){return ResolveIOServer._standardProgram},ResolveIOServer._serverConfig=null,ResolveIOServer._clientRoutes=[],ResolveIOServer._mongoConnection=null,ResolveIOServer._mainDB=null,ResolveIOServer._mainServer=null,ResolveIOServer._localLogManager=null,ResolveIOServer._mongoManager=null,ResolveIOServer._client="",ResolveIOServer._clientDir="",ResolveIOServer._sesMail=!0,ResolveIOServer._standardProgram=!1,ResolveIOServer}();exports.ResolveIOServer=ResolveIOServer,__exportStar(require("./public_api"),exports);
2
2
  //# sourceMappingURL=index.js.map
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"names":["mongodb_1","require","mongo_manager_1","ResolveIOServer","serverConfig","clientRoutes","client","clientDir","sesMail","standardProgram","_serverConfig","_clientRoutes","_client","_clientDir","_sesMail","_standardProgram","connectAndRun","_this","this","Promise","resolve","reject","MongoClient","connect","then","dbConnection","_mongoConnection","_mainDB","db","_mongoManager","MongoManager","setTimeout","__awaiter","serverApp","_a","sent","default","_mainServer","err","console","error","Date","JSON","stringify","process","exit","getClientName","getMainServer","getMongoConnection","getMainDB","getMongoManager","exports","__exportStar"],"mappings":"s5DAAAA,W,sFAAAC,QAAA,SAAA,GACAC,gBAAAD,QAAA,0BAAA,EAGAE,gBAAA,WAYC,SAAAA,gBAAYC,EAAcC,EAAwBC,EAAgBC,EAAWC,EAAgBC,GAAhB,KAAA,IAAAD,IAAAA,EAAA,CAAA,GAAgB,KAAA,IAAAC,IAAAA,EAAA,CAAA,GAC5FN,gBAAgBO,cAAgBN,EAChCD,gBAAgBQ,cAAgBN,EAChCF,gBAAgBS,QAAUN,EAC1BH,gBAAgBU,WAAaN,EAC7BJ,gBAAgBW,SAAWN,EAC3BL,gBAAgBY,iBAAmBN,CACpC,CA6CD,OA3CeN,gBAAAa,cAAd,WAAA,IAAAC,EAAAC,KACC,OAAO,IAAIC,QAAQ,SAACC,EAASC,GAC5BrB,UAAAsB,YAAYC,QAAQpB,gBAAgBO,cAAyB,SAAC,EAAEc,KAAK,SAAAC,GAEnEtB,gBAAgBuB,iBAAmBD,EACnCtB,gBAAgBwB,QAAUF,EAAaG,GAAGzB,gBAAgBO,cAAwB,QAAC,EAEnFP,gBAAgB0B,cAAgB,IAAI3B,gBAAA4B,aAAa3B,gBAAgBO,aAAa,EAE9EqB,WAAW,WAAA,OAAAC,UAAAf,EAAA,KAAA,EAAA,KAAA,EAAA,W,iEACO,MAAA,CAAA,EAAAE,QAAAC,QAAA,EAAAI,KAAA,WAAA,OAAAvB,QAAa,cAAc,CAAA,CAAA,G,cAAxCgC,EAAaC,EAAAC,KAA4B,EAAEC,QAC/CjC,gBAAgBkC,YAAc,IAAIJ,EAAUf,KAAMf,gBAAgBO,cAAeP,gBAAgBQ,cAAeO,KAAKL,WAAYK,KAAKJ,SAAUI,KAAKH,gBAAgB,EAErKK,EAAQ,CAAA,CAAI,E,UACV,CAAC,CAEN,EAAG,SAAAkB,GACFC,QAAQC,MAAM,IAAIC,KAAQ,8BAA+BC,KAAKC,UAAUL,EAAK,KAAM,CAAC,CAAC,EACrFjB,EAAM,EACNuB,QAAQC,KAAK,CAAC,CACf,CAAC,CACF,CAAC,CACF,EAEc1C,gBAAA2C,cAAd,WACC,OAAO5B,KAAKN,OACb,EAEcT,gBAAA4C,cAAd,WACC,OAAO5C,gBAAgBkC,WACxB,EAEclC,gBAAA6C,mBAAd,WACC,OAAO7C,gBAAgBuB,gBACxB,EAEcvB,gBAAA8C,UAAd,WACC,OAAO9C,gBAAgBwB,OACxB,EAEcxB,gBAAA+C,gBAAd,WACC,OAAO/C,gBAAgB0B,aACxB,EA9De1B,gBAAAO,cAAgB,KAChBP,gBAAAQ,cAAgB,GAChBR,gBAAAuB,iBAAgC,KAChCvB,gBAAAwB,QAAc,KACdxB,gBAAAkC,YAAmC,KACnClC,gBAAA0B,cAA8B,KAC9B1B,gBAAAS,QAAU,GACVT,gBAAAU,WAAa,GACbV,gBAAAW,SAAW,CAAA,EACXX,gBAAAY,iBAAmB,CAAA,EAsDnCZ,e,EAAC,EAhEYgD,QAAAhD,gBAAAA,gBAkEbiD,aAAAnD,QAAA,cAAA,EAAAkD,OAAA","file":"index.js","sourcesContent":["import { Db, MongoClient } from 'mongodb';\nimport { MongoManager } from './managers/mongo.manager';\nimport ResolveIOMainServer from './server-app';\n\nexport class ResolveIOServer {\n\tprivate static _serverConfig = null;\n\tprivate static _clientRoutes = [];\n\tprivate static _mongoConnection: MongoClient = null;\n\tprivate static _mainDB: Db = null;\n\tprivate static _mainServer: ResolveIOMainServer = null;\n\tprivate static _mongoManager: MongoManager = null;\n\tprivate static _client = '';\n\tprivate static _clientDir = '';\n\tprivate static _sesMail = true;\n\tprivate static _standardProgram = false;\n\n\tconstructor(serverConfig, clientRoutes: string[], client: string, clientDir, sesMail = true, standardProgram = false) {\n\t\tResolveIOServer._serverConfig = serverConfig;\n\t\tResolveIOServer._clientRoutes = clientRoutes;\n\t\tResolveIOServer._client = client;\n\t\tResolveIOServer._clientDir = clientDir;\n\t\tResolveIOServer._sesMail = sesMail;\n\t\tResolveIOServer._standardProgram = standardProgram;\n\t}\n\n\tpublic static connectAndRun() {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tMongoClient.connect(ResolveIOServer._serverConfig['MONGO_URL']).then(dbConnection => {\n\t\t\t\t// dbConnection.db().listCollections().toArray().then(collections => {\n\t\t\t\t\tResolveIOServer._mongoConnection = dbConnection;\n\t\t\t\t\tResolveIOServer._mainDB = dbConnection.db(ResolveIOServer._serverConfig['DATABASE']);\n\t\t\t\t\t// ResolveIOServer._mongoManager = new MongoManager(collections);\n\t\t\t\t\tResolveIOServer._mongoManager = new MongoManager(ResolveIOServer._serverConfig);\n\t\t\t\t\t\n\t\t\t\t\tsetTimeout(async () => {\n\t\t\t\t\t\tlet serverApp = (await import('./server-app')).default;\n\t\t\t\t\t\tResolveIOServer._mainServer = new serverApp(this, ResolveIOServer._serverConfig, ResolveIOServer._clientRoutes, this._clientDir, this._sesMail, this._standardProgram);\n\n\t\t\t\t\t\tresolve(true);\n\t\t\t\t\t}, 1);\n\t\t\t\t// });\n\t\t\t}, err => {\n\t\t\t\tconsole.error(new Date(), 'MONGO CLIENT CONNECT FAILED', JSON.stringify(err, null, 2));\n\t\t\t\treject();\n\t\t\t\tprocess.exit(1);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic static getClientName() {\n\t\treturn this._client;\n\t}\n\n\tpublic static getMainServer() {\n\t\treturn ResolveIOServer._mainServer;\n\t}\n\n\tpublic static getMongoConnection() {\n\t\treturn ResolveIOServer._mongoConnection;\n\t}\n\n\tpublic static getMainDB() {\n\t\treturn ResolveIOServer._mainDB;\n\t}\n\n\tpublic static getMongoManager() {\n\t\treturn ResolveIOServer._mongoManager;\n\t}\n}\n\nexport * from './public_api';"]}
1
+ {"version":3,"sources":["../../src/index.ts"],"names":["mongodb_1","require","local_log_manager_1","mongo_manager_1","ResolveIOServer","serverConfig","clientRoutes","client","clientDir","sesMail","standardProgram","_serverConfig","_clientRoutes","_client","_clientDir","_sesMail","_standardProgram","connectAndRun","_this","this","Promise","resolve","reject","_localLogManager","LocalLogManager","MongoClient","connect","then","dbConnection","_mongoConnection","_mainDB","db","_mongoManager","MongoManager","setTimeout","__awaiter","serverApp","_a","sent","default","_mainServer","err","console","error","Date","JSON","stringify","process","exit","getClientName","getMainServer","getMongoConnection","getMainDB","getMongoManager","getLocalLogManager","getServerConfig","getClientRoutes","getClientDir","getSESMail","getStandardProgram","exports","__exportStar"],"mappings":"s5DAAAA,W,sFAAAC,QAAA,SAAA,GACAC,oBAAAD,QAAA,8BAAA,EACAE,gBAAAF,QAAA,0BAAA,EAGAG,gBAAA,WAaC,SAAAA,gBAAYC,EAAcC,EAAwBC,EAAgBC,EAAWC,EAAgBC,GAAhB,KAAA,IAAAD,IAAAA,EAAA,CAAA,GAAgB,KAAA,IAAAC,IAAAA,EAAA,CAAA,GAC5FN,gBAAgBO,cAAgBN,EAChCD,gBAAgBQ,cAAgBN,EAChCF,gBAAgBS,QAAUN,EAC1BH,gBAAgBU,WAAaN,EAC7BJ,gBAAgBW,SAAWN,EAC3BL,gBAAgBY,iBAAmBN,CACpC,CAuED,OArEeN,gBAAAa,cAAd,WAAA,IAAAC,EAAAC,KACC,OAAO,IAAIC,QAAQ,SAACC,EAASC,GAC5BJ,EAAKK,iBAAmB,IAAIrB,oBAAAsB,gBAE5BxB,UAAAyB,YAAYC,QAAQtB,gBAAgBO,cAAyB,SAAC,EAAEgB,KAAK,SAAAC,GAEnExB,gBAAgByB,iBAAmBD,EACnCxB,gBAAgB0B,QAAUF,EAAaG,GAAG3B,gBAAgBO,cAAwB,QAAC,EAEnFP,gBAAgB4B,cAAgB,IAAI7B,gBAAA8B,aAEpCC,WAAW,WAAA,OAAAC,UAAAjB,EAAA,KAAA,EAAA,KAAA,EAAA,W,iEACO,MAAA,CAAA,EAAAE,QAAAC,QAAA,EAAAM,KAAA,WAAA,OAAA1B,QAAa,cAAc,C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AA,EAAA2D,OAAA","file":"index.js","sourcesContent":["import { Db, MongoClient } from 'mongodb';\nimport { LocalLogManager } from './managers/local-log.manager';\nimport { MongoManager } from './managers/mongo.manager';\nimport ResolveIOMainServer from './server-app';\n\nexport class ResolveIOServer {\n\tprivate static _serverConfig = null;\n\tprivate static _clientRoutes = [];\n\tprivate static _mongoConnection: MongoClient = null;\n\tprivate static _mainDB: Db = null;\n\tprivate static _mainServer: ResolveIOMainServer = null;\n\tprivate static _localLogManager: LocalLogManager = null;\n\tprivate static _mongoManager: MongoManager = null;\n\tprivate static _client = '';\n\tprivate static _clientDir = '';\n\tprivate static _sesMail = true;\n\tprivate static _standardProgram = false;\n\n\tconstructor(serverConfig, clientRoutes: string[], client: string, clientDir, sesMail = true, standardProgram = false) {\n\t\tResolveIOServer._serverConfig = serverConfig;\n\t\tResolveIOServer._clientRoutes = clientRoutes;\n\t\tResolveIOServer._client = client;\n\t\tResolveIOServer._clientDir = clientDir;\n\t\tResolveIOServer._sesMail = sesMail;\n\t\tResolveIOServer._standardProgram = standardProgram;\n\t}\n\n\tpublic static connectAndRun() {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis._localLogManager = new LocalLogManager();\n\n\t\t\tMongoClient.connect(ResolveIOServer._serverConfig['MONGO_URL']).then(dbConnection => {\n\t\t\t\t// dbConnection.db().listCollections().toArray().then(collections => {\n\t\t\t\t\tResolveIOServer._mongoConnection = dbConnection;\n\t\t\t\t\tResolveIOServer._mainDB = dbConnection.db(ResolveIOServer._serverConfig['DATABASE']);\n\t\t\t\t\t// ResolveIOServer._mongoManager = new MongoManager(collections);\n\t\t\t\t\tResolveIOServer._mongoManager = new MongoManager();\n\t\t\t\t\t\n\t\t\t\t\tsetTimeout(async () => {\n\t\t\t\t\t\tlet serverApp = (await import('./server-app')).default;\n\t\t\t\t\t\tResolveIOServer._mainServer = new serverApp();\n\n\t\t\t\t\t\tresolve(true);\n\t\t\t\t\t}, 1);\n\t\t\t\t// });\n\t\t\t}, err => {\n\t\t\t\tconsole.error(new Date(), 'MONGO CLIENT CONNECT FAILED', JSON.stringify(err, null, 2));\n\t\t\t\treject();\n\t\t\t\tprocess.exit(1);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic static getClientName() {\n\t\treturn this._client;\n\t}\n\n\tpublic static getMainServer() {\n\t\treturn ResolveIOServer._mainServer;\n\t}\n\n\tpublic static getMongoConnection() {\n\t\treturn ResolveIOServer._mongoConnection;\n\t}\n\n\tpublic static getMainDB() {\n\t\treturn ResolveIOServer._mainDB;\n\t}\n\n\tpublic static getMongoManager() {\n\t\treturn ResolveIOServer._mongoManager;\n\t}\n\n\tpublic static getLocalLogManager() {\n\t\treturn ResolveIOServer._localLogManager;\n\t}\n\n\tpublic static getServerConfig() {\n\t\treturn ResolveIOServer._serverConfig;\n\t}\n\n\tpublic static getClientRoutes() {\n\t\treturn ResolveIOServer._clientRoutes;\n\t}\n\n\tpublic static getClientDir() {\n\t\treturn ResolveIOServer._clientDir;\n\t}\n\n\tpublic static getSESMail() {\n\t\treturn ResolveIOServer._sesMail;\n\t}\n\n\tpublic static getStandardProgram() {\n\t\treturn ResolveIOServer._standardProgram;\n\t}\n}\n\nexport * from './public_api';"]}
@@ -1,9 +1,8 @@
1
1
  export declare class CronManager {
2
2
  private _cronManager;
3
- private _mainServer;
4
3
  private _watchCrons$;
5
4
  private _jobs;
6
- constructor(mainServer: any);
5
+ constructor();
7
6
  watchCrons(): Promise<void>;
8
7
  private doesCronJobExist;
9
8
  private doesCronJobNameExist;
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,o,r,i){return new(r=r||Promise)(function(t,n){function fulfilled(e){try{step(i.next(e))}catch(e){n(e)}}function rejected(e){try{step(i.throw(e))}catch(e){n(e)}}function step(e){var n;e.done?t(e.value):((n=e.value)instanceof r?n:new r(function(e){e(n)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,r){var i,a,s,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},_={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function verb(t){return function(e){var n=[t,e];if(i)throw new TypeError("Generator is already executing.");for(;c=_&&n[_=0]?0:c;)try{if(i=1,a&&(s=2&n[0]?a.return:n[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,n[1])).done)return s;switch(a=0,(n=s?[2&n[0],s.value]:n)[0]){case 0:case 1:s=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,a=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(s=0<(s=c.trys).length&&s[s.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3]))c.label=n[1];else if(6===n[0]&&c.label<s[1])c.label=s[1],s=n;else{if(!(s&&c.label<s[2])){s[2]&&c.ops.pop(),c.trys.pop();continue}c.label=s[2],c.ops.push(n)}}n=r.call(o,c)}catch(e){n=[6,e],a=0}finally{i=s=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}}},cron_job_collection_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.CronManager=void 0,require("../collections/cron-job.collection")),cron_1=require("../cron/cron"),cron_job_history_collection_1=require("../collections/cron-job-history.collection"),mongo_manager_1=require("../managers/mongo.manager"),CronManager=function(){function CronManager(e){this._jobs=[],this._mainServer=e,this._cronManager=new cron_1.CronJobManager,this.watchCrons()}return CronManager.prototype.watchCrons=function(){return __awaiter(this,void 0,void 0,function(){var n=this;return __generator(this,function(e){switch(e.label){case 0:return this._watchCrons$&&!this._watchCrons$.closed&&(this._watchCrons$.removeAllListeners(),this._watchCrons$.close(),this._watchCrons$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:return e.sent(),this._watchCrons$&&!this._watchCrons$.closed||(cron_job_collection_1.CronJobs.find().then(function(e){n._jobs=e,n._jobs.forEach(function(e){n.addCronJob(e),e.running&&cron_job_collection_1.CronJobs.updateOne({_id:e._id},{$set:{running:!1}})})}),this._watchCrons$=cron_job_collection_1.CronJobs.watchCollection([],{fullDocument:"updateLookup"}),this._watchCrons$.on("change",function(o){return __awaiter(n,void 0,void 0,function(){var n,t;return __generator(this,function(e){return"insert"===o.operationType?o.fullDocument&&(this._jobs.some(function(e){return e._id===o.documentKey._id})||this._jobs.push(o.fullDocument),this.addCronJob(o.fullDocument)):"replace"===o.operationType||"update"===o.operationType?o.fullDocument?(n=this._jobs.find(function(e){return e._id===o.documentKey._id}))?(this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1,o.fullDocument),n.name!==o.fullDocument.name?(this.removeCronJob(n.name),this.addCronJob(o.fullDocument)):(typeof n.time_to_run!=typeof o.fullDocument.time_to_run||"string"==typeof n.time_to_run&&n.time_to_run!==o.fullDocument.time_to_run||n.time_to_run instanceof Date&&n.time_to_run.getTime()!==o.fullDocument.time_to_run.getTime()||n.timezone!==o.fullDocument.timezone)&&this.updateCronJob(o.fullDocument)):(this._jobs.push(o.fullDocument),this.addCronJob(o.fullDocument)):this._jobs.some(function(e){return e._id===o.documentKey._id})&&(t=this._jobs.find(function(e){return e._id===o.documentKey._id}),this.removeCronJob(t.name),this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1)):"delete"===o.operationType&&this._jobs.some(function(e){return e._id===o.documentKey._id})&&(t=this._jobs.find(function(e){return e._id===o.documentKey._id}),this.removeCronJob(t.name),this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1)),[2]})})}).on("error",function(e){n._watchCrons$.removeAllListeners(),n._watchCrons$.close(),n._watchCrons$=null,n.watchCrons()}).on("end",function(){n._watchCrons$.removeAllListeners(),n._watchCrons$.close(),n._watchCrons$=null,n.watchCrons()}).on("close",function(){n._watchCrons$.removeAllListeners(),n._watchCrons$=null,n.watchCrons()})),[2]}})})},CronManager.prototype.doesCronJobExist=function(e){return this._cronManager.exists(e.name)},CronManager.prototype.doesCronJobNameExist=function(e){return this._cronManager.exists(e)},CronManager.prototype.addCronJob=function(n){var e=this;if(!this.doesCronJobExist(n))try{this._cronManager.add(n.name,n.time_to_run,function(){return e.runCronJob(n)},null,!0,n.timezone,null,!1);var t=new Date(this._cronManager.getJob(n.name).nextDate().ts);(n.running||t&&!n.next_run||t.getTime()!==n.next_run.getTime())&&cron_job_collection_1.CronJobs.updateOne({_id:n._id},{$set:{running:!1,next_run:t||null}})}catch(e){console.log("Cron error",e),n.time_to_run instanceof Date&&this.runCronJob(n)}},CronManager.prototype.updateCronJob=function(e){var n,t=this;this.doesCronJobExist(e)&&(this._cronManager.update(e.name,e.time_to_run,function(){return t.runCronJob(e)},null,!0,e.timezone),!(n=new Date(this._cronManager.getJob(e.name).nextDate().ts))||e.next_run&&n.getTime()===e.next_run.getTime()||cron_job_collection_1.CronJobs.updateOne({_id:e._id},{$set:{next_run:n}}))},CronManager.prototype.removeCronJob=function(e){this.doesCronJobNameExist(e)&&this._cronManager.delete(e)},CronManager.prototype.startCronJob=function(e){this.doesCronJobExist(e)&&this._cronManager.start(e.name)},CronManager.prototype.stopCronJob=function(e){this.doesCronJobExist(e)&&this._cronManager.stop(e.name)},CronManager.prototype.stopAllCronJobs=function(){this._cronManager.stopAll()},CronManager.prototype.runCronJob=function(s){var e=this,n=new Date;cron_job_collection_1.CronJobs.findOneAndUpdate({$and:[{_id:s._id},{running:!1},{$or:[{next_run:{$exists:!1}},{next_run:null},{next_run:{$lte:n}}]}]},{$set:{running:!0}}).then(function(a){return __awaiter(e,void 0,void 0,function(){var t,n,o,r,i=this;return __generator(this,function(e){switch(e.label){case 0:return a?(t={_id:(0,mongo_manager_1.objectIdHexString)(),name:a.name,reoccuring:a.repeat,time_to_run:a.time_to_run,method_name:a.method_run,id_cronjob:a._id,server_restart:!0,passed:!0,error:"",date_scheduled:a.next_run,date_start:new Date,date_end:null,date_next:null},[4,cron_job_history_collection_1.CronJobHistories.create(t)]):[3,14];case 1:e.sent(),n=setTimeout(function(){return __awaiter(i,void 0,void 0,function(){var n;return __generator(this,function(e){return console.log(new Date,"Cron Timeout",JSON.stringify(s,null,2)),a.repeat?(n=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=n,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:n}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),[2]})})},3e5),e.label=2;case 2:return(e.trys.push([2,11,12,13]),a.method_run_data)?[4,this._mainServer.getMethodManager().callMethodCron(a.method_run,a.method_run_data)]:[3,4];case 3:return e.sent(),[3,6];case 4:return[4,this._mainServer.getMethodManager().callMethodCron(a.method_run)];case 5:e.sent(),e.label=6;case 6:return a.method_complete?a.method_complete_data?[4,this._mainServer.getMethodManager().callMethodCron(a.method_complete,a.method_complete_data)]:[3,8]:[3,10];case 7:return e.sent(),[3,10];case 8:return[4,this._mainServer.getMethodManager().callMethodCron(a.method_complete)];case 9:e.sent(),e.label=10;case 10:return[3,13];case 11:return o=e.sent(),console.log(new Date,"Cron Error",JSON.stringify(o,null,2)),t.error=JSON.stringify(o,null,2),t.passed=!1,a.repeat?(r=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=r,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:r}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),[3,13];case 12:return clearTimeout(n),[7];case 13:a.repeat?(r=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=r,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:r}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),cron_job_history_collection_1.CronJobHistories.updateOne({_id:t._id},{$set:{server_restart:!1,passed:t.passed,error:t.error,date_end:new Date,date_next:t.date_next}}),e.label=14;case 14:return[2]}})})},function(){})},CronManager}();exports.CronManager=CronManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,o,r,i){return new(r=r||Promise)(function(t,n){function fulfilled(e){try{step(i.next(e))}catch(e){n(e)}}function rejected(e){try{step(i.throw(e))}catch(e){n(e)}}function step(e){var n;e.done?t(e.value):((n=e.value)instanceof r?n:new r(function(e){e(n)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,r){var i,a,s,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},_={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function verb(t){return function(e){var n=[t,e];if(i)throw new TypeError("Generator is already executing.");for(;c=_&&n[_=0]?0:c;)try{if(i=1,a&&(s=2&n[0]?a.return:n[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,n[1])).done)return s;switch(a=0,(n=s?[2&n[0],s.value]:n)[0]){case 0:case 1:s=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,a=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(s=0<(s=c.trys).length&&s[s.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3]))c.label=n[1];else if(6===n[0]&&c.label<s[1])c.label=s[1],s=n;else{if(!(s&&c.label<s[2])){s[2]&&c.ops.pop(),c.trys.pop();continue}c.label=s[2],c.ops.push(n)}}n=r.call(o,c)}catch(e){n=[6,e],a=0}finally{i=s=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}}},cron_job_collection_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.CronManager=void 0,require("../collections/cron-job.collection")),cron_1=require("../cron/cron"),cron_job_history_collection_1=require("../collections/cron-job-history.collection"),mongo_manager_1=require("../managers/mongo.manager"),__1=require(".."),CronManager=function(){function CronManager(){this._jobs=[],this._cronManager=new cron_1.CronJobManager,this.watchCrons()}return CronManager.prototype.watchCrons=function(){return __awaiter(this,void 0,void 0,function(){var n=this;return __generator(this,function(e){switch(e.label){case 0:return this._watchCrons$&&!this._watchCrons$.closed&&(this._watchCrons$.removeAllListeners(),this._watchCrons$.close(),this._watchCrons$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:return e.sent(),this._watchCrons$&&!this._watchCrons$.closed||(cron_job_collection_1.CronJobs.find().then(function(e){n._jobs=e,n._jobs.forEach(function(e){n.addCronJob(e),e.running&&cron_job_collection_1.CronJobs.updateOne({_id:e._id},{$set:{running:!1}})})}),this._watchCrons$=cron_job_collection_1.CronJobs.watchCollection([],{fullDocument:"updateLookup"}),this._watchCrons$.on("change",function(o){return __awaiter(n,void 0,void 0,function(){var n,t;return __generator(this,function(e){return"insert"===o.operationType?o.fullDocument&&(this._jobs.some(function(e){return e._id===o.documentKey._id})||this._jobs.push(o.fullDocument),this.addCronJob(o.fullDocument)):"replace"===o.operationType||"update"===o.operationType?o.fullDocument?(n=this._jobs.find(function(e){return e._id===o.documentKey._id}))?(this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1,o.fullDocument),n.name!==o.fullDocument.name?(this.removeCronJob(n.name),this.addCronJob(o.fullDocument)):(typeof n.time_to_run!=typeof o.fullDocument.time_to_run||"string"==typeof n.time_to_run&&n.time_to_run!==o.fullDocument.time_to_run||n.time_to_run instanceof Date&&n.time_to_run.getTime()!==o.fullDocument.time_to_run.getTime()||n.timezone!==o.fullDocument.timezone)&&this.updateCronJob(o.fullDocument)):(this._jobs.push(o.fullDocument),this.addCronJob(o.fullDocument)):this._jobs.some(function(e){return e._id===o.documentKey._id})&&(t=this._jobs.find(function(e){return e._id===o.documentKey._id}),this.removeCronJob(t.name),this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1)):"delete"===o.operationType&&this._jobs.some(function(e){return e._id===o.documentKey._id})&&(t=this._jobs.find(function(e){return e._id===o.documentKey._id}),this.removeCronJob(t.name),this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1)),[2]})})}).on("error",function(e){n._watchCrons$.removeAllListeners(),n._watchCrons$.close(),n._watchCrons$=null,n.watchCrons()}).on("end",function(){n._watchCrons$.removeAllListeners(),n._watchCrons$.close(),n._watchCrons$=null,n.watchCrons()}).on("close",function(){n._watchCrons$.removeAllListeners(),n._watchCrons$=null,n.watchCrons()})),[2]}})})},CronManager.prototype.doesCronJobExist=function(e){return this._cronManager.exists(e.name)},CronManager.prototype.doesCronJobNameExist=function(e){return this._cronManager.exists(e)},CronManager.prototype.addCronJob=function(n){var e=this;if(!this.doesCronJobExist(n))try{this._cronManager.add(n.name,n.time_to_run,function(){return e.runCronJob(n)},null,!0,n.timezone,null,!1);var t=new Date(this._cronManager.getJob(n.name).nextDate().ts);(n.running||t&&!n.next_run||t.getTime()!==n.next_run.getTime())&&cron_job_collection_1.CronJobs.updateOne({_id:n._id},{$set:{running:!1,next_run:t||null}})}catch(e){console.log("Cron error",e),n.time_to_run instanceof Date&&this.runCronJob(n)}},CronManager.prototype.updateCronJob=function(e){var n,t=this;this.doesCronJobExist(e)&&(this._cronManager.update(e.name,e.time_to_run,function(){return t.runCronJob(e)},null,!0,e.timezone),!(n=new Date(this._cronManager.getJob(e.name).nextDate().ts))||e.next_run&&n.getTime()===e.next_run.getTime()||cron_job_collection_1.CronJobs.updateOne({_id:e._id},{$set:{next_run:n}}))},CronManager.prototype.removeCronJob=function(e){this.doesCronJobNameExist(e)&&this._cronManager.delete(e)},CronManager.prototype.startCronJob=function(e){this.doesCronJobExist(e)&&this._cronManager.start(e.name)},CronManager.prototype.stopCronJob=function(e){this.doesCronJobExist(e)&&this._cronManager.stop(e.name)},CronManager.prototype.stopAllCronJobs=function(){this._cronManager.stopAll()},CronManager.prototype.runCronJob=function(s){var e=this,n=new Date;cron_job_collection_1.CronJobs.findOneAndUpdate({$and:[{_id:s._id},{running:!1},{$or:[{next_run:{$exists:!1}},{next_run:null},{next_run:{$lte:n}}]}]},{$set:{running:!0}}).then(function(a){return __awaiter(e,void 0,void 0,function(){var t,n,o,r,i=this;return __generator(this,function(e){switch(e.label){case 0:return a?(t={_id:(0,mongo_manager_1.objectIdHexString)(),name:a.name,reoccuring:a.repeat,time_to_run:a.time_to_run,method_name:a.method_run,id_cronjob:a._id,server_restart:!0,passed:!0,error:"",date_scheduled:a.next_run,date_start:new Date,date_end:null,date_next:null},[4,cron_job_history_collection_1.CronJobHistories.create(t)]):[3,14];case 1:e.sent(),n=setTimeout(function(){return __awaiter(i,void 0,void 0,function(){var n;return __generator(this,function(e){return console.log(new Date,"Cron Timeout",JSON.stringify(s,null,2)),a.repeat?(n=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=n,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:n}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),[2]})})},3e5),e.label=2;case 2:return(e.trys.push([2,11,12,13]),a.method_run_data)?[4,__1.ResolveIOServer.getMainServer().getMethodManager().callMethodCron(a.method_run,a.method_run_data)]:[3,4];case 3:return e.sent(),[3,6];case 4:return[4,__1.ResolveIOServer.getMainServer().getMethodManager().callMethodCron(a.method_run)];case 5:e.sent(),e.label=6;case 6:return a.method_complete?a.method_complete_data?[4,__1.ResolveIOServer.getMainServer().getMethodManager().callMethodCron(a.method_complete,a.method_complete_data)]:[3,8]:[3,10];case 7:return e.sent(),[3,10];case 8:return[4,__1.ResolveIOServer.getMainServer().getMethodManager().callMethodCron(a.method_complete)];case 9:e.sent(),e.label=10;case 10:return[3,13];case 11:return o=e.sent(),console.log(new Date,"Cron Error",JSON.stringify(o,null,2)),t.error=JSON.stringify(o,null,2),t.passed=!1,a.repeat?(r=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=r,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:r}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),[3,13];case 12:return clearTimeout(n),[7];case 13:a.repeat?(r=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=r,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:r}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),cron_job_history_collection_1.CronJobHistories.updateOne({_id:t._id},{$set:{server_restart:!1,passed:t.passed,error:t.error,date_end:new Date,date_next:t.date_next}}),e.label=14;case 14:return[2]}})})},function(){})},CronManager}();exports.CronManager=CronManager;
2
2
  //# sourceMappingURL=cron.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/cron.manager.ts"],"names":["cron_job_collection_1","require","cron_1","cron_job_history_collection_1","mongo_manager_1","CronManager","mainServer","this","_jobs","_mainServer","_cronManager","CronJobManager","watchCrons","prototype","_watchCrons$","closed","removeAllListeners","close","Promise","resolve","setTimeout","_a","sent","CronJobs","find","then","res","_this","forEach","job","addCronJob","running","updateOne","_id","$set","watchCollection","fullDocument","on","doc","__awaiter","operationType","some","a","documentKey","push","oldDoc","splice","map","indexOf","name","removeCronJob","time_to_run","Date","getTime","timezone","updateCronJob","err","doesCronJobExist","cron","exists","doesCronJobNameExist","cron_name","add","runCronJob","nextDate","getJob","next_run","e","console","log","update","delete","startCronJob","start","stopCronJob","stop","stopAllCronJobs","stopAll","now","findOneAndUpdate","$and","$or","$exists","$lte","cronHistory_1","objectIdHexString","reoccuring","repeat","method_name","method_run","id_cronjob","server_restart","passed","error","date_scheduled","date_start","date_end","date_next","CronJobHistories","create","timeoutHandle","JSON","stringify","deleteOne","method_run_data","getMethodManager","callMethodCron","method_complete","method_complete_data","err_1","clearTimeout","exports"],"mappings":"k8CACAA,uB,kFAAAC,QAAA,oCAAA,GAEAC,OAAAD,QAAA,cAAA,EAGAE,8BAAAF,QAAA,4CAAA,EACAG,gBAAAH,QAAA,2BAAA,EAGAI,YAAA,WAMC,SAAAA,YAAYC,GAFJC,KAAAC,MAAwB,GAG/BD,KAAKE,Y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G,aAAauD,OAAOvC,EAAIuB,IAAI,EAAEe,SAAQ,EAAO,EAAC,EAC3EoB,EAAYa,UAAYjC,EACxBhE,sBAAAuB,SAASS,UAAU,CAACC,IAAKP,EAAIO,GAAG,EAAG,CAACC,KAAM,CAACH,QAAS,CAAA,EAAOmC,SAAUF,CAAQ,CAAC,CAAC,GAG/EhE,sBAAAuB,SAASgF,UAAU,CAACtE,IAAKP,EAAIO,GAAG,CAAC,EAGlC9B,8BAAA+F,iBAAiBlE,UAAU,CAACC,IAAKmD,EAAYnD,GAAG,EAAG,CAACC,KAAM,CACzDyD,eAAgB,CAAA,EAChBC,OAAQR,EAAYQ,OACpBC,MAAOT,EAAYS,MACnBG,SAAU,IAAI5C,KACd6C,UAAWb,EAAYa,S,CACvB,CAAC,E,mCAED,YAAQ,CACZ,EACD5F,WAAA,EAAC,EAxRY0G,QAAA1G,YAAAA","file":"cron.manager.js","sourcesContent":["import { CronJobModel } from '../models/cron-job.model';\nimport { CronJobs } from '../collections/cron-job.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { CronJobManager } from '../cron/cron';\nimport * as moment from 'moment-timezone';\nimport { ChangeStream, ChangeStreamDocument } from 'mongodb';\nimport { CronJobHistories } from '../collections/cron-job-history.collection';\nimport { objectIdHexString } from '../managers/mongo.manager';\nimport { CronJobHistoryModel } from '../models/cron-job-history.model';\n\nexport class CronManager {\n\tprivate _cronManager: CronJobManager;\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _watchCrons$: ChangeStream;\n\tprivate _jobs: CronJobModel[] = [];\n\n\tconstructor(mainServer) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._cronManager = new CronJobManager();\n\n\t\tthis.watchCrons();\n\t}\n\n\tpublic async watchCrons() {\n\t\tif (this._watchCrons$ && !this._watchCrons$.closed) {\n\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\tthis._watchCrons$.close();\n\t\t\tthis._watchCrons$ = null;\n\t\t}\n\t\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\t\n\t\tif (!this._watchCrons$ || this._watchCrons$.closed) {\t\t\t\n\t\t\tCronJobs.find().then(res => {\n\t\t\t\tthis._jobs = res;\n\n\t\t\t\tthis._jobs.forEach(job => {\n\t\t\t\t\tthis.addCronJob(job);\n\t\t\t\t\tif (job.running) {\n\t\t\t\t\t\tCronJobs.updateOne({_id: job._id}, {$set: {running: false}});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tthis._watchCrons$ = CronJobs.watchCollection([], {fullDocument: 'updateLookup'});\n\n\t\t\tthis._watchCrons$.on('change', async (doc: ChangeStreamDocument<CronJobModel>) => {\n\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\tif (doc.fullDocument) {\n\t\t\t\t\t\tif (!this._jobs.some(a => a._id === <any>doc.documentKey['_id'])) {\n\t\t\t\t\t\t\tthis._jobs.push(doc.fullDocument);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (doc.operationType === 'replace' || doc.operationType === 'update') {\n\t\t\t\t\tif (doc.fullDocument) {\n\t\t\t\t\t\tlet oldDoc = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\tif (oldDoc) {\n\t\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1, doc.fullDocument);\n\n\t\t\t\t\t\t\tif (oldDoc.name !== doc.fullDocument.name) {\n\t\t\t\t\t\t\t\tthis.removeCronJob(oldDoc.name);\n\t\t\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (typeof oldDoc.time_to_run !== typeof doc.fullDocument.time_to_run || (typeof oldDoc.time_to_run === 'string' && oldDoc.time_to_run !== doc.fullDocument.time_to_run) ||\n\t\t\t\t\t\t\t\t(oldDoc.time_to_run instanceof Date && oldDoc.time_to_run.getTime() !== (<Date>doc.fullDocument.time_to_run).getTime()) || \n\t\t\t\t\t\t\t\toldDoc.timezone !== doc.fullDocument.timezone\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthis.updateCronJob(doc.fullDocument);\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._jobs.push(doc.fullDocument);\n\t\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\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\tif (this._jobs.some(a => a._id === <any>doc.documentKey['_id'])) {\n\t\t\t\t\t\t\tlet job = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\t\tthis.removeCronJob(job.name);\n\t\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\tif (this._jobs.some(a => a._id === (<any>doc).documentKey['_id'])) {\n\t\t\t\t\t\tlet job = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\tthis.removeCronJob(job.name);\n\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', (err) => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$.close();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$.close();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate doesCronJobExist(cron: CronJobModel) {\n\t\treturn this._cronManager.exists(cron.name);\n\t}\n\n\tprivate doesCronJobNameExist(cron_name: string) {\n\t\treturn this._cronManager.exists(cron_name);\n\t}\n\n\tprivate addCronJob(cron: CronJobModel) {\n\t\tif (!this.doesCronJobExist(cron)) {\n\t\t\ttry {\n\t\t\t\tthis._cronManager.add(\n\t\t\t\t\tcron.name,\n\t\t\t\t\tcron.time_to_run,\n\t\t\t\t\t() => this.runCronJob(cron),\n\t\t\t\t\tnull,\n\t\t\t\t\ttrue,\n\t\t\t\t\tcron.timezone,\n\t\t\t\t\tnull, \n\t\t\t\t\tfalse\n\t\t\t\t);\n\n\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(cron.name).nextDate()['ts']);\n\n\t\t\t\tif (cron.running || (nextDate && !cron.next_run || nextDate.getTime() !== cron.next_run.getTime())) {\n\t\t\t\t\tCronJobs.updateOne({_id: cron._id}, {$set: {running: false, next_run: nextDate || null}});\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(e) {\n\t\t\t\tconsole.log('Cron error', e);\n\n\t\t\t\tif (cron.time_to_run instanceof Date) {\n\t\t\t\t\tthis.runCronJob(cron);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate updateCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.update(cron.name, cron.time_to_run, () => this.runCronJob(cron), null, true, cron.timezone);\n\n\t\t\tlet nextDate = new Date(this._cronManager.getJob(cron.name).nextDate()['ts']);\n\n\t\t\tif (nextDate && (!cron.next_run || nextDate.getTime() !== cron.next_run.getTime())) {\n\t\t\t\tCronJobs.updateOne({_id: cron._id}, {$set: {next_run: nextDate}});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate removeCronJob(cron_name: string) {\n\t\tif (this.doesCronJobNameExist(cron_name)) {\n\t\t\tthis._cronManager.delete(cron_name);\n\t\t}\n\t}\n\n\tprivate startCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.start(cron.name);\n\t\t}\n\t}\n\n\tprivate stopCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.stop(cron.name);\n\t\t}\n\t}\n\n\tprivate stopAllCronJobs() {\n\t\tthis._cronManager.stopAll();\n\t}\n\n\tprivate runCronJob(cron: CronJobModel) {\n\t\tlet now = new Date();\n\n\t\tCronJobs.findOneAndUpdate({\n\t\t\t$and: [\n\t\t\t\t{_id: cron._id},\n\t\t\t\t{running: false},\n\t\t\t\t{\n\t\t\t\t\t$or: [\n\t\t\t\t\t\t{next_run: {$exists: false}},\n\t\t\t\t\t\t{next_run: null},\n\t\t\t\t\t\t{next_run: {$lte: now}}\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t]\n\t\t}, {$set: {running: true}}).then(async res => {\n\t\t\tif (res) {\n\t\t\t\tlet cronHistory: CronJobHistoryModel = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tname: res.name,\n\t\t\t\t\treoccuring: res.repeat,\n\t\t\t\t\ttime_to_run: res.time_to_run,\n\t\t\t\t\tmethod_name: res.method_run,\n\t\t\t\t\tid_cronjob: res._id,\n\t\t\t\t\tserver_restart: true,\n\t\t\t\t\tpassed: true,\n\t\t\t\t\terror: '',\n\t\t\t\t\tdate_scheduled: res.next_run,\n\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\tdate_end: null,\n\t\t\t\t\tdate_next: null\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tawait CronJobHistories.create(cronHistory);\n\n\t\t\t\tlet timeoutHandle = setTimeout(async () => {\n\t\t\t\t\tconsole.log(new Date(), 'Cron Timeout', JSON.stringify(cron, null, 2));\n\n\t\t\t\t\tif (res.repeat) {\n\t\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t\t} \n\t\t\t\t\telse {\n\t\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t\t}\n\t\t\t\t}, 5 * 60 * 1000); // 5 minutes in milliseconds\n\n\t\t\t\ttry {\n\t\t\t\t\tif (res.method_run_data) {\n\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_run, res.method_run_data);\t\n\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_run);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (res.method_complete) {\n\t\t\t\t\t\tif (res.method_complete_data) {\n\t\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_complete, res.method_complete_data);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_complete);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.log(new Date(), 'Cron Error', JSON.stringify(err, null, 2));\n\t\t\t\t\tcronHistory.error = JSON.stringify(err, null, 2);\n\t\t\t\t\tcronHistory.passed = false;\n\n\t\t\t\t\tif (res.repeat) {\n\t\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t\t} \n\t\t\t\t\telse {\n\t\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\t// Clear the timeout if the job completes or fails before the timeout\n\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\t}\n\n\t\t\t\tif (res.repeat) {\n\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t} \n\t\t\t\telse {\n\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t}\n\n\t\t\t\tCronJobHistories.updateOne({_id: cronHistory._id}, {$set: {\n\t\t\t\t\tserver_restart: false,\n\t\t\t\t\tpassed: cronHistory.passed,\n\t\t\t\t\terror: cronHistory.error,\n\t\t\t\t\tdate_end: new Date(),\n\t\t\t\t\tdate_next: cronHistory.date_next\n\t\t\t\t}});\n\t\t\t}\n\t\t}, () => {});\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/cron.manager.ts"],"names":["cron_job_collection_1","require","cron_1","cron_job_history_collection_1","mongo_manager_1","__1","CronManager","this","_jobs","_cronManager","CronJobManager","watchCrons","prototype","_watchCrons$","closed","removeAllListeners","close","Promise","resolve","setTimeout","_a","sent","CronJobs","find","then","res","_this","forEach","job","addCronJob","running","updateOne","_id","$set","watchCollection","fullDocument","on","doc","__awaiter","operationType","some","a","documentKey","push","oldDoc","splice","map","indexOf","name","removeCronJob","time_to_run","Date","getTime","timezone","updateCronJob","err","doesCronJobExist","cron","exists","doesCronJobNameExist","cron_name","add","runCronJob","nextDate","getJob","next_run","e","console","log","update","delete","startCronJob","start","stopCronJob","stop","stopAllCronJobs","stopAll","now","findOneAndUpdate","$and","$or","$exists","$lte","cronHistory_1","objectIdHexString","reoccuring","repeat","method_name","method_run","id_cronjob","server_restart","passed","error","date_scheduled","date_start","date_end","date_next","CronJobHistories","create","timeoutHandle","JSON","stringify","deleteOne","method_run_data","ResolveIOServer","getMainServer","getMethodManager","callMethodCron","method_complete","method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,sBAAAsB,SAASS,UAAU,CAACC,IAAKP,EAAIO,GAAG,EAAG,CAACC,KAAM,CAACH,QAAS,CAAA,EAAOmC,SAAUF,CAAQ,CAAC,CAAC,GAG/E/D,sBAAAsB,SAASgF,UAAU,CAACtE,IAAKP,EAAIO,GAAG,CAAC,E,sBAKlC+E,aAAaZ,CAAa,E,YAGvB1E,EAAI6D,QACHvB,EAAW,IAAIZ,KAAK5C,KAAKE,aAAauD,OAAOvC,EAAIuB,IAAI,EAAEe,SAAQ,EAAO,EAAC,EAC3EoB,EAAYa,UAAYjC,EACxB/D,sBAAAsB,SAASS,UAAU,CAACC,IAAKP,EAAIO,GAAG,EAAG,CAACC,KAAM,CAACH,QAAS,CAAA,EAAOmC,SAAUF,CAAQ,CAAC,CAAC,GAG/E/D,sBAAAsB,SAASgF,UAAU,CAACtE,IAAKP,EAAIO,GAAG,CAAC,EAGlC7B,8BAAA8F,iBAAiBlE,UAAU,CAACC,IAAKmD,EAAYnD,GAAG,EAAG,CAACC,KAAM,CACzDyD,eAAgB,CAAA,EAChBC,OAAQR,EAAYQ,OACpBC,MAAOT,EAAYS,MACnBG,SAAU,IAAI5C,KACd6C,UAAWb,EAAYa,S,CACvB,CAAC,E,mCAED,YAAQ,CACZ,EACD1F,WAAA,EAAC,EAtRY0G,QAAA1G,YAAAA","file":"cron.manager.js","sourcesContent":["import { CronJobModel } from '../models/cron-job.model';\nimport { CronJobs } from '../collections/cron-job.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { CronJobManager } from '../cron/cron';\nimport { ChangeStream, ChangeStreamDocument } from 'mongodb';\nimport { CronJobHistories } from '../collections/cron-job-history.collection';\nimport { objectIdHexString } from '../managers/mongo.manager';\nimport { CronJobHistoryModel } from '../models/cron-job-history.model';\nimport { ResolveIOServer } from '..';\n\nexport class CronManager {\n\tprivate _cronManager: CronJobManager;\n\tprivate _watchCrons$: ChangeStream;\n\tprivate _jobs: CronJobModel[] = [];\n\n\tconstructor() {\n\t\tthis._cronManager = new CronJobManager();\n\n\t\tthis.watchCrons();\n\t}\n\n\tpublic async watchCrons() {\n\t\tif (this._watchCrons$ && !this._watchCrons$.closed) {\n\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\tthis._watchCrons$.close();\n\t\t\tthis._watchCrons$ = null;\n\t\t}\n\t\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\t\n\t\tif (!this._watchCrons$ || this._watchCrons$.closed) {\t\t\t\n\t\t\tCronJobs.find().then(res => {\n\t\t\t\tthis._jobs = res;\n\n\t\t\t\tthis._jobs.forEach(job => {\n\t\t\t\t\tthis.addCronJob(job);\n\t\t\t\t\tif (job.running) {\n\t\t\t\t\t\tCronJobs.updateOne({_id: job._id}, {$set: {running: false}});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tthis._watchCrons$ = CronJobs.watchCollection([], {fullDocument: 'updateLookup'});\n\n\t\t\tthis._watchCrons$.on('change', async (doc: ChangeStreamDocument<CronJobModel>) => {\n\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\tif (doc.fullDocument) {\n\t\t\t\t\t\tif (!this._jobs.some(a => a._id === <any>doc.documentKey['_id'])) {\n\t\t\t\t\t\t\tthis._jobs.push(doc.fullDocument);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (doc.operationType === 'replace' || doc.operationType === 'update') {\n\t\t\t\t\tif (doc.fullDocument) {\n\t\t\t\t\t\tlet oldDoc = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\tif (oldDoc) {\n\t\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1, doc.fullDocument);\n\n\t\t\t\t\t\t\tif (oldDoc.name !== doc.fullDocument.name) {\n\t\t\t\t\t\t\t\tthis.removeCronJob(oldDoc.name);\n\t\t\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (typeof oldDoc.time_to_run !== typeof doc.fullDocument.time_to_run || (typeof oldDoc.time_to_run === 'string' && oldDoc.time_to_run !== doc.fullDocument.time_to_run) ||\n\t\t\t\t\t\t\t\t(oldDoc.time_to_run instanceof Date && oldDoc.time_to_run.getTime() !== (<Date>doc.fullDocument.time_to_run).getTime()) || \n\t\t\t\t\t\t\t\toldDoc.timezone !== doc.fullDocument.timezone\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthis.updateCronJob(doc.fullDocument);\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._jobs.push(doc.fullDocument);\n\t\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\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\tif (this._jobs.some(a => a._id === <any>doc.documentKey['_id'])) {\n\t\t\t\t\t\t\tlet job = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\t\tthis.removeCronJob(job.name);\n\t\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\tif (this._jobs.some(a => a._id === (<any>doc).documentKey['_id'])) {\n\t\t\t\t\t\tlet job = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\tthis.removeCronJob(job.name);\n\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', (err) => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$.close();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$.close();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate doesCronJobExist(cron: CronJobModel) {\n\t\treturn this._cronManager.exists(cron.name);\n\t}\n\n\tprivate doesCronJobNameExist(cron_name: string) {\n\t\treturn this._cronManager.exists(cron_name);\n\t}\n\n\tprivate addCronJob(cron: CronJobModel) {\n\t\tif (!this.doesCronJobExist(cron)) {\n\t\t\ttry {\n\t\t\t\tthis._cronManager.add(\n\t\t\t\t\tcron.name,\n\t\t\t\t\tcron.time_to_run,\n\t\t\t\t\t() => this.runCronJob(cron),\n\t\t\t\t\tnull,\n\t\t\t\t\ttrue,\n\t\t\t\t\tcron.timezone,\n\t\t\t\t\tnull, \n\t\t\t\t\tfalse\n\t\t\t\t);\n\n\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(cron.name).nextDate()['ts']);\n\n\t\t\t\tif (cron.running || (nextDate && !cron.next_run || nextDate.getTime() !== cron.next_run.getTime())) {\n\t\t\t\t\tCronJobs.updateOne({_id: cron._id}, {$set: {running: false, next_run: nextDate || null}});\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(e) {\n\t\t\t\tconsole.log('Cron error', e);\n\n\t\t\t\tif (cron.time_to_run instanceof Date) {\n\t\t\t\t\tthis.runCronJob(cron);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate updateCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.update(cron.name, cron.time_to_run, () => this.runCronJob(cron), null, true, cron.timezone);\n\n\t\t\tlet nextDate = new Date(this._cronManager.getJob(cron.name).nextDate()['ts']);\n\n\t\t\tif (nextDate && (!cron.next_run || nextDate.getTime() !== cron.next_run.getTime())) {\n\t\t\t\tCronJobs.updateOne({_id: cron._id}, {$set: {next_run: nextDate}});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate removeCronJob(cron_name: string) {\n\t\tif (this.doesCronJobNameExist(cron_name)) {\n\t\t\tthis._cronManager.delete(cron_name);\n\t\t}\n\t}\n\n\tprivate startCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.start(cron.name);\n\t\t}\n\t}\n\n\tprivate stopCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.stop(cron.name);\n\t\t}\n\t}\n\n\tprivate stopAllCronJobs() {\n\t\tthis._cronManager.stopAll();\n\t}\n\n\tprivate runCronJob(cron: CronJobModel) {\n\t\tlet now = new Date();\n\n\t\tCronJobs.findOneAndUpdate({\n\t\t\t$and: [\n\t\t\t\t{_id: cron._id},\n\t\t\t\t{running: false},\n\t\t\t\t{\n\t\t\t\t\t$or: [\n\t\t\t\t\t\t{next_run: {$exists: false}},\n\t\t\t\t\t\t{next_run: null},\n\t\t\t\t\t\t{next_run: {$lte: now}}\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t]\n\t\t}, {$set: {running: true}}).then(async res => {\n\t\t\tif (res) {\n\t\t\t\tlet cronHistory: CronJobHistoryModel = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tname: res.name,\n\t\t\t\t\treoccuring: res.repeat,\n\t\t\t\t\ttime_to_run: res.time_to_run,\n\t\t\t\t\tmethod_name: res.method_run,\n\t\t\t\t\tid_cronjob: res._id,\n\t\t\t\t\tserver_restart: true,\n\t\t\t\t\tpassed: true,\n\t\t\t\t\terror: '',\n\t\t\t\t\tdate_scheduled: res.next_run,\n\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\tdate_end: null,\n\t\t\t\t\tdate_next: null\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tawait CronJobHistories.create(cronHistory);\n\n\t\t\t\tlet timeoutHandle = setTimeout(async () => {\n\t\t\t\t\tconsole.log(new Date(), 'Cron Timeout', JSON.stringify(cron, null, 2));\n\n\t\t\t\t\tif (res.repeat) {\n\t\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t\t} \n\t\t\t\t\telse {\n\t\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t\t}\n\t\t\t\t}, 5 * 60 * 1000); // 5 minutes in milliseconds\n\n\t\t\t\ttry {\n\t\t\t\t\tif (res.method_run_data) {\n\t\t\t\t\t\tawait ResolveIOServer.getMainServer().getMethodManager().callMethodCron(res.method_run, res.method_run_data);\t\n\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tawait ResolveIOServer.getMainServer().getMethodManager().callMethodCron(res.method_run);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (res.method_complete) {\n\t\t\t\t\t\tif (res.method_complete_data) {\n\t\t\t\t\t\t\tawait ResolveIOServer.getMainServer().getMethodManager().callMethodCron(res.method_complete, res.method_complete_data);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tawait ResolveIOServer.getMainServer().getMethodManager().callMethodCron(res.method_complete);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.log(new Date(), 'Cron Error', JSON.stringify(err, null, 2));\n\t\t\t\t\tcronHistory.error = JSON.stringify(err, null, 2);\n\t\t\t\t\tcronHistory.passed = false;\n\n\t\t\t\t\tif (res.repeat) {\n\t\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t\t} \n\t\t\t\t\telse {\n\t\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\t// Clear the timeout if the job completes or fails before the timeout\n\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\t}\n\n\t\t\t\tif (res.repeat) {\n\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t} \n\t\t\t\telse {\n\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t}\n\n\t\t\t\tCronJobHistories.updateOne({_id: cronHistory._id}, {$set: {\n\t\t\t\t\tserver_restart: false,\n\t\t\t\t\tpassed: cronHistory.passed,\n\t\t\t\t\terror: cronHistory.error,\n\t\t\t\t\tdate_end: new Date(),\n\t\t\t\t\tdate_next: cronHistory.date_next\n\t\t\t\t}});\n\t\t\t}\n\t\t}, () => {});\n\t}\n}"]}
@@ -0,0 +1,16 @@
1
+ export type LocalLogType = 'monitor-mongo' | 'monitor-memory' | 'monitor-cpu' | 'log' | 'log-method-latency' | 'log-subscription';
2
+ export interface LocalLogModel {
3
+ type: LocalLogType;
4
+ date: Date;
5
+ data: any;
6
+ }
7
+ export declare class LocalLogManager {
8
+ private _logFilePath;
9
+ constructor();
10
+ writeLog(logEntry: LocalLogModel): void;
11
+ writeLogs(items: LocalLogModel[]): void;
12
+ /**
13
+ * Reads all logs from disk, then empties the file.
14
+ */
15
+ offloadLogs(): any[];
16
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LocalLogManager=void 0;var fs=require("fs"),__1=require(".."),LocalLogManager=function(){function LocalLogManager(){"https://resolveio.com"===__1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===__1.ResolveIOServer.getServerConfig().ROOT_URL||fs.existsSync("~/logs")||fs.mkdirSync("~/logs"),this._logFilePath="~/logs/local-logs.jsonl"}return LocalLogManager.prototype.writeLog=function(e){try{var o=JSON.stringify(e)+"\n";fs.appendFileSync(this._logFilePath,o,{encoding:"utf8"})}catch(e){console.error(new Date,"LocalLogManager","Failed to write log to file:",e)}},LocalLogManager.prototype.writeLogs=function(e){if(e&&0!==e.length)try{var o=e.map(function(e){return JSON.stringify(e)}).join("\n")+"\n";fs.appendFileSync(this._logFilePath,o,{encoding:"utf8"})}catch(e){console.error(new Date,"LocalLogManager","Failed to write logs batch:",e)}},LocalLogManager.prototype.offloadLogs=function(){var e=[];try{if(!fs.existsSync(this._logFilePath))return e;var o=fs.readFileSync(this._logFilePath,"utf8");if(0===o.trim().length)return e;e=o.split("\n").filter(function(e){return""!==e.trim()}),fs.writeFileSync(this._logFilePath,"")}catch(e){console.error(new Date,"LocalLogManager","Failed to offload logs:",e)}return e},LocalLogManager}();exports.LocalLogManager=LocalLogManager;
2
+ //# sourceMappingURL=local-log.manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/managers/local-log.manager.ts"],"names":["fs","require","__1","LocalLogManager","ResolveIOServer","getServerConfig","existsSync","mkdirSync","this","_logFilePath","prototype","writeLog","logEntry","line","JSON","stringify","appendFileSync","encoding","err","console","error","Date","writeLogs","items","length","lines","map","item","join","offloadLogs","result","fileData","readFileSync","trim","split","filter","l","writeFileSync","exports"],"mappings":"mGAGA,IAAAA,GAAAC,QAAA,IAAA,EACAC,IAAAD,QAAA,IAAA,EAeAE,gBAAA,WAGC,SAAAA,kBAEoD,0BAAlDD,IAAAE,gBAAgBC,gBAAe,EAAa,UACS,0BAAlDH,IAAAE,gBAAgBC,gBAAe,EAAa,U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logs.manager.ts\n****************/\nimport * as fs from 'fs';\nimport { ResolveIOServer } from '..';\n\nexport type LocalLogType = 'monitor-mongo' \n\t| 'monitor-memory'\n\t| 'monitor-cpu'\n\t| 'log'\n\t| 'log-method-latency'\n\t| 'log-subscription';\n\nexport interface LocalLogModel {\n\ttype: LocalLogType;\n\tdate: Date;\n\tdata: any;\n}\n\nexport class LocalLogManager {\n\tprivate _logFilePath: string;\n\n\tconstructor() {\n\t\tif (\n\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t) {\n\t\t\tif (!fs.existsSync('~/logs')) {\n\t\t\t\tfs.mkdirSync('~/logs');\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis._logFilePath = '~/logs/local-logs.jsonl';\n\t}\n\n\t// Internal method to append a JSON line to the file\n\tpublic writeLog(logEntry: LocalLogModel): void {\n\t\ttry {\n\t\t\tlet line = JSON.stringify(logEntry) + '\\n';\n\t\t\tfs.appendFileSync(this._logFilePath, line, { encoding: 'utf8' });\n\t\t}\n\t\tcatch(err) {\n\t\t\t// If there's an error writing logs, you might want to handle it or queue it\n\t\t\tconsole.error(new Date(), 'LocalLogManager', 'Failed to write log to file:', err);\n\t\t}\n\t}\n\n\tpublic writeLogs(items: LocalLogModel[]): void {\n\t\tif (!items || items.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t// Convert each item to a JSON string, add newline\n\t\t\tlet lines = items.map(item => JSON.stringify(item)).join('\\n') + '\\n';\n\t\t\tfs.appendFileSync(this._logFilePath, lines, { encoding: 'utf8' });\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error(new Date(), 'LocalLogManager', 'Failed to write logs batch:', err);\n\t\t}\n\t}\n\n\t/**\n\t * Reads all logs from disk, then empties the file.\n\t */\n\tpublic offloadLogs(): any[] {\n\t\tlet result = [];\n\n\t\ttry {\n\t\t\tif (!fs.existsSync(this._logFilePath)) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tlet fileData = fs.readFileSync(this._logFilePath, 'utf8');\n\t\t\tif (fileData.trim().length === 0) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tresult = fileData.split('\\n').filter(l => l.trim() !== '');\n\n\t\t\t// Truncate the file so we don't send logs more than once\n\t\t\tfs.writeFileSync(this._logFilePath, '');\n\t\t}\n\t\tcatch(err) {\n\t\t\tconsole.error(new Date(), 'LocalLogManager', 'Failed to offload logs:', err);\n\t\t}\n\n\t\treturn result;\n\t}\n}"]}
@@ -1,24 +1,19 @@
1
1
  import { MethodModel } from '../models/method.model';
2
- import ResolveIOMainServer from '../server-app';
3
2
  import { MonitorManagerFunction } from './monitor.manager';
4
3
  import { S3 } from '@aws-sdk/client-s3';
5
4
  import * as WebSocket from 'ws';
6
5
  export declare class AWS {
7
- private _serverConfig;
8
6
  private _s3;
9
7
  private _s3USEast1;
10
- constructor(serverConfig: any);
8
+ constructor();
11
9
  s3(): S3;
12
10
  s3USEast1(): S3;
13
11
  }
14
12
  export declare class MethodManager {
15
- private _mainServer;
16
13
  private _websocketManager;
17
14
  _methods: MethodModel;
18
15
  private _mailer;
19
16
  private _aws;
20
- private serverConfig;
21
- private clientDir;
22
17
  private _monitorManagerFunction;
23
18
  private _isWorkersEnabled;
24
19
  private _isWorkerInstance;
@@ -28,8 +23,7 @@ export declare class MethodManager {
28
23
  private _debugCallMethodHits;
29
24
  private _debugCallMethodCronJobHits;
30
25
  private _debugSendQueueHits;
31
- constructor(mainServer: any, serverConfig: any, clientDir: any, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled: any, isWorkerInstance: any);
32
- getMainServer(): ResolveIOMainServer;
26
+ constructor(monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled: any, isWorkerInstance: any);
33
27
  methods(method: MethodModel): void;
34
28
  callMethodCron(method: string, ...methodData: any[]): any;
35
29
  callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]): void;
@@ -1,2 +1,2 @@
1
- "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,n,o,i){return new(o=o||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var i,s,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=o.call(n,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||((n=n||Array.prototype.slice.call(t,0,o))[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),flag_updates_1=require("../methods/flag-updates"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,r,n,o,i){var s=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this.serverConfig=t,this.clientDir=r,this._monitorManagerFunction=n,this._isWorkersEnabled=o,this._isWorkerInstance=i,"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(t),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var o=this,r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<r.length||r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var n={},i=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),s=0;s<r.length;s++)n[i[s]]=r[s];try{this._methods[t].check.validate(n)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var a,c,l,u=null,d=JSON.stringify(r);return this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(d,"utf8")<8388608&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(a=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),c=(0,mongo_manager_1.objectIdHexString)(),u=new Promise(function(t,r){var n=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":c}}],{fullDocument:"updateLookup"});n.on("change",function(e){"insert"===e.operationType&&(o._monitorManagerFunction.finishMonitorFunction(a),((e=e.fullDocument).has_error?r:t)(e.data),n.close())}),n.on("error",function(e){console.error("Error watching worker responses:",e),r(e),n.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:c,method:t,params:r,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(l=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),u=(d=this._methods[t].function).call.apply(d,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(r),!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(l),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(l),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),u}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(n,o,i,s,a){for(var t=this,c=[],e=5;e<arguments.length;e++)c[e-5]=arguments[e];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<c.length||c[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(o,i,a,c,r={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),r={messageId:s,hasError:!0,data:"Internal Error"},n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),void this.sendWS(o,i,a,c,r);for(var r,l={},u=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),d=0;d<c.length;d++)l[u[d]]=c[d];try{this._methods[a].check.validate(l)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(l,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(o,i,a,c,r={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}))}}var h,_,f,g=JSON.stringify(c);this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(g,"utf8")<8388608&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a&&"incorrectUser"!==a&&"reloadWS"!==a&&"reconnectWS"!==a&&"disconnectWS"!==a?(h=this._monitorManagerFunction.startMonitorFunction("Method",a,o.user||"",o.id_socket||"",c),g=(0,mongo_manager_1.objectIdHexString)(),(_=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":g}}],{fullDocument:"updateLookup"})).on("change",function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==r.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(h),t=r.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(o,new Date,a,c,t),n?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:_.close(),e.label=3;case 3:return[2]}})})}),_.on("error",function(e){console.error("Error watching worker responses:",e),_.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:g,method:a,params:c,status:"pending",id_user:o.id_user,user:o.user,id_ws:o.id_socket})):(f=this._monitorManagerFunction.startMonitorFunction("Method",a,o.user||"",o.id_socket||"",c),(g=this._methods[a].function).call.apply(g,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:o.id_user,user:o.user,id_ws:o.id_socket})],__read(c),!1)).then(function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(f),t={messageId:s,hasError:!1,data:r},this.sendWS(o,i,a,c,t),n)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(f),t.sendWS(o,i,a,c,{messageId:s,hasError:!0,data:e}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(c,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),r={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(o,new Date,a,c,r),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n})},MethodManager.prototype.callMethodInternal=function(t){for(var o=this,r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<r.length||r[0]&&"function"!=typeof r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r]))<2e5?JSON.stringify([r],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,n,a="function"==typeof r[r.length-1]?r.slice(0,-1):r,c=null,l=JSON.stringify(a);return this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(l,"utf8")<8388608&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),s=(0,mongo_manager_1.objectIdHexString)(),c=new Promise(function(t,r){var n=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});n.on("change",function(e){"insert"===e.operationType&&(o._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?r:t)(e.data),n.close())}),n.on("error",function(e){console.error("Error watching worker responses:",e),r(e),n.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:a,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(n=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),c=(l=this._methods[t].function).call.apply(l,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(a),!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(n),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(n),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),r[r.length-1]&&"function"==typeof r[r.length-1]&&c.then(function(e){return r[r.length-1](null,e)},function(e){return r[r.length-1](e,null)}),c},MethodManager.prototype.sendWS=function(e,t,r,n,o){this._websocketManager.send(e,o),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([n,o]))<2e5?JSON.stringify([n,o],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:o.messageId,route:""})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(e){switch(e.label){case 0:return(t=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(n,void 0,void 0,function(){var t;return __generator(this,function(e){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){n.setupEmailWatcher()}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,n,o,i,s;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),n=r.next();!n.done;n=r.next())o=n.value,this.emailQueue.add(o._id.toString())}catch(e){i={error:e}}finally{try{n&&!n.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,d,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,7]),t=function(){var n,t,r,o,i,s,a,c,l,u;return __generator(this,function(e){switch(e.label){case 0:return i=d.emailQueue.values().next().value,d.emailQueue.delete(i),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:i,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(n=e.sent()))return[2,"continue"];if(!(n.attachments&&0<n.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),l=void 0,t=__values(n.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(o=r.value).path&&o.path.startsWith("http")?[4,fetch(o.path)]:[3,7];case 5:if((i=e.sent()).ok)return[4,i.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(o.path));case 6:s=e.sent(),s=Buffer.from(s),s.length<=20971520&&(o.content=s,delete o.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return s=e.sent(),l={error:s},[3,11];case 10:try{r&&!r.done&&(u=t.return)&&u.call(t)}finally{if(l)throw l.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof a?a:d.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(c={replyTo:n.reply_to||d.serverConfig.MAIL_REPLY_TO||void 0,from:n.send_from||d.serverConfig.MAIL_FROM,to:n.email,subject:(d.serverConfig.ROOT_URL.match(/https:\/\/dev\./)||d.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+n.subject,text:"string"==typeof n.text?n.text:"",html:"string"==typeof n.html?n.html:"",attachments:n.attachments||[]}).attachments&&0<c.attachments.length&&(c.attachments=c.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),[4,new Promise(function(r){h._mailer.sendMail(c,function(t,e){return __awaiter(h,void 0,void 0,function(){return __generator(this,function(e){try{t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})):"dev@resolveio.com"===n.email?email_history_collection_1.EmailHistories.deleteOne({_id:n._id}):email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"completed",completedAt:new Date}})}catch(e){console.error("Error in sendMail callback:",e),email_history_collection_1.EmailHistories.updateOne({_id:n._id},{$set:{status:"failed",error:"string"==typeof e?e:this.safeStringify(e),completedAt:new Date}})}finally{r()}return[2]})})})})];case 15:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 16:return e.sent(),[2]}})},d=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,7];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(o,i,s,a,c,l,u,d){var e=this;return void 0===d&&(d=!1),new Promise(function(r,n){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(o=!this.serverConfig.ROOT_URL.match(/https:\/\/dev\./)&&!this.serverConfig.ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||o.match(/\@resolveio\.com/)?o:"dev@resolveio.com")?"http://localhost:4200"!==this.serverConfig.ROOT_URL||d?(c=c||[],c=(c=Array.isArray(c)?c:[c]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:o,subject:i||"",text:s||"",html:a||"",attachments:c||[],send_from:l||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),n(e)})):(console.log("Send email",o,i,s,a,c,l),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(r,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?n(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?n(e):r(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(r,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?n(e):r(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?n(e):r(t)})})},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,i){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,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(r){return function(e){var t=[r,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(o,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,i=r.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)s.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),flag_updates_1=require("../methods/flag-updates"),__1=require(".."),AWS=function(){function AWS(){this._s3=null,this._s3USEast1=null}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,r){var o=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._websocketManager=__1.ResolveIOServer.getMainServer().getWebSocketManager(),this._monitorManagerFunction=e,this._isWorkersEnabled=t,this._isWorkerInstance=r,"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){console.log(new Date,"Start Server Fixture"),(0,init_1.loadServerInit)(),console.log(new Date,"End Server Fixture")},5e3),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS,__1.ResolveIOServer.getSESMail()?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:__1.ResolveIOServer.getServerConfig().MAIL_HOST,port:__1.ResolveIOServer.getServerConfig().MAIL_PORT,secure:!1,auth:{user:__1.ResolveIOServer.getServerConfig().MAIL_USERNAME,pass:__1.ResolveIOServer.getServerConfig().MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){__1.ResolveIOServer.getMainServer().getSubscriptionManager()&&__1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",o._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",o._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",o._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",o._debugCallMethodCronJobHits)),o._debugCallMethodInternalHits=0,o._debugCallMethodHits=0,o._debugCallMethodCronJobHits=0,o._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||this.setupEmailWatcher()}return MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var n=this,r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<r.length||r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().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 - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Method "+t);for(var o={},i=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),s=0;s<r.length;s++)o[i[s]]=r[s];try{this._methods[t].check.validate(o)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var a,c,l,u=null,d=JSON.stringify(r);return this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(d,"utf8")<8388608&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(a=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),c=(0,mongo_manager_1.objectIdHexString)(),u=new Promise(function(t,r){var o=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":c}}],{fullDocument:"updateLookup"});o.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(a),((e=e.fullDocument).has_error?r:t)(e.data),o.close())}),o.on("error",function(e){console.error("Error watching worker responses:",e),r(e),o.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:c,method:t,params:r,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(l=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",r),u=(d=this._methods[t].function).call.apply(d,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(r),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(l),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(l),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),u}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(o,n,i,s,a){for(var t=this,c=[],e=5;e<arguments.length;e++)c[e-5]=arguments[e];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<c.length||c[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,c,r={messageId:s,hasError:!0,data:"Internal Error"}),void(o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}));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 - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Schema For Method "+a),r={messageId:s,hasError:!0,data:"Internal Error"},o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}),void this.sendWS(n,i,a,c,r);for(var r,l={},u=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),d=0;d<c.length;d++)l[u[d]]=c[d];try{this._methods[a].check.validate(l)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(l,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,c,r={messageId:s,hasError:!0,data:"Internal Error"}),void(o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}))}}var _,h,g,f=JSON.stringify(c);this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(f,"utf8")<8388608&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a&&"incorrectUser"!==a&&"reloadWS"!==a&&"reconnectWS"!==a&&"disconnectWS"!==a?(_=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",c),f=(0,mongo_manager_1.objectIdHexString)(),(h=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":f}}],{fullDocument:"updateLookup"})).on("change",function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==r.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(_),t=r.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,c,t),o?[4,log_method_latency_collection_1.LogMethodLatencies.findById(o)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:o},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:h.close(),e.label=3;case 3:return[2]}})})}),h.on("error",function(e){console.error("Error watching worker responses:",e),h.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:f,method:a,params:c,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(g=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",c),(f=this._methods[a].function).call.apply(f,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],__read(c),!1)).then(function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(g),t={messageId:s,hasError:!1,data:r},this.sendWS(n,i,a,c,t),o)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(o)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:o},{$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(g),t.sendWS(n,i,a,c,{messageId:s,hasError:!0,data:e}),o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(c,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+a),r={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,c,r),o&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:o})},MethodManager.prototype.callMethodInternal=function(t){for(var n=this,r=[],e=1;e<arguments.length;e++)r[e-1]=arguments[e];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<r.length||r[0]&&"function"!=typeof r[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"countCollectionWithQuery"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r]))<2e5?JSON.stringify([r],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,o,a="function"==typeof r[r.length-1]?r.slice(0,-1):r,c=null,l=JSON.stringify(a);return this._isWorkersEnabled&&!this._isWorkerInstance&&Buffer.byteLength(l,"utf8")<8388608&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),s=(0,mongo_manager_1.objectIdHexString)(),c=new Promise(function(t,r){var o=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});o.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?r:t)(e.data),o.close())}),o.on("error",function(e){console.error("Error watching worker responses:",e),r(e),o.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:a,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(o=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",a),c=(l=this._methods[t].function).call.apply(l,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(a),!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(o),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(o),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+__1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(r,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),r[r.length-1]&&"function"==typeof r[r.length-1]&&c.then(function(e){return r[r.length-1](null,e)},function(e){return r[r.length-1](e,null)}),c},MethodManager.prototype.sendWS=function(e,t,r,o,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==r&&"reportBuilderGetDistinctValue"!==r&&"reportBuilderBuildTree"!==r&&"generatePDF"!==r&&"getWOOfflineData"!==r&&"countQuery"!==r&&"countWithQuery"!==r&&"countCollectionWithQuery"!==r&&"find"!==r&&"findOne"!==r&&"findWithOptions"!==r&&"uploadFileAndSave"!==r&&"getDrivers"!==r&&"processAirdropDistribution"!==r&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o,n]))<2e5?JSON.stringify([o,n],null,2):"Too Big",method:r,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){switch(e.label){case 0:return(t=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),this.tryProcessEmail()):"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),[2]})})}).on("error",function(e){console.error("Email history changestream error",e),t.close()}).on("close",function(){o.setupEmailWatcher()}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,n,i,s;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),o=r.next();!o.done;o=r.next())n=o.value,this.emailQueue.add(n._id.toString())}catch(e){i={error:e}}finally{try{o&&!o.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return this.tryProcessEmail(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,d,r,_=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,7]),t=function(){var o,t,r,n,i,s,a,c,l,u;return __generator(this,function(e){switch(e.label){case 0:return i=d.emailQueue.values().next().value,d.emailQueue.delete(i),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:i,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(o=e.sent()))return[2,"continue"];if(!(o.attachments&&0<o.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),l=void 0,t=__values(o.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(n=r.value).path&&n.path.startsWith("http")?[4,fetch(n.path)]:[3,7];case 5:if((i=e.sent()).ok)return[4,i.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(n.path));case 6:s=e.sent(),s=Buffer.from(s),s.length<=20971520&&(n.content=s,delete n.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return s=e.sent(),l={error:s},[3,11];case 10:try{r&&!r.done&&(u=t.return)&&u.call(t)}finally{if(l)throw l.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof a?a:d.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(c={replyTo:o.reply_to||__1.ResolveIOServer.getServerConfig().MAIL_REPLY_TO||void 0,from:o.send_from||__1.ResolveIOServer.getServerConfig().MAIL_FROM,to:o.email,subject:(__1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)||__1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+o.subject,text:"string"==typeof o.text?o.text:"",html:"string"==typeof o.html?o.html:"",attachments:o.attachments||[]}).attachments&&0<c.attachments.length&&(c.attachments=c.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),[4,new Promise(function(r){_._mailer.sendMail(c,function(t,e){return __awaiter(_,void 0,void 0,function(){return __generator(this,function(e){try{t?(console.error("Failed to send email:",t),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})):"dev@resolveio.com"===o.email?email_history_collection_1.EmailHistories.deleteOne({_id:o._id}):email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}})}catch(e){console.error("Error in sendMail callback:",e),email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof e?e:this.safeStringify(e),completedAt:new Date}})}finally{r()}return[2]})})})})];case 15:return e.sent(),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 16:return e.sent(),[2]}})},d=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,7];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,7];case 6:return this.isEmailProcessing=!1,0<this.emailQueue.size&&this.tryProcessEmail(),[7];case 7:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(n,i,s,a,c,l,u,d){var e=this;return void 0===d&&(d=!1),new Promise(function(r,o){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){return(n=!__1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)&&!__1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==__1.ResolveIOServer.getServerConfig().ROOT_URL||n.match(/\@resolveio\.com/)?n:"dev@resolveio.com")?"http://localhost:4200"!==__1.ResolveIOServer.getServerConfig().ROOT_URL||d?(c=c||[],c=(c=Array.isArray(c)?c:[c]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:n,subject:i||"",text:s||"",html:a||"",attachments:c||[],send_from:l||"",reply_to:u||"",status:"pending",error:""},email_history_collection_1.EmailHistories.insertOne(t).then(function(e){return r(e)},function(e){console.error("Failed to queue email:",e),o(e)})):(console.log("Send email",n,i,s,a,c,l),r(!0)):r(!0),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(__1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(__1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8",function(e,t){e?o(e):r(t)})})},MethodManager.prototype.readImage=function(e){return new Promise(function(r,o){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?o(e):r(t)}):fs.existsSync(path.join(__1.ResolveIOServer.getClientDir(),"./private/"+e))&&fs.readFile(path.join(__1.ResolveIOServer.getClientDir(),"./private/"+e),"base64",function(e,t){e?o(e):r(t)})})},MethodManager}());exports.MethodManager=MethodManager;
2
2
  //# sourceMappingURL=method.manager.js.map