emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
package/server.js CHANGED
@@ -40,15 +40,27 @@ if (!process.env.EE_ENV_LOADED) {
40
40
  // Set process title for easier identification in process lists
41
41
  process.title = 'emailengine';
42
42
 
43
- // EmailEngine and its dependencies need Node 20 or newer, the same floor the engines field in
44
- // package.json declares. Checked before anything is required, so an older runtime gets this line
45
- // instead of a syntax error from a dependency. The check used to be a structuredClone probe, which
46
- // only caught Node 16 and older.
43
+ // EmailEngine and its dependencies need Node 20 or newer. Checked before anything is required, so an
44
+ // older runtime gets this line instead of a syntax error from a dependency. The check used to be a
45
+ // structuredClone probe, which only caught Node 16 and older.
47
46
  if (Number(process.versions.node.split('.')[0]) < 20) {
48
47
  console.error(`Node.js version ${process.version} is not supported. Please upgrade to Node.js 20 or later.`);
49
48
  process.exit(1);
50
49
  }
51
50
 
51
+ // Within Node 20 the dependency tree itself asks for 20.19.0 (html-to-text 10, the entities release
52
+ // node-html-parser pulls in) or 20.18.1 (undici 7), which is what the engines field declares. npm
53
+ // treats that field as advice, and an older 20.x starts and then fails somewhere in a dependency at
54
+ // runtime, so it is named here. Only a warning: one-click DigitalOcean images upgrade EmailEngine on
55
+ // their own but not the Node they run on, and an instance that works today must not stop at its next
56
+ // self-upgrade over a minor version it may never exercise.
57
+ const { MIN_SUPPORTED_NODE, isBelowSupportedNode } = require('./lib/node-version');
58
+ if (isBelowSupportedNode(process.versions.node)) {
59
+ console.error(
60
+ `Node.js version ${process.version} is older than ${MIN_SUPPORTED_NODE}, the oldest release EmailEngine's dependencies support. Some features may fail at runtime. Please upgrade Node.js.`
61
+ );
62
+ }
63
+
52
64
  const os = require('os');
53
65
 
54
66
  // Set UV thread pool size for better async I/O performance
@@ -120,9 +132,11 @@ initSentry('main');
120
132
 
121
133
  // Import additional dependencies
122
134
  const pathlib = require('path');
123
- const { redis, queueConf, notifyQueue, submitQueue, exportQueue, logBullErrors } = require('./lib/db');
135
+ const { redis, notifyQueue, submitQueue, exportQueue } = require('./lib/db');
124
136
  const { queueStats } = require('./lib/queue-stats');
125
137
  const { pruneFailedContent } = require('./lib/outbox');
138
+ const { queueCleanAges } = require('./lib/queue-retention');
139
+ const { getFailedJobRetention } = require('./lib/env-setting-overrides');
126
140
  const { packRpcError, unpackRpcError } = require('./lib/worker-rpc-error');
127
141
  const promClient = require('prom-client');
128
142
  const fs = require('fs').promises;
@@ -139,14 +153,14 @@ const tokens = require('./lib/tokens');
139
153
 
140
154
  const { checkRateLimit } = require('./lib/rate-limit');
141
155
 
142
- const { QueueEvents } = require('bullmq');
143
-
144
156
  const getSecret = require('./lib/get-secret');
145
157
 
146
158
  const { rejectWorkerCalls } = require('./lib/reject-worker-calls');
147
159
  const {
148
160
  pickLeastLoadedWorker,
149
161
  rollbackAssignment,
162
+ assignRetryDelay,
163
+ QUICK_ASSIGN_RETRIES,
150
164
  releaseWorkerAccounts,
151
165
  requeueFailedAccounts,
152
166
  forgetAccount,
@@ -154,8 +168,9 @@ const {
154
168
  planRebalance
155
169
  } = require('./lib/account-assignment');
156
170
  const { mapConcurrent } = require('./lib/utils/map-concurrent');
157
- const { RespawnTracker } = require('./lib/respawn-backoff');
158
- const { heartbeatDiagnostics, eventLoopDelaySeries } = require('./lib/thread-diagnostics');
171
+ const { RespawnTracker, retryWithBackoff } = require('./lib/respawn-backoff');
172
+ const { legacySmtpOptionsInUse, REMOVAL_DATE } = require('./lib/deprecations');
173
+ const { heartbeatDiagnostics, eventLoopDelaySeries, threadHeapSeries } = require('./lib/thread-diagnostics');
159
174
 
160
175
  const msgpack = require('./lib/msgpack');
161
176
 
@@ -241,7 +256,8 @@ config.api.host = readEnvValue('EENGINE_HOST') || config.api.host;
241
256
 
242
257
  config.log.level = readEnvValue('EENGINE_LOG_LEVEL') || config.log.level;
243
258
 
244
- // Legacy SMTP configuration options (will be removed in future versions)
259
+ // Legacy SMTP configuration options, removed after REMOVAL_DATE (lib/deprecations.js). They only
260
+ // seed the SMTP server settings on a first start; the admin UI and the settings API own them after that
245
261
  const SMTP_ENABLED = hasEnvValue('EENGINE_SMTP_ENABLED') ? getBoolean(readEnvValue('EENGINE_SMTP_ENABLED')) : getBoolean(config.smtp.enabled);
246
262
  const SMTP_SECRET = readEnvValue('EENGINE_SMTP_SECRET') || config.smtp.secret;
247
263
  const SMTP_PORT = (readEnvValue('EENGINE_SMTP_PORT') && Number(readEnvValue('EENGINE_SMTP_PORT'))) || Number(config.smtp.port) || 2525;
@@ -293,6 +309,15 @@ logger.info({
293
309
  workersSubmission: config.workers.submit
294
310
  });
295
311
 
312
+ const legacySmtpOptions = legacySmtpOptionsInUse({ hasEnvValue, smtpConfig: config.smtp });
313
+ if (legacySmtpOptions.length) {
314
+ logger.warn({
315
+ msg: 'Deprecated SMTP server options are set, configure the SMTP server in the admin UI or through the settings API instead',
316
+ options: legacySmtpOptions,
317
+ removal: REMOVAL_DATE
318
+ });
319
+ }
320
+
296
321
  // Standard response for when no active worker is available
297
322
  const NO_ACTIVE_HANDLER_RESP_ERR = new Error('No active handler for requested account. Try again later.');
298
323
  NO_ACTIVE_HANDLER_RESP_ERR.statusCode = 503;
@@ -363,9 +388,6 @@ const THREAD_CONFIG_VALUES = {
363
388
  export: { key: 'EENGINE_WORKERS_EXPORT', value: config.workers.export }
364
389
  };
365
390
 
366
- // Queue event handlers for different job queues
367
- const queueEvents = {};
368
-
369
391
  // Unique run index for this server instance
370
392
  let runIndex;
371
393
 
@@ -558,6 +580,15 @@ const metrics = {
558
580
  labelNames: ['method', 'statusCode', 'route']
559
581
  }),
560
582
 
583
+ // Labelled by route, not by status: the counter above already splits by status, and a latency
584
+ // series per status code would multiply the route count for little an operator can act on
585
+ apiCallDuration: new promClient.Histogram({
586
+ name: 'api_call_duration_seconds',
587
+ help: 'Duration of API calls, from receiving the request to sending the response',
588
+ labelNames: ['method', 'route'],
589
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60]
590
+ }),
591
+
561
592
  imapConnections: new promClient.Gauge({
562
593
  name: 'imap_connections',
563
594
  help: 'Current IMAP connection state',
@@ -646,6 +677,12 @@ const metrics = {
646
677
  labelNames: ['queue', 'state']
647
678
  }),
648
679
 
680
+ queueFailed: new promClient.Gauge({
681
+ name: 'queue_failed_jobs',
682
+ help: 'Failed jobs a queue still retains (deliveries that were given up on)',
683
+ labelNames: ['queue']
684
+ }),
685
+
649
686
  queuesProcessed: new promClient.Counter({
650
687
  name: 'queues_processed',
651
688
  help: 'Processed job count',
@@ -675,6 +712,18 @@ const metrics = {
675
712
  labelNames: ['type', 'thread']
676
713
  }),
677
714
 
715
+ threadHeapUsed: new promClient.Gauge({
716
+ name: 'thread_heap_used_bytes',
717
+ help: 'V8 heap in use by a thread, as of the last collection (15s)',
718
+ labelNames: ['type', 'thread']
719
+ }),
720
+
721
+ threadHeapTotal: new promClient.Gauge({
722
+ name: 'thread_heap_total_bytes',
723
+ help: 'V8 heap allocated by a thread, as of the last collection (15s)',
724
+ labelNames: ['type', 'thread']
725
+ }),
726
+
678
727
  licenseDaysRemaining: new promClient.Gauge({
679
728
  name: 'license_days_remaining',
680
729
  help: 'Days until license expires (-1 for lifetime, 0 for no license)'
@@ -810,7 +859,7 @@ let reassignmentTimer = null; // Timer for failsafe reassignment
810
859
  let reassignmentPending = false; // Flag to track if reassignment is pending
811
860
  const REASSIGNMENT_FAILSAFE_DELAY = 10 * 1000; // How long an exited IMAP worker gets to restart before its accounts move
812
861
  let assignRetryCount = 0; // Counter for safety-net retries in assignAccounts
813
- const MAX_ASSIGN_RETRIES = 3; // Max consecutive safety-net retries before giving up
862
+ let assignRetryTimer = null; // The pending safety-net retry, so passes do not stack them
814
863
 
815
864
  // Worker management
816
865
  let imapInitialWorkersLoaded = false; // Have all initial IMAP workers started?
@@ -898,6 +947,18 @@ let updateServerState = async (type, state, payload) => {
898
947
  }
899
948
  };
900
949
 
950
+ /**
951
+ * updateServerState() as a report: never rejects. The listener state is what the admin UI shows,
952
+ * and a write Redis refuses (OOM, READONLY) must neither keep a worker from starting nor reach
953
+ * the global handler from a call nobody awaits
954
+ * @param {string} type - Server type ('smtp' or 'imapProxy')
955
+ * @param {string} state - New state
956
+ * @param {Object} [payload] - Optional payload data
957
+ * @returns {Promise<void>}
958
+ */
959
+ const reportServerState = (type, state, payload) =>
960
+ updateServerState(type, state, payload).catch(err => logger.error({ msg: 'Unable to update server state', type, state, err }));
961
+
901
962
  /**
902
963
  * Get detailed information about all threads
903
964
  * @returns {Promise<Array>} Array of thread information objects
@@ -1172,20 +1233,30 @@ let spawnWorker = async (type, opts, slot) => {
1172
1233
  // Check if worker type is suspended (no license)
1173
1234
  if (suspendedWorkerTypes.has(type)) {
1174
1235
  if (['smtp', 'imapProxy'].includes(type)) {
1175
- await updateServerState(type, 'suspended', {});
1236
+ await reportServerState(type, 'suspended', {});
1176
1237
  }
1177
1238
  return;
1178
1239
  }
1179
1240
 
1180
1241
  // Check if server type is enabled
1181
1242
  if (['smtp', 'imapProxy'].includes(type)) {
1182
- let serverEnabled = await settings.get(`${type}ServerEnabled`);
1243
+ // Retried rather than failed: a respawn that could not read the setting (Redis refusing
1244
+ // commands, a failover) used to end the respawn chain, and the listener stayed down until
1245
+ // the process restarted
1246
+ let serverEnabled = await retryWithBackoff(() => settings.get(`${type}ServerEnabled`), {
1247
+ delayFor: attempt => respawnTracker.delayFor(attempt),
1248
+ shouldStop: () => isClosing,
1249
+ onError: (err, delay) => logger.error({ msg: 'Unable to read the listener setting, retrying', type, delay, err })
1250
+ });
1251
+ if (isClosing) {
1252
+ return;
1253
+ }
1183
1254
  if (!serverEnabled) {
1184
- await updateServerState(type, 'disabled', {});
1255
+ await reportServerState(type, 'disabled', {});
1185
1256
  return;
1186
1257
  }
1187
1258
 
1188
- await updateServerState(type, 'spawning');
1259
+ await reportServerState(type, 'spawning');
1189
1260
  }
1190
1261
 
1191
1262
  // A fresh spawn opens its own slot. Counting the crash streak per type made every short-lived
@@ -1226,7 +1297,7 @@ let spawnWorker = async (type, opts, slot) => {
1226
1297
  // Handle worker coming online
1227
1298
  worker.on('online', () => {
1228
1299
  if (['smtp', 'imapProxy'].includes(type)) {
1229
- updateServerState(type, 'initializing').catch(err => logger.error({ msg: 'Unable to update server state', type, err }));
1300
+ reportServerState(type, 'initializing');
1230
1301
  }
1231
1302
  onlineWorkers.add(worker);
1232
1303
 
@@ -1271,12 +1342,9 @@ let spawnWorker = async (type, opts, slot) => {
1271
1342
 
1272
1343
  // Update server state for proxy servers
1273
1344
  if (['smtp', 'imapProxy'].includes(type)) {
1274
- // Not awaited, so the rejection has to be handled here: a Redis reply error
1275
- // (OOM, READONLY) would otherwise reach the global handler and take the whole
1276
- // process down with it.
1277
- updateServerState(type, suspendedWorkerTypes.has(type) ? 'suspended' : 'exited').catch(err =>
1278
- logger.error({ msg: 'Unable to update server state', type, err })
1279
- );
1345
+ // Not awaited: reportServerState() handles a Redis reply error (OOM, READONLY), which
1346
+ // would otherwise reach the global handler and take the whole process down with it
1347
+ reportServerState(type, suspendedWorkerTypes.has(type) ? 'suspended' : 'exited');
1280
1348
  }
1281
1349
 
1282
1350
  // Handle IMAP worker cleanup
@@ -1495,9 +1563,16 @@ let spawnWorker = async (type, opts, slot) => {
1495
1563
  }
1496
1564
 
1497
1565
  case 'apiCall': {
1498
- let { statusCode } = message.args[0] || {};
1566
+ let { statusCode, method, route } = message.args[0] || {};
1499
1567
  let success = statusCode >= 200 && statusCode < 300;
1500
1568
  statUpdateKey = `${message.key}:${success ? 'success' : 'fail'}`;
1569
+ if (typeof message.duration === 'number' && Number.isFinite(message.duration)) {
1570
+ try {
1571
+ metrics.apiCallDuration.observe({ method, route }, message.duration);
1572
+ } catch (err) {
1573
+ logger.error({ msg: 'Unable to apply worker metric', type, key: 'apiCallDuration', err });
1574
+ }
1575
+ }
1501
1576
  break;
1502
1577
  }
1503
1578
 
@@ -1537,14 +1612,14 @@ let spawnWorker = async (type, opts, slot) => {
1537
1612
  if (account && accountUpdateKey) {
1538
1613
  // Update account-specific counter
1539
1614
  let accountKey = `${REDIS_PREFIX}iad:${account}`;
1540
- update = update.hincrby(accountKey, `stats:count:${accountUpdateKey}`, 1);
1615
+ update = update.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1);
1541
1616
  }
1542
1617
 
1543
1618
  update.exec().catch(() => false);
1544
1619
  } else if (account && accountUpdateKey) {
1545
1620
  // Update only account-specific counter
1546
1621
  let accountKey = `${REDIS_PREFIX}iad:${account}`;
1547
- redis.hincrby(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
1622
+ redis.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
1548
1623
  }
1549
1624
 
1550
1625
  // Update Prometheus metrics. prom-client throws synchronously on an unknown
@@ -1602,9 +1677,7 @@ let spawnWorker = async (type, opts, slot) => {
1602
1677
  case 'smtpServerState':
1603
1678
  case 'imapProxyServerState': {
1604
1679
  let type = message.type.replace(/ServerState$/, '');
1605
- updateServerState(type, message.key, message.payload).catch(err =>
1606
- logger.error({ msg: 'Unable to update server state', type, err })
1607
- );
1680
+ reportServerState(type, message.key, message.payload);
1608
1681
  break;
1609
1682
  }
1610
1683
  default:
@@ -2045,28 +2118,25 @@ async function assignAccounts() {
2045
2118
 
2046
2119
  assigning = false;
2047
2120
 
2048
- // Safety net: if accounts remain unassigned, schedule a retry with backoff
2121
+ // Safety net: if accounts remain unassigned, schedule a retry with backoff, and keep
2122
+ // retrying slowly after the quick ones, see assignRetryDelay()
2049
2123
  if (unassigned && unassigned.size > 0 && availableIMAPWorkers.size > 0 && !isClosing) {
2050
2124
  assignRetryCount++;
2051
- if (assignRetryCount <= MAX_ASSIGN_RETRIES) {
2052
- let delay = 5000 * assignRetryCount;
2053
- logger.warn({
2054
- msg: 'Accounts remain unassigned after assignment pass, scheduling retry',
2055
- remaining: unassigned.size,
2056
- retry: assignRetryCount,
2057
- maxRetries: MAX_ASSIGN_RETRIES,
2058
- delayMs: delay
2059
- });
2060
- setTimeout(() => {
2061
- assignAccounts().catch(err => logger.error({ msg: 'Retry assignment failed', err }));
2062
- }, delay);
2063
- } else {
2064
- logger.error({
2065
- msg: 'Max assignment retries reached, accounts remain unassigned',
2066
- remaining: unassigned.size
2067
- });
2068
- assignRetryCount = 0;
2069
- }
2125
+ let delay = assignRetryDelay(assignRetryCount);
2126
+ logger[assignRetryCount <= QUICK_ASSIGN_RETRIES ? 'warn' : 'error']({
2127
+ msg: 'Accounts remain unassigned after assignment pass, scheduling retry',
2128
+ remaining: unassigned.size,
2129
+ retry: assignRetryCount,
2130
+ delayMs: delay
2131
+ });
2132
+ clearTimeout(assignRetryTimer);
2133
+ assignRetryTimer = setTimeout(() => {
2134
+ assignRetryTimer = null;
2135
+ if (isClosing) {
2136
+ return;
2137
+ }
2138
+ assignAccounts().catch(err => logger.error({ msg: 'Retry assignment failed', err }));
2139
+ }, delay);
2070
2140
  } else {
2071
2141
  assignRetryCount = 0;
2072
2142
  }
@@ -2463,6 +2533,12 @@ async function updateQueueCounters() {
2463
2533
  metrics.threadEventLoopDelayMax.set(labels, max);
2464
2534
  metrics.threadEventLoopDelayP99.set(labels, p99);
2465
2535
  }
2536
+ metrics.threadHeapUsed.reset();
2537
+ metrics.threadHeapTotal.reset();
2538
+ for (let { labels, used, total } of threadHeapSeries(threadsInfo)) {
2539
+ metrics.threadHeapUsed.set(labels, used);
2540
+ metrics.threadHeapTotal.set(labels, total);
2541
+ }
2466
2542
  for (let workerThreadInfo of threadsInfo || []) {
2467
2543
  let key = workerThreadInfo.type;
2468
2544
  let metricKey = `${key}_total`;
@@ -2499,23 +2575,28 @@ async function updateQueueCounters() {
2499
2575
  // `:paused` list no longer exists (a paused queue holds its jobs in `wait`), and a leftover
2500
2576
  // `0:` wait-list marker from a 5.x install counts as a phantom waiting job. The `paused`
2501
2577
  // gauge is kept at the 0 the getter reports so existing dashboards keep their series.
2502
- for (let [queue, queueObj] of [
2578
+ //
2579
+ // A queue whose count fails is skipped rather than ending the update: returning here used to
2580
+ // leave every Redis gauge below it stale for as long as that one count kept failing.
2581
+ const counted = [
2503
2582
  ['notify', notifyQueue],
2504
- ['submit', submitQueue]
2505
- ]) {
2506
- let stats;
2507
- try {
2508
- stats = await queueStats(queueObj);
2509
- } catch (err) {
2510
- logger.error({ msg: 'Queue length count failed', queue, err });
2511
- return false;
2583
+ ['submit', submitQueue],
2584
+ ['export', exportQueue]
2585
+ ];
2586
+ const results = await Promise.allSettled(counted.map(([, queueObj]) => queueStats(queueObj, { failed: true })));
2587
+ counted.forEach(([queue], i) => {
2588
+ if (results[i].status === 'rejected') {
2589
+ logger.error({ msg: 'Queue length count failed', queue, err: results[i].reason });
2590
+ return;
2512
2591
  }
2592
+ const stats = results[i].value;
2513
2593
 
2514
2594
  metrics.queues.set({ queue: `${queue}`, state: `active` }, stats.active);
2515
2595
  metrics.queues.set({ queue: `${queue}`, state: `delayed` }, stats.delayed);
2516
2596
  metrics.queues.set({ queue: `${queue}`, state: `paused` }, stats.paused);
2517
2597
  metrics.queues.set({ queue: `${queue}`, state: `waiting` }, stats.waiting);
2518
- }
2598
+ metrics.queueFailed.set({ queue: `${queue}` }, stats.failed);
2599
+ });
2519
2600
 
2520
2601
  // Update Redis metrics
2521
2602
  try {
@@ -3114,6 +3195,9 @@ const COMMAND_HANDLERS = new Map([
3114
3195
  ['subscribe', commandSubscribe],
3115
3196
  ['new', commandNewAccount],
3116
3197
  ['delete', commandDeleteAccount],
3198
+ // an account no worker holds has nothing of the provider's open; answering false here keeps
3199
+ // that apart from WorkerNotAvailable, which a worker dying mid-teardown also answers
3200
+ ['teardown', (worker, message) => (assigned.has(message.account) ? commandAccountOperation(worker, message) : false)],
3117
3201
  ['runIndex', commandRunIndex],
3118
3202
  ...['update', 'sync', 'pause', 'resume', 'reconnect'].map(cmd => [cmd, commandForwardToAccountWorker]),
3119
3203
  ...['smtpReload', 'imapProxyReload'].map(cmd => [cmd, commandReloadServer]),
@@ -3266,12 +3350,6 @@ const closeQueues = cb => {
3266
3350
  }
3267
3351
  }
3268
3352
 
3269
- for (let name of ['notify', 'submit', 'export']) {
3270
- if (queueEvents[name]) {
3271
- proms.push(queueEvents[name].close());
3272
- }
3273
- }
3274
-
3275
3353
  if (!proms.length) {
3276
3354
  return setImmediate(() => cb());
3277
3355
  }
@@ -3940,22 +4018,17 @@ startApplication()
3940
4018
  // Start worker health monitoring
3941
4019
  startHealthMonitoring();
3942
4020
 
3943
- // Initialize queue event listeners
3944
- for (let name of ['notify', 'submit', 'export']) {
3945
- queueEvents[name] = logBullErrors(new QueueEvents(name, Object.assign({}, queueConf)), `queueEvents:${name}`);
3946
- }
3947
-
3948
4021
  // Periodic queue cleanup (every 6 hours)
3949
4022
  const QUEUE_CLEANUP_INTERVAL = 6 * 60 * 60 * 1000;
3950
4023
 
3951
4024
  async function cleanupQueues() {
3952
4025
  const queues = [notifyQueue, submitQueue, exportQueue];
4026
+ const ages = queueCleanAges(await getFailedJobRetention());
3953
4027
  for (const queue of queues) {
3954
4028
  try {
3955
- // Clean completed jobs older than 24 hours
3956
- await queue.clean(24 * 60 * 60 * 1000, 10000, 'completed');
3957
- // Clean failed jobs older than 7 days
3958
- await queue.clean(7 * 24 * 60 * 60 * 1000, 10000, 'failed');
4029
+ // The same ages the jobs are added with, see lib/queue-retention.js
4030
+ await queue.clean(ages.completed, 10000, 'completed');
4031
+ await queue.clean(ages.failed, 10000, 'failed');
3959
4032
  logger.trace({ msg: 'Queue cleanup completed', queue: queue.name });
3960
4033
  } catch (err) {
3961
4034
  logger.error({ msg: 'Queue cleanup failed', queue: queue.name, err });