emailengine-app 2.89.0 → 2.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +60 -0
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/oauth/gmail.js +39 -120
  38. package/lib/oauth/http-request.js +195 -0
  39. package/lib/oauth/mail-ru.js +24 -58
  40. package/lib/oauth/outlook.js +37 -137
  41. package/lib/oauth/pubsub/google.js +176 -117
  42. package/lib/oauth2-apps.js +440 -463
  43. package/lib/openapi/build-document.js +10 -10
  44. package/lib/read-env-value.js +1 -1
  45. package/lib/route-descriptors.js +78 -0
  46. package/lib/schemas.js +10 -1
  47. package/lib/sentry-integrations.js +299 -0
  48. package/lib/sentry.js +75 -27
  49. package/lib/sso-routes.js +249 -0
  50. package/lib/sso.js +29 -6
  51. package/lib/ui-routes/account-edit-form.js +198 -0
  52. package/lib/ui-routes/account-page.js +241 -0
  53. package/lib/ui-routes/account-routes.js +12 -318
  54. package/lib/ui-routes/auth-routes.js +10 -10
  55. package/lib/ui-view-context.js +328 -0
  56. package/lib/utils/public-suffix.js +22 -101
  57. package/lib/web-safe-html.js +20 -7
  58. package/lib/worker-metrics.js +82 -0
  59. package/list-generate.js +2 -5
  60. package/package.json +23 -19
  61. package/sbom.json +267 -908
  62. package/scripts/refresh-test-tokens.js +1 -1
  63. package/server.js +320 -676
  64. package/static/css/flyonui.css +1 -1
  65. package/static/css/src/app.tailwind.css +18 -0
  66. package/static/js/ee-client.js +2619 -645
  67. package/static/js/ui.js +12 -2
  68. package/static/licenses.html +219 -737
  69. package/translations/messages.pot +64 -53
  70. package/views/accounts/browse.hbs +19 -1
  71. package/workers/api.js +20 -451
  72. package/data/public_suffix_list.dat +0 -16698
package/server.js CHANGED
@@ -8,7 +8,6 @@
8
8
  * proxy servers (SMTP, IMAP).
9
9
  *
10
10
  * @module server
11
- * @requires dotenv
12
11
  * @requires worker_threads
13
12
  * @requires @zone-eu/wild-config
14
13
  * @see {@link https://emailengine.app}
@@ -31,11 +30,8 @@ try {
31
30
  // ignore - may fail in some containerized environments
32
31
  }
33
32
 
34
- // Load environment variables if not already loaded
35
- if (!process.env.EE_ENV_LOADED) {
36
- require('dotenv').config({ quiet: true });
37
- process.env.EE_ENV_LOADED = 'true';
38
- }
33
+ // Load .env into process.env, if not already loaded
34
+ require('./lib/load-env').loadEnvOnce();
39
35
 
40
36
  // Set process title for easier identification in process lists
41
37
  process.title = 'emailengine';
@@ -67,6 +63,7 @@ if (nodeSupportLevel === 'outside-range') {
67
63
  }
68
64
 
69
65
  const { accountDataKey } = require('./lib/redis-keys');
66
+ const { resolveMetricKeys, statBuckets } = require('./lib/worker-metrics');
70
67
  const { importPreparedPassword } = require('./lib/prepared-password');
71
68
 
72
69
  const os = require('os');
@@ -113,9 +110,6 @@ const MetricsCollector = require('./lib/metrics-collector');
113
110
  // Import constants
114
111
  const {
115
112
  MAX_DAYS_STATS,
116
- MESSAGE_NEW_NOTIFY,
117
- MESSAGE_DELETED_NOTIFY,
118
- CONNECT_ERROR_NOTIFY,
119
113
  REDIS_PREFIX,
120
114
  ACCOUNT_ADDED_NOTIFY,
121
115
  ACCOUNT_DELETED_NOTIFY,
@@ -147,10 +141,9 @@ const { pruneFailedContent } = require('./lib/outbox');
147
141
  const { queueCleanAges } = require('./lib/queue-retention');
148
142
  const { getFailedJobRetention } = require('./lib/env-setting-overrides');
149
143
  const { packRpcError, unpackRpcError } = require('./lib/worker-rpc-error');
150
- const promClient = require('prom-client');
144
+ const { promClient, setupMetrics, connectionCounts } = require('./lib/metrics');
151
145
  const fs = require('fs').promises;
152
146
  const crypto = require('crypto');
153
- const { compareVersions, parseVersion } = require('./lib/utils/version');
154
147
  const Joi = require('joi');
155
148
  const { settingsSchema } = require('./lib/schemas');
156
149
  const settings = require('./lib/settings');
@@ -162,7 +155,9 @@ const { attachBeacon, persistBeaconMarkers } = require('./lib/license-beacon');
162
155
  const {
163
156
  decide,
164
157
  startupPlan,
165
- expiredSuspension,
158
+ needsVersionRecheck,
159
+ subscriptionCheckState,
160
+ workerSuspensionChange,
166
161
  checkInterval,
167
162
  subscriptionView,
168
163
  parseSuspension,
@@ -191,6 +186,7 @@ const { mapConcurrent } = require('./lib/utils/map-concurrent');
191
186
  const { RespawnTracker, retryWithBackoff } = require('./lib/respawn-backoff');
192
187
  const { legacySmtpOptionsInUse, REMOVAL_DATE } = require('./lib/deprecations');
193
188
  const { heartbeatDiagnostics, eventLoopDelaySeries, threadHeapSeries } = require('./lib/thread-diagnostics');
189
+ const { licenseDaysRemaining, countThreads } = require('./lib/metric-values');
194
190
 
195
191
  const msgpack = require('./lib/msgpack');
196
192
 
@@ -568,290 +564,8 @@ if (preparedPasswordString) {
568
564
  }
569
565
  }
570
566
 
571
- // Initialize Prometheus metrics collection
572
- const collectDefaultMetrics = promClient.collectDefaultMetrics;
573
- collectDefaultMetrics({});
574
-
575
- /**
576
- * Prometheus metrics definitions for monitoring
577
- * @const {Object}
578
- */
579
- const metrics = {
580
- threadStarts: new promClient.Counter({
581
- name: 'thread_starts',
582
- help: 'Number of started threads'
583
- }),
584
-
585
- threadStops: new promClient.Counter({
586
- name: 'thread_stops',
587
- help: 'Number of stopped threads'
588
- }),
589
-
590
- apiCall: new promClient.Counter({
591
- name: 'api_call',
592
- help: 'Number of API calls',
593
- labelNames: ['method', 'statusCode', 'route']
594
- }),
595
-
596
- // Labelled by route, not by status: the counter above already splits by status, and a latency
597
- // series per status code would multiply the route count for little an operator can act on
598
- apiCallDuration: new promClient.Histogram({
599
- name: 'api_call_duration_seconds',
600
- help: 'Duration of API calls, from receiving the request to sending the response',
601
- labelNames: ['method', 'route'],
602
- buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60]
603
- }),
604
-
605
- imapConnections: new promClient.Gauge({
606
- name: 'imap_connections',
607
- help: 'Current IMAP connection state',
608
- labelNames: ['status']
609
- }),
610
-
611
- imapResponses: new promClient.Counter({
612
- name: 'imap_responses',
613
- help: 'IMAP responses',
614
- labelNames: ['response', 'code']
615
- }),
616
-
617
- imapBytesSent: new promClient.Counter({
618
- name: 'imap_bytes_sent',
619
- help: 'IMAP bytes sent'
620
- }),
621
-
622
- imapBytesReceived: new promClient.Counter({
623
- name: 'imap_bytes_received',
624
- help: 'IMAP bytes received'
625
- }),
626
-
627
- oauth2TokenRefresh: new promClient.Counter({
628
- name: 'oauth2_token_refresh',
629
- help: 'OAuth2 access token refresh attempts',
630
- labelNames: ['status', 'provider', 'statusCode']
631
- }),
632
-
633
- oauth2ApiRequest: new promClient.Counter({
634
- name: 'oauth2_api_request',
635
- help: 'OAuth2 API requests (MS Graph, Gmail API)',
636
- labelNames: ['status', 'provider', 'statusCode']
637
- }),
638
-
639
- outlookMissedRecovery: new promClient.Counter({
640
- name: 'outlook_missed_recovery',
641
- help: 'MS Graph missed-notification recovery passes, by what asked for them and whether they found unannounced messages',
642
- labelNames: ['reason', 'outcome']
643
- }),
644
-
645
- outlookMissedRecoveredMessages: new promClient.Counter({
646
- name: 'outlook_missed_recovered_messages',
647
- help: 'New messages announced by MS Graph missed-notification recovery instead of by a change notification',
648
- labelNames: ['reason']
649
- }),
650
-
651
- outlookSubscriptions: new promClient.Gauge({
652
- name: 'outlook_subscriptions',
653
- help: 'MS Graph webhook subscription states',
654
- labelNames: ['status']
655
- }),
656
-
657
- webhooks: new promClient.Counter({
658
- name: 'webhooks',
659
- help: 'Webhooks sent',
660
- labelNames: ['status', 'event']
661
- }),
662
-
663
- events: new promClient.Counter({
664
- name: 'events',
665
- help: 'Events fired',
666
- labelNames: ['event']
667
- }),
668
-
669
- aiRequests: new promClient.Counter({
670
- name: 'ai_requests',
671
- help: 'AI summary requests',
672
- labelNames: ['model', 'status']
673
- }),
674
-
675
- aiTokens: new promClient.Counter({
676
- name: 'ai_tokens',
677
- help: 'Tokens billed for AI summary requests',
678
- labelNames: ['model', 'type']
679
- }),
680
-
681
- webhookReq: new promClient.Histogram({
682
- name: 'webhook_req',
683
- help: 'Duration of webhook requests',
684
- buckets: [100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000, 60 * 1000]
685
- }),
686
-
687
- queues: new promClient.Gauge({
688
- name: 'queue_size',
689
- help: 'Queue size',
690
- labelNames: ['queue', 'state']
691
- }),
692
-
693
- queueFailed: new promClient.Gauge({
694
- name: 'queue_failed_jobs',
695
- help: 'Failed jobs a queue still retains (deliveries that were given up on)',
696
- labelNames: ['queue']
697
- }),
698
-
699
- queuesProcessed: new promClient.Counter({
700
- name: 'queues_processed',
701
- help: 'Processed job count',
702
- labelNames: ['queue', 'status']
703
- }),
704
-
705
- threads: new promClient.Gauge({
706
- name: 'threads',
707
- help: 'Worker Threads',
708
- labelNames: ['type', 'recent']
709
- }),
710
-
711
- unresponsiveWorkers: new promClient.Gauge({
712
- name: 'unresponsive_workers',
713
- help: 'Number of unresponsive worker threads'
714
- }),
715
-
716
- threadEventLoopDelayMax: new promClient.Gauge({
717
- name: 'thread_event_loop_delay_max_seconds',
718
- help: 'Longest event loop delay of a thread over the last collection window (15s)',
719
- labelNames: ['type', 'thread']
720
- }),
721
-
722
- threadEventLoopDelayP99: new promClient.Gauge({
723
- name: 'thread_event_loop_delay_p99_seconds',
724
- help: '99th percentile event loop delay of a thread over the last collection window (15s)',
725
- labelNames: ['type', 'thread']
726
- }),
727
-
728
- threadHeapUsed: new promClient.Gauge({
729
- name: 'thread_heap_used_bytes',
730
- help: 'V8 heap in use by a thread, as of the last collection (15s)',
731
- labelNames: ['type', 'thread']
732
- }),
733
-
734
- threadHeapTotal: new promClient.Gauge({
735
- name: 'thread_heap_total_bytes',
736
- help: 'V8 heap allocated by a thread, as of the last collection (15s)',
737
- labelNames: ['type', 'thread']
738
- }),
739
-
740
- licenseDaysRemaining: new promClient.Gauge({
741
- name: 'license_days_remaining',
742
- help: 'Days until license expires (-1 for lifetime, 0 for no license)'
743
- }),
744
-
745
- emailengineConfig: new promClient.Gauge({
746
- name: 'emailengine_config',
747
- help: 'Configuration values',
748
- labelNames: ['version', 'config']
749
- }),
750
-
751
- redisVersion: new promClient.Gauge({
752
- name: 'redis_version',
753
- help: 'Redis version',
754
- labelNames: ['version']
755
- }),
756
-
757
- redisUptimeInSeconds: new promClient.Gauge({
758
- name: 'redis_uptime_in_seconds',
759
- help: 'Redis uptime in seconds'
760
- }),
761
-
762
- redisPing: new promClient.Gauge({
763
- name: 'redis_latency',
764
- help: 'Redis latency in nanoseconds'
765
- }),
766
-
767
- redisRejectedConnectionsTotal: new promClient.Gauge({
768
- name: 'redis_rejected_connections_total',
769
- help: 'Number of connections rejected by Redis'
770
- }),
771
-
772
- redisConfigMaxclients: new promClient.Gauge({
773
- name: 'redis_config_maxclients',
774
- help: 'Maximum client number for Redis'
775
- }),
776
-
777
- redisConnectedClients: new promClient.Gauge({
778
- name: 'redis_connected_clients',
779
- help: 'Number of client connections for Redis'
780
- }),
781
-
782
- redisSlowlogLength: new promClient.Gauge({
783
- name: 'redis_slowlog_length',
784
- help: 'Number of of entries in the Redis slow log'
785
- }),
786
-
787
- redisCommandsDurationSecondsTotal: new promClient.Gauge({
788
- name: 'redis_commands_duration_seconds_total',
789
- help: 'How many seconds spend on processing Redis commands'
790
- }),
791
-
792
- redisCommandsProcessedTotal: new promClient.Gauge({
793
- name: 'redis_commands_processed_total',
794
- help: 'How many commands processed by Redis'
795
- }),
796
-
797
- redisKeyspaceHitsTotal: new promClient.Gauge({
798
- name: 'redis_keyspace_hits_total',
799
- help: 'Number of successful lookup of keys in Redis'
800
- }),
801
-
802
- redisKeyspaceMissesTotal: new promClient.Gauge({
803
- name: 'redis_keyspace_misses_total',
804
- help: 'Number of failed lookup of keys in Redis'
805
- }),
806
-
807
- redisEvictedKeysTotal: new promClient.Gauge({
808
- name: 'redis_evicted_keys_total',
809
- help: 'Number of evicted keys due to maxmemory limit in Redis'
810
- }),
811
-
812
- redisMemoryUsedBytes: new promClient.Gauge({
813
- name: 'redis_memory_used_bytes',
814
- help: 'Total number of bytes allocated by Redis using its allocator'
815
- }),
816
-
817
- redisMemoryMaxBytes: new promClient.Gauge({
818
- name: 'redis_memory_max_bytes',
819
- help: 'The value of the Redis maxmemory configuration directive'
820
- }),
821
-
822
- redisMemFragmentationRatio: new promClient.Gauge({
823
- name: 'redis_mem_fragmentation_ratio',
824
- help: 'Ratio between used_memory_rss and used_memory in Redis'
825
- }),
826
-
827
- redisKeyCount: new promClient.Gauge({
828
- name: 'redis_key_count',
829
- help: 'Redis key counts',
830
- labelNames: ['db']
831
- }),
832
-
833
- redisLastSaveTime: new promClient.Gauge({
834
- name: 'redis_last_save_time',
835
- help: 'Unix timestamp of the last RDB save time'
836
- }),
837
-
838
- redisOpsPerSec: new promClient.Gauge({
839
- name: 'redis_instantaneous_ops_per_sec',
840
- help: 'Throughput operations per second'
841
- }),
842
-
843
- redisCommandRuns: new promClient.Gauge({
844
- name: 'redis_command_runs',
845
- help: 'Redis command counts',
846
- labelNames: ['command']
847
- }),
848
-
849
- redisCommandRunsFailed: new promClient.Gauge({
850
- name: 'redis_command_runs_fail',
851
- help: 'Redis command counts',
852
- labelNames: ['command', 'status']
853
- })
854
- };
567
+ // Prometheus metrics (lib/metrics.js)
568
+ const metrics = setupMetrics();
855
569
 
856
570
  // Inter-thread communication tracking
857
571
  let callQueue = new Map(); // Tracks pending cross-thread calls
@@ -1468,6 +1182,28 @@ let spawnWorker = async (type, opts, slot) => {
1468
1182
  });
1469
1183
  });
1470
1184
 
1185
+ // The worker is up and accepts work: an IMAP worker becomes available for accounts, and
1186
+ // the spawn resolves. The two IMAP checks are apart on purpose: the worker joins the set
1187
+ // before the spawn resolves, and the reassignment runs after it
1188
+ const onWorkerReady = () => {
1189
+ if (type === 'imap') {
1190
+ // IMAP worker is ready to accept accounts
1191
+ availableIMAPWorkers.add(worker);
1192
+ }
1193
+
1194
+ isOnline = true;
1195
+
1196
+ // Initialize heartbeat tracking
1197
+ workerHeartbeats.set(worker, Date.now());
1198
+ workerHealthStatus.set(worker, 'healthy');
1199
+
1200
+ resolve(worker.threadId);
1201
+
1202
+ if (type === 'imap') {
1203
+ onImapWorkerReady(worker);
1204
+ }
1205
+ };
1206
+
1471
1207
  // Handle messages from worker
1472
1208
  worker.on('message', message => {
1473
1209
  // Update message count
@@ -1479,333 +1215,290 @@ let spawnWorker = async (type, opts, slot) => {
1479
1215
  return;
1480
1216
  }
1481
1217
 
1482
- // Handle heartbeat from worker
1483
- if (message.cmd === 'heartbeat') {
1484
- handleWorkerHeartbeat(worker);
1485
- return;
1486
- }
1218
+ switch (message.cmd) {
1219
+ // Handle heartbeat from worker
1220
+ case 'heartbeat':
1221
+ handleWorkerHeartbeat(worker);
1222
+ return;
1487
1223
 
1488
- // Handle response to a call
1489
- if (message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
1490
- let { resolve, reject, timer } = callQueue.get(message.mid);
1491
- clearTimeout(timer);
1492
- callQueue.delete(message.mid);
1493
- if (message.error) {
1494
- return reject(unpackRpcError(message));
1495
- } else {
1496
- return resolve(message.response);
1497
- }
1498
- }
1224
+ // Handle response to a call; one nobody waits for anymore (timed out) is dropped
1225
+ case 'resp':
1226
+ if (message.mid && callQueue.has(message.mid)) {
1227
+ handleRpcResponse(message);
1228
+ }
1229
+ return;
1499
1230
 
1500
- // Handle call from worker
1501
- if (message.cmd === 'call' && message.mid) {
1502
- return onCommand(worker, message.message)
1503
- .then(response => {
1504
- let transferList;
1505
- // Handle transferable objects
1506
- if (response && typeof response === 'object' && response._transfer === true) {
1507
- if (typeof response._response === 'object' && response._response && response._response.buffer) {
1508
- transferList = [response._response.buffer];
1509
- }
1510
- response = response._response;
1511
- }
1231
+ // Handle call from worker
1232
+ case 'call':
1233
+ if (message.mid) {
1234
+ handleRpcCall(worker, message);
1235
+ }
1236
+ return;
1512
1237
 
1513
- let callPayload = {
1514
- cmd: 'resp',
1515
- mid: message.mid,
1516
- response
1517
- };
1238
+ case 'metrics':
1239
+ recordWorkerMetrics(type, message);
1240
+ return;
1518
1241
 
1519
- try {
1520
- postMessage(worker, callPayload, null, transferList);
1521
- } catch (err) {
1522
- // Log buffer info instead of full buffer
1523
- if (Buffer.isBuffer(callPayload.response)) {
1524
- callPayload.response = `Buffer <${callPayload.response.length}B>`;
1525
- }
1242
+ case 'settings':
1243
+ forwardSettings(message);
1244
+ return;
1526
1245
 
1527
- logger.error({ msg: 'Unable to send response to worker', worker: worker.threadId, callPayload, err });
1528
- }
1529
- })
1530
- .catch(err => {
1531
- let callPayload = Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err));
1246
+ case 'change':
1247
+ forwardStateChange(message);
1248
+ return;
1532
1249
 
1533
- try {
1534
- postMessage(worker, callPayload);
1535
- } catch (err) {
1536
- logger.error({ msg: 'Unable to send error response to worker', worker: worker.threadId, callPayload, err });
1537
- }
1538
- });
1250
+ case 'ready':
1251
+ onWorkerReady();
1252
+ return;
1539
1253
  }
1254
+ });
1255
+ });
1256
+ };
1540
1257
 
1541
- // Handle metrics messages
1542
- switch (message.cmd) {
1543
- case 'metrics': {
1544
- let statUpdateKey = false;
1545
- let accountUpdateKey = false;
1546
-
1547
- let { account } = message.meta || {};
1548
-
1549
- // Determine which metrics to update
1550
- switch (message.key) {
1551
- case 'webhooks': {
1552
- let { status } = message.args[0] || {};
1553
- statUpdateKey = `${message.key}:${status}`;
1554
- break;
1555
- }
1258
+ /**
1259
+ * Settles the pending call() a worker answered
1260
+ * @param {Object} message - `resp` message carrying the call's `mid`
1261
+ */
1262
+ function handleRpcResponse(message) {
1263
+ let { resolve, reject, timer } = callQueue.get(message.mid);
1264
+ clearTimeout(timer);
1265
+ callQueue.delete(message.mid);
1266
+ if (message.error) {
1267
+ reject(unpackRpcError(message));
1268
+ } else {
1269
+ resolve(message.response);
1270
+ }
1271
+ }
1556
1272
 
1557
- case 'webhookReq': {
1558
- break;
1559
- }
1273
+ /**
1274
+ * Runs a command a worker asked the main thread for and posts the answer back
1275
+ * @param {Worker} worker - The calling worker
1276
+ * @param {Object} message - `call` message carrying the command and its `mid`
1277
+ */
1278
+ function handleRpcCall(worker, message) {
1279
+ onCommand(worker, message.message)
1280
+ .then(response => {
1281
+ let transferList;
1282
+ // Handle transferable objects
1283
+ if (response && typeof response === 'object' && response._transfer === true) {
1284
+ if (typeof response._response === 'object' && response._response && response._response.buffer) {
1285
+ transferList = [response._response.buffer];
1286
+ }
1287
+ response = response._response;
1288
+ }
1560
1289
 
1561
- case 'events': {
1562
- let { event } = message.args[0] || {};
1563
- if (account) {
1564
- accountUpdateKey = `${message.key}:${event}`;
1565
- }
1290
+ let callPayload = {
1291
+ cmd: 'resp',
1292
+ mid: message.mid,
1293
+ response
1294
+ };
1566
1295
 
1567
- // Track specific events
1568
- switch (event) {
1569
- case MESSAGE_NEW_NOTIFY:
1570
- case MESSAGE_DELETED_NOTIFY:
1571
- case CONNECT_ERROR_NOTIFY:
1572
- statUpdateKey = `${message.key}:${event}`;
1573
- break;
1574
- }
1575
- break;
1576
- }
1296
+ try {
1297
+ postMessage(worker, callPayload, null, transferList);
1298
+ } catch (err) {
1299
+ // Log buffer info instead of full buffer
1300
+ if (Buffer.isBuffer(callPayload.response)) {
1301
+ callPayload.response = `Buffer <${callPayload.response.length}B>`;
1302
+ }
1577
1303
 
1578
- case 'apiCall': {
1579
- let { statusCode, method, route } = message.args[0] || {};
1580
- let success = statusCode >= 200 && statusCode < 300;
1581
- statUpdateKey = `${message.key}:${success ? 'success' : 'fail'}`;
1582
- if (typeof message.duration === 'number' && Number.isFinite(message.duration)) {
1583
- try {
1584
- metrics.apiCallDuration.observe({ method, route }, message.duration);
1585
- } catch (err) {
1586
- logger.error({ msg: 'Unable to apply worker metric', type, key: 'apiCallDuration', err });
1587
- }
1588
- }
1589
- break;
1590
- }
1304
+ logger.error({ msg: 'Unable to send response to worker', worker: worker.threadId, callPayload, err });
1305
+ }
1306
+ })
1307
+ .catch(err => {
1308
+ let callPayload = Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err));
1591
1309
 
1592
- case 'queuesProcessed': {
1593
- let { queue, status } = message.args[0] || {};
1594
- if (['submit'].includes(queue)) {
1595
- statUpdateKey = `${queue}:${status === 'completed' ? 'success' : 'fail'}`;
1596
- }
1597
- break;
1598
- }
1599
- }
1310
+ try {
1311
+ postMessage(worker, callPayload);
1312
+ } catch (err) {
1313
+ logger.error({ msg: 'Unable to send error response to worker', worker: worker.threadId, callPayload, err });
1314
+ }
1315
+ });
1316
+ }
1600
1317
 
1601
- // Update Redis counters for dashboard stats
1602
- if (statUpdateKey) {
1603
- let now = new Date();
1604
-
1605
- // Create daily bucket
1606
- let dateStr = `${now
1607
- .toISOString()
1608
- .substr(0, 10)
1609
- .replace(/[^0-9]+/g, '')}`;
1610
-
1611
- // Create minute bucket
1612
- let timeStr = `${now
1613
- .toISOString()
1614
- .substr(0, 16)
1615
- .replace(/[^0-9]+/g, '')}`;
1616
-
1617
- let hkey = `${REDIS_PREFIX}stats:${statUpdateKey}:${dateStr}`;
1618
-
1619
- let update = redis
1620
- .multi()
1621
- .hincrby(hkey, timeStr, 1)
1622
- .sadd(`${REDIS_PREFIX}stats:keys`, statUpdateKey)
1623
- .expire(hkey, (MAX_DAYS_STATS + 1) * 24 * 3600); // Keep for configured days + 1
1624
-
1625
- if (account && accountUpdateKey) {
1626
- // Update account-specific counter
1627
- let accountKey = accountDataKey(account);
1628
- update = update.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1);
1629
- }
1318
+ /**
1319
+ * Applies a worker's `metrics` message: the dashboard counters in Redis and the Prometheus metric
1320
+ * @param {String} type - Type of the reporting worker
1321
+ * @param {Object} message - `metrics` message
1322
+ */
1323
+ function recordWorkerMetrics(type, message) {
1324
+ let { account, statUpdateKey, accountUpdateKey } = resolveMetricKeys(message);
1630
1325
 
1631
- update.exec().catch(() => false);
1632
- } else if (account && accountUpdateKey) {
1633
- // Update only account-specific counter
1634
- let accountKey = accountDataKey(account);
1635
- redis.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
1636
- }
1326
+ if (message.key === 'apiCall' && typeof message.duration === 'number' && Number.isFinite(message.duration)) {
1327
+ let { method, route } = message.args[0] || {};
1328
+ try {
1329
+ metrics.apiCallDuration.observe({ method, route }, message.duration);
1330
+ } catch (err) {
1331
+ logger.error({ msg: 'Unable to apply worker metric', type, key: 'apiCallDuration', err });
1332
+ }
1333
+ }
1637
1334
 
1638
- // Update Prometheus metrics. prom-client throws synchronously on an unknown
1639
- // label, a negative counter increment or a non-finite value, and this runs in
1640
- // an event handler on the main thread, where a throw would take every worker
1641
- // down with it.
1642
- if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
1643
- try {
1644
- metrics[message.key][message.method](...message.args);
1645
- } catch (err) {
1646
- logger.error({ msg: 'Unable to apply worker metric', type, key: message.key, method: message.method, err });
1647
- }
1648
- }
1335
+ // Update Redis counters for dashboard stats
1336
+ if (statUpdateKey) {
1337
+ let { dateStr, timeStr } = statBuckets(new Date());
1649
1338
 
1650
- return;
1651
- }
1339
+ let hkey = `${REDIS_PREFIX}stats:${statUpdateKey}:${dateStr}`;
1652
1340
 
1653
- case 'settings':
1654
- // Reload the HTTP proxy agent in the main thread when proxy settings change
1655
- maybeReloadHttpProxyAgent(message.data);
1341
+ let update = redis
1342
+ .multi()
1343
+ .hincrby(hkey, timeStr, 1)
1344
+ .sadd(`${REDIS_PREFIX}stats:keys`, statUpdateKey)
1345
+ .expire(hkey, (MAX_DAYS_STATS + 1) * 24 * 3600); // Keep for configured days + 1
1656
1346
 
1657
- // Forward settings changes to all IMAP workers
1658
- availableIMAPWorkers.forEach(worker => {
1659
- try {
1660
- postMessage(worker, message);
1661
- } catch (err) {
1662
- logger.error({
1663
- msg: 'Unable to forward settings to worker',
1664
- worker: worker.threadId,
1665
- settingsKeys: Object.keys(message.data || {}),
1666
- err
1667
- });
1668
- }
1669
- });
1347
+ if (account && accountUpdateKey) {
1348
+ // Update account-specific counter
1349
+ let accountKey = accountDataKey(account);
1350
+ update = update.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1);
1351
+ }
1670
1352
 
1671
- // Forward settings changes to every other worker type (the IMAP workers were
1672
- // handled above); each reloads its HTTP proxy agent from the 'settings' message
1673
- for (let [type, typeWorkers] of workers) {
1674
- if (type === 'imap') {
1675
- continue;
1676
- }
1677
- typeWorkers.forEach(worker => {
1678
- try {
1679
- postMessage(worker, message);
1680
- } catch (err) {
1681
- logger.error({ msg: 'Unable to forward settings to worker', type, worker: worker.threadId, err });
1682
- }
1683
- });
1684
- }
1685
- return;
1353
+ update.exec().catch(() => false);
1354
+ } else if (account && accountUpdateKey) {
1355
+ // Update only account-specific counter
1356
+ let accountKey = accountDataKey(account);
1357
+ redis.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
1358
+ }
1686
1359
 
1687
- case 'change':
1688
- // Handle state changes
1689
- switch (message.type) {
1690
- case 'smtpServerState':
1691
- case 'imapProxyServerState': {
1692
- let type = message.type.replace(/ServerState$/, '');
1693
- reportServerState(type, message.key, message.payload);
1694
- break;
1695
- }
1696
- default:
1697
- // Forward all other state changes to API workers
1698
- for (let worker of workers.get('api') || []) {
1699
- try {
1700
- postMessage(worker, message, true);
1701
- } catch (err) {
1702
- logger.error({ msg: 'Unable to forward state change to worker', worker: worker.threadId, callPayload: message, err });
1703
- }
1704
- }
1705
- }
1706
- break;
1707
- }
1360
+ // Update Prometheus metrics. The Prometheus client throws synchronously on an unknown
1361
+ // label, a negative counter increment or a non-finite value, and this runs in
1362
+ // an event handler on the main thread, where a throw would take every worker
1363
+ // down with it.
1364
+ if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
1365
+ try {
1366
+ metrics[message.key][message.method](...message.args);
1367
+ } catch (err) {
1368
+ logger.error({ msg: 'Unable to apply worker metric', type, key: message.key, method: message.method, err });
1369
+ }
1370
+ }
1371
+ }
1708
1372
 
1709
- // Handle worker type specific messages
1710
- switch (type) {
1711
- case 'imap':
1712
- if (message.cmd === 'ready') {
1713
- // IMAP worker is ready to accept accounts
1714
- availableIMAPWorkers.add(worker);
1715
- isOnline = true;
1716
-
1717
- // Initialize heartbeat tracking
1718
- workerHeartbeats.set(worker, Date.now());
1719
- workerHealthStatus.set(worker, 'healthy');
1720
-
1721
- resolve(worker.threadId);
1722
-
1723
- logger.info({
1724
- msg: 'IMAP worker ready',
1725
- threadId: worker.threadId,
1726
- currentWorkers: availableIMAPWorkers.size,
1727
- expectedWorkers: config.workers.imap,
1728
- unassignedCount: unassigned ? unassigned.size : 0,
1729
- assignedCount: assigned.size,
1730
- imapInitialWorkersLoaded,
1731
- reassignmentPending
1732
- });
1373
+ /**
1374
+ * Applies a settings change in the main thread and forwards it to every worker
1375
+ * @param {Object} message - `settings` message
1376
+ */
1377
+ function forwardSettings(message) {
1378
+ // Reload the HTTP proxy agent in the main thread when proxy settings change
1379
+ maybeReloadHttpProxyAgent(message.data);
1733
1380
 
1734
- if (imapInitialWorkersLoaded && reassignmentPending) {
1735
- // Check if we now have the expected number of workers
1736
- // This handles the case where a worker crashed and restarted
1737
- if (availableIMAPWorkers.size === config.workers.imap) {
1738
- // All workers are back - clear timer and reassign
1739
- if (reassignmentTimer) {
1740
- clearTimeout(reassignmentTimer);
1741
- reassignmentTimer = null;
1742
- }
1743
- reassignmentPending = false;
1744
-
1745
- if (unassigned && unassigned.size > 0) {
1746
- logger.info({
1747
- msg: 'All expected workers ready, reassigning unassigned accounts',
1748
- workers: availableIMAPWorkers.size,
1749
- unassigned: unassigned.size
1750
- });
1751
- assignAccounts().catch(err => logger.error({ msg: 'Unable to assign accounts', err }));
1752
- } else {
1753
- logger.warn({
1754
- msg: 'All workers ready but no unassigned accounts found',
1755
- workers: availableIMAPWorkers.size
1756
- });
1757
- }
1758
- } else if (unassigned && unassigned.size > 0) {
1759
- // Still waiting for more workers to restart
1760
- logger.info({
1761
- msg: 'Worker ready, waiting for all workers before reassignment',
1762
- currentWorkers: availableIMAPWorkers.size,
1763
- expectedWorkers: config.workers.imap,
1764
- unassignedAccounts: unassigned.size
1765
- });
1766
- // The failsafe found no worker at all and stopped; give the rest
1767
- // of the fleet the same time to come back from here
1768
- if (!reassignmentTimer) {
1769
- armReassignmentFailsafe();
1770
- }
1771
- }
1772
- } else if (imapInitialWorkersLoaded) {
1773
- // The failsafe timer already gave this worker's accounts to the
1774
- // survivors (or it is an extra worker), so nothing is pending for it
1775
- rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err }));
1776
- }
1777
- }
1778
- break;
1381
+ // Forward settings changes to all IMAP workers
1382
+ availableIMAPWorkers.forEach(worker => {
1383
+ try {
1384
+ postMessage(worker, message);
1385
+ } catch (err) {
1386
+ logger.error({
1387
+ msg: 'Unable to forward settings to worker',
1388
+ worker: worker.threadId,
1389
+ settingsKeys: Object.keys(message.data || {}),
1390
+ err
1391
+ });
1392
+ }
1393
+ });
1779
1394
 
1780
- case 'api':
1781
- if (message.cmd === 'ready') {
1782
- // API worker is ready
1783
- isOnline = true;
1395
+ // Forward settings changes to every other worker type (the IMAP workers were
1396
+ // handled above); each reloads its HTTP proxy agent from the 'settings' message
1397
+ for (let [type, typeWorkers] of workers) {
1398
+ if (type === 'imap') {
1399
+ continue;
1400
+ }
1401
+ typeWorkers.forEach(worker => {
1402
+ try {
1403
+ postMessage(worker, message);
1404
+ } catch (err) {
1405
+ logger.error({ msg: 'Unable to forward settings to worker', type, worker: worker.threadId, err });
1406
+ }
1407
+ });
1408
+ }
1409
+ }
1784
1410
 
1785
- // Initialize heartbeat tracking
1786
- workerHeartbeats.set(worker, Date.now());
1787
- workerHealthStatus.set(worker, 'healthy');
1411
+ /**
1412
+ * Handles a state change: a listener's own state is recorded here, everything else goes to the
1413
+ * API workers
1414
+ * @param {Object} message - `change` message
1415
+ */
1416
+ function forwardStateChange(message) {
1417
+ switch (message.type) {
1418
+ case 'smtpServerState':
1419
+ case 'imapProxyServerState': {
1420
+ let serverType = message.type.replace(/ServerState$/, '');
1421
+ reportServerState(serverType, message.key, message.payload);
1422
+ break;
1423
+ }
1424
+ default:
1425
+ // Forward all other state changes to API workers
1426
+ for (let worker of workers.get('api') || []) {
1427
+ try {
1428
+ postMessage(worker, message, true);
1429
+ } catch (err) {
1430
+ logger.error({ msg: 'Unable to forward state change to worker', worker: worker.threadId, callPayload: message, err });
1431
+ }
1432
+ }
1433
+ }
1434
+ }
1788
1435
 
1789
- resolve(worker.threadId);
1790
- }
1791
- break;
1436
+ /**
1437
+ * An IMAP worker came up: once the initial set has loaded, hand it the accounts waiting for a
1438
+ * worker, or rebalance onto it
1439
+ * @param {Worker} worker - The IMAP worker that is now available
1440
+ */
1441
+ function onImapWorkerReady(worker) {
1442
+ logger.info({
1443
+ msg: 'IMAP worker ready',
1444
+ threadId: worker.threadId,
1445
+ currentWorkers: availableIMAPWorkers.size,
1446
+ expectedWorkers: config.workers.imap,
1447
+ unassignedCount: unassigned ? unassigned.size : 0,
1448
+ assignedCount: assigned.size,
1449
+ imapInitialWorkersLoaded,
1450
+ reassignmentPending
1451
+ });
1792
1452
 
1793
- default:
1794
- // For all other worker types
1795
- if (message.cmd === 'ready') {
1796
- isOnline = true;
1453
+ if (!imapInitialWorkersLoaded) {
1454
+ return;
1455
+ }
1797
1456
 
1798
- // Initialize heartbeat tracking
1799
- workerHeartbeats.set(worker, Date.now());
1800
- workerHealthStatus.set(worker, 'healthy');
1457
+ if (!reassignmentPending) {
1458
+ // The failsafe timer already gave this worker's accounts to the
1459
+ // survivors (or it is an extra worker), so nothing is pending for it
1460
+ rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err }));
1461
+ return;
1462
+ }
1801
1463
 
1802
- resolve(worker.threadId);
1803
- }
1804
- break;
1805
- }
1464
+ // Check if we now have the expected number of workers
1465
+ // This handles the case where a worker crashed and restarted
1466
+ if (availableIMAPWorkers.size === config.workers.imap) {
1467
+ // All workers are back - clear timer and reassign
1468
+ if (reassignmentTimer) {
1469
+ clearTimeout(reassignmentTimer);
1470
+ reassignmentTimer = null;
1471
+ }
1472
+ reassignmentPending = false;
1473
+
1474
+ if (unassigned && unassigned.size > 0) {
1475
+ logger.info({
1476
+ msg: 'All expected workers ready, reassigning unassigned accounts',
1477
+ workers: availableIMAPWorkers.size,
1478
+ unassigned: unassigned.size
1479
+ });
1480
+ assignAccounts().catch(err => logger.error({ msg: 'Unable to assign accounts', err }));
1481
+ } else {
1482
+ logger.warn({
1483
+ msg: 'All workers ready but no unassigned accounts found',
1484
+ workers: availableIMAPWorkers.size
1485
+ });
1486
+ }
1487
+ } else if (unassigned && unassigned.size > 0) {
1488
+ // Still waiting for more workers to restart
1489
+ logger.info({
1490
+ msg: 'Worker ready, waiting for all workers before reassignment',
1491
+ currentWorkers: availableIMAPWorkers.size,
1492
+ expectedWorkers: config.workers.imap,
1493
+ unassignedAccounts: unassigned.size
1806
1494
  });
1807
- });
1808
- };
1495
+ // The failsafe found no worker at all and stopped; give the rest
1496
+ // of the fleet the same time to come back from here
1497
+ if (!reassignmentTimer) {
1498
+ armReassignmentFailsafe();
1499
+ }
1500
+ }
1501
+ }
1809
1502
 
1810
1503
  /**
1811
1504
  * Call a command on a worker thread and wait for response
@@ -2289,21 +1982,7 @@ let licenseCheckHandler = async opts => {
2289
1982
  let subscriptionCheckTimeout = opts.subscriptionCheckTimeout || checkInterval({ subexp, subsusp });
2290
1983
 
2291
1984
  // Check if we need to validate the license
2292
- let checkKv = true;
2293
- // an unreadable record means checking again, which also rewrites it
2294
- let validatedVersion = kv && typeof kv === 'string' ? Buffer.from(kv, 'hex').toString() : null;
2295
- if (parseVersion(validatedVersion) && compareVersions(packageData.version, validatedVersion) <= 0) {
2296
- checkKv = false;
2297
- }
2298
-
2299
- if (ks && typeof ks === 'string') {
2300
- let ksDate = new Date(parseInt(ks, 16));
2301
- if (ksDate < now) {
2302
- checkKv = true;
2303
- }
2304
- } else {
2305
- checkKv = true;
2306
- }
1985
+ let checkKv = needsVersionRecheck({ kv, ks, version: packageData.version, now });
2307
1986
 
2308
1987
  // Clean up for lifetime licenses
2309
1988
  if (licenseInfo.details && licenseInfo.details.lt) {
@@ -2311,12 +1990,10 @@ let licenseCheckHandler = async opts => {
2311
1990
  subscriptionDeadline = null;
2312
1991
  }
2313
1992
 
2314
- // A suspended license is still registered and still checked, which is how it resumes
2315
- let subscriptionLicense = (licenseInfo.active || !!licenseInfo.suspension) && isSubscriptionLicense(licenseInfo.details);
2316
-
2317
- // A stored deadline that has passed suspends on its own, whether or not the license server
1993
+ // A suspended license is still registered and still checked, which is how it resumes. A
1994
+ // stored deadline that has passed suspends on its own, whether or not the license server
2318
1995
  // can be reached to say so; its next answer decides what happens after that
2319
- let localSuspension = subscriptionLicense && !licenseInfo.suspension ? expiredSuspension(subexp, subsusp, now) : null;
1996
+ let { subscriptionLicense, localSuspension } = subscriptionCheckState(licenseInfo, { subexp, subsusp, now });
2320
1997
  if (localSuspension) {
2321
1998
  await redis.hset(`${REDIS_PREFIX}settings`, 'subsusp', JSON.stringify(localSuspension));
2322
1999
  logger.warn({
@@ -2391,7 +2068,8 @@ let licenseCheckHandler = async opts => {
2391
2068
  }
2392
2069
 
2393
2070
  // Handle no active license - suspend workers
2394
- if (!licenseInfo.active && !suspendedWorkerTypes.size) {
2071
+ let workerChange = workerSuspensionChange(licenseInfo.active, suspendedWorkerTypes.size);
2072
+ if (workerChange === 'suspend') {
2395
2073
  // Said in the present tense, because that is what the loop below does. The line used to
2396
2074
  // promise a 15 minute grace period that nothing anywhere implements, so an operator
2397
2075
  // reading it waited for a window that had already closed.
@@ -2406,7 +2084,7 @@ let licenseCheckHandler = async opts => {
2406
2084
  }
2407
2085
  }
2408
2086
  }
2409
- } else if (licenseInfo.active && suspendedWorkerTypes.size) {
2087
+ } else if (workerChange === 'resume') {
2410
2088
  // Re-enable workers after license activated
2411
2089
  for (let type of suspendedWorkerTypes) {
2412
2090
  suspendedWorkerTypes.delete(type);
@@ -2616,39 +2294,29 @@ function checkRedisPing() {
2616
2294
  * @returns {Promise<void>}
2617
2295
  */
2618
2296
  async function updateQueueCounters() {
2619
- // Update EmailEngine configuration metrics
2297
+ setConfigMetrics();
2298
+ await setThreadMetrics();
2299
+ await setQueueMetrics();
2300
+ await setRedisMetrics();
2301
+ }
2302
+
2303
+ // EmailEngine configuration and license metrics
2304
+ function setConfigMetrics() {
2620
2305
  metrics.emailengineConfig.set({ version: 'v' + packageData.version }, 1);
2621
2306
  metrics.emailengineConfig.set({ config: 'uvThreadpoolSize' }, Number(process.env.UV_THREADPOOL_SIZE));
2622
2307
  metrics.emailengineConfig.set({ config: 'workersImap' }, config.workers.imap);
2623
2308
  metrics.emailengineConfig.set({ config: 'workersWebhooks' }, config.workers.webhooks);
2624
2309
  metrics.emailengineConfig.set({ config: 'workersSubmission' }, config.workers.submit);
2625
2310
 
2626
- // Update license days remaining metric
2627
- if (licenseInfo.active && licenseInfo.details) {
2628
- if (licenseInfo.details.lt) {
2629
- // Lifetime license
2630
- metrics.licenseDaysRemaining.set(-1);
2631
- } else if (licenseInfo.details.expires) {
2632
- // Time-limited license
2633
- let expiresAt = new Date(licenseInfo.details.expires).getTime();
2634
- let daysRemaining = Math.max(0, Math.ceil((expiresAt - Date.now()) / (24 * 60 * 60 * 1000)));
2635
- metrics.licenseDaysRemaining.set(daysRemaining);
2636
- } else {
2637
- // Subscription license (no fixed expiry)
2638
- metrics.licenseDaysRemaining.set(-1);
2639
- }
2640
- } else {
2641
- // No active license
2642
- metrics.licenseDaysRemaining.set(0);
2643
- }
2311
+ metrics.licenseDaysRemaining.set(licenseDaysRemaining(licenseInfo, Date.now()));
2312
+ }
2644
2313
 
2645
- // Update thread metrics
2314
+ // Worker thread metrics
2315
+ async function setThreadMetrics() {
2646
2316
  let threadsInfo = await getThreadsInfo();
2647
2317
 
2648
2318
  let now = Date.now();
2649
2319
 
2650
- let threadCounts = new Map();
2651
- let unresponsiveCount = 0;
2652
2320
  // a replaced thread leaves with its thread id, so the series are rebuilt on every update
2653
2321
  metrics.threadEventLoopDelayMax.reset();
2654
2322
  metrics.threadEventLoopDelayP99.reset();
@@ -2662,27 +2330,8 @@ async function updateQueueCounters() {
2662
2330
  metrics.threadHeapUsed.set(labels, used);
2663
2331
  metrics.threadHeapTotal.set(labels, total);
2664
2332
  }
2665
- for (let workerThreadInfo of threadsInfo || []) {
2666
- let key = workerThreadInfo.type;
2667
- let metricKey = `${key}_total`;
2668
-
2669
- // Check if thread is recent (started within METRIC_RECENT)
2670
- let recent = now - workerThreadInfo.online < METRIC_RECENT;
2671
- if (recent) {
2672
- metricKey = `${key}_recent`;
2673
- }
2674
2333
 
2675
- if (!threadCounts.has(metricKey)) {
2676
- threadCounts.set(metricKey, 1);
2677
- } else {
2678
- threadCounts.set(metricKey, threadCounts.get(metricKey) + 1);
2679
- }
2680
-
2681
- // Count unresponsive workers
2682
- if (workerThreadInfo.resourceUsageError && workerThreadInfo.resourceUsageError.unresponsive) {
2683
- unresponsiveCount++;
2684
- }
2685
- }
2334
+ let { threadCounts, unresponsiveCount } = countThreads(threadsInfo, now, METRIC_RECENT);
2686
2335
 
2687
2336
  // Set thread count metrics
2688
2337
  for (let [key, value] of threadCounts.entries()) {
@@ -2692,15 +2341,17 @@ async function updateQueueCounters() {
2692
2341
 
2693
2342
  // Set unresponsive workers metric
2694
2343
  metrics.unresponsiveWorkers.set(unresponsiveCount);
2344
+ }
2695
2345
 
2696
- // Update queue metrics through BullMQ's own API (lib/queue-stats.js). Counting raw
2697
- // llen/zcard against BullMQ's private key layout broke silently in the 5.x -> 6.x bump: the
2698
- // `:paused` list no longer exists (a paused queue holds its jobs in `wait`), and a leftover
2699
- // `0:` wait-list marker from a 5.x install counts as a phantom waiting job. The `paused`
2700
- // gauge is kept at the 0 the getter reports so existing dashboards keep their series.
2701
- //
2702
- // A queue whose count fails is skipped rather than ending the update: returning here used to
2703
- // leave every Redis gauge below it stale for as long as that one count kept failing.
2346
+ // Queue metrics, through BullMQ's own API (lib/queue-stats.js). Counting raw llen/zcard against
2347
+ // BullMQ's private key layout broke silently in the 5.x -> 6.x bump: the `:paused` list no longer
2348
+ // exists (a paused queue holds its jobs in `wait`), and a leftover `0:` wait-list marker from a
2349
+ // 5.x install counts as a phantom waiting job. The `paused` gauge is kept at the 0 the getter
2350
+ // reports so existing dashboards keep their series.
2351
+ //
2352
+ // A queue whose count fails is skipped rather than ending the update: returning here used to
2353
+ // leave every Redis gauge below it stale for as long as that one count kept failing.
2354
+ async function setQueueMetrics() {
2704
2355
  const counted = [
2705
2356
  ['notify', notifyQueue],
2706
2357
  ['submit', submitQueue],
@@ -2720,8 +2371,10 @@ async function updateQueueCounters() {
2720
2371
  metrics.queues.set({ queue: `${queue}`, state: `waiting` }, stats.waiting);
2721
2372
  metrics.queueFailed.set({ queue: `${queue}` }, stats.failed);
2722
2373
  });
2374
+ }
2723
2375
 
2724
- // Update Redis metrics
2376
+ // Redis metrics
2377
+ async function setRedisMetrics() {
2725
2378
  try {
2726
2379
  let redisInfo = await getRedisStats(redis);
2727
2380
 
@@ -2873,16 +2526,7 @@ async function commandMetrics() {
2873
2526
 
2874
2527
  async function commandStructuredMetrics() {
2875
2528
  // Return structured metrics for API
2876
- let connections = {};
2877
-
2878
- for (let key of Object.keys(metrics.imapConnections.hashMap)) {
2879
- if (key.indexOf('status:') === 0) {
2880
- let metric = metrics.imapConnections.hashMap[key];
2881
- connections[metric.labels.status] = metric.value;
2882
- }
2883
- }
2884
-
2885
- return { connections, redisPing: await getRedisPing() };
2529
+ return { connections: await connectionCounts(metrics.imapConnections), redisPing: await getRedisPing() };
2886
2530
  }
2887
2531
 
2888
2532
  async function commandImapWorkerCount() {