@resolveio/server-lib 20.14.20 → 20.14.23

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']);
@@ -406,15 +440,33 @@ var SubscriptionManager = /** @class */ (function () {
406
440
  this._warmupEnabled = false;
407
441
  return;
408
442
  }
409
- var durationMs = warmupMs || 60000;
443
+ var durationMs = warmupMs;
410
444
  this._warmupEnabled = true;
411
- this._warmupEndsAtMs = Date.now() + durationMs;
445
+ this._warmupEndsAtMs = durationMs > 0 ? Date.now() + durationMs : 0;
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(',')
@@ -423,14 +475,32 @@ var SubscriptionManager = /** @class */ (function () {
423
475
  }
424
476
  this.startWarmupTimer();
425
477
  console.log(new Date(), 'Sub Manager', 'Warmup enabled', {
426
- durationMs: durationMs,
478
+ minDurationMs: durationMs,
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,120 @@ 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.maybeDisableWarmup = function (nowMs) {
540
+ if (!this._warmupEnabled) {
541
+ return;
542
+ }
543
+ if (this._warmupQueue.length > 0 || this._warmupInFlight > 0) {
544
+ return;
545
+ }
546
+ if (this._warmupEndsAtMs > 0 && nowMs < this._warmupEndsAtMs) {
547
+ return;
548
+ }
549
+ this._warmupEnabled = false;
550
+ this._warmupAdaptiveScale = 0;
551
+ this._warmupAdaptiveLastSampleAt = 0;
552
+ if (this._warmupLagMonitor) {
553
+ this._warmupLagMonitor.disable();
554
+ this._warmupLagMonitor = null;
555
+ }
556
+ console.log(new Date(), 'Sub Manager', 'Warmup complete', {
557
+ queued: this._warmupQueue.length,
558
+ inFlight: this._warmupInFlight
559
+ });
560
+ };
561
+ SubscriptionManager.prototype.normalizePressure = function (value, target, max) {
562
+ if (!Number.isFinite(value)) {
563
+ return 0;
564
+ }
565
+ if (max <= target) {
566
+ return value > target ? 1 : 0;
567
+ }
568
+ var pressure = (value - target) / (max - target);
569
+ return this.clampNumber(pressure, 0, 1);
570
+ };
571
+ SubscriptionManager.prototype.sampleCpuPercent = function () {
572
+ var _a, _b, _c;
573
+ var usage = process.cpuUsage();
574
+ var now = process.hrtime.bigint();
575
+ var elapsedMicros = Number(now - this._warmupCpuSampleAt) / 1000;
576
+ var usageDelta = (usage.user - this._warmupCpuSampleUsage.user) + (usage.system - this._warmupCpuSampleUsage.system);
577
+ this._warmupCpuSampleUsage = usage;
578
+ this._warmupCpuSampleAt = now;
579
+ if (!elapsedMicros || elapsedMicros <= 0) {
580
+ return (_b = (_a = this._warmupAdaptiveMetrics) === null || _a === void 0 ? void 0 : _a.cpuPct) !== null && _b !== void 0 ? _b : 0;
581
+ }
582
+ var cores = Math.max(1, ((_c = os.cpus()) === null || _c === void 0 ? void 0 : _c.length) || 1);
583
+ var cpuPct = (usageDelta / (elapsedMicros * cores)) * 100;
584
+ return this.clampNumber(cpuPct, 0, 100);
585
+ };
586
+ SubscriptionManager.prototype.sampleWarmupAdaptiveMetrics = function (nowMs) {
587
+ if (!this._warmupAdaptiveEnabled) {
588
+ return this._warmupAdaptiveMetrics;
589
+ }
590
+ if (this._warmupAdaptiveLastSampleAt && (nowMs - this._warmupAdaptiveLastSampleAt) < this._warmupAdaptiveSampleMs) {
591
+ return this._warmupAdaptiveMetrics;
592
+ }
593
+ this.ensureWarmupAdaptiveMonitor();
594
+ var cpuPct = this.sampleCpuPercent();
595
+ var mem = process.memoryUsage();
596
+ var totalMem = os.totalmem();
597
+ var rssMB = mem.rss / (1024 * 1024);
598
+ var rssPct = totalMem > 0 ? (mem.rss / totalMem) * 100 : 0;
599
+ var systemMemPct = totalMem > 0 ? ((totalMem - os.freemem()) / totalMem) * 100 : 0;
600
+ var memPct = this.clampNumber(Math.max(rssPct, systemMemPct), 0, 100);
601
+ var lagMs = 0;
602
+ if (this._warmupLagMonitor) {
603
+ lagMs = this._warmupLagMonitor.percentile(99) / 1e6;
604
+ this._warmupLagMonitor.reset();
605
+ }
606
+ var cpuPressure = this.normalizePressure(cpuPct, this._warmupTargetCpuPct, this._warmupMaxCpuPct);
607
+ var memPressure = this.normalizePressure(memPct, this._warmupTargetMemPct, this._warmupMaxMemPct);
608
+ var lagPressure = this.normalizePressure(lagMs, this._warmupTargetLagMs, this._warmupMaxLagMs);
609
+ var pressure = Math.max(cpuPressure, memPressure, lagPressure);
610
+ this._warmupAdaptiveMetrics = {
611
+ cpuPct: cpuPct,
612
+ memPct: memPct,
613
+ rssMB: rssMB,
614
+ lagMs: lagMs,
615
+ pressure: pressure
616
+ };
617
+ this._warmupAdaptiveLastSampleAt = nowMs;
618
+ return this._warmupAdaptiveMetrics;
619
+ };
620
+ SubscriptionManager.prototype.updateAdaptiveScale = function (targetScale) {
621
+ var alpha = this.clampNumber(this._warmupAdaptiveAlpha, 0, 1);
622
+ if (!Number.isFinite(this._warmupAdaptiveScale)) {
623
+ this._warmupAdaptiveScale = targetScale;
624
+ return this._warmupAdaptiveScale;
625
+ }
626
+ this._warmupAdaptiveScale = this.clampNumber((alpha * targetScale) + ((1 - alpha) * this._warmupAdaptiveScale), 0, 1);
627
+ return this._warmupAdaptiveScale;
628
+ };
450
629
  SubscriptionManager.prototype.isWarmupGateActive = function () {
451
- return this._warmupEnabled && Date.now() < this._warmupEndsAtMs;
630
+ if (!this._warmupEnabled) {
631
+ return false;
632
+ }
633
+ return true;
452
634
  };
453
635
  SubscriptionManager.prototype.shouldQueueWarmup = function (publication, messageRoute) {
454
636
  if (!this.isWarmupGateActive()) {
@@ -528,15 +710,16 @@ var SubscriptionManager = /** @class */ (function () {
528
710
  if (!this._warmupTimer) {
529
711
  return;
530
712
  }
531
- if (this._warmupQueue.length > 0 || this._warmupInFlight > 0 || this.isWarmupGateActive()) {
713
+ if (this._warmupQueue.length > 0 || this._warmupInFlight > 0) {
532
714
  return;
533
715
  }
534
716
  clearInterval(this._warmupTimer);
535
717
  this._warmupTimer = null;
718
+ this.maybeDisableWarmup(Date.now());
536
719
  };
537
720
  SubscriptionManager.prototype.processWarmupQueue = function () {
538
721
  return __awaiter(this, void 0, void 0, function () {
539
- var pendingTasks, now, processed, _loop_3, this_3, state_1;
722
+ var pendingTasks, now, limits, processed, _loop_3, this_3, state_1;
540
723
  var _a;
541
724
  return __generator(this, function (_b) {
542
725
  switch (_b.label) {
@@ -550,9 +733,9 @@ var SubscriptionManager = /** @class */ (function () {
550
733
  _b.trys.push([1, , 4, 5]);
551
734
  pendingTasks = [];
552
735
  now = Date.now();
553
- if (this._warmupEnabled && now >= this._warmupEndsAtMs) {
554
- this._warmupEnabled = false;
555
- console.log(new Date(), 'Sub Manager', 'Warmup window ended', {
736
+ if (this._warmupEnabled && this._warmupEndsAtMs > 0 && now >= this._warmupEndsAtMs && !this._warmupWindowEndedLogged) {
737
+ this._warmupWindowEndedLogged = true;
738
+ console.log(new Date(), 'Sub Manager', 'Warmup minimum window ended', {
556
739
  queued: this._warmupQueue.length
557
740
  });
558
741
  }
@@ -560,6 +743,7 @@ var SubscriptionManager = /** @class */ (function () {
560
743
  this.stopWarmupTimerIfIdle();
561
744
  return [2 /*return*/];
562
745
  }
746
+ limits = this.getWarmupLimits(now);
563
747
  processed = 0;
564
748
  _loop_3 = function () {
565
749
  var item = this_3._warmupQueue.shift();
@@ -592,20 +776,19 @@ var SubscriptionManager = /** @class */ (function () {
592
776
  };
593
777
  this_3 = this;
594
778
  while (this._warmupQueue.length &&
595
- processed < this._warmupMaxPerTick &&
596
- this._warmupInFlight < this._warmupMaxInFlight) {
779
+ processed < limits.maxPerTick &&
780
+ this._warmupInFlight < limits.maxInFlight) {
597
781
  state_1 = _loop_3();
598
782
  if (state_1 === "break")
599
783
  break;
600
784
  }
785
+ this.logWarmupStatus('tick', limits);
601
786
  if (!pendingTasks.length) return [3 /*break*/, 3];
602
787
  return [4 /*yield*/, Promise.allSettled(pendingTasks)];
603
788
  case 2:
604
789
  _b.sent();
605
790
  _b.label = 3;
606
- case 3:
607
- this.logWarmupStatus('tick');
608
- return [3 /*break*/, 5];
791
+ case 3: return [3 /*break*/, 5];
609
792
  case 4:
610
793
  this._warmupProcessing = false;
611
794
  return [7 /*endfinally*/];
@@ -650,6 +833,21 @@ var SubscriptionManager = /** @class */ (function () {
650
833
  });
651
834
  });
652
835
  };
836
+ SubscriptionManager.prototype.getWarmupLimits = function (nowMs) {
837
+ var basePerTick = Math.max(1, this._warmupMaxPerTick);
838
+ var baseInFlight = Math.max(1, this._warmupMaxInFlight);
839
+ var targetPerTick = Math.max(basePerTick, this._warmupRampMaxPerTick || basePerTick);
840
+ var targetInFlight = Math.max(baseInFlight, this._warmupRampMaxInFlight || baseInFlight);
841
+ if (!this._warmupAdaptiveEnabled) {
842
+ return { maxPerTick: basePerTick, maxInFlight: baseInFlight, rampActive: false, rampProgress: 0 };
843
+ }
844
+ var metrics = this.sampleWarmupAdaptiveMetrics(nowMs);
845
+ var targetScale = this.clampNumber(1 - metrics.pressure, 0, 1);
846
+ var scale = this.updateAdaptiveScale(targetScale);
847
+ var maxPerTick = Math.max(1, (0, common_1.round)(basePerTick + (targetPerTick - basePerTick) * scale));
848
+ var maxInFlight = Math.max(1, (0, common_1.round)(baseInFlight + (targetInFlight - baseInFlight) * scale));
849
+ return { maxPerTick: maxPerTick, maxInFlight: maxInFlight, rampActive: true, rampProgress: scale, adaptiveScale: scale, metrics: metrics };
850
+ };
653
851
  SubscriptionManager.prototype.requeueWarmupItem = function (item) {
654
852
  if (this._warmupQueueKeys.has(item.key)) {
655
853
  return;
@@ -658,7 +856,11 @@ var SubscriptionManager = /** @class */ (function () {
658
856
  this._warmupQueue.push(item);
659
857
  this._warmupQueueKeys.add(item.key);
660
858
  };
661
- SubscriptionManager.prototype.logWarmupStatus = function (reason) {
859
+ SubscriptionManager.prototype.logWarmupStatus = function (reason, limits) {
860
+ var _a, _b, _c;
861
+ if (!this._enableDebug) {
862
+ return;
863
+ }
662
864
  if (!this._warmupLogIntervalMs) {
663
865
  return;
664
866
  }
@@ -667,14 +869,23 @@ var SubscriptionManager = /** @class */ (function () {
667
869
  return;
668
870
  }
669
871
  this._warmupLastLogMs = now;
872
+ var metrics = limits === null || limits === void 0 ? void 0 : limits.metrics;
670
873
  console.log(new Date(), 'Sub Manager', 'Warmup status', {
671
874
  reason: reason,
672
875
  enabled: this._warmupEnabled,
673
876
  endsInMs: this._warmupEnabled ? Math.max(0, this._warmupEndsAtMs - now) : 0,
674
877
  queued: this._warmupQueue.length,
675
878
  inFlight: this._warmupInFlight,
676
- maxPerTick: this._warmupMaxPerTick,
677
- maxInFlight: this._warmupMaxInFlight
879
+ maxPerTick: (_a = limits === null || limits === void 0 ? void 0 : limits.maxPerTick) !== null && _a !== void 0 ? _a : this._warmupMaxPerTick,
880
+ maxInFlight: (_b = limits === null || limits === void 0 ? void 0 : limits.maxInFlight) !== null && _b !== void 0 ? _b : this._warmupMaxInFlight,
881
+ rampActive: (_c = limits === null || limits === void 0 ? void 0 : limits.rampActive) !== null && _c !== void 0 ? _c : false,
882
+ rampProgress: typeof (limits === null || limits === void 0 ? void 0 : limits.rampProgress) === 'number' ? (0, common_1.round)(limits.rampProgress * 100) : 0,
883
+ adaptiveScale: typeof (limits === null || limits === void 0 ? void 0 : limits.adaptiveScale) === 'number' ? (0, common_1.round)(limits.adaptiveScale * 100) : 0,
884
+ cpuPct: metrics ? (0, common_1.round)(metrics.cpuPct) : undefined,
885
+ memPct: metrics ? (0, common_1.round)(metrics.memPct) : undefined,
886
+ rssMB: metrics ? (0, common_1.round)(metrics.rssMB) : undefined,
887
+ lagMs: metrics ? (0, common_1.round)(metrics.lagMs) : undefined,
888
+ pressure: metrics ? (0, common_1.round)(metrics.pressure * 100) : undefined
678
889
  });
679
890
  };
680
891
  SubscriptionManager.prototype.invalidatePubsCache = function (collection, type, documentId, document) {
@@ -894,6 +1105,141 @@ var SubscriptionManager = /** @class */ (function () {
894
1105
  this._lastRouteBySocket.set(socketId, { route: messageRoute, dateMs: messageDateMs });
895
1106
  return false;
896
1107
  };
1108
+ SubscriptionManager.prototype.getPublicationWorkerDispatcher = function () {
1109
+ var mainServer = resolveio_server_app_1.ResolveIOServer.getMainServer();
1110
+ return mainServer && typeof mainServer.getWorkerDispatcherManager === 'function'
1111
+ ? mainServer.getWorkerDispatcherManager()
1112
+ : null;
1113
+ };
1114
+ SubscriptionManager.prototype.shouldUsePublicationWorkers = function () {
1115
+ if (!this._publicationWorkersEnabled) {
1116
+ return false;
1117
+ }
1118
+ var dispatcher = this.getPublicationWorkerDispatcher();
1119
+ if (!dispatcher || !dispatcher.hasWorkers()) {
1120
+ return false;
1121
+ }
1122
+ if (this._publicationWorkerQueueLimit > 0) {
1123
+ var snapshot = dispatcher.getQueueSnapshot();
1124
+ if (snapshot.queueDepth >= this._publicationWorkerQueueLimit) {
1125
+ return false;
1126
+ }
1127
+ }
1128
+ return true;
1129
+ };
1130
+ SubscriptionManager.prototype.runPublicationViaWorker = function (sub, userId) {
1131
+ return __awaiter(this, void 0, void 0, function () {
1132
+ var dispatcher, response, meta, snapshot, error_3;
1133
+ return __generator(this, function (_a) {
1134
+ switch (_a.label) {
1135
+ case 0:
1136
+ if (!this.shouldUsePublicationWorkers()) {
1137
+ return [2 /*return*/, null];
1138
+ }
1139
+ dispatcher = this.getPublicationWorkerDispatcher();
1140
+ if (!dispatcher) {
1141
+ return [2 /*return*/, null];
1142
+ }
1143
+ _a.label = 1;
1144
+ case 1:
1145
+ _a.trys.push([1, 3, , 4]);
1146
+ return [4 /*yield*/, dispatcher.sendInternalPromiseRaw('runPublication', [
1147
+ sub.publication,
1148
+ sub.subscriptionData,
1149
+ userId
1150
+ ])];
1151
+ case 2:
1152
+ response = _a.sent();
1153
+ if (!response || response.error) {
1154
+ throw (response === null || response === void 0 ? void 0 : response.result) || new Error('Publication worker error');
1155
+ }
1156
+ if (!response.packedResult) {
1157
+ throw new Error('Publication worker missing packedResult');
1158
+ }
1159
+ meta = response.meta || {};
1160
+ snapshot = meta.snapshot ? (0, subscription_dependency_context_1.deserializeDependencySnapshot)(meta.snapshot) : undefined;
1161
+ return [2 /*return*/, {
1162
+ packedResult: response.packedResult,
1163
+ snapshot: snapshot,
1164
+ encoding: response.encoding || meta.encoding || 'msgpack',
1165
+ workerUsed: true
1166
+ }];
1167
+ case 3:
1168
+ error_3 = _a.sent();
1169
+ if (this._enableDebug) {
1170
+ 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);
1171
+ }
1172
+ return [2 /*return*/, null];
1173
+ case 4: return [2 /*return*/];
1174
+ }
1175
+ });
1176
+ });
1177
+ };
1178
+ SubscriptionManager.prototype.runPublicationLocally = function (sub, userId) {
1179
+ return __awaiter(this, void 0, void 0, function () {
1180
+ var pub, context, metadata, execution, _a;
1181
+ return __generator(this, function (_b) {
1182
+ switch (_b.label) {
1183
+ case 0:
1184
+ pub = this._publications[sub.publication];
1185
+ if (!pub) {
1186
+ throw new Error("Publication not found: ".concat(sub.publication));
1187
+ }
1188
+ context = Object.assign({}, this, SubscriptionManager.prototype);
1189
+ metadata = {
1190
+ publication: sub.publication,
1191
+ subscriptionData: sub.subscriptionData
1192
+ };
1193
+ if (!pub.user_specific) return [3 /*break*/, 2];
1194
+ return [4 /*yield*/, (0, subscription_dependency_context_1.withDependencyTracking)(function () {
1195
+ var _a;
1196
+ return (_a = pub.function).call.apply(_a, __spreadArray([context, userId || ''], __read(sub.subscriptionData), false));
1197
+ }, Object.assign({}, metadata, { userId: userId }))];
1198
+ case 1:
1199
+ _a = _b.sent();
1200
+ return [3 /*break*/, 4];
1201
+ case 2: return [4 /*yield*/, (0, subscription_dependency_context_1.withDependencyTracking)(function () {
1202
+ var _a;
1203
+ return (_a = pub.function).call.apply(_a, __spreadArray([context], __read(sub.subscriptionData), false));
1204
+ }, metadata)];
1205
+ case 3:
1206
+ _a = _b.sent();
1207
+ _b.label = 4;
1208
+ case 4:
1209
+ execution = _a;
1210
+ return [2 /*return*/, {
1211
+ result: execution.result,
1212
+ packedResult: this.packCachePayload(execution.result),
1213
+ snapshot: execution.snapshot,
1214
+ encoding: 'msgpack',
1215
+ workerUsed: false
1216
+ }];
1217
+ }
1218
+ });
1219
+ });
1220
+ };
1221
+ SubscriptionManager.prototype.runPublicationExecution = function (sub, userId) {
1222
+ return __awaiter(this, void 0, void 0, function () {
1223
+ var pub, effectiveUserId, workerExecution;
1224
+ return __generator(this, function (_a) {
1225
+ switch (_a.label) {
1226
+ case 0:
1227
+ pub = this._publications[sub.publication];
1228
+ if (!pub) {
1229
+ throw new Error("Publication not found: ".concat(sub.publication));
1230
+ }
1231
+ effectiveUserId = pub.user_specific ? userId : undefined;
1232
+ return [4 /*yield*/, this.runPublicationViaWorker(sub, effectiveUserId)];
1233
+ case 1:
1234
+ workerExecution = _a.sent();
1235
+ if (workerExecution) {
1236
+ return [2 /*return*/, workerExecution];
1237
+ }
1238
+ return [2 /*return*/, this.runPublicationLocally(sub, effectiveUserId)];
1239
+ }
1240
+ });
1241
+ });
1242
+ };
897
1243
  SubscriptionManager.prototype.sendDataToAllWithRetry = function (sub, collection, type) {
898
1244
  return __awaiter(this, void 0, void 0, function () {
899
1245
  return __generator(this, function (_a) {
@@ -964,6 +1310,12 @@ var SubscriptionManager = /** @class */ (function () {
964
1310
  SubscriptionManager.prototype.publications = function (method) {
965
1311
  this._publications = Object.assign(this._publications, method);
966
1312
  };
1313
+ SubscriptionManager.prototype.getPublication = function (publication) {
1314
+ return this._publications[publication];
1315
+ };
1316
+ SubscriptionManager.prototype.getPublications = function () {
1317
+ return this._publications;
1318
+ };
967
1319
  // Throttled `loggedInLatency` method
968
1320
  SubscriptionManager.prototype.loggedInLatency = function (ws) {
969
1321
  var _a, _b, _c, _d;
@@ -1020,7 +1372,7 @@ var SubscriptionManager = /** @class */ (function () {
1020
1372
  // Method to flush buffered latency updates in bulk
1021
1373
  SubscriptionManager.prototype.flushThrottledLatencyUpdates = function () {
1022
1374
  return __awaiter(this, void 0, void 0, function () {
1023
- var pendingEntries, updates, error_3, pendingEntries_1, pendingEntries_1_1, _a, id_ws, payload, current;
1375
+ var pendingEntries, updates, error_4, pendingEntries_1, pendingEntries_1_1, _a, id_ws, payload, current;
1024
1376
  var e_3, _b;
1025
1377
  var _this = this;
1026
1378
  return __generator(this, function (_c) {
@@ -1055,7 +1407,7 @@ var SubscriptionManager = /** @class */ (function () {
1055
1407
  }
1056
1408
  return [3 /*break*/, 5];
1057
1409
  case 3:
1058
- error_3 = _c.sent();
1410
+ error_4 = _c.sent();
1059
1411
  try {
1060
1412
  for (pendingEntries_1 = __values(pendingEntries), pendingEntries_1_1 = pendingEntries_1.next(); !pendingEntries_1_1.done; pendingEntries_1_1 = pendingEntries_1.next()) {
1061
1413
  _a = __read(pendingEntries_1_1.value, 2), id_ws = _a[0], payload = _a[1];
@@ -1072,7 +1424,7 @@ var SubscriptionManager = /** @class */ (function () {
1072
1424
  }
1073
1425
  finally { if (e_3) throw e_3.error; }
1074
1426
  }
1075
- console.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error_3);
1427
+ console.error(new Date(), 'Sub Manager', 'Throttled latency batch update failed', error_4);
1076
1428
  return [3 /*break*/, 5];
1077
1429
  case 4:
1078
1430
  this._latencyFlushInProgress = false;
@@ -1367,6 +1719,18 @@ var SubscriptionManager = /** @class */ (function () {
1367
1719
  }
1368
1720
  return 0;
1369
1721
  };
1722
+ SubscriptionManager.prototype.parsePositiveFloat = function (value) {
1723
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
1724
+ return value;
1725
+ }
1726
+ if (typeof value === 'string' && value.trim().length) {
1727
+ var parsed = parseFloat(value);
1728
+ if (Number.isFinite(parsed) && parsed > 0) {
1729
+ return parsed;
1730
+ }
1731
+ }
1732
+ return 0;
1733
+ };
1370
1734
  SubscriptionManager.prototype.isChangeStreamUnsupported = function (error) {
1371
1735
  var code = typeof (error === null || error === void 0 ? void 0 : error.code) === 'number' ? error.code : null;
1372
1736
  var codeName = typeof (error === null || error === void 0 ? void 0 : error.codeName) === 'string' ? error.codeName.toLowerCase() : '';
@@ -1486,7 +1850,7 @@ var SubscriptionManager = /** @class */ (function () {
1486
1850
  };
1487
1851
  SubscriptionManager.prototype.loadResumeToken = function () {
1488
1852
  return __awaiter(this, void 0, void 0, function () {
1489
- var db, doc, error_4;
1853
+ var db, doc, error_5;
1490
1854
  return __generator(this, function (_a) {
1491
1855
  switch (_a.label) {
1492
1856
  case 0:
@@ -1500,8 +1864,8 @@ var SubscriptionManager = /** @class */ (function () {
1500
1864
  doc = _a.sent();
1501
1865
  return [2 /*return*/, (doc === null || doc === void 0 ? void 0 : doc.token) || null];
1502
1866
  case 2:
1503
- error_4 = _a.sent();
1504
- console.log(new Date(), 'Sub Manager', 'Failed to load oplog resume token', error_4);
1867
+ error_5 = _a.sent();
1868
+ console.log(new Date(), 'Sub Manager', 'Failed to load oplog resume token', error_5);
1505
1869
  return [2 /*return*/, null];
1506
1870
  case 3: return [2 /*return*/];
1507
1871
  }
@@ -1510,7 +1874,7 @@ var SubscriptionManager = /** @class */ (function () {
1510
1874
  };
1511
1875
  SubscriptionManager.prototype.saveResumeToken = function (token) {
1512
1876
  return __awaiter(this, void 0, void 0, function () {
1513
- var db, error_5;
1877
+ var db, error_6;
1514
1878
  return __generator(this, function (_a) {
1515
1879
  switch (_a.label) {
1516
1880
  case 0:
@@ -1529,8 +1893,8 @@ var SubscriptionManager = /** @class */ (function () {
1529
1893
  _a.sent();
1530
1894
  return [3 /*break*/, 4];
1531
1895
  case 3:
1532
- error_5 = _a.sent();
1533
- console.log(new Date(), 'Sub Manager', 'Failed to persist oplog resume token', error_5);
1896
+ error_6 = _a.sent();
1897
+ console.log(new Date(), 'Sub Manager', 'Failed to persist oplog resume token', error_6);
1534
1898
  return [3 /*break*/, 4];
1535
1899
  case 4: return [2 /*return*/];
1536
1900
  }
@@ -1539,7 +1903,7 @@ var SubscriptionManager = /** @class */ (function () {
1539
1903
  };
1540
1904
  SubscriptionManager.prototype.clearResumeToken = function () {
1541
1905
  return __awaiter(this, void 0, void 0, function () {
1542
- var db, error_6;
1906
+ var db, error_7;
1543
1907
  return __generator(this, function (_a) {
1544
1908
  switch (_a.label) {
1545
1909
  case 0:
@@ -1553,8 +1917,8 @@ var SubscriptionManager = /** @class */ (function () {
1553
1917
  _a.sent();
1554
1918
  return [3 /*break*/, 3];
1555
1919
  case 2:
1556
- error_6 = _a.sent();
1557
- console.log(new Date(), 'Sub Manager', 'Failed to clear oplog resume token', error_6);
1920
+ error_7 = _a.sent();
1921
+ console.log(new Date(), 'Sub Manager', 'Failed to clear oplog resume token', error_7);
1558
1922
  return [3 /*break*/, 3];
1559
1923
  case 3: return [2 /*return*/];
1560
1924
  }
@@ -1625,7 +1989,7 @@ var SubscriptionManager = /** @class */ (function () {
1625
1989
  };
1626
1990
  SubscriptionManager.prototype.fullResyncSubscriptions = function (reason) {
1627
1991
  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;
1992
+ var subs, subs_1, subs_1_1, sub, pub, _a, _b, client, ws, _c, e_4_1, e_5_1, error_8;
1629
1993
  var e_5, _d, e_4, _e;
1630
1994
  var _f, _g, _h, _j, _k;
1631
1995
  return __generator(this, function (_l) {
@@ -1723,8 +2087,8 @@ var SubscriptionManager = /** @class */ (function () {
1723
2087
  return [7 /*endfinally*/];
1724
2088
  case 19: return [3 /*break*/, 21];
1725
2089
  case 20:
1726
- error_7 = _l.sent();
1727
- console.log(new Date(), 'Sub Manager', 'Full resync failed', reason, error_7);
2090
+ error_8 = _l.sent();
2091
+ console.log(new Date(), 'Sub Manager', 'Full resync failed', reason, error_8);
1728
2092
  return [3 /*break*/, 21];
1729
2093
  case 21: return [2 /*return*/];
1730
2094
  }
@@ -1734,7 +2098,7 @@ var SubscriptionManager = /** @class */ (function () {
1734
2098
  // Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)
1735
2099
  SubscriptionManager.prototype.tailOpLog = function (resumeToken) {
1736
2100
  return __awaiter(this, void 0, void 0, function () {
1737
- var watchDatabases, pipeline, lastResumeToken_1, startedWithResumeToken, error_8, innerError_1, error_9;
2101
+ var watchDatabases, pipeline, lastResumeToken_1, startedWithResumeToken, error_9, innerError_1, error_10;
1738
2102
  var _this = this;
1739
2103
  return __generator(this, function (_a) {
1740
2104
  switch (_a.label) {
@@ -1795,9 +2159,9 @@ var SubscriptionManager = /** @class */ (function () {
1795
2159
  startedWithResumeToken = true;
1796
2160
  return [3 /*break*/, 16];
1797
2161
  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)];
2162
+ error_9 = _a.sent();
2163
+ if (!this.isChangeStreamUnsupported(error_9)) return [3 /*break*/, 7];
2164
+ return [4 /*yield*/, this.enableLocalOplogFallback('change-stream-unsupported', error_9)];
1801
2165
  case 6:
1802
2166
  _a.sent();
1803
2167
  return [2 /*return*/];
@@ -1813,7 +2177,7 @@ var SubscriptionManager = /** @class */ (function () {
1813
2177
  case 10:
1814
2178
  _a.sent();
1815
2179
  lastResumeToken_1 = null;
1816
- console.log(new Date(), 'oplog resumeAfter failed, starting fresh', error_8);
2180
+ console.log(new Date(), 'oplog resumeAfter failed, starting fresh', error_9);
1817
2181
  _a.label = 11;
1818
2182
  case 11:
1819
2183
  _a.trys.push([11, 12, , 15]);
@@ -1837,13 +2201,13 @@ var SubscriptionManager = /** @class */ (function () {
1837
2201
  this._oplog$ = resolveio_server_app_1.ResolveIOServer.getMongoConnection().watch(pipeline, { fullDocument: 'updateLookup' });
1838
2202
  return [3 /*break*/, 21];
1839
2203
  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)];
2204
+ error_10 = _a.sent();
2205
+ if (!this.isChangeStreamUnsupported(error_10)) return [3 /*break*/, 20];
2206
+ return [4 /*yield*/, this.enableLocalOplogFallback('change-stream-unsupported', error_10)];
1843
2207
  case 19:
1844
2208
  _a.sent();
1845
2209
  return [2 /*return*/];
1846
- case 20: throw error_9;
2210
+ case 20: throw error_10;
1847
2211
  case 21:
1848
2212
  console.log(new Date(), 'oplog started', startedWithResumeToken ? '(resumeAfter)' : '');
1849
2213
  this._oplog$.on('change', function (doc) { return __awaiter(_this, void 0, void 0, function () {
@@ -2093,7 +2457,7 @@ var SubscriptionManager = /** @class */ (function () {
2093
2457
  };
2094
2458
  SubscriptionManager.prototype.processSubscription = function (sub, ws, messageId) {
2095
2459
  return __awaiter(this, void 0, void 0, function () {
2096
- var cacheData, serverRes, _a;
2460
+ var cachedRaw, cachedBuffer, cacheData, serverRes, _a;
2097
2461
  return __generator(this, function (_b) {
2098
2462
  switch (_b.label) {
2099
2463
  case 0:
@@ -2102,19 +2466,29 @@ var SubscriptionManager = /** @class */ (function () {
2102
2466
  _b.label = 1;
2103
2467
  case 1:
2104
2468
  _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');
2469
+ cachedRaw = this._nodeCache.get(sub.cacheId);
2470
+ cachedBuffer = this.getCacheBuffer(cachedRaw);
2471
+ if (cachedBuffer && cachedBuffer.byteLength) {
2472
+ if (this._enableDebug) {
2473
+ console.log(new Date(), 'Process Sub, Cache (packed)', sub.publication);
2474
+ }
2475
+ this._websocketManager.sendPackedBuffer(ws, messageId, false, cachedBuffer, 'msgpack');
2108
2476
  }
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);
2477
+ else {
2478
+ cacheData = this.decodeCachePayload(cachedRaw);
2479
+ if (cacheData === null || cacheData === undefined) {
2480
+ throw new Error('cache-miss');
2481
+ }
2482
+ serverRes = {
2483
+ messageId: messageId,
2484
+ hasError: false,
2485
+ data: cacheData
2486
+ };
2487
+ if (this._enableDebug) {
2488
+ console.log(new Date(), 'Process Sub, Cache', sub.publication);
2489
+ }
2490
+ this.sendWS(ws, serverRes);
2116
2491
  }
2117
- this.sendWS(ws, serverRes);
2118
2492
  return [3 /*break*/, 4];
2119
2493
  case 2:
2120
2494
  _a = _b.sent();
@@ -2156,7 +2530,6 @@ var SubscriptionManager = /** @class */ (function () {
2156
2530
  SubscriptionManager.prototype.sendDataToOne = function (ws, messageId, sub, collection, type) {
2157
2531
  return __awaiter(this, void 0, void 0, function () {
2158
2532
  var startMs, monitor, dependencySnapshot, res, execution, serverRes, err_1, _a, normalizedError, correlationId, serverRes, errorPayload, durationMs;
2159
- var _this = this;
2160
2533
  var _b;
2161
2534
  return __generator(this, function (_c) {
2162
2535
  switch (_c.label) {
@@ -2167,24 +2540,23 @@ var SubscriptionManager = /** @class */ (function () {
2167
2540
  case 1:
2168
2541
  _c.trys.push([1, 3, 5, 7]);
2169
2542
  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
- })];
2543
+ return [4 /*yield*/, this.runPublicationExecution(sub, ws['id_user'])];
2177
2544
  case 2:
2178
2545
  execution = _c.sent();
2179
2546
  res = execution.result;
2180
2547
  dependencySnapshot = execution.snapshot;
2181
2548
  this.updateSubscriptionDependencies(sub, dependencySnapshot);
2182
- serverRes = {
2183
- messageId: messageId,
2184
- hasError: false,
2185
- data: res
2186
- };
2187
- this.sendWS(ws, serverRes);
2549
+ if (execution.packedResult) {
2550
+ this._websocketManager.sendPackedBuffer(ws, messageId, false, execution.packedResult, execution.encoding || 'msgpack');
2551
+ }
2552
+ else {
2553
+ serverRes = {
2554
+ messageId: messageId,
2555
+ hasError: false,
2556
+ data: res
2557
+ };
2558
+ this.sendWS(ws, serverRes);
2559
+ }
2188
2560
  return [3 /*break*/, 7];
2189
2561
  case 3:
2190
2562
  err_1 = _c.sent();
@@ -2257,10 +2629,9 @@ var SubscriptionManager = /** @class */ (function () {
2257
2629
  return __awaiter(this, void 0, void 0, function () {
2258
2630
  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
2631
  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) {
2632
+ var _l, _m;
2633
+ return __generator(this, function (_o) {
2634
+ switch (_o.label) {
2264
2635
  case 0:
2265
2636
  if (!!sub.clients.length) return [3 /*break*/, 1];
2266
2637
  if (sub.cacheId) {
@@ -2277,25 +2648,19 @@ var SubscriptionManager = /** @class */ (function () {
2277
2648
  monitor = this._monitorManagerFunction.startMonitorFunction('Publication', sub.publication, '', '', sub.subscriptionData);
2278
2649
  res = void 0;
2279
2650
  dependencySnapshot = void 0;
2280
- _m.label = 2;
2651
+ _o.label = 2;
2281
2652
  case 2:
2282
- _m.trys.push([2, 4, 6, 8]);
2653
+ _o.trys.push([2, 4, 6, 8]);
2283
2654
  if (sub.publication !== 'superadminAPM' && sub.publication !== 'loggedInUsers') {
2284
2655
  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
2656
  }
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
- })];
2657
+ return [4 /*yield*/, this.runPublicationExecution(sub)];
2293
2658
  case 3:
2294
- execution = _m.sent();
2659
+ execution = _o.sent();
2295
2660
  res = execution.result;
2296
2661
  dependencySnapshot = execution.snapshot;
2297
2662
  this.updateSubscriptionDependencies(sub, dependencySnapshot);
2298
- packedRes = this.packCachePayload(res);
2663
+ packedRes = (_l = execution.packedResult) !== null && _l !== void 0 ? _l : this.packCachePayload(res);
2299
2664
  shouldCache = this.shouldCachePayload(sub, packedRes);
2300
2665
  if (sub.cacheId) {
2301
2666
  cachedBuffer = this.getCacheBuffer(this._nodeCache.get(sub.cacheId));
@@ -2306,12 +2671,17 @@ var SubscriptionManager = /** @class */ (function () {
2306
2671
  client = _b.value;
2307
2672
  ws = this._websocketManager.getWebSocket(client.id_socket);
2308
2673
  if (ws && ws.readyState === ws.OPEN) {
2309
- serverRes = {
2310
- messageId: client.messageId,
2311
- hasError: false,
2312
- data: res
2313
- };
2314
- this.sendWS(ws, serverRes);
2674
+ if (packedRes) {
2675
+ this._websocketManager.sendPackedBuffer(ws, client.messageId, false, packedRes, execution.encoding || 'msgpack');
2676
+ }
2677
+ else {
2678
+ serverRes = {
2679
+ messageId: client.messageId,
2680
+ hasError: false,
2681
+ data: res
2682
+ };
2683
+ this.sendWS(ws, serverRes);
2684
+ }
2315
2685
  }
2316
2686
  }
2317
2687
  }
@@ -2344,12 +2714,17 @@ var SubscriptionManager = /** @class */ (function () {
2344
2714
  client = _d.value;
2345
2715
  ws = this._websocketManager.getWebSocket(client.id_socket);
2346
2716
  if (ws && ws.readyState === ws.OPEN) {
2347
- serverRes = {
2348
- messageId: client.messageId,
2349
- hasError: false,
2350
- data: res
2351
- };
2352
- this.sendWS(ws, serverRes);
2717
+ if (packedRes) {
2718
+ this._websocketManager.sendPackedBuffer(ws, client.messageId, false, packedRes, execution.encoding || 'msgpack');
2719
+ }
2720
+ else {
2721
+ serverRes = {
2722
+ messageId: client.messageId,
2723
+ hasError: false,
2724
+ data: res
2725
+ };
2726
+ this.sendWS(ws, serverRes);
2727
+ }
2353
2728
  }
2354
2729
  }
2355
2730
  }
@@ -2393,7 +2768,7 @@ var SubscriptionManager = /** @class */ (function () {
2393
2768
  }
2394
2769
  return [3 /*break*/, 8];
2395
2770
  case 4:
2396
- err_2 = _m.sent();
2771
+ err_2 = _o.sent();
2397
2772
  _e = (0, error_tracking_1.ensureErrorWithCorrelation)(err_2), normalizedError = _e.error, correlationId = _e.correlationId;
2398
2773
  try {
2399
2774
  for (_f = __values(sub.clients), _g = _f.next(); !_g.done; _g = _f.next()) {
@@ -2433,7 +2808,7 @@ var SubscriptionManager = /** @class */ (function () {
2433
2808
  return [4 /*yield*/, error_reporter_1.ErrorReporter.report({
2434
2809
  sourceApp: 'subscription-manager',
2435
2810
  message: 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'],
2436
- environment: (_l = this.serverConfig) === null || _l === void 0 ? void 0 : _l.ROOT_URL,
2811
+ environment: (_m = this.serverConfig) === null || _m === void 0 ? void 0 : _m.ROOT_URL,
2437
2812
  clientSlug: resolveio_server_app_1.ResolveIOServer.getClientName(),
2438
2813
  clientName: this.serverConfig['CLIENT_NAME'],
2439
2814
  stack: normalizedError === null || normalizedError === void 0 ? void 0 : normalizedError.stack,
@@ -2446,7 +2821,7 @@ var SubscriptionManager = /** @class */ (function () {
2446
2821
  correlationId: correlationId
2447
2822
  })];
2448
2823
  case 5:
2449
- _m.sent();
2824
+ _o.sent();
2450
2825
  return [3 /*break*/, 8];
2451
2826
  case 6:
2452
2827
  durationMs = Date.now() - startMs;
@@ -2464,7 +2839,7 @@ var SubscriptionManager = /** @class */ (function () {
2464
2839
  }
2465
2840
  return [4 /*yield*/, this._monitorManagerFunction.finishMonitorFunction(monitor)];
2466
2841
  case 7:
2467
- _m.sent();
2842
+ _o.sent();
2468
2843
  return [7 /*endfinally*/];
2469
2844
  case 8: return [2 /*return*/];
2470
2845
  }