@resolveio/server-lib 20.7.120 → 20.7.122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/client-server-app.js +51 -1
  2. package/client-server-app.js.map +1 -1
  3. package/collections/app-status.collection.js +51 -1
  4. package/collections/app-status.collection.js.map +1 -1
  5. package/collections/counter.collection.js +55 -1
  6. package/collections/counter.collection.js.map +1 -1
  7. package/collections/cron-job-history.collection.js +136 -1
  8. package/collections/cron-job-history.collection.js.map +1 -1
  9. package/collections/cron-job.collection.js +87 -1
  10. package/collections/cron-job.collection.js.map +1 -1
  11. package/collections/email-history.collection.js +98 -1
  12. package/collections/email-history.collection.js.map +1 -1
  13. package/collections/email-verified.collection.js +60 -1
  14. package/collections/email-verified.collection.js.map +1 -1
  15. package/collections/file.collection.js +73 -1
  16. package/collections/file.collection.js.map +1 -1
  17. package/collections/flag-update.collection.js +56 -1
  18. package/collections/flag-update.collection.js.map +1 -1
  19. package/collections/flag.collection.js +56 -1
  20. package/collections/flag.collection.js.map +1 -1
  21. package/collections/log-method-latency.collection.js +72 -1
  22. package/collections/log-method-latency.collection.js.map +1 -1
  23. package/collections/log-subscription.collection.js +75 -1
  24. package/collections/log-subscription.collection.js.map +1 -1
  25. package/collections/log.collection.js +87 -1
  26. package/collections/log.collection.js.map +1 -1
  27. package/collections/logged-in-users.collection.js +66 -1
  28. package/collections/logged-in-users.collection.js.map +1 -1
  29. package/collections/monitor-cpu.collection.js +64 -1
  30. package/collections/monitor-cpu.collection.js.map +1 -1
  31. package/collections/monitor-function.collection.js +73 -1
  32. package/collections/monitor-function.collection.js.map +1 -1
  33. package/collections/monitor-memory.collection.js +76 -1
  34. package/collections/monitor-memory.collection.js.map +1 -1
  35. package/collections/monitor-mongo.collection.js +70 -1
  36. package/collections/monitor-mongo.collection.js.map +1 -1
  37. package/collections/notification.collection.js +56 -1
  38. package/collections/notification.collection.js.map +1 -1
  39. package/collections/report-builder-dashboard-builder.collection.js +108 -1
  40. package/collections/report-builder-dashboard-builder.collection.js.map +1 -1
  41. package/collections/report-builder-library.collection.js +86 -1
  42. package/collections/report-builder-library.collection.js.map +1 -1
  43. package/collections/report-builder-report.collection.js +148 -1
  44. package/collections/report-builder-report.collection.js.map +1 -1
  45. package/collections/user-group.collection.js +88 -1
  46. package/collections/user-group.collection.js.map +1 -1
  47. package/collections/user-guide.collection.js +56 -1
  48. package/collections/user-guide.collection.js.map +1 -1
  49. package/collections/user.collection.js +265 -1
  50. package/collections/user.collection.js.map +1 -1
  51. package/cron/cron.js +97 -1
  52. package/cron/cron.js.map +1 -1
  53. package/fixtures/cron-jobs.js +95 -1
  54. package/fixtures/cron-jobs.js.map +1 -1
  55. package/fixtures/init.js +78 -1
  56. package/fixtures/init.js.map +1 -1
  57. package/http/auth.js +869 -1
  58. package/http/auth.js.map +1 -1
  59. package/http/health.js +11 -1
  60. package/http/health.js.map +1 -1
  61. package/http/home.js +114 -1
  62. package/http/home.js.map +1 -1
  63. package/index.js +18 -1
  64. package/index.js.map +1 -1
  65. package/managers/cron.manager.js +461 -1
  66. package/managers/cron.manager.js.map +1 -1
  67. package/managers/local-log.manager.js +79 -1
  68. package/managers/local-log.manager.js.map +1 -1
  69. package/managers/method.manager.js +1025 -1
  70. package/managers/method.manager.js.map +1 -1
  71. package/managers/mongo.manager.js +4231 -1
  72. package/managers/mongo.manager.js.map +1 -1
  73. package/managers/monitor.manager.js +534 -1
  74. package/managers/monitor.manager.js.map +1 -1
  75. package/managers/subscription.manager.js +1292 -1
  76. package/managers/subscription.manager.js.map +1 -1
  77. package/managers/websocket.manager.js +165 -1
  78. package/managers/websocket.manager.js.map +1 -1
  79. package/managers/worker-dispatcher.manager.js +335 -1
  80. package/managers/worker-dispatcher.manager.js.map +1 -1
  81. package/managers/worker-server.manager.js +292 -1
  82. package/managers/worker-server.manager.js.map +1 -1
  83. package/methods/accounts.js +302 -1
  84. package/methods/accounts.js.map +1 -1
  85. package/methods/aws.js +748 -1
  86. package/methods/aws.js.map +1 -1
  87. package/methods/collections.js +542 -1
  88. package/methods/collections.js.map +1 -1
  89. package/methods/counters.js +111 -1
  90. package/methods/counters.js.map +1 -1
  91. package/methods/cron-jobs.js +1476 -1
  92. package/methods/cron-jobs.js.map +1 -1
  93. package/methods/flag-updates.js +8 -1
  94. package/methods/flag-updates.js.map +1 -1
  95. package/methods/flags.js +8 -1
  96. package/methods/flags.js.map +1 -1
  97. package/methods/logs.js +417 -1
  98. package/methods/logs.js.map +1 -1
  99. package/methods/monitor.js +543 -1
  100. package/methods/monitor.js.map +1 -1
  101. package/methods/pdf.js +742 -1
  102. package/methods/pdf.js.map +1 -1
  103. package/methods/report-builder.js +840 -1
  104. package/methods/report-builder.js.map +1 -1
  105. package/methods/support.js +232 -1
  106. package/methods/support.js.map +1 -1
  107. package/models/app-status.model.js +3 -1
  108. package/models/app-status.model.js.map +1 -1
  109. package/models/billing-logged-in-users.model.js +3 -1
  110. package/models/billing-logged-in-users.model.js.map +1 -1
  111. package/models/collection-document.model.js +3 -1
  112. package/models/collection-document.model.js.map +1 -1
  113. package/models/counter.model.js +3 -1
  114. package/models/counter.model.js.map +1 -1
  115. package/models/cron-job-history.model.js +3 -1
  116. package/models/cron-job-history.model.js.map +1 -1
  117. package/models/cron-job.model.js +3 -1
  118. package/models/cron-job.model.js.map +1 -1
  119. package/models/dialog.model.js +3 -1
  120. package/models/dialog.model.js.map +1 -1
  121. package/models/email-history.model.js +15 -1
  122. package/models/email-history.model.js.map +1 -1
  123. package/models/email-verified.model.js +3 -1
  124. package/models/email-verified.model.js.map +1 -1
  125. package/models/file.model.js +3 -1
  126. package/models/file.model.js.map +1 -1
  127. package/models/flag-update.model.js +3 -1
  128. package/models/flag-update.model.js.map +1 -1
  129. package/models/flag.model.js +3 -1
  130. package/models/flag.model.js.map +1 -1
  131. package/models/log-method-latency.model.js +3 -1
  132. package/models/log-method-latency.model.js.map +1 -1
  133. package/models/log-subscription.model.js +3 -1
  134. package/models/log-subscription.model.js.map +1 -1
  135. package/models/log.model.js +3 -1
  136. package/models/log.model.js.map +1 -1
  137. package/models/logged-in-users.model.js +3 -1
  138. package/models/logged-in-users.model.js.map +1 -1
  139. package/models/method-response.model.js +3 -1
  140. package/models/method-response.model.js.map +1 -1
  141. package/models/method.model.d.ts +0 -1
  142. package/models/method.model.js +3 -1
  143. package/models/method.model.js.map +1 -1
  144. package/models/monitor-cpu.model.js +3 -1
  145. package/models/monitor-cpu.model.js.map +1 -1
  146. package/models/monitor-function.model.js +3 -1
  147. package/models/monitor-function.model.js.map +1 -1
  148. package/models/monitor-memory.model.js +3 -1
  149. package/models/monitor-memory.model.js.map +1 -1
  150. package/models/monitor-mongo.model.js +3 -1
  151. package/models/monitor-mongo.model.js.map +1 -1
  152. package/models/notification.model.js +3 -1
  153. package/models/notification.model.js.map +1 -1
  154. package/models/pagination.model.js +23 -1
  155. package/models/pagination.model.js.map +1 -1
  156. package/models/permission.model.js +3 -1
  157. package/models/permission.model.js.map +1 -1
  158. package/models/report-builder-dashboard-builder.model.js +3 -1
  159. package/models/report-builder-dashboard-builder.model.js.map +1 -1
  160. package/models/report-builder-library.model.js +3 -1
  161. package/models/report-builder-library.model.js.map +1 -1
  162. package/models/report-builder-report.model.js +3 -1
  163. package/models/report-builder-report.model.js.map +1 -1
  164. package/models/report-builder.model.js +3 -1
  165. package/models/report-builder.model.js.map +1 -1
  166. package/models/select-data-label.model.js +3 -1
  167. package/models/select-data-label.model.js.map +1 -1
  168. package/models/server-message.model.js +3 -1
  169. package/models/server-message.model.js.map +1 -1
  170. package/models/subscription.model.js +3 -1
  171. package/models/subscription.model.js.map +1 -1
  172. package/models/support-ticket.model.js +3 -1
  173. package/models/support-ticket.model.js.map +1 -1
  174. package/models/user-group.model.js +3 -1
  175. package/models/user-group.model.js.map +1 -1
  176. package/models/user-guide.model.js +3 -1
  177. package/models/user-guide.model.js.map +1 -1
  178. package/models/user.model.js +3 -1
  179. package/models/user.model.js.map +1 -1
  180. package/package.json +1 -1
  181. package/public_api.js +77 -1
  182. package/public_api.js.map +1 -1
  183. package/publications/app-status.js +16 -1
  184. package/publications/app-status.js.map +1 -1
  185. package/publications/cron-jobs.js +32 -1
  186. package/publications/cron-jobs.js.map +1 -1
  187. package/publications/files.js +36 -1
  188. package/publications/files.js.map +1 -1
  189. package/publications/flags-update.js +22 -1
  190. package/publications/flags-update.js.map +1 -1
  191. package/publications/flags.js +22 -1
  192. package/publications/flags.js.map +1 -1
  193. package/publications/logs.js +164 -1
  194. package/publications/logs.js.map +1 -1
  195. package/publications/notifications.js +16 -1
  196. package/publications/notifications.js.map +1 -1
  197. package/publications/report-builder-dashboard-builders.js +42 -1
  198. package/publications/report-builder-dashboard-builders.js.map +1 -1
  199. package/publications/report-builder-libraries.js +90 -1
  200. package/publications/report-builder-libraries.js.map +1 -1
  201. package/publications/report-builder-reports.js +50 -1
  202. package/publications/report-builder-reports.js.map +1 -1
  203. package/publications/super-admin.js +16 -1
  204. package/publications/super-admin.js.map +1 -1
  205. package/publications/user-groups.js +16 -1
  206. package/publications/user-groups.js.map +1 -1
  207. package/publications/user-guides.js +16 -1
  208. package/publications/user-guides.js.map +1 -1
  209. package/resolveio-server-app.js +176 -1
  210. package/resolveio-server-app.js.map +1 -1
  211. package/server-app.js +1159 -1
  212. package/server-app.js.map +1 -1
  213. package/util/common.js +632 -1
  214. package/util/common.js.map +1 -1
  215. package/util/schema-report-builder.js +454 -1
  216. package/util/schema-report-builder.js.map +1 -1
@@ -1,2 +1,1293 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,i,s,r){return new(s=s||Promise)(function(n,t){function fulfilled(e){try{step(r.next(e))}catch(e){t(e)}}function rejected(e){try{step(r.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?n(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(fulfilled,rejected)}step((r=r.apply(e,i||[])).next())})},__generator=this&&this.__generator||function(i,s){var r,o,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(n){return function(e){var t=[n,e];if(r)throw new TypeError("Generator is already executing.");for(;c=u&&t[u=0]?0:c;)try{if(r=1,o&&(a=2&t[0]?o.return:t[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,t[1])).done)return a;switch(o=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++,o=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=s.call(i,c)}catch(e){t=[6,e],o=0}finally{r=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&i>=e.length?void 0:e)&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,s,r=n.call(e),o=[];try{for(;(void 0===t||0<t--)&&!(i=r.next()).done;)o.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o},__spreadArray=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var i,s=0,r=t.length;s<r;s++)!i&&s in t||((i=i||Array.prototype.slice.call(t,0,s))[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))},NodeCache=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0,require("node-cache")),os_1=require("os"),flag_collection_1=require("../collections/flag.collection"),logged_in_users_collection_1=require("../collections/logged-in-users.collection"),app_status_1=require("../publications/app-status"),cron_jobs_1=require("../publications/cron-jobs"),files_1=require("../publications/files"),flags_1=require("../publications/flags"),flags_update_1=require("../publications/flags-update"),logs_1=require("../publications/logs"),notifications_1=require("../publications/notifications"),report_builder_dashboard_builders_1=require("../publications/report-builder-dashboard-builders"),report_builder_libraries_1=require("../publications/report-builder-libraries"),report_builder_reports_1=require("../publications/report-builder-reports"),super_admin_1=require("../publications/super-admin"),user_groups_1=require("../publications/user-groups"),user_guides_1=require("../publications/user-guides"),resolveio_server_app_1=require("../resolveio-server-app"),common_1=require("../util/common"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),SubscriptionManager=function(){function SubscriptionManager(){this._publications={},this._subscriptions=[],this._loggedInUsers=[],this._mongoQueue=[],this._mongoQueueId=0,this._cacheId=1,this._heapSize=v8.getHeapStatistics()/numCPUs,this._enableDebug=!1,this._debugOplogCollections=[],this._debugOplogHits=0,this._debugSubCollections=[],this._debugSubHits=0,this._debugUnSubHits=0,this._debugUnSubAllHits=0,this._debugMongoQueueHits=0,this._debugMongoQueueCollections=[],this._debugSendQueueHits=0,this._debugRemoveCacheHits=0,this._oplogRetryCount=0,this.latencyBuffer=new Map,this.LATENCY_UPDATE_INTERVAL=6e4,this.LATENCY_UPDATE_THRESHOLD_MS=3e4,this._invalidationDebounceTimers=new Map,this._invalidationPendingTimestamps=new Map,this.DEBOUNCE_DELAY=100,this.MAX_WAIT_TIME=500}return SubscriptionManager.create=function(t,n,i){var e=this,s=new SubscriptionManager;return setImmediate(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,s.initialize(t,n,i)];case 1:return e.sent(),[2]}})})}),s},SubscriptionManager.prototype.initialize=function(i,s,r){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(e){switch(e.label){case 0:return this._websocketManager=resolveio_server_app_1.ResolveIOServer.getMainServer().getWebSocketManager(),this._monitorManagerFunction=r,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),setInterval(function(){return n.flushThrottledLatencyUpdates()},this.LATENCY_UPDATE_INTERVAL),this.serverConfig=s,this._wss=i,(0,super_admin_1.loadSuperAdminPublications)(this),(0,app_status_1.loadAppStatusPublications)(this),(0,logs_1.loadLogPublications)(this),(0,files_1.loadFilePublications)(this),(0,cron_jobs_1.loadCronJobPublications)(this),(0,flags_update_1.loadFlagsUpdatePublications)(this),(0,flags_1.loadFlagsPublications)(this),(0,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),[4,this.tailOpLog()];case 1:return e.sent(),setInterval(function(){n._oplogRetryCount=0},15e3),setInterval(function(){n.getEnableDebug()&&(console.log(new Date,"Sub Manager","Subs",n._subscriptions.length),console.log(new Date,"Sub Manager","Logged In Users",n._loggedInUsers.length),console.log(new Date,"Sub Manager","Mongo Queue",n._mongoQueue.length),console.log(new Date,"Sub Manager","Mongo Queue Hits",n._debugMongoQueueHits),console.log(new Date,"Sub Manager","Mongo Queue Collections",JSON.stringify(n._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",n._debugOplogHits),console.log(new Date,"Sub Manager","Oplog Collections",JSON.stringify(n._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",n._debugSendQueueHits),console.log(new Date,"Sub Manager","Sub Hits",n._debugSubHits),console.log(new Date,"Sub Manager","Sub Collections",JSON.stringify(n._debugSubCollections.sort(function(e,t){return e.publication.localeCompare(t.publication)}),null,2)),console.log(new Date,"Sub Manager","Unsub Hits",n._debugUnSubHits),console.log(new Date,"Sub Manager","Unsub All Hits",n._debugUnSubAllHits),console.log(new Date,"Sub Manager","Cache Cleanup Hits",n._debugRemoveCacheHits)),n._debugOplogHits=0,n._debugOplogCollections=[],n._debugSubCollections=[],n._debugMongoQueueHits=0,n._debugMongoQueueCollections=[],n._debugSendQueueHits=0,n._debugSubHits=0,n._debugUnSubHits=0,n._debugUnSubAllHits=0,n._debugRemoveCacheHits=0},6e4),setInterval(function(){return __awaiter(n,void 0,void 0,function(){var t,i,n,s,r,o,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:t._loggedInUsers=e.sent(),i=(0,common_1.deepCopy)(this._loggedInUsers),n=function(t){var n;return __generator(this,function(e){switch(e.label){case 0:return!(n=i[t]).date||12e4<Date.now()-n.date.getTime()?s._websocketManager.getWebSocket(n.id_ws)?(s.getEnableDebug()&&console.log(new Date,"Sub Manager","Unsub WS",s._websocketManager.getWebSocket(n.id_ws).user,s._websocketManager.getWebSocket(n.id_ws).id_socket,2),[4,s.unsubscribeAll(s._websocketManager.getWebSocket(n.id_ws))]):[3,2]:[3,4];case 1:return e.sent(),[3,4];case 2:return s._subscriptions.forEach(function(e){for(var t=e.clients.length-1;0<=t;t--)e.clients[t].id_socket===n.id_ws&&e.clients.splice(t,1)}),[4,logged_in_users_collection_1.LoggedInUsers.deleteOne({_id:n._id})];case 3:e.sent(),0<=s._loggedInUsers.findIndex(function(e){return e._id===n._id})&&s._loggedInUsers.splice(s._loggedInUsers.findIndex(function(e){return e._id===n._id}),1),e.label=4;case 4:return[2]}})},r=(s=this)._loggedInUsers.length-1,e.label=2;case 2:return 0<=r?[5,n(r)]:[3,5];case 3:e.sent(),e.label=4;case 4:return r--,[3,2];case 5:for(r=0;r<this._subscriptions.length;r++)for(o=this._subscriptions[r],a=function(e){var t=o.clients[e];c._loggedInUsers.some(function(e){return e.id_ws===t.id_socket})||o.clients.splice(e,1)},c=this,u=o.clients.length-1;0<=u;u--)a(u);return[2]}})})},3e4),[4,flag_collection_1.Flags.findOne({type:"Enable Debug"})];case 2:return(t=e.sent())&&t.value?this._enableDebug=!0:this._enableDebug=!1,this.setCacheLimit(),[2]}})})},SubscriptionManager.prototype.setCacheLimit=function(){"true"===process.env.IS_WORKERS_ENABLED?this._heapLimit=.4*this._heapSize:this._heapLimit=.3*this._heapSize},SubscriptionManager.prototype.invalidatePubsCache=function(r,o){return __awaiter(this,void 0,void 0,function(){var t,n,i,s=this;return __generator(this,function(e){switch(e.label){case 0:return(t=r,n=Date.now(),i=this._invalidationPendingTimestamps.get(t)||n,this._invalidationPendingTimestamps.set(t,i),this._invalidationDebounceTimers.has(t)&&clearTimeout(this._invalidationDebounceTimers.get(t)),n-i>=this.MAX_WAIT_TIME)?(this._invalidationPendingTimestamps.delete(t),[4,this._executeInvalidation(r,o)]):[3,2];case 1:return e.sent(),[3,3];case 2:this._invalidationDebounceTimers.set(t,setTimeout(function(){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._invalidationPendingTimestamps.delete(t),[4,this._executeInvalidation(r,o)];case 1:return e.sent(),[2]}})})},this.DEBOUNCE_DELAY)),e.label=3;case 3:return[2]}})})},SubscriptionManager.prototype._executeInvalidation=function(h,b){return __awaiter(this,void 0,void 0,function(){var t,n,i,s,r,o,a,c,u,l,_,g,d;return __generator(this,function(e){switch(e.label){case 0:this._invalidationDebounceTimers.has(h)&&(clearTimeout(this._invalidationDebounceTimers.get(h)),this._invalidationDebounceTimers.delete(h)),resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(h),t=this._subscriptions.filter(function(e){return e.collections.includes(h)}),e.label=1;case 1:e.trys.push([1,17,18,19]),n=__values(t),i=n.next(),e.label=2;case 2:if(i.done)return[3,16];if(s=i.value,this._enableDebug&&console.log(new Date,"Invalidate Sub",s.publication,s.running,s.runAgain),s.running)return s.runAgain=!0,[3,15];if(!this._publications[s.publication].user_specific)return[3,13];e.label=3;case 3:e.trys.push([3,10,11,12]),g=void 0,r=__values(s.clients),o=r.next(),e.label=4;case 4:if(o.done)return[3,9];if(a=o.value,(null==(c=this._websocketManager.getWebSocket(a.id_socket))?void 0:c.readyState)!==c.OPEN)return[3,8];e.label=5;case 5:return e.trys.push([5,7,,8]),[4,this.sendDataToOneWithRetry(c,a.messageId,s,h,b)];case 6:return e.sent(),[3,8];case 7:return e.sent(),[3,8];case 8:return o=r.next(),[3,4];case 9:return[3,12];case 10:return u=e.sent(),g={error:u},[3,12];case 11:try{o&&!o.done&&(d=r.return)&&d.call(r)}finally{if(g)throw g.error}return[7];case 12:return[3,15];case 13:return[4,this.sendDataToAllWithRetry(s,h,b)];case 14:e.sent(),e.label=15;case 15:return i=n.next(),[3,2];case 16:return[3,19];case 17:return u=e.sent(),l={error:u},[3,19];case 18:try{i&&!i.done&&(_=n.return)&&_.call(n)}finally{if(l)throw l.error}return[7];case 19:return[2]}})})},SubscriptionManager.prototype.delay=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){return setTimeout(e,t)})]})})},SubscriptionManager.prototype.sendDataToAllWithRetry=function(t,n,i){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:t.running=!0,e.label=1;case 1:return this._enableDebug&&console.log(new Date,"Running sendDataToAll Sub",t.publication),t.runAgain=!1,[4,this.sendDataToAll(t,n,i)];case 2:return(e.sent(),this._enableDebug&&console.log(new Date,"Done sendDataToAll Sub",t.publication,t.runAgain),t.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(t.runAgain)return[3,1];e.label=5;case 5:return t.running=!1,[2]}})})},SubscriptionManager.prototype.sendDataToOneWithRetry=function(t,n,i,s,r){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:i.running=!0,e.label=1;case 1:return this._enableDebug&&console.log(new Date,"Running sendDataToOne Sub",i.publication),i.runAgain=!1,[4,this.sendDataToOne(t,n,i,s,r)];case 2:return(e.sent(),this._enableDebug&&console.log(new Date,"Done sendDataToOne Sub",i.publication,i.runAgain),i.runAgain)?[4,this.delay(500)]:[3,4];case 3:e.sent(),e.label=4;case 4:if(i.runAgain)return[3,1];e.label=5;case 5:return i.running=!1,[2]}})})},SubscriptionManager.prototype.publications=function(e){this._publications=Object.assign(this._publications,e)},SubscriptionManager.prototype.loggedInLatency=function(t){var e,n,i,s=this._loggedInUsers.find(function(e){return e.id_ws===t.id_socket});s&&(e=new Date,n=this.latencyBuffer.get(t.id_socket),i=t.latency,!n||e.getTime()-n.lastUpdate.getTime()>=this.LATENCY_UPDATE_THRESHOLD_MS||100<Math.abs(i-n.latency))&&(s.date=e,this.latencyBuffer.set(t.id_socket,{latency:i,lastUpdate:e}))},SubscriptionManager.prototype.flushThrottledLatencyUpdates=function(){return __awaiter(this,void 0,void 0,function(){var t,n;return __generator(this,function(e){switch(e.label){case 0:if(0===this.latencyBuffer.size)return[2];t=Array.from(this.latencyBuffer.entries()).map(function(e){var e=__read(e,2),t=e[0],e=e[1];return{updateOne:{filter:{id_ws:t},update:{$set:{latency:e.latency,date:e.lastUpdate}}}}}),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,logged_in_users_collection_1.LoggedInUsers.bulkWrite(t)];case 2:return e.sent(),this.latencyBuffer.clear(),this.getEnableDebug()&&console.log(new Date,"Sub Manager","Throttled latency batch update successful",t.length),[3,4];case 3:return n=e.sent(),console.error(new Date,"Sub Manager","Throttled latency batch update failed",n),[3,4];case 4:return[2]}})})},SubscriptionManager.prototype.subscribe=function(u,e,l,_,g,d){return __awaiter(this,void 0,void 0,function(){var t,n,i,s,r,o,a,c=this;return __generator(this,function(e){switch(e.label){case 0:return(this._debugSubHits+=1,this._debugSubCollections.some(function(e){return e.publication===g})?this._debugSubCollections.find(function(e){return e.publication===g}).hits+=1:this._debugSubCollections.push({publication:g,hits:1}),t=this._publications[g])?[3,1]:(console.error(new Date,"No Publication: "+g),[2]);case 1:if(1<d.length||d[0]){if(!t.check)return console.error(new Date,"No Check Function For Pub "+g),[2];if(!t.check._schema)return console.error(new Date,"No Check Schema For Pub "+g),[2];for(n={},r=Object.keys(t.check._schema),i=r.filter(function(e){return!e.includes(".")}),s=0;s<d.length;s++)n[i[s]]=d[s];try{t.check.validate(n)}catch(e){if(e)return console.error(new Date,"Error in Pub Check ("+g+")",e),[2]}}return"Bypass"!==u&&(r=u.split("/"),o="",a=r[0],""===r[0]&&(o="/",a=r[1]),o+=a,1<r.length&&(o+="/"),(a=this._subscriptions.filter(function(e){return e.clients.some(function(e){return e.id_socket===l.id_socket&&"Bypass"!==e.messageRoute&&"/"!==e.messageRoute&&e.messageRoute!==u&&!e.messageRoute.startsWith(o)})})).length)&&a.forEach(function(t){t.clients.filter(function(e){return e.id_socket===l.id_socket}).forEach(function(e){c.unsubscribe(e.messageRoute,new Date,l,e.messageId,t.publication,t.subscriptionData)})}),(a=this._subscriptions.find(function(e){return e.publication===g&&JSON.stringify(e.subscriptionData)===JSON.stringify(d)}))?a.clients.some(function(e){return e.id_socket===l.id_socket&&e.messageId===_})||a.clients.push({id_user:l.id_user,messageId:_,id_socket:l.id_socket,messageRoute:u}):this._subscriptions.push({publication:g,subscriptionData:d,collections:this.getPublicationCollections(g),clients:[{id_user:l.id_user,messageId:_,id_socket:l.id_socket,messageRoute:u}],cacheId:0,running:!1,runAgain:!1}),a=a||this._subscriptions.find(function(e){return e.publication===g&&JSON.stringify(e.subscriptionData)===JSON.stringify(d)}),this._enableDebug&&console.log(new Date,"New Sub",a.publication,a.running,a.runAgain,a.clients.length),[4,this.processSubscription(a,l,_)];case 2:e.sent(),e.label=3;case 3:return[2]}})})},SubscriptionManager.prototype.createLoggedInUser=function(i){return __awaiter(this,void 0,void 0,function(){var t,n;return __generator(this,function(e){switch(e.label){case 0:return(t=this._websocketManager.getWebSocket(i))?(n={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:t.id_user,user:t.user,id_ws:t.id_socket},this._loggedInUsers.push(n),[4,logged_in_users_collection_1.LoggedInUsers.insertOne(n)]):[3,2];case 1:return e.sent(),[2,n];case 2:throw new Error("Error in Create Logged In User: No WS")}})})},SubscriptionManager.prototype.unsubscribe=function(e,t,n,i,s,r){if(this._debugUnSubHits+=1,this._publications[s]){var o=this._subscriptions.find(function(e){return e.publication===s&&JSON.stringify(e.subscriptionData)===JSON.stringify(r)});if(o){for(var a=o.clients.length-1;0<=a;a--)o.clients[a].id_user===n.id_user&&o.clients[a].messageId===i&&o.clients[a].id_socket===n.id_socket&&o.clients.splice(a,1);this._enableDebug&&console.log(new Date,"Unsub",o.publication,o.running,o.runAgain,o.clients.length)}}else console.log("No Publication: "+s)},SubscriptionManager.prototype.unsubscribeAll=function(r){return __awaiter(this,void 0,void 0,function(){var t,n,i,s;return __generator(this,function(e){switch(e.label){case 0:return(this._debugUnSubAllHits+=1,r)?r.isUnsubscribed?[2]:(r.isUnsubscribed=!0,0<=this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(r.id_socket)&&this._loggedInUsers.splice(this._loggedInUsers.map(function(e){return e.id_ws}).indexOf(r.id_socket),1),[4,logged_in_users_collection_1.LoggedInUsers.deleteOne({id_ws:r.id_socket})]):[3,2];case 1:for(e.sent(),t=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=t.length-1;0<=n;n--)for(i=t[n],s=i.clients.length-1;0<=s;s--)i.clients[s].id_socket===r.id_socket&&i.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(i){return __awaiter(this,void 0,void 0,function(){var t,s,n=this;return __generator(this,function(e){switch(e.label){case 0:return!this._oplog$||this._oplog$.closed?[3,2]:(this._oplog$.removeAllListeners(),[4,this._oplog$.close()]);case 1:e.sent(),this._oplog$=null,e.label=2;case 2:return[4,new Promise(function(e){return setTimeout(e,1e3)})];case 3:if(e.sent(),this._oplog$&&!this._oplog$.closed)return[3,12];if(this._oplogRetryCount+=1,5<this._oplogRetryCount&&(console.error("****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************"),process.exit(1)),t=[{$match:{$and:[{"ns.coll":{$nin:["log-method-latencies","log-subscriptions","logs","counters","cron-job-histories","email-histories","qb-soap-request-histories","qb-soap-request-responses","qb-soap-requests","qb-soap-retries"]}},{"ns.coll":{$not:/.*\.versions$/}},{"ns.coll":{$not:/^monitor-/}}]}}],!i)return[3,10];s=i,e.label=4;case 4:return e.trys.push([4,5,,9]),this._oplog$=resolveio_server_app_1.ResolveIOServer.getMainDB().watch(t,{resumeAfter:i}),[3,9];case 5:return(e.sent(),this._oplog$)?(this._oplog$.removeAllListeners(),[4,this._oplog$.close()]):[3,7];case 6:e.sent(),this._oplog$=null,e.label=7;case 7:return[4,this.tailOpLog(i)];case 8:return e.sent(),[2];case 9:return[3,11];case 10:this._oplog$=resolveio_server_app_1.ResolveIOServer.getMainDB().watch(t),e.label=11;case 11:console.log(new Date,"oplog started"),this._oplog$.on("change",function(i){return __awaiter(n,void 0,void 0,function(){var t,n;return __generator(this,function(e){switch(e.label){case 0:return i.ns?(this._enableDebug&&console.log(new Date,"Oplog Hit",i.ns),t=i.ns.coll,this._debugOplogCollections.some(function(e){return e.collection===i.ns.coll&&e.type===i.operationType})?this._debugOplogCollections.find(function(e){return e.collection===i.ns.coll&&e.type===i.operationType}).hits+=1:this._debugOplogCollections.push({collection:i.ns.coll,type:i.operationType,hits:1}),t?(this._debugOplogHits+=1,"insert"!==i.operationType?[3,5]:"support-tickets"!==t||"https://resolveio.com"!==this.serverConfig.ROOT_URL?[3,2]:(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"sendSupportTicketEmail",i.documentKey._id),[4,this.invalidatePubsCache(t,"insert")])):[3,10]):[3,13];case 1:e.sent(),e.label=2;case 2:return"method-responses"===t?[3,4]:[4,this.invalidatePubsCache(t,"insert")];case 3:e.sent(),e.label=4;case 4:return[3,10];case 5:return"update"!==i.operationType&&"replace"!==i.operationType?[3,8]:"method-responses"===t?[3,7]:[4,this.invalidatePubsCache(t,"update")];case 6:e.sent(),e.label=7;case 7:return[3,10];case 8:return"delete"!==i.operationType?[3,10]:"method-responses"===t?[3,10]:[4,this.invalidatePubsCache(t,"delete")];case 9:e.sent(),e.label=10;case 10:return"flags"!==t?[3,12]:[4,flag_collection_1.Flags.findOne({type:"Enable Debug"})];case 11:(n=e.sent())&&n.value?this._enableDebug=!0:this._enableDebug=!1,e.label=12;case 12:s=i._id,process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||"false"!==process.env.IS_WORKERS_ENABLED&&"true"===process.env.IS_WORKER_INSTANCE&&process.env.WORKER_INDEX,e.label=13;case 13:return[2]}})})}),this._oplog$.on("error",function(t){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.log(new Date,"oplog error",t),[4,this._oplog$.close()];case 1:return e.sent(),[2]}})})}),this._oplog$.on("end",function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.log(new Date,"oplog end"),[4,this._oplog$.close()];case 1:return e.sent(),[2]}})})}),this._oplog$.on("close",function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.log(new Date,"oplog close"),this._oplog$.removeAllListeners(),this._oplog$=null,[4,this.tailOpLog(s)];case 1:return e.sent(),[2]}})})}),e.label=12;case 12:return[2]}})})},SubscriptionManager.prototype.processSubscription=function(n,i,s){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:if(this._publications[n.publication].user_specific)return[3,8];if(!n.cacheId)return[3,5];e.label=1;case 1:return e.trys.push([1,2,,4]),t=JSON.parse(this._nodeCache.get(n.cacheId),common_1.dateReviver),t={messageId:s,hasError:!1,data:t},this._enableDebug&&console.log(new Date,"Process Sub, Cache",n.publication),this.sendWS(i,t),[3,4];case 2:return e.sent(),this._nodeCache.del(n.cacheId),n.cacheId=0,[4,this.sendDataToAllWithRetry(n,"","newSub")];case 3:return e.sent(),[3,4];case 4:return[3,7];case 5:return this._enableDebug&&console.log(new Date,"Process Sub, Non - Cache",n.publication,n.running),n.running?[2]:[4,this.sendDataToAllWithRetry(n,"","newSub")];case 6:e.sent(),e.label=7;case 7:return[3,10];case 8:return this._enableDebug&&console.log(new Date,"Process Sub Specific, Non - Cache",n.publication,n.running),n.running?[2]:[4,this.sendDataToOneWithRetry(i,s,n,"","newSub")];case 9:e.sent(),e.label=10;case 10:return[2]}})})},SubscriptionManager.prototype.sendDataToOne=function(r,o,a,c,u){return __awaiter(this,void 0,void 0,function(){var t,n,i,s;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,5,7]),resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"insertSubscriptionLog",u,a.publication,c,JSON.stringify(a.subscriptionData)),[4,(s=this._publications[a.publication].function).call.apply(s,__spreadArray([Object.assign({},this,SubscriptionManager.prototype),r.id_user],__read(a.subscriptionData),!1))];case 2:return s=e.sent(),i={messageId:o,hasError:!1,data:s},this.sendWS(r,i),[3,7];case 3:return n=e.sent(),i={messageId:o,hasError:!0,data:n},this.sendWS(r,i),[4,resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+a.publication+" - (sendDataToOne - WS)\n\nData \n"+JSON.stringify(a.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(n,null,2))];case 4:return e.sent(),[3,7];case 5:return[4,this._monitorManagerFunction.finishMonitorFunction(t)];case 6:return e.sent(),[7];case 7:return[2]}})})},SubscriptionManager.prototype.sendDataToAll=function(O,C,E){return __awaiter(this,void 0,void 0,function(){var t,n,i,s,r,o,a,c,u,l,_,g,d,h,b,p,f,v,S,y,m,w,D,M,I=this;return __generator(this,function(e){switch(e.label){case 0:return O.clients.length?[3,1]:(O.cacheId&&(this._nodeCache.del(O.cacheId),O.cacheId=0),0<=(v=this._subscriptions.findIndex(function(e){return e.publication===O.publication&&JSON.stringify(e.subscriptionData)===JSON.stringify(O.subscriptionData)}))&&this._subscriptions.splice(v,1),[2]);case 1:t=this._monitorManagerFunction.startMonitorFunction("Publication",O.publication,"","",O.subscriptionData),e.label=2;case 2:return e.trys.push([2,4,6,8]),"superadminAPM"!==O.publication&&"loggedInUsers"!==O.publication&&resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(),"insertSubscriptionLog",E,O.publication,C,JSON.stringify(O.subscriptionData)),[4,(v=this._publications[O.publication].function).call.apply(v,__spreadArray([Object.assign({},this,SubscriptionManager.prototype)],__read(O.subscriptionData),!1))];case 3:if(n=e.sent(),O.cacheId)try{if(i=JSON.parse(this._nodeCache.get(O.cacheId),common_1.dateReviver),JSON.stringify(i)!==JSON.stringify(n)){try{for(s=__values(O.clients),r=s.next();!r.done;r=s.next())b=r.value,(p=this._websocketManager.getWebSocket(b.id_socket))&&p.readyState===p.OPEN&&(f={messageId:b.messageId,hasError:!1,data:n},this.sendWS(p,f))}catch(e){S={error:e}}finally{try{r&&!r.done&&(y=s.return)&&y.call(s)}finally{if(S)throw S.error}}this._nodeCache.del(O.cacheId),(0,common_1.getBinarySize)(JSON.stringify(n))<1e6&&!O.collections.includes("logs")&&!O.collections.find(function(e){return e.endsWith(".versions")})&&!O.collections.find(function(e){return e.startsWith("monitor-")})?this._nodeCache.set(O.cacheId,JSON.stringify(n)):O.cacheId=0}}catch(e){O.clients.map(function(e){var t=I._websocketManager.getWebSocket(e.id_socket);t&&t.readyState===t.OPEN&&(e={messageId:e.messageId,hasError:!1,data:n},I.sendWS(t,e))}),this._nodeCache.del(O.cacheId),(0,common_1.getBinarySize)(JSON.stringify(n))<1e6&&!O.collections.includes("logs")&&!O.collections.find(function(e){return e.endsWith(".versions")})&&!O.collections.find(function(e){return e.startsWith("monitor-")})?this._nodeCache.set(O.cacheId,JSON.stringify(n)):O.cacheId=0}else{try{for(o=__values(O.clients),a=o.next();!a.done;a=o.next())b=a.value,(p=this._websocketManager.getWebSocket(b.id_socket))&&p.readyState===p.OPEN&&(f={messageId:b.messageId,hasError:!1,data:n},this.sendWS(p,f))}catch(e){m={error:e}}finally{try{a&&!a.done&&(w=o.return)&&w.call(o)}finally{if(m)throw m.error}}if((0,common_1.getBinarySize)(JSON.stringify(n))<1e6&&!O.collections.includes("logs")&&!O.collections.find(function(e){return e.endsWith(".versions")})&&!O.collections.find(function(e){return e.startsWith("monitor-")})){if(O.cacheId=this._cacheId++,this._nodeCache.set(O.cacheId,JSON.stringify(n)),(c=this._nodeCache.getStats().vsize)>this._heapLimit){for(u=0,l=this._subscriptions.filter(function(e){return e.cacheId&&!e.clients.length}),_=0;_<l.length&&(this._debugRemoveCacheHits+=1,this._nodeCache.del(l[_].cacheId),l[_].cacheId=0,u+=1,!(this._nodeCache.getStats().vsize<.75*this._heapLimit));_++);this._enableDebug&&console.log("Sub Cache: Too Big - "+O.publication+" - Deleted: "+u+" - "+c)}}else O.cacheId=0}return[3,8];case 4:g=e.sent();try{for(d=__values(O.clients),h=d.next();!h.done;h=d.next())b=h.value,(p=this._websocketManager.getWebSocket(b.id_socket))&&p.readyState===p.OPEN&&(f={messageId:b.messageId,hasError:!0,data:g},this.sendWS(p,f))}catch(e){D={error:e}}finally{try{h&&!h.done&&(M=d.return)&&M.call(d)}finally{if(D)throw D.error}}return[4,resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Error Detected During Subscription "+O.publication+" - (sendPubData)\n\nData \n"+JSON.stringify(O.subscriptionData,null,2)+"\n\nErrors\n"+JSON.stringify(g,null,2))];case 5:return e.sent(),[3,8];case 6:return[4,this._monitorManagerFunction.finishMonitorFunction(t)];case 7:return e.sent(),[7];case 8: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";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __values = (this && this.__values) || function(o) {
39
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
+ if (m) return m.call(o);
41
+ if (o && typeof o.length === "number") return {
42
+ next: function () {
43
+ if (o && i >= o.length) o = void 0;
44
+ return { value: o && o[i++], done: !o };
45
+ }
46
+ };
47
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
+ };
49
+ var __read = (this && this.__read) || function (o, n) {
50
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
51
+ if (!m) return o;
52
+ var i = m.call(o), r, ar = [], e;
53
+ try {
54
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
+ }
56
+ catch (error) { e = { error: error }; }
57
+ finally {
58
+ try {
59
+ if (r && !r.done && (m = i["return"])) m.call(i);
60
+ }
61
+ finally { if (e) throw e.error; }
62
+ }
63
+ return ar;
64
+ };
65
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
66
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
67
+ if (ar || !(i in from)) {
68
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
69
+ ar[i] = from[i];
70
+ }
71
+ }
72
+ return to.concat(ar || Array.prototype.slice.call(from));
73
+ };
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.SubscriptionManager = void 0;
76
+ var NodeCache = require("node-cache");
77
+ var os_1 = require("os");
78
+ var flag_collection_1 = require("../collections/flag.collection");
79
+ var logged_in_users_collection_1 = require("../collections/logged-in-users.collection");
80
+ var app_status_1 = require("../publications/app-status");
81
+ var cron_jobs_1 = require("../publications/cron-jobs");
82
+ var files_1 = require("../publications/files");
83
+ var flags_1 = require("../publications/flags");
84
+ var flags_update_1 = require("../publications/flags-update");
85
+ var logs_1 = require("../publications/logs");
86
+ var notifications_1 = require("../publications/notifications");
87
+ var report_builder_dashboard_builders_1 = require("../publications/report-builder-dashboard-builders");
88
+ var report_builder_libraries_1 = require("../publications/report-builder-libraries");
89
+ var report_builder_reports_1 = require("../publications/report-builder-reports");
90
+ var super_admin_1 = require("../publications/super-admin");
91
+ var user_groups_1 = require("../publications/user-groups");
92
+ var user_guides_1 = require("../publications/user-guides");
93
+ var resolveio_server_app_1 = require("../resolveio-server-app");
94
+ var common_1 = require("../util/common");
95
+ var numCPUs = (0, os_1.cpus)().length;
96
+ var v8 = require('v8');
97
+ // interface CurrentPerformanceMonitor {
98
+ // _id: number;
99
+ // function: string;
100
+ // publication: string;
101
+ // subscriptionData: any[];
102
+ // date_start: Date;
103
+ // date_end: Date;
104
+ // duration: number;
105
+ // result: string;
106
+ // }
107
+ var SubscriptionManager = /** @class */ (function () {
108
+ function SubscriptionManager() {
109
+ this._publications = {};
110
+ this._subscriptions = [];
111
+ this._loggedInUsers = [];
112
+ this._mongoQueue = [];
113
+ this._mongoQueueId = 0;
114
+ this._cacheId = 1;
115
+ this._heapSize = v8.getHeapStatistics() / numCPUs;
116
+ this._enableDebug = false;
117
+ this._debugOplogCollections = [];
118
+ this._debugOplogHits = 0;
119
+ this._debugSubCollections = [];
120
+ this._debugSubHits = 0;
121
+ this._debugUnSubHits = 0;
122
+ this._debugUnSubAllHits = 0;
123
+ this._debugMongoQueueHits = 0;
124
+ this._debugMongoQueueCollections = [];
125
+ this._debugSendQueueHits = 0;
126
+ this._debugRemoveCacheHits = 0;
127
+ this._oplogRetryCount = 0;
128
+ // Buffer to store throttled latency updates with timestamps
129
+ this.latencyBuffer = new Map();
130
+ // Interval to flush latency updates in MongoDB
131
+ this.LATENCY_UPDATE_INTERVAL = 60000;
132
+ // Minimum time difference between two latency updates for the same user
133
+ this.LATENCY_UPDATE_THRESHOLD_MS = 30000;
134
+ // private currentPerfomanceMonitor: CurrentPerformanceMonitor[] = [];
135
+ // private idPerformance: number = 0;
136
+ // private performanceThread;
137
+ this._invalidationDebounceTimers = new Map();
138
+ this._invalidationPendingTimestamps = new Map();
139
+ this.DEBOUNCE_DELAY = 100; // 100ms debounce window
140
+ this.MAX_WAIT_TIME = 500; // 500ms maximum delay
141
+ }
142
+ SubscriptionManager.create = function (wss, serverConfig, monitorManagerFunction) {
143
+ var _this = this;
144
+ var subscriptionManager = new SubscriptionManager();
145
+ setImmediate(function () { return __awaiter(_this, void 0, void 0, function () {
146
+ return __generator(this, function (_a) {
147
+ switch (_a.label) {
148
+ case 0: return [4 /*yield*/, subscriptionManager.initialize(wss, serverConfig, monitorManagerFunction)];
149
+ case 1:
150
+ _a.sent();
151
+ return [2 /*return*/];
152
+ }
153
+ });
154
+ }); });
155
+ return subscriptionManager;
156
+ };
157
+ SubscriptionManager.prototype.initialize = function (wss, serverConfig, monitorManagerFunction) {
158
+ return __awaiter(this, void 0, void 0, function () {
159
+ var flag;
160
+ var _this = this;
161
+ return __generator(this, function (_a) {
162
+ switch (_a.label) {
163
+ case 0:
164
+ this._websocketManager = resolveio_server_app_1.ResolveIOServer.getMainServer().getWebSocketManager();
165
+ this._monitorManagerFunction = monitorManagerFunction;
166
+ this._nodeCache = new NodeCache({ stdTTL: 0, checkperiod: 0 });
167
+ setInterval(function () { return _this.flushThrottledLatencyUpdates(); }, this.LATENCY_UPDATE_INTERVAL);
168
+ // setTimeout(() => {
169
+ // console.log('Setting up performance thread');
170
+ // this.performanceThread = new Worker(path.join(__dirname, './subscription.performance.js'));
171
+ // this.performanceThread.on('exit', code => {
172
+ // console.error(new Date(), 'THREAD EXITED!!!!!!!!!!!!!!!!!!', code);
173
+ // });
174
+ // this.performanceThread.on('error', code => {
175
+ // console.error(new Date(), 'THREAD RECV ERROR !!!!!!!!!!!!!!!!!!', code);
176
+ // });
177
+ // }, 5000);
178
+ // setInterval(() => {
179
+ // console.log('Post thread msg');
180
+ // this.performanceThread.postMessage(this.currentPerfomanceMonitor);
181
+ // this.currentPerfomanceMonitor = [];
182
+ // }, 10000);
183
+ this.serverConfig = serverConfig;
184
+ this._wss = wss;
185
+ // Publications
186
+ (0, super_admin_1.loadSuperAdminPublications)(this);
187
+ (0, app_status_1.loadAppStatusPublications)(this);
188
+ (0, logs_1.loadLogPublications)(this);
189
+ (0, files_1.loadFilePublications)(this);
190
+ (0, cron_jobs_1.loadCronJobPublications)(this);
191
+ (0, flags_update_1.loadFlagsUpdatePublications)(this);
192
+ (0, flags_1.loadFlagsPublications)(this);
193
+ (0, notifications_1.loadNotificationPublications)(this);
194
+ (0, report_builder_reports_1.loadReportBuilderReportPublications)(this);
195
+ (0, report_builder_libraries_1.loadReportBuilderLibraryPublications)(this);
196
+ (0, user_groups_1.loadUserGroupPublications)(this);
197
+ (0, user_guides_1.loadUserGuidePublications)(this);
198
+ (0, report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this);
199
+ return [4 /*yield*/, this.tailOpLog()];
200
+ case 1:
201
+ _a.sent();
202
+ setInterval(function () {
203
+ _this._oplogRetryCount = 0;
204
+ }, 15000);
205
+ setInterval(function () {
206
+ if (_this.getEnableDebug()) {
207
+ console.log(new Date(), 'Sub Manager', 'Subs', _this._subscriptions.length);
208
+ console.log(new Date(), 'Sub Manager', 'Logged In Users', _this._loggedInUsers.length);
209
+ console.log(new Date(), 'Sub Manager', 'Mongo Queue', _this._mongoQueue.length);
210
+ console.log(new Date(), 'Sub Manager', 'Mongo Queue Hits', _this._debugMongoQueueHits);
211
+ console.log(new Date(), 'Sub Manager', 'Mongo Queue Collections', JSON.stringify(_this._debugMongoQueueCollections.sort(function (a, b) { return a.collection.localeCompare(b.collection) || a.publication.localeCompare(b.publication); }), null, 2));
212
+ console.log(new Date(), 'Sub Manager', 'Oplog Hits', _this._debugOplogHits);
213
+ console.log(new Date(), 'Sub Manager', 'Oplog Collections', JSON.stringify(_this._debugOplogCollections.sort(function (a, b) { return a.collection.localeCompare(b.collection) || a.type.localeCompare(b.type); }), null, 2));
214
+ console.log(new Date(), 'Sub Manager', 'Send Queue Hits', _this._debugSendQueueHits);
215
+ console.log(new Date(), 'Sub Manager', 'Sub Hits', _this._debugSubHits);
216
+ console.log(new Date(), 'Sub Manager', 'Sub Collections', JSON.stringify(_this._debugSubCollections.sort(function (a, b) { return a.publication.localeCompare(b.publication); }), null, 2));
217
+ console.log(new Date(), 'Sub Manager', 'Unsub Hits', _this._debugUnSubHits);
218
+ console.log(new Date(), 'Sub Manager', 'Unsub All Hits', _this._debugUnSubAllHits);
219
+ console.log(new Date(), 'Sub Manager', 'Cache Cleanup Hits', _this._debugRemoveCacheHits);
220
+ }
221
+ _this._debugOplogHits = 0;
222
+ _this._debugOplogCollections = [];
223
+ _this._debugSubCollections = [];
224
+ _this._debugMongoQueueHits = 0;
225
+ _this._debugMongoQueueCollections = [];
226
+ _this._debugSendQueueHits = 0;
227
+ _this._debugSubHits = 0;
228
+ _this._debugUnSubHits = 0;
229
+ _this._debugUnSubAllHits = 0;
230
+ _this._debugRemoveCacheHits = 0;
231
+ }, 60000);
232
+ setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
233
+ var _a, userCopy, _loop_1, this_1, i, i, sub, _loop_2, this_2, j;
234
+ return __generator(this, function (_b) {
235
+ switch (_b.label) {
236
+ case 0:
237
+ _a = this;
238
+ return [4 /*yield*/, logged_in_users_collection_1.LoggedInUsers.find()];
239
+ case 1:
240
+ _a._loggedInUsers = _b.sent();
241
+ userCopy = (0, common_1.deepCopy)(this._loggedInUsers);
242
+ _loop_1 = function (i) {
243
+ var loggedInUser;
244
+ return __generator(this, function (_c) {
245
+ switch (_c.label) {
246
+ case 0:
247
+ loggedInUser = userCopy[i];
248
+ if (!(!loggedInUser.date || Date.now() - loggedInUser.date.getTime() > 120000)) return [3 /*break*/, 4];
249
+ if (!this_1._websocketManager.getWebSocket(loggedInUser.id_ws)) return [3 /*break*/, 2];
250
+ if (this_1.getEnableDebug()) {
251
+ console.log(new Date(), 'Sub Manager', 'Unsub WS', this_1._websocketManager.getWebSocket(loggedInUser.id_ws)['user'], this_1._websocketManager.getWebSocket(loggedInUser.id_ws)['id_socket'], 2);
252
+ }
253
+ return [4 /*yield*/, this_1.unsubscribeAll(this_1._websocketManager.getWebSocket(loggedInUser.id_ws))];
254
+ case 1:
255
+ _c.sent();
256
+ return [3 /*break*/, 4];
257
+ case 2:
258
+ this_1._subscriptions.forEach(function (sub) {
259
+ for (var j = sub.clients.length - 1; j >= 0; j--) {
260
+ var client = sub.clients[j];
261
+ if (client.id_socket === loggedInUser.id_ws) {
262
+ sub.clients.splice(j, 1);
263
+ }
264
+ }
265
+ });
266
+ return [4 /*yield*/, logged_in_users_collection_1.LoggedInUsers.deleteOne({ _id: loggedInUser._id })];
267
+ case 3:
268
+ _c.sent();
269
+ if (this_1._loggedInUsers.findIndex(function (a) { return a._id === loggedInUser._id; }) >= 0) {
270
+ this_1._loggedInUsers.splice(this_1._loggedInUsers.findIndex(function (a) { return a._id === loggedInUser._id; }), 1);
271
+ }
272
+ _c.label = 4;
273
+ case 4: return [2 /*return*/];
274
+ }
275
+ });
276
+ };
277
+ this_1 = this;
278
+ i = this._loggedInUsers.length - 1;
279
+ _b.label = 2;
280
+ case 2:
281
+ if (!(i >= 0)) return [3 /*break*/, 5];
282
+ return [5 /*yield**/, _loop_1(i)];
283
+ case 3:
284
+ _b.sent();
285
+ _b.label = 4;
286
+ case 4:
287
+ i--;
288
+ return [3 /*break*/, 2];
289
+ case 5:
290
+ for (i = 0; i < this._subscriptions.length; i++) {
291
+ sub = this._subscriptions[i];
292
+ _loop_2 = function (j) {
293
+ var client = sub.clients[j];
294
+ if (!this_2._loggedInUsers.some(function (a) { return a.id_ws === client.id_socket; })) {
295
+ sub.clients.splice(j, 1);
296
+ }
297
+ };
298
+ this_2 = this;
299
+ for (j = sub.clients.length - 1; j >= 0; j--) {
300
+ _loop_2(j);
301
+ }
302
+ }
303
+ return [2 /*return*/];
304
+ }
305
+ });
306
+ }); }, 30000);
307
+ return [4 /*yield*/, flag_collection_1.Flags.findOne({ type: 'Enable Debug' })];
308
+ case 2:
309
+ flag = _a.sent();
310
+ if (flag && flag.value) {
311
+ this._enableDebug = true;
312
+ }
313
+ else {
314
+ this._enableDebug = false;
315
+ }
316
+ this.setCacheLimit();
317
+ return [2 /*return*/];
318
+ }
319
+ });
320
+ });
321
+ };
322
+ SubscriptionManager.prototype.setCacheLimit = function () {
323
+ if (process.env.IS_WORKERS_ENABLED === 'true') {
324
+ this._heapLimit = this._heapSize * 0.4;
325
+ }
326
+ else {
327
+ this._heapLimit = this._heapSize * 0.3; // Use 50% of total heap size
328
+ }
329
+ };
330
+ SubscriptionManager.prototype.invalidatePubsCache = function (collection, type) {
331
+ return __awaiter(this, void 0, void 0, function () {
332
+ var debounceKey, now, firstInvalidationTime, waitedTooLong;
333
+ var _this = this;
334
+ return __generator(this, function (_a) {
335
+ switch (_a.label) {
336
+ case 0:
337
+ debounceKey = collection;
338
+ now = Date.now();
339
+ firstInvalidationTime = this._invalidationPendingTimestamps.get(debounceKey) || now;
340
+ this._invalidationPendingTimestamps.set(debounceKey, firstInvalidationTime);
341
+ // Clear any existing timer
342
+ if (this._invalidationDebounceTimers.has(debounceKey)) {
343
+ clearTimeout(this._invalidationDebounceTimers.get(debounceKey));
344
+ }
345
+ waitedTooLong = (now - firstInvalidationTime) >= this.MAX_WAIT_TIME;
346
+ if (!waitedTooLong) return [3 /*break*/, 2];
347
+ // Immediate execution path
348
+ this._invalidationPendingTimestamps.delete(debounceKey);
349
+ return [4 /*yield*/, this._executeInvalidation(collection, type)];
350
+ case 1:
351
+ _a.sent();
352
+ return [3 /*break*/, 3];
353
+ case 2:
354
+ // Normal debounce path
355
+ this._invalidationDebounceTimers.set(debounceKey, setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
356
+ return __generator(this, function (_a) {
357
+ switch (_a.label) {
358
+ case 0:
359
+ this._invalidationPendingTimestamps.delete(debounceKey);
360
+ return [4 /*yield*/, this._executeInvalidation(collection, type)];
361
+ case 1:
362
+ _a.sent();
363
+ return [2 /*return*/];
364
+ }
365
+ });
366
+ }); }, this.DEBOUNCE_DELAY));
367
+ _a.label = 3;
368
+ case 3: return [2 /*return*/];
369
+ }
370
+ });
371
+ });
372
+ };
373
+ SubscriptionManager.prototype._executeInvalidation = function (collection, type) {
374
+ return __awaiter(this, void 0, void 0, function () {
375
+ var collSubs, collSubs_1, collSubs_1_1, sub, _a, _b, client, ws, _c, e_1_1, e_2_1;
376
+ var e_2, _d, e_1, _e;
377
+ return __generator(this, function (_f) {
378
+ switch (_f.label) {
379
+ case 0:
380
+ // Clean up any existing timer (defensive)
381
+ if (this._invalidationDebounceTimers.has(collection)) {
382
+ clearTimeout(this._invalidationDebounceTimers.get(collection));
383
+ this._invalidationDebounceTimers.delete(collection);
384
+ }
385
+ // Original invalidation logic
386
+ resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(collection);
387
+ collSubs = this._subscriptions.filter(function (a) { return a.collections.includes(collection); });
388
+ _f.label = 1;
389
+ case 1:
390
+ _f.trys.push([1, 17, 18, 19]);
391
+ collSubs_1 = __values(collSubs), collSubs_1_1 = collSubs_1.next();
392
+ _f.label = 2;
393
+ case 2:
394
+ if (!!collSubs_1_1.done) return [3 /*break*/, 16];
395
+ sub = collSubs_1_1.value;
396
+ if (this._enableDebug) {
397
+ console.log(new Date(), 'Invalidate Sub', sub.publication, sub.running, sub.runAgain);
398
+ }
399
+ if (sub.running) {
400
+ sub.runAgain = true;
401
+ return [3 /*break*/, 15];
402
+ }
403
+ if (!this._publications[sub.publication].user_specific) return [3 /*break*/, 13];
404
+ _f.label = 3;
405
+ case 3:
406
+ _f.trys.push([3, 10, 11, 12]);
407
+ _a = (e_1 = void 0, __values(sub.clients)), _b = _a.next();
408
+ _f.label = 4;
409
+ case 4:
410
+ if (!!_b.done) return [3 /*break*/, 9];
411
+ client = _b.value;
412
+ ws = this._websocketManager.getWebSocket(client.id_socket);
413
+ if (!((ws === null || ws === void 0 ? void 0 : ws.readyState) === ws.OPEN)) return [3 /*break*/, 8];
414
+ _f.label = 5;
415
+ case 5:
416
+ _f.trys.push([5, 7, , 8]);
417
+ return [4 /*yield*/, this.sendDataToOneWithRetry(ws, client.messageId, sub, collection, type)];
418
+ case 6:
419
+ _f.sent();
420
+ return [3 /*break*/, 8];
421
+ case 7:
422
+ _c = _f.sent();
423
+ return [3 /*break*/, 8];
424
+ case 8:
425
+ _b = _a.next();
426
+ return [3 /*break*/, 4];
427
+ case 9: return [3 /*break*/, 12];
428
+ case 10:
429
+ e_1_1 = _f.sent();
430
+ e_1 = { error: e_1_1 };
431
+ return [3 /*break*/, 12];
432
+ case 11:
433
+ try {
434
+ if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
435
+ }
436
+ finally { if (e_1) throw e_1.error; }
437
+ return [7 /*endfinally*/];
438
+ case 12: return [3 /*break*/, 15];
439
+ case 13: return [4 /*yield*/, this.sendDataToAllWithRetry(sub, collection, type)];
440
+ case 14:
441
+ _f.sent();
442
+ _f.label = 15;
443
+ case 15:
444
+ collSubs_1_1 = collSubs_1.next();
445
+ return [3 /*break*/, 2];
446
+ case 16: return [3 /*break*/, 19];
447
+ case 17:
448
+ e_2_1 = _f.sent();
449
+ e_2 = { error: e_2_1 };
450
+ return [3 /*break*/, 19];
451
+ case 18:
452
+ try {
453
+ if (collSubs_1_1 && !collSubs_1_1.done && (_d = collSubs_1.return)) _d.call(collSubs_1);
454
+ }
455
+ finally { if (e_2) throw e_2.error; }
456
+ return [7 /*endfinally*/];
457
+ case 19: return [2 /*return*/];
458
+ }
459
+ });
460
+ });
461
+ };
462
+ SubscriptionManager.prototype.delay = function (ms) {
463
+ return __awaiter(this, void 0, void 0, function () {
464
+ return __generator(this, function (_a) {
465
+ // eslint-disable-next-line no-restricted-syntax
466
+ return [2 /*return*/, new Promise(function (resolve) { return setTimeout(resolve, ms); })];
467
+ });
468
+ });
469
+ };
470
+ SubscriptionManager.prototype.sendDataToAllWithRetry = function (sub, collection, type) {
471
+ return __awaiter(this, void 0, void 0, function () {
472
+ return __generator(this, function (_a) {
473
+ switch (_a.label) {
474
+ case 0:
475
+ sub.running = true;
476
+ _a.label = 1;
477
+ case 1:
478
+ if (this._enableDebug) {
479
+ console.log(new Date(), 'Running sendDataToAll Sub', sub.publication);
480
+ }
481
+ sub.runAgain = false;
482
+ return [4 /*yield*/, this.sendDataToAll(sub, collection, type)];
483
+ case 2:
484
+ _a.sent();
485
+ if (this._enableDebug) {
486
+ console.log(new Date(), 'Done sendDataToAll Sub', sub.publication, sub.runAgain);
487
+ }
488
+ if (!sub.runAgain) return [3 /*break*/, 4];
489
+ return [4 /*yield*/, this.delay(500)];
490
+ case 3:
491
+ _a.sent(); // delay, adjust as needed
492
+ _a.label = 4;
493
+ case 4:
494
+ if (sub.runAgain) return [3 /*break*/, 1];
495
+ _a.label = 5;
496
+ case 5:
497
+ sub.running = false;
498
+ return [2 /*return*/];
499
+ }
500
+ });
501
+ });
502
+ };
503
+ SubscriptionManager.prototype.sendDataToOneWithRetry = function (ws, messageId, sub, collection, type) {
504
+ return __awaiter(this, void 0, void 0, function () {
505
+ return __generator(this, function (_a) {
506
+ switch (_a.label) {
507
+ case 0:
508
+ sub.running = true;
509
+ _a.label = 1;
510
+ case 1:
511
+ if (this._enableDebug) {
512
+ console.log(new Date(), 'Running sendDataToOne Sub', sub.publication);
513
+ }
514
+ sub.runAgain = false;
515
+ return [4 /*yield*/, this.sendDataToOne(ws, messageId, sub, collection, type)];
516
+ case 2:
517
+ _a.sent();
518
+ if (this._enableDebug) {
519
+ console.log(new Date(), 'Done sendDataToOne Sub', sub.publication, sub.runAgain);
520
+ }
521
+ if (!sub.runAgain) return [3 /*break*/, 4];
522
+ return [4 /*yield*/, this.delay(500)];
523
+ case 3:
524
+ _a.sent(); // delay, adjust as needed
525
+ _a.label = 4;
526
+ case 4:
527
+ if (sub.runAgain) return [3 /*break*/, 1];
528
+ _a.label = 5;
529
+ case 5:
530
+ sub.running = false;
531
+ return [2 /*return*/];
532
+ }
533
+ });
534
+ });
535
+ };
536
+ // Add all files to publications private object
537
+ SubscriptionManager.prototype.publications = function (method) {
538
+ this._publications = Object.assign(this._publications, method);
539
+ };
540
+ // Throttled `loggedInLatency` method
541
+ SubscriptionManager.prototype.loggedInLatency = function (ws) {
542
+ var loggedInUser = this._loggedInUsers.find(function (a) { return a.id_ws === ws['id_socket']; });
543
+ if (!loggedInUser)
544
+ return;
545
+ var now = new Date();
546
+ var existingEntry = this.latencyBuffer.get(ws['id_socket']);
547
+ var newLatency = ws['latency'];
548
+ // Throttle updates: only update if time threshold has passed or latency has significantly changed
549
+ if (!existingEntry ||
550
+ (now.getTime() - existingEntry.lastUpdate.getTime() >= this.LATENCY_UPDATE_THRESHOLD_MS) ||
551
+ (Math.abs(newLatency - existingEntry.latency) > 100) // Optional: log only significant changes
552
+ ) {
553
+ // Update in-memory and buffer
554
+ loggedInUser.date = now;
555
+ this.latencyBuffer.set(ws['id_socket'], { latency: newLatency, lastUpdate: now });
556
+ }
557
+ };
558
+ // Method to flush buffered latency updates in bulk
559
+ SubscriptionManager.prototype.flushThrottledLatencyUpdates = function () {
560
+ return __awaiter(this, void 0, void 0, function () {
561
+ var updates, error_1;
562
+ return __generator(this, function (_a) {
563
+ switch (_a.label) {
564
+ case 0:
565
+ if (this.latencyBuffer.size === 0)
566
+ return [2 /*return*/]; // No updates to flush
567
+ updates = Array.from(this.latencyBuffer.entries()).map(function (_a) {
568
+ var _b = __read(_a, 2), id_ws = _b[0], _c = _b[1], latency = _c.latency, lastUpdate = _c.lastUpdate;
569
+ return ({
570
+ updateOne: {
571
+ filter: { id_ws: id_ws },
572
+ update: { $set: { latency: latency, date: lastUpdate } }
573
+ }
574
+ });
575
+ });
576
+ _a.label = 1;
577
+ case 1:
578
+ _a.trys.push([1, 3, , 4]);
579
+ return [4 /*yield*/, logged_in_users_collection_1.LoggedInUsers.bulkWrite(updates)];
580
+ case 2:
581
+ _a.sent();
582
+ this.latencyBuffer.clear(); // Clear buffer after successful update
583
+ if (this.getEnableDebug()) {
584
+ console.log(new Date(), 'Sub Manager', 'Throttled latency batch update successful', updates.length);
585
+ }
586
+ return [3 /*break*/, 4];
587
+ case 3:
588
+ error_1 = _a.sent();
589
+ console.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error_1);
590
+ return [3 /*break*/, 4];
591
+ case 4: return [2 /*return*/];
592
+ }
593
+ });
594
+ });
595
+ };
596
+ // Subscribe to publication
597
+ SubscriptionManager.prototype.subscribe = function (messageRoute, messageDate, ws, messageId, publication, subscriptionData) {
598
+ return __awaiter(this, void 0, void 0, function () {
599
+ var pub, valObj, valKeys, rootKeys, i, urlData, urlModule_1, urlNext, otherRouteSubs, sub;
600
+ var _this = this;
601
+ return __generator(this, function (_a) {
602
+ switch (_a.label) {
603
+ case 0:
604
+ this._debugSubHits += 1;
605
+ if (!this._debugSubCollections.some(function (a) { return a.publication === publication; })) {
606
+ this._debugSubCollections.push({
607
+ publication: publication,
608
+ hits: 1
609
+ });
610
+ }
611
+ else {
612
+ this._debugSubCollections.find(function (a) { return a.publication === publication; }).hits += 1;
613
+ }
614
+ pub = this._publications[publication];
615
+ if (!!pub) return [3 /*break*/, 1];
616
+ console.error(new Date(), 'No Publication: ' + publication);
617
+ return [2 /*return*/];
618
+ case 1:
619
+ if (subscriptionData.length > 1 || subscriptionData[0]) {
620
+ if (!pub.check) {
621
+ console.error(new Date(), 'No Check Function For Pub ' + publication);
622
+ return [2 /*return*/];
623
+ }
624
+ else if (!pub.check._schema) {
625
+ console.error(new Date(), 'No Check Schema For Pub ' + publication);
626
+ return [2 /*return*/];
627
+ }
628
+ else {
629
+ valObj = {};
630
+ valKeys = Object.keys(pub.check._schema);
631
+ rootKeys = valKeys.filter(function (a) { return !a.includes('.'); });
632
+ for (i = 0; i < subscriptionData.length; i++) {
633
+ valObj[rootKeys[i]] = subscriptionData[i];
634
+ }
635
+ try {
636
+ pub.check.validate(valObj);
637
+ }
638
+ catch (errors) {
639
+ if (errors) {
640
+ console.error(new Date(), 'Error in Pub Check (' + publication + ')', errors);
641
+ return [2 /*return*/];
642
+ }
643
+ }
644
+ }
645
+ }
646
+ if (messageRoute !== 'Bypass') {
647
+ urlData = messageRoute.split('/');
648
+ urlModule_1 = '';
649
+ urlNext = urlData[0];
650
+ if (urlData[0] === '') {
651
+ urlModule_1 = '/';
652
+ urlNext = urlData[1];
653
+ }
654
+ urlModule_1 += urlNext;
655
+ if (urlData.length > 1) {
656
+ urlModule_1 += '/';
657
+ }
658
+ otherRouteSubs = this._subscriptions.filter(function (a) { return a.clients.some(function (b) { return b.id_socket === ws['id_socket'] && b.messageRoute !== 'Bypass' && b.messageRoute !== '/' && b.messageRoute !== messageRoute && !b.messageRoute.startsWith(urlModule_1); }); });
659
+ if (otherRouteSubs.length) {
660
+ // ResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Detected Undestroyed Subscription - ' + this.serverConfig['CLIENT_NAME'], 'USER: ' + ws['user'] + ' (Socket: ' + ws['id_socket'] + ') ' + ' is on route: ' + messageRoute + ' but has the following subscriptions on other routes:' + JSON.stringify(otherRouteSubs, null, 2));
661
+ otherRouteSubs.forEach(function (otherSub) {
662
+ otherSub.clients.filter(function (a) { return a.id_socket === ws['id_socket']; }).forEach(function (client) {
663
+ _this.unsubscribe(client.messageRoute, new Date(), ws, client.messageId, otherSub.publication, otherSub.subscriptionData);
664
+ });
665
+ });
666
+ }
667
+ }
668
+ sub = this._subscriptions.find(function (a) { return a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData); });
669
+ // If sub found (another user watching same data), add client to same sub
670
+ if (sub) {
671
+ if (!sub.clients.some(function (a) { return a.id_socket === ws['id_socket'] && a.messageId === messageId; })) {
672
+ sub.clients.push({
673
+ id_user: ws['id_user'],
674
+ messageId: messageId,
675
+ id_socket: ws['id_socket'],
676
+ messageRoute: messageRoute
677
+ });
678
+ }
679
+ }
680
+ // If sub not found, create new sub
681
+ else {
682
+ this._subscriptions.push({
683
+ publication: publication,
684
+ subscriptionData: subscriptionData,
685
+ collections: this.getPublicationCollections(publication),
686
+ clients: [{
687
+ id_user: ws['id_user'],
688
+ messageId: messageId,
689
+ id_socket: ws['id_socket'],
690
+ messageRoute: messageRoute,
691
+ }],
692
+ cacheId: 0,
693
+ running: false,
694
+ runAgain: false
695
+ });
696
+ }
697
+ if (!sub) {
698
+ sub = this._subscriptions.find(function (a) { return a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData); });
699
+ }
700
+ if (this._enableDebug) {
701
+ console.log(new Date(), 'New Sub', sub.publication, sub.running, sub.runAgain, sub.clients.length);
702
+ }
703
+ // Immediately send data to the new client
704
+ return [4 /*yield*/, this.processSubscription(sub, ws, messageId)];
705
+ case 2:
706
+ // Immediately send data to the new client
707
+ _a.sent();
708
+ _a.label = 3;
709
+ case 3: return [2 /*return*/];
710
+ }
711
+ });
712
+ });
713
+ };
714
+ SubscriptionManager.prototype.createLoggedInUser = function (id_ws) {
715
+ return __awaiter(this, void 0, void 0, function () {
716
+ var ws, user;
717
+ return __generator(this, function (_a) {
718
+ switch (_a.label) {
719
+ case 0:
720
+ ws = this._websocketManager.getWebSocket(id_ws);
721
+ if (!ws) return [3 /*break*/, 2];
722
+ user = {
723
+ _id: (0, common_1.objectIdHexString)(),
724
+ __v: 0,
725
+ date: new Date(),
726
+ id_user: ws['id_user'],
727
+ user: ws['user'],
728
+ id_ws: ws['id_socket']
729
+ };
730
+ this._loggedInUsers.push(user);
731
+ return [4 /*yield*/, logged_in_users_collection_1.LoggedInUsers.insertOne(user)];
732
+ case 1:
733
+ _a.sent();
734
+ return [2 /*return*/, user];
735
+ case 2: throw new Error('Error in Create Logged In User: No WS');
736
+ }
737
+ });
738
+ });
739
+ };
740
+ // Unsubscribe from publication
741
+ SubscriptionManager.prototype.unsubscribe = function (messageRoute, messageDate, ws, messageId, publication, subscriptionData) {
742
+ this._debugUnSubHits += 1;
743
+ if (!this._publications[publication]) {
744
+ console.log('No Publication: ' + publication);
745
+ return;
746
+ }
747
+ else {
748
+ var sub = this._subscriptions.find(function (a) { return a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData); });
749
+ if (sub) {
750
+ for (var i = sub.clients.length - 1; i >= 0; i--) {
751
+ if (sub.clients[i].id_user === ws['id_user'] && sub.clients[i].messageId === messageId && sub.clients[i].id_socket === ws['id_socket']) {
752
+ sub.clients.splice(i, 1);
753
+ }
754
+ }
755
+ if (this._enableDebug) {
756
+ console.log(new Date(), 'Unsub', sub.publication, sub.running, sub.runAgain, sub.clients.length);
757
+ }
758
+ }
759
+ }
760
+ };
761
+ // Unsubscribe from publication
762
+ SubscriptionManager.prototype.unsubscribeAll = function (ws) {
763
+ return __awaiter(this, void 0, void 0, function () {
764
+ var userSubs, i, sub, j;
765
+ return __generator(this, function (_a) {
766
+ switch (_a.label) {
767
+ case 0:
768
+ this._debugUnSubAllHits += 1;
769
+ if (!ws) return [3 /*break*/, 2];
770
+ // Check if WebSocket has already been unsubscribed
771
+ if (ws['isUnsubscribed']) {
772
+ return [2 /*return*/]; // Skip if already unsubscribed
773
+ }
774
+ // Mark the WebSocket as unsubscribed to prevent further calls
775
+ ws['isUnsubscribed'] = true;
776
+ if (this._loggedInUsers.map(function (a) { return a.id_ws; }).indexOf(ws['id_socket']) >= 0) {
777
+ this._loggedInUsers.splice(this._loggedInUsers.map(function (a) { return a.id_ws; }).indexOf(ws['id_socket']), 1);
778
+ }
779
+ return [4 /*yield*/, logged_in_users_collection_1.LoggedInUsers.deleteOne({ id_ws: ws['id_socket'] })];
780
+ case 1:
781
+ _a.sent();
782
+ userSubs = this._subscriptions.filter(function (a) { return a.clients.some(function (b) { return b.id_user === ws['id_user'] && b.id_socket === ws['id_socket']; }); });
783
+ for (i = userSubs.length - 1; i >= 0; i--) {
784
+ sub = userSubs[i];
785
+ for (j = sub.clients.length - 1; j >= 0; j--) {
786
+ if (sub.clients[j].id_socket === ws['id_socket']) {
787
+ sub.clients.splice(j, 1);
788
+ }
789
+ }
790
+ }
791
+ this._websocketManager.removeWebSocket(ws);
792
+ _a.label = 2;
793
+ case 2: return [2 /*return*/];
794
+ }
795
+ });
796
+ });
797
+ };
798
+ SubscriptionManager.prototype.getActiveSubscriptions = function () {
799
+ return this._subscriptions;
800
+ };
801
+ // Get publication collection
802
+ SubscriptionManager.prototype.getPublicationCollections = function (publication) {
803
+ return this._publications[publication].collections;
804
+ };
805
+ // Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)
806
+ SubscriptionManager.prototype.tailOpLog = function (resumeToken) {
807
+ return __awaiter(this, void 0, void 0, function () {
808
+ var pipeline, lastResumeToken_1, _a;
809
+ var _this = this;
810
+ return __generator(this, function (_b) {
811
+ switch (_b.label) {
812
+ case 0:
813
+ if (!(this._oplog$ && !this._oplog$.closed)) return [3 /*break*/, 2];
814
+ this._oplog$.removeAllListeners();
815
+ return [4 /*yield*/, this._oplog$.close()];
816
+ case 1:
817
+ _b.sent();
818
+ this._oplog$ = null;
819
+ _b.label = 2;
820
+ case 2:
821
+ // eslint-disable-next-line no-restricted-syntax
822
+ return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 1000); })];
823
+ case 3:
824
+ // eslint-disable-next-line no-restricted-syntax
825
+ _b.sent();
826
+ if (!(!this._oplog$ || this._oplog$.closed)) return [3 /*break*/, 12];
827
+ this._oplogRetryCount += 1;
828
+ if (this._oplogRetryCount > 5) {
829
+ console.error('****************** TAIL OPLOG ERROR, RETRYING A BUNCH OF TIMES, KILLING PROCESS **************************');
830
+ process.exit(1);
831
+ }
832
+ pipeline = [
833
+ {
834
+ $match: {
835
+ $and: [
836
+ { 'ns.coll': { $nin: [
837
+ 'log-method-latencies',
838
+ 'log-subscriptions',
839
+ 'logs',
840
+ 'counters',
841
+ 'cron-job-histories',
842
+ 'email-histories',
843
+ 'qb-soap-request-histories',
844
+ 'qb-soap-request-responses',
845
+ 'qb-soap-requests',
846
+ 'qb-soap-retries'
847
+ ] } },
848
+ { 'ns.coll': { $not: /.*\.versions$/ } },
849
+ { 'ns.coll': { $not: /^monitor-/ } },
850
+ ]
851
+ },
852
+ },
853
+ ];
854
+ if (!resumeToken) return [3 /*break*/, 10];
855
+ lastResumeToken_1 = resumeToken;
856
+ _b.label = 4;
857
+ case 4:
858
+ _b.trys.push([4, 5, , 9]);
859
+ this._oplog$ = resolveio_server_app_1.ResolveIOServer.getMainDB().watch(pipeline, { resumeAfter: resumeToken });
860
+ return [3 /*break*/, 9];
861
+ case 5:
862
+ _a = _b.sent();
863
+ if (!this._oplog$) return [3 /*break*/, 7];
864
+ this._oplog$.removeAllListeners();
865
+ return [4 /*yield*/, this._oplog$.close()];
866
+ case 6:
867
+ _b.sent();
868
+ this._oplog$ = null;
869
+ _b.label = 7;
870
+ case 7: return [4 /*yield*/, this.tailOpLog(resumeToken)];
871
+ case 8:
872
+ _b.sent();
873
+ return [2 /*return*/];
874
+ case 9: return [3 /*break*/, 11];
875
+ case 10:
876
+ this._oplog$ = resolveio_server_app_1.ResolveIOServer.getMainDB().watch(pipeline);
877
+ _b.label = 11;
878
+ case 11:
879
+ console.log(new Date(), 'oplog started');
880
+ this._oplog$.on('change', function (doc) { return __awaiter(_this, void 0, void 0, function () {
881
+ var collection, flag;
882
+ return __generator(this, function (_a) {
883
+ switch (_a.label) {
884
+ case 0:
885
+ if (!doc.ns) return [3 /*break*/, 13];
886
+ if (this._enableDebug) {
887
+ console.log(new Date(), 'Oplog Hit', doc.ns);
888
+ }
889
+ collection = doc.ns.coll;
890
+ if (!this._debugOplogCollections.some(function (a) { return a.collection === doc.ns.coll && a.type === doc.operationType; })) {
891
+ this._debugOplogCollections.push({
892
+ collection: doc.ns.coll,
893
+ type: doc.operationType,
894
+ hits: 1
895
+ });
896
+ }
897
+ else {
898
+ this._debugOplogCollections.find(function (a) { return a.collection === doc.ns.coll && a.type === doc.operationType; }).hits += 1;
899
+ }
900
+ if (!collection) return [3 /*break*/, 10];
901
+ this._debugOplogHits += 1;
902
+ if (!(doc.operationType === 'insert')) return [3 /*break*/, 5];
903
+ if (!(collection === 'support-tickets')) return [3 /*break*/, 2];
904
+ if (!(this.serverConfig['ROOT_URL'] === 'https://resolveio.com')) return [3 /*break*/, 2];
905
+ resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(), 'sendSupportTicketEmail', doc.documentKey['_id']);
906
+ return [4 /*yield*/, this.invalidatePubsCache(collection, 'insert')];
907
+ case 1:
908
+ _a.sent();
909
+ _a.label = 2;
910
+ case 2:
911
+ if (!(collection !== 'method-responses')) return [3 /*break*/, 4];
912
+ return [4 /*yield*/, this.invalidatePubsCache(collection, 'insert')];
913
+ case 3:
914
+ _a.sent();
915
+ _a.label = 4;
916
+ case 4: return [3 /*break*/, 10];
917
+ case 5:
918
+ if (!(doc.operationType === 'update' || doc.operationType === 'replace')) return [3 /*break*/, 8];
919
+ if (!(collection !== 'method-responses')) return [3 /*break*/, 7];
920
+ return [4 /*yield*/, this.invalidatePubsCache(collection, 'update')];
921
+ case 6:
922
+ _a.sent();
923
+ _a.label = 7;
924
+ case 7: return [3 /*break*/, 10];
925
+ case 8:
926
+ if (!(doc.operationType === 'delete')) return [3 /*break*/, 10];
927
+ if (!(collection !== 'method-responses')) return [3 /*break*/, 10];
928
+ return [4 /*yield*/, this.invalidatePubsCache(collection, 'delete')];
929
+ case 9:
930
+ _a.sent();
931
+ _a.label = 10;
932
+ case 10:
933
+ if (!(collection === 'flags')) return [3 /*break*/, 12];
934
+ return [4 /*yield*/, flag_collection_1.Flags.findOne({ type: 'Enable Debug' })];
935
+ case 11:
936
+ flag = _a.sent();
937
+ if (flag && flag.value) {
938
+ this._enableDebug = true;
939
+ }
940
+ else {
941
+ this._enableDebug = false;
942
+ }
943
+ _a.label = 12;
944
+ case 12:
945
+ lastResumeToken_1 = doc._id;
946
+ if ((!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') && (process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0'))) {
947
+ }
948
+ _a.label = 13;
949
+ case 13: return [2 /*return*/];
950
+ }
951
+ });
952
+ }); });
953
+ this._oplog$.on('error', function (error) { return __awaiter(_this, void 0, void 0, function () {
954
+ return __generator(this, function (_a) {
955
+ switch (_a.label) {
956
+ case 0:
957
+ console.log(new Date(), 'oplog error', error);
958
+ return [4 /*yield*/, this._oplog$.close()];
959
+ case 1:
960
+ _a.sent();
961
+ return [2 /*return*/];
962
+ }
963
+ });
964
+ }); });
965
+ this._oplog$.on('end', function () { return __awaiter(_this, void 0, void 0, function () {
966
+ return __generator(this, function (_a) {
967
+ switch (_a.label) {
968
+ case 0:
969
+ console.log(new Date(), 'oplog end');
970
+ return [4 /*yield*/, this._oplog$.close()];
971
+ case 1:
972
+ _a.sent();
973
+ return [2 /*return*/];
974
+ }
975
+ });
976
+ }); });
977
+ this._oplog$.on('close', function () { return __awaiter(_this, void 0, void 0, function () {
978
+ return __generator(this, function (_a) {
979
+ switch (_a.label) {
980
+ case 0:
981
+ console.log(new Date(), 'oplog close');
982
+ this._oplog$.removeAllListeners();
983
+ this._oplog$ = null;
984
+ return [4 /*yield*/, this.tailOpLog(lastResumeToken_1)];
985
+ case 1:
986
+ _a.sent();
987
+ return [2 /*return*/];
988
+ }
989
+ });
990
+ }); });
991
+ _b.label = 12;
992
+ case 12: return [2 /*return*/];
993
+ }
994
+ });
995
+ });
996
+ };
997
+ SubscriptionManager.prototype.processSubscription = function (sub, ws, messageId) {
998
+ return __awaiter(this, void 0, void 0, function () {
999
+ var cacheData, serverRes, _a;
1000
+ return __generator(this, function (_b) {
1001
+ switch (_b.label) {
1002
+ case 0:
1003
+ if (!!this._publications[sub.publication].user_specific) return [3 /*break*/, 8];
1004
+ if (!sub.cacheId) return [3 /*break*/, 5];
1005
+ _b.label = 1;
1006
+ case 1:
1007
+ _b.trys.push([1, 2, , 4]);
1008
+ cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), common_1.dateReviver);
1009
+ serverRes = {
1010
+ messageId: messageId,
1011
+ hasError: false,
1012
+ data: cacheData
1013
+ };
1014
+ if (this._enableDebug) {
1015
+ console.log(new Date(), 'Process Sub, Cache', sub.publication);
1016
+ }
1017
+ this.sendWS(ws, serverRes);
1018
+ return [3 /*break*/, 4];
1019
+ case 2:
1020
+ _a = _b.sent();
1021
+ this._nodeCache.del(sub.cacheId);
1022
+ sub.cacheId = 0;
1023
+ return [4 /*yield*/, this.sendDataToAllWithRetry(sub, '', 'newSub')];
1024
+ case 3:
1025
+ _b.sent();
1026
+ return [3 /*break*/, 4];
1027
+ case 4: return [3 /*break*/, 7];
1028
+ case 5:
1029
+ if (this._enableDebug) {
1030
+ console.log(new Date(), 'Process Sub, Non - Cache', sub.publication, sub.running);
1031
+ }
1032
+ if (sub.running) {
1033
+ return [2 /*return*/];
1034
+ }
1035
+ return [4 /*yield*/, this.sendDataToAllWithRetry(sub, '', 'newSub')];
1036
+ case 6:
1037
+ _b.sent();
1038
+ _b.label = 7;
1039
+ case 7: return [3 /*break*/, 10];
1040
+ case 8:
1041
+ if (this._enableDebug) {
1042
+ console.log(new Date(), 'Process Sub Specific, Non - Cache', sub.publication, sub.running);
1043
+ }
1044
+ if (sub.running) {
1045
+ return [2 /*return*/];
1046
+ }
1047
+ return [4 /*yield*/, this.sendDataToOneWithRetry(ws, messageId, sub, '', 'newSub')];
1048
+ case 9:
1049
+ _b.sent();
1050
+ _b.label = 10;
1051
+ case 10: return [2 /*return*/];
1052
+ }
1053
+ });
1054
+ });
1055
+ };
1056
+ SubscriptionManager.prototype.sendDataToOne = function (ws, messageId, sub, collection, type) {
1057
+ return __awaiter(this, void 0, void 0, function () {
1058
+ var monitor, res, serverRes, err_1, serverRes;
1059
+ var _a;
1060
+ return __generator(this, function (_b) {
1061
+ switch (_b.label) {
1062
+ case 0:
1063
+ monitor = this._monitorManagerFunction.startMonitorFunction('User Specific Publication', sub.publication, '', '', sub.subscriptionData);
1064
+ _b.label = 1;
1065
+ case 1:
1066
+ _b.trys.push([1, 3, 5, 7]);
1067
+ resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));
1068
+ return [4 /*yield*/, (_a = this._publications[sub.publication].function).call.apply(_a, __spreadArray([Object.assign({}, this, SubscriptionManager.prototype), ws['id_user']], __read(sub.subscriptionData), false))];
1069
+ case 2:
1070
+ res = _b.sent();
1071
+ serverRes = {
1072
+ messageId: messageId,
1073
+ hasError: false,
1074
+ data: res
1075
+ };
1076
+ this.sendWS(ws, serverRes);
1077
+ return [3 /*break*/, 7];
1078
+ case 3:
1079
+ err_1 = _b.sent();
1080
+ serverRes = {
1081
+ messageId: messageId,
1082
+ hasError: true,
1083
+ data: err_1
1084
+ };
1085
+ this.sendWS(ws, serverRes);
1086
+ return [4 /*yield*/, resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendDataToOne - WS)\n\nData \n' + JSON.stringify(sub.subscriptionData, null, 2) + '\n\nErrors\n' + JSON.stringify(err_1, null, 2))];
1087
+ case 4:
1088
+ _b.sent();
1089
+ return [3 /*break*/, 7];
1090
+ case 5: return [4 /*yield*/, this._monitorManagerFunction.finishMonitorFunction(monitor)];
1091
+ case 6:
1092
+ _b.sent();
1093
+ return [7 /*endfinally*/];
1094
+ case 7: return [2 /*return*/];
1095
+ }
1096
+ });
1097
+ });
1098
+ };
1099
+ // Fetch pub once, send to all clients linked to this pub
1100
+ SubscriptionManager.prototype.sendDataToAll = function (sub, collection, type) {
1101
+ return __awaiter(this, void 0, void 0, function () {
1102
+ var subIndex, monitor, res_1, cacheData, _a, _b, client, ws, serverRes, _c, _d, client, ws, serverRes, nodeCacheSize, deleteCount, subArr, zz, err_2, _e, _f, client, ws, serverRes;
1103
+ var _g, e_3, _h, e_4, _j, e_5, _k;
1104
+ var _this = this;
1105
+ return __generator(this, function (_l) {
1106
+ switch (_l.label) {
1107
+ case 0:
1108
+ if (!!sub.clients.length) return [3 /*break*/, 1];
1109
+ if (sub.cacheId) {
1110
+ this._nodeCache.del(sub.cacheId);
1111
+ sub.cacheId = 0;
1112
+ }
1113
+ subIndex = this._subscriptions.findIndex(function (a) { return a.publication === sub.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(sub.subscriptionData); });
1114
+ if (subIndex >= 0) {
1115
+ this._subscriptions.splice(subIndex, 1);
1116
+ }
1117
+ return [2 /*return*/];
1118
+ case 1:
1119
+ monitor = this._monitorManagerFunction.startMonitorFunction('Publication', sub.publication, '', '', sub.subscriptionData);
1120
+ _l.label = 2;
1121
+ case 2:
1122
+ _l.trys.push([2, 4, 6, 8]);
1123
+ if (sub.publication !== 'superadminAPM' && sub.publication !== 'loggedInUsers') {
1124
+ resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().callMethod.call(resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertSubscriptionLog', type, sub.publication, collection, JSON.stringify(sub.subscriptionData));
1125
+ }
1126
+ return [4 /*yield*/, (_g = this._publications[sub.publication].function).call.apply(_g, __spreadArray([Object.assign({}, this, SubscriptionManager.prototype)], __read(sub.subscriptionData), false))];
1127
+ case 3:
1128
+ res_1 = _l.sent();
1129
+ if (sub.cacheId) {
1130
+ try {
1131
+ cacheData = JSON.parse(this._nodeCache.get(sub.cacheId), common_1.dateReviver);
1132
+ if (JSON.stringify(cacheData) !== JSON.stringify(res_1)) {
1133
+ try {
1134
+ for (_a = __values(sub.clients), _b = _a.next(); !_b.done; _b = _a.next()) {
1135
+ client = _b.value;
1136
+ ws = this._websocketManager.getWebSocket(client.id_socket);
1137
+ if (ws && ws.readyState === ws.OPEN) {
1138
+ serverRes = {
1139
+ messageId: client.messageId,
1140
+ hasError: false,
1141
+ data: res_1
1142
+ };
1143
+ this.sendWS(ws, serverRes);
1144
+ }
1145
+ }
1146
+ }
1147
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1148
+ finally {
1149
+ try {
1150
+ if (_b && !_b.done && (_h = _a.return)) _h.call(_a);
1151
+ }
1152
+ finally { if (e_3) throw e_3.error; }
1153
+ }
1154
+ this._nodeCache.del(sub.cacheId);
1155
+ if ((0, common_1.getBinarySize)(JSON.stringify(res_1)) < 1000000 &&
1156
+ !sub.collections.includes('logs') &&
1157
+ !sub.collections.find(function (a) { return a.endsWith('.versions'); }) &&
1158
+ !sub.collections.find(function (a) { return a.startsWith('monitor-'); })) {
1159
+ this._nodeCache.set(sub.cacheId, JSON.stringify(res_1));
1160
+ }
1161
+ else {
1162
+ sub.cacheId = 0;
1163
+ }
1164
+ }
1165
+ }
1166
+ catch (_m) {
1167
+ sub.clients.map(function (client) {
1168
+ var ws = _this._websocketManager.getWebSocket(client.id_socket);
1169
+ if (ws && ws.readyState === ws.OPEN) {
1170
+ var serverRes = {
1171
+ messageId: client.messageId,
1172
+ hasError: false,
1173
+ data: res_1
1174
+ };
1175
+ _this.sendWS(ws, serverRes);
1176
+ }
1177
+ });
1178
+ this._nodeCache.del(sub.cacheId);
1179
+ if ((0, common_1.getBinarySize)(JSON.stringify(res_1)) < 1000000 &&
1180
+ !sub.collections.includes('logs') &&
1181
+ !sub.collections.find(function (a) { return a.endsWith('.versions'); }) &&
1182
+ !sub.collections.find(function (a) { return a.startsWith('monitor-'); })) {
1183
+ this._nodeCache.set(sub.cacheId, JSON.stringify(res_1));
1184
+ }
1185
+ else {
1186
+ sub.cacheId = 0;
1187
+ }
1188
+ }
1189
+ }
1190
+ else {
1191
+ try {
1192
+ for (_c = __values(sub.clients), _d = _c.next(); !_d.done; _d = _c.next()) {
1193
+ client = _d.value;
1194
+ ws = this._websocketManager.getWebSocket(client.id_socket);
1195
+ if (ws && ws.readyState === ws.OPEN) {
1196
+ serverRes = {
1197
+ messageId: client.messageId,
1198
+ hasError: false,
1199
+ data: res_1
1200
+ };
1201
+ this.sendWS(ws, serverRes);
1202
+ }
1203
+ }
1204
+ }
1205
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
1206
+ finally {
1207
+ try {
1208
+ if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
1209
+ }
1210
+ finally { if (e_4) throw e_4.error; }
1211
+ }
1212
+ if ((0, common_1.getBinarySize)(JSON.stringify(res_1)) < 1000000 &&
1213
+ !sub.collections.includes('logs') &&
1214
+ !sub.collections.find(function (a) { return a.endsWith('.versions'); }) &&
1215
+ !sub.collections.find(function (a) { return a.startsWith('monitor-'); })) {
1216
+ sub.cacheId = this._cacheId++;
1217
+ this._nodeCache.set(sub.cacheId, JSON.stringify(res_1));
1218
+ nodeCacheSize = this._nodeCache.getStats().vsize;
1219
+ if (nodeCacheSize > this._heapLimit) {
1220
+ deleteCount = 0;
1221
+ subArr = this._subscriptions.filter(function (a) { return a.cacheId && !a.clients.length; });
1222
+ for (zz = 0; zz < subArr.length; zz++) {
1223
+ this._debugRemoveCacheHits += 1;
1224
+ this._nodeCache.del(subArr[zz].cacheId);
1225
+ subArr[zz].cacheId = 0;
1226
+ deleteCount += 1;
1227
+ if (this._nodeCache.getStats().vsize < this._heapLimit * 0.75) {
1228
+ break;
1229
+ }
1230
+ }
1231
+ if (this._enableDebug) {
1232
+ console.log('Sub Cache: ' +
1233
+ 'Too Big - ' +
1234
+ sub.publication +
1235
+ ' - Deleted: ' +
1236
+ deleteCount +
1237
+ ' - ' +
1238
+ nodeCacheSize);
1239
+ }
1240
+ }
1241
+ }
1242
+ else {
1243
+ sub.cacheId = 0;
1244
+ }
1245
+ }
1246
+ return [3 /*break*/, 8];
1247
+ case 4:
1248
+ err_2 = _l.sent();
1249
+ try {
1250
+ for (_e = __values(sub.clients), _f = _e.next(); !_f.done; _f = _e.next()) {
1251
+ client = _f.value;
1252
+ ws = this._websocketManager.getWebSocket(client.id_socket);
1253
+ if (ws && ws.readyState === ws.OPEN) {
1254
+ serverRes = {
1255
+ messageId: client.messageId,
1256
+ hasError: true,
1257
+ data: err_2
1258
+ };
1259
+ this.sendWS(ws, serverRes);
1260
+ }
1261
+ }
1262
+ }
1263
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
1264
+ finally {
1265
+ try {
1266
+ if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
1267
+ }
1268
+ finally { if (e_5) throw e_5.error; }
1269
+ }
1270
+ return [4 /*yield*/, resolveio_server_app_1.ResolveIOServer.getMainServer().getMethodManager().sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Subscription ' + sub.publication + ' - (sendPubData)\n\nData \n' + JSON.stringify(sub.subscriptionData, null, 2) + '\n\nErrors\n' + JSON.stringify(err_2, null, 2))];
1271
+ case 5:
1272
+ _l.sent();
1273
+ return [3 /*break*/, 8];
1274
+ case 6: return [4 /*yield*/, this._monitorManagerFunction.finishMonitorFunction(monitor)];
1275
+ case 7:
1276
+ _l.sent();
1277
+ return [7 /*endfinally*/];
1278
+ case 8: return [2 /*return*/];
1279
+ }
1280
+ });
1281
+ });
1282
+ };
1283
+ SubscriptionManager.prototype.sendWS = function (ws, data) {
1284
+ this._websocketManager.send(ws, data);
1285
+ };
1286
+ SubscriptionManager.prototype.getEnableDebug = function () {
1287
+ return this._enableDebug;
1288
+ };
1289
+ return SubscriptionManager;
1290
+ }());
1291
+ exports.SubscriptionManager = SubscriptionManager;
1292
+
2
1293
  //# sourceMappingURL=subscription.manager.js.map