emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. 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';
@@ -66,7 +62,17 @@ if (nodeSupportLevel === 'outside-range') {
66
62
  console.error(`Node.js ${process.version} is outside the range EmailEngine supports (${SUPPORTED_RANGE_LABEL}). It runs, but please upgrade Node.js.`);
67
63
  }
68
64
 
65
+ // Validates EENGINE_LOG_REDACT_HEADERS before the logger loads, so a bad entry stops the boot with a
66
+ // one-line message instead of a stack trace
67
+ try {
68
+ require('./lib/logger-consts');
69
+ } catch (err) {
70
+ console.error(err.message);
71
+ process.exit(1);
72
+ }
73
+
69
74
  const { accountDataKey } = require('./lib/redis-keys');
75
+ const { resolveMetricKeys, statBuckets } = require('./lib/worker-metrics');
70
76
  const { importPreparedPassword } = require('./lib/prepared-password');
71
77
 
72
78
  const os = require('os');
@@ -113,9 +119,6 @@ const MetricsCollector = require('./lib/metrics-collector');
113
119
  // Import constants
114
120
  const {
115
121
  MAX_DAYS_STATS,
116
- MESSAGE_NEW_NOTIFY,
117
- MESSAGE_DELETED_NOTIFY,
118
- CONNECT_ERROR_NOTIFY,
119
122
  REDIS_PREFIX,
120
123
  ACCOUNT_ADDED_NOTIFY,
121
124
  ACCOUNT_DELETED_NOTIFY,
@@ -147,10 +150,9 @@ const { pruneFailedContent } = require('./lib/outbox');
147
150
  const { queueCleanAges } = require('./lib/queue-retention');
148
151
  const { getFailedJobRetention } = require('./lib/env-setting-overrides');
149
152
  const { packRpcError, unpackRpcError } = require('./lib/worker-rpc-error');
150
- const promClient = require('prom-client');
153
+ const { promClient, setupMetrics, connectionCounts } = require('./lib/metrics');
151
154
  const fs = require('fs').promises;
152
155
  const crypto = require('crypto');
153
- const { compareVersions, parseVersion } = require('./lib/utils/version');
154
156
  const Joi = require('joi');
155
157
  const { settingsSchema } = require('./lib/schemas');
156
158
  const settings = require('./lib/settings');
@@ -162,7 +164,9 @@ const { attachBeacon, persistBeaconMarkers } = require('./lib/license-beacon');
162
164
  const {
163
165
  decide,
164
166
  startupPlan,
165
- expiredSuspension,
167
+ needsVersionRecheck,
168
+ subscriptionCheckState,
169
+ workerSuspensionChange,
166
170
  checkInterval,
167
171
  subscriptionView,
168
172
  parseSuspension,
@@ -185,12 +189,14 @@ const {
185
189
  requeueFailedAccounts,
186
190
  forgetAccount,
187
191
  shouldRequeueFailedAssignment,
192
+ findUntrackedAccounts,
188
193
  planRebalance
189
194
  } = require('./lib/account-assignment');
190
195
  const { mapConcurrent } = require('./lib/utils/map-concurrent');
191
196
  const { RespawnTracker, retryWithBackoff } = require('./lib/respawn-backoff');
192
197
  const { legacySmtpOptionsInUse, REMOVAL_DATE } = require('./lib/deprecations');
193
198
  const { heartbeatDiagnostics, eventLoopDelaySeries, threadHeapSeries } = require('./lib/thread-diagnostics');
199
+ const { licenseDaysRemaining, countThreads } = require('./lib/metric-values');
194
200
 
195
201
  const msgpack = require('./lib/msgpack');
196
202
 
@@ -568,290 +574,8 @@ if (preparedPasswordString) {
568
574
  }
569
575
  }
570
576
 
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
- };
577
+ // Prometheus metrics (lib/metrics.js)
578
+ const metrics = setupMetrics();
855
579
 
856
580
  // Inter-thread communication tracking
857
581
  let callQueue = new Map(); // Tracks pending cross-thread calls
@@ -873,6 +597,10 @@ let reassignmentPending = false; // Flag to track if reassignment is pending
873
597
  const REASSIGNMENT_FAILSAFE_DELAY = 10 * 1000; // How long an exited IMAP worker gets to restart before its accounts move
874
598
  let assignRetryCount = 0; // Counter for safety-net retries in assignAccounts
875
599
  let assignRetryTimer = null; // The pending safety-net retry, so passes do not stack them
600
+ // Accounts the orphan sweep adopted, announced with accountAdded once a pass actually assigns them
601
+ // (which may be a later retry pass, not the one the sweep started)
602
+ let announceOnAssign = new Set();
603
+ const ORPHAN_SWEEP_INTERVAL = 60 * 60 * 1000;
876
604
 
877
605
  // Worker management
878
606
  let imapInitialWorkersLoaded = false; // Have all initial IMAP workers started?
@@ -1468,6 +1196,28 @@ let spawnWorker = async (type, opts, slot) => {
1468
1196
  });
1469
1197
  });
1470
1198
 
1199
+ // The worker is up and accepts work: an IMAP worker becomes available for accounts, and
1200
+ // the spawn resolves. The two IMAP checks are apart on purpose: the worker joins the set
1201
+ // before the spawn resolves, and the reassignment runs after it
1202
+ const onWorkerReady = () => {
1203
+ if (type === 'imap') {
1204
+ // IMAP worker is ready to accept accounts
1205
+ availableIMAPWorkers.add(worker);
1206
+ }
1207
+
1208
+ isOnline = true;
1209
+
1210
+ // Initialize heartbeat tracking
1211
+ workerHeartbeats.set(worker, Date.now());
1212
+ workerHealthStatus.set(worker, 'healthy');
1213
+
1214
+ resolve(worker.threadId);
1215
+
1216
+ if (type === 'imap') {
1217
+ onImapWorkerReady(worker);
1218
+ }
1219
+ };
1220
+
1471
1221
  // Handle messages from worker
1472
1222
  worker.on('message', message => {
1473
1223
  // Update message count
@@ -1479,333 +1229,290 @@ let spawnWorker = async (type, opts, slot) => {
1479
1229
  return;
1480
1230
  }
1481
1231
 
1482
- // Handle heartbeat from worker
1483
- if (message.cmd === 'heartbeat') {
1484
- handleWorkerHeartbeat(worker);
1485
- return;
1486
- }
1232
+ switch (message.cmd) {
1233
+ // Handle heartbeat from worker
1234
+ case 'heartbeat':
1235
+ handleWorkerHeartbeat(worker);
1236
+ return;
1487
1237
 
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
- }
1238
+ // Handle response to a call; one nobody waits for anymore (timed out) is dropped
1239
+ case 'resp':
1240
+ if (message.mid && callQueue.has(message.mid)) {
1241
+ handleRpcResponse(message);
1242
+ }
1243
+ return;
1499
1244
 
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
- }
1245
+ // Handle call from worker
1246
+ case 'call':
1247
+ if (message.mid) {
1248
+ handleRpcCall(worker, message);
1249
+ }
1250
+ return;
1512
1251
 
1513
- let callPayload = {
1514
- cmd: 'resp',
1515
- mid: message.mid,
1516
- response
1517
- };
1252
+ case 'metrics':
1253
+ recordWorkerMetrics(type, message);
1254
+ return;
1518
1255
 
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
- }
1256
+ case 'settings':
1257
+ forwardSettings(message);
1258
+ return;
1526
1259
 
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));
1260
+ case 'change':
1261
+ forwardStateChange(message);
1262
+ return;
1532
1263
 
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
- });
1264
+ case 'ready':
1265
+ onWorkerReady();
1266
+ return;
1539
1267
  }
1268
+ });
1269
+ });
1270
+ };
1540
1271
 
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
- }
1272
+ /**
1273
+ * Settles the pending call() a worker answered
1274
+ * @param {Object} message - `resp` message carrying the call's `mid`
1275
+ */
1276
+ function handleRpcResponse(message) {
1277
+ let { resolve, reject, timer } = callQueue.get(message.mid);
1278
+ clearTimeout(timer);
1279
+ callQueue.delete(message.mid);
1280
+ if (message.error) {
1281
+ reject(unpackRpcError(message));
1282
+ } else {
1283
+ resolve(message.response);
1284
+ }
1285
+ }
1556
1286
 
1557
- case 'webhookReq': {
1558
- break;
1559
- }
1287
+ /**
1288
+ * Runs a command a worker asked the main thread for and posts the answer back
1289
+ * @param {Worker} worker - The calling worker
1290
+ * @param {Object} message - `call` message carrying the command and its `mid`
1291
+ */
1292
+ function handleRpcCall(worker, message) {
1293
+ onCommand(worker, message.message)
1294
+ .then(response => {
1295
+ let transferList;
1296
+ // Handle transferable objects
1297
+ if (response && typeof response === 'object' && response._transfer === true) {
1298
+ if (typeof response._response === 'object' && response._response && response._response.buffer) {
1299
+ transferList = [response._response.buffer];
1300
+ }
1301
+ response = response._response;
1302
+ }
1560
1303
 
1561
- case 'events': {
1562
- let { event } = message.args[0] || {};
1563
- if (account) {
1564
- accountUpdateKey = `${message.key}:${event}`;
1565
- }
1304
+ let callPayload = {
1305
+ cmd: 'resp',
1306
+ mid: message.mid,
1307
+ response
1308
+ };
1566
1309
 
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
- }
1310
+ try {
1311
+ postMessage(worker, callPayload, null, transferList);
1312
+ } catch (err) {
1313
+ // Log buffer info instead of full buffer
1314
+ if (Buffer.isBuffer(callPayload.response)) {
1315
+ callPayload.response = `Buffer <${callPayload.response.length}B>`;
1316
+ }
1577
1317
 
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
- }
1318
+ logger.error({ msg: 'Unable to send response to worker', worker: worker.threadId, callPayload, err });
1319
+ }
1320
+ })
1321
+ .catch(err => {
1322
+ let callPayload = Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err));
1591
1323
 
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
- }
1324
+ try {
1325
+ postMessage(worker, callPayload);
1326
+ } catch (err) {
1327
+ logger.error({ msg: 'Unable to send error response to worker', worker: worker.threadId, callPayload, err });
1328
+ }
1329
+ });
1330
+ }
1600
1331
 
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
- }
1332
+ /**
1333
+ * Applies a worker's `metrics` message: the dashboard counters in Redis and the Prometheus metric
1334
+ * @param {String} type - Type of the reporting worker
1335
+ * @param {Object} message - `metrics` message
1336
+ */
1337
+ function recordWorkerMetrics(type, message) {
1338
+ let { account, statUpdateKey, accountUpdateKey } = resolveMetricKeys(message);
1630
1339
 
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
- }
1340
+ if (message.key === 'apiCall' && typeof message.duration === 'number' && Number.isFinite(message.duration)) {
1341
+ let { method, route } = message.args[0] || {};
1342
+ try {
1343
+ metrics.apiCallDuration.observe({ method, route }, message.duration);
1344
+ } catch (err) {
1345
+ logger.error({ msg: 'Unable to apply worker metric', type, key: 'apiCallDuration', err });
1346
+ }
1347
+ }
1637
1348
 
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
- }
1349
+ // Update Redis counters for dashboard stats
1350
+ if (statUpdateKey) {
1351
+ let { dateStr, timeStr } = statBuckets(new Date());
1649
1352
 
1650
- return;
1651
- }
1353
+ let hkey = `${REDIS_PREFIX}stats:${statUpdateKey}:${dateStr}`;
1652
1354
 
1653
- case 'settings':
1654
- // Reload the HTTP proxy agent in the main thread when proxy settings change
1655
- maybeReloadHttpProxyAgent(message.data);
1355
+ let update = redis
1356
+ .multi()
1357
+ .hincrby(hkey, timeStr, 1)
1358
+ .sadd(`${REDIS_PREFIX}stats:keys`, statUpdateKey)
1359
+ .expire(hkey, (MAX_DAYS_STATS + 1) * 24 * 3600); // Keep for configured days + 1
1656
1360
 
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
- });
1361
+ if (account && accountUpdateKey) {
1362
+ // Update account-specific counter
1363
+ let accountKey = accountDataKey(account);
1364
+ update = update.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1);
1365
+ }
1670
1366
 
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;
1367
+ update.exec().catch(() => false);
1368
+ } else if (account && accountUpdateKey) {
1369
+ // Update only account-specific counter
1370
+ let accountKey = accountDataKey(account);
1371
+ redis.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
1372
+ }
1686
1373
 
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
- }
1374
+ // Update Prometheus metrics. The Prometheus client throws synchronously on an unknown
1375
+ // label, a negative counter increment or a non-finite value, and this runs in
1376
+ // an event handler on the main thread, where a throw would take every worker
1377
+ // down with it.
1378
+ if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
1379
+ try {
1380
+ metrics[message.key][message.method](...message.args);
1381
+ } catch (err) {
1382
+ logger.error({ msg: 'Unable to apply worker metric', type, key: message.key, method: message.method, err });
1383
+ }
1384
+ }
1385
+ }
1708
1386
 
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
- });
1387
+ /**
1388
+ * Applies a settings change in the main thread and forwards it to every worker
1389
+ * @param {Object} message - `settings` message
1390
+ */
1391
+ function forwardSettings(message) {
1392
+ // Reload the HTTP proxy agent in the main thread when proxy settings change
1393
+ maybeReloadHttpProxyAgent(message.data);
1733
1394
 
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;
1395
+ // Forward settings changes to all IMAP workers
1396
+ availableIMAPWorkers.forEach(worker => {
1397
+ try {
1398
+ postMessage(worker, message);
1399
+ } catch (err) {
1400
+ logger.error({
1401
+ msg: 'Unable to forward settings to worker',
1402
+ worker: worker.threadId,
1403
+ settingsKeys: Object.keys(message.data || {}),
1404
+ err
1405
+ });
1406
+ }
1407
+ });
1779
1408
 
1780
- case 'api':
1781
- if (message.cmd === 'ready') {
1782
- // API worker is ready
1783
- isOnline = true;
1409
+ // Forward settings changes to every other worker type (the IMAP workers were
1410
+ // handled above); each reloads its HTTP proxy agent from the 'settings' message
1411
+ for (let [type, typeWorkers] of workers) {
1412
+ if (type === 'imap') {
1413
+ continue;
1414
+ }
1415
+ typeWorkers.forEach(worker => {
1416
+ try {
1417
+ postMessage(worker, message);
1418
+ } catch (err) {
1419
+ logger.error({ msg: 'Unable to forward settings to worker', type, worker: worker.threadId, err });
1420
+ }
1421
+ });
1422
+ }
1423
+ }
1784
1424
 
1785
- // Initialize heartbeat tracking
1786
- workerHeartbeats.set(worker, Date.now());
1787
- workerHealthStatus.set(worker, 'healthy');
1425
+ /**
1426
+ * Handles a state change: a listener's own state is recorded here, everything else goes to the
1427
+ * API workers
1428
+ * @param {Object} message - `change` message
1429
+ */
1430
+ function forwardStateChange(message) {
1431
+ switch (message.type) {
1432
+ case 'smtpServerState':
1433
+ case 'imapProxyServerState': {
1434
+ let serverType = message.type.replace(/ServerState$/, '');
1435
+ reportServerState(serverType, message.key, message.payload);
1436
+ break;
1437
+ }
1438
+ default:
1439
+ // Forward all other state changes to API workers
1440
+ for (let worker of workers.get('api') || []) {
1441
+ try {
1442
+ postMessage(worker, message, true);
1443
+ } catch (err) {
1444
+ logger.error({ msg: 'Unable to forward state change to worker', worker: worker.threadId, callPayload: message, err });
1445
+ }
1446
+ }
1447
+ }
1448
+ }
1788
1449
 
1789
- resolve(worker.threadId);
1790
- }
1791
- break;
1450
+ /**
1451
+ * An IMAP worker came up: once the initial set has loaded, hand it the accounts waiting for a
1452
+ * worker, or rebalance onto it
1453
+ * @param {Worker} worker - The IMAP worker that is now available
1454
+ */
1455
+ function onImapWorkerReady(worker) {
1456
+ logger.info({
1457
+ msg: 'IMAP worker ready',
1458
+ threadId: worker.threadId,
1459
+ currentWorkers: availableIMAPWorkers.size,
1460
+ expectedWorkers: config.workers.imap,
1461
+ unassignedCount: unassigned ? unassigned.size : 0,
1462
+ assignedCount: assigned.size,
1463
+ imapInitialWorkersLoaded,
1464
+ reassignmentPending
1465
+ });
1792
1466
 
1793
- default:
1794
- // For all other worker types
1795
- if (message.cmd === 'ready') {
1796
- isOnline = true;
1467
+ if (!imapInitialWorkersLoaded) {
1468
+ return;
1469
+ }
1797
1470
 
1798
- // Initialize heartbeat tracking
1799
- workerHeartbeats.set(worker, Date.now());
1800
- workerHealthStatus.set(worker, 'healthy');
1471
+ if (!reassignmentPending) {
1472
+ // The failsafe timer already gave this worker's accounts to the
1473
+ // survivors (or it is an extra worker), so nothing is pending for it
1474
+ rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err }));
1475
+ return;
1476
+ }
1801
1477
 
1802
- resolve(worker.threadId);
1803
- }
1804
- break;
1805
- }
1478
+ // Check if we now have the expected number of workers
1479
+ // This handles the case where a worker crashed and restarted
1480
+ if (availableIMAPWorkers.size === config.workers.imap) {
1481
+ // All workers are back - clear timer and reassign
1482
+ if (reassignmentTimer) {
1483
+ clearTimeout(reassignmentTimer);
1484
+ reassignmentTimer = null;
1485
+ }
1486
+ reassignmentPending = false;
1487
+
1488
+ if (unassigned && unassigned.size > 0) {
1489
+ logger.info({
1490
+ msg: 'All expected workers ready, reassigning unassigned accounts',
1491
+ workers: availableIMAPWorkers.size,
1492
+ unassigned: unassigned.size
1493
+ });
1494
+ assignAccounts().catch(err => logger.error({ msg: 'Unable to assign accounts', err }));
1495
+ } else {
1496
+ logger.warn({
1497
+ msg: 'All workers ready but no unassigned accounts found',
1498
+ workers: availableIMAPWorkers.size
1499
+ });
1500
+ }
1501
+ } else if (unassigned && unassigned.size > 0) {
1502
+ // Still waiting for more workers to restart
1503
+ logger.info({
1504
+ msg: 'Worker ready, waiting for all workers before reassignment',
1505
+ currentWorkers: availableIMAPWorkers.size,
1506
+ expectedWorkers: config.workers.imap,
1507
+ unassignedAccounts: unassigned.size
1806
1508
  });
1807
- });
1808
- };
1509
+ // The failsafe found no worker at all and stopped; give the rest
1510
+ // of the fleet the same time to come back from here
1511
+ if (!reassignmentTimer) {
1512
+ armReassignmentFailsafe();
1513
+ }
1514
+ }
1515
+ }
1809
1516
 
1810
1517
  /**
1811
1518
  * Call a command on a worker thread and wait for response
@@ -2100,14 +1807,19 @@ async function assignAccounts() {
2100
1807
 
2101
1808
  logger.error({ msg: 'Failed to assign account to worker', account, threadId: worker.threadId, err });
2102
1809
 
2103
- if (await shouldRequeueFailedAssignment(err, account, isRegisteredAccount)) {
1810
+ if (await shouldRequeueFailedAssignment(account, isRegisteredAccount)) {
2104
1811
  failedAccounts.push(account);
2105
1812
  } else {
1813
+ announceOnAssign.delete(account);
2106
1814
  logger.info({ msg: 'Dropped assignment of an account that no longer exists', account });
2107
1815
  }
2108
1816
  continue;
2109
1817
  }
2110
1818
 
1819
+ if (announceOnAssign.delete(account)) {
1820
+ sendWebhook(account, ACCOUNT_ADDED_NOTIFY, { account }).catch(err => logger.error({ msg: 'Account added webhook failed', account, err }));
1821
+ }
1822
+
2111
1823
  // Add delay between assignments to avoid overwhelming the system
2112
1824
  if (CONNECTION_SETUP_DELAY) {
2113
1825
  await new Promise(r => setTimeout(r, CONNECTION_SETUP_DELAY));
@@ -2156,6 +1868,47 @@ async function assignAccounts() {
2156
1868
  }
2157
1869
  }
2158
1870
 
1871
+ /**
1872
+ * Safety net for registered accounts the assignment state lost track of. assignAccounts() reads the
1873
+ * registered set only on its first run, so an account whose `new` dispatch never reached the main
1874
+ * thread (Account.notifyWorker() logs that failure rather than failing the saved create) stayed
1875
+ * unsynced until a restart. Queues such accounts and announces each with accountAdded once a pass
1876
+ * assigns it, since the lost dispatch was what would have announced it
1877
+ * @returns {Promise<void>}
1878
+ */
1879
+ async function sweepOrphanedAccounts() {
1880
+ if (isClosing || assigning || !unassigned || !availableIMAPWorkers.size) {
1881
+ return;
1882
+ }
1883
+
1884
+ // SSCAN in batches rather than SMEMBERS, so a large account set does not stall the main thread
1885
+ let candidates = new Set();
1886
+ let cursor = '0';
1887
+ do {
1888
+ let [nextCursor, batch] = await redis.sscan(`${REDIS_PREFIX}ia:accounts`, cursor, 'COUNT', 1000);
1889
+ cursor = nextCursor;
1890
+ for (let account of findUntrackedAccounts(batch, { assigned, unassigned })) {
1891
+ candidates.add(account);
1892
+ }
1893
+ } while (cursor !== '0' && !isClosing);
1894
+
1895
+ // Settled after the scan: a create has queued the account and an assignment pass may have
1896
+ // picked some up. An account deleted during the scan is dropped by the pass's membership check
1897
+ // after its assign fails, before anything is announced
1898
+ let orphaned = findUntrackedAccounts(candidates, { assigned, unassigned });
1899
+ if (!orphaned.length || isClosing) {
1900
+ return;
1901
+ }
1902
+
1903
+ logger.warn({ msg: 'Queueing registered accounts that were never assigned', count: orphaned.length, accounts: orphaned.slice(0, 20) });
1904
+ for (let account of orphaned) {
1905
+ unassigned.add(account);
1906
+ announceOnAssign.add(account);
1907
+ }
1908
+ // When a pass is already running this returns at once; that pass's retry picks the accounts up
1909
+ await assignAccounts();
1910
+ }
1911
+
2159
1912
  // License checking state
2160
1913
  let licenseCheckTimer = false;
2161
1914
  let checkingLicense = false;
@@ -2289,21 +2042,7 @@ let licenseCheckHandler = async opts => {
2289
2042
  let subscriptionCheckTimeout = opts.subscriptionCheckTimeout || checkInterval({ subexp, subsusp });
2290
2043
 
2291
2044
  // 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
- }
2045
+ let checkKv = needsVersionRecheck({ kv, ks, version: packageData.version, now });
2307
2046
 
2308
2047
  // Clean up for lifetime licenses
2309
2048
  if (licenseInfo.details && licenseInfo.details.lt) {
@@ -2311,12 +2050,10 @@ let licenseCheckHandler = async opts => {
2311
2050
  subscriptionDeadline = null;
2312
2051
  }
2313
2052
 
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
2053
+ // A suspended license is still registered and still checked, which is how it resumes. A
2054
+ // stored deadline that has passed suspends on its own, whether or not the license server
2318
2055
  // 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;
2056
+ let { subscriptionLicense, localSuspension } = subscriptionCheckState(licenseInfo, { subexp, subsusp, now });
2320
2057
  if (localSuspension) {
2321
2058
  await redis.hset(`${REDIS_PREFIX}settings`, 'subsusp', JSON.stringify(localSuspension));
2322
2059
  logger.warn({
@@ -2391,7 +2128,8 @@ let licenseCheckHandler = async opts => {
2391
2128
  }
2392
2129
 
2393
2130
  // Handle no active license - suspend workers
2394
- if (!licenseInfo.active && !suspendedWorkerTypes.size) {
2131
+ let workerChange = workerSuspensionChange(licenseInfo.active, suspendedWorkerTypes.size);
2132
+ if (workerChange === 'suspend') {
2395
2133
  // Said in the present tense, because that is what the loop below does. The line used to
2396
2134
  // promise a 15 minute grace period that nothing anywhere implements, so an operator
2397
2135
  // reading it waited for a window that had already closed.
@@ -2406,7 +2144,7 @@ let licenseCheckHandler = async opts => {
2406
2144
  }
2407
2145
  }
2408
2146
  }
2409
- } else if (licenseInfo.active && suspendedWorkerTypes.size) {
2147
+ } else if (workerChange === 'resume') {
2410
2148
  // Re-enable workers after license activated
2411
2149
  for (let type of suspendedWorkerTypes) {
2412
2150
  suspendedWorkerTypes.delete(type);
@@ -2616,39 +2354,29 @@ function checkRedisPing() {
2616
2354
  * @returns {Promise<void>}
2617
2355
  */
2618
2356
  async function updateQueueCounters() {
2619
- // Update EmailEngine configuration metrics
2357
+ setConfigMetrics();
2358
+ await setThreadMetrics();
2359
+ await setQueueMetrics();
2360
+ await setRedisMetrics();
2361
+ }
2362
+
2363
+ // EmailEngine configuration and license metrics
2364
+ function setConfigMetrics() {
2620
2365
  metrics.emailengineConfig.set({ version: 'v' + packageData.version }, 1);
2621
2366
  metrics.emailengineConfig.set({ config: 'uvThreadpoolSize' }, Number(process.env.UV_THREADPOOL_SIZE));
2622
2367
  metrics.emailengineConfig.set({ config: 'workersImap' }, config.workers.imap);
2623
2368
  metrics.emailengineConfig.set({ config: 'workersWebhooks' }, config.workers.webhooks);
2624
2369
  metrics.emailengineConfig.set({ config: 'workersSubmission' }, config.workers.submit);
2625
2370
 
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
- }
2371
+ metrics.licenseDaysRemaining.set(licenseDaysRemaining(licenseInfo, Date.now()));
2372
+ }
2644
2373
 
2645
- // Update thread metrics
2374
+ // Worker thread metrics
2375
+ async function setThreadMetrics() {
2646
2376
  let threadsInfo = await getThreadsInfo();
2647
2377
 
2648
2378
  let now = Date.now();
2649
2379
 
2650
- let threadCounts = new Map();
2651
- let unresponsiveCount = 0;
2652
2380
  // a replaced thread leaves with its thread id, so the series are rebuilt on every update
2653
2381
  metrics.threadEventLoopDelayMax.reset();
2654
2382
  metrics.threadEventLoopDelayP99.reset();
@@ -2662,27 +2390,8 @@ async function updateQueueCounters() {
2662
2390
  metrics.threadHeapUsed.set(labels, used);
2663
2391
  metrics.threadHeapTotal.set(labels, total);
2664
2392
  }
2665
- for (let workerThreadInfo of threadsInfo || []) {
2666
- let key = workerThreadInfo.type;
2667
- let metricKey = `${key}_total`;
2668
2393
 
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
-
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
- }
2394
+ let { threadCounts, unresponsiveCount } = countThreads(threadsInfo, now, METRIC_RECENT);
2686
2395
 
2687
2396
  // Set thread count metrics
2688
2397
  for (let [key, value] of threadCounts.entries()) {
@@ -2692,15 +2401,17 @@ async function updateQueueCounters() {
2692
2401
 
2693
2402
  // Set unresponsive workers metric
2694
2403
  metrics.unresponsiveWorkers.set(unresponsiveCount);
2404
+ }
2695
2405
 
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.
2406
+ // Queue metrics, through BullMQ's own API (lib/queue-stats.js). Counting raw llen/zcard against
2407
+ // BullMQ's private key layout broke silently in the 5.x -> 6.x bump: the `:paused` list no longer
2408
+ // exists (a paused queue holds its jobs in `wait`), and a leftover `0:` wait-list marker from a
2409
+ // 5.x install counts as a phantom waiting job. The `paused` gauge is kept at the 0 the getter
2410
+ // reports so existing dashboards keep their series.
2411
+ //
2412
+ // A queue whose count fails is skipped rather than ending the update: returning here used to
2413
+ // leave every Redis gauge below it stale for as long as that one count kept failing.
2414
+ async function setQueueMetrics() {
2704
2415
  const counted = [
2705
2416
  ['notify', notifyQueue],
2706
2417
  ['submit', submitQueue],
@@ -2720,8 +2431,10 @@ async function updateQueueCounters() {
2720
2431
  metrics.queues.set({ queue: `${queue}`, state: `waiting` }, stats.waiting);
2721
2432
  metrics.queueFailed.set({ queue: `${queue}` }, stats.failed);
2722
2433
  });
2434
+ }
2723
2435
 
2724
- // Update Redis metrics
2436
+ // Redis metrics
2437
+ async function setRedisMetrics() {
2725
2438
  try {
2726
2439
  let redisInfo = await getRedisStats(redis);
2727
2440
 
@@ -2873,16 +2586,7 @@ async function commandMetrics() {
2873
2586
 
2874
2587
  async function commandStructuredMetrics() {
2875
2588
  // 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() };
2589
+ return { connections: await connectionCounts(metrics.imapConnections), redisPing: await getRedisPing() };
2886
2590
  }
2887
2591
 
2888
2592
  async function commandImapWorkerCount() {
@@ -3161,6 +2865,20 @@ async function commandNewAccount(worker, message) {
3161
2865
  // before that used to throw here and fail the request with a 500. Skipping the add is
3162
2866
  // safe rather than merely quiet: the account is already in `ia:accounts` by the time
3163
2867
  // this message is sent, so the first load picks it up.
2868
+ //
2869
+ // This dispatch announces the account itself, so the orphan sweep must not announce it again
2870
+ announceOnAssign.delete(message.account);
2871
+ if (assigned.has(message.account)) {
2872
+ // Still assigned: a `delete` for an earlier account with the same id never arrived, or the
2873
+ // orphan sweep adopted this one first. Queueing it again would let the next pass assign it to
2874
+ // a second worker, two connections for one account. The worker holding it reconnects instead,
2875
+ // which reloads the stored record
2876
+ commandForwardToAccountWorker(worker, { cmd: 'reconnect', account: message.account });
2877
+ sendWebhook(message.account, ACCOUNT_ADDED_NOTIFY, { account: message.account }).catch(err =>
2878
+ logger.error({ msg: 'Account added webhook failed', account: message.account, err })
2879
+ );
2880
+ return;
2881
+ }
3164
2882
  if (unassigned) {
3165
2883
  unassigned.add(message.account);
3166
2884
  }
@@ -3176,6 +2894,7 @@ async function commandDeleteAccount(worker, message) {
3176
2894
  // answered with a 500 for a deletion that had in fact succeeded: the account was
3177
2895
  // already gone from Redis by the time this message was sent.
3178
2896
  let assignedWorker = forgetAccount({ workerAssigned, assigned, unassigned }, message.account);
2897
+ announceOnAssign.delete(message.account);
3179
2898
  if (assignedWorker) {
3180
2899
  // Notify worker to clean up
3181
2900
  call(assignedWorker, message)
@@ -4173,6 +3892,10 @@ startApplication()
4173
3892
  collectMetrics().catch(err => logger.error({ msg: 'Metrics collection failed', err }));
4174
3893
  }, 1000).unref();
4175
3894
 
3895
+ setInterval(() => {
3896
+ sweepOrphanedAccounts().catch(err => logger.error({ msg: 'Orphaned account sweep failed', err }));
3897
+ }, ORPHAN_SWEEP_INTERVAL).unref();
3898
+
4176
3899
  // Schedule periodic checks. A monthly-plan license, or one that is not in good standing, is
4177
3900
  // checked right away (unless an hour has not passed since the last check, so a restart
4178
3901
  // loop costs one call an hour); everything else after the usual first delay