@resolveio/server-lib 20.6.13 → 20.6.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,i,o,s){return new(o=o||Promise)(function(n,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?n(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,i||[])).next())})},__generator=this&&this.__generator||function(i,o){var s,r,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(n){return function(e){var t=[n,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,r&&(a=2&t[0]?r.return:t[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,t[1])).done)return a;switch(r=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,r=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=o.call(i,c)}catch(e){t=[6,e],r=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&i>=e.length?void 0:e)&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,o,s=n.call(e),r=[];try{for(;(void 0===t||0<t--)&&!(i=s.next()).done;)r.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return r},__spreadArray=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var i,o=0,s=t.length;o<s;o++)!i&&o in t||((i=i||Array.prototype.slice.call(t,0,o))[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))},logs_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0,require("../publications/logs")),app_status_1=require("../publications/app-status"),files_1=require("../publications/files"),super_admin_1=require("../publications/super-admin"),logged_in_users_collection_1=require("../collections/logged-in-users.collection"),cron_jobs_1=require("../publications/cron-jobs"),flags_1=require("../publications/flags"),method_responses_1=require("../publications/method-responses"),resolveio_server_app_1=require("../resolveio-server-app"),notifications_1=require("../publications/notifications"),report_builder_reports_1=require("../publications/report-builder-reports"),report_builder_libraries_1=require("../publications/report-builder-libraries"),user_groups_1=require("../publications/user-groups"),user_guides_1=require("../publications/user-guides"),report_builder_dashboard_builders_1=require("../publications/report-builder-dashboard-builders"),common_1=require("../util/common"),NodeCache=require("node-cache"),flag_collection_1=require("../collections/flag.collection"),os_1=require("os"),flags_update_1=require("../publications/flags-update"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(e,t,n){var i=this;this._publications={},this._subscriptions=[],this._loggedInUsers=[],this._mongoQueue=[],this._mongoQueueId=0,this._cacheId=1,this._heapSize=v8.getHeapStatistics()/numCPUs,this._enableDebug=!1,this._debugOplogCollections=[],this._debugOplogHits=0,this._debugSubCollections=[],this._debugSubHits=0,this._debugUnSubHits=0,this._debugUnSubAllHits=0,this._debugMongoQueueHits=0,this._debugMongoQueueCollections=[],this._debugSendQueueHits=0,this._debugRemoveCacheHits=0,this._oplogRetryCount=0,this.latencyBuffer=new Map,this.LATENCY_UPDATE_INTERVAL=6e4,this.LATENCY_UPDATE_THRESHOLD_MS=3e4,this._websocketManager=resolveio_server_app_1.ResolveIOServer.getMainServer().getWebSocketManager(),this._monitorManagerFunction=n,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),setInterval(function(){return i.flushThrottledLatencyUpdates()},this.LATENCY_UPDATE_INTERVAL),this.serverConfig=t,this._wss=e,(0,super_admin_1.loadSuperAdminPublications)(this),(0,app_status_1.loadAppStatusPublications)(this),(0,logs_1.loadLogPublications)(this),(0,files_1.loadFilePublications)(this),(0,cron_jobs_1.loadCronJobPublications)(this),(0,flags_update_1.loadFlagsUpdatePublications)(this),(0,flags_1.loadFlagsPublications)(this),(0,method_responses_1.loadMethodResponsePublications)(this),(0,notifications_1.loadNotificationPublications)(this),(0,report_builder_reports_1.loadReportBuilderReportPublications)(this),(0,report_builder_libraries_1.loadReportBuilderLibraryPublications)(this),(0,user_groups_1.loadUserGroupPublications)(this),(0,user_guides_1.loadUserGuidePublications)(this),(0,report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this),this.tailOpLog(),setInterval(function(){i._oplogRetryCount=0},15e3),setInterval(function(){i.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",i._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",i._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",i._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",i._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(i._debugMongoQueueCollections.sort(function(e,t){return e.collection.localeCompare(t.collection)||e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Oplog Hits",i._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(i._debugOplogCollections.sort(function(e,t){return e.collection.localeCompare(t.collection)||e.type.localeCompare(t.type)}),null,2)),console.log(new Date,"Sub Manager","Send Queue Hits",i._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",i._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(i._debugSubCollections.sort(function(e,t){return e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",i._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",i._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",i._debugRemoveCacheHits)),i._debugOplogHits=0,i._debugOplogCollections=[],i._debugSubCollections=[],i._debugMongoQueueHits=0,i._debugMongoQueueCollections=[],i._debugSendQueueHits=0,i._debugSubHits=0,i._debugUnSubHits=0,i._debugUnSubAllHits=0,i._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(i,void 0,void 0,function(){var t,i,n,o,s,r,a,c,l;return __generator(this,function(e){switch(e.label){case 0:return t=this,[4,logged_in_users_collection_1.LoggedInUsers.find()];case 1:for(t._loggedInUsers=e.sent(),i=(0,common_1.deepCopy)(this._loggedInUsers),n=function(e){var n=i[e];(!n.date||12e4<Date.now()-n.date.getTime())&&(o._websocketManager.getWebSocket(n.id_ws)?(o.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",o._websocketManager.getWebSocket(n.id_ws).user,o._websocketManager.getWebSocket(n.id_ws).id_socket,2),o.unsubscribeAll(o._websocketManager.getWebSocket(n.id_ws))):(o._subscriptions.forEach(function(e){for(var t=e.clients.length-1;0<=t;t--)e.clients[t].id_socket===n.id_ws&&e.clients.splice(t,1)}),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:n._id}),0<=o._loggedInUsers.findIndex(function(e){return e._id===n._id})&&o._loggedInUsers.splice(o._loggedInUsers.findIndex(function(e){return e._id===n._id}),1)))},s=(o=this)._loggedInUsers.length-1;0<=s;s--)n(s);for(s=0;s<this._subscriptions.length;s++)for(r=this._subscriptions[s],a=function(e){var t=r.clients[e];c._loggedInUsers.some(function(e){return e.id_ws===t.id_socket})||r.clients.splice(e,1)},c=this,l=r.clients.length-1;0<=l;l--)a(l);return[2]}})})},3e4),flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?i._enableDebug=!0:i._enableDebug=!1}),this.setCacheLimit()}return SubscriptionManager.prototype.setCacheLimit=function(){"true"===process.env.IS_WORKERS_ENABLED?this._heapLimit=.4*this._heapSize:this._heapLimit=.3*this._heapSize},SubscriptionManager.prototype.invalidatePubsCache=function(u,g){return __awaiter(this,void 0,void 0,function(){var t,n,o,i,s,r,a,c,l=this;return __generator(this,function(e){resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u),t=this._subscriptions.filter(function(e){return e.collections.includes(u)}),n=function(i){if(o._enableDebug&&console.log(new Date,"Invalidate Sub",i.publication,i.running,i.runAgain),i.running)return i.runAgain=!0,"continue";o._publications[i.publication].user_specific?Promise.all(i.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t;return __generator(this,function(e){if((t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN)try{this.sendDataToOneWithRetry(t,n.messageId,i,u,g)}catch(e){resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - User Specific - Socket: "+n.id_socket+", User: "+n.id_user+", MessageId: "+n.messageId+", Pub: "+i.publication+", Err: "+JSON.stringify(e,null,2))}return[2]})})})):o.sendDataToAllWithRetry(i,u,g)},o=this;try{for(i=__values(t),s=i.next();!s.done;s=i.next())r=s.value,n(r)}catch(e){a={error:e}}finally{try{s&&!s.done&&(c=i.return)&&c.call(i)}finally{if(a)throw a.error}}return[2]})})},SubscriptionManager.prototype.delay=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){return setTimeout(e,t)})]})})},SubscriptionManager.prototype.sendDataToAllWithRetry=function(t,n,i){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:t.running=!0,e.label=1;case 1:return this._enableDebug&&console.log(new Date,"Running sendDataToAll Sub",t.publication),t.runAgain=!1,[4,this.sendDataToAll(t,n,i)];case 2:return(e.sent(),this._enableDebug&&console.log(new Date,"Done sendDataToAll Sub",t.publication,t.runAgain),t.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(t.runAgain)return[3,1];e.label=5;case 5:return t.running=!1,[2]}})})},SubscriptionManager.prototype.sendDataToOneWithRetry=function(t,n,i,o,s){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:i.running=!0,e.label=1;case 1:return this._enableDebug&&console.log(new Date,"Running sendDataToOne Sub",i.publication),i.runAgain=!1,[4,this.sendDataToOne(t,n,i,o,s)];case 2:return(e.sent(),this._enableDebug&&console.log(new Date,"Done sendDataToOne Sub",i.publication,i.runAgain),i.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(i.runAgain)return[3,1];e.label=5;case 5:return i.running=!1,[2]}})})},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(t){var e,n,i,o=this._loggedInUsers.find(function(e){return e.id_ws===t.id_socket});o&&(e=new Date,n=this.latencyBuffer.get(t.id_socket),i=t.latency,!n||e.getTime()-n.lastUpdate.getTime()>=this.LATENCY_UPDATE_THRESHOLD_MS||100<Math.abs(i-n.latency))&&(o.date=e,this.latencyBuffer.set(t.id_socket,{latency:i,lastUpdate:e}))},SubscriptionManager.prototype.flushThrottledLatencyUpdates=function(){return __awaiter(this,void 0,void 0,function(){var t,n;return __generator(this,function(e){switch(e.label){case 0:if(0===this.latencyBuffer.size)return[2];t=Array.from(this.latencyBuffer.entries()).map(function(e){var e=__read(e,2),t=e[0],e=e[1];return{updateOne:{filter:{id_ws:t},update:{$set:{latency:e.latency,date:e.lastUpdate}}}}}),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,logged_in_users_collection_1.LoggedInUsers.bulkWrite(t)];case 2:return e.sent(),this.latencyBuffer.clear(),this.getEnableDebug()&&console.log(new Date,"Sub Manager","Throttled latency batch update successful",t.length),[3,4];case 3:return n=e.sent(),console.error(new Date,"Sub Manager","Throttled latency batch update failed",n),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.subscribe=function(t,e,n,i,o,s){var r=this,a=(this._debugSubHits+=1,this._debugSubCollections.some(function(e){return e.publication===o})?this._debugSubCollections.find(function(e){return e.publication===o}).hits+=1:this._debugSubCollections.push({publication:o,hits:1}),this._publications[o]);if(a){if(1<s.length||s[0]){if(!a.check)return void console.error(new Date,"No Check Function For Pub "+o);if(!a.check._schema)return void console.error(new Date,"No Check Schema For Pub "+o);for(var c={},l=Object.keys(a.check._schema).filter(function(e){return!e.includes(".")}),u=0;u<s.length;u++)c[l[u]]=s[u];try{a.check.validate(c)}catch(e){if(e)return void console.error(new Date,"Error in Pub Check ("+o+")",e)}}"Bypass"!==t&&(a=t.split("/"),g="",_=a[0],""===a[0]&&(g="/",_=a[1]),g+=_,1<a.length&&(g+="/"),(_=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===n.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==t&&!e.messageRoute.startsWith(g)})})).length)&&(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Detected Undestroyed Subscription - "+this.serverConfig.CLIENT_NAME,"USER: "+n.user+" (Socket: "+n.id_socket+") is on route: "+t+" but has the following subscriptions on other routes:"+JSON.stringify(_,null,2)),_.forEach(function(t){t.clients.filter(function(e){return e.id_socket===n.id_socket}).forEach(function(e){r.unsubscribe(e.messageRoute,new Date,n,e.messageId,t.publication,t.subscriptionData)})}));var g,_,a=this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)});a?a.clients.some(function(e){return e.id_socket===n.id_socket&&e.messageId===i})||a.clients.push({id_user:n.id_user,messageId:i,id_socket:n.id_socket,messageRoute:t}):this._subscriptions.push({publication:o,subscriptionData:s,collections:this.getPublicationCollections(o),clients:[{id_user:n.id_user,messageId:i,id_socket:n.id_socket,messageRoute:t}],cacheId:0,running:!1,runAgain:!1}),a=a||this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)}),this._enableDebug&&console.log(new Date,"New Sub",a.publication,a.running,a.runAgain,a.clients.length),this.processSubscription(a,n,i)}else console.error(new Date,"No Publication: "+o)},SubscriptionManager.prototype.createLoggedInUser=function(i){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return[2,new Promise(function(n,e){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i))?(t={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:t.id_user,user:t.user,id_ws:t.id_socket},this._loggedInUsers.push(t),logged_in_users_collection_1.LoggedInUsers.insertOne(t),n(t)):n(null),[2]})})})]})})},SubscriptionManager.prototype.unsubscribe=function(e,t,n,i,o,s){if(this._debugUnSubHits+=1,this._publications[o]){var r=this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)});if(r){for(var a=r.clients.length-1;0<=a;a--)r.clients[a].id_user===n.id_user&&r.clients[a].messageId===i&&r.clients[a].id_socket===n.id_socket&&r.clients.splice(a,1);this._enableDebug&&console.log(new Date,"Unsub",r.publication,r.running,r.runAgain,r.clients.length)}}else console.log("No Publication: "+o)},SubscriptionManager.prototype.unsubscribeAll=function(s){return __awaiter(this,void 0,void 0,function(){var t,n,i,o;return __generator(this,function(e){if(this._debugUnSubAllHits+=1,s){if(s.isUnsubscribed)return[2];for(s.isUnsubscribed=!0,0<=this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(s.id_socket)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(s.id_socket),1),logged_in_users_collection_1.LoggedInUsers.deleteOne({id_ws:s.id_socket}),t=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_user===s.id_user&&e.id_socket===s.id_socket})}),n=t.length-1;0<=n;n--)for(i=t[n],o=i.clients.length-1;0<=o;o--)i.clients[o].id_socket===s.id_socket&&i.clients.splice(o,1);this._websocketManager.removeWebSocket(s)}return[2]})})},SubscriptionManager.prototype.getActiveSubscriptions=function(){return this._subscriptions},SubscriptionManager.prototype.getPublicationCollections=function(e){return this._publications[e].collections},SubscriptionManager.prototype.tailOpLog=function(o){return __awaiter(this,void 0,void 0,function(){var t,n,i=this;return __generator(this,function(e){switch(e.label){case 0:return this._oplog$&&!this._oplog$.closed&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:if(e.sent(),!this._oplog$||this._oplog$.closed){if(this._oplogRetryCount+=1,5<this._oplogRetryCount&&(console.error("****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************"),process.exit(1)),t=[{$match:{$and:[{"ns.coll":{$nin:["logs"]}},{"ns.coll":{$not:/.*\.versions$/}},{"ns.coll":{$not:/^monitor-/}}]}}],o){n=o;try{this._oplog$=resolveio_server_app_1.ResolveIOServer.getMainDB().watch(t,{resumeAfter:o})}catch(e){return this._oplog$&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),this.tailOpLog(o),[2]}}else this._oplog$=resolveio_server_app_1.ResolveIOServer.getMainDB().watch(t);console.log(new Date,"oplog started"),this._oplog$.on("change",function(t){var e;t.ns&&(i._enableDebug&&console.log(new Date,"Oplog Hit",t.ns),e=t.ns.coll,i._debugOplogCollections.some(function(e){return e.collection===t.ns.coll&&e.type===t.operationType})?i._debugOplogCollections.find(function(e){return e.collection===t.ns.coll&&e.type===t.operationType}).hits+=1:i._debugOplogCollections.push({collection:t.ns.coll,type:t.operationType,hits:1}),e&&(i._debugOplogHits+=1,"insert"===t.operationType?("support-tickets"===e&&"https://resolveio.com"===i.serverConfig.ROOT_URL&&(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"sendSupportTicketEmail",t.documentKey._id),i.invalidatePubsCache(e,"insert")),"method-responses"!==e&&i.invalidatePubsCache(e,"insert")):"update"===t.operationType||"replace"===t.operationType?"method-responses"!==e&&i.invalidatePubsCache(e,"update"):"delete"===t.operationType&&"method-responses"!==e&&i.invalidatePubsCache(e,"delete")),"flags"===e&&flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?i._enableDebug=!0:i._enableDebug=!1}),n=t._id,process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||"false"!==process.env.IS_WORKERS_ENABLED&&"true"===process.env.IS_WORKER_INSTANCE&&process.env.WORKER_INDEX)}),this._oplog$.on("error",function(e){console.log(new Date,"oplog error",e),i._oplog$.removeAllListeners(),i._oplog$.close(),i._oplog$=null,i.tailOpLog(n)}),this._oplog$.on("end",function(){console.log(new Date,"oplog end"),i._oplog$.removeAllListeners(),i._oplog$.close(),i._oplog$=null,i.tailOpLog(n)}),this._oplog$.on("close",function(){console.log(new Date,"oplog close"),i._oplog$.removeAllListeners(),i._oplog$=null,i.tailOpLog(n)})}return[2]}})})},SubscriptionManager.prototype.processSubscription=function(i,o,s){return __awaiter(this,void 0,void 0,function(){var t,n;return __generator(this,function(e){if(this._publications[i.publication].user_specific){if(this._enableDebug&&console.log(new Date,"Process Sub Specific, Non - Cache",i.publication,i.running),i.running)return[2];this.sendDataToOneWithRetry(o,s,i,"","newSub")}else if(i.cacheId)try{t=JSON.parse(this._nodeCache.get(i.cacheId),common_1.dateReviver),n={messageId:s,hasError:!1,data:t},this._enableDebug&&console.log(new Date,"Process Sub, Cache",i.publication),this.sendWS(o,n)}catch(e){this._nodeCache.del(i.cacheId),i.cacheId=0,this.sendDataToAllWithRetry(i,"","newSub")}else{if(this._enableDebug&&console.log(new Date,"Process Sub, Non - Cache",i.publication,i.running),i.running)return[2];this.sendDataToAllWithRetry(i,"","newSub")}return[2]})})},SubscriptionManager.prototype.sendDataToOne=function(s,r,a,c,l){return __awaiter(this,void 0,void 0,function(){var t,n,i,o;return __generator(this,function(e){switch(e.label){case 0:t=this._monitorManagerFunction.startMonitorFunction("User Specific Publication",a.publication,"","",a.subscriptionData),e.label=1;case 1:return e.trys.push([1,3,,4]),resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"insertSubscriptionLog",l,a.publication,c,JSON.stringify(a.subscriptionData)),[4,(o=this._publications[a.publication].function).call.apply(o,__spreadArray([Object.assign({},this,SubscriptionManager.prototype),s.id_user],__read(a.subscriptionData),!1))];case 2:return o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),i={messageId:r,hasError:!1,data:o},this.sendWS(s,i),[3,4];case 3:return n=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),i={messageId:r,hasError:!0,data:n},this.sendWS(s,i),resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+a.publication+" - (sendDataToOne - WS)\n\nData \n"+JSON.stringify(a.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(n,null,2)),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.sendDataToAll=function(g,_,d){return __awaiter(this,void 0,void 0,function(){var t,o,n,i,s,r,a,c,l,u=this;return __generator(this,function(e){switch(e.label){case 0:return g.clients.length?[3,1]:(g.cacheId&&(this._nodeCache.del(g.cacheId),g.cacheId=0),0<=(l=this._subscriptions.findIndex(function(e){return e.publication===g.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(g.subscriptionData)}))&&this._subscriptions.splice(l,1),[2]);case 1:t=this._monitorManagerFunction.startMonitorFunction("Publication",g.publication,"","",g.subscriptionData),e.label=2;case 2:return e.trys.push([2,4,,5]),"superadminAPM"!==g.publication&&"loggedInUsers"!==g.publication&&resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"insertSubscriptionLog",d,g.publication,_,JSON.stringify(g.subscriptionData)),[4,(l=this._publications[g.publication].function).call.apply(l,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],__read(g.subscriptionData),!1))];case 3:if(o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),g.cacheId)try{n=JSON.parse(this._nodeCache.get(g.cacheId),common_1.dateReviver),JSON.stringify(n)!==JSON.stringify(o)&&(Promise.all(g.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t,n;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN&&(n={messageId:i.messageId,hasError:!1,data:o},this.sendWS(t,n)),[2]})})})),this._nodeCache.del(g.cacheId),(0,common_1.getBinarySize)(JSON.stringify(o))<1e6&&!g.collections.includes("logs")&&!g.collections.find(function(e){return e.endsWith(".versions")})&&!g.collections.find(function(e){return e.startsWith("monitor-")})?this._nodeCache.set(g.cacheId,JSON.stringify(o)):g.cacheId=0)}catch(e){Promise.all(g.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t,n;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN&&(n={messageId:i.messageId,hasError:!1,data:o},this.sendWS(t,n)),[2]})})})),this._nodeCache.del(g.cacheId),(0,common_1.getBinarySize)(JSON.stringify(o))<1e6&&!g.collections.includes("logs")&&!g.collections.find(function(e){return e.endsWith(".versions")})&&!g.collections.find(function(e){return e.startsWith("monitor-")})?this._nodeCache.set(g.cacheId,JSON.stringify(o)):g.cacheId=0}else if(Promise.all(g.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t,n;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN&&(n={messageId:i.messageId,hasError:!1,data:o},this.sendWS(t,n)),[2]})})})),(0,common_1.getBinarySize)(JSON.stringify(o))<1e6&&!g.collections.includes("logs")&&!g.collections.find(function(e){return e.endsWith(".versions")})&&!g.collections.find(function(e){return e.startsWith("monitor-")})){if(g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o)),(i=this._nodeCache.getStats().vsize)>this._heapLimit){for(s=0,r=this._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),a=0;a<r.length&&(this._debugRemoveCacheHits+=1,this._nodeCache.del(r[a].cacheId),r[a].cacheId=0,s+=1,!(this._nodeCache.getStats().vsize<.75*this._heapLimit));a++);this._enableDebug&&console.log("Sub Cache: Too Big - "+g.publication+" - Deleted: "+s+" - "+i)}}else g.cacheId=0;return[3,5];case 4:return c=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),Promise.all(g.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t,n;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN&&(n={messageId:i.messageId,hasError:!0,data:c},this.sendWS(t,n)),[2]})})})),resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+g.publication+" - (sendPubData)\n\nData \n"+JSON.stringify(g.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(c,null,2)),[3,5];case 5:return[2]}})})},SubscriptionManager.prototype.sendWS=function(e,t){this._websocketManager.send(e,t)},SubscriptionManager.prototype.getEnableDebug=function(){return this._enableDebug},SubscriptionManager}();exports.SubscriptionManager=SubscriptionManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,i,o,s){return new(o=o||Promise)(function(n,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?n(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,i||[])).next())})},__generator=this&&this.__generator||function(i,o){var s,r,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(n){return function(e){var t=[n,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,r&&(a=2&t[0]?r.return:t[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,t[1])).done)return a;switch(r=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,r=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=o.call(i,c)}catch(e){t=[6,e],r=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&i>=e.length?void 0:e)&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,o,s=n.call(e),r=[];try{for(;(void 0===t||0<t--)&&!(i=s.next()).done;)r.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return r},__spreadArray=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var i,o=0,s=t.length;o<s;o++)!i&&o in t||((i=i||Array.prototype.slice.call(t,0,o))[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))},logs_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0,require("../publications/logs")),app_status_1=require("../publications/app-status"),files_1=require("../publications/files"),super_admin_1=require("../publications/super-admin"),logged_in_users_collection_1=require("../collections/logged-in-users.collection"),cron_jobs_1=require("../publications/cron-jobs"),flags_1=require("../publications/flags"),method_responses_1=require("../publications/method-responses"),resolveio_server_app_1=require("../resolveio-server-app"),notifications_1=require("../publications/notifications"),report_builder_reports_1=require("../publications/report-builder-reports"),report_builder_libraries_1=require("../publications/report-builder-libraries"),user_groups_1=require("../publications/user-groups"),user_guides_1=require("../publications/user-guides"),report_builder_dashboard_builders_1=require("../publications/report-builder-dashboard-builders"),common_1=require("../util/common"),NodeCache=require("node-cache"),flag_collection_1=require("../collections/flag.collection"),os_1=require("os"),flags_update_1=require("../publications/flags-update"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(e,t,n){var i=this;this._publications={},this._subscriptions=[],this._loggedInUsers=[],this._mongoQueue=[],this._mongoQueueId=0,this._cacheId=1,this._heapSize=v8.getHeapStatistics()/numCPUs,this._enableDebug=!1,this._debugOplogCollections=[],this._debugOplogHits=0,this._debugSubCollections=[],this._debugSubHits=0,this._debugUnSubHits=0,this._debugUnSubAllHits=0,this._debugMongoQueueHits=0,this._debugMongoQueueCollections=[],this._debugSendQueueHits=0,this._debugRemoveCacheHits=0,this._oplogRetryCount=0,this.latencyBuffer=new Map,this.LATENCY_UPDATE_INTERVAL=6e4,this.LATENCY_UPDATE_THRESHOLD_MS=3e4,this._websocketManager=resolveio_server_app_1.ResolveIOServer.getMainServer().getWebSocketManager(),this._monitorManagerFunction=n,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),setInterval(function(){return i.flushThrottledLatencyUpdates()},this.LATENCY_UPDATE_INTERVAL),this.serverConfig=t,this._wss=e,(0,super_admin_1.loadSuperAdminPublications)(this),(0,app_status_1.loadAppStatusPublications)(this),(0,logs_1.loadLogPublications)(this),(0,files_1.loadFilePublications)(this),(0,cron_jobs_1.loadCronJobPublications)(this),(0,flags_update_1.loadFlagsUpdatePublications)(this),(0,flags_1.loadFlagsPublications)(this),(0,method_responses_1.loadMethodResponsePublications)(this),(0,notifications_1.loadNotificationPublications)(this),(0,report_builder_reports_1.loadReportBuilderReportPublications)(this),(0,report_builder_libraries_1.loadReportBuilderLibraryPublications)(this),(0,user_groups_1.loadUserGroupPublications)(this),(0,user_guides_1.loadUserGuidePublications)(this),(0,report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this),this.tailOpLog(),setInterval(function(){i._oplogRetryCount=0},15e3),setInterval(function(){i.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",i._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",i._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",i._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",i._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(i._debugMongoQueueCollections.sort(function(e,t){return e.collection.localeCompare(t.collection)||e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Oplog Hits",i._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(i._debugOplogCollections.sort(function(e,t){return e.collection.localeCompare(t.collection)||e.type.localeCompare(t.type)}),null,2)),console.log(new Date,"Sub Manager","Send Queue Hits",i._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",i._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(i._debugSubCollections.sort(function(e,t){return e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",i._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",i._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",i._debugRemoveCacheHits)),i._debugOplogHits=0,i._debugOplogCollections=[],i._debugSubCollections=[],i._debugMongoQueueHits=0,i._debugMongoQueueCollections=[],i._debugSendQueueHits=0,i._debugSubHits=0,i._debugUnSubHits=0,i._debugUnSubAllHits=0,i._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(i,void 0,void 0,function(){var t,i,n,o,s,r,a,c,l;return __generator(this,function(e){switch(e.label){case 0:return t=this,[4,logged_in_users_collection_1.LoggedInUsers.find()];case 1:for(t._loggedInUsers=e.sent(),i=(0,common_1.deepCopy)(this._loggedInUsers),n=function(e){var n=i[e];(!n.date||12e4<Date.now()-n.date.getTime())&&(o._websocketManager.getWebSocket(n.id_ws)?(o.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",o._websocketManager.getWebSocket(n.id_ws).user,o._websocketManager.getWebSocket(n.id_ws).id_socket,2),o.unsubscribeAll(o._websocketManager.getWebSocket(n.id_ws))):(o._subscriptions.forEach(function(e){for(var t=e.clients.length-1;0<=t;t--)e.clients[t].id_socket===n.id_ws&&e.clients.splice(t,1)}),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:n._id}),0<=o._loggedInUsers.findIndex(function(e){return e._id===n._id})&&o._loggedInUsers.splice(o._loggedInUsers.findIndex(function(e){return e._id===n._id}),1)))},s=(o=this)._loggedInUsers.length-1;0<=s;s--)n(s);for(s=0;s<this._subscriptions.length;s++)for(r=this._subscriptions[s],a=function(e){var t=r.clients[e];c._loggedInUsers.some(function(e){return e.id_ws===t.id_socket})||r.clients.splice(e,1)},c=this,l=r.clients.length-1;0<=l;l--)a(l);return[2]}})})},3e4),flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?i._enableDebug=!0:i._enableDebug=!1}),this.setCacheLimit()}return SubscriptionManager.prototype.setCacheLimit=function(){"true"===process.env.IS_WORKERS_ENABLED?this._heapLimit=.4*this._heapSize:this._heapLimit=.3*this._heapSize},SubscriptionManager.prototype.invalidatePubsCache=function(u,g){return __awaiter(this,void 0,void 0,function(){var t,n,o,i,s,r,a,c,l=this;return __generator(this,function(e){resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u),t=this._subscriptions.filter(function(e){return e.collections.includes(u)}),n=function(i){if(o._enableDebug&&console.log(new Date,"Invalidate Sub",i.publication,i.running,i.runAgain),i.running)return i.runAgain=!0,"continue";o._publications[i.publication].user_specific?Promise.all(i.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t;return __generator(this,function(e){if((t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN)try{this.sendDataToOneWithRetry(t,n.messageId,i,u,g)}catch(e){resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - User Specific - Socket: "+n.id_socket+", User: "+n.id_user+", MessageId: "+n.messageId+", Pub: "+i.publication+", Err: "+JSON.stringify(e,null,2))}return[2]})})})):o.sendDataToAllWithRetry(i,u,g)},o=this;try{for(i=__values(t),s=i.next();!s.done;s=i.next())r=s.value,n(r)}catch(e){a={error:e}}finally{try{s&&!s.done&&(c=i.return)&&c.call(i)}finally{if(a)throw a.error}}return[2]})})},SubscriptionManager.prototype.delay=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){return setTimeout(e,t)})]})})},SubscriptionManager.prototype.sendDataToAllWithRetry=function(t,n,i){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:t.running=!0,e.label=1;case 1:return this._enableDebug&&console.log(new Date,"Running sendDataToAll Sub",t.publication),t.runAgain=!1,[4,this.sendDataToAll(t,n,i)];case 2:return(e.sent(),this._enableDebug&&console.log(new Date,"Done sendDataToAll Sub",t.publication,t.runAgain),t.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(t.runAgain)return[3,1];e.label=5;case 5:return t.running=!1,[2]}})})},SubscriptionManager.prototype.sendDataToOneWithRetry=function(t,n,i,o,s){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:i.running=!0,e.label=1;case 1:return this._enableDebug&&console.log(new Date,"Running sendDataToOne Sub",i.publication),i.runAgain=!1,[4,this.sendDataToOne(t,n,i,o,s)];case 2:return(e.sent(),this._enableDebug&&console.log(new Date,"Done sendDataToOne Sub",i.publication,i.runAgain),i.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(i.runAgain)return[3,1];e.label=5;case 5:return i.running=!1,[2]}})})},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(t){var e,n,i,o=this._loggedInUsers.find(function(e){return e.id_ws===t.id_socket});o&&(e=new Date,n=this.latencyBuffer.get(t.id_socket),i=t.latency,!n||e.getTime()-n.lastUpdate.getTime()>=this.LATENCY_UPDATE_THRESHOLD_MS||100<Math.abs(i-n.latency))&&(o.date=e,this.latencyBuffer.set(t.id_socket,{latency:i,lastUpdate:e}))},SubscriptionManager.prototype.flushThrottledLatencyUpdates=function(){return __awaiter(this,void 0,void 0,function(){var t,n;return __generator(this,function(e){switch(e.label){case 0:if(0===this.latencyBuffer.size)return[2];t=Array.from(this.latencyBuffer.entries()).map(function(e){var e=__read(e,2),t=e[0],e=e[1];return{updateOne:{filter:{id_ws:t},update:{$set:{latency:e.latency,date:e.lastUpdate}}}}}),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,logged_in_users_collection_1.LoggedInUsers.bulkWrite(t)];case 2:return e.sent(),this.latencyBuffer.clear(),this.getEnableDebug()&&console.log(new Date,"Sub Manager","Throttled latency batch update successful",t.length),[3,4];case 3:return n=e.sent(),console.error(new Date,"Sub Manager","Throttled latency batch update failed",n),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.subscribe=function(t,e,n,i,o,s){var r=this,a=(this._debugSubHits+=1,this._debugSubCollections.some(function(e){return e.publication===o})?this._debugSubCollections.find(function(e){return e.publication===o}).hits+=1:this._debugSubCollections.push({publication:o,hits:1}),this._publications[o]);if(a){if(1<s.length||s[0]){if(!a.check)return void console.error(new Date,"No Check Function For Pub "+o);if(!a.check._schema)return void console.error(new Date,"No Check Schema For Pub "+o);for(var c={},l=Object.keys(a.check._schema).filter(function(e){return!e.includes(".")}),u=0;u<s.length;u++)c[l[u]]=s[u];try{a.check.validate(c)}catch(e){if(e)return void console.error(new Date,"Error in Pub Check ("+o+")",e)}}"Bypass"!==t&&(a=t.split("/"),g="",_=a[0],""===a[0]&&(g="/",_=a[1]),g+=_,1<a.length&&(g+="/"),(_=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===n.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==t&&!e.messageRoute.startsWith(g)})})).length)&&_.forEach(function(t){t.clients.filter(function(e){return e.id_socket===n.id_socket}).forEach(function(e){r.unsubscribe(e.messageRoute,new Date,n,e.messageId,t.publication,t.subscriptionData)})});var g,_,a=this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)});a?a.clients.some(function(e){return e.id_socket===n.id_socket&&e.messageId===i})||a.clients.push({id_user:n.id_user,messageId:i,id_socket:n.id_socket,messageRoute:t}):this._subscriptions.push({publication:o,subscriptionData:s,collections:this.getPublicationCollections(o),clients:[{id_user:n.id_user,messageId:i,id_socket:n.id_socket,messageRoute:t}],cacheId:0,running:!1,runAgain:!1}),a=a||this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)}),this._enableDebug&&console.log(new Date,"New Sub",a.publication,a.running,a.runAgain,a.clients.length),this.processSubscription(a,n,i)}else console.error(new Date,"No Publication: "+o)},SubscriptionManager.prototype.createLoggedInUser=function(i){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return[2,new Promise(function(n,e){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i))?(t={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:t.id_user,user:t.user,id_ws:t.id_socket},this._loggedInUsers.push(t),logged_in_users_collection_1.LoggedInUsers.insertOne(t),n(t)):n(null),[2]})})})]})})},SubscriptionManager.prototype.unsubscribe=function(e,t,n,i,o,s){if(this._debugUnSubHits+=1,this._publications[o]){var r=this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)});if(r){for(var a=r.clients.length-1;0<=a;a--)r.clients[a].id_user===n.id_user&&r.clients[a].messageId===i&&r.clients[a].id_socket===n.id_socket&&r.clients.splice(a,1);this._enableDebug&&console.log(new Date,"Unsub",r.publication,r.running,r.runAgain,r.clients.length)}}else console.log("No Publication: "+o)},SubscriptionManager.prototype.unsubscribeAll=function(s){return __awaiter(this,void 0,void 0,function(){var t,n,i,o;return __generator(this,function(e){if(this._debugUnSubAllHits+=1,s){if(s.isUnsubscribed)return[2];for(s.isUnsubscribed=!0,0<=this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(s.id_socket)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(s.id_socket),1),logged_in_users_collection_1.LoggedInUsers.deleteOne({id_ws:s.id_socket}),t=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_user===s.id_user&&e.id_socket===s.id_socket})}),n=t.length-1;0<=n;n--)for(i=t[n],o=i.clients.length-1;0<=o;o--)i.clients[o].id_socket===s.id_socket&&i.clients.splice(o,1);this._websocketManager.removeWebSocket(s)}return[2]})})},SubscriptionManager.prototype.getActiveSubscriptions=function(){return this._subscriptions},SubscriptionManager.prototype.getPublicationCollections=function(e){return this._publications[e].collections},SubscriptionManager.prototype.tailOpLog=function(o){return __awaiter(this,void 0,void 0,function(){var t,n,i=this;return __generator(this,function(e){switch(e.label){case 0:return this._oplog$&&!this._oplog$.closed&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:if(e.sent(),!this._oplog$||this._oplog$.closed){if(this._oplogRetryCount+=1,5<this._oplogRetryCount&&(console.error("****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************"),process.exit(1)),t=[{$match:{$and:[{"ns.coll":{$nin:["logs"]}},{"ns.coll":{$not:/.*\.versions$/}},{"ns.coll":{$not:/^monitor-/}}]}}],o){n=o;try{this._oplog$=resolveio_server_app_1.ResolveIOServer.getMainDB().watch(t,{resumeAfter:o})}catch(e){return this._oplog$&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),this.tailOpLog(o),[2]}}else this._oplog$=resolveio_server_app_1.ResolveIOServer.getMainDB().watch(t);console.log(new Date,"oplog started"),this._oplog$.on("change",function(t){var e;t.ns&&(i._enableDebug&&console.log(new Date,"Oplog Hit",t.ns),e=t.ns.coll,i._debugOplogCollections.some(function(e){return e.collection===t.ns.coll&&e.type===t.operationType})?i._debugOplogCollections.find(function(e){return e.collection===t.ns.coll&&e.type===t.operationType}).hits+=1:i._debugOplogCollections.push({collection:t.ns.coll,type:t.operationType,hits:1}),e&&(i._debugOplogHits+=1,"insert"===t.operationType?("support-tickets"===e&&"https://resolveio.com"===i.serverConfig.ROOT_URL&&(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"sendSupportTicketEmail",t.documentKey._id),i.invalidatePubsCache(e,"insert")),"method-responses"!==e&&i.invalidatePubsCache(e,"insert")):"update"===t.operationType||"replace"===t.operationType?"method-responses"!==e&&i.invalidatePubsCache(e,"update"):"delete"===t.operationType&&"method-responses"!==e&&i.invalidatePubsCache(e,"delete")),"flags"===e&&flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?i._enableDebug=!0:i._enableDebug=!1}),n=t._id,process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||"false"!==process.env.IS_WORKERS_ENABLED&&"true"===process.env.IS_WORKER_INSTANCE&&process.env.WORKER_INDEX)}),this._oplog$.on("error",function(e){console.log(new Date,"oplog error",e),i._oplog$.removeAllListeners(),i._oplog$.close(),i._oplog$=null,i.tailOpLog(n)}),this._oplog$.on("end",function(){console.log(new Date,"oplog end"),i._oplog$.removeAllListeners(),i._oplog$.close(),i._oplog$=null,i.tailOpLog(n)}),this._oplog$.on("close",function(){console.log(new Date,"oplog close"),i._oplog$.removeAllListeners(),i._oplog$=null,i.tailOpLog(n)})}return[2]}})})},SubscriptionManager.prototype.processSubscription=function(i,o,s){return __awaiter(this,void 0,void 0,function(){var t,n;return __generator(this,function(e){if(this._publications[i.publication].user_specific){if(this._enableDebug&&console.log(new Date,"Process Sub Specific, Non - Cache",i.publication,i.running),i.running)return[2];this.sendDataToOneWithRetry(o,s,i,"","newSub")}else if(i.cacheId)try{t=JSON.parse(this._nodeCache.get(i.cacheId),common_1.dateReviver),n={messageId:s,hasError:!1,data:t},this._enableDebug&&console.log(new Date,"Process Sub, Cache",i.publication),this.sendWS(o,n)}catch(e){this._nodeCache.del(i.cacheId),i.cacheId=0,this.sendDataToAllWithRetry(i,"","newSub")}else{if(this._enableDebug&&console.log(new Date,"Process Sub, Non - Cache",i.publication,i.running),i.running)return[2];this.sendDataToAllWithRetry(i,"","newSub")}return[2]})})},SubscriptionManager.prototype.sendDataToOne=function(s,r,a,c,l){return __awaiter(this,void 0,void 0,function(){var t,n,i,o;return __generator(this,function(e){switch(e.label){case 0:t=this._monitorManagerFunction.startMonitorFunction("User Specific Publication",a.publication,"","",a.subscriptionData),e.label=1;case 1:return e.trys.push([1,3,,4]),resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"insertSubscriptionLog",l,a.publication,c,JSON.stringify(a.subscriptionData)),[4,(o=this._publications[a.publication].function).call.apply(o,__spreadArray([Object.assign({},this,SubscriptionManager.prototype),s.id_user],__read(a.subscriptionData),!1))];case 2:return o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),i={messageId:r,hasError:!1,data:o},this.sendWS(s,i),[3,4];case 3:return n=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),i={messageId:r,hasError:!0,data:n},this.sendWS(s,i),resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+a.publication+" - (sendDataToOne - WS)\n\nData \n"+JSON.stringify(a.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(n,null,2)),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.sendDataToAll=function(g,_,d){return __awaiter(this,void 0,void 0,function(){var t,o,n,i,s,r,a,c,l,u=this;return __generator(this,function(e){switch(e.label){case 0:return g.clients.length?[3,1]:(g.cacheId&&(this._nodeCache.del(g.cacheId),g.cacheId=0),0<=(l=this._subscriptions.findIndex(function(e){return e.publication===g.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(g.subscriptionData)}))&&this._subscriptions.splice(l,1),[2]);case 1:t=this._monitorManagerFunction.startMonitorFunction("Publication",g.publication,"","",g.subscriptionData),e.label=2;case 2:return e.trys.push([2,4,,5]),"superadminAPM"!==g.publication&&"loggedInUsers"!==g.publication&&resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"insertSubscriptionLog",d,g.publication,_,JSON.stringify(g.subscriptionData)),[4,(l=this._publications[g.publication].function).call.apply(l,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],__read(g.subscriptionData),!1))];case 3:if(o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),g.cacheId)try{n=JSON.parse(this._nodeCache.get(g.cacheId),common_1.dateReviver),JSON.stringify(n)!==JSON.stringify(o)&&(Promise.all(g.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t,n;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN&&(n={messageId:i.messageId,hasError:!1,data:o},this.sendWS(t,n)),[2]})})})),this._nodeCache.del(g.cacheId),(0,common_1.getBinarySize)(JSON.stringify(o))<1e6&&!g.collections.includes("logs")&&!g.collections.find(function(e){return e.endsWith(".versions")})&&!g.collections.find(function(e){return e.startsWith("monitor-")})?this._nodeCache.set(g.cacheId,JSON.stringify(o)):g.cacheId=0)}catch(e){Promise.all(g.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t,n;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN&&(n={messageId:i.messageId,hasError:!1,data:o},this.sendWS(t,n)),[2]})})})),this._nodeCache.del(g.cacheId),(0,common_1.getBinarySize)(JSON.stringify(o))<1e6&&!g.collections.includes("logs")&&!g.collections.find(function(e){return e.endsWith(".versions")})&&!g.collections.find(function(e){return e.startsWith("monitor-")})?this._nodeCache.set(g.cacheId,JSON.stringify(o)):g.cacheId=0}else if(Promise.all(g.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t,n;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN&&(n={messageId:i.messageId,hasError:!1,data:o},this.sendWS(t,n)),[2]})})})),(0,common_1.getBinarySize)(JSON.stringify(o))<1e6&&!g.collections.includes("logs")&&!g.collections.find(function(e){return e.endsWith(".versions")})&&!g.collections.find(function(e){return e.startsWith("monitor-")})){if(g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o)),(i=this._nodeCache.getStats().vsize)>this._heapLimit){for(s=0,r=this._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),a=0;a<r.length&&(this._debugRemoveCacheHits+=1,this._nodeCache.del(r[a].cacheId),r[a].cacheId=0,s+=1,!(this._nodeCache.getStats().vsize<.75*this._heapLimit));a++);this._enableDebug&&console.log("Sub Cache: Too Big - "+g.publication+" - Deleted: "+s+" - "+i)}}else g.cacheId=0;return[3,5];case 4:return c=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),Promise.all(g.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t,n;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN&&(n={messageId:i.messageId,hasError:!0,data:c},this.sendWS(t,n)),[2]})})})),resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+g.publication+" - (sendPubData)\n\nData \n"+JSON.stringify(g.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(c,null,2)),[3,5];case 5:return[2]}})})},SubscriptionManager.prototype.sendWS=function(e,t){this._websocketManager.send(e,t)},SubscriptionManager.prototype.getEnableDebug=function(){return this._enableDebug},SubscriptionManager}();exports.SubscriptionManager=SubscriptionManager;
2
2
  //# sourceMappingURL=subscription.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/subscription.manager.ts"],"names":["logs_1","require","app_status_1","files_1","super_admin_1","logged_in_users_collection_1","cron_jobs_1","flags_1","method_responses_1","resolveio_server_app_1","notifications_1","report_builder_reports_1","report_builder_libraries_1","user_groups_1","user_guides_1","report_builder_dashboard_builders_1","common_1","NodeCache","flag_collection_1","os_1","flags_update_1","numCPUs","cpus","length","v8","SubscriptionManager","wss","serverConfig","monitorManagerFunction","_this","this","_publications","_subscriptions","_loggedInUsers","_mongoQueue","_mongoQueueId","_cacheId","_heapSize","getHeapStatistics","_enableDebug","_debugOplogCollections","_debugOplogHits","_debugSubCollections","_debugSubHits","_debugUnSubHits","_debugUnSubAllHits","_debugMongoQueueHits","_debugMongoQueueCollections","_debugSendQueueHits","_debugRemoveCacheHits","_oplogRetryCount","latencyBuffer","Map","LATENCY_UPDATE_INTERVAL","LATENCY_UPDATE_THRESHOLD_MS","_websocketManager","ResolveIOServer","getMainServer","getWebSocketManager","_monitorManagerFunction","_nodeCache","stdTTL","checkperiod","setInterval","flushThrottledLatencyUpdates","_wss","loadSuperAdminPublications","loadAppStatusPublications","loadLogPublications","loadFilePublications","loadCronJobPublications","loadFlagsUpdatePublications","loadFlagsPublications","loadMethodResponsePublications","loadNotificationPublications","loadReportBuilderReportPublications","loadReportBuilderLibraryPublications","loadUserGroupPublications","loadUserGuidePublications","loadReportBuilderDashboardBuilderPublications","tailOpLog","getEnableDebug","console","log","Date","JSON","stringify","sort","a","b","collection","localeCompare","publication","type","__awaiter","_a","LoggedInUsers","find","_b","sent","userCopy","deepCopy","i","loggedInUser","date","now","getTime","this_1","getWebSocket","id_ws","unsubscribeAll","forEach","sub","j","clients","id_socket","splice","deleteOne","_id","findIndex","client","this_2","some","Flags","findOne","then","flag","value","setCacheLimit","prototype","process","env","IS_WORKERS_ENABLED","_heapLimit","invalidatePubsCache","getMongoManager","invalidateQueryCache","collSubs","filter","collections","includes","this_3","running","runAgain","user_specific","Promise","all","map","ws","readyState","OPEN","sendDataToOneWithRetry","messageId","err","getMethodManager","sendEmail","id_user","sendDataToAllWithRetry","collSubs_1","__values","collSubs_1_1","next","done","delay","ms","resolve","setTimeout","sendDataToAll","sendDataToOne","publications","method","Object","assign","loggedInLatency","existingEntry","newLatency","get","lastUpdate","Math","abs","latency","set","size","updates","Array","from","entries","__read","_c","updateOne","update","$set","bulkWrite","clear","error","error_1","subscribe","messageRoute","messageDate","subscriptionData","pub","hits","push","check","_schema","valObj","rootKeys","keys","validate","errors","urlData","split","urlModule_1","urlNext","otherRouteSubs","startsWith","otherSub","unsubscribe","getPublicationCollections","cacheId","processSubscription","createLoggedInUser","reject","user","objectIdHexString","__v","insertOne","indexOf","userSubs","removeWebSocket","getActiveSubscriptions","resumeToken","_oplog$","closed","removeAllListeners","close","exit","pipeline","$match","$and","ns.coll","$nin","$not","lastResumeToken_1","getMainDB","watch","resumeAfter","errOp","on","doc","ns","coll","operationType","callMethod","call","documentKey","NODE_APP_INSTANCE","IS_WORKER_INSTANCE","WORKER_INDEX","cacheData","parse","dateReviver","serverRes","hasError","data","sendWS","del","monitor","startMonitorFunction","function","apply","__spreadArray","res","finishMonitorFunction","err_1","subIndex","res_1","getBinarySize","endsWith","nodeCacheSize","getStats","vsize","deleteCount","subArr","zz","err_2","send","exports"],"mappings":"+xEAGAA,Q,0FAAAC,QAAA,sBAAA,GACAC,aAAAD,QAAA,4BAAA,EACAE,QAAAF,QAAA,uBAAA,EACAG,cAAAH,QAAA,6BAAA,EACAI,6BAAAJ,QAAA,2CAAA,EACAK,YAAAL,QAAA,2BAAA,EACAM,QAAAN,QAAA,uBAAA,EACAO,mBAAAP,QAAA,kCAAA,EACAQ,uBAAAR,QAAA,yBAAA,EACAS,gBAAAT,QAAA,+BAAA,EACAU,yBAAAV,QAAA,wCAAA,EAIAW,2BAAAX,QAAA,0CAAA,EACAY,cAAAZ,QAAA,6BAAA,EACAa,cAAAb,QAAA,6BAAA,EACAc,oCAAAd,QAAA,mDAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,UAAAhB,QAAA,YAAA,EAEAiB,kBAAAjB,QAAA,gCAAA,EACAkB,KAAAlB,QAAA,IAAA,EAEAmB,eAAAnB,QAAA,8BAAA,EACMoB,SAAU,EAAAF,KAAAG,MAAI,EAAGC,OACjBC,GAAKvB,QAAQ,IAAI,EA0BvBwB,oBAAA,WAiDC,SAAAA,oBAAYC,EAAuBC,EAAcC,GAAjD,IAAAC,EAAAC,KA/CQA,KAAAC,cAAmC,GACnCD,KAAAE,eAA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O,oBAAAwG,UAAAhD,eAAP,WACC,OAAOnD,KAAKS,YACb,EACDd,mBAAA,EAAC,EA77BYsQ,QAAAtQ,oBAAAA","file":"subscription.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { ActiveSubscriptionModel, SubscriptionModel } from '../models/subscription.model';\nimport * as WebSocket from 'ws';\nimport { loadLogPublications } from '../publications/logs';\nimport { loadAppStatusPublications } from '../publications/app-status';\nimport { loadFilePublications } from '../publications/files';\nimport { loadSuperAdminPublications } from '../publications/super-admin';\nimport { LoggedInUsers } from '../collections/logged-in-users.collection';\nimport { loadCronJobPublications } from '../publications/cron-jobs';\nimport { loadFlagsPublications } from '../publications/flags';\nimport { loadMethodResponsePublications } from '../publications/method-responses';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { loadNotificationPublications } from '../publications/notifications';\nimport { loadReportBuilderReportPublications } from '../publications/report-builder-reports';\nimport { LoggedInUserModel } from '../models/logged-in-users.model';\n\nimport { ChangeStream, ChangeStreamDeleteDocument, ChangeStreamInsertDocument, ChangeStreamReplaceDocument, ChangeStreamUpdateDocument, ResumeToken } from 'mongodb';\nimport { loadReportBuilderLibraryPublications } from '../publications/report-builder-libraries';\nimport { loadUserGroupPublications } from '../publications/user-groups';\nimport { loadUserGuidePublications } from '../publications/user-guides';\nimport { loadReportBuilderDashboardBuilderPublications } from '../publications/report-builder-dashboard-builders';\nimport { dateReviver, deepCopy, getBinarySize, objectIdHexString } from '../util/common';\nimport * as NodeCache from 'node-cache';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { Flags } from '../collections/flag.collection';\nimport { cpus } from 'os';\nimport { WebSocketManager } from './websocket.manager';\nimport { loadFlagsUpdatePublications } from '../publications/flags-update';\nconst numCPUs = cpus().length;\nconst v8 = require('v8');\n\n// Performance Dependencies\n// import * as path from 'path';\n// import { Worker } from 'worker_threads';\n\ninterface MongoQueueModel {\n\t_id: number,\n\ttype: string;\n\tcollection: string;\n\tsubscription: ActiveSubscriptionModel;\n\trunning: boolean;\n\trun_again: boolean;\n}\n\n// interface CurrentPerformanceMonitor {\n// \t_id: number;\n// \tfunction: string;\n// \tpublication: string;\n// \tsubscriptionData: any[];\n// \tdate_start: Date;\n// \tdate_end: Date;\n// \tduration: number;\n// \tresult: string;\n// }\n\nexport class SubscriptionManager {\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _publications: SubscriptionModel = {};\n\tprivate _subscriptions: ActiveSubscriptionModel[] = [];\n\tprivate _wss: WebSocket.Server;\n\tprivate _loggedInUsers: LoggedInUserModel[] = [];\n\n\tprivate _mongoQueue: MongoQueueModel[] = [];\n\tprivate _mongoQueueId = 0;\n\t\n\tprivate _oplog$: ChangeStream;\n\n\tprivate _nodeCache;\n\tprivate _cacheId = 1;\n\n\tprivate _heapSize = v8.getHeapStatistics() / numCPUs;\n\tprivate _heapLimit: number;\n\n\tprivate serverConfig;\n\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _enableDebug = false;\n\tprivate _debugOplogCollections = [];\n\tprivate _debugOplogHits = 0;\n\tprivate _debugSubCollections = [];\n\tprivate _debugSubHits = 0;\n\tprivate _debugUnSubHits = 0;\n\tprivate _debugUnSubAllHits = 0;\n\tprivate _debugMongoQueueHits = 0;\n\tprivate _debugMongoQueueCollections = [];\n\tprivate _debugSendQueueHits = 0;\n\tprivate _debugRemoveCacheHits = 0;\n\n\tprivate _oplogRetryCount = 0;\n\n\t// Buffer to store throttled latency updates with timestamps\n\tprivate latencyBuffer = new Map<string, { latency: number, lastUpdate: Date }>();\n\n\t// Interval to flush latency updates in MongoDB\n\tprivate readonly LATENCY_UPDATE_INTERVAL = 60000;\n\n\t// Minimum time difference between two latency updates for the same user\n\tprivate readonly LATENCY_UPDATE_THRESHOLD_MS = 30000;\n\n\t// private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];\n\t// private idPerformance: number = 0;\n\t// private performanceThread;\n\n\tconstructor(wss: WebSocket.Server, serverConfig, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._websocketManager = ResolveIOServer.getMainServer().getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\tthis._nodeCache = new NodeCache( { stdTTL: 0, checkperiod: 0 } );\n\n\t\tsetInterval(() => this.flushThrottledLatencyUpdates(), this.LATENCY_UPDATE_INTERVAL);\n\n\t\t// setTimeout(() => {\n\t\t// \tconsole.log('Setting up performance thread');\n\n\t\t// \tthis.performanceThread = new Worker(path.join(__dirname, './subscription.performance.js'));\n\n\t\t// \tthis.performanceThread.on('exit', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD EXITED!!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\n\t\t// \tthis.performanceThread.on('error', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD RECV ERROR !!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\t\t// }, 5000);\n\n\t\t// setInterval(() => {\n\t\t// \tconsole.log('Post thread msg');\n\t\t// \tthis.performanceThread.postMessage(this.currentPerfomanceMonitor);\n\t\t// \tthis.currentPerfomanceMonitor = [];\n\t\t// }, 10000);\n\n\t\tthis.serverConfig = serverConfig;\n\t\tthis._wss = wss;\n\n\t\t// Publications\n\t\tloadSuperAdminPublications(this);\n\t\tloadAppStatusPublications(this);\n\t\tloadLogPublications(this);\n\t\tloadFilePublications(this);\n\t\tloadCronJobPublications(this);\n\t\tloadFlagsUpdatePublications(this);\n\t\tloadFlagsPublications(this);\n\t\tloadMethodResponsePublications(this);\n\t\tloadNotificationPublications(this);\n\t\tloadReportBuilderReportPublications(this);\n\t\tloadReportBuilderLibraryPublications(this);\n\t\tloadUserGroupPublications(this);\n\t\tloadUserGuidePublications(this);\n\t\tloadReportBuilderDashboardBuilderPublications(this);\n\n\t\tthis.tailOpLog();\n\n\t\tsetInterval(() => {\n\t\t\tthis._oplogRetryCount = 0;\n\t\t}, 15000);\n\n\t\tsetInterval(() => {\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Subs', this._subscriptions.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Logged In Users', this._loggedInUsers.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue', this._mongoQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Hits', this._debugMongoQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Collections', JSON.stringify(this._debugMongoQueueCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Hits', this._debugOplogHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Collections', JSON.stringify(this._debugOplogCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.type.localeCompare(b.type)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Hits', this._debugSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Collections', JSON.stringify(this._debugSubCollections.sort((a, b) => a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub Hits', this._debugUnSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub All Hits', this._debugUnSubAllHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Cache Cleanup Hits', this._debugRemoveCacheHits);\n\t\t\t}\n\t\t\t\n\t\t\tthis._debugOplogHits = 0;\n\t\t\tthis._debugOplogCollections = [];\n\t\t\tthis._debugSubCollections = [];\n\t\t\tthis._debugMongoQueueHits = 0;\n\t\t\tthis._debugMongoQueueCollections = [];\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSubHits = 0;\n\t\t\tthis._debugUnSubHits = 0;\n\t\t\tthis._debugUnSubAllHits = 0;\n\t\t\tthis._debugRemoveCacheHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(async () => {\n\t\t\tthis._loggedInUsers = await LoggedInUsers.find();\n\t\n\t\t\tlet userCopy = deepCopy(this._loggedInUsers);\n\t\t\tfor (let i = this._loggedInUsers.length - 1; i >= 0; i--) {\n\t\t\t\tlet loggedInUser = userCopy[i];\n\n\t\t\t\tif (!loggedInUser.date || Date.now() - loggedInUser.date.getTime() > 120000) {\n\t\t\t\t\tif (this._websocketManager.getWebSocket(loggedInUser.id_ws)) {\n\t\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', this._websocketManager.getWebSocket(loggedInUser.id_ws)['user'], this._websocketManager.getWebSocket(loggedInUser.id_ws)['id_socket'], 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.unsubscribeAll(this._websocketManager.getWebSocket(loggedInUser.id_ws));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._subscriptions.forEach(sub => {\n\t\t\t\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\t\t\t\tif (client.id_socket === loggedInUser.id_ws) {\n\t\t\t\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tLoggedInUsers.deleteOne({_id: loggedInUser._id});\n\n\t\t\t\t\t\tif (this._loggedInUsers.findIndex(a => a._id === loggedInUser._id) >= 0) {\n\t\t\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.findIndex(a => a._id === loggedInUser._id), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (let i = 0; i < this._subscriptions.length; i++) {\n\t\t\t\tlet sub = this._subscriptions[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\tif (!this._loggedInUsers.some(a => a.id_ws === client.id_socket)) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, 30000);\n\n\t\tFlags.findOne({type: 'Enable Debug'}).then(flag => {\n\t\t\tif (flag && flag.value) {\n\t\t\t\tthis._enableDebug = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._enableDebug = false;\n\t\t\t}\n\t\t});\n\n\t\tthis.setCacheLimit();\n\t}\n\n\tprivate setCacheLimit() {\t\n\t\tif (process.env.IS_WORKERS_ENABLED === 'true') {\n\t\t\tthis._heapLimit = this._heapSize * 0.4;\n\t\t}\n\t\telse {\n\t\t\tthis._heapLimit = this._heapSize * 0.3; // Use 50% of total heap size\n\t\t}\n\t}\n\n\tpublic async invalidatePubsCache(collection: string, type: string) {\n\t\tResolveIOServer.getMongoManager().invalidateQueryCache(collection);\n\n\t\tlet collSubs = this._subscriptions.filter(a => a.collections.includes(collection));\n\n\t\tfor (let sub of collSubs) {\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Invalidate Sub', sub.publication, sub.running, sub.runAgain);\n\t\t\t}\n\n\t\t\tif (sub.running) {\n\t\t\t\tsub.runAgain = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (this._publications[sub.publication].user_specific) {\n\t\t\t\tPromise.all(\n\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tthis.sendDataToOneWithRetry(ws, client.messageId, sub, collection, type);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t// Handle error\n\t\t\t\t\t\t\t\tResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During sendDataToOne - User Specific - Socket: ' + client.id_socket + ', User: ' + client.id_user + ', MessageId: ' + client.messageId + ', Pub: ' + sub.publication + ', Err: ' + JSON.stringify(err, null, 2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.sendDataToAllWithRetry(sub, collection, type);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async delay(ms: number) {\n\t\treturn new Promise(resolve => setTimeout(resolve, ms));\n\t}\n\n\tprivate async sendDataToAllWithRetry(sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tsub.running = true;\n\n\t\tdo {\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Running sendDataToAll Sub', sub.publication);\n\t\t\t}\n\n\t\t\tsub.runAgain = false;\n\t\t\tawait this.sendDataToAll(sub, collection, type);\n\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Done sendDataToAll Sub', sub.publication, sub.runAgain);\n\t\t\t}\n\n\t\t\tif (sub.runAgain) {\n\t\t\t\tawait this.delay(500); // delay, adjust as needed\n\t\t\t}\n\t\t} while (sub.runAgain);\n\n\t\tsub.running = false;\n\t}\n\n\tprivate async sendDataToOneWithRetry(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tsub.running = true;\n\n\t\tdo {\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Running sendDataToOne Sub', sub.publication);\n\t\t\t}\n\n\t\t\tsub.runAgain = false;\n\t\t\tawait this.sendDataToOne(ws, messageId, sub, collection, type);\n\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Done sendDataToOne Sub', sub.publication, sub.runAgain);\n\t\t\t}\n\n\t\t\tif (sub.runAgain) {\n\t\t\t\tawait this.delay(500); // delay, adjust as needed\n\t\t\t}\n\t\t} while (sub.runAgain);\n\t\tsub.running = false;\n\t}\n\n\t// Add all files to publications private object\n\tpublic publications(method: SubscriptionModel) {\n\t\tthis._publications = Object.assign(this._publications, method);\n\t}\n\n\t// Throttled `loggedInLatency` method\n\tpublic loggedInLatency(ws: WebSocket) {\n\t\tlet loggedInUser = this._loggedInUsers.find(a => a.id_ws === ws['id_socket']);\n\t\tif (!loggedInUser) return;\n\n\t\tconst now = new Date();\n\t\tconst existingEntry = this.latencyBuffer.get(ws['id_socket']);\n\t\tconst newLatency = ws['latency'];\n\n\t\t// Throttle updates: only update if time threshold has passed or latency has significantly changed\n\t\tif (\n\t\t\t!existingEntry || \n\t\t\t(now.getTime() - existingEntry.lastUpdate.getTime() >= this.LATENCY_UPDATE_THRESHOLD_MS) || \n\t\t\t(Math.abs(newLatency - existingEntry.latency) > 100) // Optional: log only significant changes\n\t\t) {\n\t\t\t// Update in-memory and buffer\n\t\t\tloggedInUser.date = now;\n\t\t\tthis.latencyBuffer.set(ws['id_socket'], { latency: newLatency, lastUpdate: now });\n\t\t}\n\t}\n\n\t// Method to flush buffered latency updates in bulk\n\tprivate async flushThrottledLatencyUpdates() {\n\t\tif (this.latencyBuffer.size === 0) return; // No updates to flush\n\n\t\tconst updates = Array.from(this.latencyBuffer.entries()).map(([id_ws, { latency, lastUpdate }]) => ({\n\t\t\tupdateOne: {\n\t\t\t\tfilter: { id_ws },\n\t\t\t\tupdate: { $set: { latency, date: lastUpdate } }\n\t\t\t}\n\t\t}));\n\n\t\ttry {\n\t\t\tawait LoggedInUsers.bulkWrite(updates);\n\t\t\tthis.latencyBuffer.clear(); // Clear buffer after successful update\n\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Throttled latency batch update successful', updates.length);\n\t\t\t}\n\t\t}\n\t\tcatch (error) {\n\t\t\tconsole.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error);\n\t\t\t// Optional: implement retry logic or logging for failed updates\n\t\t}\n\t}\n\n\t// Subscribe to publication\n\tpublic subscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugSubHits += 1;\n\n\t\tif (!this._debugSubCollections.some(a => a.publication === publication)) {\n\t\t\tthis._debugSubCollections.push({\n\t\t\t\tpublication: publication,\n\t\t\t\thits: 1\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tthis._debugSubCollections.find(a => a.publication === publication).hits += 1;\n\t\t}\n\n\t\tlet pub = this._publications[publication];\n\n\t\tif (!pub) {\n\t\t\tconsole.error(new Date(), 'No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tif (subscriptionData.length > 1 || subscriptionData[0]) {\n\t\t\t\tif (!pub.check) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Function For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (!pub.check._schema) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Schema For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet valObj = {};\n\t\t\t\t\tlet valKeys = Object.keys(pub.check._schema);\n\n\t\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\t\tfor (let i = 0; i < subscriptionData.length; i++) {\n\t\t\t\t\t\tvalObj[rootKeys[i]] = subscriptionData[i];\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpub.check.validate(valObj);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (errors) {\n\t\t\t\t\t\tif (errors) {\n\t\t\t\t\t\t\tconsole.error(new Date(), 'Error in Pub Check (' + publication + ')', errors);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (messageRoute !== 'Bypass') {\n\t\t\t\tlet urlData = messageRoute.split('/');\n\t\t\t\tlet urlModule = '';\n\t\t\t\tlet urlNext = urlData[0];\n\n\t\t\t\tif (urlData[0] === '') {\n\t\t\t\t\turlModule = '/';\n\t\t\t\t\turlNext = urlData[1];\n\t\t\t\t}\n\n\t\t\t\turlModule += urlNext;\n\n\t\t\t\tif (urlData.length > 1) {\n\t\t\t\t\turlModule += '/';\n\t\t\t\t}\n\n\t\t\t\tlet otherRouteSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_socket === ws['id_socket'] && b.messageRoute !== 'Bypass' && b.messageRoute !== '/' && b.messageRoute !== messageRoute && !b.messageRoute.startsWith(urlModule)));\n\n\t\t\t\tif (otherRouteSubs.length) {\n\t\t\t\t\tResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Detected Undestroyed Subscription - ' + this.serverConfig['CLIENT_NAME'], 'USER: ' + ws['user'] + ' (Socket: ' + ws['id_socket'] + ') ' + ' is on route: ' + messageRoute + ' but has the following subscriptions on other routes:' + JSON.stringify(otherRouteSubs, null, 2));\n\n\t\t\t\t\totherRouteSubs.forEach(otherSub => {\n\t\t\t\t\t\totherSub.clients.filter(a => a.id_socket === ws['id_socket']).forEach(client => {\n\t\t\t\t\t\t\tthis.unsubscribe(client.messageRoute, new Date(), ws, client.messageId, otherSub.publication, otherSub.subscriptionData);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet sub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\n\t\t\t// If sub found (another user watching same data), add client to same sub\n\t\t\tif (sub) {\n\t\t\t\tif (!sub.clients.some(a => a.id_socket === ws['id_socket'] && a.messageId === messageId)) {\n\t\t\t\t\tsub.clients.push({\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If sub not found, create new sub\n\t\t\telse {\n\t\t\t\tthis._subscriptions.push({\n\t\t\t\t\tpublication: publication,\n\t\t\t\t\tsubscriptionData: subscriptionData,\n\t\t\t\t\tcollections: this.getPublicationCollections(publication),\n\t\t\t\t\tclients: [{\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute,\n\t\t\t\t\t}],\n\t\t\t\t\tcacheId: 0,\n\t\t\t\t\trunning: false,\n\t\t\t\t\trunAgain: false\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!sub) {\n\t\t\t\tsub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\t\t\t}\n\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'New Sub', sub.publication, sub.running, sub.runAgain, sub.clients.length);\n\t\t\t}\n\n\t\t\t// Immediately send data to the new client\n\t\t\tthis.processSubscription(sub, ws, messageId);\n\t\t}\n\t}\n\n\tpublic async createLoggedInUser(id_ws: string): Promise<LoggedInUserModel> {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tlet ws = this._websocketManager.getWebSocket(id_ws);\n\n\t\t\tif (ws) {\n\t\t\t\tlet user = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tthis._loggedInUsers.push(user);\n\t\t\t\tLoggedInUsers.insertOne(user);\n\t\t\t\t\n\t\t\t\tresolve(user);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(null);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Unsubscribe from publication \n\tpublic unsubscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugUnSubHits += 1;\n\n\t\tif (!this._publications[publication]) {\n\t\t\tconsole.log('No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet sub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\n\t\t\tif (sub) {\n\t\t\t\tfor (let i = sub.clients.length - 1; i >= 0; i--) {\n\t\t\t\t\tif (sub.clients[i].id_user === ws['id_user'] && sub.clients[i].messageId === messageId && sub.clients[i].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(i, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\tconsole.log(new Date(), 'Unsub', sub.publication, sub.running, sub.runAgain, sub.clients.length);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// Unsubscribe from publication\n\tpublic async unsubscribeAll(ws: WebSocket) {\n\t\tthis._debugUnSubAllHits += 1;\n\n\t\tif (ws) {\n\t\t\t// Check if WebSocket has already been unsubscribed\n\t\t\tif (ws['isUnsubscribed']) {\n\t\t\t\treturn; // Skip if already unsubscribed\n\t\t\t}\n\t\t\t\n\t\t\t// Mark the WebSocket as unsubscribed to prevent further calls\n\t\t\tws['isUnsubscribed'] = true;\n\t\t\t\n\t\t\tif (this._loggedInUsers.map(a => a.id_ws).indexOf(ws['id_socket']) >= 0) {\n\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.map(a => a.id_ws).indexOf(ws['id_socket']), 1);\n\t\t\t}\n\t\t\tLoggedInUsers.deleteOne({ id_ws: ws['id_socket'] });\n\n\t\t\tlet userSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_user === ws['id_user'] && b.id_socket === ws['id_socket']));\n\n\t\t\tfor (let i = userSubs.length - 1; i >= 0; i--) {\n\t\t\t\tlet sub = userSubs[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tif (sub.clients[j].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._websocketManager.removeWebSocket(ws);\n\t\t}\n\t}\n\n\tpublic getActiveSubscriptions() {\n\t\treturn this._subscriptions;\n\t}\n\n\t// Get publication collection\n\tprivate getPublicationCollections(publication: string) {\n\t\treturn this._publications[publication].collections;\n\t}\n\n\t// Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)\n\tprivate async tailOpLog(resumeToken?: ResumeToken) {\n\t\tif (this._oplog$ && !this._oplog$.closed) {\n\t\t\tthis._oplog$.removeAllListeners();\n\t\t\tthis._oplog$.close();\n\t\t\tthis._oplog$ = null;\n\t\t}\n\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\n\t\tif (!this._oplog$ || this._oplog$.closed) {\n\t\t\tthis._oplogRetryCount += 1;\n\n\t\t\tif (this._oplogRetryCount > 5) {\n\t\t\t\tconsole.error('****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\tconst pipeline = [\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t{'ns.coll': { $nin: ['logs'] }},\n\t\t\t\t\t\t\t{'ns.coll': { $not: /.*\\.versions$/ }},\n\t\t\t\t\t\t\t{'ns.coll': { $not: /^monitor-/ }},\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\n\t\t\tlet lastResumeToken: ResumeToken;\n\n\t\t\tif (resumeToken) {\n\t\t\t\tlastResumeToken = resumeToken;\n\t\t\t\ttry {\n\t\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch(pipeline, { resumeAfter: resumeToken });\n\t\t\t\t}\n\t\t\t\tcatch (errOp) {\n\t\t\t\t\tif (this._oplog$) {\n\t\t\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\t\t\tthis._oplog$.close();\n\t\t\t\t\t\tthis._oplog$ = null;\n\t\t\t\t\t}\n\t\t\t\t\tthis.tailOpLog(resumeToken);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch(pipeline);\n\t\t\t}\n\n\t\t\tconsole.log(new Date(), 'oplog started');\n\n\t\t\tthis._oplog$.on('change', (doc: ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument) => {\n\t\t\t\tif (doc.ns) {\n\t\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Oplog Hit', doc.ns);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet collection = doc.ns.coll;\n\n\t\t\t\t\tif (!this._debugOplogCollections.some(a => a.collection === doc.ns.coll && a.type === doc.operationType)) {\n\t\t\t\t\t\tthis._debugOplogCollections.push({\n\t\t\t\t\t\t\tcollection: doc.ns.coll,\n\t\t\t\t\t\t\ttype: doc.operationType,\n\t\t\t\t\t\t\thits: 1\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._debugOplogCollections.find(a => a.collection === doc.ns.coll && a.type === doc.operationType).hits += 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection) {\n\t\t\t\t\t\tthis._debugOplogHits += 1;\n\n\t\t\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\t\t\tif (collection === 'support-tickets') {\n\t\t\t\t\t\t\t\tif (this.serverConfig['ROOT_URL'] === 'https://resolveio.com') {\n\t\t\t\t\t\t\t\t\tResolveIOServer.getMainServer().getMethodManager().callMethod.call(ResolveIOServer.getMainServer().getMethodManager(), 'sendSupportTicketEmail', doc.documentKey['_id']);\n\t\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'update' || doc.operationType === 'replace') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'update');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'delete');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection === 'flags') {\n\t\t\t\t\t\tFlags.findOne({ type: 'Enable Debug' }).then(flag => {\n\t\t\t\t\t\t\tif (flag && flag.value) {\n\t\t\t\t\t\t\t\tthis._enableDebug = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._enableDebug = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tlastResumeToken = doc._id;\n\n\t\t\t\t\tif ((!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') && (process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0'))) {\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tthis._oplog$.on('error', error => {\n\t\t\t\tconsole.log(new Date(), 'oplog error', error);\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('end', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog end');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog close');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async processSubscription(sub: ActiveSubscriptionModel, ws: WebSocket, messageId: number) {\n\t\tif (!this._publications[sub.publication].user_specific) {\t\t\t\n\t\t\tif (sub.cacheId) {\n\t\t\t\ttry {\n\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), dateReviver);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\tdata: cacheData\n\t\t\t\t\t};\n\n\t\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Process Sub, Cache', sub.publication);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\t\tsub.cacheId = 0;\n\n\t\t\t\t\tthis.sendDataToAllWithRetry(sub, '', 'newSub');\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\tconsole.log(new Date(), 'Process Sub, Non - Cache', sub.publication, sub.running);\n\t\t\t\t}\n\n\t\t\t\tif (sub.running) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.sendDataToAllWithRetry(sub, '', 'newSub');\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Process Sub Specific, Non - Cache', sub.publication, sub.running);\n\t\t\t}\n\n\t\t\tif (sub.running) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tthis.sendDataToOneWithRetry(ws, messageId, sub, '', 'newSub');\n\t\t}\n\t}\n\n\tprivate async sendDataToOne(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', sub.publication, '', '', sub.subscriptionData);\n\t\ttry {\n\t\t\tResolveIOServer.getMainServer().getMethodManager().callMethod.call(ResolveIOServer.getMainServer().getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));\n\n\t\t\tlet res = await this._publications[sub.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ws['id_user'], ...sub.subscriptionData);\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: res\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, serverRes);\n\t\t}\n\t\tcatch (err) {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: err\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, serverRes);\n\n\t\t\tResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendDataToOne - WS)\\n\\nData \\n' + JSON.stringify(sub.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t}\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate async sendDataToAll(sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tif (!sub.clients.length) {\n\t\t\tif (sub.cacheId) {\n\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\tsub.cacheId = 0;\n\t\t\t}\n\n\t\t\tlet subIndex = this._subscriptions.findIndex(a => a.publication === sub.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(sub.subscriptionData));\n\t\t\tif (subIndex >= 0) {\n\t\t\t\tthis._subscriptions.splice(subIndex, 1);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Publication', sub.publication, '', '', sub.subscriptionData);\n\n\t\t\ttry {\n\t\t\t\tif (sub.publication !== 'superadminAPM' && sub.publication !== 'loggedInUsers') {\n\t\t\t\t\tResolveIOServer.getMainServer().getMethodManager().callMethod.call(ResolveIOServer.getMainServer().getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));\n\t\t\t\t}\n\n\t\t\t\tlet res = await this._publications[sub.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ...sub.subscriptionData);\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tif (sub.cacheId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), dateReviver);\n\t\n\t\t\t\t\t\tif (JSON.stringify(cacheData) !== JSON.stringify(res)) {\n\t\t\t\t\t\t\tPromise.all(\n\t\t\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\n\t\t\t\t\t\t\tif (getBinarySize(JSON.stringify(res)) < 1000000 && \n\t\t\t\t\t\t\t\t!sub.collections.includes('logs') &&\n\t\t\t\t\t\t\t\t!sub.collections.find(a => a.endsWith('.versions')) &&\n\t\t\t\t\t\t\t\t!sub.collections.find(a => a.startsWith('monitor-'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tsub.cacheId = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tPromise.all(\n\t\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\n\t\t\t\t\t\tif (getBinarySize(JSON.stringify(res)) < 1000000 && \n\t\t\t\t\t\t\t!sub.collections.includes('logs') &&\n\t\t\t\t\t\t\t!sub.collections.find(a => a.endsWith('.versions')) &&\n\t\t\t\t\t\t\t!sub.collections.find(a => a.startsWith('monitor-'))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsub.cacheId = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tPromise.all(\n\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t};\n\t\n\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tif (getBinarySize(JSON.stringify(res)) < 1000000 && \n\t\t\t\t\t\t!sub.collections.includes('logs') &&\n\t\t\t\t\t\t!sub.collections.find(a => a.endsWith('.versions')) &&\n\t\t\t\t\t\t!sub.collections.find(a => a.startsWith('monitor-'))\n\t\t\t\t\t) {\n\t\t\t\t\t\tsub.cacheId = this._cacheId++;\n\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\n\t\t\t\t\t\tconst nodeCacheSize = this._nodeCache.getStats().vsize;\n\n\t\t\t\t\t\tif (nodeCacheSize > this._heapLimit) {\n\t\t\t\t\t\t\t// Evict cache entries as needed\n\t\t\t\t\t\t\tlet deleteCount = 0;\n\t\t\t\t\t\t\tconst subArr = this._subscriptions.filter(a => a.cacheId && !a.clients.length);\n\t\t\t\t\t\n\t\t\t\t\t\t\tfor (let zz = 0; zz < subArr.length; zz++) {\n\t\t\t\t\t\t\t\tthis._debugRemoveCacheHits += 1;\n\t\t\t\t\t\t\t\tthis._nodeCache.del(subArr[zz].cacheId);\n\t\t\t\t\t\t\t\tsubArr[zz].cacheId = 0;\n\t\t\t\t\t\t\t\tdeleteCount += 1;\n\t\t\t\t\t\t\t\tif (this._nodeCache.getStats().vsize < this._heapLimit * 0.75) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\t'Sub Cache: ' +\n\t\t\t\t\t\t\t\t\t'Too Big - ' +\n\t\t\t\t\t\t\t\t\tsub.publication +\n\t\t\t\t\t\t\t\t\t' - Deleted: ' +\n\t\t\t\t\t\t\t\t\tdeleteCount +\n\t\t\t\t\t\t\t\t\t' - ' +\n\t\t\t\t\t\t\t\t\tnodeCacheSize\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tsub.cacheId = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tPromise.all(\n\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\t\tdata: err\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendPubData)\\n\\nData \\n' + JSON.stringify(sub.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate sendWS(ws: WebSocket, data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\t}\n\n\tpublic getEnableDebug() {\n\t\treturn this._enableDebug;\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../../src/managers/subscription.manager.ts"],"names":["logs_1","require","app_status_1","files_1","super_admin_1","logged_in_users_collection_1","cron_jobs_1","flags_1","method_responses_1","resolveio_server_app_1","notifications_1","report_builder_reports_1","report_builder_libraries_1","user_groups_1","user_guides_1","report_builder_dashboard_builders_1","common_1","NodeCache","flag_collection_1","os_1","flags_update_1","numCPUs","cpus","length","v8","SubscriptionManager","wss","serverConfig","monitorManagerFunction","_this","this","_publications","_subscriptions","_loggedInUsers","_mongoQueue","_mongoQueueId","_cacheId","_heapSize","getHeapStatistics","_enableDebug","_debugOplogCollections","_debugOplogHits","_debugSubCollections","_debugSubHits","_debugUnSubHits","_debugUnSubAllHits","_debugMongoQueueHits","_debugMongoQueueCollections","_debugSendQueueHits","_debugRemoveCacheHits","_oplogRetryCount","latencyBuffer","Map","LATENCY_UPDATE_INTERVAL","LATENCY_UPDATE_THRESHOLD_MS","_websocketManager","ResolveIOServer","getMainServer","getWebSocketManager","_monitorManagerFunction","_nodeCache","stdTTL","checkperiod","setInterval","flushThrottledLatencyUpdates","_wss","loadSuperAdminPublications","loadAppStatusPublications","loadLogPublications","loadFilePublications","loadCronJobPublications","loadFlagsUpdatePublications","loadFlagsPublications","loadMethodResponsePublications","loadNotificationPublications","loadReportBuilderReportPublications","loadReportBuilderLibraryPublications","loadUserGroupPublications","loadUserGuidePublications","loadReportBuilderDashboardBuilderPublications","tailOpLog","getEnableDebug","console","log","Date","JSON","stringify","sort","a","b","collection","localeCompare","publication","type","__awaiter","_a","LoggedInUsers","find","_b","sent","userCopy","deepCopy","i","loggedInUser","date","now","getTime","this_1","getWebSocket","id_ws","unsubscribeAll","forEach","sub","j","clients","id_socket","splice","deleteOne","_id","findIndex","client","this_2","some","Flags","findOne","then","flag","value","setCacheLimit","prototype","process","env","IS_WORKERS_ENABLED","_heapLimit","invalidatePubsCache","getMongoManager","invalidateQueryCache","collSubs","filter","collections","includes","this_3","running","runAgain","user_specific","Promise","all","map","ws","readyState","OPEN","sendDataToOneWithRetry","messageId","err","getMethodManager","sendEmail","id_user","sendDataToAllWithRetry","collSubs_1","__values","collSubs_1_1","next","done","delay","ms","resolve","setTimeout","sendDataToAll","sendDataToOne","publications","method","Object","assign","loggedInLatency","existingEntry","newLatency","get","lastUpdate","Math","abs","latency","set","size","updates","Array","from","entries","__read","_c","updateOne","update","$set","bulkWrite","clear","error","error_1","subscribe","messageRoute","messageDate","subscriptionData","pub","hits","push","check","_schema","valObj","rootKeys","keys","validate","errors","urlData","split","urlModule_1","urlNext","otherRouteSubs","startsWith","otherSub","unsubscribe","getPublicationCollections","cacheId","processSubscription","createLoggedInUser","reject","user","objectIdHexString","__v","insertOne","indexOf","userSubs","removeWebSocket","getActiveSubscriptions","resumeToken","_oplog$","closed","removeAllListeners","close","exit","pipeline","$match","$and","ns.coll","$nin","$not","lastResumeToken_1","getMainDB","watch","resumeAfter","errOp","on","doc","ns","coll","operationType","callMethod","call","documentKey","NODE_APP_INSTANCE","IS_WORKER_INSTANCE","WORKER_INDEX","cacheData","parse","dateReviver","serverRes","hasError","data","sendWS","del","monitor","startMonitorFunction","function","apply","__spreadArray","res","finishMonitorFunction","err_1","subIndex","res_1","getBinarySize","endsWith","nodeCacheSize","getStats","vsize","deleteCount","subArr","zz","err_2","send","exports"],"mappings":"+xEAGAA,Q,0FAAAC,QAAA,sBAAA,GACAC,aAAAD,QAAA,4BAAA,EACAE,QAAAF,QAAA,uBAAA,EACAG,cAAAH,QAAA,6BAAA,EACAI,6BAAAJ,QAAA,2CAAA,EACAK,YAAAL,QAAA,2BAAA,EACAM,QAAAN,QAAA,uBAAA,EACAO,mBAAAP,QAAA,kCAAA,EACAQ,uBAAAR,QAAA,yBAAA,EACAS,gBAAAT,QAAA,+BAAA,EACAU,yBAAAV,QAAA,wCAAA,EAIAW,2BAAAX,QAAA,0CAAA,EACAY,cAAAZ,QAAA,6BAAA,EACAa,cAAAb,QAAA,6BAAA,EACAc,oCAAAd,QAAA,mDAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,UAAAhB,QAAA,YAAA,EAEAiB,kBAAAjB,QAAA,gCAAA,EACAkB,KAAAlB,QAAA,IAAA,EAEAmB,eAAAnB,QAAA,8BAAA,EACMoB,SAAU,EAAAF,KAAAG,MAAI,EAAGC,OACjBC,GAAKvB,QAAQ,IAAI,EA0BvBwB,oBAAA,WAiDC,SAAAA,oBAAYC,EAAuBC,EAAcC,GAAjD,IAAAC,EAAAC,KA/CQA,KAAAC,cAAmC,GACnCD,KAAAE,eAA4C,GAE5CF,KAAAG,eAAsC,GAEtCH,KAAAI,YAAiC,GACjCJ,KAAAK,cAAgB,EAKhBL,KAAAM,SAAW,EAEXN,KAAAO,UAAYb,GAAGc,kBAAiB,EAAKjB,QAOrCS,KAAAS,aAAe,CAAA,EACfT,KAAAU,uBAAyB,GACzBV,KAAAW,gBAAkB,EAClBX,KAAAY,qBAAuB,GACvBZ,KAAAa,cAAgB,EAChBb,KAAAc,gBAAkB,EAClBd,KAAAe,mBAAqB,EACrBf,KAAAgB,qBAAuB,EACvBhB,KAAAiB,4BAA8B,GAC9BjB,K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E,QAAQiC,IAAI,SAAM3B,GAAM,OAAA1B,UAAAjE,EAAA,KAAA,EAAA,KAAA,EAAA,W,mDACvBuH,EAAKtH,KAAKyB,kBAAkBqD,aAAaY,EAAOL,SAAS,IACnDiC,EAAGC,aAAeD,EAAGE,OAC1BgH,EAAiC,CACpC9G,UAAWhC,EAAOgC,UAClB+G,SAAU,CAAA,EACVC,KAAMqB,C,EAGP/P,KAAK2O,OAAOrH,EAAIkH,CAAS,G,QAE1B,CAAC,EAGH7P,uBAAA+C,gBAAgBC,cAAa,EAAGiG,iBAAgB,EAAGC,UAAU,oBAAqB,6BAA+B7H,KAAKH,aAA0B,YAAG,sCAAwCqF,EAAIpB,YAAc,8BAAgCP,KAAKC,UAAU0B,EAAIuF,iBAAkB,KAAM,CAAC,EAAI,eAAiBlH,KAAKC,UAAUuM,EAAK,KAAM,CAAC,CAAC,E,6BAKrUpQ,oBAAAwG,UAAAwI,OAAR,SAAerH,EAAeoH,GAC7B1O,KAAKyB,kBAAkBuO,KAAK1I,EAAIoH,CAAI,CACrC,EAEO/O,oBAAAwG,UAAAhD,eAAP,WACC,OAAOnD,KAAKS,YACb,EACDd,mBAAA,EAAC,EA77BYsQ,QAAAtQ,oBAAAA","file":"subscription.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { ActiveSubscriptionModel, SubscriptionModel } from '../models/subscription.model';\nimport * as WebSocket from 'ws';\nimport { loadLogPublications } from '../publications/logs';\nimport { loadAppStatusPublications } from '../publications/app-status';\nimport { loadFilePublications } from '../publications/files';\nimport { loadSuperAdminPublications } from '../publications/super-admin';\nimport { LoggedInUsers } from '../collections/logged-in-users.collection';\nimport { loadCronJobPublications } from '../publications/cron-jobs';\nimport { loadFlagsPublications } from '../publications/flags';\nimport { loadMethodResponsePublications } from '../publications/method-responses';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { loadNotificationPublications } from '../publications/notifications';\nimport { loadReportBuilderReportPublications } from '../publications/report-builder-reports';\nimport { LoggedInUserModel } from '../models/logged-in-users.model';\n\nimport { ChangeStream, ChangeStreamDeleteDocument, ChangeStreamInsertDocument, ChangeStreamReplaceDocument, ChangeStreamUpdateDocument, ResumeToken } from 'mongodb';\nimport { loadReportBuilderLibraryPublications } from '../publications/report-builder-libraries';\nimport { loadUserGroupPublications } from '../publications/user-groups';\nimport { loadUserGuidePublications } from '../publications/user-guides';\nimport { loadReportBuilderDashboardBuilderPublications } from '../publications/report-builder-dashboard-builders';\nimport { dateReviver, deepCopy, getBinarySize, objectIdHexString } from '../util/common';\nimport * as NodeCache from 'node-cache';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { Flags } from '../collections/flag.collection';\nimport { cpus } from 'os';\nimport { WebSocketManager } from './websocket.manager';\nimport { loadFlagsUpdatePublications } from '../publications/flags-update';\nconst numCPUs = cpus().length;\nconst v8 = require('v8');\n\n// Performance Dependencies\n// import * as path from 'path';\n// import { Worker } from 'worker_threads';\n\ninterface MongoQueueModel {\n\t_id: number,\n\ttype: string;\n\tcollection: string;\n\tsubscription: ActiveSubscriptionModel;\n\trunning: boolean;\n\trun_again: boolean;\n}\n\n// interface CurrentPerformanceMonitor {\n// \t_id: number;\n// \tfunction: string;\n// \tpublication: string;\n// \tsubscriptionData: any[];\n// \tdate_start: Date;\n// \tdate_end: Date;\n// \tduration: number;\n// \tresult: string;\n// }\n\nexport class SubscriptionManager {\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _publications: SubscriptionModel = {};\n\tprivate _subscriptions: ActiveSubscriptionModel[] = [];\n\tprivate _wss: WebSocket.Server;\n\tprivate _loggedInUsers: LoggedInUserModel[] = [];\n\n\tprivate _mongoQueue: MongoQueueModel[] = [];\n\tprivate _mongoQueueId = 0;\n\t\n\tprivate _oplog$: ChangeStream;\n\n\tprivate _nodeCache;\n\tprivate _cacheId = 1;\n\n\tprivate _heapSize = v8.getHeapStatistics() / numCPUs;\n\tprivate _heapLimit: number;\n\n\tprivate serverConfig;\n\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _enableDebug = false;\n\tprivate _debugOplogCollections = [];\n\tprivate _debugOplogHits = 0;\n\tprivate _debugSubCollections = [];\n\tprivate _debugSubHits = 0;\n\tprivate _debugUnSubHits = 0;\n\tprivate _debugUnSubAllHits = 0;\n\tprivate _debugMongoQueueHits = 0;\n\tprivate _debugMongoQueueCollections = [];\n\tprivate _debugSendQueueHits = 0;\n\tprivate _debugRemoveCacheHits = 0;\n\n\tprivate _oplogRetryCount = 0;\n\n\t// Buffer to store throttled latency updates with timestamps\n\tprivate latencyBuffer = new Map<string, { latency: number, lastUpdate: Date }>();\n\n\t// Interval to flush latency updates in MongoDB\n\tprivate readonly LATENCY_UPDATE_INTERVAL = 60000;\n\n\t// Minimum time difference between two latency updates for the same user\n\tprivate readonly LATENCY_UPDATE_THRESHOLD_MS = 30000;\n\n\t// private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];\n\t// private idPerformance: number = 0;\n\t// private performanceThread;\n\n\tconstructor(wss: WebSocket.Server, serverConfig, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._websocketManager = ResolveIOServer.getMainServer().getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\tthis._nodeCache = new NodeCache( { stdTTL: 0, checkperiod: 0 } );\n\n\t\tsetInterval(() => this.flushThrottledLatencyUpdates(), this.LATENCY_UPDATE_INTERVAL);\n\n\t\t// setTimeout(() => {\n\t\t// \tconsole.log('Setting up performance thread');\n\n\t\t// \tthis.performanceThread = new Worker(path.join(__dirname, './subscription.performance.js'));\n\n\t\t// \tthis.performanceThread.on('exit', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD EXITED!!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\n\t\t// \tthis.performanceThread.on('error', code => {\n\t\t// \t\tconsole.error(new Date(), 'THREAD RECV ERROR !!!!!!!!!!!!!!!!!!', code);\n\t\t// \t});\n\t\t// }, 5000);\n\n\t\t// setInterval(() => {\n\t\t// \tconsole.log('Post thread msg');\n\t\t// \tthis.performanceThread.postMessage(this.currentPerfomanceMonitor);\n\t\t// \tthis.currentPerfomanceMonitor = [];\n\t\t// }, 10000);\n\n\t\tthis.serverConfig = serverConfig;\n\t\tthis._wss = wss;\n\n\t\t// Publications\n\t\tloadSuperAdminPublications(this);\n\t\tloadAppStatusPublications(this);\n\t\tloadLogPublications(this);\n\t\tloadFilePublications(this);\n\t\tloadCronJobPublications(this);\n\t\tloadFlagsUpdatePublications(this);\n\t\tloadFlagsPublications(this);\n\t\tloadMethodResponsePublications(this);\n\t\tloadNotificationPublications(this);\n\t\tloadReportBuilderReportPublications(this);\n\t\tloadReportBuilderLibraryPublications(this);\n\t\tloadUserGroupPublications(this);\n\t\tloadUserGuidePublications(this);\n\t\tloadReportBuilderDashboardBuilderPublications(this);\n\n\t\tthis.tailOpLog();\n\n\t\tsetInterval(() => {\n\t\t\tthis._oplogRetryCount = 0;\n\t\t}, 15000);\n\n\t\tsetInterval(() => {\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Subs', this._subscriptions.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Logged In Users', this._loggedInUsers.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue', this._mongoQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Hits', this._debugMongoQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Mongo Queue Collections', JSON.stringify(this._debugMongoQueueCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Hits', this._debugOplogHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Oplog Collections', JSON.stringify(this._debugOplogCollections.sort((a, b) => a.collection.localeCompare(b.collection) || a.type.localeCompare(b.type)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Hits', this._debugSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Sub Collections', JSON.stringify(this._debugSubCollections.sort((a, b) => a.publication.localeCompare(b.publication)), null, 2));\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub Hits', this._debugUnSubHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub All Hits', this._debugUnSubAllHits);\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Cache Cleanup Hits', this._debugRemoveCacheHits);\n\t\t\t}\n\t\t\t\n\t\t\tthis._debugOplogHits = 0;\n\t\t\tthis._debugOplogCollections = [];\n\t\t\tthis._debugSubCollections = [];\n\t\t\tthis._debugMongoQueueHits = 0;\n\t\t\tthis._debugMongoQueueCollections = [];\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSubHits = 0;\n\t\t\tthis._debugUnSubHits = 0;\n\t\t\tthis._debugUnSubAllHits = 0;\n\t\t\tthis._debugRemoveCacheHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(async () => {\n\t\t\tthis._loggedInUsers = await LoggedInUsers.find();\n\t\n\t\t\tlet userCopy = deepCopy(this._loggedInUsers);\n\t\t\tfor (let i = this._loggedInUsers.length - 1; i >= 0; i--) {\n\t\t\t\tlet loggedInUser = userCopy[i];\n\n\t\t\t\tif (!loggedInUser.date || Date.now() - loggedInUser.date.getTime() > 120000) {\n\t\t\t\t\tif (this._websocketManager.getWebSocket(loggedInUser.id_ws)) {\n\t\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', this._websocketManager.getWebSocket(loggedInUser.id_ws)['user'], this._websocketManager.getWebSocket(loggedInUser.id_ws)['id_socket'], 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.unsubscribeAll(this._websocketManager.getWebSocket(loggedInUser.id_ws));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._subscriptions.forEach(sub => {\n\t\t\t\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\t\t\t\tif (client.id_socket === loggedInUser.id_ws) {\n\t\t\t\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tLoggedInUsers.deleteOne({_id: loggedInUser._id});\n\n\t\t\t\t\t\tif (this._loggedInUsers.findIndex(a => a._id === loggedInUser._id) >= 0) {\n\t\t\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.findIndex(a => a._id === loggedInUser._id), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (let i = 0; i < this._subscriptions.length; i++) {\n\t\t\t\tlet sub = this._subscriptions[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tlet client = sub.clients[j];\n\n\t\t\t\t\tif (!this._loggedInUsers.some(a => a.id_ws === client.id_socket)) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, 30000);\n\n\t\tFlags.findOne({type: 'Enable Debug'}).then(flag => {\n\t\t\tif (flag && flag.value) {\n\t\t\t\tthis._enableDebug = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._enableDebug = false;\n\t\t\t}\n\t\t});\n\n\t\tthis.setCacheLimit();\n\t}\n\n\tprivate setCacheLimit() {\t\n\t\tif (process.env.IS_WORKERS_ENABLED === 'true') {\n\t\t\tthis._heapLimit = this._heapSize * 0.4;\n\t\t}\n\t\telse {\n\t\t\tthis._heapLimit = this._heapSize * 0.3; // Use 50% of total heap size\n\t\t}\n\t}\n\n\tpublic async invalidatePubsCache(collection: string, type: string) {\n\t\tResolveIOServer.getMongoManager().invalidateQueryCache(collection);\n\n\t\tlet collSubs = this._subscriptions.filter(a => a.collections.includes(collection));\n\n\t\tfor (let sub of collSubs) {\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Invalidate Sub', sub.publication, sub.running, sub.runAgain);\n\t\t\t}\n\n\t\t\tif (sub.running) {\n\t\t\t\tsub.runAgain = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (this._publications[sub.publication].user_specific) {\n\t\t\t\tPromise.all(\n\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tthis.sendDataToOneWithRetry(ws, client.messageId, sub, collection, type);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t// Handle error\n\t\t\t\t\t\t\t\tResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During sendDataToOne - User Specific - Socket: ' + client.id_socket + ', User: ' + client.id_user + ', MessageId: ' + client.messageId + ', Pub: ' + sub.publication + ', Err: ' + JSON.stringify(err, null, 2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.sendDataToAllWithRetry(sub, collection, type);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async delay(ms: number) {\n\t\treturn new Promise(resolve => setTimeout(resolve, ms));\n\t}\n\n\tprivate async sendDataToAllWithRetry(sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tsub.running = true;\n\n\t\tdo {\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Running sendDataToAll Sub', sub.publication);\n\t\t\t}\n\n\t\t\tsub.runAgain = false;\n\t\t\tawait this.sendDataToAll(sub, collection, type);\n\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Done sendDataToAll Sub', sub.publication, sub.runAgain);\n\t\t\t}\n\n\t\t\tif (sub.runAgain) {\n\t\t\t\tawait this.delay(500); // delay, adjust as needed\n\t\t\t}\n\t\t} while (sub.runAgain);\n\n\t\tsub.running = false;\n\t}\n\n\tprivate async sendDataToOneWithRetry(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tsub.running = true;\n\n\t\tdo {\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Running sendDataToOne Sub', sub.publication);\n\t\t\t}\n\n\t\t\tsub.runAgain = false;\n\t\t\tawait this.sendDataToOne(ws, messageId, sub, collection, type);\n\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Done sendDataToOne Sub', sub.publication, sub.runAgain);\n\t\t\t}\n\n\t\t\tif (sub.runAgain) {\n\t\t\t\tawait this.delay(500); // delay, adjust as needed\n\t\t\t}\n\t\t} while (sub.runAgain);\n\t\tsub.running = false;\n\t}\n\n\t// Add all files to publications private object\n\tpublic publications(method: SubscriptionModel) {\n\t\tthis._publications = Object.assign(this._publications, method);\n\t}\n\n\t// Throttled `loggedInLatency` method\n\tpublic loggedInLatency(ws: WebSocket) {\n\t\tlet loggedInUser = this._loggedInUsers.find(a => a.id_ws === ws['id_socket']);\n\t\tif (!loggedInUser) return;\n\n\t\tconst now = new Date();\n\t\tconst existingEntry = this.latencyBuffer.get(ws['id_socket']);\n\t\tconst newLatency = ws['latency'];\n\n\t\t// Throttle updates: only update if time threshold has passed or latency has significantly changed\n\t\tif (\n\t\t\t!existingEntry || \n\t\t\t(now.getTime() - existingEntry.lastUpdate.getTime() >= this.LATENCY_UPDATE_THRESHOLD_MS) || \n\t\t\t(Math.abs(newLatency - existingEntry.latency) > 100) // Optional: log only significant changes\n\t\t) {\n\t\t\t// Update in-memory and buffer\n\t\t\tloggedInUser.date = now;\n\t\t\tthis.latencyBuffer.set(ws['id_socket'], { latency: newLatency, lastUpdate: now });\n\t\t}\n\t}\n\n\t// Method to flush buffered latency updates in bulk\n\tprivate async flushThrottledLatencyUpdates() {\n\t\tif (this.latencyBuffer.size === 0) return; // No updates to flush\n\n\t\tconst updates = Array.from(this.latencyBuffer.entries()).map(([id_ws, { latency, lastUpdate }]) => ({\n\t\t\tupdateOne: {\n\t\t\t\tfilter: { id_ws },\n\t\t\t\tupdate: { $set: { latency, date: lastUpdate } }\n\t\t\t}\n\t\t}));\n\n\t\ttry {\n\t\t\tawait LoggedInUsers.bulkWrite(updates);\n\t\t\tthis.latencyBuffer.clear(); // Clear buffer after successful update\n\n\t\t\tif (this.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Throttled latency batch update successful', updates.length);\n\t\t\t}\n\t\t}\n\t\tcatch (error) {\n\t\t\tconsole.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error);\n\t\t\t// Optional: implement retry logic or logging for failed updates\n\t\t}\n\t}\n\n\t// Subscribe to publication\n\tpublic subscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugSubHits += 1;\n\n\t\tif (!this._debugSubCollections.some(a => a.publication === publication)) {\n\t\t\tthis._debugSubCollections.push({\n\t\t\t\tpublication: publication,\n\t\t\t\thits: 1\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tthis._debugSubCollections.find(a => a.publication === publication).hits += 1;\n\t\t}\n\n\t\tlet pub = this._publications[publication];\n\n\t\tif (!pub) {\n\t\t\tconsole.error(new Date(), 'No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tif (subscriptionData.length > 1 || subscriptionData[0]) {\n\t\t\t\tif (!pub.check) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Function For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (!pub.check._schema) {\n\t\t\t\t\tconsole.error(new Date(), 'No Check Schema For Pub ' + publication);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet valObj = {};\n\t\t\t\t\tlet valKeys = Object.keys(pub.check._schema);\n\n\t\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\t\tfor (let i = 0; i < subscriptionData.length; i++) {\n\t\t\t\t\t\tvalObj[rootKeys[i]] = subscriptionData[i];\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpub.check.validate(valObj);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (errors) {\n\t\t\t\t\t\tif (errors) {\n\t\t\t\t\t\t\tconsole.error(new Date(), 'Error in Pub Check (' + publication + ')', errors);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (messageRoute !== 'Bypass') {\n\t\t\t\tlet urlData = messageRoute.split('/');\n\t\t\t\tlet urlModule = '';\n\t\t\t\tlet urlNext = urlData[0];\n\n\t\t\t\tif (urlData[0] === '') {\n\t\t\t\t\turlModule = '/';\n\t\t\t\t\turlNext = urlData[1];\n\t\t\t\t}\n\n\t\t\t\turlModule += urlNext;\n\n\t\t\t\tif (urlData.length > 1) {\n\t\t\t\t\turlModule += '/';\n\t\t\t\t}\n\n\t\t\t\tlet otherRouteSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_socket === ws['id_socket'] && b.messageRoute !== 'Bypass' && b.messageRoute !== '/' && b.messageRoute !== messageRoute && !b.messageRoute.startsWith(urlModule)));\n\n\t\t\t\tif (otherRouteSubs.length) {\n\t\t\t\t\t// ResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Detected Undestroyed Subscription - ' + this.serverConfig['CLIENT_NAME'], 'USER: ' + ws['user'] + ' (Socket: ' + ws['id_socket'] + ') ' + ' is on route: ' + messageRoute + ' but has the following subscriptions on other routes:' + JSON.stringify(otherRouteSubs, null, 2));\n\n\t\t\t\t\totherRouteSubs.forEach(otherSub => {\n\t\t\t\t\t\totherSub.clients.filter(a => a.id_socket === ws['id_socket']).forEach(client => {\n\t\t\t\t\t\t\tthis.unsubscribe(client.messageRoute, new Date(), ws, client.messageId, otherSub.publication, otherSub.subscriptionData);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet sub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\n\t\t\t// If sub found (another user watching same data), add client to same sub\n\t\t\tif (sub) {\n\t\t\t\tif (!sub.clients.some(a => a.id_socket === ws['id_socket'] && a.messageId === messageId)) {\n\t\t\t\t\tsub.clients.push({\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If sub not found, create new sub\n\t\t\telse {\n\t\t\t\tthis._subscriptions.push({\n\t\t\t\t\tpublication: publication,\n\t\t\t\t\tsubscriptionData: subscriptionData,\n\t\t\t\t\tcollections: this.getPublicationCollections(publication),\n\t\t\t\t\tclients: [{\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\tid_socket: ws['id_socket'],\n\t\t\t\t\t\tmessageRoute: messageRoute,\n\t\t\t\t\t}],\n\t\t\t\t\tcacheId: 0,\n\t\t\t\t\trunning: false,\n\t\t\t\t\trunAgain: false\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!sub) {\n\t\t\t\tsub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\t\t\t}\n\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'New Sub', sub.publication, sub.running, sub.runAgain, sub.clients.length);\n\t\t\t}\n\n\t\t\t// Immediately send data to the new client\n\t\t\tthis.processSubscription(sub, ws, messageId);\n\t\t}\n\t}\n\n\tpublic async createLoggedInUser(id_ws: string): Promise<LoggedInUserModel> {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tlet ws = this._websocketManager.getWebSocket(id_ws);\n\n\t\t\tif (ws) {\n\t\t\t\tlet user = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tthis._loggedInUsers.push(user);\n\t\t\t\tLoggedInUsers.insertOne(user);\n\t\t\t\t\n\t\t\t\tresolve(user);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(null);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Unsubscribe from publication \n\tpublic unsubscribe(messageRoute: string, messageDate: Date, ws: WebSocket, messageId: number, publication: string, subscriptionData: any[]) {\n\t\tthis._debugUnSubHits += 1;\n\n\t\tif (!this._publications[publication]) {\n\t\t\tconsole.log('No Publication: ' + publication);\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet sub = this._subscriptions.find(a => a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData));\n\n\t\t\tif (sub) {\n\t\t\t\tfor (let i = sub.clients.length - 1; i >= 0; i--) {\n\t\t\t\t\tif (sub.clients[i].id_user === ws['id_user'] && sub.clients[i].messageId === messageId && sub.clients[i].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(i, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\tconsole.log(new Date(), 'Unsub', sub.publication, sub.running, sub.runAgain, sub.clients.length);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// Unsubscribe from publication\n\tpublic async unsubscribeAll(ws: WebSocket) {\n\t\tthis._debugUnSubAllHits += 1;\n\n\t\tif (ws) {\n\t\t\t// Check if WebSocket has already been unsubscribed\n\t\t\tif (ws['isUnsubscribed']) {\n\t\t\t\treturn; // Skip if already unsubscribed\n\t\t\t}\n\t\t\t\n\t\t\t// Mark the WebSocket as unsubscribed to prevent further calls\n\t\t\tws['isUnsubscribed'] = true;\n\t\t\t\n\t\t\tif (this._loggedInUsers.map(a => a.id_ws).indexOf(ws['id_socket']) >= 0) {\n\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.map(a => a.id_ws).indexOf(ws['id_socket']), 1);\n\t\t\t}\n\t\t\tLoggedInUsers.deleteOne({ id_ws: ws['id_socket'] });\n\n\t\t\tlet userSubs = this._subscriptions.filter(a => a.clients.some(b => b.id_user === ws['id_user'] && b.id_socket === ws['id_socket']));\n\n\t\t\tfor (let i = userSubs.length - 1; i >= 0; i--) {\n\t\t\t\tlet sub = userSubs[i];\n\n\t\t\t\tfor (let j = sub.clients.length - 1; j >= 0; j--) {\n\t\t\t\t\tif (sub.clients[j].id_socket === ws['id_socket']) {\n\t\t\t\t\t\tsub.clients.splice(j, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._websocketManager.removeWebSocket(ws);\n\t\t}\n\t}\n\n\tpublic getActiveSubscriptions() {\n\t\treturn this._subscriptions;\n\t}\n\n\t// Get publication collection\n\tprivate getPublicationCollections(publication: string) {\n\t\treturn this._publications[publication].collections;\n\t}\n\n\t// Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)\n\tprivate async tailOpLog(resumeToken?: ResumeToken) {\n\t\tif (this._oplog$ && !this._oplog$.closed) {\n\t\t\tthis._oplog$.removeAllListeners();\n\t\t\tthis._oplog$.close();\n\t\t\tthis._oplog$ = null;\n\t\t}\n\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\n\t\tif (!this._oplog$ || this._oplog$.closed) {\n\t\t\tthis._oplogRetryCount += 1;\n\n\t\t\tif (this._oplogRetryCount > 5) {\n\t\t\t\tconsole.error('****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\n\t\t\tconst pipeline = [\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t$and: [\n\t\t\t\t\t\t\t{'ns.coll': { $nin: ['logs'] }},\n\t\t\t\t\t\t\t{'ns.coll': { $not: /.*\\.versions$/ }},\n\t\t\t\t\t\t\t{'ns.coll': { $not: /^monitor-/ }},\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\n\t\t\tlet lastResumeToken: ResumeToken;\n\n\t\t\tif (resumeToken) {\n\t\t\t\tlastResumeToken = resumeToken;\n\t\t\t\ttry {\n\t\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch(pipeline, { resumeAfter: resumeToken });\n\t\t\t\t}\n\t\t\t\tcatch (errOp) {\n\t\t\t\t\tif (this._oplog$) {\n\t\t\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\t\t\tthis._oplog$.close();\n\t\t\t\t\t\tthis._oplog$ = null;\n\t\t\t\t\t}\n\t\t\t\t\tthis.tailOpLog(resumeToken);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._oplog$ = ResolveIOServer.getMainDB().watch(pipeline);\n\t\t\t}\n\n\t\t\tconsole.log(new Date(), 'oplog started');\n\n\t\t\tthis._oplog$.on('change', (doc: ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument) => {\n\t\t\t\tif (doc.ns) {\n\t\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Oplog Hit', doc.ns);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet collection = doc.ns.coll;\n\n\t\t\t\t\tif (!this._debugOplogCollections.some(a => a.collection === doc.ns.coll && a.type === doc.operationType)) {\n\t\t\t\t\t\tthis._debugOplogCollections.push({\n\t\t\t\t\t\t\tcollection: doc.ns.coll,\n\t\t\t\t\t\t\ttype: doc.operationType,\n\t\t\t\t\t\t\thits: 1\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._debugOplogCollections.find(a => a.collection === doc.ns.coll && a.type === doc.operationType).hits += 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection) {\n\t\t\t\t\t\tthis._debugOplogHits += 1;\n\n\t\t\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\t\t\tif (collection === 'support-tickets') {\n\t\t\t\t\t\t\t\tif (this.serverConfig['ROOT_URL'] === 'https://resolveio.com') {\n\t\t\t\t\t\t\t\t\tResolveIOServer.getMainServer().getMethodManager().callMethod.call(ResolveIOServer.getMainServer().getMethodManager(), 'sendSupportTicketEmail', doc.documentKey['_id']);\n\t\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'insert');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'update' || doc.operationType === 'replace') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'update');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\t\t\tif (collection !== 'method-responses') {\n\t\t\t\t\t\t\t\tthis.invalidatePubsCache(collection, 'delete');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (collection === 'flags') {\n\t\t\t\t\t\tFlags.findOne({ type: 'Enable Debug' }).then(flag => {\n\t\t\t\t\t\t\tif (flag && flag.value) {\n\t\t\t\t\t\t\t\tthis._enableDebug = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthis._enableDebug = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tlastResumeToken = doc._id;\n\n\t\t\t\t\tif ((!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') && (process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0'))) {\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tthis._oplog$.on('error', error => {\n\t\t\t\tconsole.log(new Date(), 'oplog error', error);\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('end', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog end');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$.close();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\n\t\t\tthis._oplog$.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'oplog close');\n\t\t\t\tthis._oplog$.removeAllListeners();\n\t\t\t\tthis._oplog$ = null;\n\t\t\t\tthis.tailOpLog(lastResumeToken);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async processSubscription(sub: ActiveSubscriptionModel, ws: WebSocket, messageId: number) {\n\t\tif (!this._publications[sub.publication].user_specific) {\t\t\t\n\t\t\tif (sub.cacheId) {\n\t\t\t\ttry {\n\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), dateReviver);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\tdata: cacheData\n\t\t\t\t\t};\n\n\t\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Process Sub, Cache', sub.publication);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\t\tsub.cacheId = 0;\n\n\t\t\t\t\tthis.sendDataToAllWithRetry(sub, '', 'newSub');\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\tconsole.log(new Date(), 'Process Sub, Non - Cache', sub.publication, sub.running);\n\t\t\t\t}\n\n\t\t\t\tif (sub.running) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.sendDataToAllWithRetry(sub, '', 'newSub');\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (this._enableDebug) {\n\t\t\t\tconsole.log(new Date(), 'Process Sub Specific, Non - Cache', sub.publication, sub.running);\n\t\t\t}\n\n\t\t\tif (sub.running) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tthis.sendDataToOneWithRetry(ws, messageId, sub, '', 'newSub');\n\t\t}\n\t}\n\n\tprivate async sendDataToOne(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', sub.publication, '', '', sub.subscriptionData);\n\t\ttry {\n\t\t\tResolveIOServer.getMainServer().getMethodManager().callMethod.call(ResolveIOServer.getMainServer().getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));\n\n\t\t\tlet res = await this._publications[sub.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ws['id_user'], ...sub.subscriptionData);\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: res\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, serverRes);\n\t\t}\n\t\tcatch (err) {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: err\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, serverRes);\n\n\t\t\tResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendDataToOne - WS)\\n\\nData \\n' + JSON.stringify(sub.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t}\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate async sendDataToAll(sub: ActiveSubscriptionModel, collection: string, type: string) {\n\t\tif (!sub.clients.length) {\n\t\t\tif (sub.cacheId) {\n\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\t\t\t\tsub.cacheId = 0;\n\t\t\t}\n\n\t\t\tlet subIndex = this._subscriptions.findIndex(a => a.publication === sub.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(sub.subscriptionData));\n\t\t\tif (subIndex >= 0) {\n\t\t\t\tthis._subscriptions.splice(subIndex, 1);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Publication', sub.publication, '', '', sub.subscriptionData);\n\n\t\t\ttry {\n\t\t\t\tif (sub.publication !== 'superadminAPM' && sub.publication !== 'loggedInUsers') {\n\t\t\t\t\tResolveIOServer.getMainServer().getMethodManager().callMethod.call(ResolveIOServer.getMainServer().getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));\n\t\t\t\t}\n\n\t\t\t\tlet res = await this._publications[sub.publication].function.call(Object.assign({}, this, SubscriptionManager.prototype), ...sub.subscriptionData);\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tif (sub.cacheId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlet cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), dateReviver);\n\t\n\t\t\t\t\t\tif (JSON.stringify(cacheData) !== JSON.stringify(res)) {\n\t\t\t\t\t\t\tPromise.all(\n\t\t\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\n\t\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\n\t\t\t\t\t\t\tif (getBinarySize(JSON.stringify(res)) < 1000000 && \n\t\t\t\t\t\t\t\t!sub.collections.includes('logs') &&\n\t\t\t\t\t\t\t\t!sub.collections.find(a => a.endsWith('.versions')) &&\n\t\t\t\t\t\t\t\t!sub.collections.find(a => a.startsWith('monitor-'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tsub.cacheId = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tPromise.all(\n\t\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t\t};\n\t\t\n\t\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tthis._nodeCache.del(sub.cacheId);\n\n\t\t\t\t\t\tif (getBinarySize(JSON.stringify(res)) < 1000000 && \n\t\t\t\t\t\t\t!sub.collections.includes('logs') &&\n\t\t\t\t\t\t\t!sub.collections.find(a => a.endsWith('.versions')) &&\n\t\t\t\t\t\t\t!sub.collections.find(a => a.startsWith('monitor-'))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsub.cacheId = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tPromise.all(\n\t\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\t\thasError: false,\n\t\t\t\t\t\t\t\t\tdata: res\n\t\t\t\t\t\t\t\t};\n\t\n\t\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tif (getBinarySize(JSON.stringify(res)) < 1000000 && \n\t\t\t\t\t\t!sub.collections.includes('logs') &&\n\t\t\t\t\t\t!sub.collections.find(a => a.endsWith('.versions')) &&\n\t\t\t\t\t\t!sub.collections.find(a => a.startsWith('monitor-'))\n\t\t\t\t\t) {\n\t\t\t\t\t\tsub.cacheId = this._cacheId++;\n\t\t\t\t\t\tthis._nodeCache.set(sub.cacheId, JSON.stringify(res));\n\n\t\t\t\t\t\tconst nodeCacheSize = this._nodeCache.getStats().vsize;\n\n\t\t\t\t\t\tif (nodeCacheSize > this._heapLimit) {\n\t\t\t\t\t\t\t// Evict cache entries as needed\n\t\t\t\t\t\t\tlet deleteCount = 0;\n\t\t\t\t\t\t\tconst subArr = this._subscriptions.filter(a => a.cacheId && !a.clients.length);\n\t\t\t\t\t\n\t\t\t\t\t\t\tfor (let zz = 0; zz < subArr.length; zz++) {\n\t\t\t\t\t\t\t\tthis._debugRemoveCacheHits += 1;\n\t\t\t\t\t\t\t\tthis._nodeCache.del(subArr[zz].cacheId);\n\t\t\t\t\t\t\t\tsubArr[zz].cacheId = 0;\n\t\t\t\t\t\t\t\tdeleteCount += 1;\n\t\t\t\t\t\t\t\tif (this._nodeCache.getStats().vsize < this._heapLimit * 0.75) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (this._enableDebug) {\n\t\t\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\t\t'Sub Cache: ' +\n\t\t\t\t\t\t\t\t\t'Too Big - ' +\n\t\t\t\t\t\t\t\t\tsub.publication +\n\t\t\t\t\t\t\t\t\t' - Deleted: ' +\n\t\t\t\t\t\t\t\t\tdeleteCount +\n\t\t\t\t\t\t\t\t\t' - ' +\n\t\t\t\t\t\t\t\t\tnodeCacheSize\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tsub.cacheId = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tPromise.all(\n\t\t\t\t\tsub.clients.map(async client => {\n\t\t\t\t\t\tlet ws = this._websocketManager.getWebSocket(client.id_socket);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\t\tmessageId: client.messageId,\n\t\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\t\tdata: err\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\tthis.sendWS(ws, serverRes);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendPubData)\\n\\nData \\n' + JSON.stringify(sub.subscriptionData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate sendWS(ws: WebSocket, data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\t}\n\n\tpublic getEnableDebug() {\n\t\treturn this._enableDebug;\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.6.13",
3
+ "version": "20.6.15",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",
package/public_api.d.ts CHANGED
@@ -13,6 +13,7 @@ export * from './collections/log.collection';
13
13
  export * from './collections/logged-in-users.collection';
14
14
  export * from './collections/method-response.collection';
15
15
  export * from './collections/monitor-cpu.collection';
16
+ export * from './collections/monitor-function.collection';
16
17
  export * from './collections/monitor-memory.collection';
17
18
  export * from './collections/monitor-mongo.collection';
18
19
  export * from './collections/notification.collection';
package/public_api.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var l=Object.getOwnPropertyDescriptor(r,o);l&&("get"in l?r.__esModule:!l.writable&&!l.configurable)||(l={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,l)}:function(e,r,o,t){e[t=void 0===t?o:t]=r[o]}),__exportStar=this&&this.__exportStar||function(e,r){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(r,o)||__createBinding(r,e,o)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(require("./collections/app-status.collection"),exports),__exportStar(require("./collections/counter.collection"),exports),__exportStar(require("./collections/cron-job-history.collection"),exports),__exportStar(require("./collections/cron-job.collection"),exports),__exportStar(require("./collections/email-history.collection"),exports),__exportStar(require("./collections/email-verified.collection"),exports),__exportStar(require("./collections/file.collection"),exports),__exportStar(require("./collections/flag.collection"),exports),__exportStar(require("./collections/flag-update.collection"),exports),__exportStar(require("./collections/log-method-latency.collection"),exports),__exportStar(require("./collections/log-subscription.collection"),exports),__exportStar(require("./collections/log.collection"),exports),__exportStar(require("./collections/logged-in-users.collection"),exports),__exportStar(require("./collections/method-response.collection"),exports),__exportStar(require("./collections/monitor-cpu.collection"),exports),__exportStar(require("./collections/monitor-memory.collection"),exports),__exportStar(require("./collections/monitor-mongo.collection"),exports),__exportStar(require("./collections/notification.collection"),exports),__exportStar(require("./collections/report-builder-library.collection"),exports),__exportStar(require("./collections/report-builder-report.collection"),exports),__exportStar(require("./collections/user-group.collection"),exports),__exportStar(require("./collections/user-guide.collection"),exports),__exportStar(require("./collections/user.collection"),exports),__exportStar(require("./models/app-status.model"),exports),__exportStar(require("./models/billing-logged-in-users.model"),exports),__exportStar(require("./models/collection-document.model"),exports),__exportStar(require("./models/counter.model"),exports),__exportStar(require("./models/cron-job-history.model"),exports),__exportStar(require("./models/cron-job.model"),exports),__exportStar(require("./models/dialog.model"),exports),__exportStar(require("./models/email-history.model"),exports),__exportStar(require("./models/email-verified.model"),exports),__exportStar(require("./models/file.model"),exports),__exportStar(require("./models/flag.model"),exports),__exportStar(require("./models/flag-update.model"),exports),__exportStar(require("./models/log-method-latency.model"),exports),__exportStar(require("./models/log-subscription.model"),exports),__exportStar(require("./models/log.model"),exports),__exportStar(require("./models/logged-in-users.model"),exports),__exportStar(require("./models/method-response.model"),exports),__exportStar(require("./models/method.model"),exports),__exportStar(require("./models/monitor-cpu.model"),exports),__exportStar(require("./models/monitor-memory.model"),exports),__exportStar(require("./models/monitor-mongo.model"),exports),__exportStar(require("./models/notification.model"),exports),__exportStar(require("./models/pagination.model"),exports),__exportStar(require("./models/permission.model"),exports),__exportStar(require("./models/report-builder-library.model"),exports),__exportStar(require("./models/report-builder-report.model"),exports),__exportStar(require("./models/report-builder.model"),exports),__exportStar(require("./models/select-data-label.model"),exports),__exportStar(require("./models/server-response.model"),exports),__exportStar(require("./models/subscription.model"),exports),__exportStar(require("./models/support-ticket.model"),exports),__exportStar(require("./models/user-group.model"),exports),__exportStar(require("./models/user-guide.model"),exports),__exportStar(require("./models/user.model"),exports),__exportStar(require("./util/common"),exports),__exportStar(require("./managers/mongo.manager"),exports),__exportStar(require("./resolveio-server-app"),exports);
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var l=Object.getOwnPropertyDescriptor(r,o);l&&("get"in l?r.__esModule:!l.writable&&!l.configurable)||(l={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,l)}:function(e,r,o,t){e[t=void 0===t?o:t]=r[o]}),__exportStar=this&&this.__exportStar||function(e,r){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(r,o)||__createBinding(r,e,o)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(require("./collections/app-status.collection"),exports),__exportStar(require("./collections/counter.collection"),exports),__exportStar(require("./collections/cron-job-history.collection"),exports),__exportStar(require("./collections/cron-job.collection"),exports),__exportStar(require("./collections/email-history.collection"),exports),__exportStar(require("./collections/email-verified.collection"),exports),__exportStar(require("./collections/file.collection"),exports),__exportStar(require("./collections/flag.collection"),exports),__exportStar(require("./collections/flag-update.collection"),exports),__exportStar(require("./collections/log-method-latency.collection"),exports),__exportStar(require("./collections/log-subscription.collection"),exports),__exportStar(require("./collections/log.collection"),exports),__exportStar(require("./collections/logged-in-users.collection"),exports),__exportStar(require("./collections/method-response.collection"),exports),__exportStar(require("./collections/monitor-cpu.collection"),exports),__exportStar(require("./collections/monitor-function.collection"),exports),__exportStar(require("./collections/monitor-memory.collection"),exports),__exportStar(require("./collections/monitor-mongo.collection"),exports),__exportStar(require("./collections/notification.collection"),exports),__exportStar(require("./collections/report-builder-library.collection"),exports),__exportStar(require("./collections/report-builder-report.collection"),exports),__exportStar(require("./collections/user-group.collection"),exports),__exportStar(require("./collections/user-guide.collection"),exports),__exportStar(require("./collections/user.collection"),exports),__exportStar(require("./models/app-status.model"),exports),__exportStar(require("./models/billing-logged-in-users.model"),exports),__exportStar(require("./models/collection-document.model"),exports),__exportStar(require("./models/counter.model"),exports),__exportStar(require("./models/cron-job-history.model"),exports),__exportStar(require("./models/cron-job.model"),exports),__exportStar(require("./models/dialog.model"),exports),__exportStar(require("./models/email-history.model"),exports),__exportStar(require("./models/email-verified.model"),exports),__exportStar(require("./models/file.model"),exports),__exportStar(require("./models/flag.model"),exports),__exportStar(require("./models/flag-update.model"),exports),__exportStar(require("./models/log-method-latency.model"),exports),__exportStar(require("./models/log-subscription.model"),exports),__exportStar(require("./models/log.model"),exports),__exportStar(require("./models/logged-in-users.model"),exports),__exportStar(require("./models/method-response.model"),exports),__exportStar(require("./models/method.model"),exports),__exportStar(require("./models/monitor-cpu.model"),exports),__exportStar(require("./models/monitor-memory.model"),exports),__exportStar(require("./models/monitor-mongo.model"),exports),__exportStar(require("./models/notification.model"),exports),__exportStar(require("./models/pagination.model"),exports),__exportStar(require("./models/permission.model"),exports),__exportStar(require("./models/report-builder-library.model"),exports),__exportStar(require("./models/report-builder-report.model"),exports),__exportStar(require("./models/report-builder.model"),exports),__exportStar(require("./models/select-data-label.model"),exports),__exportStar(require("./models/server-response.model"),exports),__exportStar(require("./models/subscription.model"),exports),__exportStar(require("./models/support-ticket.model"),exports),__exportStar(require("./models/user-group.model"),exports),__exportStar(require("./models/user-guide.model"),exports),__exportStar(require("./models/user.model"),exports),__exportStar(require("./util/common"),exports),__exportStar(require("./managers/mongo.manager"),exports),__exportStar(require("./resolveio-server-app"),exports);
2
2
  //# sourceMappingURL=public_api.js.map
package/public_api.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/public_api.ts"],"names":["__exportStar","require","exports"],"mappings":"4hBAAAA,aAAAC,QAAA,qCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,kCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2CAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,mCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,wCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,yCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,sCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,6CAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2CAAA,EAAAC,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AAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,8BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,6BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,uCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,sCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,kCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,gCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,6BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,qBAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,eAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,0BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,wBAAA,EAAAC,OAAA","file":"public_api.js","sourcesContent":["export * from './collections/app-status.collection';\nexport * from './collections/counter.collection';\nexport * from './collections/cron-job-history.collection';\nexport * from './collections/cron-job.collection';\nexport * from './collections/email-history.collection';\nexport * from './collections/email-verified.collection';\nexport * from './collections/file.collection';\nexport * from './collections/flag.collection';\nexport * from './collections/flag-update.collection';\nexport * from './collections/log-method-latency.collection';\nexport * from './collections/log-subscription.collection';\nexport * from './collections/log.collection';\nexport * from './collections/logged-in-users.collection';\nexport * from './collections/method-response.collection';\nexport * from './collections/monitor-cpu.collection';\nexport * from './collections/monitor-memory.collection';\nexport * from './collections/monitor-mongo.collection';\nexport * from './collections/notification.collection';\nexport * from './collections/report-builder-library.collection';\nexport * from './collections/report-builder-report.collection';\nexport * from './collections/user-group.collection';\nexport * from './collections/user-guide.collection';\nexport * from './collections/user.collection';\nexport * from './models/app-status.model';\nexport * from './models/billing-logged-in-users.model';\nexport * from './models/collection-document.model';\nexport * from './models/counter.model';\nexport * from './models/cron-job-history.model';\nexport * from './models/cron-job.model';\nexport * from './models/dialog.model';\nexport * from './models/email-history.model';\nexport * from './models/email-verified.model';\nexport * from './models/file.model';\nexport * from './models/flag.model';\nexport * from './models/flag-update.model';\nexport * from './models/log-method-latency.model';\nexport * from './models/log-subscription.model';\nexport * from './models/log.model';\nexport * from './models/logged-in-users.model';\nexport * from './models/method-response.model';\nexport * from './models/method.model';\nexport * from './models/monitor-cpu.model';\nexport * from './models/monitor-memory.model';\nexport * from './models/monitor-mongo.model';\nexport * from './models/notification.model';\nexport * from './models/pagination.model';\nexport * from './models/permission.model';\nexport * from './models/report-builder-library.model';\nexport * from './models/report-builder-report.model';\nexport * from './models/report-builder.model';\nexport * from './models/select-data-label.model';\nexport * from './models/server-response.model';\nexport * from './models/subscription.model';\nexport * from './models/support-ticket.model';\nexport * from './models/user-group.model';\nexport * from './models/user-guide.model';\nexport * from './models/user.model';\nexport * from './util/common';\nexport * from './managers/mongo.manager';\nexport * from './resolveio-server-app';"]}
1
+ {"version":3,"sources":["../../src/public_api.ts"],"names":["__exportStar","require","exports"],"mappings":"4hBAAAA,aAAAC,QAAA,qCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,kCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2CAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,mCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,wCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,yCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,sCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,6CAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2CAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,8B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AA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,8BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,6BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,uCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,sCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,kCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,gCAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,6BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,+BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,2BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,qBAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,eAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,0BAAA,EAAAC,OAAA,EACAF,aAAAC,QAAA,wBAAA,EAAAC,OAAA","file":"public_api.js","sourcesContent":["export * from './collections/app-status.collection';\nexport * from './collections/counter.collection';\nexport * from './collections/cron-job-history.collection';\nexport * from './collections/cron-job.collection';\nexport * from './collections/email-history.collection';\nexport * from './collections/email-verified.collection';\nexport * from './collections/file.collection';\nexport * from './collections/flag.collection';\nexport * from './collections/flag-update.collection';\nexport * from './collections/log-method-latency.collection';\nexport * from './collections/log-subscription.collection';\nexport * from './collections/log.collection';\nexport * from './collections/logged-in-users.collection';\nexport * from './collections/method-response.collection';\nexport * from './collections/monitor-cpu.collection';\nexport * from './collections/monitor-function.collection';\nexport * from './collections/monitor-memory.collection';\nexport * from './collections/monitor-mongo.collection';\nexport * from './collections/notification.collection';\nexport * from './collections/report-builder-library.collection';\nexport * from './collections/report-builder-report.collection';\nexport * from './collections/user-group.collection';\nexport * from './collections/user-guide.collection';\nexport * from './collections/user.collection';\nexport * from './models/app-status.model';\nexport * from './models/billing-logged-in-users.model';\nexport * from './models/collection-document.model';\nexport * from './models/counter.model';\nexport * from './models/cron-job-history.model';\nexport * from './models/cron-job.model';\nexport * from './models/dialog.model';\nexport * from './models/email-history.model';\nexport * from './models/email-verified.model';\nexport * from './models/file.model';\nexport * from './models/flag.model';\nexport * from './models/flag-update.model';\nexport * from './models/log-method-latency.model';\nexport * from './models/log-subscription.model';\nexport * from './models/log.model';\nexport * from './models/logged-in-users.model';\nexport * from './models/method-response.model';\nexport * from './models/method.model';\nexport * from './models/monitor-cpu.model';\nexport * from './models/monitor-memory.model';\nexport * from './models/monitor-mongo.model';\nexport * from './models/notification.model';\nexport * from './models/pagination.model';\nexport * from './models/permission.model';\nexport * from './models/report-builder-library.model';\nexport * from './models/report-builder-report.model';\nexport * from './models/report-builder.model';\nexport * from './models/select-data-label.model';\nexport * from './models/server-response.model';\nexport * from './models/subscription.model';\nexport * from './models/support-ticket.model';\nexport * from './models/user-group.model';\nexport * from './models/user-guide.model';\nexport * from './models/user.model';\nexport * from './util/common';\nexport * from './managers/mongo.manager';\nexport * from './resolveio-server-app';"]}
package/server-app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","user_collection_1","home_1","auth_1","health_1","mongodb_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","_runningTasks","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_workers","_taskQueue","_inFlightRequests","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","prototype","initServerApp","_this","initServerFlag","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","setTimeout","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","wsUrl","connect","ws","lastComm","interval","WORKER_INDEX","NODE_APP_INSTANCE","sendWorkerResponse","rawData","toString","msg","parse","e","type","handleIncomingTask","clearInterval","err","data","taskId","method","params","userContext","push","timedOut","timeoutHandle","managerThis","Object","assign","id_user","user","id_ws","callMethod","call","apply","__spreadArray","__read","result","_b","clearTimeout","filter","a","err_1","payload","readyState","OPEN","send","getActiveMonitorFunctions","length","setImmediate","getMongoConnection","then","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","url","includes","urlParts","split","infoData","headers","origin","token","verify","decoded","Users","findById","fullname","readonly","workerId_1","interval_1","lastComm_1","objectIdHexString","id","activeTasks","maxConcurrency","handleWorkerMessage","w","addWebSocket","createLoggedInUser","unsubscribeWS","socketData","processSocketMessage","now","getTime","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","__values","socketData_1_1","value","handleClientMessage","messageRoute","messageDate","messageId","some","roles","groups","views","b","super_admin","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","serverResMethod","getLocalLogManager","writeLog","_id","collection","id_document","getBinarySize","route","Logs","insertOne","client","instance","_methods","err_3","getMongoManager","invalidateQueryCache","splice","map","indexOf","dataCopy","msgId","methodName","ack","worker","findAvailableWorker","queueTask","callMethodLocally","err_4","dispatchQueue","item","assignTaskToWorker","candidates","x","sort","task","Math","max","unshift","workerId","messageStr","inflight","find","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,Q,0FAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EACAM,OAAAN,QAAA,iBAAA,EAEAO,SAAAP,QAAA,eAAA,EACAQ,eAAAR,QAAA,yBAAA,EACAS,iBAAAT,QAAA,2BAAA,EACAU,uBAAAV,QAAA,iCAAA,EACAW,kBAAAX,QAAA,4BAAA,EAEAY,iBAAAZ,QAAA,8BAAA,EACAa,kBAAAb,QAAA,+BAAA,EAEAc,OAAAd,QAAA,aAAA,EACAe,OAAAf,QAAA,aAAA,EACAgB,SAAAhB,QAAA,eAAA,EACAiB,UAAAjB,QAAA,SAAA,EAEAkB,oBAAAlB,QAAA,8BAAA,EACAmB,uBAAAnB,QAAA,wBAAA,EAsBAoB,oBAAA,WAsCC,SAAAA,sBAhCQC,KAAAC,gBAAkB,GACnBD,KAAAE,QAAU,CAAA,EACTF,KAAAG,gBAAkB,CAAA,EAClBH,KAAAI,cAAgB,CAAA,EAChBJ,KAAAK,YAAc,CAAA,EACdL,KAAAM,cAAgB,GAEhBN,KAAAO,OAAS,QAQTP,KAAAQ,cAA0B,GAG1BR,KAAAS,cAAsB,KAEtBT,KAAAU,cAAgB,EAChBV,KAAAW,eAAiB,EAEjBX,KAAAY,kBAAoB,CAAA,EACpBZ,KAAAa,kBAAoB,CAAA,EAEpBb,KAAAc,cAAgB,CAAA,EAEhBd,KAAAe,SAA+B,GAC/Bf,KAAAgB,WAA8B,GAC9BhB,KAAAiB,kBAA2D,GAGlEjB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AAKiC,qBAAqBC,eAAc,GACxEC,QAAQC,IAAI,IAAIjB,KAAQ,aAAc,WAAY0E,EAAS,KAAGA,EAAc,SAAC,EAE9E7F,KAAKiC,qBAAqBwO,eAAe5K,CAAE,EAC3CA,EAAG6K,mBAAkB,CAEtB,EAEO3Q,oBAAAyB,UAAAmP,OAAP,WACC,OAAO3Q,KAAKsE,IACb,EAEOvE,oBAAAyB,UAAAwB,gBAAP,WACC,OAAOlD,uBAAAiD,gBAAgBC,gBAAe,CACvC,EACDjD,mBAAA,EAAC,EA5rCY6Q,QAAA7Q,oBAAAA","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { MongoNetworkTimeoutError } from 'mongodb';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\ninterface WorkerConnection {\n\tid: string;\n\tws: WebSocket;\n\tactiveTasks: number;\n\tmaxConcurrency: number;\n}\n\ninterface TaskQueueItem {\n\ttaskId: string;\n\tmethod: string;\n\tparams: any[];\n\tuserContext?: { id_user?: string; user?: string; id_ws?: string };\n}\n\ninterface InFlightRequest {\n\tws: WebSocket; // the client's WebSocket\n\tmessageId: number; // the ID so the client knows which call this corresponds to\n\tmethod: string;\n}\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\tprivate _runningTasks = [];\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tprivate _workers: WorkerConnection[] = [];\n\tprivate _taskQueue: TaskQueueItem[] = [];\n\tprivate _inFlightRequests: { [taskId: string]: InFlightRequest } = {};\n\n\tconstructor() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\t}\n\n\tinitServerApp() {\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tlet initServerFlag = false;\n\n\t\tsetTimeout(() => {\n\t\t\tinitServerFlag = true;\n\t\t}, 5000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tif (error && error['name'] === 'MongoServerError' && !initServerFlag) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\tif (this._isWorkersEnabled) {\n\t\t\tif (this._isWorkerInstance) {\n\t\t\t\tconsole.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._cronManager = new CronManager();\n\t\t\t\tthis.startWorkerInstance();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n\t\t\tthis.startServerInstance();\n\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\tthis._cronManager = new CronManager();\n\t\t\tthis.listen();\n\t\t}\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || ResolveIOServer.getServerConfig()['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || ResolveIOServer.getServerConfig()['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app, ResolveIOServer.getServerConfig());\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async startWorkerInstance() {\n\t\tconsole.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');\n\n\t\tlet wsUrl = ResolveIOServer.getServerConfig()['SERVER_URL'] + '/websocket?workerToken=' + ResolveIOServer.getServerConfig()['WORKER_TOKEN'];\n\n\t\tconst connect = () => {\n\t\t\tconst ws = new WebSocket(wsUrl);\n\n\t\t\tlet lastComm = null;\n\t\t\tlet interval = null;\n\n\t\t\tws.on('open', () => {\n\t\t\t\tconsole.log(new Date(), 'Connected to main server as worker', process.env.WORKER_INDEX, process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\n\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t}\n\t\t\t\t}, 15000);\n\t\t\t});\n\n\t\t\tws.on('message', (rawData: any) => {\n\t\t\t\t// console.log(new Date(), 'Message Recv', rawData);\n\n\t\t\t\tif (typeof rawData !== 'string') {\n\t\t\t\t\trawData = rawData.toString();\n\t\t\t\t}\n\n\t\t\t\t// console.log(new Date(), 'String Message Recv', rawData);\n\n\t\t\t\tif (rawData === 'ping') {\n\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t}\n\t\t\t\telse if (rawData === 'pong') {\n\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\tlastComm = new Date();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet msg: any;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmsg = JSON.parse(rawData, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.error('Worker parse error', e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// We expect: { type: 'task', taskId, method, params, userContext? }\n\t\t\t\t\tif (msg.type === 'task') {\n\t\t\t\t\t\tthis.handleIncomingTask(ws, msg);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'Disconnected from main server. Reconnecting in 5s...');\n\t\t\t\tsetTimeout(connect, 5000);\n\n\t\t\t\tif (interval) {\n\t\t\t\t\tclearInterval(interval);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.on('error', (err) => {\n\t\t\t\tconsole.error(new Date(), 'Worker WS error:', err);\n\t\t\t\tws.close();\n\t\t\t});\n\t\t};\n\n\t\tconnect();\n\t}\n\n\tprivate async handleIncomingTask(ws: WebSocket, data: any) {\n\t\tlet { taskId, method, params, userContext } = data;\n\t\tthis._runningTasks.push(taskId);\n\t\tif (!taskId || !method) {\n\t\t\tconsole.log('Invalid task message received', data);\n\t\t\treturn;\n\t\t}\n\n\t\tlet timedOut = false;\n\t\tlet timeoutHandle = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tconsole.error('Worker timed out on task:', taskId);\n\n\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\ttype: 'taskComplete',\n\t\t\t\ttaskId,\n\t\t\t\terror: true,\n\t\t\t\tmessage: 'Task timed out'\n\t\t\t});\n\t\t}, 120000);\n\n\t\ttry {\n\t\t\tlet managerThis = Object.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\tid_user: userContext?.id_user || '',\n\t\t\t\tuser: userContext?.user || '',\n\t\t\t\tid_ws: userContext?.id_ws || ''\n\t\t\t});\n\n\t\t\tlet result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: false,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t\tcatch (err) {\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tconsole.error('Worker failed task:', taskId, err);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: true,\n\t\t\t\t\tmessage: err.message || 'Unknown error'\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t}\n\n\tprivate sendWorkerResponse(ws: WebSocket, payload: any) {\n\t\tif (typeof payload !== 'string') {\n\t\t\tpayload = JSON.stringify(payload);\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\ttry {\n\t\t\t\tws.send(payload);\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tconsole.error('Failed to send worker response:', err);\n\t\t\t}\n\t\t}\n\t\telse if (ws) {\n\t\t\tws.close();\n\t\t}\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length\n\t\t\t&& !this._offlineUpdates.length && !this._taskQueue.length && !this._runningTasks.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}, () => { process.exit(1); });\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), 'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000;\n\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\t// If it's a worker, we might skip token checks or do a simple check:\n\t\t\t\t\tif (info.req.url && info.req.url.includes('workerToken=')) {\n\t\t\t\t\t\tlet urlParts = info.req.url.split('workerToken='); \n\t\t\t\t\t\tlet workerToken = urlParts[1] || '';\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\n\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tinfo.origin !== ResolveIOServer.getServerConfig()['ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']\n\t\t\t\t\t) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Listen for connections from clients or workers.\n\t */\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t// It's a WORKER\n\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\tws['id_worker'] = workerId;\n\n\t\t\t\t// For demonstration, let each worker handle up to 2 tasks concurrently\n\t\t\t\tlet maxConcurrency = 2;\n\n\t\t\t\tthis._workers.push({\n\t\t\t\t\tid: workerId,\n\t\t\t\t\tws: ws,\n\t\t\t\t\tactiveTasks: 0,\n\t\t\t\t\tmaxConcurrency: maxConcurrency\n\t\t\t\t});\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tws.on('open', () => {\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\n\t\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\t\tws.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 15000);\n\t\t\t\t});\n\n\t\t\t\tconsole.log(new Date(), 'Worker connected:', workerId);\n\n\t\t\t\tws.on('message', (message: any) => {\n\t\t\t\t\t// console.log(new Date(), 'Message Recv', message);\n\n\t\t\t\t\tif (typeof message !== 'string') {\n\t\t\t\t\t\tmessage = message.toString();\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log(new Date(), 'String Message Recv', message);\n\n\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t\t}\n\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.handleWorkerMessage(workerId, message);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\tthis._workers = this._workers.filter(w => w.id !== workerId);\n\t\t\t\t\t\n\t\t\t\t\tif (interval) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error on WS Worker', error);\n\t\t\t\t\tws.close();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Normal client\n\t\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}, 5000);\n\t\t\t\t});\n\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Connection from user: ' + req['user']);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['retryCnt'] = 0;\n\n\t\t\t\tws.on('message', async (message: string) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\tthis._methodManager.sendEmail(\n\t\t\t\t\t\t\t'dev@resolveio.com', \n\t\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], \n\t\t\t\t\t\t\tJSON.stringify([message, e])\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// call our existing processSocketMessage\n\t\t\t\t\tthis.processSocketMessage(ws, socketData);\n\t\t\t\t})\n\t\t\t\t.on('end', () => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t})\n\t\t\t\t.on('close', () => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t})\n\t\t\t\t.on('error', error => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\t// Keep alive timer\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any) {\n\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tws.send('pong');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\tws['isAlive'] = true;\n\t\t\tws['pongTime'] = new Date();\n\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the top level is not an array, let's skip\n\t\tif (!Array.isArray(socketData[0])) {\n\t\t\tconsole.log('Invalid message format (expected array of arrays)', socketData);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle each sub-message\n\t\tfor (let message of socketData) {\n\t\t\tawait this.handleClientMessage(ws, message);\n\t\t}\n\t}\n\n\tprivate async handleClientMessage(ws: WebSocket, msg: any[]): Promise<void> {\n\t\t// This is basically your old logic from processSocketMessage,\n\t\t// but we'll insert our worker-queue logic for \"method\" calls.\n\n\t\tlet messageRoute = msg[0];\n\t\tlet messageDate = msg[1];\n\t\tlet messageId = msg[2];\n\t\tlet type = msg[3];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = msg[4];\n\t\t\tlet pub = msg[5];\n\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = msg[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethod.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse {\n\t\t\t// It's presumably a 'method' or something else\n\t\t\tlet dataCopy = [...msg];\n\n\t\t\tlet route = dataCopy.shift();\n\t\t\tlet date = dataCopy.shift();\n\t\t\tlet msgId = dataCopy.shift();\n\t\t\tlet msgType = dataCopy.shift();\n\t\t\t\n\t\t\tif (msgType === 'method') {\n\t\t\t\tlet methodName = dataCopy.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (methodName !== 'reportBuilderGetResults' && methodName !== 'reportBuilderGetDistinctValue' && methodName !== 'reportBuilderBuildTree' && methodName !== 'generatePDF' && methodName !== 'getWOOfflineData' && methodName !== 'countQuery' && methodName !== 'countWithQuery' && methodName !== 'countCollectionWithQuery' && methodName !== 'find' && methodName !== 'findOne' && methodName !== 'findWithOptions' && methodName !== 'getDrivers' && methodName !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(dataCopy)) < 200000 ? JSON.stringify(dataCopy, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(dataCopy)) < 200000 ? JSON.stringify(dataCopy, null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Immediately ACK\n\t\t\t\tlet ack: ServerResponseModel = {\n\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, ack);\n\t\t\t\t}\n\n\t\t\t\t// Check if we can offload to a worker\n\t\t\t\tlet worker = this.findAvailableWorker();\n\t\t\t\tif (this._isWorkersEnabled && \n\t\t\t\t\tworker &&\n\t\t\t\t\t// methodName !== 'find' &&\n\t\t\t\t\t// methodName !== 'insertDocument' &&\n\t\t\t\t\t// methodName !== 'countWithQuery' &&\n\t\t\t\t\t// methodName !== 'findOne' &&\n\t\t\t\t\t// methodName !== 'updateDocumentProps' &&\n\t\t\t\t\t// methodName !== 'findWithOptions' &&\n\t\t\t\t\t// methodName !== 'updateDocument' &&\n\t\t\t\t\t// methodName !== 'insertErrorLog' &&\n\t\t\t\t\t// methodName !== 'removeDocument' &&\n\t\t\t\t\tmethodName !== 'supportCreateBillingUser' &&\n\t\t\t\t\tmethodName !== 'getSignedUrl' &&\n\t\t\t\t\tmethodName !== 'getSignedUrls' &&\n\t\t\t\t\tmethodName !== 'getSignedUrlWithId' &&\n\t\t\t\t\tmethodName !== 'incorrectUser' &&\n\t\t\t\t\tmethodName !== 'reloadWS' &&\n\t\t\t\t\tmethodName !== 'reconnectWS' &&\n\t\t\t\t\tmethodName !== 'disconnectWS'\n\t\t\t\t) {\n\t\t\t\t\t// Offload to a worker\n\t\t\t\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\t\t\t\t// Store correlation so when worker finishes, we can respond\n\t\t\t\t\tthis._inFlightRequests[taskId] = {\n\t\t\t\t\t\tws,\n\t\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\t\tmethod: methodName\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.queueTask(taskId, methodName, dataCopy, {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// No worker available: do method locally\n\t\t\t\t\tthis.callMethodLocally(ws, msgId, methodName, dataCopy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * callMethodLocally is your old approach for invoking the method in-process.\n\t */\n\tprivate async callMethodLocally(ws: WebSocket, messageId: number, method: string, params: any[]) {\n\t\tlet serverRes: ServerResponseModel = {\n\t\t\tmessageId: messageId,\n\t\t\thasError: false,\n\t\t\tdata: null\n\t\t};\n\n\t\ttry {\n\t\t\t// You can keep your logging code (LogMethodLatencies, Logs.insertOne, etc.)\n\t\t\tlet result = await this._methodManager.callMethod.call(\n\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t}),\n\t\t\t\tmethod,\n\t\t\t\t...params\n\t\t\t);\n\n\t\t\tserverRes.data = result;\n\t\t}\n\t\tcatch (err) {\n\t\t\tserverRes.hasError = true;\n\t\t\tserverRes.data = err.message || 'Unknown error';\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t}\n\t}\n\n\t/**\n\t * Add a new task to our in-memory queue and try to dispatch.\n\t */\n\tprivate queueTask(taskId: string, method: string, params: any[], userContext?: { id_user?: string; user?: string; id_ws?: string }) {\n\t\tthis._taskQueue.push({\n\t\t\ttaskId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tuserContext\n\t\t});\n\t\tthis.dispatchQueue();\n\t}\n\n\t/**\n\t * The main loop that assigns tasks from _taskQueue to any worker that has capacity.\n\t */\n\tprivate dispatchQueue() {\n\t\tif (!this._taskQueue.length) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Try to assign tasks while we have them\n\t\tfor (let i = 0; i < 9999; i++) {\n\t\t\tlet item = this._taskQueue[0];\n\t\t\tif (!item) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet w = this.findAvailableWorker();\n\t\t\tif (!w) {\n\t\t\t\tbreak; // no worker can take more tasks\n\t\t\t}\n\n\t\t\t// Remove from queue\n\t\t\tthis._taskQueue.shift();\n\t\t\tthis.assignTaskToWorker(w, item);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency. Or null if none.\n\t */\n\tprivate findAvailableWorker(): WorkerConnection | null {\n\t\tlet candidates = this._workers.filter(x => x.activeTasks < x.maxConcurrency);\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sort by how busy they are\n\t\tcandidates.sort((a, b) => a.activeTasks - b.activeTasks);\n\t\treturn candidates[0];\n\t}\n\n\tprivate assignTaskToWorker(worker: WorkerConnection, task: TaskQueueItem) {\n\t\tworker.activeTasks++;\n\n\t\tlet payload = {\n\t\t\ttype: 'task',\n\t\t\ttaskId: task.taskId,\n\t\t\tmethod: task.method,\n\t\t\tparams: task.params,\n\t\t\tuserContext: task.userContext\n\t\t};\n\n\t\ttry {\n\t\t\tworker.ws.send(JSON.stringify(payload));\n\t\t\t// console.log('Assigned task', task.taskId, 'to worker', worker.id);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to send task to worker:', err);\n\t\t\tworker.activeTasks = Math.max(0, worker.activeTasks - 1);\n\t\t\t// Put task back at front\n\t\t\tthis._taskQueue.unshift(task);\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages coming back from a worker (like 'taskComplete').\n\t */\n\tprivate handleWorkerMessage(workerId: string, messageStr: string) {\n\t\tlet data: any;\n\t\ttry {\n\t\t\tdata = JSON.parse(messageStr, dateReviver);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to parse worker message:', messageStr);\n\t\t\treturn;\n\t\t}\n\n\t\tif (data.type === 'taskComplete') {\n\t\t\tlet w = this._workers.find(x => x.id === workerId);\n\t\t\tif (!w) {\n\t\t\t\tconsole.error('Unknown worker for taskComplete:', workerId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tw.activeTasks = Math.max(0, w.activeTasks - 1);\n\n\t\t\tlet { taskId, error, message, result } = data;\n\n\t\t\t// Look up original request\n\t\t\tlet inflight = this._inFlightRequests[taskId];\n\t\t\tif (!inflight) {\n\t\t\t\tconsole.error('No in-flight request found for task:', taskId);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdelete this._inFlightRequests[taskId];\n\n\t\t\t\t// Send the final response to the client\n\t\t\t\tlet res: ServerResponseModel = {\n\t\t\t\t\tmessageId: inflight.messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: result\n\t\t\t\t};\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.hasError = true;\n\t\t\t\t\tres.data = message;\n\t\t\t\t}\n\n\t\t\t\tif (inflight.ws && inflight.ws.readyState === inflight.ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(inflight.ws, res);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to dispatch more from the queue\n\t\t\tthis.dispatchQueue();\n\t\t}\n\t}\n\n\t/**\n\t * Cleanly remove a client from the subscription manager, etc.\n\t */\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","user_collection_1","home_1","auth_1","health_1","mongodb_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","_runningTasks","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","_workers","_taskQueue","_inFlightRequests","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","prototype","initServerApp","_this","initServerFlag","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","setTimeout","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","wsUrl","connect","ws","lastComm","interval","WORKER_INDEX","NODE_APP_INSTANCE","sendWorkerResponse","rawData","toString","msg","parse","e","type","handleIncomingTask","clearInterval","err","data","taskId","method","params","userContext","push","timedOut","timeoutHandle","managerThis","Object","assign","id_user","user","id_ws","callMethod","call","apply","__spreadArray","__read","result","_b","clearTimeout","filter","a","err_1","payload","readyState","OPEN","send","getActiveMonitorFunctions","length","setImmediate","getMongoConnection","then","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","url","includes","urlParts","split","infoData","headers","origin","token","verify","decoded","Users","findById","fullname","readonly","workerId_1","interval_1","lastComm_1","objectIdHexString","id","activeTasks","maxConcurrency","handleWorkerMessage","w","addWebSocket","createLoggedInUser","unsubscribeWS","socketData","processSocketMessage","now","getTime","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","__values","socketData_1_1","value","handleClientMessage","messageRoute","messageDate","messageId","some","roles","groups","views","b","super_admin","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","serverResMethod","getLocalLogManager","writeLog","_id","collection","id_document","getBinarySize","route","Logs","insertOne","client","instance","_methods","err_3","getMongoManager","invalidateQueryCache","splice","map","indexOf","dataCopy","msgId","methodName","ack","worker","findAvailableWorker","queueTask","callMethodLocally","err_4","dispatchQueue","item","assignTaskToWorker","candidates","x","sort","task","Math","max","unshift","workerId","messageStr","inflight","find","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,Q,0FAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EACAM,OAAAN,QAAA,iBAAA,EAEAO,SAAAP,QAAA,eAAA,EACAQ,eAAAR,QAAA,yBAAA,EACAS,iBAAAT,QAAA,2BAAA,EACAU,uBAAAV,QAAA,iCAAA,EACAW,kBAAAX,QAAA,4BAAA,EAEAY,iBAAAZ,QAAA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6E,KAAKC,IAAI,EAAG3E,EAAEH,YAAc,CAAC,EAEvCxE,EAAmCD,EAAIC,OAA/BtE,EAA2BqE,EAAIrE,MAAxBa,EAAoBwD,EAAIxD,QAAf2E,EAAWnB,EAAImB,QAGzCwI,EAAWvQ,KAAKiB,kBAAkB4F,KAKrC,OAAO7G,KAAKiB,kBAAkB4F,GAG1BxB,EAA2B,CAC9BuH,UAAW2D,EAAS3D,UACpBa,SAAU,CAAA,EACV7G,KAAMmB,C,EAGHxF,IACH8C,EAAIoI,SAAW,CAAA,EACfpI,EAAIuB,KAAOxD,GAGRmN,EAAS1K,IAAM0K,EAAS1K,GAAGyC,aAAeiI,EAAS1K,GAAG0C,MACzDvI,KAAKgE,kBAAkBwE,KAAK+H,EAAS1K,GAAIR,CAAG,GAlB7ClD,QAAQI,MAAM,uCAAwCsE,CAAM,EAuB7D7G,KAAK2P,cAAa,GAlCjBxN,QAAQI,MAAM,mCAAoC8N,CAAQ,EAoC7D,EAKOtQ,oBAAAyB,UAAAmK,cAAP,SAAqB9F,GAChB7F,KAAKiC,sBAAwBjC,KAAKiC,qBAAqBC,eAAc,GACxEC,QAAQC,IAAI,IAAIjB,KAAQ,aAAc,WAAY0E,EAAS,KAAGA,EAAc,SAAC,EAE9E7F,KAAKiC,qBAAqBwO,eAAe5K,CAAE,EAC3CA,EAAG6K,mBAAkB,CAEtB,EAEO3Q,oBAAAyB,UAAAmP,OAAP,WACC,OAAO3Q,KAAKsE,IACb,EAEOvE,oBAAAyB,UAAAwB,gBAAP,WACC,OAAOlD,uBAAAiD,gBAAgBC,gBAAe,CACvC,EACDjD,mBAAA,EAAC,EA1rCY6Q,QAAA7Q,oBAAAA","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { MongoNetworkTimeoutError } from 'mongodb';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\ninterface WorkerConnection {\n\tid: string;\n\tws: WebSocket;\n\tactiveTasks: number;\n\tmaxConcurrency: number;\n}\n\ninterface TaskQueueItem {\n\ttaskId: string;\n\tmethod: string;\n\tparams: any[];\n\tuserContext?: { id_user?: string; user?: string; id_ws?: string };\n}\n\ninterface InFlightRequest {\n\tws: WebSocket; // the client's WebSocket\n\tmessageId: number; // the ID so the client knows which call this corresponds to\n\tmethod: string;\n}\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\tprivate _runningTasks = [];\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tprivate _workers: WorkerConnection[] = [];\n\tprivate _taskQueue: TaskQueueItem[] = [];\n\tprivate _inFlightRequests: { [taskId: string]: InFlightRequest } = {};\n\n\tconstructor() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\t}\n\n\tinitServerApp() {\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tlet initServerFlag = false;\n\n\t\tsetTimeout(() => {\n\t\t\tinitServerFlag = true;\n\t\t}, 5000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tif (error && error['name'] === 'MongoServerError' && !initServerFlag) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\tif (this._isWorkersEnabled) {\n\t\t\tif (this._isWorkerInstance) {\n\t\t\t\tconsole.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._cronManager = new CronManager();\n\t\t\t\tthis.startWorkerInstance();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n\t\t\tthis.startServerInstance();\n\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\tthis._cronManager = new CronManager();\n\t\t\tthis.listen();\n\t\t}\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || ResolveIOServer.getServerConfig()['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || ResolveIOServer.getServerConfig()['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app, ResolveIOServer.getServerConfig());\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async startWorkerInstance() {\n\t\tconsole.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');\n\n\t\tlet wsUrl = ResolveIOServer.getServerConfig()['SERVER_URL'] + '/websocket?workerToken=' + ResolveIOServer.getServerConfig()['WORKER_TOKEN'];\n\n\t\tconst connect = () => {\n\t\t\tconst ws = new WebSocket(wsUrl);\n\n\t\t\tlet lastComm = null;\n\t\t\tlet interval = null;\n\n\t\t\tws.on('open', () => {\n\t\t\t\tconsole.log(new Date(), 'Connected to main server as worker', process.env.WORKER_INDEX, process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\n\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t}\n\t\t\t\t}, 15000);\n\t\t\t});\n\n\t\t\tws.on('message', (rawData: any) => {\n\t\t\t\t// console.log(new Date(), 'Message Recv', rawData);\n\n\t\t\t\tif (typeof rawData !== 'string') {\n\t\t\t\t\trawData = rawData.toString();\n\t\t\t\t}\n\n\t\t\t\t// console.log(new Date(), 'String Message Recv', rawData);\n\n\t\t\t\tif (rawData === 'ping') {\n\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t}\n\t\t\t\telse if (rawData === 'pong') {\n\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\tlastComm = new Date();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet msg: any;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmsg = JSON.parse(rawData, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.error('Worker parse error', e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// We expect: { type: 'task', taskId, method, params, userContext? }\n\t\t\t\t\tif (msg.type === 'task') {\n\t\t\t\t\t\tthis.handleIncomingTask(ws, msg);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.on('close', () => {\n\t\t\t\tconsole.log(new Date(), 'Disconnected from main server. Reconnecting in 5s...');\n\t\t\t\tsetTimeout(connect, 5000);\n\n\t\t\t\tif (interval) {\n\t\t\t\t\tclearInterval(interval);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.on('error', (err) => {\n\t\t\t\tconsole.error(new Date(), 'Worker WS error:', err);\n\t\t\t\tws.close();\n\t\t\t});\n\t\t};\n\n\t\tconnect();\n\t}\n\n\tprivate async handleIncomingTask(ws: WebSocket, data: any) {\n\t\tlet { taskId, method, params, userContext } = data;\n\t\tthis._runningTasks.push(taskId);\n\t\tif (!taskId || !method) {\n\t\t\tconsole.log('Invalid task message received', data);\n\t\t\treturn;\n\t\t}\n\n\t\tlet timedOut = false;\n\t\tlet timeoutHandle = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tconsole.error('Worker timed out on task:', taskId);\n\n\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\ttype: 'taskComplete',\n\t\t\t\ttaskId,\n\t\t\t\terror: true,\n\t\t\t\tmessage: 'Task timed out'\n\t\t\t});\n\t\t}, 120000);\n\n\t\ttry {\n\t\t\tlet managerThis = Object.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\tid_user: userContext?.id_user || '',\n\t\t\t\tuser: userContext?.user || '',\n\t\t\t\tid_ws: userContext?.id_ws || ''\n\t\t\t});\n\n\t\t\tlet result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: false,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t\tcatch (err) {\n\t\t\tif (!timedOut) {\n\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\tconsole.error('Worker failed task:', taskId, err);\n\t\t\t\tthis.sendWorkerResponse(ws, {\n\t\t\t\t\ttype: 'taskComplete',\n\t\t\t\t\ttaskId,\n\t\t\t\t\terror: true,\n\t\t\t\t\tmessage: err.message || 'Unknown error'\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._runningTasks = this._runningTasks.filter(a => a !== taskId);\n\t\t}\n\t}\n\n\tprivate sendWorkerResponse(ws: WebSocket, payload: any) {\n\t\tif (typeof payload !== 'string') {\n\t\t\tpayload = JSON.stringify(payload);\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\ttry {\n\t\t\t\tws.send(payload);\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tconsole.error('Failed to send worker response:', err);\n\t\t\t}\n\t\t}\n\t\telse if (ws) {\n\t\t\tws.close();\n\t\t}\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length\n\t\t\t&& !this._offlineUpdates.length && !this._taskQueue.length && !this._runningTasks.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}, () => { process.exit(1); });\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), 'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000;\n\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\t// If it's a worker, we might skip token checks or do a simple check:\n\t\t\t\t\tif (info.req.url && info.req.url.includes('workerToken=')) {\n\t\t\t\t\t\tlet urlParts = info.req.url.split('workerToken='); \n\t\t\t\t\t\tlet workerToken = urlParts[1] || '';\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\n\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tinfo.origin !== ResolveIOServer.getServerConfig()['ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']\n\t\t\t\t\t) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Listen for connections from clients or workers.\n\t */\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t// It's a WORKER\n\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\tws['id_worker'] = workerId;\n\n\t\t\t\t// For demonstration, let each worker handle up to 2 tasks concurrently\n\t\t\t\tlet maxConcurrency = 2;\n\n\t\t\t\tthis._workers.push({\n\t\t\t\t\tid: workerId,\n\t\t\t\t\tws: ws,\n\t\t\t\t\tactiveTasks: 0,\n\t\t\t\t\tmaxConcurrency: maxConcurrency\n\t\t\t\t});\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tws.on('open', () => {\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\n\t\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\t\tws.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'ping');\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 15000);\n\t\t\t\t});\n\n\t\t\t\tconsole.log(new Date(), 'Worker connected:', workerId);\n\n\t\t\t\tws.on('message', (message: any) => {\n\t\t\t\t\t// console.log(new Date(), 'Message Recv', message);\n\n\t\t\t\t\tif (typeof message !== 'string') {\n\t\t\t\t\t\tmessage = message.toString();\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log(new Date(), 'String Message Recv', message);\n\n\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t\t}\n\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.handleWorkerMessage(workerId, message);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\tthis._workers = this._workers.filter(w => w.id !== workerId);\n\t\t\t\t\t\n\t\t\t\t\tif (interval) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error on WS Worker', error);\n\t\t\t\t\tws.close();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Normal client\n\t\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}, 5000);\n\t\t\t\t});\n\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Connection from user: ' + req['user']);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['retryCnt'] = 0;\n\n\t\t\t\tws.on('message', async (message: string) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\tthis._methodManager.sendEmail(\n\t\t\t\t\t\t\t'dev@resolveio.com', \n\t\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], \n\t\t\t\t\t\t\tJSON.stringify([message, e])\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// call our existing processSocketMessage\n\t\t\t\t\tthis.processSocketMessage(ws, socketData);\n\t\t\t\t})\n\t\t\t\t.on('end', () => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t})\n\t\t\t\t.on('close', () => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t})\n\t\t\t\t.on('error', error => {\n\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\t// Keep alive timer\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any) {\n\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tws.send('pong');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\tws['isAlive'] = true;\n\t\t\tws['pongTime'] = new Date();\n\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the top level is not an array, let's skip\n\t\tif (!Array.isArray(socketData[0])) {\n\t\t\tconsole.log('Invalid message format (expected array of arrays)', socketData);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle each sub-message\n\t\tfor (let message of socketData) {\n\t\t\tawait this.handleClientMessage(ws, message);\n\t\t}\n\t}\n\n\tprivate async handleClientMessage(ws: WebSocket, msg: any[]): Promise<void> {\n\t\t// This is basically your old logic from processSocketMessage,\n\t\t// but we'll insert our worker-queue logic for \"method\" calls.\n\n\t\tlet messageRoute = msg[0];\n\t\tlet messageDate = msg[1];\n\t\tlet messageId = msg[2];\n\t\tlet type = msg[3];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = msg[4];\n\t\t\tlet pub = msg[5];\n\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = msg[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethod.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse {\n\t\t\t// It's presumably a 'method' or something else\n\t\t\tlet dataCopy = [...msg];\n\n\t\t\tlet route = dataCopy.shift();\n\t\t\tlet date = dataCopy.shift();\n\t\t\tlet msgId = dataCopy.shift();\n\t\t\tlet msgType = dataCopy.shift();\n\t\t\t\n\t\t\tif (msgType === 'method') {\n\t\t\t\tlet methodName = dataCopy.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (methodName !== 'reportBuilderGetResults' && methodName !== 'reportBuilderGetDistinctValue' && methodName !== 'reportBuilderBuildTree' && methodName !== 'generatePDF' && methodName !== 'getWOOfflineData' && methodName !== 'countQuery' && methodName !== 'countWithQuery' && methodName !== 'countCollectionWithQuery' && methodName !== 'find' && methodName !== 'findOne' && methodName !== 'findWithOptions' && methodName !== 'getDrivers' && methodName !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(dataCopy)) < 200000 ? JSON.stringify(dataCopy, null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(dataCopy)) < 200000 ? JSON.stringify(dataCopy, null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com'\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Immediately ACK\n\t\t\t\tlet ack: ServerResponseModel = {\n\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, ack);\n\t\t\t\t}\n\n\t\t\t\t// Check if we can offload to a worker\n\t\t\t\tlet worker = this.findAvailableWorker();\n\t\t\t\tif (this._isWorkersEnabled && \n\t\t\t\t\tworker &&\n\t\t\t\t\t// methodName !== 'find' &&\n\t\t\t\t\t// methodName !== 'insertDocument' &&\n\t\t\t\t\t// methodName !== 'countWithQuery' &&\n\t\t\t\t\t// methodName !== 'findOne' &&\n\t\t\t\t\t// methodName !== 'updateDocumentProps' &&\n\t\t\t\t\t// methodName !== 'findWithOptions' &&\n\t\t\t\t\t// methodName !== 'updateDocument' &&\n\t\t\t\t\t// methodName !== 'insertErrorLog' &&\n\t\t\t\t\t// methodName !== 'removeDocument' &&\n\t\t\t\t\tmethodName !== 'supportCreateBillingUser' &&\n\t\t\t\t\tmethodName !== 'getSignedUrl' &&\n\t\t\t\t\tmethodName !== 'getSignedUrls' &&\n\t\t\t\t\tmethodName !== 'getSignedUrlWithId' &&\n\t\t\t\t\tmethodName !== 'incorrectUser' &&\n\t\t\t\t\tmethodName !== 'reloadWS' &&\n\t\t\t\t\tmethodName !== 'reconnectWS' &&\n\t\t\t\t\tmethodName !== 'disconnectWS'\n\t\t\t\t) {\n\t\t\t\t\t// Offload to a worker\n\t\t\t\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\t\t\t\t// Store correlation so when worker finishes, we can respond\n\t\t\t\t\tthis._inFlightRequests[taskId] = {\n\t\t\t\t\t\tws,\n\t\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\t\tmethod: methodName\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.queueTask(taskId, methodName, dataCopy, {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// No worker available: do method locally\n\t\t\t\t\tthis.callMethodLocally(ws, msgId, methodName, dataCopy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * callMethodLocally is your old approach for invoking the method in-process.\n\t */\n\tprivate async callMethodLocally(ws: WebSocket, messageId: number, method: string, params: any[]) {\n\t\tlet serverRes: ServerResponseModel = {\n\t\t\tmessageId: messageId,\n\t\t\thasError: false,\n\t\t\tdata: null\n\t\t};\n\n\t\ttry {\n\t\t\t// You can keep your logging code (LogMethodLatencies, Logs.insertOne, etc.)\n\t\t\tlet result = await this._methodManager.callMethod.call(\n\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t}),\n\t\t\t\tmethod,\n\t\t\t\t...params\n\t\t\t);\n\n\t\t\tserverRes.data = result;\n\t\t}\n\t\tcatch (err) {\n\t\t\tserverRes.hasError = true;\n\t\t\tserverRes.data = err.message || 'Unknown error';\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t}\n\t}\n\n\t/**\n\t * Add a new task to our in-memory queue and try to dispatch.\n\t */\n\tprivate queueTask(taskId: string, method: string, params: any[], userContext?: { id_user?: string; user?: string; id_ws?: string }) {\n\t\tthis._taskQueue.push({\n\t\t\ttaskId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tuserContext\n\t\t});\n\t\tthis.dispatchQueue();\n\t}\n\n\t/**\n\t * The main loop that assigns tasks from _taskQueue to any worker that has capacity.\n\t */\n\tprivate dispatchQueue() {\n\t\tif (!this._taskQueue.length) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Try to assign tasks while we have them\n\t\tfor (let i = 0; i < 9999; i++) {\n\t\t\tlet item = this._taskQueue[0];\n\t\t\tif (!item) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet w = this.findAvailableWorker();\n\t\t\tif (!w) {\n\t\t\t\tbreak; // no worker can take more tasks\n\t\t\t}\n\n\t\t\t// Remove from queue\n\t\t\tthis._taskQueue.shift();\n\t\t\tthis.assignTaskToWorker(w, item);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency. Or null if none.\n\t */\n\tprivate findAvailableWorker(): WorkerConnection | null {\n\t\tlet candidates = this._workers.filter(x => x.activeTasks < x.maxConcurrency);\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sort by how busy they are\n\t\tcandidates.sort((a, b) => a.activeTasks - b.activeTasks);\n\t\treturn candidates[0];\n\t}\n\n\tprivate assignTaskToWorker(worker: WorkerConnection, task: TaskQueueItem) {\n\t\tworker.activeTasks++;\n\n\t\tlet payload = {\n\t\t\ttype: 'task',\n\t\t\ttaskId: task.taskId,\n\t\t\tmethod: task.method,\n\t\t\tparams: task.params,\n\t\t\tuserContext: task.userContext\n\t\t};\n\n\t\ttry {\n\t\t\tworker.ws.send(JSON.stringify(payload));\n\t\t\t// console.log('Assigned task', task.taskId, 'to worker', worker.id);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to send task to worker:', err);\n\t\t\tworker.activeTasks = Math.max(0, worker.activeTasks - 1);\n\t\t\t// Put task back at front\n\t\t\tthis._taskQueue.unshift(task);\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages coming back from a worker (like 'taskComplete').\n\t */\n\tprivate handleWorkerMessage(workerId: string, messageStr: string) {\n\t\tlet data: any;\n\t\ttry {\n\t\t\tdata = JSON.parse(messageStr, dateReviver);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to parse worker message:', messageStr);\n\t\t\treturn;\n\t\t}\n\n\t\tif (data.type === 'taskComplete') {\n\t\t\tlet w = this._workers.find(x => x.id === workerId);\n\t\t\tif (!w) {\n\t\t\t\tconsole.error('Unknown worker for taskComplete:', workerId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tw.activeTasks = Math.max(0, w.activeTasks - 1);\n\n\t\t\tlet { taskId, error, message, result } = data;\n\n\t\t\t// Look up original request\n\t\t\tlet inflight = this._inFlightRequests[taskId];\n\t\t\tif (!inflight) {\n\t\t\t\tconsole.error('No in-flight request found for task:', taskId);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdelete this._inFlightRequests[taskId];\n\n\t\t\t\t// Send the final response to the client\n\t\t\t\tlet res: ServerResponseModel = {\n\t\t\t\t\tmessageId: inflight.messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: result\n\t\t\t\t};\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.hasError = true;\n\t\t\t\t\tres.data = message;\n\t\t\t\t}\n\n\t\t\t\tif (inflight.ws && inflight.ws.readyState === inflight.ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(inflight.ws, res);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to dispatch more from the queue\n\t\t\tthis.dispatchQueue();\n\t\t}\n\t}\n\n\t/**\n\t * Cleanly remove a client from the subscription manager, etc.\n\t */\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n}"]}