@resolveio/server-lib 20.6.16 → 20.6.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/managers/method.manager.js +1 -1
- package/managers/method.manager.js.map +1 -1
- package/managers/mongo.manager.js +1 -1
- package/managers/mongo.manager.js.map +1 -1
- package/methods/logs.js +1 -1
- package/methods/logs.js.map +1 -1
- package/package.json +1 -1
- package/server-app.js +1 -1
- package/server-app.js.map +1 -1
package/methods/logs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,i){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var i,a,c,s={label:0,sent:function(){if(1&c[0])throw c[1];return c[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(i)throw new TypeError("Generator is already executing.");for(;s=l&&t[l=0]?0:s;)try{if(i=1,a&&(c=2&t[0]?a.return:t[0]?a.throw||((c=a.return)&&c.call(a),0):a.next)&&!(c=c.call(a,t[1])).done)return c;switch(a=0,(t=c?[2&t[0],c.value]:t)[0]){case 0:case 1:c=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,a=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(c=0<(c=s.trys).length&&c[c.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!c||t[1]>c[0]&&t[1]<c[3]))s.label=t[1];else if(6===t[0]&&s.label<c[1])s.label=c[1],c=t;else{if(!(c&&s.label<c[2])){c[2]&&s.ops.pop(),s.trys.pop();continue}s.label=c[2],s.ops.push(t)}}t=n.call(r,s)}catch(e){t=[6,e],a=0}finally{i=c=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},log_collection_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.loadLogMethods=void 0,require("../collections/log.collection")),log_subscription_collection_1=require("../collections/log-subscription.collection"),resolveio_server_app_1=require("../resolveio-server-app"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),common_1=require("../util/common");function loadLogMethods(e){e.methods({insertErrorLog:{function:function(o,r){var n=this;return new Promise(function(e,t){n.sendEmail("dev@resolveio.com","Error Detected - "+resolveio_server_app_1.ResolveIOServer.getClientName(),n.user+"\n"+o+"\n"+JSON.stringify(r,null,2)),"https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),type:"error",collection:"",id_document:"",payload:JSON.stringify(r,null,2),method:"",id_user:n.id_user||"",user:n.user||"",messageId:0,route:""}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"error",collection:"",id_document:"",payload:JSON.stringify(r,null,2),method:"",id_user:n.id_user||"",user:n.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com"}),e(!0)})},skipValidation:!0},insertSubscriptionLog:{function:function(o,r,n,i){return new Promise(function(e,t){"https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-subscription",data:{_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,type:o,subscription:r,collection_name:n,subData:i}}):log_subscription_collection_1.LogSubscriptions.create({_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,type:o,subscription:r,collection_name:n,subData:i,client:"ResolveIO",instance:"backend.resolveio.com"}),e(!0)})},skipValidation:!0},superadminAPM:{function:function(s,l,d){var t=this;return new Promise(function(c,e){return __awaiter(t,void 0,void 0,function(){var t,o,r,n,i,a;return __generator(this,function(e){switch(e.label){case 0:return[4,log_method_latency_collection_1.LogMethodLatencies.aggregate([{$match:{$and:[{createdAt:{$gte:s}},{createdAt:{$lte:l}}]}},{$group:{_id:"$method",method:{$first:"$method"},count:{$sum:1},latency_min:{$min:"$latency_ms"},latency_avg:{$avg:"$latency_ms"},latency_max:{$max:"$latency_ms"}}}],{allowDiskUse:!0,readPreference:"http://localhost:4200"!==this.serverConfig.ROOT_URL?"secondary":"primary"},!0)];case 1:return t=e.sent(),[4,log_subscription_collection_1.LogSubscriptions.aggregate([{$match:{$and:[{createdAt:{$gte:s}},{createdAt:{$lte:l}}]}},{$group:{_id:"$subscription",subscription:{$first:"$subscription"},count:{$sum:1}}}],{allowDiskUse:!0,readPreference:"http://localhost:4200"!==this.serverConfig.ROOT_URL?"secondary":"primary"},!0)];case 2:return o=e.sent(),r={},n={},n="seconds"===d?(r={second:{$second:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},minute:{$minute:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},hour:{$hour:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},day:{$dayOfMonth:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},month:{$month:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},year:{$year:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}}},{"_id.year":1,"_id.month":1,"_id.day":1,"_id.hour":1,"_id.minute":1,"_id.second":1}):"minutes"===d?(r={minute:{$minute:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},hour:{$hour:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},day:{$dayOfMonth:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},month:{$month:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},year:{$year:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}}},{"_id.year":1,"_id.month":1,"_id.day":1,"_id.hour":1,"_id.minute":1}):"hours"===d?(r={hour:{$hour:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},day:{$dayOfMonth:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},month:{$month:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},year:{$year:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}}},{"_id.year":1,"_id.month":1,"_id.day":1,"_id.hour":1}):(r={day:{$dayOfMonth:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},month:{$month:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},year:{$year:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}}},{"_id.year":1,"_id.month":1,"_id.day":1}),[4,log_method_latency_collection_1.LogMethodLatencies.aggregate([{$match:{$and:[{createdAt:{$gte:s}},{createdAt:{$lte:l}}]}},{$group:{_id:r,count:{$sum:1}}},{$sort:n}],{allowDiskUse:!0,readPreference:"http://localhost:4200"!==this.serverConfig.ROOT_URL?"secondary":"primary"},!0)];case 3:return i=e.sent(),[4,log_subscription_collection_1.LogSubscriptions.aggregate([{$match:{$and:[{createdAt:{$gte:s}},{createdAt:{$lte:l}}]}},{$group:{_id:r,count:{$sum:1}}},{$sort:n}],{allowDiskUse:!0,readPreference:"http://localhost:4200"!==this.serverConfig.ROOT_URL?"secondary":"primary"},!0)];case 4:return a=e.sent(),c({methods:t,subscriptions:o,methodGraphData:i,subGraphData:a}),[2]}})})})},skipValidation:!0}})}exports.loadLogMethods=loadLogMethods;
|
|
1
|
+
"use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,i){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var i,a,c,s={label:0,sent:function(){if(1&c[0])throw c[1];return c[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(i)throw new TypeError("Generator is already executing.");for(;s=l&&t[l=0]?0:s;)try{if(i=1,a&&(c=2&t[0]?a.return:t[0]?a.throw||((c=a.return)&&c.call(a),0):a.next)&&!(c=c.call(a,t[1])).done)return c;switch(a=0,(t=c?[2&t[0],c.value]:t)[0]){case 0:case 1:c=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,a=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(c=0<(c=s.trys).length&&c[c.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!c||t[1]>c[0]&&t[1]<c[3]))s.label=t[1];else if(6===t[0]&&s.label<c[1])s.label=c[1],c=t;else{if(!(c&&s.label<c[2])){c[2]&&s.ops.pop(),s.trys.pop();continue}s.label=c[2],s.ops.push(t)}}t=n.call(r,s)}catch(e){t=[6,e],a=0}finally{i=c=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},log_collection_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.loadLogMethods=void 0,require("../collections/log.collection")),log_subscription_collection_1=require("../collections/log-subscription.collection"),resolveio_server_app_1=require("../resolveio-server-app"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),common_1=require("../util/common");function loadLogMethods(e){e.methods({insertErrorLog:{function:function(o,r){var n=this;return new Promise(function(e,t){n.sendEmail("dev@resolveio.com","Error Detected - "+resolveio_server_app_1.ResolveIOServer.getClientName(),n.user+"\n"+o+"\n"+JSON.stringify(r,null,2)),"https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"error",collection:"",id_document:"",payload:JSON.stringify(r,null,2),method:"",id_user:n.id_user||"",user:n.user||"",messageId:0,route:""}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"error",collection:"",id_document:"",payload:JSON.stringify(r,null,2),method:"",id_user:n.id_user||"",user:n.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com"}),e(!0)})},skipValidation:!0},insertSubscriptionLog:{function:function(o,r,n,i){return new Promise(function(e,t){"https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-subscription",data:{_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,type:o,subscription:r,collection_name:n,subData:i}}):log_subscription_collection_1.LogSubscriptions.create({_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,type:o,subscription:r,collection_name:n,subData:i,client:"ResolveIO",instance:"backend.resolveio.com"}),e(!0)})},skipValidation:!0},superadminAPM:{function:function(s,l,d){var t=this;return new Promise(function(c,e){return __awaiter(t,void 0,void 0,function(){var t,o,r,n,i,a;return __generator(this,function(e){switch(e.label){case 0:return[4,log_method_latency_collection_1.LogMethodLatencies.aggregate([{$match:{$and:[{createdAt:{$gte:s}},{createdAt:{$lte:l}}]}},{$group:{_id:"$method",method:{$first:"$method"},count:{$sum:1},latency_min:{$min:"$latency_ms"},latency_avg:{$avg:"$latency_ms"},latency_max:{$max:"$latency_ms"}}}],{allowDiskUse:!0,readPreference:"http://localhost:4200"!==this.serverConfig.ROOT_URL?"secondary":"primary"},!0)];case 1:return t=e.sent(),[4,log_subscription_collection_1.LogSubscriptions.aggregate([{$match:{$and:[{createdAt:{$gte:s}},{createdAt:{$lte:l}}]}},{$group:{_id:"$subscription",subscription:{$first:"$subscription"},count:{$sum:1}}}],{allowDiskUse:!0,readPreference:"http://localhost:4200"!==this.serverConfig.ROOT_URL?"secondary":"primary"},!0)];case 2:return o=e.sent(),r={},n={},n="seconds"===d?(r={second:{$second:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},minute:{$minute:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},hour:{$hour:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},day:{$dayOfMonth:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},month:{$month:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},year:{$year:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}}},{"_id.year":1,"_id.month":1,"_id.day":1,"_id.hour":1,"_id.minute":1,"_id.second":1}):"minutes"===d?(r={minute:{$minute:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},hour:{$hour:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},day:{$dayOfMonth:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},month:{$month:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},year:{$year:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}}},{"_id.year":1,"_id.month":1,"_id.day":1,"_id.hour":1,"_id.minute":1}):"hours"===d?(r={hour:{$hour:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},day:{$dayOfMonth:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},month:{$month:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},year:{$year:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}}},{"_id.year":1,"_id.month":1,"_id.day":1,"_id.hour":1}):(r={day:{$dayOfMonth:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},month:{$month:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}},year:{$year:{date:"$createdAt",timezone:process.env.TZ_CLIENT||"America/Chicago"}}},{"_id.year":1,"_id.month":1,"_id.day":1}),[4,log_method_latency_collection_1.LogMethodLatencies.aggregate([{$match:{$and:[{createdAt:{$gte:s}},{createdAt:{$lte:l}}]}},{$group:{_id:r,count:{$sum:1}}},{$sort:n}],{allowDiskUse:!0,readPreference:"http://localhost:4200"!==this.serverConfig.ROOT_URL?"secondary":"primary"},!0)];case 3:return i=e.sent(),[4,log_subscription_collection_1.LogSubscriptions.aggregate([{$match:{$and:[{createdAt:{$gte:s}},{createdAt:{$lte:l}}]}},{$group:{_id:r,count:{$sum:1}}},{$sort:n}],{allowDiskUse:!0,readPreference:"http://localhost:4200"!==this.serverConfig.ROOT_URL?"secondary":"primary"},!0)];case 4:return a=e.sent(),c({methods:t,subscriptions:o,methodGraphData:i,subGraphData:a}),[2]}})})})},skipValidation:!0}})}exports.loadLogMethods=loadLogMethods;
|
|
2
2
|
//# sourceMappingURL=logs.js.map
|
package/methods/logs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/methods/logs.ts"],"names":["log_collection_1","require","log_subscription_collection_1","resolveio_server_app_1","log_method_latency_collection_1","common_1","loadLogMethods","methodManager","methods","insertErrorLog","function","message","data","_this","this","Promise","resolve","reject","sendEmail","ResolveIOServer","getClientName","user","JSON","stringify","getServerConfig","getLocalLogManager","writeLog","type","_id","objectIdHexString","collection","id_document","payload","method","id_user","messageId","route","Logs","insertOne","client","instance","skipValidation","insertSubscriptionLog","subscription","collection_name","subData","__v","date","Date","LogSubscriptions","create","superadminAPM","date_start","date_end","graphInterval","__awaiter","LogMethodLatencies","aggregate","$match","$and","createdAt","$gte","$lte","$group","$first","count","$sum","latency_min","$min","latency_avg","$avg","latency_max","$max","allowDiskUse","readPreference","serverConfig","latencies","_a","sent","subscriptions","groupId","groupSort","second","$second","timezone","process","env","TZ_CLIENT","minute","$minute","hour","$hour","day","$dayOfMonth","month","$month","year","$year","_id.year","_id.month","_id.day","_id.hour","_id.minute","_id.second","$sort","methodGraphData","subGraphData","exports"],"mappings":"k8CACAA,kB,qFAAAC,QAAA,+BAAA,GACAC,8BAAAD,QAAA,4CAAA,EACAE,uBAAAF,QAAA,yBAAA,EACAG,gCAAAH,QAAA,8CAAA,EACAI,SAAAJ,QAAA,gBAAA,EAEA,SAAgBK,eAAeC,GAC9BA,EAAcC,QAAQ,CACrBC,eAAgB,CACfC,SAAU,SAASC,EAASC,GAAlB,IAAAC,EAAAC,KACT,OAAO,IAAIC,QAAQ,SAACC,EAASC,GAC5BJ,EAAKK,UAAU,oBAAqB,oBAAsBf,uBAAAgB,gBAAgBC,cAAa,EAAIP,EAAKQ,KAAO,KAAOV,EAAU,KAAOW,KAAKC,UAAUX,EAAM,KAAM,CAAC,CAAC,EAGzG,0BAAlDT,uBAAAgB,gBAAgBK,gBAAe,EAAa,UACQ,0BAAlDrB,uBAAAgB,gBAAgBK,gBAAe,EAAa,SAE9CrB,uBAAAgB,gBAAgBM,mBAAkB,EAAGC,SAAS,CAC7CC,KAAM,MACNf,KAAM,CACLgB,KAAK,EAAAvB,SAAAwB,mBAAiB,EACtBF,KAAM,QACNG,WAAY,GACZC,YAAa,GACbC,QAASV,KAAKC,UAAUX,EAAM,KAAM,CAAC,EACrCqB,OAAQ,GACRC,QAASrB,EAAKqB,SAAW,GACzBb,KAAMR,EAAKQ,MAAQ,GACnBc,UAAW,EACXC,MAAO,E,EAER,EAGDpC,iBAAAqC,KAAKC,UA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AAO,CACNC,OAAQ,CACPhD,KAAM,aACNqC,SAAUC,QAAQC,IAAIC,WAAa,iB,GAGrCS,KAAM,CACLC,MAAO,CACNlD,KAAM,aACNqC,SAAUC,QAAQC,IAAIC,WAAa,iB,IAK1B,CACXW,WAAY,EACZC,YAAa,EACbC,UAAW,C,GAIS,CAAA,EAAMhG,gCAAAoD,mBAAmBC,UAAU,CACxD,CACCC,OAAQ,CACPC,KAAM,CACL,CACCC,UAAW,CAACC,KAAMT,CAAU,C,EAE7B,CACCQ,UAAW,CAACE,KAAMT,CAAQ,C,KAK9B,CACCU,OAAQ,CACPnC,IAAKoD,EACLf,MAAO,CACNC,KAAM,C,IAIT,CACCsC,MAAOvB,C,GAEN,CAACR,aAAc,CAAA,EAAMC,eAAkD,0BAAlC5D,KAAK6D,aAAuB,SAAgC,YAAc,SAAS,EAAG,CAAA,CAAI,G,OAE/G,OA1Bf8B,EAAkB5B,EAAAC,KAAA,EA0BH,CAAA,EAAM5E,8BAAA+C,iBAAiBQ,UAAU,CACnD,CACCC,OAAQ,CACPC,KAAM,CACL,CACCC,UAAW,CAACC,KAAMT,CAAU,C,EAE7B,CACCQ,UAAW,CAACE,KAAMT,CAAQ,C,KAK9B,CACCU,OAAQ,CACPnC,IAAKoD,EACLf,MAAO,CACNC,KAAM,C,IAIT,CACCsC,MAAOvB,C,GAEN,CAACR,aAAc,CAAA,EAAMC,eAAkD,0BAAlC5D,KAAK6D,aAAuB,SAAgC,YAAc,SAAS,EAAG,CAAA,CAAI,G,cAxB9H+B,EAAe7B,EAAAC,KAAA,EA0BnB9D,EAAQ,CACPR,QAASoE,EACTG,cAAeA,EACf0B,gBAAiBA,EACjBC,aAAcA,C,CACd,E,SACD,CACF,EACAjE,eAAgB,CAAA,C,EAEjB,CACF,CAvWAkE,QAAArG,eAAAA","file":"logs.js","sourcesContent":["import { MethodManager } from '../managers/method.manager';\nimport { Logs } from '../collections/log.collection';\nimport { LogSubscriptions } from '../collections/log-subscription.collection';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport { objectIdHexString } from '../util/common';\n\nexport function loadLogMethods(methodManager: MethodManager) {\n\tmethodManager.methods({\n\t\tinsertErrorLog: {\n\t\t\tfunction: function(message, data) {\n\t\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'Error Detected - ' + ResolveIOServer.getClientName(), this.user + '\\n' + message + '\\n' + JSON.stringify(data, null, 2));\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: JSON.stringify(data, null, 2),\n\t\t\t\t\t\t\t\tmethod: '',\n\t\t\t\t\t\t\t\tid_user: this.id_user || '',\n\t\t\t\t\t\t\t\tuser: this.user || '',\n\t\t\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\t\t\troute: '',\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: JSON.stringify(data, null, 2),\n\t\t\t\t\t\t\tmethod: '',\n\t\t\t\t\t\t\tid_user: this.id_user || '',\n\t\t\t\t\t\t\tuser: this.user || '',\n\t\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\t\troute: '',\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(true);\n\t\t\t\t});\n\t\t\t},\n\t\t\tskipValidation: true\n\t\t},\n\t\tinsertSubscriptionLog: {\n\t\t\tfunction: function(type, subscription, collection_name, subData) {\n\t\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log-subscription',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\ttype: type,\n\t\t\t\t\t\t\t\tsubscription: subscription,\n\t\t\t\t\t\t\t\tcollection_name: collection_name,\n\t\t\t\t\t\t\t\tsubData: subData\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogSubscriptions.create({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\ttype: type,\n\t\t\t\t\t\t\tsubscription: subscription,\n\t\t\t\t\t\t\tcollection_name: collection_name,\n\t\t\t\t\t\t\tsubData: subData,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(true);\n\t\t\t\t});\n\t\t\t},\n\t\t\tskipValidation: true\n\t\t},\n\t\tsuperadminAPM: {\n\t\t\tfunction: function(date_start: Date, date_end: Date, graphInterval) {\n\t\t\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t\t\tlet latencies = await LogMethodLatencies.aggregate([\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$gte: date_start}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$lte: date_end}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: '$method',\n\t\t\t\t\t\t\t\tmethod: {$first: '$method'},\n\t\t\t\t\t\t\t\tcount: {$sum: 1},\n\t\t\t\t\t\t\t\tlatency_min: {$min: '$latency_ms'},\n\t\t\t\t\t\t\t\tlatency_avg: {$avg: '$latency_ms'},\n\t\t\t\t\t\t\t\tlatency_max: {$max: '$latency_ms'}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t], {allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary'}, true);\n\n\t\t\t\t\tlet subscriptions = await LogSubscriptions.aggregate([\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$gte: date_start}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$lte: date_end}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: '$subscription',\n\t\t\t\t\t\t\t\tsubscription: {$first: '$subscription'},\n\t\t\t\t\t\t\t\tcount: {$sum: 1}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t], {allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary'}, true);\n\n\t\t\t\t\tlet groupId = {};\n\t\t\t\t\tlet groupSort = {};\n\n\t\t\t\t\tif (graphInterval === 'seconds') {\n\t\t\t\t\t\tgroupId = {\n\t\t\t\t\t\t\tsecond: {\n\t\t\t\t\t\t\t\t$second: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tminute: {\n\t\t\t\t\t\t\t\t$minute: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\thour: {\n\t\t\t\t\t\t\t\t$hour: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tday: {\n\t\t\t\t\t\t\t\t$dayOfMonth: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmonth: {\n\t\t\t\t\t\t\t\t$month: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tyear: {\n\t\t\t\t\t\t\t\t$year: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tgroupSort = {\n\t\t\t\t\t\t\t'_id.year': 1,\n\t\t\t\t\t\t\t'_id.month': 1,\n\t\t\t\t\t\t\t'_id.day': 1,\n\t\t\t\t\t\t\t'_id.hour': 1,\n\t\t\t\t\t\t\t'_id.minute': 1,\n\t\t\t\t\t\t\t'_id.second': 1\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\telse if (graphInterval === 'minutes') {\n\t\t\t\t\t\tgroupId = {\n\t\t\t\t\t\t\tminute: {\n\t\t\t\t\t\t\t\t$minute: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\thour: {\n\t\t\t\t\t\t\t\t$hour: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tday: {\n\t\t\t\t\t\t\t\t$dayOfMonth: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmonth: {\n\t\t\t\t\t\t\t\t$month: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tyear: {\n\t\t\t\t\t\t\t\t$year: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tgroupSort = {\n\t\t\t\t\t\t\t'_id.year': 1,\n\t\t\t\t\t\t\t'_id.month': 1,\n\t\t\t\t\t\t\t'_id.day': 1,\n\t\t\t\t\t\t\t'_id.hour': 1,\n\t\t\t\t\t\t\t'_id.minute': 1\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\telse if (graphInterval === 'hours') {\n\t\t\t\t\t\tgroupId = {\n\t\t\t\t\t\t\thour: {\n\t\t\t\t\t\t\t\t$hour: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tday: {\n\t\t\t\t\t\t\t\t$dayOfMonth: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmonth: {\n\t\t\t\t\t\t\t\t$month: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tyear: {\n\t\t\t\t\t\t\t\t$year: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tgroupSort = {\n\t\t\t\t\t\t\t'_id.year': 1,\n\t\t\t\t\t\t\t'_id.month': 1,\n\t\t\t\t\t\t\t'_id.day': 1,\n\t\t\t\t\t\t\t'_id.hour': 1\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgroupId = {\n\t\t\t\t\t\t\tday: {\n\t\t\t\t\t\t\t\t$dayOfMonth: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmonth: {\n\t\t\t\t\t\t\t\t$month: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tyear: {\n\t\t\t\t\t\t\t\t$year: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tgroupSort = {\n\t\t\t\t\t\t\t'_id.year': 1,\n\t\t\t\t\t\t\t'_id.month': 1,\n\t\t\t\t\t\t\t'_id.day': 1\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tlet methodGraphData = await LogMethodLatencies.aggregate([\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$gte: date_start}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$lte: date_end}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: groupId,\n\t\t\t\t\t\t\t\tcount: {\n\t\t\t\t\t\t\t\t\t$sum: 1\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$sort: groupSort\n\t\t\t\t\t\t}\n\t\t\t\t\t], {allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary'}, true);\n\n\t\t\t\t\tlet subGraphData = await LogSubscriptions.aggregate([\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$gte: date_start}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$lte: date_end}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: groupId,\n\t\t\t\t\t\t\t\tcount: {\n\t\t\t\t\t\t\t\t\t$sum: 1\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$sort: groupSort\n\t\t\t\t\t\t}\n\t\t\t\t\t], {allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary'}, true);\n\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tmethods: latencies,\n\t\t\t\t\t\tsubscriptions: subscriptions,\n\t\t\t\t\t\tmethodGraphData: methodGraphData,\n\t\t\t\t\t\tsubGraphData: subGraphData\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t},\n\t\t\tskipValidation: true\n\t\t}\n\t});\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/methods/logs.ts"],"names":["log_collection_1","require","log_subscription_collection_1","resolveio_server_app_1","log_method_latency_collection_1","common_1","loadLogMethods","methodManager","methods","insertErrorLog","function","message","data","_this","this","Promise","resolve","reject","sendEmail","ResolveIOServer","getClientName","user","JSON","stringify","getServerConfig","getLocalLogManager","writeLog","type","_id","objectIdHexString","createdAt","Date","collection","id_document","payload","method","id_user","messageId","route","Logs","insertOne","client","instance","skipValidation","insertSubscriptionLog","subscription","collection_name","subData","__v","date","LogSubscriptions","create","superadminAPM","date_start","date_end","graphInterval","__awaiter","LogMethodLatencies","aggregate","$match","$and","$gte","$lte","$group","$first","count","$sum","latency_min","$min","latency_avg","$avg","latency_max","$max","allowDiskUse","readPreference","serverConfig","latencies","_a","sent","subscriptions","groupId","groupSort","second","$second","timezone","process","env","TZ_CLIENT","minute","$minute","hour","$hour","day","$dayOfMonth","month","$month","year","$year","_id.year","_id.month","_id.day","_id.hour","_id.minute","_id.second","$sort","methodGraphData","subGraphData","exports"],"mappings":"k8CACAA,kB,qFAAAC,QAAA,+BAAA,GACAC,8BAAAD,QAAA,4CAAA,EACAE,uBAAAF,QAAA,yBAAA,EACAG,gCAAAH,QAAA,8CAAA,EACAI,SAAAJ,QAAA,gBAAA,EAEA,SAAgBK,eAAeC,GAC9BA,EAAcC,QAAQ,CAC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,SAAS,EAAG,CAAA,CAAI,G,OAE/G,OA1Bf8B,EAAkB5B,EAAAC,KAAA,EA0BH,CAAA,EAAM5E,8BAAAgD,iBAAiBQ,UAAU,CACnD,CACCC,OAAQ,CACPC,KAAM,CACL,CACC9B,UAAW,CAAC+B,KAAMR,CAAU,C,EAE7B,CACCvB,UAAW,CAACgC,KAAMR,CAAQ,C,KAK9B,CACCS,OAAQ,CACPnC,IAAKoD,EACLf,MAAO,CACNC,KAAM,C,IAIT,CACCsC,MAAOvB,C,GAEN,CAACR,aAAc,CAAA,EAAMC,eAAkD,0BAAlC5D,KAAK6D,aAAuB,SAAgC,YAAc,SAAS,EAAG,CAAA,CAAI,G,cAxB9H+B,EAAe7B,EAAAC,KAAA,EA0BnB9D,EAAQ,CACPR,QAASoE,EACTG,cAAeA,EACf0B,gBAAiBA,EACjBC,aAAcA,C,CACd,E,SACD,CACF,EACA/D,eAAgB,CAAA,C,EAEjB,CACF,CAxWAgE,QAAArG,eAAAA","file":"logs.js","sourcesContent":["import { MethodManager } from '../managers/method.manager';\nimport { Logs } from '../collections/log.collection';\nimport { LogSubscriptions } from '../collections/log-subscription.collection';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport { objectIdHexString } from '../util/common';\n\nexport function loadLogMethods(methodManager: MethodManager) {\n\tmethodManager.methods({\n\t\tinsertErrorLog: {\n\t\t\tfunction: function(message, data) {\n\t\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'Error Detected - ' + ResolveIOServer.getClientName(), this.user + '\\n' + message + '\\n' + JSON.stringify(data, null, 2));\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: JSON.stringify(data, null, 2),\n\t\t\t\t\t\t\t\tmethod: '',\n\t\t\t\t\t\t\t\tid_user: this.id_user || '',\n\t\t\t\t\t\t\t\tuser: this.user || '',\n\t\t\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\t\t\troute: '',\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: JSON.stringify(data, null, 2),\n\t\t\t\t\t\t\tmethod: '',\n\t\t\t\t\t\t\tid_user: this.id_user || '',\n\t\t\t\t\t\t\tuser: this.user || '',\n\t\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\t\troute: '',\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(true);\n\t\t\t\t});\n\t\t\t},\n\t\t\tskipValidation: true\n\t\t},\n\t\tinsertSubscriptionLog: {\n\t\t\tfunction: function(type, subscription, collection_name, subData) {\n\t\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log-subscription',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\ttype: type,\n\t\t\t\t\t\t\t\tsubscription: subscription,\n\t\t\t\t\t\t\t\tcollection_name: collection_name,\n\t\t\t\t\t\t\t\tsubData: subData\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogSubscriptions.create({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\ttype: type,\n\t\t\t\t\t\t\tsubscription: subscription,\n\t\t\t\t\t\t\tcollection_name: collection_name,\n\t\t\t\t\t\t\tsubData: subData,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(true);\n\t\t\t\t});\n\t\t\t},\n\t\t\tskipValidation: true\n\t\t},\n\t\tsuperadminAPM: {\n\t\t\tfunction: function(date_start: Date, date_end: Date, graphInterval) {\n\t\t\t\treturn new Promise(async (resolve, reject) => {\n\t\t\t\t\tlet latencies = await LogMethodLatencies.aggregate([\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$gte: date_start}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$lte: date_end}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: '$method',\n\t\t\t\t\t\t\t\tmethod: {$first: '$method'},\n\t\t\t\t\t\t\t\tcount: {$sum: 1},\n\t\t\t\t\t\t\t\tlatency_min: {$min: '$latency_ms'},\n\t\t\t\t\t\t\t\tlatency_avg: {$avg: '$latency_ms'},\n\t\t\t\t\t\t\t\tlatency_max: {$max: '$latency_ms'}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t], {allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary'}, true);\n\n\t\t\t\t\tlet subscriptions = await LogSubscriptions.aggregate([\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$gte: date_start}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$lte: date_end}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: '$subscription',\n\t\t\t\t\t\t\t\tsubscription: {$first: '$subscription'},\n\t\t\t\t\t\t\t\tcount: {$sum: 1}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t], {allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary'}, true);\n\n\t\t\t\t\tlet groupId = {};\n\t\t\t\t\tlet groupSort = {};\n\n\t\t\t\t\tif (graphInterval === 'seconds') {\n\t\t\t\t\t\tgroupId = {\n\t\t\t\t\t\t\tsecond: {\n\t\t\t\t\t\t\t\t$second: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tminute: {\n\t\t\t\t\t\t\t\t$minute: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\thour: {\n\t\t\t\t\t\t\t\t$hour: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tday: {\n\t\t\t\t\t\t\t\t$dayOfMonth: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmonth: {\n\t\t\t\t\t\t\t\t$month: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tyear: {\n\t\t\t\t\t\t\t\t$year: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tgroupSort = {\n\t\t\t\t\t\t\t'_id.year': 1,\n\t\t\t\t\t\t\t'_id.month': 1,\n\t\t\t\t\t\t\t'_id.day': 1,\n\t\t\t\t\t\t\t'_id.hour': 1,\n\t\t\t\t\t\t\t'_id.minute': 1,\n\t\t\t\t\t\t\t'_id.second': 1\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\telse if (graphInterval === 'minutes') {\n\t\t\t\t\t\tgroupId = {\n\t\t\t\t\t\t\tminute: {\n\t\t\t\t\t\t\t\t$minute: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\thour: {\n\t\t\t\t\t\t\t\t$hour: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tday: {\n\t\t\t\t\t\t\t\t$dayOfMonth: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmonth: {\n\t\t\t\t\t\t\t\t$month: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tyear: {\n\t\t\t\t\t\t\t\t$year: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tgroupSort = {\n\t\t\t\t\t\t\t'_id.year': 1,\n\t\t\t\t\t\t\t'_id.month': 1,\n\t\t\t\t\t\t\t'_id.day': 1,\n\t\t\t\t\t\t\t'_id.hour': 1,\n\t\t\t\t\t\t\t'_id.minute': 1\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\telse if (graphInterval === 'hours') {\n\t\t\t\t\t\tgroupId = {\n\t\t\t\t\t\t\thour: {\n\t\t\t\t\t\t\t\t$hour: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tday: {\n\t\t\t\t\t\t\t\t$dayOfMonth: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmonth: {\n\t\t\t\t\t\t\t\t$month: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tyear: {\n\t\t\t\t\t\t\t\t$year: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tgroupSort = {\n\t\t\t\t\t\t\t'_id.year': 1,\n\t\t\t\t\t\t\t'_id.month': 1,\n\t\t\t\t\t\t\t'_id.day': 1,\n\t\t\t\t\t\t\t'_id.hour': 1\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgroupId = {\n\t\t\t\t\t\t\tday: {\n\t\t\t\t\t\t\t\t$dayOfMonth: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tmonth: {\n\t\t\t\t\t\t\t\t$month: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tyear: {\n\t\t\t\t\t\t\t\t$year: {\n\t\t\t\t\t\t\t\t\tdate: '$createdAt',\n\t\t\t\t\t\t\t\t\ttimezone: process.env.TZ_CLIENT || 'America/Chicago'\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tgroupSort = {\n\t\t\t\t\t\t\t'_id.year': 1,\n\t\t\t\t\t\t\t'_id.month': 1,\n\t\t\t\t\t\t\t'_id.day': 1\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tlet methodGraphData = await LogMethodLatencies.aggregate([\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$gte: date_start}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$lte: date_end}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: groupId,\n\t\t\t\t\t\t\t\tcount: {\n\t\t\t\t\t\t\t\t\t$sum: 1\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$sort: groupSort\n\t\t\t\t\t\t}\n\t\t\t\t\t], {allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary'}, true);\n\n\t\t\t\t\tlet subGraphData = await LogSubscriptions.aggregate([\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$gte: date_start}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcreatedAt: {$lte: date_end}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t\t_id: groupId,\n\t\t\t\t\t\t\t\tcount: {\n\t\t\t\t\t\t\t\t\t$sum: 1\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$sort: groupSort\n\t\t\t\t\t\t}\n\t\t\t\t\t], {allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary'}, true);\n\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tmethods: latencies,\n\t\t\t\t\t\tsubscriptions: subscriptions,\n\t\t\t\t\t\tmethodGraphData: methodGraphData,\n\t\t\t\t\t\tsubGraphData: subGraphData\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t},\n\t\t\tskipValidation: true\n\t\t}\n\t});\n}"]}
|
package/package.json
CHANGED
package/server-app.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __awaiter=this&&this.__awaiter||function(e,o,n,s){return new(n=n||Promise)(function(t,r){function fulfilled(e){try{step(s.next(e))}catch(e){r(e)}}function rejected(e){try{step(s.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof n?r:new n(function(e){e(r)})).then(fulfilled,rejected)}step((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var s,i,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function verb(t){return function(e){var r=[t,e];if(s)throw new TypeError("Generator is already executing.");for(;l=u&&r[u=0]?0:l;)try{if(s=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 l.label++,{value:r[1],done:!1};case 5:l.label++,i=r[1],r=[0];continue;case 7:r=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){l=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))l.label=r[1];else if(6===r[0]&&l.label<a[1])l.label=a[1],a=r;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(r)}}r=n.call(o,l)}catch(e){r=[6,e],i=0}finally{s=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,n,s=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(o=s.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var o,n=0,s=r.length;n<s;n++)!o&&n in r||((o=o||Array.prototype.slice.call(r,0,n))[n]=r[n]);return e.concat(o||Array.prototype.slice.call(r))},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],o=0;if(t)return t.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(r?"Object is not iterable.":"Symbol.iterator is not defined.")},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),mongodb_1=require("mongodb"),websocket_manager_1=require("./managers/websocket.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this._runningTasks=[],this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._safeShutdown=!1,this._workers=[],this._taskQueue=[],this._inFlightRequests={},this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction}return ResolveIOMainServer.prototype.initServerApp=function(){var e=this,s=(this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){e._subscriptionManager&&e._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",e._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",e._debugMsgQueue)),e._debugMsgQueue=0,e._debugMsgRecv=0},6e4),!1);setTimeout(function(){s=!0},5e3),process.on("unhandledRejection",function(o,n){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return o&&"MongoError"===o.name&&48===o.code?[2]:o&&"MongoServerError"===o.name&&!s?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[o,n]),r=moment().diff(this._serverStartTime,"seconds"),o&&("MongoNetworkTimeoutError"===o.name||o instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:o.name,message:o.message,stack:o.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return o&&"MongoError"===o.name&&"not master"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return o&&"MongoError"===o.name&&"not master and slaveOk=false"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:o&&"StatusError"!==o.name&&""!==o.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(e,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGTERM",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGQUIT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager,this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager,this.listen())},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,n,s=this;return __generator(this,function(e){return console.log(new Date,"Worker instance started, connecting to main server via WebSocket..."),r=resolveio_server_app_1.ResolveIOServer.getServerConfig().SERVER_URL+"/websocket?workerToken="+resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN,(n=function(){var t=new WebSocket(r),o=null,e=null;t.on("open",function(){console.log(new Date,"Connected to main server as worker",process.env.WORKER_INDEX,process.env.NODE_APP_INSTANCE),s.sendWorkerResponse(t,"ping"),e=setInterval(function(){o?(o=null,s.sendWorkerResponse(t,"ping")):t.close()},15e3)}),t.on("message",function(e){if("ping"===(e="string"!=typeof e?e.toString():e))s.sendWorkerResponse(t,"pong");else if("pong"===e)o=new Date;else{var r=void 0;try{r=JSON.parse(e,common_1.dateReviver)}catch(e){return void console.error("Worker parse error",e)}"task"===r.type&&s.handleIncomingTask(t,r)}}),t.on("close",function(){console.log(new Date,"Disconnected from main server. Reconnecting in 5s..."),setTimeout(n,5e3),e&&clearInterval(e)}),t.on("error",function(e){console.error(new Date,"Worker WS error:",e),t.close()})})(),[2]})})},ResolveIOMainServer.prototype.handleIncomingTask=function(c,_){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s,i,a,l,u=this;return __generator(this,function(e){switch(e.label){case 0:if(r=_.taskId,t=_.method,o=_.params,n=_.userContext,this._runningTasks.push(r),!r||!t)return console.log("Invalid task message received",_),[2];s=!1,i=setTimeout(function(){s=!0,console.error("Worker timed out on task:",r),u.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!0,message:"Task timed out"})},12e4),e.label=1;case 1:return e.trys.push([1,3,,4]),a=Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:(null==n?void 0:n.id_user)||"",user:(null==n?void 0:n.user)||"",id_ws:(null==n?void 0:n.id_ws)||""}),[4,(l=this._methodManager.callMethod).call.apply(l,__spreadArray([a,t],__read(o),!1))];case 2:return l=e.sent(),s||(clearTimeout(i),this.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!1,result:l})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,4];case 3:return a=e.sent(),s||(clearTimeout(i),console.error("Worker failed task:",r,a),this.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!0,message:a.message||"Unknown error"})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,4];case 4:return[2]}})})},ResolveIOMainServer.prototype.sendWorkerResponse=function(e,r){if("string"!=typeof r&&(r=JSON.stringify(r)),e&&e.readyState===e.OPEN)try{e.send(r)}catch(e){console.error("Failed to send worker response:",e)}else e&&e.close()},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length||this._taskQueue.length||this._runningTasks.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):resolveio_server_app_1.ResolveIOServer.getMongoConnection()?resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(s,i){return __awaiter(e,void 0,void 0,function(){var r,t,n=this;return __generator(this,function(e){if(this._rebootFlag)i(!1,409,"Unable To Process");else{if("DEBUG"===this.LOGGER&&console.log("Verify Client",s,i),s.req.url&&s.req.url.includes("workerToken="))return r=s.req.url.split("workerToken="),(r[1]||"")===resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN?i(!0):i(!1,401,"Unauthorized"),[2];r=s.req.headers["sec-websocket-protocol"].split(/,/),(s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(t=r[0])?jwt.verify(t,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,o){return __awaiter(n,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:s.req.id_user=o.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(o.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")}return[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var s=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",s._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",s._portWSS)}),this._serverWSS.on("connection",function(o,e){var r,t,n;e.url&&e.url.includes("workerToken=")?(r=(0,common_1.objectIdHexString)(),o.id_worker=r,s._workers.push({id:r,ws:o,activeTasks:0,maxConcurrency:2}),n=t=null,o.on("open",function(){s.sendWorkerResponse(o,"ping"),t=setInterval(function(){n?(n=null,s.sendWorkerResponse(o,"ping")):o.close()},15e3)}),console.log(new Date,"Worker connected:",r),o.on("message",function(e){"ping"===(e="string"!=typeof e?e.toString():e)?s.sendWorkerResponse(o,"pong"):"pong"===e?n=new Date:s.handleWorkerMessage(r,e)}),o.on("close",function(){console.log(new Date,"Worker disconnected:",r),s._workers=s._workers.filter(function(e){return e.id!==r}),t&&clearInterval(t)}),o.on("error",function(e){console.error("Error on WS Worker",e),o.close()})):(o.id_socket=(0,common_1.objectIdHexString)(),o.id_user=e.id_user,o.user=e.user,o.user_readonly=e.user_readonly,o.doc_user=e.doc_user,s._websocketManager.addWebSocket(o),s._subscriptionManager.createLoggedInUser(o.id_socket).then(function(){setTimeout(function(){o.pingTime=new Date,o.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(o))})},5e3)}),"DEBUG"===s.LOGGER&&console.log("Connection from user: "+e.user),o.isAlive=!0,o.retryCnt=0,o.on("message",function(t){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){this._debugMsgRecv+=1,r=[];try{r=JSON.parse(t,common_1.dateReviver)}catch(e){return console.log("Error - JSON.parse",t),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t,e])),[2]}return this.processSocketMessage(o,r),[2]})})}).on("end",function(){s.unsubscribeWS(o)}).on("close",function(){s.unsubscribeWS(o)}).on("error",function(e){s.unsubscribeWS(o)}))}),setInterval(function(){s._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?s.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(i,a){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s;return __generator(this,function(e){switch(e.label){case 0:if("string"==typeof a&&"ping"===a)return i&&i.readyState===i.OPEN&&i.send("pong"),[2];if("string"==typeof a&&"pong"===a)return i.isAlive=!0,i.pongTime=new Date,i.latency=moment.duration(moment(i.pongTime).diff(i.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(i),[2];if(!Array.isArray(a[0]))return console.log("Invalid message format (expected array of arrays)",a),[2];e.label=1;case 1:e.trys.push([1,6,7,8]),r=__values(a),t=r.next(),e.label=2;case 2:return t.done?[3,5]:(o=t.value,[4,this.handleClientMessage(i,o)]);case 3:e.sent(),e.label=4;case 4:return t=r.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),n={error:o},[3,8];case 7:try{t&&!t.done&&(s=r.return)&&s.call(r)}finally{if(n)throw n.error}return[7];case 8:return[2]}})})},ResolveIOMainServer.prototype.handleClientMessage=function(h,f){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s,i,a,l,u,c,_,g,v,d,p;return __generator(this,function(e){switch(e.label){case 0:return(r=f[0],a=f[1],t=f[2],o=f[3],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||h.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||h.doc_user.roles.super_admin)?"subscription"!==o?[3,1]:(n=f[4],u=f[5],"sub"===n?this._subscriptionManager.subscribe(r,a,h,t,u,f.slice(6)):this._subscriptionManager.unsubscribe(r,a,h,t,u,f.slice(6)),[3,11]):[2];case 1:if(this.publicProgram||"offline"!==o)return[3,10];n={messageId:t,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,n),this._offlineUpdates.push(h),s=f[4],i=0,e.label=2;case 2:if(!(i<s.length))return[3,9];if(a=s[i],l=a.data,l.shift(),l.shift(),u=l.shift(),l.shift(),c=l.shift(),p={messageId:u,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,p),"insertDocument"===c&&"driver-gps"===l[0])return[3,8];if("reportBuilderGetResults"!==c&&"reportBuilderGetDistinctValue"!==c&&"reportBuilderBuildTree"!==c&&"generatePDF"!==c&&"getWOOfflineData"!==c&&"countQuery"!==c&&"countWithQuery"!==c&&"countCollectionWithQuery"!==c&&"find"!==c&&"findOne"!==c&&"findWithOptions"!==c&&"getDrivers"!==c&&"processAirdropDistribution"!==c&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:c,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:c,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r,client:"ResolveIO",instance:"backend.resolveio.com"})),!this._methodManager._methods[c])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(p=this._methodManager.callMethod).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:h.id_user,user:h.user,id_ws:h.id_socket}),c],__read(l),!1))];case 4:return e.sent(),[3,6];case 5:return _=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(_,null,2)),[3,6];case 6:return"updateDocumentOffline"!==c&&"updateDocumentPropsOffline"!==c||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,8];case 7:console.log("Offline - Could not find method: "+c),e.label=8;case 8:return i++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(h.id_socket),1),[3,11];case 10:if(_=__spreadArray([],__read(f),!1),_.shift(),_.shift(),g=_.shift(),"method"===_.shift()){if(v=_.shift(),h.user_readonly)return[2];"reportBuilderGetResults"!==v&&"reportBuilderGetDistinctValue"!==v&&"reportBuilderBuildTree"!==v&&"generatePDF"!==v&&"getWOOfflineData"!==v&&"countQuery"!==v&&"countWithQuery"!==v&&"countCollectionWithQuery"!==v&&"find"!==v&&"findOne"!==v&&"findWithOptions"!==v&&"getDrivers"!==v&&"processAirdropDistribution"!==v&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(_))<2e5?JSON.stringify(_,null,2):"Too Big",method:v,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(_))<2e5?JSON.stringify(_,null,2):"Too Big",method:v,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r,client:"ResolveIO",instance:"backend.resolveio.com"})),d={messageId:g,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,d),d=this.findAvailableWorker(),this._isWorkersEnabled&&d&&"find"!==v&&"insertDocument"!==v&&"countWithQuery"!==v&&"findOne"!==v&&"updateDocumentProps"!==v&&"findWithOptions"!==v&&"updateDocument"!==v&&"insertErrorLog"!==v&&"removeDocument"!==v&&"supportCreateBillingUser"!==v&&"getSignedUrl"!==v&&"getSignedUrls"!==v&&"getSignedUrlWithId"!==v&&"incorrectUser"!==v&&"reloadWS"!==v&&"reconnectWS"!==v&&"disconnectWS"!==v?(d="task-"+(0,common_1.objectIdHexString)(),this._inFlightRequests[d]={ws:h,messageId:g,method:v},this.queueTask(d,v,_,{id_user:h.id_user,user:h.user,id_ws:h.id_socket})):this.callMethodLocally(h,g,v,_)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.callMethodLocally=function(n,s,i,a){return __awaiter(this,void 0,void 0,function(){var r,t,o;return __generator(this,function(e){switch(e.label){case 0:r={messageId:s,hasError:!1,data:null},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(o=this._methodManager.callMethod).call.apply(o,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket}),i],__read(a),!1))];case 2:return o=e.sent(),r.data=o,[3,4];case 3:return t=e.sent(),r.hasError=!0,r.data=t.message||"Unknown error",[3,4];case 4:return n&&n.readyState===n.OPEN&&this._websocketManager.send(n,r),[2]}})})},ResolveIOMainServer.prototype.queueTask=function(e,r,t,o){this._taskQueue.push({taskId:e,method:r,params:t,userContext:o}),this.dispatchQueue()},ResolveIOMainServer.prototype.dispatchQueue=function(){if(this._taskQueue.length)for(var e=0;e<9999;e++){var r=this._taskQueue[0];if(!r)break;var t=this.findAvailableWorker();if(!t)break;this._taskQueue.shift(),this.assignTaskToWorker(t,r)}},ResolveIOMainServer.prototype.findAvailableWorker=function(){var e=this._workers.filter(function(e){return e.activeTasks<e.maxConcurrency});return e.length?(e.sort(function(e,r){return e.activeTasks-r.activeTasks}),e[0]):null},ResolveIOMainServer.prototype.assignTaskToWorker=function(r,t){r.activeTasks++;var e={type:"task",taskId:t.taskId,method:t.method,params:t.params,userContext:t.userContext};try{r.ws.send(JSON.stringify(e))}catch(e){console.error("Failed to send task to worker:",e),r.activeTasks=Math.max(0,r.activeTasks-1),this._taskQueue.unshift(t)}},ResolveIOMainServer.prototype.handleWorkerMessage=function(r,t){var e,o,n,s;try{s=JSON.parse(t,common_1.dateReviver)}catch(e){return void console.error("Failed to parse worker message:",t)}"taskComplete"===s.type&&((t=this._workers.find(function(e){return e.id===r}))?(t.activeTasks=Math.max(0,t.activeTasks-1),t=s.taskId,e=s.error,o=s.message,s=s.result,(n=this._inFlightRequests[t])?(delete this._inFlightRequests[t],s={messageId:n.messageId,hasError:!1,data:s},e&&(s.hasError=!0,s.data=o),n.ws&&n.ws.readyState===n.ws.OPEN&&this._websocketManager.send(n.ws,s)):console.error("No in-flight request found for task:",t),this.dispatchQueue()):console.error("Unknown worker for taskComplete:",r))},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager&&this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
|
|
1
|
+
"use strict";var __awaiter=this&&this.__awaiter||function(e,o,n,s){return new(n=n||Promise)(function(t,r){function fulfilled(e){try{step(s.next(e))}catch(e){r(e)}}function rejected(e){try{step(s.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof n?r:new n(function(e){e(r)})).then(fulfilled,rejected)}step((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var s,i,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function verb(t){return function(e){var r=[t,e];if(s)throw new TypeError("Generator is already executing.");for(;l=u&&r[u=0]?0:l;)try{if(s=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 l.label++,{value:r[1],done:!1};case 5:l.label++,i=r[1],r=[0];continue;case 7:r=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){l=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))l.label=r[1];else if(6===r[0]&&l.label<a[1])l.label=a[1],a=r;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(r)}}r=n.call(o,l)}catch(e){r=[6,e],i=0}finally{s=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,n,s=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(o=s.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var o,n=0,s=r.length;n<s;n++)!o&&n in r||((o=o||Array.prototype.slice.call(r,0,n))[n]=r[n]);return e.concat(o||Array.prototype.slice.call(r))},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],o=0;if(t)return t.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(r?"Object is not iterable.":"Symbol.iterator is not defined.")},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),mongodb_1=require("mongodb"),websocket_manager_1=require("./managers/websocket.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this._runningTasks=[],this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._safeShutdown=!1,this._workers=[],this._taskQueue=[],this._inFlightRequests={},this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction}return ResolveIOMainServer.prototype.initServerApp=function(){var e=this,s=(this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){e._subscriptionManager&&e._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",e._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",e._debugMsgQueue)),e._debugMsgQueue=0,e._debugMsgRecv=0},6e4),!1);setTimeout(function(){s=!0},5e3),process.on("unhandledRejection",function(o,n){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return o&&"MongoError"===o.name&&48===o.code?[2]:o&&"MongoServerError"===o.name&&!s?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[o,n]),r=moment().diff(this._serverStartTime,"seconds"),o&&("MongoNetworkTimeoutError"===o.name||o instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:o.name,message:o.message,stack:o.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return o&&"MongoError"===o.name&&"not master"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return o&&"MongoError"===o.name&&"not master and slaveOk=false"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:o&&"StatusError"!==o.name&&""!==o.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(e,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGTERM",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGQUIT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager,this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager,this.listen())},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,n,s=this;return __generator(this,function(e){return console.log(new Date,"Worker instance started, connecting to main server via WebSocket..."),r=resolveio_server_app_1.ResolveIOServer.getServerConfig().SERVER_URL+"/websocket?workerToken="+resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN,(n=function(){var t=new WebSocket(r),o=null,e=null;t.on("open",function(){console.log(new Date,"Connected to main server as worker",process.env.WORKER_INDEX,process.env.NODE_APP_INSTANCE),s.sendWorkerResponse(t,"ping"),e=setInterval(function(){o?(o=null,s.sendWorkerResponse(t,"ping")):t.close()},15e3)}),t.on("message",function(e){if("ping"===(e="string"!=typeof e?e.toString():e))s.sendWorkerResponse(t,"pong");else if("pong"===e)o=new Date;else{var r=void 0;try{r=JSON.parse(e,common_1.dateReviver)}catch(e){return void console.error("Worker parse error",e)}"task"===r.type&&s.handleIncomingTask(t,r)}}),t.on("close",function(){console.log(new Date,"Disconnected from main server. Reconnecting in 5s..."),setTimeout(n,5e3),e&&clearInterval(e)}),t.on("error",function(e){console.error(new Date,"Worker WS error:",e),t.close()})})(),[2]})})},ResolveIOMainServer.prototype.handleIncomingTask=function(c,_){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s,i,a,l,u=this;return __generator(this,function(e){switch(e.label){case 0:if(r=_.taskId,t=_.method,o=_.params,n=_.userContext,this._runningTasks.push(r),!r||!t)return console.log("Invalid task message received",_),[2];s=!1,i=setTimeout(function(){s=!0,console.error("Worker timed out on task:",r),u.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!0,message:"Task timed out"})},12e4),e.label=1;case 1:return e.trys.push([1,3,,4]),a=Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:(null==n?void 0:n.id_user)||"",user:(null==n?void 0:n.user)||"",id_ws:(null==n?void 0:n.id_ws)||""}),[4,(l=this._methodManager.callMethod).call.apply(l,__spreadArray([a,t],__read(o),!1))];case 2:return l=e.sent(),s||(clearTimeout(i),this.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!1,result:l})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,4];case 3:return a=e.sent(),s||(clearTimeout(i),console.error("Worker failed task:",r,a),this.sendWorkerResponse(c,{type:"taskComplete",taskId:r,error:!0,message:a.message||"Unknown error"})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,4];case 4:return[2]}})})},ResolveIOMainServer.prototype.sendWorkerResponse=function(e,r){if("string"!=typeof r&&(r=JSON.stringify(r)),e&&e.readyState===e.OPEN)try{e.send(r)}catch(e){console.error("Failed to send worker response:",e)}else e&&e.close()},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length||this._taskQueue.length||this._runningTasks.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):resolveio_server_app_1.ResolveIOServer.getMongoConnection()?resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(s,i){return __awaiter(e,void 0,void 0,function(){var r,t,n=this;return __generator(this,function(e){if(this._rebootFlag)i(!1,409,"Unable To Process");else{if("DEBUG"===this.LOGGER&&console.log("Verify Client",s,i),s.req.url&&s.req.url.includes("workerToken="))return r=s.req.url.split("workerToken="),(r[1]||"")===resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN?i(!0):i(!1,401,"Unauthorized"),[2];r=s.req.headers["sec-websocket-protocol"].split(/,/),(s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(t=r[0])?jwt.verify(t,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,o){return __awaiter(n,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:s.req.id_user=o.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(o.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")}return[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var s=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",s._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",s._portWSS)}),this._serverWSS.on("connection",function(o,e){var r,t,n;e.url&&e.url.includes("workerToken=")?(r=(0,common_1.objectIdHexString)(),o.id_worker=r,s._workers.push({id:r,ws:o,activeTasks:0,maxConcurrency:2}),n=t=null,o.on("open",function(){s.sendWorkerResponse(o,"ping"),t=setInterval(function(){n?(n=null,s.sendWorkerResponse(o,"ping")):o.close()},15e3)}),console.log(new Date,"Worker connected:",r),o.on("message",function(e){"ping"===(e="string"!=typeof e?e.toString():e)?s.sendWorkerResponse(o,"pong"):"pong"===e?n=new Date:s.handleWorkerMessage(r,e)}),o.on("close",function(){console.log(new Date,"Worker disconnected:",r),s._workers=s._workers.filter(function(e){return e.id!==r}),t&&clearInterval(t)}),o.on("error",function(e){console.error("Error on WS Worker",e),o.close()})):(o.id_socket=(0,common_1.objectIdHexString)(),o.id_user=e.id_user,o.user=e.user,o.user_readonly=e.user_readonly,o.doc_user=e.doc_user,s._websocketManager.addWebSocket(o),s._subscriptionManager.createLoggedInUser(o.id_socket).then(function(){setTimeout(function(){o.pingTime=new Date,o.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(o))})},5e3)}),"DEBUG"===s.LOGGER&&console.log("Connection from user: "+e.user),o.isAlive=!0,o.retryCnt=0,o.on("message",function(t){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){this._debugMsgRecv+=1,r=[];try{r=JSON.parse(t,common_1.dateReviver)}catch(e){return console.log("Error - JSON.parse",t),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t,e])),[2]}return this.processSocketMessage(o,r),[2]})})}).on("end",function(){s.unsubscribeWS(o)}).on("close",function(){s.unsubscribeWS(o)}).on("error",function(e){s.unsubscribeWS(o)}))}),setInterval(function(){s._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?s.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(s._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),s.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(i,a){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s;return __generator(this,function(e){switch(e.label){case 0:if("string"==typeof a&&"ping"===a)return i&&i.readyState===i.OPEN&&i.send("pong"),[2];if("string"==typeof a&&"pong"===a)return i.isAlive=!0,i.pongTime=new Date,i.latency=moment.duration(moment(i.pongTime).diff(i.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(i),[2];if(!Array.isArray(a[0]))return console.log("Invalid message format (expected array of arrays)",a),[2];e.label=1;case 1:e.trys.push([1,6,7,8]),r=__values(a),t=r.next(),e.label=2;case 2:return t.done?[3,5]:(o=t.value,[4,this.handleClientMessage(i,o)]);case 3:e.sent(),e.label=4;case 4:return t=r.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),n={error:o},[3,8];case 7:try{t&&!t.done&&(s=r.return)&&s.call(r)}finally{if(n)throw n.error}return[7];case 8:return[2]}})})},ResolveIOMainServer.prototype.handleClientMessage=function(h,f){return __awaiter(this,void 0,void 0,function(){var r,t,o,n,s,i,a,l,u,c,_,g,v,d,p;return __generator(this,function(e){switch(e.label){case 0:return(r=f[0],a=f[1],t=f[2],o=f[3],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||h.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||h.doc_user.roles.super_admin)?"subscription"!==o?[3,1]:(n=f[4],u=f[5],"sub"===n?this._subscriptionManager.subscribe(r,a,h,t,u,f.slice(6)):this._subscriptionManager.unsubscribe(r,a,h,t,u,f.slice(6)),[3,11]):[2];case 1:if(this.publicProgram||"offline"!==o)return[3,10];n={messageId:t,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,n),this._offlineUpdates.push(h),s=f[4],i=0,e.label=2;case 2:if(!(i<s.length))return[3,9];if(a=s[i],l=a.data,l.shift(),l.shift(),u=l.shift(),l.shift(),c=l.shift(),p={messageId:u,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,p),"insertDocument"===c&&"driver-gps"===l[0])return[3,8];if("reportBuilderGetResults"!==c&&"reportBuilderGetDistinctValue"!==c&&"reportBuilderBuildTree"!==c&&"generatePDF"!==c&&"getWOOfflineData"!==c&&"countQuery"!==c&&"countWithQuery"!==c&&"countCollectionWithQuery"!==c&&"find"!==c&&"findOne"!==c&&"findWithOptions"!==c&&"getDrivers"!==c&&"processAirdropDistribution"!==c&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:c,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(l))<2e5?JSON.stringify(l,null,2):"Too Big",method:c,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r,client:"ResolveIO",instance:"backend.resolveio.com"})),!this._methodManager._methods[c])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(p=this._methodManager.callMethod).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:h.id_user,user:h.user,id_ws:h.id_socket}),c],__read(l),!1))];case 4:return e.sent(),[3,6];case 5:return _=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(_,null,2)),[3,6];case 6:return"updateDocumentOffline"!==c&&"updateDocumentPropsOffline"!==c||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,8];case 7:console.log("Offline - Could not find method: "+c),e.label=8;case 8:return i++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(h.id_socket),1),[3,11];case 10:if(_=__spreadArray([],__read(f),!1),_.shift(),_.shift(),g=_.shift(),"method"===_.shift()){if(v=_.shift(),h.user_readonly)return[2];"reportBuilderGetResults"!==v&&"reportBuilderGetDistinctValue"!==v&&"reportBuilderBuildTree"!==v&&"generatePDF"!==v&&"getWOOfflineData"!==v&&"countQuery"!==v&&"countWithQuery"!==v&&"countCollectionWithQuery"!==v&&"find"!==v&&"findOne"!==v&&"findWithOptions"!==v&&"getDrivers"!==v&&"processAirdropDistribution"!==v&&("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(_))<2e5?JSON.stringify(_,null,2):"Too Big",method:v,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r}}):log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(_))<2e5?JSON.stringify(_,null,2):"Too Big",method:v,id_user:h.id_user||"",user:h.user||"",messageId:t,route:r,client:"ResolveIO",instance:"backend.resolveio.com"})),d={messageId:g,hasError:!1,data:"ACK"},h&&h.readyState===h.OPEN&&this._websocketManager.send(h,d),d=this.findAvailableWorker(),this._isWorkersEnabled&&d&&"find"!==v&&"insertDocument"!==v&&"countWithQuery"!==v&&"findOne"!==v&&"updateDocumentProps"!==v&&"findWithOptions"!==v&&"updateDocument"!==v&&"insertErrorLog"!==v&&"removeDocument"!==v&&"supportCreateBillingUser"!==v&&"getSignedUrl"!==v&&"getSignedUrls"!==v&&"getSignedUrlWithId"!==v&&"incorrectUser"!==v&&"reloadWS"!==v&&"reconnectWS"!==v&&"disconnectWS"!==v?(d="task-"+(0,common_1.objectIdHexString)(),this._inFlightRequests[d]={ws:h,messageId:g,method:v},this.queueTask(d,v,_,{id_user:h.id_user,user:h.user,id_ws:h.id_socket})):this.callMethodLocally(h,g,v,_)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.callMethodLocally=function(n,s,i,a){return __awaiter(this,void 0,void 0,function(){var r,t,o;return __generator(this,function(e){switch(e.label){case 0:r={messageId:s,hasError:!1,data:null},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(o=this._methodManager.callMethod).call.apply(o,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket}),i],__read(a),!1))];case 2:return o=e.sent(),r.data=o,[3,4];case 3:return t=e.sent(),r.hasError=!0,r.data=t.message||"Unknown error",[3,4];case 4:return n&&n.readyState===n.OPEN&&this._websocketManager.send(n,r),[2]}})})},ResolveIOMainServer.prototype.queueTask=function(e,r,t,o){this._taskQueue.push({taskId:e,method:r,params:t,userContext:o}),this.dispatchQueue()},ResolveIOMainServer.prototype.dispatchQueue=function(){if(this._taskQueue.length)for(var e=0;e<9999;e++){var r=this._taskQueue[0];if(!r)break;var t=this.findAvailableWorker();if(!t)break;this._taskQueue.shift(),this.assignTaskToWorker(t,r)}},ResolveIOMainServer.prototype.findAvailableWorker=function(){var e=this._workers.filter(function(e){return e.activeTasks<e.maxConcurrency});return e.length?(e.sort(function(e,r){return e.activeTasks-r.activeTasks}),e[0]):null},ResolveIOMainServer.prototype.assignTaskToWorker=function(r,t){r.activeTasks++;var e={type:"task",taskId:t.taskId,method:t.method,params:t.params,userContext:t.userContext};try{r.ws.send(JSON.stringify(e))}catch(e){console.error("Failed to send task to worker:",e),r.activeTasks=Math.max(0,r.activeTasks-1),this._taskQueue.unshift(t)}},ResolveIOMainServer.prototype.handleWorkerMessage=function(r,t){var e,o,n,s;try{s=JSON.parse(t,common_1.dateReviver)}catch(e){return void console.error("Failed to parse worker message:",t)}"taskComplete"===s.type&&((t=this._workers.find(function(e){return e.id===r}))?(t.activeTasks=Math.max(0,t.activeTasks-1),t=s.taskId,e=s.error,o=s.message,s=s.result,(n=this._inFlightRequests[t])?(delete this._inFlightRequests[t],s={messageId:n.messageId,hasError:!1,data:s},e&&(s.hasError=!0,s.data=o),n.ws&&n.ws.readyState===n.ws.OPEN&&this._websocketManager.send(n.ws,s)):console.error("No in-flight request found for task:",t),this.dispatchQueue()):console.error("Unknown worker for taskComplete:",r))},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager&&this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
|
|
2
2
|
//# sourceMappingURL=server-app.js.map
|