@resolveio/server-lib 20.14.20 → 20.14.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -75,6 +75,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
75
75
  exports.SubscriptionManager = void 0;
76
76
  var NodeCache = require("node-cache");
77
77
  var msgpackr_1 = require("msgpackr");
78
+ var os = require("os");
79
+ var perf_hooks_1 = require("perf_hooks");
78
80
  var flag_collection_1 = require("../collections/flag.collection");
79
81
  var logged_in_users_collection_1 = require("../collections/logged-in-users.collection");
80
82
  var app_status_1 = require("../publications/app-status");
@@ -184,7 +186,32 @@ var SubscriptionManager = /** @class */ (function () {
184
186
  this._warmupLogIntervalMs = 10000;
185
187
  this._warmupLastLogMs = 0;
186
188
  this._warmupAllowPublications = new Set();
189
+ this._warmupRampMaxPerTick = 0;
190
+ this._warmupRampMaxInFlight = 0;
191
+ this._warmupWindowEndedLogged = false;
192
+ this._warmupAdaptiveEnabled = true;
193
+ this._warmupAdaptiveSampleMs = 1000;
194
+ this._warmupAdaptiveAlpha = 0.2;
195
+ this._warmupTargetCpuPct = 55;
196
+ this._warmupMaxCpuPct = 85;
197
+ this._warmupTargetMemPct = 70;
198
+ this._warmupMaxMemPct = 85;
199
+ this._warmupTargetLagMs = 80;
200
+ this._warmupMaxLagMs = 200;
201
+ this._warmupAdaptiveScale = 0;
202
+ this._warmupAdaptiveLastSampleAt = 0;
203
+ this._warmupAdaptiveMetrics = { cpuPct: 0, memPct: 0, rssMB: 0, lagMs: 0, pressure: 0 };
204
+ this._warmupCpuSampleUsage = process.cpuUsage();
205
+ this._warmupCpuSampleAt = process.hrtime.bigint();
206
+ this._warmupLagMonitor = null;
207
+ this._publicationWorkersEnabled = true;
208
+ this._publicationWorkerQueueLimit = 0;
187
209
  }
210
+ SubscriptionManager.createPublicationRegistry = function (serverConfig) {
211
+ var subscriptionManager = new SubscriptionManager();
212
+ subscriptionManager.initializePublicationRegistry(serverConfig);
213
+ return subscriptionManager;
214
+ };
188
215
  SubscriptionManager.create = function (wss, serverConfig, monitorManagerFunction) {
189
216
  var _this = this;
190
217
  var subscriptionManager = new SubscriptionManager();
@@ -200,6 +227,10 @@ var SubscriptionManager = /** @class */ (function () {
200
227
  }); });
201
228
  return subscriptionManager;
202
229
  };
230
+ SubscriptionManager.prototype.initializePublicationRegistry = function (serverConfig) {
231
+ this.serverConfig = serverConfig || resolveio_server_app_1.ResolveIOServer.getServerConfig();
232
+ this.registerCorePublications();
233
+ };
203
234
  SubscriptionManager.prototype.initialize = function (wss, serverConfig, monitorManagerFunction) {
204
235
  return __awaiter(this, void 0, void 0, function () {
205
236
  var resumeToken, flag, dependencyFlag;
@@ -230,21 +261,7 @@ var SubscriptionManager = /** @class */ (function () {
230
261
  this._wss = wss;
231
262
  this._oplogMode = this.resolveOplogMode();
232
263
  this._localOplogResyncIntervalMs = this.resolveLocalOplogResyncIntervalMs();
233
- // Publications
234
- (0, super_admin_1.loadSuperAdminPublications)(this);
235
- (0, ai_terminal_1.loadAiTerminalPublications)(this);
236
- (0, app_status_1.loadAppStatusPublications)(this);
237
- (0, logs_1.loadLogPublications)(this);
238
- (0, files_1.loadFilePublications)(this);
239
- (0, cron_jobs_1.loadCronJobPublications)(this);
240
- (0, flags_update_1.loadFlagsUpdatePublications)(this);
241
- (0, flags_1.loadFlagsPublications)(this);
242
- (0, notifications_1.loadNotificationPublications)(this);
243
- (0, report_builder_reports_1.loadReportBuilderReportPublications)(this);
244
- (0, report_builder_libraries_1.loadReportBuilderLibraryPublications)(this);
245
- (0, user_groups_1.loadUserGroupPublications)(this);
246
- (0, user_guides_1.loadUserGuidePublications)(this);
247
- (0, report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this);
264
+ this.registerCorePublications();
248
265
  if (!(this._oplogMode === 'local')) return [3 /*break*/, 2];
249
266
  return [4 /*yield*/, this.enableLocalOplogFallback('config')];
250
267
  case 1:
@@ -383,11 +400,28 @@ var SubscriptionManager = /** @class */ (function () {
383
400
  }
384
401
  this.setCacheLimit();
385
402
  this.configureWarmup();
403
+ this.configurePublicationWorkers();
386
404
  return [2 /*return*/];
387
405
  }
388
406
  });
389
407
  });
390
408
  };
409
+ SubscriptionManager.prototype.registerCorePublications = function () {
410
+ (0, super_admin_1.loadSuperAdminPublications)(this);
411
+ (0, ai_terminal_1.loadAiTerminalPublications)(this);
412
+ (0, app_status_1.loadAppStatusPublications)(this);
413
+ (0, logs_1.loadLogPublications)(this);
414
+ (0, files_1.loadFilePublications)(this);
415
+ (0, cron_jobs_1.loadCronJobPublications)(this);
416
+ (0, flags_update_1.loadFlagsUpdatePublications)(this);
417
+ (0, flags_1.loadFlagsPublications)(this);
418
+ (0, notifications_1.loadNotificationPublications)(this);
419
+ (0, report_builder_reports_1.loadReportBuilderReportPublications)(this);
420
+ (0, report_builder_libraries_1.loadReportBuilderLibraryPublications)(this);
421
+ (0, user_groups_1.loadUserGroupPublications)(this);
422
+ (0, user_guides_1.loadUserGuidePublications)(this);
423
+ (0, report_builder_dashboard_builders_1.loadReportBuilderDashboardBuilderPublications)(this);
424
+ };
391
425
  SubscriptionManager.prototype.setCacheLimit = function () {
392
426
  if (process.env.IS_WORKERS_ENABLED === 'true') {
393
427
  this._heapLimit = this._heapSize * 0.4;
@@ -397,7 +431,7 @@ var SubscriptionManager = /** @class */ (function () {
397
431
  }
398
432
  };
399
433
  SubscriptionManager.prototype.configureWarmup = function () {
400
- var _a, _b, _c, _d, _e, _f, _g, _h;
434
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
401
435
  var config = this.serverConfig || resolveio_server_app_1.ResolveIOServer.getServerConfig() || {};
402
436
  var enabledRaw = (_a = process.env.SUBSCRIPTION_WARMUP_ENABLED) !== null && _a !== void 0 ? _a : config['SUBSCRIPTION_WARMUP_ENABLED'];
403
437
  var warmupMs = this.parsePositiveNumber((_b = process.env.SUBSCRIPTION_WARMUP_MS) !== null && _b !== void 0 ? _b : config['SUBSCRIPTION_WARMUP_MS']);
@@ -412,9 +446,27 @@ var SubscriptionManager = /** @class */ (function () {
412
446
  this._warmupTickMs = this.parsePositiveNumber((_c = process.env.SUBSCRIPTION_WARMUP_TICK_MS) !== null && _c !== void 0 ? _c : config['SUBSCRIPTION_WARMUP_TICK_MS']) || this._warmupTickMs;
413
447
  this._warmupMaxPerTick = this.parsePositiveNumber((_d = process.env.SUBSCRIPTION_WARMUP_MAX_PER_TICK) !== null && _d !== void 0 ? _d : config['SUBSCRIPTION_WARMUP_MAX_PER_TICK']) || this._warmupMaxPerTick;
414
448
  this._warmupMaxInFlight = this.parsePositiveNumber((_e = process.env.SUBSCRIPTION_WARMUP_MAX_IN_FLIGHT) !== null && _e !== void 0 ? _e : config['SUBSCRIPTION_WARMUP_MAX_IN_FLIGHT']) || Math.max(1, this._warmupMaxPerTick);
415
- this._warmupQueueLimit = this.parsePositiveNumber((_f = process.env.SUBSCRIPTION_WARMUP_QUEUE_LIMIT) !== null && _f !== void 0 ? _f : config['SUBSCRIPTION_WARMUP_QUEUE_LIMIT']) || this._warmupQueueLimit;
416
- this._warmupLogIntervalMs = this.parsePositiveNumber((_g = process.env.SUBSCRIPTION_WARMUP_LOG_INTERVAL_MS) !== null && _g !== void 0 ? _g : config['SUBSCRIPTION_WARMUP_LOG_INTERVAL_MS']) || this._warmupLogIntervalMs;
417
- var allowRaw = (_h = process.env.SUBSCRIPTION_WARMUP_ALLOW_PUBS) !== null && _h !== void 0 ? _h : config['SUBSCRIPTION_WARMUP_ALLOW_PUBS'];
449
+ this._warmupRampMaxPerTick = this.parsePositiveNumber((_f = process.env.SUBSCRIPTION_WARMUP_RAMP_MAX_PER_TICK) !== null && _f !== void 0 ? _f : config['SUBSCRIPTION_WARMUP_RAMP_MAX_PER_TICK']) || this._warmupMaxPerTick;
450
+ this._warmupRampMaxInFlight = this.parsePositiveNumber((_g = process.env.SUBSCRIPTION_WARMUP_RAMP_MAX_IN_FLIGHT) !== null && _g !== void 0 ? _g : config['SUBSCRIPTION_WARMUP_RAMP_MAX_IN_FLIGHT']) || this._warmupMaxInFlight;
451
+ this._warmupQueueLimit = this.parsePositiveNumber((_h = process.env.SUBSCRIPTION_WARMUP_QUEUE_LIMIT) !== null && _h !== void 0 ? _h : config['SUBSCRIPTION_WARMUP_QUEUE_LIMIT']) || this._warmupQueueLimit;
452
+ this._warmupLogIntervalMs = this.parsePositiveNumber((_j = process.env.SUBSCRIPTION_WARMUP_LOG_INTERVAL_MS) !== null && _j !== void 0 ? _j : config['SUBSCRIPTION_WARMUP_LOG_INTERVAL_MS']) || this._warmupLogIntervalMs;
453
+ var adaptiveRaw = (_k = process.env.SUBSCRIPTION_WARMUP_ADAPTIVE_ENABLED) !== null && _k !== void 0 ? _k : config['SUBSCRIPTION_WARMUP_ADAPTIVE_ENABLED'];
454
+ this._warmupAdaptiveEnabled = adaptiveRaw === undefined ? true : this.parseBoolean(adaptiveRaw);
455
+ this._warmupAdaptiveSampleMs = this.parsePositiveNumber((_l = process.env.SUBSCRIPTION_WARMUP_ADAPTIVE_SAMPLE_MS) !== null && _l !== void 0 ? _l : config['SUBSCRIPTION_WARMUP_ADAPTIVE_SAMPLE_MS']) || this._warmupAdaptiveSampleMs;
456
+ this._warmupAdaptiveAlpha = this.parsePositiveFloat((_m = process.env.SUBSCRIPTION_WARMUP_ADAPTIVE_ALPHA) !== null && _m !== void 0 ? _m : config['SUBSCRIPTION_WARMUP_ADAPTIVE_ALPHA']) || this._warmupAdaptiveAlpha;
457
+ this._warmupTargetCpuPct = this.parsePositiveNumber((_o = process.env.SUBSCRIPTION_WARMUP_TARGET_CPU_PCT) !== null && _o !== void 0 ? _o : config['SUBSCRIPTION_WARMUP_TARGET_CPU_PCT']) || this._warmupTargetCpuPct;
458
+ this._warmupMaxCpuPct = this.parsePositiveNumber((_p = process.env.SUBSCRIPTION_WARMUP_MAX_CPU_PCT) !== null && _p !== void 0 ? _p : config['SUBSCRIPTION_WARMUP_MAX_CPU_PCT']) || this._warmupMaxCpuPct;
459
+ this._warmupTargetMemPct = this.parsePositiveNumber((_q = process.env.SUBSCRIPTION_WARMUP_TARGET_MEM_PCT) !== null && _q !== void 0 ? _q : config['SUBSCRIPTION_WARMUP_TARGET_MEM_PCT']) || this._warmupTargetMemPct;
460
+ this._warmupMaxMemPct = this.parsePositiveNumber((_r = process.env.SUBSCRIPTION_WARMUP_MAX_MEM_PCT) !== null && _r !== void 0 ? _r : config['SUBSCRIPTION_WARMUP_MAX_MEM_PCT']) || this._warmupMaxMemPct;
461
+ this._warmupTargetLagMs = this.parsePositiveNumber((_s = process.env.SUBSCRIPTION_WARMUP_TARGET_LAG_MS) !== null && _s !== void 0 ? _s : config['SUBSCRIPTION_WARMUP_TARGET_LAG_MS']) || this._warmupTargetLagMs;
462
+ this._warmupMaxLagMs = this.parsePositiveNumber((_t = process.env.SUBSCRIPTION_WARMUP_MAX_LAG_MS) !== null && _t !== void 0 ? _t : config['SUBSCRIPTION_WARMUP_MAX_LAG_MS']) || this._warmupMaxLagMs;
463
+ this._warmupAdaptiveScale = 0;
464
+ this._warmupAdaptiveLastSampleAt = 0;
465
+ this._warmupWindowEndedLogged = false;
466
+ if (this._warmupAdaptiveEnabled) {
467
+ this.ensureWarmupAdaptiveMonitor();
468
+ }
469
+ var allowRaw = (_u = process.env.SUBSCRIPTION_WARMUP_ALLOW_PUBS) !== null && _u !== void 0 ? _u : config['SUBSCRIPTION_WARMUP_ALLOW_PUBS'];
418
470
  if (typeof allowRaw === 'string' && allowRaw.trim()) {
419
471
  this._warmupAllowPublications = new Set(allowRaw
420
472
  .split(',')
@@ -427,10 +479,28 @@ var SubscriptionManager = /** @class */ (function () {
427
479
  tickMs: this._warmupTickMs,
428
480
  maxPerTick: this._warmupMaxPerTick,
429
481
  maxInFlight: this._warmupMaxInFlight,
482
+ rampMaxPerTick: this._warmupRampMaxPerTick,
483
+ rampMaxInFlight: this._warmupRampMaxInFlight,
484
+ adaptiveEnabled: this._warmupAdaptiveEnabled,
485
+ adaptiveSampleMs: this._warmupAdaptiveSampleMs,
486
+ adaptiveAlpha: this._warmupAdaptiveAlpha,
487
+ targetCpuPct: this._warmupTargetCpuPct,
488
+ maxCpuPct: this._warmupMaxCpuPct,
489
+ targetMemPct: this._warmupTargetMemPct,
490
+ maxMemPct: this._warmupMaxMemPct,
491
+ targetLagMs: this._warmupTargetLagMs,
492
+ maxLagMs: this._warmupMaxLagMs,
430
493
  queueLimit: this._warmupQueueLimit,
431
494
  allowPubs: Array.from(this._warmupAllowPublications.values())
432
495
  });
433
496
  };
497
+ SubscriptionManager.prototype.configurePublicationWorkers = function () {
498
+ var _a, _b;
499
+ var config = this.serverConfig || resolveio_server_app_1.ResolveIOServer.getServerConfig() || {};
500
+ var enabledRaw = (_a = process.env.SUBSCRIPTION_WORKERS_ENABLED) !== null && _a !== void 0 ? _a : config['SUBSCRIPTION_WORKERS_ENABLED'];
501
+ this._publicationWorkersEnabled = enabledRaw === undefined ? true : this.parseBoolean(enabledRaw);
502
+ this._publicationWorkerQueueLimit = this.parsePositiveNumber((_b = process.env.SUBSCRIPTION_WORKER_QUEUE_MAX) !== null && _b !== void 0 ? _b : config['SUBSCRIPTION_WORKER_QUEUE_MAX']);
503
+ };
434
504
  SubscriptionManager.prototype.parseBoolean = function (value) {
435
505
  if (value === true) {
436
506
  return true;
@@ -447,8 +517,98 @@ var SubscriptionManager = /** @class */ (function () {
447
517
  }
448
518
  return false;
449
519
  };
520
+ SubscriptionManager.prototype.clampNumber = function (value, min, max) {
521
+ if (value < min) {
522
+ return min;
523
+ }
524
+ if (value > max) {
525
+ return max;
526
+ }
527
+ return value;
528
+ };
529
+ SubscriptionManager.prototype.ensureWarmupAdaptiveMonitor = function () {
530
+ if (this._warmupLagMonitor) {
531
+ return;
532
+ }
533
+ this._warmupLagMonitor = (0, perf_hooks_1.monitorEventLoopDelay)({ resolution: 20 });
534
+ this._warmupLagMonitor.enable();
535
+ this._warmupCpuSampleUsage = process.cpuUsage();
536
+ this._warmupCpuSampleAt = process.hrtime.bigint();
537
+ this._warmupAdaptiveLastSampleAt = Date.now();
538
+ };
539
+ SubscriptionManager.prototype.normalizePressure = function (value, target, max) {
540
+ if (!Number.isFinite(value)) {
541
+ return 0;
542
+ }
543
+ if (max <= target) {
544
+ return value > target ? 1 : 0;
545
+ }
546
+ var pressure = (value - target) / (max - target);
547
+ return this.clampNumber(pressure, 0, 1);
548
+ };
549
+ SubscriptionManager.prototype.sampleCpuPercent = function () {
550
+ var _a, _b, _c;
551
+ var usage = process.cpuUsage();
552
+ var now = process.hrtime.bigint();
553
+ var elapsedMicros = Number(now - this._warmupCpuSampleAt) / 1000;
554
+ var usageDelta = (usage.user - this._warmupCpuSampleUsage.user) + (usage.system - this._warmupCpuSampleUsage.system);
555
+ this._warmupCpuSampleUsage = usage;
556
+ this._warmupCpuSampleAt = now;
557
+ if (!elapsedMicros || elapsedMicros <= 0) {
558
+ return (_b = (_a = this._warmupAdaptiveMetrics) === null || _a === void 0 ? void 0 : _a.cpuPct) !== null && _b !== void 0 ? _b : 0;
559
+ }
560
+ var cores = Math.max(1, ((_c = os.cpus()) === null || _c === void 0 ? void 0 : _c.length) || 1);
561
+ var cpuPct = (usageDelta / (elapsedMicros * cores)) * 100;
562
+ return this.clampNumber(cpuPct, 0, 100);
563
+ };
564
+ SubscriptionManager.prototype.sampleWarmupAdaptiveMetrics = function (nowMs) {
565
+ if (!this._warmupAdaptiveEnabled) {
566
+ return this._warmupAdaptiveMetrics;
567
+ }
568
+ if (this._warmupAdaptiveLastSampleAt && (nowMs - this._warmupAdaptiveLastSampleAt) < this._warmupAdaptiveSampleMs) {
569
+ return this._warmupAdaptiveMetrics;
570
+ }
571
+ this.ensureWarmupAdaptiveMonitor();
572
+ var cpuPct = this.sampleCpuPercent();
573
+ var mem = process.memoryUsage();
574
+ var totalMem = os.totalmem();
575
+ var rssMB = mem.rss / (1024 * 1024);
576
+ var rssPct = totalMem > 0 ? (mem.rss / totalMem) * 100 : 0;
577
+ var systemMemPct = totalMem > 0 ? ((totalMem - os.freemem()) / totalMem) * 100 : 0;
578
+ var memPct = this.clampNumber(Math.max(rssPct, systemMemPct), 0, 100);
579
+ var lagMs = 0;
580
+ if (this._warmupLagMonitor) {
581
+ lagMs = this._warmupLagMonitor.percentile(99) / 1e6;
582
+ this._warmupLagMonitor.reset();
583
+ }
584
+ var cpuPressure = this.normalizePressure(cpuPct, this._warmupTargetCpuPct, this._warmupMaxCpuPct);
585
+ var memPressure = this.normalizePressure(memPct, this._warmupTargetMemPct, this._warmupMaxMemPct);
586
+ var lagPressure = this.normalizePressure(lagMs, this._warmupTargetLagMs, this._warmupMaxLagMs);
587
+ var pressure = Math.max(cpuPressure, memPressure, lagPressure);
588
+ this._warmupAdaptiveMetrics = {
589
+ cpuPct: cpuPct,
590
+ memPct: memPct,
591
+ rssMB: rssMB,
592
+ lagMs: lagMs,
593
+ pressure: pressure
594
+ };
595
+ this._warmupAdaptiveLastSampleAt = nowMs;
596
+ return this._warmupAdaptiveMetrics;
597
+ };
598
+ SubscriptionManager.prototype.updateAdaptiveScale = function (targetScale) {
599
+ var alpha = this.clampNumber(this._warmupAdaptiveAlpha, 0, 1);
600
+ if (!Number.isFinite(this._warmupAdaptiveScale)) {
601
+ this._warmupAdaptiveScale = targetScale;
602
+ return this._warmupAdaptiveScale;
603
+ }
604
+ this._warmupAdaptiveScale = this.clampNumber((alpha * targetScale) + ((1 - alpha) * this._warmupAdaptiveScale), 0, 1);
605
+ return this._warmupAdaptiveScale;
606
+ };
450
607
  SubscriptionManager.prototype.isWarmupGateActive = function () {
451
- return this._warmupEnabled && Date.now() < this._warmupEndsAtMs;
608
+ if (!this._warmupEnabled) {
609
+ return false;
610
+ }
611
+ return true;
452
612
  };
453
613
  SubscriptionManager.prototype.shouldQueueWarmup = function (publication, messageRoute) {
454
614
  if (!this.isWarmupGateActive()) {
@@ -528,7 +688,7 @@ var SubscriptionManager = /** @class */ (function () {
528
688
  if (!this._warmupTimer) {
529
689
  return;
530
690
  }
531
- if (this._warmupQueue.length > 0 || this._warmupInFlight > 0 || this.isWarmupGateActive()) {
691
+ if (this._warmupQueue.length > 0 || this._warmupInFlight > 0) {
532
692
  return;
533
693
  }
534
694
  clearInterval(this._warmupTimer);
@@ -536,7 +696,7 @@ var SubscriptionManager = /** @class */ (function () {
536
696
  };
537
697
  SubscriptionManager.prototype.processWarmupQueue = function () {
538
698
  return __awaiter(this, void 0, void 0, function () {
539
- var pendingTasks, now, processed, _loop_3, this_3, state_1;
699
+ var pendingTasks, now, limits, processed, _loop_3, this_3, state_1;
540
700
  var _a;
541
701
  return __generator(this, function (_b) {
542
702
  switch (_b.label) {
@@ -550,9 +710,9 @@ var SubscriptionManager = /** @class */ (function () {
550
710
  _b.trys.push([1, , 4, 5]);
551
711
  pendingTasks = [];
552
712
  now = Date.now();
553
- if (this._warmupEnabled && now >= this._warmupEndsAtMs) {
554
- this._warmupEnabled = false;
555
- console.log(new Date(), 'Sub Manager', 'Warmup window ended', {
713
+ if (this._warmupEnabled && now >= this._warmupEndsAtMs && !this._warmupWindowEndedLogged) {
714
+ this._warmupWindowEndedLogged = true;
715
+ console.log(new Date(), 'Sub Manager', 'Warmup minimum window ended', {
556
716
  queued: this._warmupQueue.length
557
717
  });
558
718
  }
@@ -560,6 +720,7 @@ var SubscriptionManager = /** @class */ (function () {
560
720
  this.stopWarmupTimerIfIdle();
561
721
  return [2 /*return*/];
562
722
  }
723
+ limits = this.getWarmupLimits(now);
563
724
  processed = 0;
564
725
  _loop_3 = function () {
565
726
  var item = this_3._warmupQueue.shift();
@@ -592,20 +753,19 @@ var SubscriptionManager = /** @class */ (function () {
592
753
  };
593
754
  this_3 = this;
594
755
  while (this._warmupQueue.length &&
595
- processed < this._warmupMaxPerTick &&
596
- this._warmupInFlight < this._warmupMaxInFlight) {
756
+ processed < limits.maxPerTick &&
757
+ this._warmupInFlight < limits.maxInFlight) {
597
758
  state_1 = _loop_3();
598
759
  if (state_1 === "break")
599
760
  break;
600
761
  }
762
+ this.logWarmupStatus('tick', limits);
601
763
  if (!pendingTasks.length) return [3 /*break*/, 3];
602
764
  return [4 /*yield*/, Promise.allSettled(pendingTasks)];
603
765
  case 2:
604
766
  _b.sent();
605
767
  _b.label = 3;
606
- case 3:
607
- this.logWarmupStatus('tick');
608
- return [3 /*break*/, 5];
768
+ case 3: return [3 /*break*/, 5];
609
769
  case 4:
610
770
  this._warmupProcessing = false;
611
771
  return [7 /*endfinally*/];
@@ -650,6 +810,21 @@ var SubscriptionManager = /** @class */ (function () {
650
810
  });
651
811
  });
652
812
  };
813
+ SubscriptionManager.prototype.getWarmupLimits = function (nowMs) {
814
+ var basePerTick = Math.max(1, this._warmupMaxPerTick);
815
+ var baseInFlight = Math.max(1, this._warmupMaxInFlight);
816
+ var targetPerTick = Math.max(basePerTick, this._warmupRampMaxPerTick || basePerTick);
817
+ var targetInFlight = Math.max(baseInFlight, this._warmupRampMaxInFlight || baseInFlight);
818
+ if (!this._warmupAdaptiveEnabled) {
819
+ return { maxPerTick: basePerTick, maxInFlight: baseInFlight, rampActive: false, rampProgress: 0 };
820
+ }
821
+ var metrics = this.sampleWarmupAdaptiveMetrics(nowMs);
822
+ var targetScale = this.clampNumber(1 - metrics.pressure, 0, 1);
823
+ var scale = this.updateAdaptiveScale(targetScale);
824
+ var maxPerTick = Math.max(1, (0, common_1.round)(basePerTick + (targetPerTick - basePerTick) * scale));
825
+ var maxInFlight = Math.max(1, (0, common_1.round)(baseInFlight + (targetInFlight - baseInFlight) * scale));
826
+ return { maxPerTick: maxPerTick, maxInFlight: maxInFlight, rampActive: true, rampProgress: scale, adaptiveScale: scale, metrics: metrics };
827
+ };
653
828
  SubscriptionManager.prototype.requeueWarmupItem = function (item) {
654
829
  if (this._warmupQueueKeys.has(item.key)) {
655
830
  return;
@@ -658,7 +833,8 @@ var SubscriptionManager = /** @class */ (function () {
658
833
  this._warmupQueue.push(item);
659
834
  this._warmupQueueKeys.add(item.key);
660
835
  };
661
- SubscriptionManager.prototype.logWarmupStatus = function (reason) {
836
+ SubscriptionManager.prototype.logWarmupStatus = function (reason, limits) {
837
+ var _a, _b, _c;
662
838
  if (!this._warmupLogIntervalMs) {
663
839
  return;
664
840
  }
@@ -667,14 +843,23 @@ var SubscriptionManager = /** @class */ (function () {
667
843
  return;
668
844
  }
669
845
  this._warmupLastLogMs = now;
846
+ var metrics = limits === null || limits === void 0 ? void 0 : limits.metrics;
670
847
  console.log(new Date(), 'Sub Manager', 'Warmup status', {
671
848
  reason: reason,
672
849
  enabled: this._warmupEnabled,
673
850
  endsInMs: this._warmupEnabled ? Math.max(0, this._warmupEndsAtMs - now) : 0,
674
851
  queued: this._warmupQueue.length,
675
852
  inFlight: this._warmupInFlight,
676
- maxPerTick: this._warmupMaxPerTick,
677
- maxInFlight: this._warmupMaxInFlight
853
+ maxPerTick: (_a = limits === null || limits === void 0 ? void 0 : limits.maxPerTick) !== null && _a !== void 0 ? _a : this._warmupMaxPerTick,
854
+ maxInFlight: (_b = limits === null || limits === void 0 ? void 0 : limits.maxInFlight) !== null && _b !== void 0 ? _b : this._warmupMaxInFlight,
855
+ rampActive: (_c = limits === null || limits === void 0 ? void 0 : limits.rampActive) !== null && _c !== void 0 ? _c : false,
856
+ rampProgress: typeof (limits === null || limits === void 0 ? void 0 : limits.rampProgress) === 'number' ? (0, common_1.round)(limits.rampProgress * 100) : 0,
857
+ adaptiveScale: typeof (limits === null || limits === void 0 ? void 0 : limits.adaptiveScale) === 'number' ? (0, common_1.round)(limits.adaptiveScale * 100) : 0,
858
+ cpuPct: metrics ? (0, common_1.round)(metrics.cpuPct) : undefined,
859
+ memPct: metrics ? (0, common_1.round)(metrics.memPct) : undefined,
860
+ rssMB: metrics ? (0, common_1.round)(metrics.rssMB) : undefined,
861
+ lagMs: metrics ? (0, common_1.round)(metrics.lagMs) : undefined,
862
+ pressure: metrics ? (0, common_1.round)(metrics.pressure * 100) : undefined
678
863
  });
679
864
  };
680
865
  SubscriptionManager.prototype.invalidatePubsCache = function (collection, type, documentId, document) {
@@ -894,6 +1079,141 @@ var SubscriptionManager = /** @class */ (function () {
894
1079
  this._lastRouteBySocket.set(socketId, { route: messageRoute, dateMs: messageDateMs });
895
1080
  return false;
896
1081
  };
1082
+ SubscriptionManager.prototype.getPublicationWorkerDispatcher = function () {
1083
+ var mainServer = resolveio_server_app_1.ResolveIOServer.getMainServer();
1084
+ return mainServer && typeof mainServer.getWorkerDispatcherManager === 'function'
1085
+ ? mainServer.getWorkerDispatcherManager()
1086
+ : null;
1087
+ };
1088
+ SubscriptionManager.prototype.shouldUsePublicationWorkers = function () {
1089
+ if (!this._publicationWorkersEnabled) {
1090
+ return false;
1091
+ }
1092
+ var dispatcher = this.getPublicationWorkerDispatcher();
1093
+ if (!dispatcher || !dispatcher.hasWorkers()) {
1094
+ return false;
1095
+ }
1096
+ if (this._publicationWorkerQueueLimit > 0) {
1097
+ var snapshot = dispatcher.getQueueSnapshot();
1098
+ if (snapshot.queueDepth >= this._publicationWorkerQueueLimit) {
1099
+ return false;
1100
+ }
1101
+ }
1102
+ return true;
1103
+ };
1104
+ SubscriptionManager.prototype.runPublicationViaWorker = function (sub, userId) {
1105
+ return __awaiter(this, void 0, void 0, function () {
1106
+ var dispatcher, response, meta, snapshot, error_3;
1107
+ return __generator(this, function (_a) {
1108
+ switch (_a.label) {
1109
+ case 0:
1110
+ if (!this.shouldUsePublicationWorkers()) {
1111
+ return [2 /*return*/, null];
1112
+ }
1113
+ dispatcher = this.getPublicationWorkerDispatcher();
1114
+ if (!dispatcher) {
1115
+ return [2 /*return*/, null];
1116
+ }
1117
+ _a.label = 1;
1118
+ case 1:
1119
+ _a.trys.push([1, 3, , 4]);
1120
+ return [4 /*yield*/, dispatcher.sendInternalPromiseRaw('runPublication', [
1121
+ sub.publication,
1122
+ sub.subscriptionData,
1123
+ userId
1124
+ ])];
1125
+ case 2:
1126
+ response = _a.sent();
1127
+ if (!response || response.error) {
1128
+ throw (response === null || response === void 0 ? void 0 : response.result) || new Error('Publication worker error');
1129
+ }
1130
+ if (!response.packedResult) {
1131
+ throw new Error('Publication worker missing packedResult');
1132
+ }
1133
+ meta = response.meta || {};
1134
+ snapshot = meta.snapshot ? (0, subscription_dependency_context_1.deserializeDependencySnapshot)(meta.snapshot) : undefined;
1135
+ return [2 /*return*/, {
1136
+ packedResult: response.packedResult,
1137
+ snapshot: snapshot,
1138
+ encoding: response.encoding || meta.encoding || 'msgpack',
1139
+ workerUsed: true
1140
+ }];
1141
+ case 3:
1142
+ error_3 = _a.sent();
1143
+ if (this._enableDebug) {
1144
+ console.log(new Date(), 'Sub Manager', 'Worker publication failed, falling back', sub.publication, (error_3 === null || error_3 === void 0 ? void 0 : error_3.message) || error_3);
1145
+ }
1146
+ return [2 /*return*/, null];
1147
+ case 4: return [2 /*return*/];
1148
+ }
1149
+ });
1150
+ });
1151
+ };
1152
+ SubscriptionManager.prototype.runPublicationLocally = function (sub, userId) {
1153
+ return __awaiter(this, void 0, void 0, function () {
1154
+ var pub, context, metadata, execution, _a;
1155
+ return __generator(this, function (_b) {
1156
+ switch (_b.label) {
1157
+ case 0:
1158
+ pub = this._publications[sub.publication];
1159
+ if (!pub) {
1160
+ throw new Error("Publication not found: ".concat(sub.publication));
1161
+ }
1162
+ context = Object.assign({}, this, SubscriptionManager.prototype);
1163
+ metadata = {
1164
+ publication: sub.publication,
1165
+ subscriptionData: sub.subscriptionData
1166
+ };
1167
+ if (!pub.user_specific) return [3 /*break*/, 2];
1168
+ return [4 /*yield*/, (0, subscription_dependency_context_1.withDependencyTracking)(function () {
1169
+ var _a;
1170
+ return (_a = pub.function).call.apply(_a, __spreadArray([context, userId || ''], __read(sub.subscriptionData), false));
1171
+ }, Object.assign({}, metadata, { userId: userId }))];
1172
+ case 1:
1173
+ _a = _b.sent();
1174
+ return [3 /*break*/, 4];
1175
+ case 2: return [4 /*yield*/, (0, subscription_dependency_context_1.withDependencyTracking)(function () {
1176
+ var _a;
1177
+ return (_a = pub.function).call.apply(_a, __spreadArray([context], __read(sub.subscriptionData), false));
1178
+ }, metadata)];
1179
+ case 3:
1180
+ _a = _b.sent();
1181
+ _b.label = 4;
1182
+ case 4:
1183
+ execution = _a;
1184
+ return [2 /*return*/, {
1185
+ result: execution.result,
1186
+ packedResult: this.packCachePayload(execution.result),
1187
+ snapshot: execution.snapshot,
1188
+ encoding: 'msgpack',
1189
+ workerUsed: false
1190
+ }];
1191
+ }
1192
+ });
1193
+ });
1194
+ };
1195
+ SubscriptionManager.prototype.runPublicationExecution = function (sub, userId) {
1196
+ return __awaiter(this, void 0, void 0, function () {
1197
+ var pub, effectiveUserId, workerExecution;
1198
+ return __generator(this, function (_a) {
1199
+ switch (_a.label) {
1200
+ case 0:
1201
+ pub = this._publications[sub.publication];
1202
+ if (!pub) {
1203
+ throw new Error("Publication not found: ".concat(sub.publication));
1204
+ }
1205
+ effectiveUserId = pub.user_specific ? userId : undefined;
1206
+ return [4 /*yield*/, this.runPublicationViaWorker(sub, effectiveUserId)];
1207
+ case 1:
1208
+ workerExecution = _a.sent();
1209
+ if (workerExecution) {
1210
+ return [2 /*return*/, workerExecution];
1211
+ }
1212
+ return [2 /*return*/, this.runPublicationLocally(sub, effectiveUserId)];
1213
+ }
1214
+ });
1215
+ });
1216
+ };
897
1217
  SubscriptionManager.prototype.sendDataToAllWithRetry = function (sub, collection, type) {
898
1218
  return __awaiter(this, void 0, void 0, function () {
899
1219
  return __generator(this, function (_a) {
@@ -964,6 +1284,12 @@ var SubscriptionManager = /** @class */ (function () {
964
1284
  SubscriptionManager.prototype.publications = function (method) {
965
1285
  this._publications = Object.assign(this._publications, method);
966
1286
  };
1287
+ SubscriptionManager.prototype.getPublication = function (publication) {
1288
+ return this._publications[publication];
1289
+ };
1290
+ SubscriptionManager.prototype.getPublications = function () {
1291
+ return this._publications;
1292
+ };
967
1293
  // Throttled `loggedInLatency` method
968
1294
  SubscriptionManager.prototype.loggedInLatency = function (ws) {
969
1295
  var _a, _b, _c, _d;
@@ -1020,7 +1346,7 @@ var SubscriptionManager = /** @class */ (function () {
1020
1346
  // Method to flush buffered latency updates in bulk
1021
1347
  SubscriptionManager.prototype.flushThrottledLatencyUpdates = function () {
1022
1348
  return __awaiter(this, void 0, void 0, function () {
1023
- var pendingEntries, updates, error_3, pendingEntries_1, pendingEntries_1_1, _a, id_ws, payload, current;
1349
+ var pendingEntries, updates, error_4, pendingEntries_1, pendingEntries_1_1, _a, id_ws, payload, current;
1024
1350
  var e_3, _b;
1025
1351
  var _this = this;
1026
1352
  return __generator(this, function (_c) {
@@ -1055,7 +1381,7 @@ var SubscriptionManager = /** @class */ (function () {
1055
1381
  }
1056
1382
  return [3 /*break*/, 5];
1057
1383
  case 3:
1058
- error_3 = _c.sent();
1384
+ error_4 = _c.sent();
1059
1385
  try {
1060
1386
  for (pendingEntries_1 = __values(pendingEntries), pendingEntries_1_1 = pendingEntries_1.next(); !pendingEntries_1_1.done; pendingEntries_1_1 = pendingEntries_1.next()) {
1061
1387
  _a = __read(pendingEntries_1_1.value, 2), id_ws = _a[0], payload = _a[1];
@@ -1072,7 +1398,7 @@ var SubscriptionManager = /** @class */ (function () {
1072
1398
  }
1073
1399
  finally { if (e_3) throw e_3.error; }
1074
1400
  }
1075
- console.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error_3);
1401
+ console.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error_4);
1076
1402
  return [3 /*break*/, 5];
1077
1403
  case 4:
1078
1404
  this._latencyFlushInProgress = false;
@@ -1367,6 +1693,18 @@ var SubscriptionManager = /** @class */ (function () {
1367
1693
  }
1368
1694
  return 0;
1369
1695
  };
1696
+ SubscriptionManager.prototype.parsePositiveFloat = function (value) {
1697
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
1698
+ return value;
1699
+ }
1700
+ if (typeof value === 'string' && value.trim().length) {
1701
+ var parsed = parseFloat(value);
1702
+ if (Number.isFinite(parsed) && parsed > 0) {
1703
+ return parsed;
1704
+ }
1705
+ }
1706
+ return 0;
1707
+ };
1370
1708
  SubscriptionManager.prototype.isChangeStreamUnsupported = function (error) {
1371
1709
  var code = typeof (error === null || error === void 0 ? void 0 : error.code) === 'number' ? error.code : null;
1372
1710
  var codeName = typeof (error === null || error === void 0 ? void 0 : error.codeName) === 'string' ? error.codeName.toLowerCase() : '';
@@ -1486,7 +1824,7 @@ var SubscriptionManager = /** @class */ (function () {
1486
1824
  };
1487
1825
  SubscriptionManager.prototype.loadResumeToken = function () {
1488
1826
  return __awaiter(this, void 0, void 0, function () {
1489
- var db, doc, error_4;
1827
+ var db, doc, error_5;
1490
1828
  return __generator(this, function (_a) {
1491
1829
  switch (_a.label) {
1492
1830
  case 0:
@@ -1500,8 +1838,8 @@ var SubscriptionManager = /** @class */ (function () {
1500
1838
  doc = _a.sent();
1501
1839
  return [2 /*return*/, (doc === null || doc === void 0 ? void 0 : doc.token) || null];
1502
1840
  case 2:
1503
- error_4 = _a.sent();
1504
- console.log(new Date(), 'Sub Manager', 'Failed to load oplog resume token', error_4);
1841
+ error_5 = _a.sent();
1842
+ console.log(new Date(), 'Sub Manager', 'Failed to load oplog resume token', error_5);
1505
1843
  return [2 /*return*/, null];
1506
1844
  case 3: return [2 /*return*/];
1507
1845
  }
@@ -1510,7 +1848,7 @@ var SubscriptionManager = /** @class */ (function () {
1510
1848
  };
1511
1849
  SubscriptionManager.prototype.saveResumeToken = function (token) {
1512
1850
  return __awaiter(this, void 0, void 0, function () {
1513
- var db, error_5;
1851
+ var db, error_6;
1514
1852
  return __generator(this, function (_a) {
1515
1853
  switch (_a.label) {
1516
1854
  case 0:
@@ -1529,8 +1867,8 @@ var SubscriptionManager = /** @class */ (function () {
1529
1867
  _a.sent();
1530
1868
  return [3 /*break*/, 4];
1531
1869
  case 3:
1532
- error_5 = _a.sent();
1533
- console.log(new Date(), 'Sub Manager', 'Failed to persist oplog resume token', error_5);
1870
+ error_6 = _a.sent();
1871
+ console.log(new Date(), 'Sub Manager', 'Failed to persist oplog resume token', error_6);
1534
1872
  return [3 /*break*/, 4];
1535
1873
  case 4: return [2 /*return*/];
1536
1874
  }
@@ -1539,7 +1877,7 @@ var SubscriptionManager = /** @class */ (function () {
1539
1877
  };
1540
1878
  SubscriptionManager.prototype.clearResumeToken = function () {
1541
1879
  return __awaiter(this, void 0, void 0, function () {
1542
- var db, error_6;
1880
+ var db, error_7;
1543
1881
  return __generator(this, function (_a) {
1544
1882
  switch (_a.label) {
1545
1883
  case 0:
@@ -1553,8 +1891,8 @@ var SubscriptionManager = /** @class */ (function () {
1553
1891
  _a.sent();
1554
1892
  return [3 /*break*/, 3];
1555
1893
  case 2:
1556
- error_6 = _a.sent();
1557
- console.log(new Date(), 'Sub Manager', 'Failed to clear oplog resume token', error_6);
1894
+ error_7 = _a.sent();
1895
+ console.log(new Date(), 'Sub Manager', 'Failed to clear oplog resume token', error_7);
1558
1896
  return [3 /*break*/, 3];
1559
1897
  case 3: return [2 /*return*/];
1560
1898
  }
@@ -1625,7 +1963,7 @@ var SubscriptionManager = /** @class */ (function () {
1625
1963
  };
1626
1964
  SubscriptionManager.prototype.fullResyncSubscriptions = function (reason) {
1627
1965
  return __awaiter(this, void 0, void 0, function () {
1628
- var subs, subs_1, subs_1_1, sub, pub, _a, _b, client, ws, _c, e_4_1, e_5_1, error_7;
1966
+ var subs, subs_1, subs_1_1, sub, pub, _a, _b, client, ws, _c, e_4_1, e_5_1, error_8;
1629
1967
  var e_5, _d, e_4, _e;
1630
1968
  var _f, _g, _h, _j, _k;
1631
1969
  return __generator(this, function (_l) {
@@ -1723,8 +2061,8 @@ var SubscriptionManager = /** @class */ (function () {
1723
2061
  return [7 /*endfinally*/];
1724
2062
  case 19: return [3 /*break*/, 21];
1725
2063
  case 20:
1726
- error_7 = _l.sent();
1727
- console.log(new Date(), 'Sub Manager', 'Full resync failed', reason, error_7);
2064
+ error_8 = _l.sent();
2065
+ console.log(new Date(), 'Sub Manager', 'Full resync failed', reason, error_8);
1728
2066
  return [3 /*break*/, 21];
1729
2067
  case 21: return [2 /*return*/];
1730
2068
  }
@@ -1734,7 +2072,7 @@ var SubscriptionManager = /** @class */ (function () {
1734
2072
  // Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)
1735
2073
  SubscriptionManager.prototype.tailOpLog = function (resumeToken) {
1736
2074
  return __awaiter(this, void 0, void 0, function () {
1737
- var watchDatabases, pipeline, lastResumeToken_1, startedWithResumeToken, error_8, innerError_1, error_9;
2075
+ var watchDatabases, pipeline, lastResumeToken_1, startedWithResumeToken, error_9, innerError_1, error_10;
1738
2076
  var _this = this;
1739
2077
  return __generator(this, function (_a) {
1740
2078
  switch (_a.label) {
@@ -1795,9 +2133,9 @@ var SubscriptionManager = /** @class */ (function () {
1795
2133
  startedWithResumeToken = true;
1796
2134
  return [3 /*break*/, 16];
1797
2135
  case 5:
1798
- error_8 = _a.sent();
1799
- if (!this.isChangeStreamUnsupported(error_8)) return [3 /*break*/, 7];
1800
- return [4 /*yield*/, this.enableLocalOplogFallback('change-stream-unsupported', error_8)];
2136
+ error_9 = _a.sent();
2137
+ if (!this.isChangeStreamUnsupported(error_9)) return [3 /*break*/, 7];
2138
+ return [4 /*yield*/, this.enableLocalOplogFallback('change-stream-unsupported', error_9)];
1801
2139
  case 6:
1802
2140
  _a.sent();
1803
2141
  return [2 /*return*/];
@@ -1813,7 +2151,7 @@ var SubscriptionManager = /** @class */ (function () {
1813
2151
  case 10:
1814
2152
  _a.sent();
1815
2153
  lastResumeToken_1 = null;
1816
- console.log(new Date(), 'oplog resumeAfter failed, starting fresh', error_8);
2154
+ console.log(new Date(), 'oplog resumeAfter failed, starting fresh', error_9);
1817
2155
  _a.label = 11;
1818
2156
  case 11:
1819
2157
  _a.trys.push([11, 12, , 15]);
@@ -1837,13 +2175,13 @@ var SubscriptionManager = /** @class */ (function () {
1837
2175
  this._oplog$ = resolveio_server_app_1.ResolveIOServer.getMongoConnection().watch(pipeline, { fullDocument: 'updateLookup' });
1838
2176
  return [3 /*break*/, 21];
1839
2177
  case 18:
1840
- error_9 = _a.sent();
1841
- if (!this.isChangeStreamUnsupported(error_9)) return [3 /*break*/, 20];
1842
- return [4 /*yield*/, this.enableLocalOplogFallback('change-stream-unsupported', error_9)];
2178
+ error_10 = _a.sent();
2179
+ if (!this.isChangeStreamUnsupported(error_10)) return [3 /*break*/, 20];
2180
+ return [4 /*yield*/, this.enableLocalOplogFallback('change-stream-unsupported', error_10)];
1843
2181
  case 19:
1844
2182
  _a.sent();
1845
2183
  return [2 /*return*/];
1846
- case 20: throw error_9;
2184
+ case 20: throw error_10;
1847
2185
  case 21:
1848
2186
  console.log(new Date(), 'oplog started', startedWithResumeToken ? '(resumeAfter)' : '');
1849
2187
  this._oplog$.on('change', function (doc) { return __awaiter(_this, void 0, void 0, function () {
@@ -2093,7 +2431,7 @@ var SubscriptionManager = /** @class */ (function () {
2093
2431
  };
2094
2432
  SubscriptionManager.prototype.processSubscription = function (sub, ws, messageId) {
2095
2433
  return __awaiter(this, void 0, void 0, function () {
2096
- var cacheData, serverRes, _a;
2434
+ var cachedRaw, cachedBuffer, cacheData, serverRes, _a;
2097
2435
  return __generator(this, function (_b) {
2098
2436
  switch (_b.label) {
2099
2437
  case 0:
@@ -2102,19 +2440,29 @@ var SubscriptionManager = /** @class */ (function () {
2102
2440
  _b.label = 1;
2103
2441
  case 1:
2104
2442
  _b.trys.push([1, 2, , 4]);
2105
- cacheData = this.decodeCachePayload(this._nodeCache.get(sub.cacheId));
2106
- if (cacheData === null || cacheData === undefined) {
2107
- throw new Error('cache-miss');
2443
+ cachedRaw = this._nodeCache.get(sub.cacheId);
2444
+ cachedBuffer = this.getCacheBuffer(cachedRaw);
2445
+ if (cachedBuffer && cachedBuffer.byteLength) {
2446
+ if (this._enableDebug) {
2447
+ console.log(new Date(), 'Process Sub, Cache (packed)', sub.publication);
2448
+ }
2449
+ this._websocketManager.sendPackedBuffer(ws, messageId, false, cachedBuffer, 'msgpack');
2108
2450
  }
2109
- serverRes = {
2110
- messageId: messageId,
2111
- hasError: false,
2112
- data: cacheData
2113
- };
2114
- if (this._enableDebug) {
2115
- console.log(new Date(), 'Process Sub, Cache', sub.publication);
2451
+ else {
2452
+ cacheData = this.decodeCachePayload(cachedRaw);
2453
+ if (cacheData === null || cacheData === undefined) {
2454
+ throw new Error('cache-miss');
2455
+ }
2456
+ serverRes = {
2457
+ messageId: messageId,
2458
+ hasError: false,
2459
+ data: cacheData
2460
+ };
2461
+ if (this._enableDebug) {
2462
+ console.log(new Date(), 'Process Sub, Cache', sub.publication);
2463
+ }
2464
+ this.sendWS(ws, serverRes);
2116
2465
  }
2117
- this.sendWS(ws, serverRes);
2118
2466
  return [3 /*break*/, 4];
2119
2467
  case 2:
2120
2468
  _a = _b.sent();
@@ -2156,7 +2504,6 @@ var SubscriptionManager = /** @class */ (function () {
2156
2504
  SubscriptionManager.prototype.sendDataToOne = function (ws, messageId, sub, collection, type) {
2157
2505
  return __awaiter(this, void 0, void 0, function () {
2158
2506
  var startMs, monitor, dependencySnapshot, res, execution, serverRes, err_1, _a, normalizedError, correlationId, serverRes, errorPayload, durationMs;
2159
- var _this = this;
2160
2507
  var _b;
2161
2508
  return __generator(this, function (_c) {
2162
2509
  switch (_c.label) {
@@ -2167,24 +2514,23 @@ var SubscriptionManager = /** @class */ (function () {
2167
2514
  case 1:
2168
2515
  _c.trys.push([1, 3, 5, 7]);
2169
2516
  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));
2170
- return [4 /*yield*/, (0, subscription_dependency_context_1.withDependencyTracking)(function () {
2171
- var _a;
2172
- return (_a = _this._publications[sub.publication].function).call.apply(_a, __spreadArray([Object.assign({}, _this, SubscriptionManager.prototype), ws['id_user']], __read(sub.subscriptionData), false));
2173
- }, {
2174
- publication: sub.publication,
2175
- subscriptionData: sub.subscriptionData
2176
- })];
2517
+ return [4 /*yield*/, this.runPublicationExecution(sub, ws['id_user'])];
2177
2518
  case 2:
2178
2519
  execution = _c.sent();
2179
2520
  res = execution.result;
2180
2521
  dependencySnapshot = execution.snapshot;
2181
2522
  this.updateSubscriptionDependencies(sub, dependencySnapshot);
2182
- serverRes = {
2183
- messageId: messageId,
2184
- hasError: false,
2185
- data: res
2186
- };
2187
- this.sendWS(ws, serverRes);
2523
+ if (execution.packedResult) {
2524
+ this._websocketManager.sendPackedBuffer(ws, messageId, false, execution.packedResult, execution.encoding || 'msgpack');
2525
+ }
2526
+ else {
2527
+ serverRes = {
2528
+ messageId: messageId,
2529
+ hasError: false,
2530
+ data: res
2531
+ };
2532
+ this.sendWS(ws, serverRes);
2533
+ }
2188
2534
  return [3 /*break*/, 7];
2189
2535
  case 3:
2190
2536
  err_1 = _c.sent();
@@ -2257,10 +2603,9 @@ var SubscriptionManager = /** @class */ (function () {
2257
2603
  return __awaiter(this, void 0, void 0, function () {
2258
2604
  var subIndex, startMs, monitor, res, dependencySnapshot, execution, packedRes, shouldCache, cachedBuffer, isSame, _a, _b, client, ws, serverRes, _c, _d, client, ws, serverRes, nodeCacheSize, deleteCount, subArr, zz, err_2, _e, normalizedError, correlationId, _f, _g, client, ws, serverRes, errorPayload, durationMs;
2259
2605
  var e_6, _h, e_7, _j, e_8, _k;
2260
- var _this = this;
2261
- var _l;
2262
- return __generator(this, function (_m) {
2263
- switch (_m.label) {
2606
+ var _l, _m;
2607
+ return __generator(this, function (_o) {
2608
+ switch (_o.label) {
2264
2609
  case 0:
2265
2610
  if (!!sub.clients.length) return [3 /*break*/, 1];
2266
2611
  if (sub.cacheId) {
@@ -2277,25 +2622,19 @@ var SubscriptionManager = /** @class */ (function () {
2277
2622
  monitor = this._monitorManagerFunction.startMonitorFunction('Publication', sub.publication, '', '', sub.subscriptionData);
2278
2623
  res = void 0;
2279
2624
  dependencySnapshot = void 0;
2280
- _m.label = 2;
2625
+ _o.label = 2;
2281
2626
  case 2:
2282
- _m.trys.push([2, 4, 6, 8]);
2627
+ _o.trys.push([2, 4, 6, 8]);
2283
2628
  if (sub.publication !== 'superadminAPM' && sub.publication !== 'loggedInUsers') {
2284
2629
  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));
2285
2630
  }
2286
- return [4 /*yield*/, (0, subscription_dependency_context_1.withDependencyTracking)(function () {
2287
- var _a;
2288
- return (_a = _this._publications[sub.publication].function).call.apply(_a, __spreadArray([Object.assign({}, _this, SubscriptionManager.prototype)], __read(sub.subscriptionData), false));
2289
- }, {
2290
- publication: sub.publication,
2291
- subscriptionData: sub.subscriptionData
2292
- })];
2631
+ return [4 /*yield*/, this.runPublicationExecution(sub)];
2293
2632
  case 3:
2294
- execution = _m.sent();
2633
+ execution = _o.sent();
2295
2634
  res = execution.result;
2296
2635
  dependencySnapshot = execution.snapshot;
2297
2636
  this.updateSubscriptionDependencies(sub, dependencySnapshot);
2298
- packedRes = this.packCachePayload(res);
2637
+ packedRes = (_l = execution.packedResult) !== null && _l !== void 0 ? _l : this.packCachePayload(res);
2299
2638
  shouldCache = this.shouldCachePayload(sub, packedRes);
2300
2639
  if (sub.cacheId) {
2301
2640
  cachedBuffer = this.getCacheBuffer(this._nodeCache.get(sub.cacheId));
@@ -2306,12 +2645,17 @@ var SubscriptionManager = /** @class */ (function () {
2306
2645
  client = _b.value;
2307
2646
  ws = this._websocketManager.getWebSocket(client.id_socket);
2308
2647
  if (ws && ws.readyState === ws.OPEN) {
2309
- serverRes = {
2310
- messageId: client.messageId,
2311
- hasError: false,
2312
- data: res
2313
- };
2314
- this.sendWS(ws, serverRes);
2648
+ if (packedRes) {
2649
+ this._websocketManager.sendPackedBuffer(ws, client.messageId, false, packedRes, execution.encoding || 'msgpack');
2650
+ }
2651
+ else {
2652
+ serverRes = {
2653
+ messageId: client.messageId,
2654
+ hasError: false,
2655
+ data: res
2656
+ };
2657
+ this.sendWS(ws, serverRes);
2658
+ }
2315
2659
  }
2316
2660
  }
2317
2661
  }
@@ -2344,12 +2688,17 @@ var SubscriptionManager = /** @class */ (function () {
2344
2688
  client = _d.value;
2345
2689
  ws = this._websocketManager.getWebSocket(client.id_socket);
2346
2690
  if (ws && ws.readyState === ws.OPEN) {
2347
- serverRes = {
2348
- messageId: client.messageId,
2349
- hasError: false,
2350
- data: res
2351
- };
2352
- this.sendWS(ws, serverRes);
2691
+ if (packedRes) {
2692
+ this._websocketManager.sendPackedBuffer(ws, client.messageId, false, packedRes, execution.encoding || 'msgpack');
2693
+ }
2694
+ else {
2695
+ serverRes = {
2696
+ messageId: client.messageId,
2697
+ hasError: false,
2698
+ data: res
2699
+ };
2700
+ this.sendWS(ws, serverRes);
2701
+ }
2353
2702
  }
2354
2703
  }
2355
2704
  }
@@ -2393,7 +2742,7 @@ var SubscriptionManager = /** @class */ (function () {
2393
2742
  }
2394
2743
  return [3 /*break*/, 8];
2395
2744
  case 4:
2396
- err_2 = _m.sent();
2745
+ err_2 = _o.sent();
2397
2746
  _e = (0, error_tracking_1.ensureErrorWithCorrelation)(err_2), normalizedError = _e.error, correlationId = _e.correlationId;
2398
2747
  try {
2399
2748
  for (_f = __values(sub.clients), _g = _f.next(); !_g.done; _g = _f.next()) {
@@ -2433,7 +2782,7 @@ var SubscriptionManager = /** @class */ (function () {
2433
2782
  return [4 /*yield*/, error_reporter_1.ErrorReporter.report({
2434
2783
  sourceApp: 'subscription-manager',
2435
2784
  message: 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
2436
- environment: (_l = this.serverConfig) === null || _l === void 0 ? void 0 : _l.ROOT_URL,
2785
+ environment: (_m = this.serverConfig) === null || _m === void 0 ? void 0 : _m.ROOT_URL,
2437
2786
  clientSlug: resolveio_server_app_1.ResolveIOServer.getClientName(),
2438
2787
  clientName: this.serverConfig['CLIENT_NAME'],
2439
2788
  stack: normalizedError === null || normalizedError === void 0 ? void 0 : normalizedError.stack,
@@ -2446,7 +2795,7 @@ var SubscriptionManager = /** @class */ (function () {
2446
2795
  correlationId: correlationId
2447
2796
  })];
2448
2797
  case 5:
2449
- _m.sent();
2798
+ _o.sent();
2450
2799
  return [3 /*break*/, 8];
2451
2800
  case 6:
2452
2801
  durationMs = Date.now() - startMs;
@@ -2464,7 +2813,7 @@ var SubscriptionManager = /** @class */ (function () {
2464
2813
  }
2465
2814
  return [4 /*yield*/, this._monitorManagerFunction.finishMonitorFunction(monitor)];
2466
2815
  case 7:
2467
- _m.sent();
2816
+ _o.sent();
2468
2817
  return [7 /*endfinally*/];
2469
2818
  case 8: return [2 /*return*/];
2470
2819
  }