@resolveio/server-lib 20.7.20 → 20.7.22
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.map +1 -1
- package/managers/monitor.manager.js.map +1 -1
- package/package.json +1 -1
- package/resolveio-server-app.js +1 -1
- package/resolveio-server-app.js.map +1 -1
- package/server-app.d.ts +2 -2
- package/server-app.js +1 -1
- package/server-app.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/managers/monitor.manager.ts"],"names":["axios_1","require","monitor_cpu_collection_1","monitor_function_collection_1","monitor_memory_collection_1","monitor_mongo_collection_1","resolveio_server_app_1","common_1","os","MAX_BATCH_SIZE","MonitorManager","this","_instanceHostname","_monitorData","create","monitorManager","initialize","_a","sent","prototype","hostname","replace","setupIntervals","setupEventLoop","cpuAverage","totalIdle","totalTick","cpus","i","len","length","type","cpu","times","idle","total","ResolveIOServer","getServerConfig","default","get","instanceId_1","_b","setInterval","__awaiter","_this","post","id_aws_instance","data","version","process","env","APP_VERSION","toString","version_key","APP_VERSION_KEY","lastCPU","now","Date","endMeasure","idleDifference","totalDifference","percentageCPU","MonitorCPUs","_id","objectIdHexString","metadata","instance","client","date","app","system","loadavg","pushMonitorData","memUsage","memoryUsage","MonitorMemorys","physical_total","heapTotal","physical_used","heapUsed","physical_free","freemem","virtual","rss","private","external","physical","totalmem","addMongoTracker","collection","startsWith","MonitorMongos","method","doc_collection","duration","query","Buffer","byteLength","addFunctionTracker","JSON","stringify","MonitorFunctions","startTime","functionType","name","functionName","user","push","estimateBatchSize","flushMonitorData","reduce","item","batch","batchSize","shift","itemSize","unshift","getLocalLogManager","writeLogs","error","console","MonitorMongo","exports","_startTime","_method","_collection","_query","monitorMongo","finish","endTime","mongoMonitor","getMainServer","getMonitorManager","MonitorManagerFunction","_functionCnt","_functions","_functionLastCompletedWS","monitorManagerFunction","startMonitorFunction","id_socket","newMonitorFunction","MonitorFunction","id","finishMonitorFunction","monitor","find","a","_functionLastCompleted","splice","map","indexOf","getActiveMonitorFunctions","getLastCompletedMonitorFunction","getLastCompletedMonitorFunctionWS","_timer","lastTime","monitorFunction","diff","getTime","clearInterval"],"mappings":"k8CAAAA,S,iKAAAC,QAAA,OAAA,GACAC,yBAAAD,QAAA,uCAAA,EACAE,8BAAAF,QAAA,4CAAA,EACAG,4BAAAH,QAAA,0CAAA,EACAI,2BAAAJ,QAAA,yCAAA,EACAK,uBAAAL,QAAA,yBAAA,EACAM,SAAAN,QAAA,gBAAA,EAGMO,GAAKP,QAAQ,IAAI,EACjBQ,eAAiB,QAEvBC,eAAA,WAIC,SAAAA,iBAHQC,KAAAC,kBAAoB,GACpBD,KAAAE,aAAgC,EAEzB,CA+RhB,OA7RcH,eAAAI,OAAb,W,gHAEC,MAAA,CAAA,GADMC,EAAiB,IAAIL,gBACNM,WAAU,G,OAC/B,OADAC,EAAAC,KAAA,EACA,CAAA,EAAOH,E,OAGML,eAAAS,UAAAH,WAAd,W,0GAGC,OAFAL,KAAKC,kBAAoBJ,GAAGY,SAAQ,EAAGC,QAAQ,MAAO,GAAG,EAEzD,CAAA,EAAMV,KAAKW,eAAc,G,cAAzBL,EAAAC,KAAA,EACAP,KAAKY,eAAc,E,UAGpBb,eAAAS,UAAAK,WAAA,WAIC,IAHA,IAAIC,EAAY,EAAGC,EAAY,EAC3BC,EAAOnB,GAAGmB,KAAI,EAETC,EAAI,EAAGC,EAAMF,EAAKG,OAAQF,EAAIC,EAAKD,CAAC,GAAI,CAChD,IAESG,EAFLC,EAAML,EAAKC,GAEf,IAASG,KAAQC,EAAIC,MACpBP,GAAaM,EAAIC,MAAMF,GAExBN,GAAaO,EAAIC,MAAMC,I,CAGxB,MAAO,CACNA,KAAMT,EAAYE,EAAKG,OACvBK,MAAOT,EAAYC,EAAKG,M,CAE1B,EAEMpB,eAAAS,UAAAG,eAAN,W,4HA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1B/I,KAAAmF,SAAW,EAKXnF,KAAA2F,UAAkB,KAClB3F,KAAAsH,QAAgB,KAChBtH,KAAAgJ,SAAiB,KACjBhJ,KAAAgI,UAAY,GACZhI,KAAAmI,GAAK,CAEG,CAyDhB,OAvDQD,gBAAA/H,OAAP,SACCgI,EACAvC,EACAE,EACAC,EACAiC,EACA5F,GAEA,IAAM6G,EAAkB,IAAIf,gBAE5B,OADAe,EAAgB5I,WAAW8H,EAAIvC,EAAcE,EAAcC,EAAMiC,EAAW5F,CAAI,EACzE6G,CACR,EAEQf,gBAAA1H,UAAAH,WAAR,SACC8H,EACAvC,EACAE,EACAC,EACAiC,EACA5F,GAND,IAAAH,EAAAjC,KAQCA,KAAKmI,GAAKA,EACVnI,KAAK2F,UAAY,IAAI7C,KACrB9C,KAAK4F,aAAeA,EACpB5F,KAAK8F,aAAeA,EACpB9F,KAAK+F,KAAOA,EACZ/F,KAAKgI,UAAYA,EACjBhI,KAAKoC,KAAOA,EACZpC,KAAKgJ,SAAW,IAAIlG,KAEpB9C,KAAK+I,OAAShH,YAAY,WACzB,IAAImH,EAAOpG,KAAKD,IAAG,EAAKZ,EAAK+G,SAASG,QAAO,EAEzCD,EAAOjH,EAAKkD,WACflD,EAAKkD,SAAW+D,GAGjBjH,EAAK+G,SAAW,IAAIlG,IACrB,EAAG,GAAI,CACR,EAEaoF,gBAAA1H,UAAA6G,OAAb,W,0GAYC,OAXIrH,KAAK+I,SACRK,cAAcpJ,KAAK+I,MAAM,EACzB/I,KAAK+I,OAAS,MAGf/I,KAAKsH,QAAU,IAAIxE,KAEf9C,KAAKmF,SAIT,CAAA,EAAMxF,uBAAA8B,gBAAgB+F,cAAa,EAAGC,kBAAiB,EAAGlC,mBAAmBvF,IAAI,G,cAAjFM,EAAAC,KAAA,E,UAEF2H,eAAA,EAAC,GAtEYnB,QAAAmB,gBAAAA","file":"monitor.manager.js","sourcesContent":["import axios from 'axios';\nimport { MonitorCPUs } from '../collections/monitor-cpu.collection';\nimport { MonitorFunctions } from '../collections/monitor-function.collection';\nimport { MonitorMemorys } from '../collections/monitor-memory.collection';\nimport { MonitorMongos } from '../collections/monitor-mongo.collection';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { objectIdHexString } from '../util/common';\nimport { LocalLogModel } from './local-log.manager';\n\nconst os = require('os');\nconst MAX_BATCH_SIZE = 8 * 1024 * 1024; // 8MB max for safety\n\nexport class MonitorManager {\n\tprivate _instanceHostname = '';\n\tprivate _monitorData: LocalLogModel[] = [];\n\n\tconstructor() {}\n\n\tstatic async create() {\n\t\tconst monitorManager = new MonitorManager();\n\t\tawait monitorManager.initialize();\n\t\treturn monitorManager;\n\t}\n\n\tprivate async initialize() {\n\t\tthis._instanceHostname = os.hostname().replace(/\\./g, '-');\n\n\t\tawait this.setupIntervals();\n\t\tthis.setupEventLoop();\n\t}\n\n\tcpuAverage() {\n\t\tvar totalIdle = 0, totalTick = 0;\n\t\tvar cpus = os.cpus();\n\n\t\tfor (var i = 0, len = cpus.length; i < len; i++) {\n\t\t\tvar cpu = cpus[i];\n\n\t\t\tfor (let type in cpu.times) {\n\t\t\t\ttotalTick += cpu.times[type];\n\t\t\t}\n\t\t\ttotalIdle += cpu.times.idle;\n\t\t}\n\n\t\treturn {\n\t\t\tidle: totalIdle / cpus.length,\n\t\t\ttotal: totalTick / cpus.length\n\t\t};\n\t}\n\n\tasync setupIntervals() {\n\t\t// Example: If not on production or localhost, do a health check\n\t\tif (\n\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t) {\n\t\t\ttry {\n\t\t\t\tlet instanceId = await axios.get('http://169.254.169.254/latest/meta-data/instance-id');\n\n\t\t\t\tsetInterval(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait axios.post('https://backend.resolveio.com/api/health', {\n\t\t\t\t\t\t\ttype: 'application',\n\t\t\t\t\t\t\tid_aws_instance: instanceId.data,\n\t\t\t\t\t\t\tversion: typeof process.env.APP_VERSION === 'number'\n\t\t\t\t\t\t\t\t? (<any>process.env.APP_VERSION).toString()\n\t\t\t\t\t\t\t\t: process.env.APP_VERSION,\n\t\t\t\t\t\t\tversion_key: process.env.APP_VERSION_KEY\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tcatch {}\n\t\t\t\t}, 10000);\n\t\t\t}\n\t\t\tcatch {}\n\t\t}\n\n\t\tlet lastCPU = this.cpuAverage();\n\n\t\tsetInterval(async () => {\n\t\t\tlet now = new Date();\n\t\t\tvar endMeasure = this.cpuAverage();\n\t\t\tvar idleDifference = endMeasure.idle - lastCPU.idle;\n\t\t\tvar totalDifference = endMeasure.total - lastCPU.total;\n\t\t\tvar percentageCPU = 1 - idleDifference / totalDifference;\n\n\t\t\t// Original local code\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'https://resolveio.com'\n\t\t\t|| ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tawait MonitorCPUs.create({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t},\n\t\t\t\t\tdate: now,\n\t\t\t\t\tapp: percentageCPU,\n\t\t\t\t\tsystem: os.loadavg()[0]\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.pushMonitorData({\n\t\t\t\t\ttype: 'monitor-cpu',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdate: now,\n\t\t\t\t\t\tapp: percentageCPU,\n\t\t\t\t\t\tsystem: os.loadavg()[0]\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlastCPU = endMeasure;\n\n\t\t\tconst memUsage = process.memoryUsage();\n\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'https://resolveio.com'\n\t\t\t|| ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tawait MonitorMemorys.create({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t},\n\t\t\t\t\tdate: now,\n\t\t\t\t\tphysical_total: memUsage.heapTotal,\n\t\t\t\t\tphysical_used: memUsage.heapUsed,\n\t\t\t\t\tphysical_free: os.freemem(),\n\t\t\t\t\tvirtual: memUsage.rss,\n\t\t\t\t\tprivate: memUsage.external,\n\t\t\t\t\tphysical: os.totalmem()\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.pushMonitorData({\n\t\t\t\t\ttype: 'monitor-memory',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdate: now,\n\t\t\t\t\t\tphysical_total: memUsage.heapTotal,\n\t\t\t\t\t\tphysical_used: memUsage.heapUsed,\n\t\t\t\t\t\tphysical_free: os.freemem(),\n\t\t\t\t\t\tvirtual: memUsage.rss,\n\t\t\t\t\t\tprivate: memUsage.external,\n\t\t\t\t\t\tphysical: os.totalmem(),\n\t\t\t\t\t\ttype: 'memory'\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}, 3000);\n\t}\n\n\tasync addMongoTracker(data: MongoMonitorModel) {\n\t\tif (\n\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'https://resolveio.com'\n\t\t\t|| ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200'\n\t\t) {\n\t\t\tif (!data.collection.startsWith('monitor-')) {\n\t\t\t\tawait MonitorMongos.create({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t},\n\t\t\t\t\tdate: new Date(data.date),\n\t\t\t\t\tmethod: data.method,\n\t\t\t\t\tdoc_collection: data.collection,\n\t\t\t\t\tduration: data.duration,\n\t\t\t\t\tquery: Buffer.byteLength(data.query, 'utf8') < 15800000\n\t\t\t\t\t\t? data.query\n\t\t\t\t\t\t: 'Too Big'\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (this._instanceHostname) {\n\t\t\t\tthis.pushMonitorData({\n\t\t\t\t\ttype: 'monitor-mongo',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdate: new Date(data.date),\n\t\t\t\t\t\tmethod: data.method,\n\t\t\t\t\t\tdoc_collection: data.collection,\n\t\t\t\t\t\tduration: data.duration,\n\t\t\t\t\t\tquery: Buffer.byteLength(data.query, 'utf8') < 15800000\n\t\t\t\t\t\t\t? data.query\n\t\t\t\t\t\t\t: 'Too Big'\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tasync addFunctionTracker(data: MonitorFunction) {\n\t\tif (typeof(data.data) !== 'string') {\n\t\t\tdata.data = JSON.stringify(data.data);\n\t\t}\n\n\t\tif (\n\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'https://resolveio.com'\n\t\t\t|| ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200'\n\t\t) {\n\t\t\tawait MonitorFunctions.create({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\tmetadata: {\n\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t},\n\t\t\t\tdate: new Date(data.startTime),\n\t\t\t\ttype: data.functionType,\n\t\t\t\tname: data.functionName,\n\t\t\t\tuser: data.user,\n\t\t\t\tduration: data.duration,\n\t\t\t\tdata: Buffer.byteLength(data.data, 'utf8') < 15800000\n\t\t\t\t\t? data.data\n\t\t\t\t\t: 'Too Big'\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tif (this._instanceHostname) {\n\t\t\t\tthis.pushMonitorData({\n\t\t\t\t\ttype: 'monitor-function',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdate: new Date(data.startTime),\n\t\t\t\t\t\ttype: data.functionType,\n\t\t\t\t\t\tname: data.functionName,\n\t\t\t\t\t\tuser: data.user,\n\t\t\t\t\t\tduration: data.duration,\n\t\t\t\t\t\tdata: Buffer.byteLength(data.data, 'utf8') < 15800000\n\t\t\t\t\t\t\t? data.data\n\t\t\t\t\t\t\t: 'Too Big'\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate pushMonitorData(data: LocalLogModel) {\n\t\tthis._monitorData.push(data);\n\n\t\t// If data is huge, flush immediately to file\n\t\tif (this.estimateBatchSize() >= MAX_BATCH_SIZE) {\n\t\t\tthis.flushMonitorData();\n\t\t}\n\t}\n\n\tprivate estimateBatchSize(): number {\n\t\treturn this._monitorData.reduce((total, item) => {\n\t\t\treturn total + Buffer.byteLength(JSON.stringify(item));\n\t\t}, 0);\n\t}\n\n\tsetupEventLoop() {\n\t\t// Flush every 2.5 seconds\n\t\tsetInterval(() => {\n\t\t\tif (this._monitorData.length > 0) {\n\t\t\t\tthis.flushMonitorData();\n\t\t\t}\n\t\t}, 2500);\n\t}\n\n\tprivate flushMonitorData() {\n\t\tconst batch = [];\n\t\tlet batchSize = 0;\n\n\t\twhile (this._monitorData.length > 0 && batchSize < MAX_BATCH_SIZE) {\n\t\t\tconst item = this._monitorData.shift();\n\t\t\tconst itemSize = Buffer.byteLength(JSON.stringify(item));\n\n\t\t\tif ((batchSize + itemSize) > MAX_BATCH_SIZE && batch.length > 0) {\n\t\t\t\t// put the item back for next round\n\t\t\t\tthis._monitorData.unshift(item);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tbatch.push(item);\n\t\t\tbatchSize += itemSize;\n\t\t}\n\n\t\ttry {\n\t\t\t// Now, instead of calling an external HTTP endpoint, we write the batch to disk:\n\t\t\tResolveIOServer.getLocalLogManager().writeLogs(batch);\n\t\t}\n\t\tcatch (error) {\n\t\t\tconsole.error(new Date(), 'MonitorManager', 'Failed to flush monitor data to file:', error);\n\t\t}\n\t}\n}\n\nexport interface MongoMonitorModel {\n\tdate: Date;\n\tmethod: string;\n\tcollection: string;\n\tduration: number;\n\tquery: string;\n}\n\nexport class MonitorMongo {\n\tprivate _startTime = 0;\n\tprivate _method = '';\n\tprivate _collection = '';\n\tprivate _query = '';\n\n\tconstructor() {}\n\n\tstatic create(method: string, collection: string, query: string) {\n\t\tconst monitorMongo = new MonitorMongo();\n\t\tmonitorMongo.initialize(method, collection, query);\n\t\treturn monitorMongo;\n\t}\n\n\tprivate initialize(method: string, collection: string, query: string) {\n\t\tthis._startTime = Date.now();\n\t\tthis._method = method;\n\t\tthis._collection = collection;\n\t\tthis._query = query;\n\t}\n\n\tpublic async finish() {\n\t\tlet endTime = Date.now();\n\n\t\tlet mongoMonitor: MongoMonitorModel = {\n\t\t\tdate: new Date(endTime),\n\t\t\tmethod: this._method,\n\t\t\tcollection: this._collection,\n\t\t\tquery: this._query,\n\t\t\tduration: endTime - this._startTime\n\t\t};\n\n\t\tawait ResolveIOServer.getMainServer().getMonitorManager().addMongoTracker(mongoMonitor);\n\t}\n}\n\nexport class MonitorManagerFunction {\n\tprivate _functionCnt = 0;\n\tprivate _functions: MonitorFunction[] = [];\n\tprivate _functionLastCompletedWS: { [id_socket: string]: MonitorFunction; } = {};\n\tprivate _functionLastCompleted: MonitorFunction;\n\n\tconstructor() {}\n\n\tstatic create() {\n\t\tconst monitorManagerFunction = new MonitorManagerFunction();\n\t\tmonitorManagerFunction.initialize();\n\t\treturn monitorManagerFunction;\n\t}\n\n\tprivate initialize() {\n\n\t}\n\n\tstartMonitorFunction(\n\t\tfunctionType: MonitorFunctionType,\n\t\tfunctionName: string,\n\t\tuser: string,\n\t\tid_socket: string,\n\t\tdata: any\n\t) {\n\t\tlet newMonitorFunction = MonitorFunction.create(\n\t\t\tthis._functionCnt++,\n\t\t\tfunctionType,\n\t\t\tfunctionName,\n\t\t\tuser,\n\t\t\tid_socket,\n\t\t\tdata\n\t\t);\n\n\t\tthis._functions.push(newMonitorFunction);\n\t\treturn newMonitorFunction.id;\n\t}\n\n\tasync finishMonitorFunction(id: number) {\n\t\tlet monitor = this._functions.find(a => a.id === id);\n\n\t\tif (monitor) {\n\t\t\tawait monitor.finish();\n\t\t\tthis._functionLastCompleted = monitor;\n\t\t\tthis._functionLastCompletedWS[monitor.id_socket] = monitor;\n\t\t\tthis._functions.splice(\n\t\t\t\tthis._functions.map(a => a.id).indexOf(id),\n\t\t\t\t1\n\t\t\t);\n\t\t}\n\t}\n\n\tgetActiveMonitorFunctions() {\n\t\treturn this._functions;\n\t}\n\n\tgetLastCompletedMonitorFunction() {\n\t\treturn this._functionLastCompleted;\n\t}\n\n\tgetLastCompletedMonitorFunctionWS() {\n\t\treturn this._functionLastCompletedWS;\n\t}\n}\n\nexport type MonitorFunctionType =\n\t'Cron Method'\n\t| 'Method'\n\t| 'User Specific Publication'\n\t| 'Publication';\n\nexport class MonitorFunction {\n\tprivate _timer: NodeJS.Timeout = null;\n\tpublic duration = 0;\n\tpublic functionType: MonitorFunctionType;\n\tpublic functionName: string;\n\tpublic user: string;\n\tpublic data: any;\n\tpublic startTime: Date = null;\n\tpublic endTime: Date = null;\n\tpublic lastTime: Date = null;\n\tpublic id_socket = '';\n\tpublic id = 0;\n\n\tconstructor() {}\n\n\tstatic create(\n\t\tid: number,\n\t\tfunctionType: MonitorFunctionType,\n\t\tfunctionName: string,\n\t\tuser: string,\n\t\tid_socket: string,\n\t\tdata: any\n\t) {\n\t\tconst monitorFunction = new MonitorFunction();\n\t\tmonitorFunction.initialize(id, functionType, functionName, user, id_socket, data);\n\t\treturn monitorFunction;\n\t}\n\n\tprivate initialize(\n\t\tid: number,\n\t\tfunctionType: MonitorFunctionType,\n\t\tfunctionName: string,\n\t\tuser: string,\n\t\tid_socket: string,\n\t\tdata: any\n\t) {\n\t\tthis.id = id;\n\t\tthis.startTime = new Date();\n\t\tthis.functionType = functionType;\n\t\tthis.functionName = functionName;\n\t\tthis.user = user;\n\t\tthis.id_socket = id_socket;\n\t\tthis.data = data;\n\t\tthis.lastTime = new Date();\n\n\t\tthis._timer = setInterval(() => {\n\t\t\tlet diff = Date.now() - this.lastTime.getTime();\n\n\t\t\tif (diff > this.duration) {\n\t\t\t\tthis.duration = diff;\n\t\t\t}\n\n\t\t\tthis.lastTime = new Date();\n\t\t}, 1000);\n\t}\n\n\tpublic async finish() {\n\t\tif (this._timer) {\n\t\t\tclearInterval(this._timer);\n\t\t\tthis._timer = null;\n\t\t}\n\n\t\tthis.endTime = new Date();\n\n\t\tif (this.duration >= 5000) {\n\t\t\t// Optional slow function logging or email\n\t\t}\n\n\t\tawait ResolveIOServer.getMainServer().getMonitorManager().addFunctionTracker(this);\n\t}\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/managers/monitor.manager.ts"],"names":["axios_1","require","monitor_cpu_collection_1","monitor_function_collection_1","monitor_memory_collection_1","monitor_mongo_collection_1","resolveio_server_app_1","common_1","os","MAX_BATCH_SIZE","MonitorManager","this","_instanceHostname","_monitorData","create","monitorManager","initialize","_a","sent","prototype","hostname","replace","setupIntervals","setupEventLoop","cpuAverage","totalIdle","totalTick","cpus","i","len","length","type","cpu","times","idle","total","ResolveIOServer","getServerConfig","default","get","instanceId_1","_b","setInterval","__awaiter","_this","post","id_aws_instance","data","version","process","env","APP_VERSION","toString","version_key","APP_VERSION_KEY","lastCPU","now","Date","endMeasure","idleDifference","totalDifference","percentageCPU","MonitorCPUs","_id","objectIdHexString","metadata","instance","client","date","app","system","loadavg","pushMonitorData","memUsage","memoryUsage","MonitorMemorys","physical_total","heapTotal","physical_used","heapUsed","physical_free","freemem","virtual","rss","private","external","physical","totalmem","addMongoTracker","collection","startsWith","MonitorMongos","method","doc_collection","duration","query","Buffer","byteLength","addFunctionTracker","JSON","stringify","MonitorFunctions","startTime","functionType","name","functionName","user","push","estimateBatchSize","flushMonitorData","reduce","item","batch","batchSize","shift","itemSize","unshift","getLocalLogManager","writeLogs","error","console","MonitorMongo","exports","_startTime","_method","_collection","_query","monitorMongo","finish","endTime","mongoMonitor","getMainServer","getMonitorManager","MonitorManagerFunction","_functionCnt","_functions","_functionLastCompletedWS","monitorManagerFunction","startMonitorFunction","id_socket","newMonitorFunction","MonitorFunction","id","finishMonitorFunction","monitor","find","a","_functionLastCompleted","splice","map","indexOf","getActiveMonitorFunctions","getLastCompletedMonitorFunction","getLastCompletedMonitorFunctionWS","_timer","lastTime","monitorFunction","diff","getTime","clearInterval"],"mappings":"k8CAAAA,S,iKAAAC,QAAA,OAAA,GACAC,yBAAAD,QAAA,uCAAA,EACAE,8BAAAF,QAAA,4CAAA,EACAG,4BAAAH,QAAA,0CAAA,EACAI,2BAAAJ,QAAA,yCAAA,EACAK,uBAAAL,QAAA,yBAAA,EACAM,SAAAN,QAAA,gBAAA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C,EACAiC,EACA5F,GAND,IAAAH,EAAAjC,KAQCA,KAAKmI,GAAKA,EACVnI,KAAK2F,UAAY,IAAI7C,KACrB9C,KAAK4F,aAAeA,EACpB5F,KAAK8F,aAAeA,EACpB9F,KAAK+F,KAAOA,EACZ/F,KAAKgI,UAAYA,EACjBhI,KAAKoC,KAAOA,EACZpC,KAAKgJ,SAAW,IAAIlG,KAEpB9C,KAAK+I,OAAShH,YAAY,WACzB,IAAImH,EAAOpG,KAAKD,IAAG,EAAKZ,EAAK+G,SAASG,QAAO,EAEzCD,EAAOjH,EAAKkD,WACflD,EAAKkD,SAAW+D,GAGjBjH,EAAK+G,SAAW,IAAIlG,IACrB,EAAG,GAAI,CACR,EAEaoF,gBAAA1H,UAAA6G,OAAb,W,0GAYC,OAXIrH,KAAK+I,SACRK,cAAcpJ,KAAK+I,MAAM,EACzB/I,KAAK+I,OAAS,MAGf/I,KAAKsH,QAAU,IAAIxE,KAEf9C,KAAKmF,SAIT,CAAA,EAAMxF,uBAAA8B,gBAAgB+F,cAAa,EAAGC,kBAAiB,EAAGlC,mBAAmBvF,IAAI,G,cAAjFM,EAAAC,KAAA,E,UAEF2H,eAAA,EAAC,GAtEYnB,QAAAmB,gBAAAA","file":"monitor.manager.js","sourcesContent":["import axios from 'axios';\nimport { MonitorCPUs } from '../collections/monitor-cpu.collection';\nimport { MonitorFunctions } from '../collections/monitor-function.collection';\nimport { MonitorMemorys } from '../collections/monitor-memory.collection';\nimport { MonitorMongos } from '../collections/monitor-mongo.collection';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { objectIdHexString } from '../util/common';\nimport { LocalLogModel } from './local-log.manager';\n\nconst os = require('os');\nconst MAX_BATCH_SIZE = 8 * 1024 * 1024; // 8MB max for safety\n\nexport class MonitorManager {\n\tprivate _instanceHostname = '';\n\tprivate _monitorData: LocalLogModel[] = [];\n\n\tconstructor() {}\n\n\tstatic async create() {\n\t\tconst monitorManager = new MonitorManager();\n\t\tawait monitorManager.initialize();\n\t\treturn monitorManager;\n\t}\n\n\tprivate async initialize() {\n\t\tthis._instanceHostname = os.hostname().replace(/\\./g, '-');\n\t\tawait this.setupIntervals();\n\t\tthis.setupEventLoop();\n\t}\n\n\tcpuAverage() {\n\t\tvar totalIdle = 0, totalTick = 0;\n\t\tvar cpus = os.cpus();\n\n\t\tfor (var i = 0, len = cpus.length; i < len; i++) {\n\t\t\tvar cpu = cpus[i];\n\n\t\t\tfor (let type in cpu.times) {\n\t\t\t\ttotalTick += cpu.times[type];\n\t\t\t}\n\t\t\ttotalIdle += cpu.times.idle;\n\t\t}\n\n\t\treturn {\n\t\t\tidle: totalIdle / cpus.length,\n\t\t\ttotal: totalTick / cpus.length\n\t\t};\n\t}\n\n\tasync setupIntervals() {\n\t\t// Example: If not on production or localhost, do a health check\n\t\tif (\n\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t) {\n\t\t\ttry {\n\t\t\t\tlet instanceId = await axios.get('http://169.254.169.254/latest/meta-data/instance-id');\n\n\t\t\t\tsetInterval(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait axios.post('https://backend.resolveio.com/api/health', {\n\t\t\t\t\t\t\ttype: 'application',\n\t\t\t\t\t\t\tid_aws_instance: instanceId.data,\n\t\t\t\t\t\t\tversion: typeof process.env.APP_VERSION === 'number'\n\t\t\t\t\t\t\t\t? (<any>process.env.APP_VERSION).toString()\n\t\t\t\t\t\t\t\t: process.env.APP_VERSION,\n\t\t\t\t\t\t\tversion_key: process.env.APP_VERSION_KEY\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tcatch {}\n\t\t\t\t}, 10000);\n\t\t\t}\n\t\t\tcatch {}\n\t\t}\n\n\t\tlet lastCPU = this.cpuAverage();\n\n\t\tsetInterval(async () => {\n\t\t\tlet now = new Date();\n\t\t\tvar endMeasure = this.cpuAverage();\n\t\t\tvar idleDifference = endMeasure.idle - lastCPU.idle;\n\t\t\tvar totalDifference = endMeasure.total - lastCPU.total;\n\t\t\tvar percentageCPU = 1 - idleDifference / totalDifference;\n\n\t\t\t// Original local code\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'https://resolveio.com'\n\t\t\t|| ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tawait MonitorCPUs.create({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t},\n\t\t\t\t\tdate: now,\n\t\t\t\t\tapp: percentageCPU,\n\t\t\t\t\tsystem: os.loadavg()[0]\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.pushMonitorData({\n\t\t\t\t\ttype: 'monitor-cpu',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdate: now,\n\t\t\t\t\t\tapp: percentageCPU,\n\t\t\t\t\t\tsystem: os.loadavg()[0]\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlastCPU = endMeasure;\n\n\t\t\tconst memUsage = process.memoryUsage();\n\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'https://resolveio.com'\n\t\t\t|| ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tawait MonitorMemorys.create({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t},\n\t\t\t\t\tdate: now,\n\t\t\t\t\tphysical_total: memUsage.heapTotal,\n\t\t\t\t\tphysical_used: memUsage.heapUsed,\n\t\t\t\t\tphysical_free: os.freemem(),\n\t\t\t\t\tvirtual: memUsage.rss,\n\t\t\t\t\tprivate: memUsage.external,\n\t\t\t\t\tphysical: os.totalmem()\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.pushMonitorData({\n\t\t\t\t\ttype: 'monitor-memory',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdate: now,\n\t\t\t\t\t\tphysical_total: memUsage.heapTotal,\n\t\t\t\t\t\tphysical_used: memUsage.heapUsed,\n\t\t\t\t\t\tphysical_free: os.freemem(),\n\t\t\t\t\t\tvirtual: memUsage.rss,\n\t\t\t\t\t\tprivate: memUsage.external,\n\t\t\t\t\t\tphysical: os.totalmem(),\n\t\t\t\t\t\ttype: 'memory'\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}, 3000);\n\t}\n\n\tasync addMongoTracker(data: MongoMonitorModel) {\n\t\tif (\n\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'https://resolveio.com'\n\t\t\t|| ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200'\n\t\t) {\n\t\t\tif (!data.collection.startsWith('monitor-')) {\n\t\t\t\tawait MonitorMongos.create({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t},\n\t\t\t\t\tdate: new Date(data.date),\n\t\t\t\t\tmethod: data.method,\n\t\t\t\t\tdoc_collection: data.collection,\n\t\t\t\t\tduration: data.duration,\n\t\t\t\t\tquery: Buffer.byteLength(data.query, 'utf8') < 15800000\n\t\t\t\t\t\t? data.query\n\t\t\t\t\t\t: 'Too Big'\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (this._instanceHostname) {\n\t\t\t\tthis.pushMonitorData({\n\t\t\t\t\ttype: 'monitor-mongo',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdate: new Date(data.date),\n\t\t\t\t\t\tmethod: data.method,\n\t\t\t\t\t\tdoc_collection: data.collection,\n\t\t\t\t\t\tduration: data.duration,\n\t\t\t\t\t\tquery: Buffer.byteLength(data.query, 'utf8') < 15800000\n\t\t\t\t\t\t\t? data.query\n\t\t\t\t\t\t\t: 'Too Big'\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tasync addFunctionTracker(data: MonitorFunction) {\n\t\tif (typeof(data.data) !== 'string') {\n\t\t\tdata.data = JSON.stringify(data.data);\n\t\t}\n\n\t\tif (\n\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'https://resolveio.com'\n\t\t\t|| ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200'\n\t\t) {\n\t\t\tawait MonitorFunctions.create({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\tmetadata: {\n\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t},\n\t\t\t\tdate: new Date(data.startTime),\n\t\t\t\ttype: data.functionType,\n\t\t\t\tname: data.functionName,\n\t\t\t\tuser: data.user,\n\t\t\t\tduration: data.duration,\n\t\t\t\tdata: Buffer.byteLength(data.data, 'utf8') < 15800000\n\t\t\t\t\t? data.data\n\t\t\t\t\t: 'Too Big'\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tif (this._instanceHostname) {\n\t\t\t\tthis.pushMonitorData({\n\t\t\t\t\ttype: 'monitor-function',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tinstance: this._instanceHostname,\n\t\t\t\t\t\t\tclient: ResolveIOServer.getServerConfig()['CLIENT_NAME']\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdate: new Date(data.startTime),\n\t\t\t\t\t\ttype: data.functionType,\n\t\t\t\t\t\tname: data.functionName,\n\t\t\t\t\t\tuser: data.user,\n\t\t\t\t\t\tduration: data.duration,\n\t\t\t\t\t\tdata: Buffer.byteLength(data.data, 'utf8') < 15800000\n\t\t\t\t\t\t\t? data.data\n\t\t\t\t\t\t\t: 'Too Big'\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate pushMonitorData(data: LocalLogModel) {\n\t\tthis._monitorData.push(data);\n\n\t\t// If data is huge, flush immediately to file\n\t\tif (this.estimateBatchSize() >= MAX_BATCH_SIZE) {\n\t\t\tthis.flushMonitorData();\n\t\t}\n\t}\n\n\tprivate estimateBatchSize(): number {\n\t\treturn this._monitorData.reduce((total, item) => {\n\t\t\treturn total + Buffer.byteLength(JSON.stringify(item));\n\t\t}, 0);\n\t}\n\n\tsetupEventLoop() {\n\t\t// Flush every 2.5 seconds\n\t\tsetInterval(() => {\n\t\t\tif (this._monitorData.length > 0) {\n\t\t\t\tthis.flushMonitorData();\n\t\t\t}\n\t\t}, 2500);\n\t}\n\n\tprivate flushMonitorData() {\n\t\tconst batch = [];\n\t\tlet batchSize = 0;\n\n\t\twhile (this._monitorData.length > 0 && batchSize < MAX_BATCH_SIZE) {\n\t\t\tconst item = this._monitorData.shift();\n\t\t\tconst itemSize = Buffer.byteLength(JSON.stringify(item));\n\n\t\t\tif ((batchSize + itemSize) > MAX_BATCH_SIZE && batch.length > 0) {\n\t\t\t\t// put the item back for next round\n\t\t\t\tthis._monitorData.unshift(item);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tbatch.push(item);\n\t\t\tbatchSize += itemSize;\n\t\t}\n\n\t\ttry {\n\t\t\t// Now, instead of calling an external HTTP endpoint, we write the batch to disk:\n\t\t\tResolveIOServer.getLocalLogManager().writeLogs(batch);\n\t\t}\n\t\tcatch (error) {\n\t\t\tconsole.error(new Date(), 'MonitorManager', 'Failed to flush monitor data to file:', error);\n\t\t}\n\t}\n}\n\nexport interface MongoMonitorModel {\n\tdate: Date;\n\tmethod: string;\n\tcollection: string;\n\tduration: number;\n\tquery: string;\n}\n\nexport class MonitorMongo {\n\tprivate _startTime = 0;\n\tprivate _method = '';\n\tprivate _collection = '';\n\tprivate _query = '';\n\n\tconstructor() {}\n\n\tstatic create(method: string, collection: string, query: string) {\n\t\tconst monitorMongo = new MonitorMongo();\n\t\tmonitorMongo.initialize(method, collection, query);\n\t\treturn monitorMongo;\n\t}\n\n\tprivate initialize(method: string, collection: string, query: string) {\n\t\tthis._startTime = Date.now();\n\t\tthis._method = method;\n\t\tthis._collection = collection;\n\t\tthis._query = query;\n\t}\n\n\tpublic async finish() {\n\t\tlet endTime = Date.now();\n\n\t\tlet mongoMonitor: MongoMonitorModel = {\n\t\t\tdate: new Date(endTime),\n\t\t\tmethod: this._method,\n\t\t\tcollection: this._collection,\n\t\t\tquery: this._query,\n\t\t\tduration: endTime - this._startTime\n\t\t};\n\n\t\tawait ResolveIOServer.getMainServer().getMonitorManager().addMongoTracker(mongoMonitor);\n\t}\n}\n\nexport class MonitorManagerFunction {\n\tprivate _functionCnt = 0;\n\tprivate _functions: MonitorFunction[] = [];\n\tprivate _functionLastCompletedWS: { [id_socket: string]: MonitorFunction; } = {};\n\tprivate _functionLastCompleted: MonitorFunction;\n\n\tconstructor() {}\n\n\tstatic create() {\n\t\tconst monitorManagerFunction = new MonitorManagerFunction();\n\t\tmonitorManagerFunction.initialize();\n\t\treturn monitorManagerFunction;\n\t}\n\n\tprivate initialize() {\n\n\t}\n\n\tstartMonitorFunction(\n\t\tfunctionType: MonitorFunctionType,\n\t\tfunctionName: string,\n\t\tuser: string,\n\t\tid_socket: string,\n\t\tdata: any\n\t) {\n\t\tlet newMonitorFunction = MonitorFunction.create(\n\t\t\tthis._functionCnt++,\n\t\t\tfunctionType,\n\t\t\tfunctionName,\n\t\t\tuser,\n\t\t\tid_socket,\n\t\t\tdata\n\t\t);\n\n\t\tthis._functions.push(newMonitorFunction);\n\t\treturn newMonitorFunction.id;\n\t}\n\n\tasync finishMonitorFunction(id: number) {\n\t\tlet monitor = this._functions.find(a => a.id === id);\n\n\t\tif (monitor) {\n\t\t\tawait monitor.finish();\n\t\t\tthis._functionLastCompleted = monitor;\n\t\t\tthis._functionLastCompletedWS[monitor.id_socket] = monitor;\n\t\t\tthis._functions.splice(\n\t\t\t\tthis._functions.map(a => a.id).indexOf(id),\n\t\t\t\t1\n\t\t\t);\n\t\t}\n\t}\n\n\tgetActiveMonitorFunctions() {\n\t\treturn this._functions;\n\t}\n\n\tgetLastCompletedMonitorFunction() {\n\t\treturn this._functionLastCompleted;\n\t}\n\n\tgetLastCompletedMonitorFunctionWS() {\n\t\treturn this._functionLastCompletedWS;\n\t}\n}\n\nexport type MonitorFunctionType =\n\t'Cron Method'\n\t| 'Method'\n\t| 'User Specific Publication'\n\t| 'Publication';\n\nexport class MonitorFunction {\n\tprivate _timer: NodeJS.Timeout = null;\n\tpublic duration = 0;\n\tpublic functionType: MonitorFunctionType;\n\tpublic functionName: string;\n\tpublic user: string;\n\tpublic data: any;\n\tpublic startTime: Date = null;\n\tpublic endTime: Date = null;\n\tpublic lastTime: Date = null;\n\tpublic id_socket = '';\n\tpublic id = 0;\n\n\tconstructor() {}\n\n\tstatic create(\n\t\tid: number,\n\t\tfunctionType: MonitorFunctionType,\n\t\tfunctionName: string,\n\t\tuser: string,\n\t\tid_socket: string,\n\t\tdata: any\n\t) {\n\t\tconst monitorFunction = new MonitorFunction();\n\t\tmonitorFunction.initialize(id, functionType, functionName, user, id_socket, data);\n\t\treturn monitorFunction;\n\t}\n\n\tprivate initialize(\n\t\tid: number,\n\t\tfunctionType: MonitorFunctionType,\n\t\tfunctionName: string,\n\t\tuser: string,\n\t\tid_socket: string,\n\t\tdata: any\n\t) {\n\t\tthis.id = id;\n\t\tthis.startTime = new Date();\n\t\tthis.functionType = functionType;\n\t\tthis.functionName = functionName;\n\t\tthis.user = user;\n\t\tthis.id_socket = id_socket;\n\t\tthis.data = data;\n\t\tthis.lastTime = new Date();\n\n\t\tthis._timer = setInterval(() => {\n\t\t\tlet diff = Date.now() - this.lastTime.getTime();\n\n\t\t\tif (diff > this.duration) {\n\t\t\t\tthis.duration = diff;\n\t\t\t}\n\n\t\t\tthis.lastTime = new Date();\n\t\t}, 1000);\n\t}\n\n\tpublic async finish() {\n\t\tif (this._timer) {\n\t\t\tclearInterval(this._timer);\n\t\t\tthis._timer = null;\n\t\t}\n\n\t\tthis.endTime = new Date();\n\n\t\tif (this.duration >= 5000) {\n\t\t\t// Optional slow function logging or email\n\t\t}\n\n\t\tawait ResolveIOServer.getMainServer().getMonitorManager().addFunctionTracker(this);\n\t}\n}"]}
|
package/package.json
CHANGED
package/resolveio-server-app.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __awaiter=this&&this.__awaiter||function(e,o,t,v){return new(t=t||Promise)(function(n,r){function fulfilled(e){try{step(v.next(e))}catch(e){r(e)}}function rejected(e){try{step(v.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?n(e.value):((r=e.value)instanceof t?r:new t(function(e){e(r)})).then(fulfilled,rejected)}step((v=v.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,t){var v,s,l,i={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]},a={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function verb(n){return function(e){var r=[n,e];if(v)throw new TypeError("Generator is already executing.");for(;i=a&&r[a=0]?0:i;)try{if(v=1,s&&(l=2&r[0]?s.return:r[0]?s.throw||((l=s.return)&&l.call(s),0):s.next)&&!(l=l.call(s,r[1])).done)return l;switch(s=0,(r=l?[2&r[0],l.value]:r)[0]){case 0:case 1:l=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,s=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(l=0<(l=i.trys).length&&l[l.length-1])&&(6===r[0]||2===r[0])){i=0;continue}if(3===r[0]&&(!l||r[1]>l[0]&&r[1]<l[3]))i.label=r[1];else if(6===r[0]&&i.label<l[1])i.label=l[1],l=r;else{if(!(l&&i.label<l[2])){l[2]&&i.ops.pop(),i.trys.pop();continue}i.label=l[2],i.ops.push(r)}}r=t.call(o,i)}catch(e){r=[6,e],s=0}finally{v=l=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},mongodb_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOServer=void 0,require("mongodb")),ResolveIOServer=function(){function ResolveIOServer(){}return ResolveIOServer.create=function(n,o,t,v,s,l){return void 0===s&&(s=!0),void 0===l&&(l=!1),__awaiter(this,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return[4,(r=new ResolveIOServer).initialize(n,o,t,v,s,l)];case 1:return e.sent(),[2,r]}})})},ResolveIOServer.prototype.initialize=function(t,v,s,l,i,a){return void 0===i&&(i=!0),void 0===a&&(a=!1),__awaiter(this,void 0,void 0,function(){var r,n,o;return __generator(this,function(e){switch(e.label){case 0:ResolveIOServer._serverConfig=t,ResolveIOServer._clientRoutes=v,ResolveIOServer._client=s,ResolveIOServer._clientDir=l,ResolveIOServer._sesMail=i,ResolveIOServer._standardProgram=a,e.label=1;case 1:return e.trys.push([1,
|
|
1
|
+
"use strict";var __awaiter=this&&this.__awaiter||function(e,o,t,v){return new(t=t||Promise)(function(n,r){function fulfilled(e){try{step(v.next(e))}catch(e){r(e)}}function rejected(e){try{step(v.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?n(e.value):((r=e.value)instanceof t?r:new t(function(e){e(r)})).then(fulfilled,rejected)}step((v=v.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,t){var v,s,l,i={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]},a={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function verb(n){return function(e){var r=[n,e];if(v)throw new TypeError("Generator is already executing.");for(;i=a&&r[a=0]?0:i;)try{if(v=1,s&&(l=2&r[0]?s.return:r[0]?s.throw||((l=s.return)&&l.call(s),0):s.next)&&!(l=l.call(s,r[1])).done)return l;switch(s=0,(r=l?[2&r[0],l.value]:r)[0]){case 0:case 1:l=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,s=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(l=0<(l=i.trys).length&&l[l.length-1])&&(6===r[0]||2===r[0])){i=0;continue}if(3===r[0]&&(!l||r[1]>l[0]&&r[1]<l[3]))i.label=r[1];else if(6===r[0]&&i.label<l[1])i.label=l[1],l=r;else{if(!(l&&i.label<l[2])){l[2]&&i.ops.pop(),i.trys.pop();continue}i.label=l[2],i.ops.push(r)}}r=t.call(o,i)}catch(e){r=[6,e],s=0}finally{v=l=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},mongodb_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOServer=void 0,require("mongodb")),ResolveIOServer=function(){function ResolveIOServer(){}return ResolveIOServer.create=function(n,o,t,v,s,l){return void 0===s&&(s=!0),void 0===l&&(l=!1),__awaiter(this,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return[4,(r=new ResolveIOServer).initialize(n,o,t,v,s,l)];case 1:return e.sent(),[2,r]}})})},ResolveIOServer.prototype.initialize=function(t,v,s,l,i,a){return void 0===i&&(i=!0),void 0===a&&(a=!1),__awaiter(this,void 0,void 0,function(){var r,n,o;return __generator(this,function(e){switch(e.label){case 0:ResolveIOServer._serverConfig=t,ResolveIOServer._clientRoutes=v,ResolveIOServer._client=s,ResolveIOServer._clientDir=l,ResolveIOServer._sesMail=i,ResolveIOServer._standardProgram=a,e.label=1;case 1:return e.trys.push([1,8,,9]),[4,mongodb_1.MongoClient.connect(ResolveIOServer.getServerConfig().MONGO_URL)];case 2:return r=e.sent(),ResolveIOServer.setMongoConnection(r),ResolveIOServer.setMainDB(r.db(ResolveIOServer.getServerConfig().DATABASE)),[4,Promise.resolve().then(function(){return require("./managers/local-log.manager")})];case 3:return r=e.sent().LocalLogManager,n=r.create(),ResolveIOServer.setLocalLogManager(n),[4,Promise.resolve().then(function(){return require("./managers/mongo.manager")})];case 4:return[4,e.sent().MongoManager.create()];case 5:return n=e.sent(),ResolveIOServer.setMongoManager(n),[4,Promise.resolve().then(function(){return require("./server-app")})];case 6:return[4,e.sent().ResolveIOMainServer.create()];case 7:return o=e.sent(),ResolveIOServer.setMainServer(o),[2,!0];case 8:return(o=e.sent()).message="Error in ResolveIOServer (initialize): Mongo Client Connect And Run ResolveIO Server App Library - "+o.message,process.exit(1),[3,9];case 9:return[2]}})})},ResolveIOServer.getClientName=function(){return this._client},ResolveIOServer.getMainServer=function(){return ResolveIOServer._mainServer},ResolveIOServer.setMainServer=function(e){ResolveIOServer._mainServer=e},ResolveIOServer.setMongoConnection=function(e){ResolveIOServer._mongoConnection=e},ResolveIOServer.getMongoConnection=function(){return ResolveIOServer._mongoConnection},ResolveIOServer.getMainDB=function(){return ResolveIOServer._mainDB},ResolveIOServer.setMainDB=function(e){ResolveIOServer._mainDB=e},ResolveIOServer.getMongoManager=function(){return ResolveIOServer._mongoManager},ResolveIOServer.setMongoManager=function(e){ResolveIOServer._mongoManager=e},ResolveIOServer.getLocalLogManager=function(){return ResolveIOServer._localLogManager},ResolveIOServer.setLocalLogManager=function(e){ResolveIOServer._localLogManager=e},ResolveIOServer.getServerConfig=function(){return ResolveIOServer._serverConfig},ResolveIOServer.getClientRoutes=function(){return ResolveIOServer._clientRoutes},ResolveIOServer.getClientDir=function(){return ResolveIOServer._clientDir},ResolveIOServer.getSESMail=function(){return ResolveIOServer._sesMail},ResolveIOServer.getStandardProgram=function(){return ResolveIOServer._standardProgram},ResolveIOServer._serverConfig=null,ResolveIOServer._clientRoutes=[],ResolveIOServer._mongoConnection=null,ResolveIOServer._mainDB=null,ResolveIOServer._mainServer=null,ResolveIOServer._localLogManager=null,ResolveIOServer._mongoManager=null,ResolveIOServer._client="",ResolveIOServer._clientDir="",ResolveIOServer._sesMail=!0,ResolveIOServer._standardProgram=!1,ResolveIOServer}();exports.ResolveIOServer=ResolveIOServer;
|
|
2
2
|
//# sourceMappingURL=resolveio-server-app.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/resolveio-server-app.ts"],"names":["mongodb_1","require","ResolveIOServer","create","serverConfig","clientRoutes","client","clientDir","sesMail","standardProgram","resolveioServer","initialize","_a","sent","prototype","_serverConfig","_clientRoutes","_client","_clientDir","_sesMail","_standardProgram","MongoClient","connect","getServerConfig","dbConnection","setMongoConnection","setMainDB","db","Promise","resolve","then","LocalLogManager_1","LocalLogManager","localLogManager","setLocalLogManager","MongoManager","mongoManager","setMongoManager","
|
|
1
|
+
{"version":3,"sources":["../../src/resolveio-server-app.ts"],"names":["mongodb_1","require","ResolveIOServer","create","serverConfig","clientRoutes","client","clientDir","sesMail","standardProgram","resolveioServer","initialize","_a","sent","prototype","_serverConfig","_clientRoutes","_client","_clientDir","_sesMail","_standardProgram","MongoClient","connect","getServerConfig","dbConnection","setMongoConnection","setMainDB","db","Promise","resolve","then","LocalLogManager_1","LocalLogManager","localLogManager","setLocalLogManager","MongoManager","mongoManager","setMongoManager","ResolveIOMainServer","app","setMainServer","message","err_1","process","exit","getClientName","this","getMainServer","_mainServer","mainServer","mongoConnection","_mongoConnection","getMongoConnection","getMainDB","_mainDB","mainDB","getMongoManager","_mongoManager","getLocalLogManager","_localLogManager","getClientRoutes","getClientDir","getSESMail","getStandardProgram","exports"],"mappings":"k8CAAAA,W,sFAAAC,QAAA,SAAA,GAKAC,gBAAA,WAaC,SAAAA,mBAwGD,OAtGqBA,gBAAAC,OAApB,SAA2BC,EAAcC,EAAwBC,EAAgBC,EAAWC,EAAgBC,G,OAAhB,KAAA,IAAAD,IAAAA,EAAA,CAAA,GAAgB,KAAA,IAAAC,IAAAA,EAAA,CAAA,G,yGAE3G,MAAA,CAAA,GADMC,EAAkB,IAAIR,iBACNS,WAAWP,EAAcC,EAAcC,EAAQC,EAAWC,EAASC,CAAe,G,OACxG,OADAG,EAAAC,KAAA,EACA,CAAA,EAAOH,E,OAGMR,gBAAAY,UAAAH,WAAd,SAAyBP,EAAcC,EAAwBC,EAAgBC,EAAWC,EAAgBC,G,OAAhB,KAAA,IAAAD,IAAAA,EAAA,CAAA,GAAgB,KAAA,IAAAC,IAAAA,EAAA,CAAA,G,6GACzGP,gBAAgBa,cAAgBX,EAChCF,gBAAgBc,cAAgBX,EAChCH,gBAAgBe,QAAUX,EAC1BJ,gBAAgBgB,WAAaX,EAC7BL,gBAAgBiB,SAAWX,EAC3BN,gBAAgBkB,iBAAmBX,E,iBAGf,O,sBAAA,CAAA,EAAMT,UAAAqB,YAAYC,QAAQpB,gBAAgBqB,gBAAe,EAAc,SAAC,G,OAIpE,OAJnBC,EAAeZ,EAAAC,KAAA,EACnBX,gBAAgBuB,mBAAmBD,CAAY,EAC/CtB,gBAAgBwB,UAAUF,EAAaG,GAAGzB,gBAAgBqB,gBAAe,EAAa,QAAC,CAAC,EAEjE,CAAA,EAAAK,QAAAC,QAAA,EAAAC,KAAA,WAAA,OAAA7B,QAAa,8BAA8B,CAAA,CAAA,G,OAI9C,OAJhB8B,EAAmBnB,E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,mBAAd,SAAiCD,GAChC/B,gBAAgByD,iBAAmB1B,CACpC,EAEc/B,gBAAAqB,gBAAd,WACC,OAAOrB,gBAAgBa,aACxB,EAEcb,gBAAA0D,gBAAd,WACC,OAAO1D,gBAAgBc,aACxB,EAEcd,gBAAA2D,aAAd,WACC,OAAO3D,gBAAgBgB,UACxB,EAEchB,gBAAA4D,WAAd,WACC,OAAO5D,gBAAgBiB,QACxB,EAEcjB,gBAAA6D,mBAAd,WACC,OAAO7D,gBAAgBkB,gBACxB,EAnHelB,gBAAAa,cAAgB,KAChBb,gBAAAc,cAAgB,GAChBd,gBAAAiD,iBAAgC,KAChCjD,gBAAAoD,QAAc,KACdpD,gBAAA8C,YAAc,KACd9C,gBAAAyD,iBAAmB,KACnBzD,gBAAAuD,cAAgB,KAChBvD,gBAAAe,QAAU,GACVf,gBAAAgB,WAAa,GACbhB,gBAAAiB,SAAW,CAAA,EACXjB,gBAAAkB,iBAAmB,CAAA,EA0GnClB,e,EAAC,EArHY8D,QAAA9D,gBAAAA","file":"resolveio-server-app.js","sourcesContent":["import { Db, MongoClient } from 'mongodb';\nimport { LocalLogManager } from './managers/local-log.manager';\nimport { MongoManager } from './managers/mongo.manager';\nimport { ResolveIOMainServer } from './server-app';\n\nexport class ResolveIOServer {\n\tprivate static _serverConfig = null;\n\tprivate static _clientRoutes = [];\n\tprivate static _mongoConnection: MongoClient = null;\n\tprivate static _mainDB: Db = null;\n\tprivate static _mainServer = null;\n\tprivate static _localLogManager = null;\n\tprivate static _mongoManager = null;\n\tprivate static _client = '';\n\tprivate static _clientDir = '';\n\tprivate static _sesMail = true;\n\tprivate static _standardProgram = false;\n\n\tconstructor() {}\n\t\n\tpublic static async create(serverConfig, clientRoutes: string[], client: string, clientDir, sesMail = true, standardProgram = false) {\n\t\tconst resolveioServer = new ResolveIOServer();\n\t\tawait resolveioServer.initialize(serverConfig, clientRoutes, client, clientDir, sesMail, standardProgram);\n\t\treturn resolveioServer;\n\t}\n\n\tprivate async initialize(serverConfig, clientRoutes: string[], client: string, clientDir, sesMail = true, standardProgram = false) {\n\t\tResolveIOServer._serverConfig = serverConfig;\n\t\tResolveIOServer._clientRoutes = clientRoutes;\n\t\tResolveIOServer._client = client;\n\t\tResolveIOServer._clientDir = clientDir;\n\t\tResolveIOServer._sesMail = sesMail;\n\t\tResolveIOServer._standardProgram = standardProgram;\n\t\t\n\t\ttry {\n\t\t\tlet dbConnection = await MongoClient.connect(ResolveIOServer.getServerConfig()['MONGO_URL']);\n\t\t\tResolveIOServer.setMongoConnection(dbConnection);\n\t\t\tResolveIOServer.setMainDB(dbConnection.db(ResolveIOServer.getServerConfig()['DATABASE']));\n\t\n\t\t\tlet LocalLogManager = (await import('./managers/local-log.manager')).LocalLogManager;\n\t\t\tlet localLogManager = LocalLogManager.create();\n\t\t\tResolveIOServer.setLocalLogManager(localLogManager);\n\n\t\t\tlet MongoManager = (await import('./managers/mongo.manager')).MongoManager;\n\t\t\tlet mongoManager = await MongoManager.create();\n\t\t\tResolveIOServer.setMongoManager(mongoManager);\n\t\t\t\n\t\t\tlet serverApp = (await import('./server-app')).ResolveIOMainServer;\n\t\t\tlet app = await serverApp.create();\n\t\t\tResolveIOServer.setMainServer(app);\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\tcatch (err) {\n\t\t\terr.message = 'Error in ResolveIOServer (initialize): Mongo Client Connect And Run ResolveIO Server App Library - ' + err.message;\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tpublic static getClientName() {\n\t\treturn this._client;\n\t}\n\n\tpublic static getMainServer(): ResolveIOMainServer {\n\t\treturn ResolveIOServer._mainServer;\n\t}\n\n\tpublic static setMainServer(mainServer: ResolveIOMainServer) {\n\t\tResolveIOServer._mainServer = mainServer;\n\t}\n\n\tpublic static setMongoConnection(mongoConnection: MongoClient) {\n\t\tResolveIOServer._mongoConnection = mongoConnection;\n\t}\n\n\tpublic static getMongoConnection(): MongoClient {\n\t\treturn ResolveIOServer._mongoConnection;\n\t}\n\n\tpublic static getMainDB(): Db {\n\t\treturn ResolveIOServer._mainDB;\n\t}\n\n\tpublic static setMainDB(mainDB: Db) {\n\t\tResolveIOServer._mainDB = mainDB\n\t}\n\n\tpublic static getMongoManager(): MongoManager {\n\t\treturn ResolveIOServer._mongoManager;\n\t}\n\n\tpublic static setMongoManager(mongoManager: MongoManager) {\n\t\tResolveIOServer._mongoManager = mongoManager;\n\t}\n\n\tpublic static getLocalLogManager(): LocalLogManager {\n\t\treturn ResolveIOServer._localLogManager;\n\t}\n\n\tpublic static setLocalLogManager(localLogManager: LocalLogManager) {\n\t\tResolveIOServer._localLogManager = localLogManager;\n\t}\n\n\tpublic static getServerConfig() {\n\t\treturn ResolveIOServer._serverConfig;\n\t}\n\n\tpublic static getClientRoutes() {\n\t\treturn ResolveIOServer._clientRoutes;\n\t}\n\n\tpublic static getClientDir(): string {\n\t\treturn ResolveIOServer._clientDir;\n\t}\n\n\tpublic static getSESMail(): boolean {\n\t\treturn ResolveIOServer._sesMail;\n\t}\n\n\tpublic static getStandardProgram(): boolean {\n\t\treturn ResolveIOServer._standardProgram;\n\t}\n}"]}
|
package/server-app.d.ts
CHANGED
|
@@ -38,10 +38,10 @@ export declare class ResolveIOMainServer {
|
|
|
38
38
|
private _taskQueue;
|
|
39
39
|
private _inFlightRequests;
|
|
40
40
|
constructor();
|
|
41
|
-
static create(): ResolveIOMainServer
|
|
41
|
+
static create(): Promise<ResolveIOMainServer>;
|
|
42
42
|
private initialize;
|
|
43
43
|
private startServerInstance;
|
|
44
|
-
|
|
44
|
+
startWorkerInstance(): void;
|
|
45
45
|
private handleIncomingTask;
|
|
46
46
|
private sendWorkerResponse;
|
|
47
47
|
private safeShutdown;
|
package/server-app.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(t){return function(e){var r=[t,e];if(o)throw new TypeError("Generator is already executing.");for(;c=l&&r[l=0]?0:c;)try{if(o=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))c.label=r[1];else if(6===r[0]&&c.label<a[1])c.label=a[1],a=r;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(r)}}r=s.call(n,c)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,s,o=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(n=o.next()).done;)i.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(t=o.return)&&t.call(o)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},bodyParser=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("body-parser")),express=require("express"),xmlParser=require("express-xml-bodyparser"),http_1=require("http"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),WebSocket=require("ws"),log_collection_1=require("./collections/log.collection"),user_collection_1=require("./collections/user.collection"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),monitor_manager_1=require("./managers/monitor.manager"),subscription_manager_1=require("./managers/subscription.manager"),common_1=require("./util/common"),mongodb_1=require("mongodb"),auth_1=require("./http/auth"),health_1=require("./http/health"),home_1=require("./http/home"),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={}}return ResolveIOMainServer.create=function(){var e=new ResolveIOMainServer;return e.initialize(),e},ResolveIOMainServer.prototype.initialize=function(){var e=this,o=(this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){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(){o=!0},5e3),process.on("unhandledRejection",function(n,s){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:n&&"MongoServerError"===n.name&&!o?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,11];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,11];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,11];case 9:return n?"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,11]:[3,11];case 10:e.sent(),e.label=11;case 11: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(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),process.on("SIGTERM",function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),process.on("SIGQUIT",function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=method_manager_1.MethodManager.create(null,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=cron_manager_1.CronManager.create(),this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=websocket_manager_1.WebSocketManager.create(this),this.startServerInstance(),this._methodManager=method_manager_1.MethodManager.create(this._websocketManager,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=subscription_manager_1.SubscriptionManager.create(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=websocket_manager_1.WebSocketManager.create(this),this.startServerInstance(),this._methodManager=method_manager_1.MethodManager.create(this._websocketManager,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=subscription_manager_1.SubscriptionManager.create(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=cron_manager_1.CronManager.create(),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"!==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(){var e=this,r=(console.log(new Date,"Worker instance started, connecting to main server via WebSocket..."),resolveio_server_app_1.ResolveIOServer.getServerConfig().SERVER_URL+"/websocket?workerToken="+resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN),n=new WebSocket(r),s=null,t=null;n.on("open",function(){console.log(new Date,"Connected to main server as worker",process.env.WORKER_INDEX,process.env.NODE_APP_INSTANCE),e.sendWorkerResponse(n,"ping"),t=setInterval(function(){s?(s=null,e.sendWorkerResponse(n,"ping")):n.close()},15e3)}),n.on("message",function(t){return __awaiter(e,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return"ping"!==(t="string"!=typeof t?t.toString():t)?[3,1]:(this.sendWorkerResponse(n,"pong"),[3,4]);case 1:return"pong"!==t?[3,2]:(s=new Date,[3,4]);case 2:r=void 0;try{r=JSON.parse(t,common_1.dateReviver)}catch(e){return console.error("Worker parse error",e),[2]}return"task"!==r.type?[3,4]:[4,this.handleIncomingTask(n,r)];case 3:e.sent(),e.label=4;case 4:return[2]}})})}),n.on("close",function(){console.log(new Date,"Disconnected from main server. Reconnecting in 5s..."),setTimeout(e.startWorkerInstance,5e3),t&&clearInterval(t)}),n.on("error",function(e){console.error(new Date,"Worker WS error:",e),n.close()})},ResolveIOMainServer.prototype.handleIncomingTask=function(u,_){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c,l=this;return __generator(this,function(e){switch(e.label){case 0:if(r=_.taskId,t=_.method,n=_.params,s=_.userContext,this._runningTasks.push(r),!r||!t)return console.log("Invalid task message received",_),[2];o=!1,i=setTimeout(function(){return __awaiter(l,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return o=!0,console.error(new Date,"Worker timed out on task:",r,"Method:",t),console.error(new Date,"Error in Method: ".concat(t," - ").concat(JSON.stringify(_,null,2))),this.sendWorkerResponse(u,{type:"taskComplete",taskId:r,error:!0,message:"Task timed out"}),[4,this._methodManager.callMethod("insertErrorLog","Timeout in Method: ".concat(t," - ").concat(JSON.stringify(_,null,2)))];case 1:return e.sent(),[2]}})})},12e4),e.label=1;case 1:return e.trys.push([1,3,,5]),a=Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:(null==s?void 0:s.id_user)||"",user:(null==s?void 0:s.user)||"",id_ws:(null==s?void 0:s.id_ws)||""}),[4,(c=this._methodManager.callMethod).call.apply(c,__spreadArray([a,t],__read(n),!1))];case 2:return c=e.sent(),o||(clearTimeout(i),this.sendWorkerResponse(u,{type:"taskComplete",taskId:r,error:!1,result:c})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,5];case 3:return a=e.sent(),o||(clearTimeout(i),console.error("Worker failed task:",r,"Method:",t,a),this.sendWorkerResponse(u,{type:"taskComplete",taskId:r,error:!0,message:a||"Unknown error"})),console.error(new Date,"Error in Method: ".concat(t," - ").concat(JSON.stringify(_,null,2))),[4,this._methodManager.callMethod("insertErrorLog","Error in Method: ".concat(t," - ").concat(JSON.stringify(_,null,2)))];case 4:return e.sent(),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,5];case 5: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(){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:if(this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length||this._taskQueue.length||this._runningTasks.length)return[3,7];if(!resolveio_server_app_1.ResolveIOServer.getMongoConnection())return[3,5];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1)];case 2:return e.sent(),console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0),[3,4];case 3:return e.sent(),process.exit(1),[3,4];case 4:return[3,6];case 5:process.exit(0),e.label=6;case 6:return[3,8];case 7:this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){r._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){return __awaiter(r,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),e.label=8;case 8:return[2]}})})},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 r=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,o){var e;r._rebootFlag?o(!1,409,"Unable To Process"):("DEBUG"===r.LOGGER&&console.log("Verify Client",s,o),s.req.url&&s.req.url.includes("workerToken=")?(s.req.url.split("workerToken=")[1]||"")===resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN?o(!0):o(!1,401,"Unauthorized"):(e=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)&&(e=e[0])?jwt.verify(e,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,n){return __awaiter(r,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(o(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:s.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.req.doc_user=r,o(!0)):o(!1),[3,5];case 4:return e.sent(),o(!1),[3,5];case 5:return[2]}})})}):o(!1,401,"Unauthorized")))}})},ResolveIOMainServer.prototype.listen=function(){var e=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",e._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",e._portWSS)}),this._serverWSS.on("connection",function(o,i){return __awaiter(e,void 0,void 0,function(){var r,t,n,s=this;return __generator(this,function(e){switch(e.label){case 0:return i.url&&i.url.includes("workerToken=")?(r=(0,common_1.objectIdHexString)(),o.id_worker=r,this._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()}),[3,3]):[3,1];case 1:return o.id_socket=(0,common_1.objectIdHexString)(),o.id_user=i.id_user,o.user=i.user,o.user_readonly=i.user_readonly,o.doc_user=i.doc_user,this._websocketManager.addWebSocket(o),[4,this._subscriptionManager.createLoggedInUser(o.id_socket)];case 2:e.sent(),setTimeout(function(){o.pingTime=new Date,o.send("ping",function(r){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(o)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})})},5e3),"DEBUG"===this.LOGGER&&console.log("Connection from user: "+i.user),o.isAlive=!0,o.retryCnt=0,o.on("message",function(n){return __awaiter(s,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:this._debugMsgRecv+=1,r=[],e.label=1;case 1:return e.trys.push([1,2,,4]),r=JSON.parse(n,common_1.dateReviver),[3,4];case 2:return t=e.sent(),console.log("Error - JSON.parse",n),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n,t]))];case 3:return e.sent(),[2];case 4:return[4,this.processSocketMessage(o,r)];case 5:return e.sent(),[2]}})})}).on("end",function(){o.close()}).on("error",function(){o.close()}).on("close",function(){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.unsubscribeWS(o)];case 1:return e.sent(),[2]}})})}),e.label=3;case 3:return[2]}})})}),setInterval(function(){return __awaiter(e,void 0,void 0,function(){var r,n,t,s,o,i,a,c=this;return __generator(this,function(e){switch(e.label){case 0:r=function(t){return __generator(this,function(e){switch(e.label){case 0:return t.pingTime&&2e4<=Date.now()-t.pingTime.getTime()?!1!==t.isAlive?[3,4]:(t.retryCnt++,3<=t.retryCnt?[4,n.unsubscribeWS(t)]:[3,2]):[3,5];case 1:return e.sent(),[3,3];case 2:t.pingTime=new Date,t.send("ping",function(r){return __awaiter(c,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(t)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),e.label=3;case 3:return[3,5];case 4:t.retryCnt=0,t.isAlive=!1,t.pingTime=new Date,t.send("ping",function(r){return __awaiter(c,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(t)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),e.label=5;case 5:return[2]}})},n=this,e.label=1;case 1:e.trys.push([1,6,7,8]),t=__values(this._serverWSS.clients),s=t.next(),e.label=2;case 2:return s.done?[3,5]:(o=s.value,[5,r(o)]);case 3:e.sent(),e.label=4;case 4:return s=t.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),i={error:o},[3,8];case 7:try{s&&!s.done&&(a=t.return)&&a.call(t)}finally{if(i)throw i.error}return[7];case 8:return[2]}})})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(i,a){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o;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]:(n=t.value,[4,this.handleClientMessage(i,n)]);case 3:e.sent(),e.label=4;case 4:return t=r.next(),[3,2];case 5:return[3,8];case 6:return n=e.sent(),s={error:n},[3,8];case 7:try{t&&!t.done&&(o=r.return)&&o.call(r)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},ResolveIOMainServer.prototype.handleClientMessage=function(f,m){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c,l,u,_,g,h,d,v,p;return __generator(this,function(e){switch(e.label){case 0:return(r=m[0],t=m[1],n=m[2],s=m[3],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||f.doc_user.roles.super_admin)?"subscription"!==s?[3,4]:(i=m[4],o=m[5],"sub"!==i?[3,2]:[4,this._subscriptionManager.subscribe(r,t,f,n,o,m.slice(6))]):[2];case 1:return e.sent(),[3,3];case 2:this._subscriptionManager.unsubscribe(r,t,f,n,o,m.slice(6)),e.label=3;case 3:return[3,22];case 4:if(this.publicProgram||"offline"!==s)return[3,16];i={messageId:n,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,i),this._offlineUpdates.push(f),a=m[4],c=0,e.label=5;case 5:if(!(c<a.length))return[3,15];if(l=a[c],l=l.data,l.shift(),l.shift(),p=l.shift(),l.shift(),u=l.shift(),p={messageId:p,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,p),"insertDocument"===u&&"driver-gps"===l[0])return[3,14];if("reportBuilderGetResults"!==u&&"reportBuilderGetDistinctValue"!==u&&"reportBuilderBuildTree"!==u&&"generatePDF"!==u&&"getWOOfflineData"!==u&&"countQuery"!==u&&"countWithQuery"!==u&&"countCollectionWithQuery"!==u&&"find"!==u&&"findOne"!==u&&"findWithOptions"!==u&&"getDrivers"!==u&&"processAirdropDistribution"!==u){if("https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL)return[3,6];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:u,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r}})}return[3,8];case 6:return[4,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:u,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r,client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 7:e.sent(),e.label=8;case 8:if(!this._methodManager._methods[u])return[3,13];e.label=9;case 9:return e.trys.push([9,11,,12]),[4,(p=this._methodManager.callMethod).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),u],__read(l),!1))];case 10:return e.sent(),[3,12];case 11:return d=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(d,null,2)),[3,12];case 12:return"updateDocumentOffline"!==u&&"updateDocumentPropsOffline"!==u||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,14];case 13:console.log("Offline - Could not find method: "+u),e.label=14;case 14:return c++,[3,5];case 15:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(f.id_socket),1),[3,22];case 16:if(_=__spreadArray([],__read(m),!1),_.shift(),_.shift(),g=_.shift(),"method"!==_.shift())return[3,22];if(h=_.shift(),f.user_readonly)return[2];if("reportBuilderGetResults"!==h&&"reportBuilderGetDistinctValue"!==h&&"reportBuilderBuildTree"!==h&&"generatePDF"!==h&&"getWOOfflineData"!==h&&"countQuery"!==h&&"countWithQuery"!==h&&"countCollectionWithQuery"!==h&&"find"!==h&&"findOne"!==h&&"findWithOptions"!==h&&"getDrivers"!==h&&"processAirdropDistribution"!==h){if("https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL)return[3,17];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:h,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r}})}return[3,19];case 17:return[4,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:h,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r,client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 18:e.sent(),e.label=19;case 19:return(d={messageId:g,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,d),v=this.findAvailableWorker(),this._isWorkersEnabled&&v&&"find"!==h&&"insertDocument"!==h&&"countWithQuery"!==h&&"findOne"!==h&&"updateDocumentProps"!==h&&"findWithOptions"!==h&&"updateDocument"!==h&&"insertErrorLog"!==h&&"removeDocument"!==h&&"supportCreateBillingUser"!==h&&"getSignedUrl"!==h&&"getSignedUrls"!==h&&"getSignedUrlWithId"!==h&&"incorrectUser"!==h&&"reloadWS"!==h&&"reconnectWS"!==h&&"disconnectWS"!==h)?(v="task-"+(0,common_1.objectIdHexString)(),this._inFlightRequests[v]={ws:f,messageId:g,method:h},this.queueTask(v,h,_,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),[3,22]):[3,20];case 20:return[4,this.callMethodLocally(f,g,h,_)];case 21:e.sent(),e.label=22;case 22:return[2]}})})},ResolveIOMainServer.prototype.callMethodLocally=function(s,o,i,a){return __awaiter(this,void 0,void 0,function(){var r,t,n;return __generator(this,function(e){switch(e.label){case 0:r={messageId:o,hasError:!1,data:null},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(n=this._methodManager.callMethod).call.apply(n,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:s.id_user,user:s.user,id_ws:s.id_socket}),i],__read(a),!1))];case 2:return n=e.sent(),r.data=n,[3,4];case 3:return t=e.sent(),r.hasError=!0,r.data=t||"Unknown error",[3,4];case 4:return s&&s.readyState===s.OPEN&&this._websocketManager.send(s,r),[2]}})})},ResolveIOMainServer.prototype.queueTask=function(e,r,t,n){this._taskQueue.push({taskId:e,method:r,params:t,userContext:n}),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,n,s,o;try{o=JSON.parse(t,common_1.dateReviver)}catch(e){return void console.error("Failed to parse worker message:",t)}"taskComplete"===o.type&&((t=this._workers.find(function(e){return e.id===r}))?(t.activeTasks=Math.max(0,t.activeTasks-1),t=o.taskId,e=o.error,n=o.message,o=o.result,(s=this._inFlightRequests[t])?(delete this._inFlightRequests[t],o={messageId:s.messageId,hasError:!1,data:o},e&&(o.hasError=!0,o.data=n),s.ws&&s.ws.readyState===s.ws.OPEN&&this._websocketManager.send(s.ws,o)):console.error("No in-flight request found for task:",t),this.dispatchQueue()):console.error("Unknown worker for taskComplete:",r))},ResolveIOMainServer.prototype.unsubscribeWS=function(r){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._subscriptionManager&&this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",r.user,r.id_socket),[4,this._subscriptionManager.unsubscribeAll(r)];case 1:return e.sent(),r.removeAllListeners(),r=null,[2]}})})},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,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(t){return function(e){var r=[t,e];if(o)throw new TypeError("Generator is already executing.");for(;c=l&&r[l=0]?0:c;)try{if(o=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))c.label=r[1];else if(6===r[0]&&c.label<a[1])c.label=a[1],a=r;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(r)}}r=s.call(n,c)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,s,o=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(n=o.next()).done;)i.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(t=o.return)&&t.call(o)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},bodyParser=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("body-parser")),express=require("express"),xmlParser=require("express-xml-bodyparser"),http_1=require("http"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),WebSocket=require("ws"),log_collection_1=require("./collections/log.collection"),user_collection_1=require("./collections/user.collection"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),monitor_manager_1=require("./managers/monitor.manager"),subscription_manager_1=require("./managers/subscription.manager"),common_1=require("./util/common"),mongodb_1=require("mongodb"),auth_1=require("./http/auth"),health_1=require("./http/health"),home_1=require("./http/home"),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={}}return ResolveIOMainServer.create=function(){return __awaiter(this,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return[4,(r=new ResolveIOMainServer).initialize()];case 1:return e.sent(),[2,r]}})})},ResolveIOMainServer.prototype.initialize=function(){return __awaiter(this,void 0,void 0,function(){var r,o,i=this;return __generator(this,function(e){switch(e.label){case 0:return this._serverStartTime=new Date,this._lastErrorMsg=null,r=this,[4,monitor_manager_1.MonitorManager.create()];case 1:return r._monitorManager=e.sent(),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){i._subscriptionManager&&i._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",i._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",i._debugMsgQueue)),i._debugMsgQueue=0,i._debugMsgRecv=0},6e4),o=!1,setTimeout(function(){o=!0},5e3),process.on("unhandledRejection",function(n,s){return __awaiter(i,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:n&&"MongoServerError"===n.name&&!o?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,11];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,11];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,11];case 9:return n?"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,11]:[3,11];case 10:e.sent(),e.label=11;case 11:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(i,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(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),process.on("SIGTERM",function(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),process.on("SIGQUIT",function(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=method_manager_1.MethodManager.create(null,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=cron_manager_1.CronManager.create(),this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=websocket_manager_1.WebSocketManager.create(this),this.startServerInstance(),this._methodManager=method_manager_1.MethodManager.create(this._websocketManager,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=subscription_manager_1.SubscriptionManager.create(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=websocket_manager_1.WebSocketManager.create(this),this.startServerInstance(),this._methodManager=method_manager_1.MethodManager.create(this._websocketManager,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=subscription_manager_1.SubscriptionManager.create(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=cron_manager_1.CronManager.create(),this.listen()),[2]}})})},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"!==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(){var e=this,r=(console.log(new Date,"Worker instance started, connecting to main server via WebSocket..."),resolveio_server_app_1.ResolveIOServer.getServerConfig().SERVER_URL+"/websocket?workerToken="+resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN),n=new WebSocket(r),s=null,t=null;n.on("open",function(){console.log(new Date,"Connected to main server as worker",process.env.WORKER_INDEX,process.env.NODE_APP_INSTANCE),e.sendWorkerResponse(n,"ping"),t=setInterval(function(){s?(s=null,e.sendWorkerResponse(n,"ping")):n.close()},15e3)}),n.on("message",function(t){return __awaiter(e,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return"ping"!==(t="string"!=typeof t?t.toString():t)?[3,1]:(this.sendWorkerResponse(n,"pong"),[3,4]);case 1:return"pong"!==t?[3,2]:(s=new Date,[3,4]);case 2:r=void 0;try{r=JSON.parse(t,common_1.dateReviver)}catch(e){return console.error("Worker parse error",e),[2]}return"task"!==r.type?[3,4]:[4,this.handleIncomingTask(n,r)];case 3:e.sent(),e.label=4;case 4:return[2]}})})}),n.on("close",function(){console.log(new Date,"Disconnected from main server. Reconnecting in 5s..."),setTimeout(function(){return e.startWorkerInstance},5e3),t&&clearInterval(t)}),n.on("error",function(e){console.error(new Date,"Worker WS error:",e),n.close()})},ResolveIOMainServer.prototype.handleIncomingTask=function(u,_){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c,l=this;return __generator(this,function(e){switch(e.label){case 0:if(r=_.taskId,t=_.method,n=_.params,s=_.userContext,this._runningTasks.push(r),!r||!t)return console.log("Invalid task message received",_),[2];o=!1,i=setTimeout(function(){return __awaiter(l,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return o=!0,console.error(new Date,"Worker timed out on task:",r,"Method:",t),console.error(new Date,"Error in Method: ".concat(t," - ").concat(JSON.stringify(_,null,2))),this.sendWorkerResponse(u,{type:"taskComplete",taskId:r,error:!0,message:"Task timed out"}),[4,this._methodManager.callMethod("insertErrorLog","Timeout in Method: ".concat(t," - ").concat(JSON.stringify(_,null,2)))];case 1:return e.sent(),[2]}})})},12e4),e.label=1;case 1:return e.trys.push([1,3,,5]),a=Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:(null==s?void 0:s.id_user)||"",user:(null==s?void 0:s.user)||"",id_ws:(null==s?void 0:s.id_ws)||""}),[4,(c=this._methodManager.callMethod).call.apply(c,__spreadArray([a,t],__read(n),!1))];case 2:return c=e.sent(),o||(clearTimeout(i),this.sendWorkerResponse(u,{type:"taskComplete",taskId:r,error:!1,result:c})),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,5];case 3:return a=e.sent(),o||(clearTimeout(i),console.error("Worker failed task:",r,"Method:",t,a),this.sendWorkerResponse(u,{type:"taskComplete",taskId:r,error:!0,message:a||"Unknown error"})),console.error(new Date,"Error in Method: ".concat(t," - ").concat(JSON.stringify(_,null,2))),[4,this._methodManager.callMethod("insertErrorLog","Error in Method: ".concat(t," - ").concat(JSON.stringify(_,null,2)))];case 4:return e.sent(),this._runningTasks=this._runningTasks.filter(function(e){return e!==r}),[3,5];case 5: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(){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:if(this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length||this._taskQueue.length||this._runningTasks.length)return[3,7];if(!resolveio_server_app_1.ResolveIOServer.getMongoConnection())return[3,5];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1)];case 2:return e.sent(),console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0),[3,4];case 3:return e.sent(),process.exit(1),[3,4];case 4:return[3,6];case 5:process.exit(0),e.label=6;case 6:return[3,8];case 7:this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){r._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){return __awaiter(r,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),e.label=8;case 8:return[2]}})})},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 r=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,o){var e;r._rebootFlag?o(!1,409,"Unable To Process"):("DEBUG"===r.LOGGER&&console.log("Verify Client",s,o),s.req.url&&s.req.url.includes("workerToken=")?(s.req.url.split("workerToken=")[1]||"")===resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN?o(!0):o(!1,401,"Unauthorized"):(e=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)&&(e=e[0])?jwt.verify(e,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,n){return __awaiter(r,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(o(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:s.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.req.doc_user=r,o(!0)):o(!1),[3,5];case 4:return e.sent(),o(!1),[3,5];case 5:return[2]}})})}):o(!1,401,"Unauthorized")))}})},ResolveIOMainServer.prototype.listen=function(){var e=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",e._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",e._portWSS)}),this._serverWSS.on("connection",function(o,i){return __awaiter(e,void 0,void 0,function(){var r,t,n,s=this;return __generator(this,function(e){switch(e.label){case 0:return i.url&&i.url.includes("workerToken=")?(r=(0,common_1.objectIdHexString)(),o.id_worker=r,this._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()}),[3,3]):[3,1];case 1:return o.id_socket=(0,common_1.objectIdHexString)(),o.id_user=i.id_user,o.user=i.user,o.user_readonly=i.user_readonly,o.doc_user=i.doc_user,this._websocketManager.addWebSocket(o),[4,this._subscriptionManager.createLoggedInUser(o.id_socket)];case 2:e.sent(),setTimeout(function(){o.pingTime=new Date,o.send("ping",function(r){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(o)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})})},5e3),"DEBUG"===this.LOGGER&&console.log("Connection from user: "+i.user),o.isAlive=!0,o.retryCnt=0,o.on("message",function(n){return __awaiter(s,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:this._debugMsgRecv+=1,r=[],e.label=1;case 1:return e.trys.push([1,2,,4]),r=JSON.parse(n,common_1.dateReviver),[3,4];case 2:return t=e.sent(),console.log("Error - JSON.parse",n),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n,t]))];case 3:return e.sent(),[2];case 4:return[4,this.processSocketMessage(o,r)];case 5:return e.sent(),[2]}})})}).on("end",function(){o.close()}).on("error",function(){o.close()}).on("close",function(){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.unsubscribeWS(o)];case 1:return e.sent(),[2]}})})}),e.label=3;case 3:return[2]}})})}),setInterval(function(){return __awaiter(e,void 0,void 0,function(){var r,n,t,s,o,i,a,c=this;return __generator(this,function(e){switch(e.label){case 0:r=function(t){return __generator(this,function(e){switch(e.label){case 0:return t.pingTime&&2e4<=Date.now()-t.pingTime.getTime()?!1!==t.isAlive?[3,4]:(t.retryCnt++,3<=t.retryCnt?[4,n.unsubscribeWS(t)]:[3,2]):[3,5];case 1:return e.sent(),[3,3];case 2:t.pingTime=new Date,t.send("ping",function(r){return __awaiter(c,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(t)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),e.label=3;case 3:return[3,5];case 4:t.retryCnt=0,t.isAlive=!1,t.pingTime=new Date,t.send("ping",function(r){return __awaiter(c,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(t)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),e.label=5;case 5:return[2]}})},n=this,e.label=1;case 1:e.trys.push([1,6,7,8]),t=__values(this._serverWSS.clients),s=t.next(),e.label=2;case 2:return s.done?[3,5]:(o=s.value,[5,r(o)]);case 3:e.sent(),e.label=4;case 4:return s=t.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),i={error:o},[3,8];case 7:try{s&&!s.done&&(a=t.return)&&a.call(t)}finally{if(i)throw i.error}return[7];case 8:return[2]}})})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(i,a){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o;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]:(n=t.value,[4,this.handleClientMessage(i,n)]);case 3:e.sent(),e.label=4;case 4:return t=r.next(),[3,2];case 5:return[3,8];case 6:return n=e.sent(),s={error:n},[3,8];case 7:try{t&&!t.done&&(o=r.return)&&o.call(r)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},ResolveIOMainServer.prototype.handleClientMessage=function(f,m){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c,l,u,_,g,h,d,v,p;return __generator(this,function(e){switch(e.label){case 0:return(r=m[0],t=m[1],n=m[2],s=m[3],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||f.doc_user.roles.super_admin)?"subscription"!==s?[3,4]:(i=m[4],o=m[5],"sub"!==i?[3,2]:[4,this._subscriptionManager.subscribe(r,t,f,n,o,m.slice(6))]):[2];case 1:return e.sent(),[3,3];case 2:this._subscriptionManager.unsubscribe(r,t,f,n,o,m.slice(6)),e.label=3;case 3:return[3,22];case 4:if(this.publicProgram||"offline"!==s)return[3,16];i={messageId:n,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,i),this._offlineUpdates.push(f),a=m[4],c=0,e.label=5;case 5:if(!(c<a.length))return[3,15];if(l=a[c],l=l.data,l.shift(),l.shift(),p=l.shift(),l.shift(),u=l.shift(),p={messageId:p,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,p),"insertDocument"===u&&"driver-gps"===l[0])return[3,14];if("reportBuilderGetResults"!==u&&"reportBuilderGetDistinctValue"!==u&&"reportBuilderBuildTree"!==u&&"generatePDF"!==u&&"getWOOfflineData"!==u&&"countQuery"!==u&&"countWithQuery"!==u&&"countCollectionWithQuery"!==u&&"find"!==u&&"findOne"!==u&&"findWithOptions"!==u&&"getDrivers"!==u&&"processAirdropDistribution"!==u){if("https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL)return[3,6];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:u,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r}})}return[3,8];case 6:return[4,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:u,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r,client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 7:e.sent(),e.label=8;case 8:if(!this._methodManager._methods[u])return[3,13];e.label=9;case 9:return e.trys.push([9,11,,12]),[4,(p=this._methodManager.callMethod).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),u],__read(l),!1))];case 10:return e.sent(),[3,12];case 11:return d=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(d,null,2)),[3,12];case 12:return"updateDocumentOffline"!==u&&"updateDocumentPropsOffline"!==u||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,14];case 13:console.log("Offline - Could not find method: "+u),e.label=14;case 14:return c++,[3,5];case 15:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(f.id_socket),1),[3,22];case 16:if(_=__spreadArray([],__read(m),!1),_.shift(),_.shift(),g=_.shift(),"method"!==_.shift())return[3,22];if(h=_.shift(),f.user_readonly)return[2];if("reportBuilderGetResults"!==h&&"reportBuilderGetDistinctValue"!==h&&"reportBuilderBuildTree"!==h&&"generatePDF"!==h&&"getWOOfflineData"!==h&&"countQuery"!==h&&"countWithQuery"!==h&&"countCollectionWithQuery"!==h&&"find"!==h&&"findOne"!==h&&"findWithOptions"!==h&&"getDrivers"!==h&&"processAirdropDistribution"!==h){if("https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL)return[3,17];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:h,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r}})}return[3,19];case 17:return[4,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:h,id_user:f.id_user||"",user:f.user||"",messageId:n,route:r,client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 18:e.sent(),e.label=19;case 19:return(d={messageId:g,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,d),v=this.findAvailableWorker(),this._isWorkersEnabled&&v&&"find"!==h&&"insertDocument"!==h&&"countWithQuery"!==h&&"findOne"!==h&&"updateDocumentProps"!==h&&"findWithOptions"!==h&&"updateDocument"!==h&&"insertErrorLog"!==h&&"removeDocument"!==h&&"supportCreateBillingUser"!==h&&"getSignedUrl"!==h&&"getSignedUrls"!==h&&"getSignedUrlWithId"!==h&&"incorrectUser"!==h&&"reloadWS"!==h&&"reconnectWS"!==h&&"disconnectWS"!==h)?(v="task-"+(0,common_1.objectIdHexString)(),this._inFlightRequests[v]={ws:f,messageId:g,method:h},this.queueTask(v,h,_,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),[3,22]):[3,20];case 20:return[4,this.callMethodLocally(f,g,h,_)];case 21:e.sent(),e.label=22;case 22:return[2]}})})},ResolveIOMainServer.prototype.callMethodLocally=function(s,o,i,a){return __awaiter(this,void 0,void 0,function(){var r,t,n;return __generator(this,function(e){switch(e.label){case 0:r={messageId:o,hasError:!1,data:null},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(n=this._methodManager.callMethod).call.apply(n,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:s.id_user,user:s.user,id_ws:s.id_socket}),i],__read(a),!1))];case 2:return n=e.sent(),r.data=n,[3,4];case 3:return t=e.sent(),r.hasError=!0,r.data=t||"Unknown error",[3,4];case 4:return s&&s.readyState===s.OPEN&&this._websocketManager.send(s,r),[2]}})})},ResolveIOMainServer.prototype.queueTask=function(e,r,t,n){this._taskQueue.push({taskId:e,method:r,params:t,userContext:n}),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,n,s,o;try{o=JSON.parse(t,common_1.dateReviver)}catch(e){return void console.error("Failed to parse worker message:",t)}"taskComplete"===o.type&&((t=this._workers.find(function(e){return e.id===r}))?(t.activeTasks=Math.max(0,t.activeTasks-1),t=o.taskId,e=o.error,n=o.message,o=o.result,(s=this._inFlightRequests[t])?(delete this._inFlightRequests[t],o={messageId:s.messageId,hasError:!1,data:o},e&&(o.hasError=!0,o.data=n),s.ws&&s.ws.readyState===s.ws.OPEN&&this._websocketManager.send(s.ws,o)):console.error("No in-flight request found for task:",t),this.dispatchQueue()):console.error("Unknown worker for taskComplete:",r))},ResolveIOMainServer.prototype.unsubscribeWS=function(r){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._subscriptionManager&&this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",r.user,r.id_socket),[4,this._subscriptionManager.unsubscribeAll(r)];case 1:return e.sent(),r.removeAllListeners(),r=null,[2]}})})},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
|