emailengine-app 2.85.0 → 2.86.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.
- package/.ncurc.js +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +74 -0
- package/Dockerfile +14 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +1 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +194 -165
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +78 -26
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +4 -3
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +130 -156
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +51 -11
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +372 -226
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/outlook-client.js +372 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/gateway.js +17 -1
- package/lib/get-raw-email.js +25 -107
- package/lib/health.js +75 -0
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth2-apps.js +630 -655
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +163 -39
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +54 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +21 -20
- package/sbom.json +304 -382
- package/server.js +149 -76
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +21 -31
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +102 -28
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- 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
|
|
44
|
-
//
|
|
45
|
-
//
|
|
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,
|
|
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 {
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
1255
|
+
await reportServerState(type, 'disabled', {});
|
|
1185
1256
|
return;
|
|
1186
1257
|
}
|
|
1187
1258
|
|
|
1188
|
-
await
|
|
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
|
-
|
|
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
|
|
1275
|
-
//
|
|
1276
|
-
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
logger.error({
|
|
2065
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
logger.error({ msg: 'Queue length count failed', queue, err });
|
|
2511
|
-
return
|
|
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
|
-
//
|
|
3956
|
-
await queue.clean(
|
|
3957
|
-
|
|
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 });
|