@resolveio/server-lib 20.4.12 → 20.4.14

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,n,o,s){return new(o=o||Promise)(function(i,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?i(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var s,r,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function verb(i){return function(e){var t=[i,e];if(s)throw new TypeError("Generator is already executing.");for(;c=u&&t[u=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(n,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}}}},__spreadArray=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,o=0,s=t.length;o<s;o++)!n&&o in t||((n=n||Array.prototype.slice.call(t,0,o))[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))},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"),index_1=require("../index"),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"),mongo_manager_1=require("./mongo.manager"),common_1=require("../util/common"),NodeCache=require("node-cache"),flag_collection_1=require("../collections/flag.collection"),os_1=require("os"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(e,t,i,n){var o=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._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this._monitorManagerFunction=n,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),this.serverConfig=i,this._wss=t,(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_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(){o._oplogRetryCount=0},15e3),setInterval(function(){o.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",o._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",o._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",o._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",o._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(o._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",o._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(o._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",o._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",o._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(o._debugSubCollections.sort(function(e,t){return e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",o._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",o._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",o._debugRemoveCacheHits)),o._debugOplogHits=0,o._debugOplogCollections=[],o._debugSubCollections=[],o._debugMongoQueueHits=0,o._debugMongoQueueCollections=[],o._debugSendQueueHits=0,o._debugSubHits=0,o._debugUnSubHits=0,o._debugUnSubAllHits=0,o._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(o,void 0,void 0,function(){var t,n,i,o,s,r,a,c,u;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(),n=(0,common_1.deepCopy)(this._loggedInUsers),i=function(e){var i=n[e];(!i.date||12e4<Date.now()-i.date.getTime())&&(o._websocketManager.getWebSocket(i.id_ws)?(o.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",o._websocketManager.getWebSocket(i.id_ws).user,o._websocketManager.getWebSocket(i.id_ws).id_socket,2),o.unsubscribeAll(o._websocketManager.getWebSocket(i.id_ws))):(o._subscriptions.forEach(function(e){for(var t=e.clients.length-1;0<=t;t--)e.clients[t].id_socket===i.id_ws&&e.clients.splice(t,1)}),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:i._id}),0<=o._loggedInUsers.findIndex(function(e){return e._id===i._id})&&o._loggedInUsers.splice(o._loggedInUsers.findIndex(function(e){return e._id===i._id}),1)))},s=(o=this)._loggedInUsers.length-1;0<=s;s--)i(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,u=r.clients.length-1;0<=u;u--)a(u);return[2]}})})},3e4),flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?o._enableDebug=!0:o._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(c,u){return __awaiter(this,void 0,void 0,function(){var t,i,o,n,s,r,a=this;return __generator(this,function(e){for(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c),t=this._subscriptions.filter(function(e){return e.collections.includes(c)}),i=function(n){o._publications[n.publication].user_specific?Promise.all(n.clients.map(function(i){return __awaiter(a,void 0,void 0,function(){var t;return __generator(this,function(e){if((t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN)try{this.sendDataToOne(t,i.messageId,n,u,c)}catch(e){this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - User Specific - Socket: "+i.id_socket+", User: "+i.id_user+", MessageId: "+i.messageId+", Pub: "+n.publication+", Err: "+JSON.stringify(e,null,2))}return[2]})})})):o.sendDataToAll(n)},o=this,n=0,s=t;n<s.length;n++)r=s[n],i(r);return[2]})})},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(t){var i=this,e=this._loggedInUsers.find(function(e){return e.id_ws===t.id_socket});e&&(e.date=new Date,logged_in_users_collection_1.LoggedInUsers.updateOne({id_ws:t.id_socket},{$set:{latency:t.latency,date:e.date}}).then(function(e){e||(i.unsubscribeAll(t),i.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",t.user,t.id_socket,3))},function(){i.unsubscribeAll(t),i.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",t.user,t.id_socket,4)}))},SubscriptionManager.prototype.subscribe=function(t,e,i,n,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={},u=Object.keys(a.check._schema).filter(function(e){return!e.includes(".")}),l=0;l<s.length;l++)c[u[l]]=s[l];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="",d=a[0],""===a[0]&&(g="/",d=a[1]),g+=d,1<a.length&&(g+="/"),(d=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===i.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==t&&!e.messageRoute.startsWith(g)})})).length)&&(this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Detected Undestroyed Subscription - "+this.serverConfig.CLIENT_NAME,"USER: "+i.user+" (Socket: "+i.id_socket+") is on route: "+t+" but has the following subscriptions on other routes:"+JSON.stringify(d,null,2)),d.forEach(function(t){t.clients.filter(function(e){return e.id_socket===i.id_socket}).forEach(function(e){r.unsubscribe(e.messageRoute,new Date,i,e.messageId,t.publication,t.subscriptionData)})}));var g,d,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===i.id_socket&&e.messageId===n})||a.clients.push({id_user:i.id_user,messageId:n,id_socket:i.id_socket,messageRoute:t}):this._subscriptions.push({publication:o,subscriptionData:s,collections:this.getPublicationCollections(o),clients:[{id_user:i.id_user,messageId:n,id_socket:i.id_socket,messageRoute:t}],cacheId:0}),a=a||this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)}),this.processSubscription(a,i,n)}else console.error(new Date,"No Publication: "+o)},SubscriptionManager.prototype.createLoggedInUser=function(n){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return[2,new Promise(function(i,e){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n))?(t={_id:(0,mongo_manager_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),i(t)):i(null),[2]})})})]})})},SubscriptionManager.prototype.unsubscribe=function(e,t,i,n,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===i.id_user&&r.clients[a].messageId===n&&r.clients[a].id_socket===i.id_socket&&r.clients.splice(a,1)}else console.log("No Publication: "+o)},SubscriptionManager.prototype.unsubscribeAll=function(r){return __awaiter(this,void 0,void 0,function(){var t,i,n,o,s;return __generator(this,function(e){switch(e.label){case 0:return(this._debugUnSubAllHits+=1,r)?[4,logged_in_users_collection_1.LoggedInUsers.findOne({id_ws:r.id_socket})]:[3,2];case 1:for((t=e.sent())&&(0<=this._loggedInUsers.map(function(e){return e._id}).indexOf(t._id)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e._id}).indexOf(t._id),1),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:t._id})),i=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_user===r.id_user&&e.id_socket===r.id_socket})}),n=i.length-1;0<=n;n--)for(o=i[n],s=o.clients.length-1;0<=s;s--)o.clients[s].id_socket===r.id_socket&&o.clients.splice(s,1);this._websocketManager.removeWebSocket(r),e.label=2;case 2:return[2]}})})},SubscriptionManager.prototype.getActiveSubscriptions=function(){return this._subscriptions},SubscriptionManager.prototype.getPublicationCollections=function(e){return this._publications[e].collections},SubscriptionManager.prototype.tailOpLog=function(t){return __awaiter(this,void 0,void 0,function(){var i,n=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){i=t;try{this._oplog$=index_1.ResolveIOServer.getMainDB().watch([],{resumeAfter:t})}catch(e){return this._oplog$&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),this.tailOpLog(t),[2]}}else this._oplog$=index_1.ResolveIOServer.getMainDB().watch();console.log(new Date,"oplog started"),this._oplog$.on("change",function(t){var e;t.ns&&(e=t.ns.coll,n._debugOplogCollections.some(function(e){return e.collection===t.ns.coll&&e.type===t.operationType})?n._debugOplogCollections.find(function(e){return e.collection===t.ns.coll&&e.type===t.operationType}).hits+=1:n._debugOplogCollections.push({collection:t.ns.coll,type:t.operationType,hits:1}),!e||e.endsWith(".versions")||e.startsWith("monitor-")||"logs"===e||"log-method-latencies"===e||"log-subscriptions"===e||(n._debugOplogHits+=1,"insert"===t.operationType?("support-tickets"===e&&"https://resolveio.com"===n.serverConfig.ROOT_URL&&(n._mainServer.getMethodManager().callMethodInternal.call(n._mainServer.getMethodManager(),"sendSupportTicketEmail",t.documentKey._id),n.invalidatePubsCache(e,"insert")),"method-responses"!==e&&n.invalidatePubsCache(e,"insert")):"update"===t.operationType||"replace"===t.operationType?"method-responses"!==e&&n.invalidatePubsCache(e,"update"):"delete"===t.operationType&&"method-responses"!==e&&n.invalidatePubsCache(e,"delete")),"flags"===e&&flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?n._enableDebug=!0:n._enableDebug=!1}),i=t._id)}),this._oplog$.on("error",function(e){console.log(new Date,"oplog error",e),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(i)}),this._oplog$.on("end",function(){console.log(new Date,"oplog end"),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(i)}),this._oplog$.on("close",function(){console.log(new Date,"oplog close"),n._oplog$.removeAllListeners(),n._oplog$=null,n.tailOpLog(i)})}return[2]}})})},SubscriptionManager.prototype.processSubscription=function(n,o,s){return __awaiter(this,void 0,void 0,function(){var t,i;return __generator(this,function(e){if(this._publications[n.publication].user_specific)this.sendDataToOne(o,s,n,"newSub",n.collections[0]);else if(n.cacheId)try{t=JSON.parse(this._nodeCache.get(n.cacheId),common_1.dateReviver),i={messageId:s,hasError:!1,data:t},this.sendWS(o,i)}catch(e){this._nodeCache.del(n.cacheId),n.cacheId=0,this.sendDataToAll(n)}else this.sendDataToAll(n);return[2]})})},SubscriptionManager.prototype.sendDataToOne=function(s,r,a,e,t){return __awaiter(this,void 0,void 0,function(){var t,i,n,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]),[4,(o=this._publications[a.publication].function).call.apply(o,__spreadArray([Object.assign({},this,SubscriptionManager.prototype),s.id_user],a.subscriptionData,!1))];case 2:return o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),n={messageId:r,hasError:!1,data:o},this.sendWS(s,n),[3,4];case 3:return i=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),n={messageId:r,hasError:!0,data:i},this.sendWS(s,n),this._mainServer.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(i,null,2)),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.sendDataToAll=function(g){return __awaiter(this,void 0,void 0,function(){var t,o,i,n,s,r,a,c,u,l=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<=(u=this._subscriptions.findIndex(function(e){return e.publication===g.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(g.subscriptionData)}))&&this._subscriptions.splice(u,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]),[4,(u=this._publications[g.publication].function).call.apply(u,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],g.subscriptionData,!1))];case 3:if(o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),g.cacheId)try{i=JSON.parse(this._nodeCache.get(g.cacheId),common_1.dateReviver),JSON.stringify(i)!==JSON.stringify(o)&&(Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),this._nodeCache.del(g.cacheId),g.cacheId=0,!o||Array.isArray(o)&&!o.length||(g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o))))}catch(e){Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),this._nodeCache.del(g.cacheId),g.cacheId=0,!o||Array.isArray(o)&&!o.length||(g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o)))}else if(Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),o&&(!Array.isArray(o)||o.length)&&(g.cacheId=this._cacheId++,this._nodeCache.set(g.cacheId,JSON.stringify(o)),(n=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+" - "+n)}return[3,5];case 4:return c=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),Promise.all(g.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!0,data:c},this.sendWS(t,i)),[2]})})})),this._mainServer.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,n,o,s){return new(o=o||Promise)(function(i,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?i(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var s,r,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function verb(i){return function(e){var t=[i,e];if(s)throw new TypeError("Generator is already executing.");for(;c=u&&t[u=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(n,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,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,o,s=i.call(e),r=[];try{for(;(void 0===t||0<t--)&&!(n=s.next()).done;)r.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}return r},__spreadArray=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,o=0,s=t.length;o<s;o++)!n&&o in t||((n=n||Array.prototype.slice.call(t,0,o))[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))},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"),index_1=require("../index"),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"),mongo_manager_1=require("./mongo.manager"),common_1=require("../util/common"),NodeCache=require("node-cache"),flag_collection_1=require("../collections/flag.collection"),os_1=require("os"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(e,t,i,n){var o=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._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this._monitorManagerFunction=n,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),this.serverConfig=i,this._wss=t,(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_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(){o._oplogRetryCount=0},15e3),setInterval(function(){o.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",o._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",o._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",o._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",o._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(o._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",o._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(o._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",o._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",o._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(o._debugSubCollections.sort(function(e,t){return e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",o._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",o._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",o._debugRemoveCacheHits)),o._debugOplogHits=0,o._debugOplogCollections=[],o._debugSubCollections=[],o._debugMongoQueueHits=0,o._debugMongoQueueCollections=[],o._debugSendQueueHits=0,o._debugSubHits=0,o._debugUnSubHits=0,o._debugUnSubAllHits=0,o._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(o,void 0,void 0,function(){var t,n,i,o,s,r,a,c,u;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(),n=(0,common_1.deepCopy)(this._loggedInUsers),i=function(e){var i=n[e];(!i.date||12e4<Date.now()-i.date.getTime())&&(o._websocketManager.getWebSocket(i.id_ws)?(o.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",o._websocketManager.getWebSocket(i.id_ws).user,o._websocketManager.getWebSocket(i.id_ws).id_socket,2),o.unsubscribeAll(o._websocketManager.getWebSocket(i.id_ws))):(o._subscriptions.forEach(function(e){for(var t=e.clients.length-1;0<=t;t--)e.clients[t].id_socket===i.id_ws&&e.clients.splice(t,1)}),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:i._id}),0<=o._loggedInUsers.findIndex(function(e){return e._id===i._id})&&o._loggedInUsers.splice(o._loggedInUsers.findIndex(function(e){return e._id===i._id}),1)))},s=(o=this)._loggedInUsers.length-1;0<=s;s--)i(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,u=r.clients.length-1;0<=u;u--)a(u);return[2]}})})},3e4),flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?o._enableDebug=!0:o._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(l,_){return __awaiter(this,void 0,void 0,function(){var t,i,o,n,s,r,a,c,u=this;return __generator(this,function(e){t=this._subscriptions.filter(function(e){return e.collections.includes(l)}),i=function(n){o._publications[n.publication].user_specific?Promise.all(n.clients.map(function(i){return __awaiter(u,void 0,void 0,function(){var t;return __generator(this,function(e){if((t=this._websocketManager.getWebSocket(i.id_socket))&&t.readyState===t.OPEN)try{this.sendDataToOne(t,i.messageId,n,_,l)}catch(e){this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During sendDataToOne - User Specific - Socket: "+i.id_socket+", User: "+i.id_user+", MessageId: "+i.messageId+", Pub: "+n.publication+", Err: "+JSON.stringify(e,null,2))}return[2]})})})):o.sendDataToAll(n)},o=this;try{for(n=__values(t),s=n.next();!s.done;s=n.next())r=s.value,i(r)}catch(e){a={error:e}}finally{try{s&&!s.done&&(c=n.return)&&c.call(n)}finally{if(a)throw a.error}}return[2]})})},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(t){var i=this,e=this._loggedInUsers.find(function(e){return e.id_ws===t.id_socket});e&&(e.date=new Date,logged_in_users_collection_1.LoggedInUsers.updateOne({id_ws:t.id_socket},{$set:{latency:t.latency,date:e.date}}).then(function(e){e||(i.unsubscribeAll(t),i.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",t.user,t.id_socket,3))},function(){i.unsubscribeAll(t),i.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",t.user,t.id_socket,4)}))},SubscriptionManager.prototype.subscribe=function(t,e,i,n,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={},u=Object.keys(a.check._schema).filter(function(e){return!e.includes(".")}),l=0;l<s.length;l++)c[u[l]]=s[l];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("/"),_="",d=a[0],""===a[0]&&(_="/",d=a[1]),_+=d,1<a.length&&(_+="/"),(d=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===i.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==t&&!e.messageRoute.startsWith(_)})})).length)&&(this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Detected Undestroyed Subscription - "+this.serverConfig.CLIENT_NAME,"USER: "+i.user+" (Socket: "+i.id_socket+") is on route: "+t+" but has the following subscriptions on other routes:"+JSON.stringify(d,null,2)),d.forEach(function(t){t.clients.filter(function(e){return e.id_socket===i.id_socket}).forEach(function(e){r.unsubscribe(e.messageRoute,new Date,i,e.messageId,t.publication,t.subscriptionData)})}));var _,d,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===i.id_socket&&e.messageId===n})||a.clients.push({id_user:i.id_user,messageId:n,id_socket:i.id_socket,messageRoute:t}):this._subscriptions.push({publication:o,subscriptionData:s,collections:this.getPublicationCollections(o),clients:[{id_user:i.id_user,messageId:n,id_socket:i.id_socket,messageRoute:t}],cacheId:0}),a=a||this._subscriptions.find(function(e){return e.publication===o&&JSON.stringify(e.subscriptionData)===JSON.stringify(s)}),this.processSubscription(a,i,n)}else console.error(new Date,"No Publication: "+o)},SubscriptionManager.prototype.createLoggedInUser=function(n){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return[2,new Promise(function(i,e){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n))?(t={_id:(0,mongo_manager_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),i(t)):i(null),[2]})})})]})})},SubscriptionManager.prototype.unsubscribe=function(e,t,i,n,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===i.id_user&&r.clients[a].messageId===n&&r.clients[a].id_socket===i.id_socket&&r.clients.splice(a,1)}else console.log("No Publication: "+o)},SubscriptionManager.prototype.unsubscribeAll=function(r){return __awaiter(this,void 0,void 0,function(){var t,i,n,o,s;return __generator(this,function(e){switch(e.label){case 0:return(this._debugUnSubAllHits+=1,r)?[4,logged_in_users_collection_1.LoggedInUsers.findOne({id_ws:r.id_socket})]:[3,2];case 1:for((t=e.sent())&&(0<=this._loggedInUsers.map(function(e){return e._id}).indexOf(t._id)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e._id}).indexOf(t._id),1),logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:t._id})),i=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_user===r.id_user&&e.id_socket===r.id_socket})}),n=i.length-1;0<=n;n--)for(o=i[n],s=o.clients.length-1;0<=s;s--)o.clients[s].id_socket===r.id_socket&&o.clients.splice(s,1);this._websocketManager.removeWebSocket(r),e.label=2;case 2:return[2]}})})},SubscriptionManager.prototype.getActiveSubscriptions=function(){return this._subscriptions},SubscriptionManager.prototype.getPublicationCollections=function(e){return this._publications[e].collections},SubscriptionManager.prototype.tailOpLog=function(t){return __awaiter(this,void 0,void 0,function(){var i,n=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){i=t;try{this._oplog$=index_1.ResolveIOServer.getMainDB().watch([],{resumeAfter:t})}catch(e){return this._oplog$&&(this._oplog$.removeAllListeners(),this._oplog$.close(),this._oplog$=null),this.tailOpLog(t),[2]}}else this._oplog$=index_1.ResolveIOServer.getMainDB().watch();console.log(new Date,"oplog started"),this._oplog$.on("change",function(t){var e;t.ns&&(e=t.ns.coll,n._debugOplogCollections.some(function(e){return e.collection===t.ns.coll&&e.type===t.operationType})?n._debugOplogCollections.find(function(e){return e.collection===t.ns.coll&&e.type===t.operationType}).hits+=1:n._debugOplogCollections.push({collection:t.ns.coll,type:t.operationType,hits:1}),!e||e.endsWith(".versions")||e.startsWith("monitor-")||"logs"===e||"log-method-latencies"===e||"log-subscriptions"===e||(n._debugOplogHits+=1,"insert"===t.operationType?("support-tickets"===e&&"https://resolveio.com"===n.serverConfig.ROOT_URL&&(n._mainServer.getMethodManager().callMethodInternal.call(n._mainServer.getMethodManager(),"sendSupportTicketEmail",t.documentKey._id),n.invalidatePubsCache(e,"insert")),"method-responses"!==e&&n.invalidatePubsCache(e,"insert")):"update"===t.operationType||"replace"===t.operationType?"method-responses"!==e&&n.invalidatePubsCache(e,"update"):"delete"===t.operationType&&"method-responses"!==e&&n.invalidatePubsCache(e,"delete")),"flags"===e&&flag_collection_1.Flags.findOne({type:"Enable Debug"}).then(function(e){e&&e.value?n._enableDebug=!0:n._enableDebug=!1}),i=t._id)}),this._oplog$.on("error",function(e){console.log(new Date,"oplog error",e),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(i)}),this._oplog$.on("end",function(){console.log(new Date,"oplog end"),n._oplog$.removeAllListeners(),n._oplog$.close(),n._oplog$=null,n.tailOpLog(i)}),this._oplog$.on("close",function(){console.log(new Date,"oplog close"),n._oplog$.removeAllListeners(),n._oplog$=null,n.tailOpLog(i)})}return[2]}})})},SubscriptionManager.prototype.processSubscription=function(n,o,s){return __awaiter(this,void 0,void 0,function(){var t,i;return __generator(this,function(e){if(this._publications[n.publication].user_specific)this.sendDataToOne(o,s,n,"newSub",n.collections[0]);else if(n.cacheId)try{t=JSON.parse(this._nodeCache.get(n.cacheId),common_1.dateReviver),i={messageId:s,hasError:!1,data:t},this.sendWS(o,i)}catch(e){this._nodeCache.del(n.cacheId),n.cacheId=0,this.sendDataToAll(n)}else this.sendDataToAll(n);return[2]})})},SubscriptionManager.prototype.sendDataToOne=function(s,r,a,e,t){return __awaiter(this,void 0,void 0,function(){var t,i,n,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]),[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),n={messageId:r,hasError:!1,data:o},this.sendWS(s,n),[3,4];case 3:return i=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),n={messageId:r,hasError:!0,data:i},this.sendWS(s,n),this._mainServer.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(i,null,2)),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.sendDataToAll=function(_){return __awaiter(this,void 0,void 0,function(){var t,o,i,n,s,r,a,c,u,l=this;return __generator(this,function(e){switch(e.label){case 0:return _.clients.length?[3,1]:(_.cacheId&&(this._nodeCache.del(_.cacheId),_.cacheId=0),0<=(u=this._subscriptions.findIndex(function(e){return e.publication===_.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(_.subscriptionData)}))&&this._subscriptions.splice(u,1),[2]);case 1:t=this._monitorManagerFunction.startMonitorFunction("Publication",_.publication,"","",_.subscriptionData),e.label=2;case 2:return e.trys.push([2,4,,5]),[4,(u=this._publications[_.publication].function).call.apply(u,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],__read(_.subscriptionData),!1))];case 3:if(o=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),_.cacheId)try{i=JSON.parse(this._nodeCache.get(_.cacheId),common_1.dateReviver),JSON.stringify(i)!==JSON.stringify(o)&&(Promise.all(_.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),this._nodeCache.del(_.cacheId),_.cacheId=0,!o||Array.isArray(o)&&!o.length||(_.cacheId=this._cacheId++,this._nodeCache.set(_.cacheId,JSON.stringify(o))))}catch(e){Promise.all(_.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),this._nodeCache.del(_.cacheId),_.cacheId=0,!o||Array.isArray(o)&&!o.length||(_.cacheId=this._cacheId++,this._nodeCache.set(_.cacheId,JSON.stringify(o)))}else if(Promise.all(_.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!1,data:o},this.sendWS(t,i)),[2]})})})),o&&(!Array.isArray(o)||o.length)&&(_.cacheId=this._cacheId++,this._nodeCache.set(_.cacheId,JSON.stringify(o)),(n=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 - "+_.publication+" - Deleted: "+s+" - "+n)}return[3,5];case 4:return c=e.sent(),this._monitorManagerFunction.finishMonitorFunction(t),Promise.all(_.clients.map(function(n){return __awaiter(l,void 0,void 0,function(){var t,i;return __generator(this,function(e){return(t=this._websocketManager.getWebSocket(n.id_socket))&&t.readyState===t.OPEN&&(i={messageId:n.messageId,hasError:!0,data:c},this.sendWS(t,i)),[2]})})})),this._mainServer.getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+_.publication+" - (sendPubData)\n\nData \n"+JSON.stringify(_.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","index_1","notifications_1","report_builder_reports_1","report_builder_libraries_1","user_groups_1","user_guides_1","report_builder_dashboard_builders_1","mongo_manager_1","common_1","NodeCache","flag_collection_1","os_1","numCPUs","cpus","length","v8","SubscriptionManager","mainServer","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","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","_nodeCache","stdTTL","checkperiod","_wss","loadSuperAdminPublications","loadAppStatusPublications","loadLogPublications","loadFilePublications","loadCronJobPublications","loadFlagsPublications","loadMethodResponsePublications","loadNotificationPublications","loadReportBuilderReportPublications","loadReportBuilderLibraryPublications","loadUserGroupPublications","loadUserGuidePublications","loadReportBuilderDashboardBuilderPublications","tailOpLog","setInterval","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","ResolveIOServer","getMongoManager","invalidateQueryCache","collSubs","filter","collections","includes","this_3","user_specific","Promise","all","map","ws","readyState","OPEN","sendDataToOne","messageId","err","getMethodManager","sendEmail","id_user","sendDataToAll","_i","collSubs_1","publications","method","Object","assign","loggedInLatency","updateOne","$set","latency","res","subscribe","messageRoute","messageDate","subscriptionData","pub","hits","push","check","error","_schema","valObj","rootKeys","keys","validate","errors","urlData","split","urlModule_1","urlNext","otherRouteSubs","startsWith","otherSub","unsubscribe","getPublicationCollections","cacheId","processSubscription","createLoggedInUser","resolve","reject","user","objectIdHexString","__v","insertOne","indexOf","userSubs","removeWebSocket","getActiveSubscriptions","resumeToken","_oplog$","closed","removeAllListeners","close","setTimeout","exit","lastResumeToken_1","getMainDB","watch","resumeAfter","errOp","on","doc","ns","coll","operationType","endsWith","callMethodInternal","call","documentKey","cacheData","parse","get","dateReviver","serverRes","hasError","data","sendWS","del","monitor","startMonitorFunction","function","apply","__spreadArray","finishMonitorFunction","err_1","subIndex","res_1","Array","isArray","set","nodeCacheSize","getStats","vsize","deleteCount","subArr","zz","err_2","send","exports"],"mappings":"wqDAGAA,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,EAEAQ,QAAAR,QAAA,UAAA,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,gBAAAf,QAAA,iBAAA,EACAgB,SAAAhB,QAAA,gBAAA,EACAiB,UAAAjB,QAAA,YAAA,EAEAkB,kBAAAlB,QAAA,gCAAA,EACAmB,KAAAnB,QAAA,IAAA,EAEMoB,SAAU,EAAAD,KAAAE,MAAI,EAAGC,OACjBC,GAAKvB,QAAQ,IAAI,EA0BvBwB,oBAAA,WA0CC,SAAAA,oBAAY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C,EAAGC,aAAeD,EAAGE,OAC1BiF,EAAiC,CACpC/E,UAAW/B,EAAO+B,UAClBgF,SAAU,CAAA,EACVC,KAAMqB,C,EAGPxN,KAAKoM,OAAOtF,EAAImF,CAAS,G,QAE1B,CAAC,EAGHjM,KAAKqB,YAAY+F,iBAAgB,EAAGC,UAAU,oBAAqB,6BAA+BrH,KAAKH,aAA0B,YAAG,sCAAwC8E,EAAIpB,YAAc,8BAAgCP,KAAKC,UAAU0B,EAAI2D,iBAAkB,KAAM,CAAC,EAAI,eAAiBtF,KAAKC,UAAUuK,EAAK,KAAM,CAAC,CAAC,E,6BAKtT9N,oBAAAkG,UAAAwG,OAAR,SAAetF,EAAeqF,GAC7BnM,KAAKsB,kBAAkBmM,KAAK3G,EAAIqF,CAAI,CACrC,EAEOzM,oBAAAkG,UAAAhD,eAAP,WACC,OAAO5C,KAAKS,YACb,EACDf,mBAAA,EAAC,EA1xBYgO,QAAAhO,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 ResolveIOMainServer from '../server-app';\nimport { ResolveIOServer } from '../index';\nimport { loadNotificationPublications } from '../publications/notifications';\nimport { loadReportBuilderReportPublications } from '../publications/report-builder-reports';\nimport { LoggedInUserModel } from '../models/logged-in-users.model';\n\nimport { ChangeStream, ChangeStreamDeleteDocument, ChangeStreamDocument, 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 { objectIdHexString } from './mongo.manager';\nimport { dateReviver, deepCopy } 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';\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\n\tprivate _mainServer: ResolveIOMainServer;\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// private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];\n\t// private idPerformance: number = 0;\n\t// private performanceThread;\n\n\tconstructor(mainServer, wss: WebSocket.Server, serverConfig, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._websocketManager = this._mainServer.getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\tthis._nodeCache = new NodeCache( { stdTTL: 0, checkperiod: 0 } );\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\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._publications[sub.publication].user_specific) {\n\t\t\t\t// For user-specific publications, process each client separately\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.sendDataToOne(ws, client.messageId, sub, type, collection);\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\tthis._mainServer.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\t// For non-user-specific publications, send data to all clients\n\t\t\t\tthis.sendDataToAll(sub);\n\t\t\t}\n\t\t}\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\tpublic loggedInLatency(ws: WebSocket) {\n\t\tlet loggedInUser = this._loggedInUsers.find(a => a.id_ws === ws['id_socket']);\n\n\t\tif (loggedInUser) {\n\t\t\tloggedInUser.date = new Date();\n\n\t\t\tLoggedInUsers.updateOne({id_ws: ws['id_socket']}, {$set: {latency: ws['latency'], date: loggedInUser.date}}).then(res => {\n\t\t\t\tif (!res) {\n\t\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 3);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, () => {\n\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 4);\n\t\t\t\t}\n\t\t\t});\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\tthis._mainServer.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});\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\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\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\tlet loggedInUser = await LoggedInUsers.findOne({ id_ws: ws['id_socket'] });\n\n\t\t\tif (loggedInUser) {\n\t\t\t\tif (this._loggedInUsers.map(a => a._id).indexOf(loggedInUser._id) >= 0) {\n\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.map(a => a._id).indexOf(loggedInUser._id), 1);\n\t\t\t\t}\n\n\t\t\t\tLoggedInUsers.deleteOne({ _id: loggedInUser._id });\n\t\t\t}\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\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([], { 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();\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\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 && !collection.endsWith('.versions') && !collection.startsWith('monitor-') && collection !== 'logs' && collection !== 'log-method-latencies' && collection !== 'log-subscriptions') {\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\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.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\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) {\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\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.sendDataToAll(sub);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.sendDataToAll(sub);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthis.sendDataToOne(ws, messageId, sub, 'newSub', sub.collections[0]);\n\t\t}\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate async sendDataToOne(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, type: string, collection: string) {\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', sub.publication, '', '', sub.subscriptionData);\n\t\ttry {\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\tthis._mainServer.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) {\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\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\t\t\t\t\t\t\tsub.cacheId = 0;\n\n\t\t\t\t\t\t\tif (res && (!Array.isArray(res) || res.length)) {\n\t\t\t\t\t\t\t\tsub.cacheId = this._cacheId++;\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}\n\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\t\t\t\t\t\tsub.cacheId = 0;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (res && (!Array.isArray(res) || res.length)) {\n\t\t\t\t\t\t\tsub.cacheId = this._cacheId++;\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}\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 (res && (!Array.isArray(res) || res.length)) {\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}\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\tthis._mainServer.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","index_1","notifications_1","report_builder_reports_1","report_builder_libraries_1","user_groups_1","user_guides_1","report_builder_dashboard_builders_1","mongo_manager_1","common_1","NodeCache","flag_collection_1","os_1","numCPUs","cpus","length","v8","SubscriptionManager","mainServer","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","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","_nodeCache","stdTTL","checkperiod","_wss","loadSuperAdminPublications","loadAppStatusPublications","loadLogPublications","loadFilePublications","loadCronJobPublications","loadFlagsPublications","loadMethodResponsePublications","loadNotificationPublications","loadReportBuilderReportPublications","loadReportBuilderLibraryPublications","loadUserGroupPublications","loadUserGuidePublications","loadReportBuilderDashboardBuilderPublications","tailOpLog","setInterval","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","collSubs","filter","collections","includes","this_3","user_specific","Promise","all","map","ws","readyState","OPEN","sendDataToOne","messageId","err","getMethodManager","sendEmail","id_user","sendDataToAll","collSubs_1","__values","collSubs_1_1","next","done","publications","method","Object","assign","loggedInLatency","updateOne","$set","latency","res","subscribe","messageRoute","messageDate","subscriptionData","pub","hits","push","check","error","_schema","valObj","rootKeys","keys","validate","errors","urlData","split","urlModule_1","urlNext","otherRouteSubs","startsWith","otherSub","unsubscribe","getPublicationCollections","cacheId","processSubscription","createLoggedInUser","resolve","reject","user","objectIdHexString","__v","insertOne","indexOf","userSubs","removeWebSocket","getActiveSubscriptions","resumeToken","_oplog$","closed","removeAllListeners","close","setTimeout","exit","lastResumeToken_1","ResolveIOServer","getMainDB","watch","resumeAfter","errOp","on","doc","ns","coll","operationType","endsWith","callMethodInternal","call","documentKey","cacheData","parse","get","dateReviver","serverRes","hasError","data","sendWS","del","monitor","startMonitorFunction","function","apply","__spreadArray","__read","finishMonitorFunction","err_1","subIndex","res_1","Array","isArray","set","nodeCacheSize","getStats","vsize","deleteCount","subArr","zz","err_2","send","exports"],"mappings":"+xEAGAA,Q,0FAA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f,mBAAA,EAAC,EAxxBYkO,QAAAlO,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 ResolveIOMainServer from '../server-app';\nimport { ResolveIOServer } from '../index';\nimport { loadNotificationPublications } from '../publications/notifications';\nimport { loadReportBuilderReportPublications } from '../publications/report-builder-reports';\nimport { LoggedInUserModel } from '../models/logged-in-users.model';\n\nimport { ChangeStream, ChangeStreamDeleteDocument, ChangeStreamDocument, 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 { objectIdHexString } from './mongo.manager';\nimport { dateReviver, deepCopy } 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';\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\n\tprivate _mainServer: ResolveIOMainServer;\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// private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];\n\t// private idPerformance: number = 0;\n\t// private performanceThread;\n\n\tconstructor(mainServer, wss: WebSocket.Server, serverConfig, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._websocketManager = this._mainServer.getWebSocketManager();\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\tthis._nodeCache = new NodeCache( { stdTTL: 0, checkperiod: 0 } );\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\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\tlet collSubs = this._subscriptions.filter(a => a.collections.includes(collection));\n\n\t\tfor (let sub of collSubs) {\n\t\t\tif (this._publications[sub.publication].user_specific) {\n\t\t\t\t// For user-specific publications, process each client separately\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.sendDataToOne(ws, client.messageId, sub, type, collection);\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\tthis._mainServer.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\t// For non-user-specific publications, send data to all clients\n\t\t\t\tthis.sendDataToAll(sub);\n\t\t\t}\n\t\t}\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\tpublic loggedInLatency(ws: WebSocket) {\n\t\tlet loggedInUser = this._loggedInUsers.find(a => a.id_ws === ws['id_socket']);\n\n\t\tif (loggedInUser) {\n\t\t\tloggedInUser.date = new Date();\n\n\t\t\tLoggedInUsers.updateOne({id_ws: ws['id_socket']}, {$set: {latency: ws['latency'], date: loggedInUser.date}}).then(res => {\n\t\t\t\tif (!res) {\n\t\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 3);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, () => {\n\t\t\t\tthis.unsubscribeAll(ws);\n\t\t\t\tif (this.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Sub Manager', 'Unsub WS', ws['user'], ws['id_socket'], 4);\n\t\t\t\t}\n\t\t\t});\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\tthis._mainServer.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});\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\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\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\tlet loggedInUser = await LoggedInUsers.findOne({ id_ws: ws['id_socket'] });\n\n\t\t\tif (loggedInUser) {\n\t\t\t\tif (this._loggedInUsers.map(a => a._id).indexOf(loggedInUser._id) >= 0) {\n\t\t\t\t\tthis._loggedInUsers.splice(this._loggedInUsers.map(a => a._id).indexOf(loggedInUser._id), 1);\n\t\t\t\t}\n\n\t\t\t\tLoggedInUsers.deleteOne({ _id: loggedInUser._id });\n\t\t\t}\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\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([], { 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();\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\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 && !collection.endsWith('.versions') && !collection.startsWith('monitor-') && collection !== 'logs' && collection !== 'log-method-latencies' && collection !== 'log-subscriptions') {\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\tthis._mainServer.getMethodManager().callMethodInternal.call(this._mainServer.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\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) {\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\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.sendDataToAll(sub);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.sendDataToAll(sub);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthis.sendDataToOne(ws, messageId, sub, 'newSub', sub.collections[0]);\n\t\t}\n\t}\n\n\t// Fetch pub once, send to all clients linked to this pub\n\tprivate async sendDataToOne(ws: WebSocket, messageId: number, sub: ActiveSubscriptionModel, type: string, collection: string) {\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', sub.publication, '', '', sub.subscriptionData);\n\t\ttry {\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\tthis._mainServer.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) {\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\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\t\t\t\t\t\t\tsub.cacheId = 0;\n\n\t\t\t\t\t\t\tif (res && (!Array.isArray(res) || res.length)) {\n\t\t\t\t\t\t\t\tsub.cacheId = this._cacheId++;\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}\n\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\t\t\t\t\t\tsub.cacheId = 0;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (res && (!Array.isArray(res) || res.length)) {\n\t\t\t\t\t\t\tsub.cacheId = this._cacheId++;\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}\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 (res && (!Array.isArray(res) || res.length)) {\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}\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\tthis._mainServer.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,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var worker_threads_1=require("worker_threads"),common_1=require("../util/common"),totalPerfomanceMonitor=[];function processMsg(a){totalPerfomanceMonitor.length?(totalPerfomanceMonitor.forEach(function(n){var t=a.filter(function(t){return t.function===n.function&&t.publication===n.publication&&JSON.stringify(t.subscriptionData)===JSON.stringify(n.subscriptionData)});t.length?(n.data=n.data.concat(t),n.duration_total_max=Math.max.apply(Math,n.data.map(function(t){return t.duration})),n.duration_total_min=Math.min.apply(Math,n.data.map(function(t){return t.duration})),n.duration_total_avg=(0,common_1.round)(n.data.map(function(t){return t.duration}).reduce(function(t,n){return t+n},0)/n.data.length),n.hits_total=n.data.length,n.duration_current_max=Math.max.apply(Math,t.map(function(t){return t.duration})),n.duration_current_min=Math.min.apply(Math,t.map(function(t){return t.duration})),n.duration_current_avg=(0,common_1.round)(t.map(function(t){return t.duration}).reduce(function(t,n){return t+n},0)/t.length),n.hits_current=t.length):(n.duration_current_max=0,n.duration_current_min=0,n.duration_current_avg=0,n.hits_current=0),t.forEach(function(n){a.splice(a.findIndex(function(t){return t._id===n._id}),1)})}),a.forEach(function(n){var t=totalPerfomanceMonitor.find(function(t){return t.function===n.function&&t.publication===n.publication&&JSON.stringify(t.subscriptionData)===JSON.stringify(n.subscriptionData)});t?t.data.push(n):totalPerfomanceMonitor.push({function:n.function,publication:n.publication,subscriptionData:n.subscriptionData,data:[n],duration_total_max:0,duration_total_min:0,duration_total_avg:0,hits_total:0,duration_current_max:0,duration_current_min:0,duration_current_avg:0,hits_current:0})})):(a.forEach(function(n){var t=totalPerfomanceMonitor.find(function(t){return t.function===n.function&&t.publication===n.publication&&JSON.stringify(t.subscriptionData)===JSON.stringify(n.subscriptionData)});t?t.data.push(n):totalPerfomanceMonitor.push({function:n.function,publication:n.publication,subscriptionData:n.subscriptionData,data:[n],duration_total_max:0,duration_total_min:0,duration_total_avg:0,hits_total:0,duration_current_max:0,duration_current_min:0,duration_current_avg:0,hits_current:0})}),totalPerfomanceMonitor.forEach(function(t){t.duration_total_max=Math.max.apply(Math,t.data.map(function(t){return t.duration})),t.duration_total_min=Math.min.apply(Math,t.data.map(function(t){return t.duration})),t.duration_total_avg=(0,common_1.round)(t.data.map(function(t){return t.duration}).reduce(function(t,n){return t+n},0)/t.data.length),t.hits_total=t.data.length,t.duration_current_max=Math.max.apply(Math,t.data.map(function(t){return t.duration})),t.duration_current_min=Math.min.apply(Math,t.data.map(function(t){return t.duration})),t.duration_current_avg=(0,common_1.round)(t.data.map(function(t){return t.duration}).reduce(function(t,n){return t+n},0)/t.data.length),t.hits_current=t.data.length})),console.log("---------------------------------------------------------------------------------"),console.log("---------------------------------------------------------------------------------"),console.log("Performance",new Date),console.log("---------------------------------------------------------------------------------"),console.log("Function, Publication, Hits Total, Dur Tot Max, Dur Tot Min, Dur Tot Avg, Hits Current, Dur Curr Max, Dur Curr Min, Dur Curr Avg, Sub Data"),totalPerfomanceMonitor.sort(function(t,n){return n.hits_total-t.hits_total}).forEach(function(t){console.log(t.function+","+t.publication+","+t.hits_total+","+t.duration_total_max+","+t.duration_total_min+","+t.duration_total_avg+","+t.hits_current+","+t.duration_current_max+","+t.duration_current_min+","+t.duration_current_avg+","+JSON.stringify(t.subscriptionData))}),console.log("---------------------------------------------------------------------------------"),console.log("---------------------------------------------------------------------------------")}worker_threads_1.parentPort.on("message",function(t){console.log("Recv Msg"),processMsg(t)});
1
+ "use strict";var __read=this&&this.__read||function(t,r){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var a,o,i=n.call(t),u=[];try{for(;(void 0===r||0<r--)&&!(a=i.next()).done;)u.push(a.value)}catch(t){o={error:t}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return u},__spreadArray=this&&this.__spreadArray||function(t,r,n){if(n||2===arguments.length)for(var a,o=0,i=r.length;o<i;o++)!a&&o in r||((a=a||Array.prototype.slice.call(r,0,o))[o]=r[o]);return t.concat(a||Array.prototype.slice.call(r))},worker_threads_1=(Object.defineProperty(exports,"__esModule",{value:!0}),require("worker_threads")),common_1=require("../util/common"),totalPerfomanceMonitor=[];function processMsg(n){totalPerfomanceMonitor.length?(totalPerfomanceMonitor.forEach(function(r){var t=n.filter(function(t){return t.function===r.function&&t.publication===r.publication&&JSON.stringify(t.subscriptionData)===JSON.stringify(r.subscriptionData)});t.length?(r.data=r.data.concat(t),r.duration_total_max=Math.max.apply(Math,__spreadArray([],__read(r.data.map(function(t){return t.duration})),!1)),r.duration_total_min=Math.min.apply(Math,__spreadArray([],__read(r.data.map(function(t){return t.duration})),!1)),r.duration_total_avg=(0,common_1.round)(r.data.map(function(t){return t.duration}).reduce(function(t,r){return t+r},0)/r.data.length),r.hits_total=r.data.length,r.duration_current_max=Math.max.apply(Math,__spreadArray([],__read(t.map(function(t){return t.duration})),!1)),r.duration_current_min=Math.min.apply(Math,__spreadArray([],__read(t.map(function(t){return t.duration})),!1)),r.duration_current_avg=(0,common_1.round)(t.map(function(t){return t.duration}).reduce(function(t,r){return t+r},0)/t.length),r.hits_current=t.length):(r.duration_current_max=0,r.duration_current_min=0,r.duration_current_avg=0,r.hits_current=0),t.forEach(function(r){n.splice(n.findIndex(function(t){return t._id===r._id}),1)})}),n.forEach(function(r){var t=totalPerfomanceMonitor.find(function(t){return t.function===r.function&&t.publication===r.publication&&JSON.stringify(t.subscriptionData)===JSON.stringify(r.subscriptionData)});t?t.data.push(r):totalPerfomanceMonitor.push({function:r.function,publication:r.publication,subscriptionData:r.subscriptionData,data:[r],duration_total_max:0,duration_total_min:0,duration_total_avg:0,hits_total:0,duration_current_max:0,duration_current_min:0,duration_current_avg:0,hits_current:0})})):(n.forEach(function(r){var t=totalPerfomanceMonitor.find(function(t){return t.function===r.function&&t.publication===r.publication&&JSON.stringify(t.subscriptionData)===JSON.stringify(r.subscriptionData)});t?t.data.push(r):totalPerfomanceMonitor.push({function:r.function,publication:r.publication,subscriptionData:r.subscriptionData,data:[r],duration_total_max:0,duration_total_min:0,duration_total_avg:0,hits_total:0,duration_current_max:0,duration_current_min:0,duration_current_avg:0,hits_current:0})}),totalPerfomanceMonitor.forEach(function(t){t.duration_total_max=Math.max.apply(Math,__spreadArray([],__read(t.data.map(function(t){return t.duration})),!1)),t.duration_total_min=Math.min.apply(Math,__spreadArray([],__read(t.data.map(function(t){return t.duration})),!1)),t.duration_total_avg=(0,common_1.round)(t.data.map(function(t){return t.duration}).reduce(function(t,r){return t+r},0)/t.data.length),t.hits_total=t.data.length,t.duration_current_max=Math.max.apply(Math,__spreadArray([],__read(t.data.map(function(t){return t.duration})),!1)),t.duration_current_min=Math.min.apply(Math,__spreadArray([],__read(t.data.map(function(t){return t.duration})),!1)),t.duration_current_avg=(0,common_1.round)(t.data.map(function(t){return t.duration}).reduce(function(t,r){return t+r},0)/t.data.length),t.hits_current=t.data.length})),console.log("---------------------------------------------------------------------------------"),console.log("---------------------------------------------------------------------------------"),console.log("Performance",new Date),console.log("---------------------------------------------------------------------------------"),console.log("Function, Publication, Hits Total, Dur Tot Max, Dur Tot Min, Dur Tot Avg, Hits Current, Dur Curr Max, Dur Curr Min, Dur Curr Avg, Sub Data"),totalPerfomanceMonitor.sort(function(t,r){return r.hits_total-t.hits_total}).forEach(function(t){console.log(t.function+","+t.publication+","+t.hits_total+","+t.duration_total_max+","+t.duration_total_min+","+t.duration_total_avg+","+t.hits_current+","+t.duration_current_max+","+t.duration_current_min+","+t.duration_current_avg+","+JSON.stringify(t.subscriptionData))}),console.log("---------------------------------------------------------------------------------"),console.log("---------------------------------------------------------------------------------")}worker_threads_1.parentPort.on("message",function(t){console.log("Recv Msg"),processMsg(t)});
2
2
  //# sourceMappingURL=subscription.performance.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/subscription.performance.ts"],"names":["worker_threads_1","require","common_1","totalPerfomanceMonitor","processMsg","msg","length","forEach","total","currents","filter","a","function","publication","JSON","stringify","subscriptionData","data","concat","duration_total_max","Math","max","apply","map","duration","duration_total_min","min","duration_total_avg","round","reduce","b","hits_total","duration_current_max","duration_current_min","duration_current_avg","hits_current","current","splice","findIndex","_id","entry","find","push","console","log","Date","sort","parentPort","on"],"mappings":"oEAAA,IAAAA,iBAAAC,QAAA,gBAAA,EACAC,SAAAD,QAAA,gBAAA,EA4BIE,uBAAoD,GAOxD,SAASC,WAAWC,GACfF,uBAAuBG,QACpBH,uBAAuBI,QAAQ,SAAAC,GAC3B,IAAIC,EAAWJ,EAAIK,OAAO,SAAAC,GAAK,OAAAA,EAAEC,WAAaJ,EAAMI,UAAYD,EAAEE,cAAgBL,EAAMK,aAAeC,KAAKC,UAAUJ,EAAEK,gBAAgB,IAAMF,KAAKC,UAAUP,EAAMQ,gBAAgB,CAApJ,CAAqJ,EAEhLP,EAASH,QACTE,EAAMS,KAAOT,EAAMS,KAAKC,OAAOT,CAAQ,EACvCD,EAAMW,mBAAqBC,KAAKC,IAAGC,MAARF,KAAYZ,EAAMS,KAAKM,IAAI,SAAAZ,GAAK,OAAAA,EAAEa,QAAF,CAAU,CAAC,EACtEhB,EAAMiB,mBAAqBL,KAAKM,IAAGJ,MAARF,KAAYZ,EAAMS,KAAKM,IAAI,SAAAZ,GAAK,OAAAA,EAAEa,QAAF,CAAU,CAAC,EACtEhB,EAAMmB,oBAAqB,EAAAzB,SAAA0B,OAAMpB,EAAMS,KAAKM,IAAI,SAAAZ,GAAK,OAAAA,EAAEa,QAAF,CAAU,EAAEK,OAAO,SAAClB,EAAGmB,GAAM,OAAAnB,EAAImB,CAAJ,EAAO,CAAC,EAAItB,EAAMS,KAAKX,MAAM,EAC/GE,EAAMuB,WAAavB,EAAMS,KAAKX,OAC9BE,EAAMwB,qBAAuBZ,KAAKC,IAAGC,MAARF,KAAYX,EAASc,IAAI,SAAAZ,GAAK,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,GAAK,OAAAA,EAAEa,QAAF,CAAU,CAAC,EACxEhB,EAAM0B,sBAAuB,EAAAhC,SAAA0B,OAAMpB,EAAMS,KAAKM,IAAI,SAAAZ,GAAK,OAAAA,EAAEa,QAAF,CAAU,EAAEK,OAAO,SAAClB,EAAGmB,GAAM,OAAAnB,EAAImB,CAAJ,EAAO,CAAC,EAAItB,EAAMS,KAAKX,MAAM,EACjHE,EAAM2B,aAAe3B,EAAMS,KAAKX,MACpC,CAAC,GAGLqC,QAAQC,IAAI,mFAAmF,EAC/FD,QAAQC,IAAI,mFAAmF,EAE/FD,QAAQC,IAAI,cAAe,IAAIC,IAAM,EACrCF,QAAQC,IAAI,mFAAmF,EAG/FD,QAAQC,IAAI,4IAA4I,EAExJzC,uBAAuB2C,KAAK,SAACnC,EAAGmB,GAAM,OAAAA,EAAEC,WAAapB,EAAEoB,UAAjB,CAA2B,EAAExB,QAAQ,SAAAC,GACvEmC,QAAQC,IAAIpC,EAAMI,SAAW,IAAMJ,EAAMK,YAAc,IAAML,EAAMuB,WAAa,IAAMvB,EAAMW,mBAAqB,IAAMX,EAAMiB,mBAAqB,IAAMjB,EAAMmB,mBAAqB,IAAMnB,EAAM2B,aAAe,IAAM3B,EAAMwB,qBAAuB,IAAMxB,EAAMyB,qBAAuB,IAAMzB,EAAM0B,qBAAuB,IAAMpB,KAAKC,UAAUP,EAAMQ,gBAAgB,CAAC,CACvW,CAAC,EAED2B,QAAQC,IAAI,mFAAmF,EAC/FD,QAAQC,IAAI,mFAAmF,CACnG,CA3GA5C,iBAAA+C,WAAWC,GAAG,UAAW,SAAA3C,GACrBsC,QAAQC,IAAI,UAAU,EACzBxC,WAAWC,CAAG,CACf,CAAC","file":"subscription.performance.js","sourcesContent":["import { parentPort } from 'worker_threads';\nimport { round } from '../util/common';\n\ninterface 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\ninterface TotalPerformanceMonitor {\n\tfunction: string;\n\tpublication: string;\n\tsubscriptionData: any[];\n\tdata: CurrentPerformanceMonitor[];\n\tduration_total_max: number;\n\tduration_total_min: number;\n\tduration_total_avg: number;\n\thits_total: number;\n\tduration_current_max: number;\n\tduration_current_min: number;\n\tduration_current_avg: number;\n\thits_current: number;\n}\n\nlet totalPerfomanceMonitor: TotalPerformanceMonitor[] = [];\n\nparentPort.on('message', msg => {\n console.log('Recv Msg');\n\tprocessMsg(msg);\n});\n\nfunction processMsg(msg: CurrentPerformanceMonitor[]) {\n\tif (totalPerfomanceMonitor.length) {\n totalPerfomanceMonitor.forEach(total => {\n let currents = msg.filter(a => a.function === total.function && a.publication === total.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(total.subscriptionData));\n\n if (currents.length) {\n total.data = total.data.concat(currents);\n total.duration_total_max = Math.max(...total.data.map(a => a.duration));\n total.duration_total_min = Math.min(...total.data.map(a => a.duration));\n total.duration_total_avg = round(total.data.map(a => a.duration).reduce((a, b) => a + b, 0) / total.data.length);\n total.hits_total = total.data.length;\n total.duration_current_max = Math.max(...currents.map(a => a.duration));\n total.duration_current_min = Math.min(...currents.map(a => a.duration));\n total.duration_current_avg = round(currents.map(a => a.duration).reduce((a, b) => a + b, 0) / currents.length);\n total.hits_current = currents.length;\n }\n else {\n total.duration_current_max = 0;\n total.duration_current_min = 0;\n total.duration_current_avg = 0;\n total.hits_current = 0;\n }\n\n currents.forEach(current => {\n msg.splice(msg.findIndex(a => a._id === current._id), 1);\n });\n });\n\n msg.forEach(entry => {\n let total = totalPerfomanceMonitor.find(a => a.function === entry.function && a.publication === entry.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(entry.subscriptionData));\n if (total) {\n total.data.push(entry);\n }\n else {\n totalPerfomanceMonitor.push({\n function: entry.function,\n publication: entry.publication,\n subscriptionData: entry.subscriptionData,\n data: [entry],\n duration_total_max: 0,\n duration_total_min: 0,\n duration_total_avg: 0,\n hits_total: 0,\n duration_current_max: 0,\n duration_current_min: 0,\n duration_current_avg: 0,\n hits_current: 0\n });\n }\n });\n }\n else {\n msg.forEach(entry => {\n let total = totalPerfomanceMonitor.find(a => a.function === entry.function && a.publication === entry.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(entry.subscriptionData));\n if (total) {\n total.data.push(entry);\n }\n else {\n totalPerfomanceMonitor.push({\n function: entry.function,\n publication: entry.publication,\n subscriptionData: entry.subscriptionData,\n data: [entry],\n duration_total_max: 0,\n duration_total_min: 0,\n duration_total_avg: 0,\n hits_total: 0,\n duration_current_max: 0,\n duration_current_min: 0,\n duration_current_avg: 0,\n hits_current: 0\n });\n }\n });\n\n totalPerfomanceMonitor.forEach(total => {\n total.duration_total_max = Math.max(...total.data.map(a => a.duration));\n total.duration_total_min = Math.min(...total.data.map(a => a.duration));\n total.duration_total_avg = round(total.data.map(a => a.duration).reduce((a, b) => a + b, 0) / total.data.length);\n total.hits_total = total.data.length;\n total.duration_current_max = Math.max(...total.data.map(a => a.duration));\n total.duration_current_min = Math.min(...total.data.map(a => a.duration));\n total.duration_current_avg = round(total.data.map(a => a.duration).reduce((a, b) => a + b, 0) / total.data.length);\n total.hits_current = total.data.length;\n });\n }\n\n console.log('---------------------------------------------------------------------------------');\n console.log('---------------------------------------------------------------------------------');\n\n console.log('Performance', new Date());\n console.log('---------------------------------------------------------------------------------');\n\n\n console.log('Function, Publication, Hits Total, Dur Tot Max, Dur Tot Min, Dur Tot Avg, Hits Current, Dur Curr Max, Dur Curr Min, Dur Curr Avg, Sub Data');\n\n totalPerfomanceMonitor.sort((a, b) => b.hits_total - a.hits_total).forEach(total => {\n console.log(total.function + ',' + total.publication + ',' + total.hits_total + ',' + total.duration_total_max + ',' + total.duration_total_min + ',' + total.duration_total_avg + ',' + total.hits_current + ',' + total.duration_current_max + ',' + total.duration_current_min + ',' + total.duration_current_avg + ',' + JSON.stringify(total.subscriptionData));\n });\n\n console.log('---------------------------------------------------------------------------------');\n console.log('---------------------------------------------------------------------------------');\n}"]}
1
+ {"version":3,"sources":["../../src/managers/subscription.performance.ts"],"names":["worker_threads_1","require","common_1","totalPerfomanceMonitor","processMsg","msg","length","forEach","total","currents","filter","a","function","publication","JSON","stringify","subscriptionData","data","concat","duration_total_max","Math","max","apply","__spreadArray","__read","map","duration","duration_total_min","min","duration_total_avg","round","reduce","b","hits_total","duration_current_max","duration_current_min","duration_current_avg","hits_current","current","splice","findIndex","_id","entry","find","push","console","log","Date","sort","parentPort","on"],"mappings":"wiBAAAA,kB,uDAAAC,QAAA,gBAAA,GACAC,SAAAD,QAAA,gBAAA,EA4BIE,uBAAoD,GAOxD,SAASC,WAAWC,GACfF,uBAAuBG,QACpBH,uBAAuBI,QAAQ,SAAAC,GAC3B,IAAIC,EAAWJ,EAAIK,OAAO,SAAAC,GAAK,OAAAA,EAAEC,WAAaJ,EAAMI,UAAYD,EAAEE,cAAgBL,EAAMK,aAAeC,KAAKC,UAAUJ,EAAEK,gBAAgB,IAAMF,KAAKC,UAAUP,EAAMQ,gBAAgB,CAApJ,CAAqJ,EAEhLP,EAASH,QACTE,EAAMS,KAAOT,EAAMS,KAAKC,OAAOT,CAAQ,EACvCD,EAAMW,mBAAqBC,KAAKC,IAAGC,MAARF,KAAIG,cAAA,GAAAC,OAAQhB,EAAMS,KAAKQ,IAAI,SAAAd,GAAK,OAAAA,EAAEe,QAAF,CAAU,CAAC,EAAA,CAAA,CAAA,CAAA,EACtElB,EAAMmB,mBAAqBP,KAAKQ,IAAGN,MAARF,KAAIG,cAAA,GAAAC,OAAQhB,EAAMS,KAAKQ,IAAI,SAAAd,GAAK,OAAAA,EAAEe,QAAF,CAAU,CAAC,EAAA,CAAA,CAAA,CAAA,EACtElB,EAAMqB,oBAAqB,EAAA3B,SAAA4B,OAAMtB,EAAMS,KAAKQ,IAAI,SAAAd,GAAK,OAAAA,EAAEe,QAAF,CAAU,EAAEK,OAAO,SAACpB,EAAGqB,GAAM,OAAArB,EAAIqB,CAA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,EAAM4B,qBAAuB,IAAMtB,KAAKC,UAAUP,EAAMQ,gBAAgB,CAAC,CACvW,CAAC,EAED6B,QAAQC,IAAI,mFAAmF,EAC/FD,QAAQC,IAAI,mFAAmF,CACnG,CA3GA9C,iBAAAiD,WAAWC,GAAG,UAAW,SAAA7C,GACrBwC,QAAQC,IAAI,UAAU,EACzB1C,WAAWC,CAAG,CACf,CAAC","file":"subscription.performance.js","sourcesContent":["import { parentPort } from 'worker_threads';\nimport { round } from '../util/common';\n\ninterface 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\ninterface TotalPerformanceMonitor {\n\tfunction: string;\n\tpublication: string;\n\tsubscriptionData: any[];\n\tdata: CurrentPerformanceMonitor[];\n\tduration_total_max: number;\n\tduration_total_min: number;\n\tduration_total_avg: number;\n\thits_total: number;\n\tduration_current_max: number;\n\tduration_current_min: number;\n\tduration_current_avg: number;\n\thits_current: number;\n}\n\nlet totalPerfomanceMonitor: TotalPerformanceMonitor[] = [];\n\nparentPort.on('message', msg => {\n console.log('Recv Msg');\n\tprocessMsg(msg);\n});\n\nfunction processMsg(msg: CurrentPerformanceMonitor[]) {\n\tif (totalPerfomanceMonitor.length) {\n totalPerfomanceMonitor.forEach(total => {\n let currents = msg.filter(a => a.function === total.function && a.publication === total.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(total.subscriptionData));\n\n if (currents.length) {\n total.data = total.data.concat(currents);\n total.duration_total_max = Math.max(...total.data.map(a => a.duration));\n total.duration_total_min = Math.min(...total.data.map(a => a.duration));\n total.duration_total_avg = round(total.data.map(a => a.duration).reduce((a, b) => a + b, 0) / total.data.length);\n total.hits_total = total.data.length;\n total.duration_current_max = Math.max(...currents.map(a => a.duration));\n total.duration_current_min = Math.min(...currents.map(a => a.duration));\n total.duration_current_avg = round(currents.map(a => a.duration).reduce((a, b) => a + b, 0) / currents.length);\n total.hits_current = currents.length;\n }\n else {\n total.duration_current_max = 0;\n total.duration_current_min = 0;\n total.duration_current_avg = 0;\n total.hits_current = 0;\n }\n\n currents.forEach(current => {\n msg.splice(msg.findIndex(a => a._id === current._id), 1);\n });\n });\n\n msg.forEach(entry => {\n let total = totalPerfomanceMonitor.find(a => a.function === entry.function && a.publication === entry.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(entry.subscriptionData));\n if (total) {\n total.data.push(entry);\n }\n else {\n totalPerfomanceMonitor.push({\n function: entry.function,\n publication: entry.publication,\n subscriptionData: entry.subscriptionData,\n data: [entry],\n duration_total_max: 0,\n duration_total_min: 0,\n duration_total_avg: 0,\n hits_total: 0,\n duration_current_max: 0,\n duration_current_min: 0,\n duration_current_avg: 0,\n hits_current: 0\n });\n }\n });\n }\n else {\n msg.forEach(entry => {\n let total = totalPerfomanceMonitor.find(a => a.function === entry.function && a.publication === entry.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(entry.subscriptionData));\n if (total) {\n total.data.push(entry);\n }\n else {\n totalPerfomanceMonitor.push({\n function: entry.function,\n publication: entry.publication,\n subscriptionData: entry.subscriptionData,\n data: [entry],\n duration_total_max: 0,\n duration_total_min: 0,\n duration_total_avg: 0,\n hits_total: 0,\n duration_current_max: 0,\n duration_current_min: 0,\n duration_current_avg: 0,\n hits_current: 0\n });\n }\n });\n\n totalPerfomanceMonitor.forEach(total => {\n total.duration_total_max = Math.max(...total.data.map(a => a.duration));\n total.duration_total_min = Math.min(...total.data.map(a => a.duration));\n total.duration_total_avg = round(total.data.map(a => a.duration).reduce((a, b) => a + b, 0) / total.data.length);\n total.hits_total = total.data.length;\n total.duration_current_max = Math.max(...total.data.map(a => a.duration));\n total.duration_current_min = Math.min(...total.data.map(a => a.duration));\n total.duration_current_avg = round(total.data.map(a => a.duration).reduce((a, b) => a + b, 0) / total.data.length);\n total.hits_current = total.data.length;\n });\n }\n\n console.log('---------------------------------------------------------------------------------');\n console.log('---------------------------------------------------------------------------------');\n\n console.log('Performance', new Date());\n console.log('---------------------------------------------------------------------------------');\n\n\n console.log('Function, Publication, Hits Total, Dur Tot Max, Dur Tot Min, Dur Tot Avg, Hits Current, Dur Curr Max, Dur Curr Min, Dur Curr Avg, Sub Data');\n\n totalPerfomanceMonitor.sort((a, b) => b.hits_total - a.hits_total).forEach(total => {\n console.log(total.function + ',' + total.publication + ',' + total.hits_total + ',' + total.duration_total_max + ',' + total.duration_total_min + ',' + total.duration_total_avg + ',' + total.hits_current + ',' + total.duration_current_max + ',' + total.duration_current_min + ',' + total.duration_current_avg + ',' + JSON.stringify(total.subscriptionData));\n });\n\n console.log('---------------------------------------------------------------------------------');\n console.log('---------------------------------------------------------------------------------');\n}"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WebSocketManager=void 0;var WebSocketManager=function(){function WebSocketManager(e,t,s){void 0===t&&(t=20480),void 0===s&&(s=25),this._messageBuffers=new Map,this._batchingTimers=new Map,this._webSockets=new Map,this._mainServer=e,this._maxMessageSize=t,this._messageDelay=s}return WebSocketManager.prototype.addWebSocket=function(e){var t=e.id_socket;this._webSockets.set(t,e)},WebSocketManager.prototype.removeWebSocket=function(e){var t=e.id_socket;this._webSockets.delete(t),this.closeConnection(e)},WebSocketManager.prototype.getWebSocket=function(e){return this._webSockets.get(e)},WebSocketManager.prototype.send=function(e,t){var s=this,n=e.id_socket;this._messageBuffers.has(n)||this._messageBuffers.set(n,[]),"string"==typeof t?this._messageBuffers.get(n).push({messageId:null,hasError:!1,data:t}):this._messageBuffers.get(n).push(t),this._batchingTimers.has(n)||(t=setTimeout(function(){s.flushMessages(e)},this._messageDelay),this._batchingTimers.set(n,t))},WebSocketManager.prototype.flushMessages=function(t){var e,s=this,n=t.id_socket,i=this._messageBuffers.get(n);i&&0<i.length&&(e=JSON.stringify(i),Buffer.byteLength(e,"utf8")>this._maxMessageSize?this.sendMessagesInChunks(t,i):t.send(e,function(e){e&&s.handleSendError(t,e)}),this._messageBuffers.delete(n),clearTimeout(this._batchingTimers.get(n)),this._batchingTimers.delete(n))},WebSocketManager.prototype.sendMessagesInChunks=function(t,e){for(var s=this,n=[],i=0,r=0,a=e;r<a.length;r++){var o=a[r],c=JSON.stringify([o]),c=Buffer.byteLength(c,"utf8");i+c>this._maxMessageSize?(t.send(JSON.stringify(n),function(e){e&&s.handleSendError(t,e)}),n=[o],i=c):(n.push(o),i+=c)}0<n.length&&t.send(JSON.stringify(n),function(e){e&&s.handleSendError(t,e)})},WebSocketManager.prototype.handleSendError=function(e,t){this._mainServer.getSubscriptionManager().getEnableDebug()&&console.log(new Date,"WebSocketManager","Unsub WS",e.user,e.id_socket,t),this._mainServer.getSubscriptionManager().unsubscribeAll(e),this.removeWebSocket(e)},WebSocketManager.prototype.closeConnection=function(e){e.close();var t=e.id_socket;this._messageBuffers.delete(t),this._batchingTimers.has(t)&&(clearTimeout(this._batchingTimers.get(t)),this._batchingTimers.delete(t)),process.nextTick(function(){[e.OPEN,e.CLOSING].includes(e.readyState)&&e.terminate()})},WebSocketManager}();exports.WebSocketManager=WebSocketManager;
1
+ "use strict";var __values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,s=t&&e[t],n=0;if(s)return s.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},WebSocketManager=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.WebSocketManager=void 0,function(){function WebSocketManager(e,t,s){void 0===t&&(t=20480),void 0===s&&(s=25),this._messageBuffers=new Map,this._batchingTimers=new Map,this._webSockets=new Map,this._mainServer=e,this._maxMessageSize=t,this._messageDelay=s}return WebSocketManager.prototype.addWebSocket=function(e){var t=e.id_socket;this._webSockets.set(t,e)},WebSocketManager.prototype.removeWebSocket=function(e){var t=e.id_socket;this._webSockets.delete(t),this.closeConnection(e)},WebSocketManager.prototype.getWebSocket=function(e){return this._webSockets.get(e)},WebSocketManager.prototype.send=function(e,t){var s=this,n=e.id_socket;this._messageBuffers.has(n)||this._messageBuffers.set(n,[]),"string"==typeof t?this._messageBuffers.get(n).push({messageId:null,hasError:!1,data:t}):this._messageBuffers.get(n).push(t),this._batchingTimers.has(n)||(t=setTimeout(function(){s.flushMessages(e)},this._messageDelay),this._batchingTimers.set(n,t))},WebSocketManager.prototype.flushMessages=function(t){var e,s=this,n=t.id_socket,r=this._messageBuffers.get(n);r&&0<r.length&&(e=JSON.stringify(r),Buffer.byteLength(e,"utf8")>this._maxMessageSize?this.sendMessagesInChunks(t,r):t.send(e,function(e){e&&s.handleSendError(t,e)}),this._messageBuffers.delete(n),clearTimeout(this._batchingTimers.get(n)),this._batchingTimers.delete(n))},WebSocketManager.prototype.sendMessagesInChunks=function(t,e){var s,n,r=this,i=[],o=0;try{for(var a=__values(e),c=a.next();!c.done;c=a.next()){var h=c.value,g=JSON.stringify([h]),u=Buffer.byteLength(g,"utf8");o+u>this._maxMessageSize?(t.send(JSON.stringify(i),function(e){e&&r.handleSendError(t,e)}),i=[h],o=u):(i.push(h),o+=u)}}catch(e){s={error:e}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(s)throw s.error}}0<i.length&&t.send(JSON.stringify(i),function(e){e&&r.handleSendError(t,e)})},WebSocketManager.prototype.handleSendError=function(e,t){this._mainServer.getSubscriptionManager().getEnableDebug()&&console.log(new Date,"WebSocketManager","Unsub WS",e.user,e.id_socket,t),this._mainServer.getSubscriptionManager().unsubscribeAll(e),this.removeWebSocket(e)},WebSocketManager.prototype.closeConnection=function(e){e.close();var t=e.id_socket;this._messageBuffers.delete(t),this._batchingTimers.has(t)&&(clearTimeout(this._batchingTimers.get(t)),this._batchingTimers.delete(t)),process.nextTick(function(){[e.OPEN,e.CLOSING].includes(e.readyState)&&e.terminate()})},WebSocketManager}());exports.WebSocketManager=WebSocketManager;
2
2
  //# sourceMappingURL=websocket.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/websocket.manager.ts"],"names":["WebSocketManager","mainServer","maxMessageSize","messageDelay","this","_messageBuffers","Map","_batchingTimers","_webSockets","_mainServer","_maxMessageSize","_messageDelay","prototype","addWebSocket","ws","wsId","set","removeWebSocket","delete","closeConnection","getWebSocket","id_socket","get","send","data","_this","has","push","messageId","hasError","timer","setTimeout","flushMessages","combinedData","messages","length","JSON","stringify","Buffer","byteLength","sendMessagesInChunks","error","handleSendError","clearTimeout","chunk","chunkSize","_i","messages_1","message","messageData","messageSize","getSubscriptionManager","getEnableDebug","console","log","Date","unsubscribeAll","close","process","nextTick","OPEN","CLOSING","includes","readyState","terminate","exports"],"mappings":"oGAUA,IAAAA,iBAAA,WAQC,SAAAA,iBAAYC,EAAiCC,EAAgCC,GAAhC,KAAA,IAAAD,IAAAA,EAAA,OAAgC,KAAA,IAAAC,IAAAA,EAAA,IANrEC,KAAAC,gBAAsD,IAAIC,IAC1DF,KAAAG,gBAA+C,IAAID,IAGnDF,KAAAI,YAAsC,IAAIF,IAGjDF,KAAKK,YAAcR,EACnBG,KAAKM,gBAAkBR,EACvBE,KAAKO,cAAgBR,CACtB,CAkID,OAhIQH,iBAAAY,UAAAC,aAAP,SAAoBC,GACnB,IAAMC,EAAOD,EAAc,UAC3BV,KAAKI,YAAYQ,IAAID,EAAMD,CAAE,CAC9B,EAEOd,iBAAAY,UAAAK,gBAAP,SAAuBH,GACtB,IAAMC,EAAOD,EAAc,UAC3BV,KAAKI,YAAYU,OAAOH,CAAI,EAC5BX,KAAKe,gBAAgBL,CAAE,CACxB,EAEOd,iBAAAY,UAAAQ,aAAP,SAAoBC,GACnB,OAAOjB,KAAKI,YAAYc,IAAID,CAAS,CACtC,EAEOrB,iBAAAY,UAAAW,KAAP,SAAYT,EAAeU,GAA3B,IAAAC,EAAArB,KACOW,EAAOD,EAAc,UAEtBV,KAAKC,gBAAgBqB,IAAIX,CAAI,GACjCX,KAAKC,gBAAgBW,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AElCI,EAAGS,KAAKa,KAAKC,UAAUO,CAAK,EAAG,SAACH,GAC3BA,GACHhB,EAAKiB,gBAAgB5B,EAAI2B,CAAK,CAEhC,CAAC,EAEDG,EAAQ,CAACI,GACTH,EAAYK,IAGZN,EAAMjB,KAAKqB,CAAO,EAClBH,GAAaK,E,CAKI,EAAfN,EAAMT,QACTrB,EAAGS,KAAKa,KAAKC,UAAUO,CAAK,EAAG,SAACH,GAC3BA,GACHhB,EAAKiB,gBAAgB5B,EAAI2B,CAAK,CAEhC,CAAC,CAEH,EAEQzC,iBAAAY,UAAA8B,gBAAR,SAAwB5B,EAAe2B,GAElCrC,KAAKK,YAAY0C,uBAAsB,EAAGC,eAAc,GAC3DC,QAAQC,IAAI,IAAIC,KAAQ,mBAAoB,WAAYzC,EAAS,KAAGA,EAAc,UAAG2B,CAAK,EAE3FrC,KAAKK,YAAY0C,uBAAsB,EAAGK,eAAe1C,CAAE,EAC3DV,KAAKa,gBAAgBH,CAAE,CACxB,EAEOd,iBAAAY,UAAAO,gBAAP,SAAuBL,GACtBA,EAAG2C,MAAK,EACR,IAAM1C,EAAOD,EAAc,UAE3BV,KAAKC,gBAAgBa,OAAOH,CAAI,EAC5BX,KAAKG,gBAAgBmB,IAAIX,CAAI,IAChC4B,aAAavC,KAAKG,gBAAgBe,IAAIP,CAAI,CAAC,EAC3CX,KAAKG,gBAAgBW,OAAOH,CAAI,GAG3B2C,QAAQC,SAAS,WACT,CAAC7C,EAAG8C,KAAM9C,EAAG+C,SAASC,SAAchD,EAAGiD,UAAU,GAEjDjD,EAAGkD,UAAS,CAEpB,CAAC,CACR,EACDhE,gBAAA,EAAC,EA9IYiE,QAAAjE,iBAAAA","file":"websocket.manager.js","sourcesContent":["import { WebSocket } from 'ws';\nimport { ResolveIOServer } from '../index';\nimport ResolveIOMainServer from '../server-app';\n\ninterface ServerResponseModel {\n\tmessageId: number;\n\thasError: boolean;\n\tdata: any;\n}\n\nexport class WebSocketManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _messageBuffers: Map<string, ServerResponseModel[]> = new Map();\n\tprivate _batchingTimers: Map<string, NodeJS.Timeout> = new Map();\n\tprivate _maxMessageSize: number;\n\tprivate _messageDelay: number;\n\tprivate _webSockets: Map<string, WebSocket> = new Map();\n\n\tconstructor(mainServer: ResolveIOMainServer, maxMessageSize: number = 20480, messageDelay: number = 25) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._maxMessageSize = maxMessageSize;\n\t\tthis._messageDelay = messageDelay;\n\t}\n\n\tpublic addWebSocket(ws: WebSocket): void {\n\t\tconst wsId = ws['id_socket'];\n\t\tthis._webSockets.set(wsId, ws);\n\t}\n\n\tpublic removeWebSocket(ws: WebSocket): void {\n\t\tconst wsId = ws['id_socket'];\n\t\tthis._webSockets.delete(wsId);\n\t\tthis.closeConnection(ws);\n\t}\n\n\tpublic getWebSocket(id_socket: string): WebSocket | undefined {\n\t\treturn this._webSockets.get(id_socket);\n\t}\n\n\tpublic send(ws: WebSocket, data: ServerResponseModel | string): void {\n\t\tconst wsId = ws['id_socket'];\n\n\t\tif (!this._messageBuffers.has(wsId)) {\n\t\t\tthis._messageBuffers.set(wsId, []);\n\t\t}\n\n\t\tif (typeof data === 'string') {\n\t\t\t// Handle string messages like 'ping' or 'pong'\n\t\t\tthis._messageBuffers.get(wsId).push({ messageId: null, hasError: false, data: data });\n\t\t}\n\t\telse {\n\t\t\tthis._messageBuffers.get(wsId).push(data);\n\t\t}\n\n\t\tif (!this._batchingTimers.has(wsId)) {\n\t\t\t// Set a timer to send the batch after a short delay\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.flushMessages(ws);\n\t\t\t}, this._messageDelay);\n\t\t\tthis._batchingTimers.set(wsId, timer);\n\t\t}\n\t}\n\n\tprivate flushMessages(ws: WebSocket): void {\n\t\tconst wsId = ws['id_socket'];\n\t\tconst messages = this._messageBuffers.get(wsId);\n\n\t\tif (messages && messages.length > 0) {\n\t\t\t// Combine messages into one payload\n\t\t\tconst combinedData = JSON.stringify(messages);\n\t\t\tconst dataSize = Buffer.byteLength(combinedData, 'utf8');\n\n\t\t\tif (dataSize > this._maxMessageSize) {\n\t\t\t\t// Split messages to ensure each does not exceed max size\n\t\t\t\tthis.sendMessagesInChunks(ws, messages);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tws.send(combinedData, (error) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tthis.handleSendError(ws, error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Clear the buffer and timer\n\t\t\tthis._messageBuffers.delete(wsId);\n\t\t\tclearTimeout(this._batchingTimers.get(wsId));\n\t\t\tthis._batchingTimers.delete(wsId);\n\t\t}\n\t}\n\n\tprivate sendMessagesInChunks(ws: WebSocket, messages: ServerResponseModel[]): void {\n\t\tlet chunk: ServerResponseModel[] = [];\n\t\tlet chunkSize = 0;\n\n\t\tfor (const message of messages) {\n\t\t\tconst messageData = JSON.stringify([message]); // Wrap message in array for consistency\n\t\t\tconst messageSize = Buffer.byteLength(messageData, 'utf8');\n\n\t\t\tif (chunkSize + messageSize > this._maxMessageSize) {\n\t\t\t\t// Send current chunk\n\t\t\t\tws.send(JSON.stringify(chunk), (error) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tthis.handleSendError(ws, error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t// Start new chunk\n\t\t\t\tchunk = [message];\n\t\t\t\tchunkSize = messageSize;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tchunk.push(message);\n\t\t\t\tchunkSize += messageSize;\n\t\t\t}\n\t\t}\n\n\t\t// Send any remaining messages\n\t\tif (chunk.length > 0) {\n\t\t\tws.send(JSON.stringify(chunk), (error) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tthis.handleSendError(ws, error);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate handleSendError(ws: WebSocket, error: Error): void {\n\t\t// Handle send error, e.g., unsubscribe, close connection\n\t\tif (this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'WebSocketManager', 'Unsub WS', ws['user'], ws['id_socket'], error);\n\t\t}\n\t\tthis._mainServer.getSubscriptionManager().unsubscribeAll(ws);\n\t\tthis.removeWebSocket(ws);\n\t}\n\n\tpublic closeConnection(ws: WebSocket): void {\n\t\tws.close();\n\t\tconst wsId = ws['id_socket'];\n\t\t// Clean up buffers and timers\n\t\tthis._messageBuffers.delete(wsId);\n\t\tif (this._batchingTimers.has(wsId)) {\n\t\t\tclearTimeout(this._batchingTimers.get(wsId));\n\t\t\tthis._batchingTimers.delete(wsId);\n\t\t}\n \n process.nextTick(() => {\n if ([ws.OPEN, ws.CLOSING].includes(<any>ws.readyState)) {\n // Socket still hangs, hard close\n ws.terminate();\n }\n });\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/websocket.manager.ts"],"names":["WebSocketManager","mainServer","maxMessageSize","messageDelay","this","_messageBuffers","Map","_batchingTimers","_webSockets","_mainServer","_maxMessageSize","_messageDelay","prototype","addWebSocket","ws","wsId","set","removeWebSocket","delete","closeConnection","getWebSocket","id_socket","get","send","data","_this","has","push","messageId","hasError","timer","setTimeout","flushMessages","combinedData","messages","length","JSON","stringify","Buffer","byteLength","sendMessagesInChunks","error","handleSendError","clearTimeout","chunk","chunkSize","messages_1","__values","messages_1_1","next","done","message","value","messageData","messageSize","getSubscriptionManager","getEnableDebug","console","log","Date","unsubscribeAll","close","process","nextTick","OPEN","CLOSING","includes","readyState","terminate","exports"],"mappings":"uVAUAA,kB,uFAAA,WAQC,SAAAA,iBAAYC,EAAiCC,EAAgCC,GAAhC,KAAA,IAAAD,IAAAA,EAAA,OAAgC,KAAA,IAAAC,IAAAA,EAAA,IANrEC,KAAAC,gBAAsD,IAAIC,IAC1DF,KAAAG,gBAA+C,IAAID,IAGnDF,KAAAI,YAAsC,IAAIF,IAGjDF,KAAKK,YAAcR,EACnBG,KAAKM,gBAAkB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,EAAG+C,MAAK,EACR,IAAM9C,EAAOD,EAAc,UAE3BV,KAAKC,gBAAgBa,OAAOH,CAAI,EAC5BX,KAAKG,gBAAgBmB,IAAIX,CAAI,IAChC4B,aAAavC,KAAKG,gBAAgBe,IAAIP,CAAI,CAAC,EAC3CX,KAAKG,gBAAgBW,OAAOH,CAAI,GAG3B+C,QAAQC,SAAS,WACT,CAACjD,EAAGkD,KAAMlD,EAAGmD,SAASC,SAAcpD,EAAGqD,UAAU,GAEjDrD,EAAGsD,UAAS,CAEpB,CAAC,CACR,EACDpE,gBAAA,EAAC,GA9IYqE,QAAArE,iBAAAA","file":"websocket.manager.js","sourcesContent":["import { WebSocket } from 'ws';\nimport { ResolveIOServer } from '../index';\nimport ResolveIOMainServer from '../server-app';\n\ninterface ServerResponseModel {\n\tmessageId: number;\n\thasError: boolean;\n\tdata: any;\n}\n\nexport class WebSocketManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _messageBuffers: Map<string, ServerResponseModel[]> = new Map();\n\tprivate _batchingTimers: Map<string, NodeJS.Timeout> = new Map();\n\tprivate _maxMessageSize: number;\n\tprivate _messageDelay: number;\n\tprivate _webSockets: Map<string, WebSocket> = new Map();\n\n\tconstructor(mainServer: ResolveIOMainServer, maxMessageSize: number = 20480, messageDelay: number = 25) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._maxMessageSize = maxMessageSize;\n\t\tthis._messageDelay = messageDelay;\n\t}\n\n\tpublic addWebSocket(ws: WebSocket): void {\n\t\tconst wsId = ws['id_socket'];\n\t\tthis._webSockets.set(wsId, ws);\n\t}\n\n\tpublic removeWebSocket(ws: WebSocket): void {\n\t\tconst wsId = ws['id_socket'];\n\t\tthis._webSockets.delete(wsId);\n\t\tthis.closeConnection(ws);\n\t}\n\n\tpublic getWebSocket(id_socket: string): WebSocket | undefined {\n\t\treturn this._webSockets.get(id_socket);\n\t}\n\n\tpublic send(ws: WebSocket, data: ServerResponseModel | string): void {\n\t\tconst wsId = ws['id_socket'];\n\n\t\tif (!this._messageBuffers.has(wsId)) {\n\t\t\tthis._messageBuffers.set(wsId, []);\n\t\t}\n\n\t\tif (typeof data === 'string') {\n\t\t\t// Handle string messages like 'ping' or 'pong'\n\t\t\tthis._messageBuffers.get(wsId).push({ messageId: null, hasError: false, data: data });\n\t\t}\n\t\telse {\n\t\t\tthis._messageBuffers.get(wsId).push(data);\n\t\t}\n\n\t\tif (!this._batchingTimers.has(wsId)) {\n\t\t\t// Set a timer to send the batch after a short delay\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.flushMessages(ws);\n\t\t\t}, this._messageDelay);\n\t\t\tthis._batchingTimers.set(wsId, timer);\n\t\t}\n\t}\n\n\tprivate flushMessages(ws: WebSocket): void {\n\t\tconst wsId = ws['id_socket'];\n\t\tconst messages = this._messageBuffers.get(wsId);\n\n\t\tif (messages && messages.length > 0) {\n\t\t\t// Combine messages into one payload\n\t\t\tconst combinedData = JSON.stringify(messages);\n\t\t\tconst dataSize = Buffer.byteLength(combinedData, 'utf8');\n\n\t\t\tif (dataSize > this._maxMessageSize) {\n\t\t\t\t// Split messages to ensure each does not exceed max size\n\t\t\t\tthis.sendMessagesInChunks(ws, messages);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tws.send(combinedData, (error) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tthis.handleSendError(ws, error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Clear the buffer and timer\n\t\t\tthis._messageBuffers.delete(wsId);\n\t\t\tclearTimeout(this._batchingTimers.get(wsId));\n\t\t\tthis._batchingTimers.delete(wsId);\n\t\t}\n\t}\n\n\tprivate sendMessagesInChunks(ws: WebSocket, messages: ServerResponseModel[]): void {\n\t\tlet chunk: ServerResponseModel[] = [];\n\t\tlet chunkSize = 0;\n\n\t\tfor (const message of messages) {\n\t\t\tconst messageData = JSON.stringify([message]); // Wrap message in array for consistency\n\t\t\tconst messageSize = Buffer.byteLength(messageData, 'utf8');\n\n\t\t\tif (chunkSize + messageSize > this._maxMessageSize) {\n\t\t\t\t// Send current chunk\n\t\t\t\tws.send(JSON.stringify(chunk), (error) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tthis.handleSendError(ws, error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t// Start new chunk\n\t\t\t\tchunk = [message];\n\t\t\t\tchunkSize = messageSize;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tchunk.push(message);\n\t\t\t\tchunkSize += messageSize;\n\t\t\t}\n\t\t}\n\n\t\t// Send any remaining messages\n\t\tif (chunk.length > 0) {\n\t\t\tws.send(JSON.stringify(chunk), (error) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tthis.handleSendError(ws, error);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate handleSendError(ws: WebSocket, error: Error): void {\n\t\t// Handle send error, e.g., unsubscribe, close connection\n\t\tif (this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'WebSocketManager', 'Unsub WS', ws['user'], ws['id_socket'], error);\n\t\t}\n\t\tthis._mainServer.getSubscriptionManager().unsubscribeAll(ws);\n\t\tthis.removeWebSocket(ws);\n\t}\n\n\tpublic closeConnection(ws: WebSocket): void {\n\t\tws.close();\n\t\tconst wsId = ws['id_socket'];\n\t\t// Clean up buffers and timers\n\t\tthis._messageBuffers.delete(wsId);\n\t\tif (this._batchingTimers.has(wsId)) {\n\t\t\tclearTimeout(this._batchingTimers.get(wsId));\n\t\t\tthis._batchingTimers.delete(wsId);\n\t\t}\n \n process.nextTick(() => {\n if ([ws.OPEN, ws.CLOSING].includes(<any>ws.readyState)) {\n // Socket still hangs, hard close\n ws.terminate();\n }\n });\n\t}\n}"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.4.12",
3
+ "version": "20.4.14",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",