emailengine-app 2.84.2 → 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 +29 -9
- package/.prettierignore +5 -1
- package/.prettierrc.js +2 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +107 -0
- package/Dockerfile +20 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +2 -2
- package/bin/emailengine.js +434 -408
- package/config/default.toml +2 -0
- package/copy-static-files.sh +41 -14
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +16563 -0
- package/eslint.config.js +81 -99
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +230 -170
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/format.js +4 -3
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +255 -38
- package/lib/api-routes/blocklist-routes.js +91 -4
- package/lib/api-routes/delivery-test-routes.js +27 -4
- package/lib/api-routes/export-routes.js +28 -2
- package/lib/api-routes/gateway-routes.js +110 -12
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +44 -5
- package/lib/api-routes/message-routes.js +112 -10
- package/lib/api-routes/oauth2-app-routes.js +63 -23
- package/lib/api-routes/outbox-routes.js +97 -52
- package/lib/api-routes/permission-map.js +67 -7
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +34 -6
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +337 -309
- package/lib/api-routes/template-routes.js +45 -8
- package/lib/api-routes/token-routes.js +152 -100
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +132 -6
- package/lib/bounce-detect.js +397 -205
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -45
- 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 +137 -184
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +60 -22
- 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 -242
- package/lib/email-client/imap/subconnection.js +8 -30
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +228 -164
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/notification-handler.js +1 -2
- 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 +19 -4
- package/lib/get-raw-email.js +25 -107
- package/lib/hapi-request-logger.js +107 -0
- package/lib/health.js +75 -0
- package/lib/imapproxy/imap-core/README.md +6 -5
- 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/mcp/tools.js +37 -8
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +36 -0
- package/lib/oauth/outlook-mailbox.js +35 -0
- package/lib/oauth/state.js +24 -0
- package/lib/oauth2-apps.js +631 -656
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/pbkdf2-phc.js +1 -1
- 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 +164 -40
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/sso.js +1 -1
- package/lib/swagger-options.js +1 -1
- package/lib/thread-diagnostics.js +63 -0
- package/lib/timezones.js +109 -0
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +7 -6
- package/lib/tools.js +48 -51
- package/lib/totp.js +2 -5
- package/lib/translations.js +1 -2
- package/lib/ui-routes/account-routes.js +475 -454
- package/lib/ui-routes/account-setup.js +99 -0
- package/lib/ui-routes/admin-config-routes.js +152 -100
- package/lib/ui-routes/admin-entities-routes.js +93 -21
- package/lib/ui-routes/auth-routes.js +90 -38
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/internals-routes.js +5 -0
- package/lib/ui-routes/oauth-config-routes.js +124 -82
- 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/route-helpers.js +19 -3
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/ui-routes/tls-config-routes.js +58 -15
- package/lib/utils/back-off.js +82 -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/murmurhash3.js +66 -0
- package/lib/utils/public-suffix.js +122 -0
- package/lib/utils/random-id.js +26 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/utils/version.js +74 -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 +56 -0
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +93 -45
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +37 -38
- package/sbom.json +7902 -1
- package/server.js +784 -518
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +225 -1060
- package/translations/messages.pot +62 -63
- package/views/config/ai.hbs +1 -1
- package/views/config/security.hbs +24 -2
- package/views/config/service.hbs +47 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/internals/index.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/views/partials/webhook_form.hbs +1 -1
- package/views/suppression-lists/index.hbs +1 -1
- package/workers/api.js +840 -611
- package/workers/export.js +17 -632
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +18 -448
- 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
|
|
@@ -75,7 +87,7 @@ const {
|
|
|
75
87
|
getDuration,
|
|
76
88
|
getByteSize,
|
|
77
89
|
getBoolean,
|
|
78
|
-
|
|
90
|
+
workerPoolSize,
|
|
79
91
|
selectRendezvousNode,
|
|
80
92
|
checkLicense,
|
|
81
93
|
checkForUpgrade,
|
|
@@ -120,14 +132,16 @@ 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;
|
|
129
143
|
const crypto = require('crypto');
|
|
130
|
-
const {
|
|
144
|
+
const { compareVersions, parseVersion } = require('./lib/utils/version');
|
|
131
145
|
const Joi = require('joi');
|
|
132
146
|
const { settingsSchema } = require('./lib/schemas');
|
|
133
147
|
const settings = require('./lib/settings');
|
|
@@ -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,7 +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');
|
|
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');
|
|
158
174
|
|
|
159
175
|
const msgpack = require('./lib/msgpack');
|
|
160
176
|
|
|
@@ -225,16 +241,14 @@ const CONNECTION_SETUP_DELAY = getDuration(readEnvValue('EENGINE_CONNECTION_SETU
|
|
|
225
241
|
config.api.maxSize = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
|
|
226
242
|
config.dbs.redis = readEnvValue('EENGINE_REDIS') || readEnvValue('REDIS_URL') || config.dbs.redis;
|
|
227
243
|
|
|
228
|
-
config.workers.imap =
|
|
229
|
-
config.workers.webhooks =
|
|
230
|
-
config.workers.submit =
|
|
244
|
+
config.workers.imap = workerPoolSize(readEnvValue('EENGINE_WORKERS'), config.workers.imap, 4);
|
|
245
|
+
config.workers.webhooks = workerPoolSize(readEnvValue('EENGINE_WORKERS_WEBHOOKS'), config.workers.webhooks);
|
|
246
|
+
config.workers.submit = workerPoolSize(readEnvValue('EENGINE_WORKERS_SUBMIT'), config.workers.submit);
|
|
231
247
|
// The Workers page has labelled this row EENGINE_WORKERS_EXPORT since the export worker shipped, while
|
|
232
248
|
// only --workers.export and [workers] export were read, so an operator who set it saw no effect
|
|
233
|
-
config.workers.export =
|
|
249
|
+
config.workers.export = workerPoolSize(readEnvValue('EENGINE_WORKERS_EXPORT'), config.workers.export);
|
|
234
250
|
// API worker count. Values >1 require SO_REUSEPORT (Linux); on unsupported platforms it falls back to 1 at startup.
|
|
235
|
-
|
|
236
|
-
// count over-spawning, Math.max keeps at least one API worker.
|
|
237
|
-
config.workers.api = Math.max(1, Math.floor(getWorkerCount(readEnvValue('EENGINE_WORKERS_API') || config.workers.api)));
|
|
251
|
+
config.workers.api = workerPoolSize(readEnvValue('EENGINE_WORKERS_API'), config.workers.api);
|
|
238
252
|
|
|
239
253
|
config.api.port =
|
|
240
254
|
(hasEnvValue('EENGINE_PORT') && Number(readEnvValue('EENGINE_PORT'))) || (hasEnvValue('PORT') && Number(readEnvValue('PORT'))) || config.api.port;
|
|
@@ -242,7 +256,8 @@ config.api.host = readEnvValue('EENGINE_HOST') || config.api.host;
|
|
|
242
256
|
|
|
243
257
|
config.log.level = readEnvValue('EENGINE_LOG_LEVEL') || config.log.level;
|
|
244
258
|
|
|
245
|
-
// 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
|
|
246
261
|
const SMTP_ENABLED = hasEnvValue('EENGINE_SMTP_ENABLED') ? getBoolean(readEnvValue('EENGINE_SMTP_ENABLED')) : getBoolean(config.smtp.enabled);
|
|
247
262
|
const SMTP_SECRET = readEnvValue('EENGINE_SMTP_SECRET') || config.smtp.secret;
|
|
248
263
|
const SMTP_PORT = (readEnvValue('EENGINE_SMTP_PORT') && Number(readEnvValue('EENGINE_SMTP_PORT'))) || Number(config.smtp.port) || 2525;
|
|
@@ -294,6 +309,15 @@ logger.info({
|
|
|
294
309
|
workersSubmission: config.workers.submit
|
|
295
310
|
});
|
|
296
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
|
+
|
|
297
321
|
// Standard response for when no active worker is available
|
|
298
322
|
const NO_ACTIVE_HANDLER_RESP_ERR = new Error('No active handler for requested account. Try again later.');
|
|
299
323
|
NO_ACTIVE_HANDLER_RESP_ERR.statusCode = 503;
|
|
@@ -364,9 +388,6 @@ const THREAD_CONFIG_VALUES = {
|
|
|
364
388
|
export: { key: 'EENGINE_WORKERS_EXPORT', value: config.workers.export }
|
|
365
389
|
};
|
|
366
390
|
|
|
367
|
-
// Queue event handlers for different job queues
|
|
368
|
-
const queueEvents = {};
|
|
369
|
-
|
|
370
391
|
// Unique run index for this server instance
|
|
371
392
|
let runIndex;
|
|
372
393
|
|
|
@@ -559,6 +580,15 @@ const metrics = {
|
|
|
559
580
|
labelNames: ['method', 'statusCode', 'route']
|
|
560
581
|
}),
|
|
561
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
|
+
|
|
562
592
|
imapConnections: new promClient.Gauge({
|
|
563
593
|
name: 'imap_connections',
|
|
564
594
|
help: 'Current IMAP connection state',
|
|
@@ -647,6 +677,12 @@ const metrics = {
|
|
|
647
677
|
labelNames: ['queue', 'state']
|
|
648
678
|
}),
|
|
649
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
|
+
|
|
650
686
|
queuesProcessed: new promClient.Counter({
|
|
651
687
|
name: 'queues_processed',
|
|
652
688
|
help: 'Processed job count',
|
|
@@ -664,6 +700,30 @@ const metrics = {
|
|
|
664
700
|
help: 'Number of unresponsive worker threads'
|
|
665
701
|
}),
|
|
666
702
|
|
|
703
|
+
threadEventLoopDelayMax: new promClient.Gauge({
|
|
704
|
+
name: 'thread_event_loop_delay_max_seconds',
|
|
705
|
+
help: 'Longest event loop delay of a thread over the last collection window (15s)',
|
|
706
|
+
labelNames: ['type', 'thread']
|
|
707
|
+
}),
|
|
708
|
+
|
|
709
|
+
threadEventLoopDelayP99: new promClient.Gauge({
|
|
710
|
+
name: 'thread_event_loop_delay_p99_seconds',
|
|
711
|
+
help: '99th percentile event loop delay of a thread over the last collection window (15s)',
|
|
712
|
+
labelNames: ['type', 'thread']
|
|
713
|
+
}),
|
|
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
|
+
|
|
667
727
|
licenseDaysRemaining: new promClient.Gauge({
|
|
668
728
|
name: 'license_days_remaining',
|
|
669
729
|
help: 'Days until license expires (-1 for lifetime, 0 for no license)'
|
|
@@ -799,7 +859,7 @@ let reassignmentTimer = null; // Timer for failsafe reassignment
|
|
|
799
859
|
let reassignmentPending = false; // Flag to track if reassignment is pending
|
|
800
860
|
const REASSIGNMENT_FAILSAFE_DELAY = 10 * 1000; // How long an exited IMAP worker gets to restart before its accounts move
|
|
801
861
|
let assignRetryCount = 0; // Counter for safety-net retries in assignAccounts
|
|
802
|
-
|
|
862
|
+
let assignRetryTimer = null; // The pending safety-net retry, so passes do not stack them
|
|
803
863
|
|
|
804
864
|
// Worker management
|
|
805
865
|
let imapInitialWorkersLoaded = false; // Have all initial IMAP workers started?
|
|
@@ -887,6 +947,18 @@ let updateServerState = async (type, state, payload) => {
|
|
|
887
947
|
}
|
|
888
948
|
};
|
|
889
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
|
+
|
|
890
962
|
/**
|
|
891
963
|
* Get detailed information about all threads
|
|
892
964
|
* @returns {Promise<Array>} Array of thread information objects
|
|
@@ -1003,12 +1075,29 @@ async function getThreadsInfo() {
|
|
|
1003
1075
|
return threadsInfo;
|
|
1004
1076
|
}
|
|
1005
1077
|
|
|
1078
|
+
/**
|
|
1079
|
+
* The heartbeat log fields for a thread, see lib/thread-diagnostics.js
|
|
1080
|
+
* @param {Worker} worker - The worker thread
|
|
1081
|
+
* @param {number} now - Current time in milliseconds
|
|
1082
|
+
* @param {number} [lastHeartbeat] - When the thread last reported in
|
|
1083
|
+
* @returns {Object} Fields to add to the log entry
|
|
1084
|
+
*/
|
|
1085
|
+
function workerHeartbeatDiagnostics(worker, now, lastHeartbeat) {
|
|
1086
|
+
return heartbeatDiagnostics({
|
|
1087
|
+
now,
|
|
1088
|
+
lastHeartbeat,
|
|
1089
|
+
accounts: workerAssigned.get(worker)?.size,
|
|
1090
|
+
threadInfo: metricsCollector?.cachedThreadsInfo?.find(threadInfo => threadInfo.threadId === worker.threadId)
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1006
1094
|
/**
|
|
1007
1095
|
* Handle heartbeat from worker thread
|
|
1008
1096
|
* @param {Worker} worker - The worker thread
|
|
1009
1097
|
*/
|
|
1010
1098
|
function handleWorkerHeartbeat(worker) {
|
|
1011
1099
|
const now = Date.now();
|
|
1100
|
+
const previousHeartbeat = workerHeartbeats.get(worker);
|
|
1012
1101
|
workerHeartbeats.set(worker, now);
|
|
1013
1102
|
|
|
1014
1103
|
// Mark as healthy if it was previously unhealthy
|
|
@@ -1017,7 +1106,9 @@ function handleWorkerHeartbeat(worker) {
|
|
|
1017
1106
|
logger.info({
|
|
1018
1107
|
msg: 'Worker recovered',
|
|
1019
1108
|
threadId: worker.threadId,
|
|
1020
|
-
type: workersMeta.get(worker)?.type
|
|
1109
|
+
type: workersMeta.get(worker)?.type,
|
|
1110
|
+
// timeSinceHeartbeat here is how long the thread was blocked
|
|
1111
|
+
...workerHeartbeatDiagnostics(worker, now, previousHeartbeat)
|
|
1021
1112
|
});
|
|
1022
1113
|
}
|
|
1023
1114
|
workerHealthStatus.set(worker, 'healthy');
|
|
@@ -1048,7 +1139,7 @@ async function checkWorkerHealth() {
|
|
|
1048
1139
|
msg: 'Worker critically unresponsive, restarting',
|
|
1049
1140
|
threadId: worker.threadId,
|
|
1050
1141
|
type,
|
|
1051
|
-
|
|
1142
|
+
...workerHeartbeatDiagnostics(worker, now, lastHeartbeat)
|
|
1052
1143
|
});
|
|
1053
1144
|
|
|
1054
1145
|
workerHealthStatus.set(worker, 'restarting');
|
|
@@ -1070,7 +1161,7 @@ async function checkWorkerHealth() {
|
|
|
1070
1161
|
msg: 'Worker unhealthy - no heartbeat',
|
|
1071
1162
|
threadId: worker.threadId,
|
|
1072
1163
|
type,
|
|
1073
|
-
|
|
1164
|
+
...workerHeartbeatDiagnostics(worker, now, lastHeartbeat)
|
|
1074
1165
|
});
|
|
1075
1166
|
|
|
1076
1167
|
workerHealthStatus.set(worker, 'unhealthy');
|
|
@@ -1115,7 +1206,7 @@ async function sendWebhook(account, event, data) {
|
|
|
1115
1206
|
payload.data = data;
|
|
1116
1207
|
}
|
|
1117
1208
|
|
|
1118
|
-
await Webhooks.
|
|
1209
|
+
await Webhooks.enqueue(event, payload);
|
|
1119
1210
|
}
|
|
1120
1211
|
|
|
1121
1212
|
/**
|
|
@@ -1142,20 +1233,30 @@ let spawnWorker = async (type, opts, slot) => {
|
|
|
1142
1233
|
// Check if worker type is suspended (no license)
|
|
1143
1234
|
if (suspendedWorkerTypes.has(type)) {
|
|
1144
1235
|
if (['smtp', 'imapProxy'].includes(type)) {
|
|
1145
|
-
await
|
|
1236
|
+
await reportServerState(type, 'suspended', {});
|
|
1146
1237
|
}
|
|
1147
1238
|
return;
|
|
1148
1239
|
}
|
|
1149
1240
|
|
|
1150
1241
|
// Check if server type is enabled
|
|
1151
1242
|
if (['smtp', 'imapProxy'].includes(type)) {
|
|
1152
|
-
|
|
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
|
+
}
|
|
1153
1254
|
if (!serverEnabled) {
|
|
1154
|
-
await
|
|
1255
|
+
await reportServerState(type, 'disabled', {});
|
|
1155
1256
|
return;
|
|
1156
1257
|
}
|
|
1157
1258
|
|
|
1158
|
-
await
|
|
1259
|
+
await reportServerState(type, 'spawning');
|
|
1159
1260
|
}
|
|
1160
1261
|
|
|
1161
1262
|
// A fresh spawn opens its own slot. Counting the crash streak per type made every short-lived
|
|
@@ -1196,7 +1297,7 @@ let spawnWorker = async (type, opts, slot) => {
|
|
|
1196
1297
|
// Handle worker coming online
|
|
1197
1298
|
worker.on('online', () => {
|
|
1198
1299
|
if (['smtp', 'imapProxy'].includes(type)) {
|
|
1199
|
-
|
|
1300
|
+
reportServerState(type, 'initializing');
|
|
1200
1301
|
}
|
|
1201
1302
|
onlineWorkers.add(worker);
|
|
1202
1303
|
|
|
@@ -1241,12 +1342,9 @@ let spawnWorker = async (type, opts, slot) => {
|
|
|
1241
1342
|
|
|
1242
1343
|
// Update server state for proxy servers
|
|
1243
1344
|
if (['smtp', 'imapProxy'].includes(type)) {
|
|
1244
|
-
// Not awaited
|
|
1245
|
-
//
|
|
1246
|
-
|
|
1247
|
-
updateServerState(type, suspendedWorkerTypes.has(type) ? 'suspended' : 'exited').catch(err =>
|
|
1248
|
-
logger.error({ msg: 'Unable to update server state', type, err })
|
|
1249
|
-
);
|
|
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');
|
|
1250
1348
|
}
|
|
1251
1349
|
|
|
1252
1350
|
// Handle IMAP worker cleanup
|
|
@@ -1465,9 +1563,16 @@ let spawnWorker = async (type, opts, slot) => {
|
|
|
1465
1563
|
}
|
|
1466
1564
|
|
|
1467
1565
|
case 'apiCall': {
|
|
1468
|
-
let { statusCode } = message.args[0] || {};
|
|
1566
|
+
let { statusCode, method, route } = message.args[0] || {};
|
|
1469
1567
|
let success = statusCode >= 200 && statusCode < 300;
|
|
1470
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
|
+
}
|
|
1471
1576
|
break;
|
|
1472
1577
|
}
|
|
1473
1578
|
|
|
@@ -1507,14 +1612,14 @@ let spawnWorker = async (type, opts, slot) => {
|
|
|
1507
1612
|
if (account && accountUpdateKey) {
|
|
1508
1613
|
// Update account-specific counter
|
|
1509
1614
|
let accountKey = `${REDIS_PREFIX}iad:${account}`;
|
|
1510
|
-
update = update.
|
|
1615
|
+
update = update.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1);
|
|
1511
1616
|
}
|
|
1512
1617
|
|
|
1513
1618
|
update.exec().catch(() => false);
|
|
1514
1619
|
} else if (account && accountUpdateKey) {
|
|
1515
1620
|
// Update only account-specific counter
|
|
1516
1621
|
let accountKey = `${REDIS_PREFIX}iad:${account}`;
|
|
1517
|
-
redis.
|
|
1622
|
+
redis.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
|
|
1518
1623
|
}
|
|
1519
1624
|
|
|
1520
1625
|
// Update Prometheus metrics. prom-client throws synchronously on an unknown
|
|
@@ -1572,9 +1677,7 @@ let spawnWorker = async (type, opts, slot) => {
|
|
|
1572
1677
|
case 'smtpServerState':
|
|
1573
1678
|
case 'imapProxyServerState': {
|
|
1574
1679
|
let type = message.type.replace(/ServerState$/, '');
|
|
1575
|
-
|
|
1576
|
-
logger.error({ msg: 'Unable to update server state', type, err })
|
|
1577
|
-
);
|
|
1680
|
+
reportServerState(type, message.key, message.payload);
|
|
1578
1681
|
break;
|
|
1579
1682
|
}
|
|
1580
1683
|
default:
|
|
@@ -2015,28 +2118,25 @@ async function assignAccounts() {
|
|
|
2015
2118
|
|
|
2016
2119
|
assigning = false;
|
|
2017
2120
|
|
|
2018
|
-
// 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()
|
|
2019
2123
|
if (unassigned && unassigned.size > 0 && availableIMAPWorkers.size > 0 && !isClosing) {
|
|
2020
2124
|
assignRetryCount++;
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
logger.error({
|
|
2035
|
-
|
|
2036
|
-
remaining: unassigned.size
|
|
2037
|
-
});
|
|
2038
|
-
assignRetryCount = 0;
|
|
2039
|
-
}
|
|
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);
|
|
2040
2140
|
} else {
|
|
2041
2141
|
assignRetryCount = 0;
|
|
2042
2142
|
}
|
|
@@ -2069,7 +2169,9 @@ let licenseCheckHandler = async opts => {
|
|
|
2069
2169
|
// Check if we need to validate the license
|
|
2070
2170
|
let kv = await redis.hget(`${REDIS_PREFIX}settings`, 'kv');
|
|
2071
2171
|
let checkKv = true;
|
|
2072
|
-
|
|
2172
|
+
// an unreadable record means checking again, which also rewrites it
|
|
2173
|
+
let validatedVersion = kv && typeof kv === 'string' ? Buffer.from(kv, 'hex').toString() : null;
|
|
2174
|
+
if (parseVersion(validatedVersion) && compareVersions(packageData.version, validatedVersion) <= 0) {
|
|
2073
2175
|
checkKv = false;
|
|
2074
2176
|
}
|
|
2075
2177
|
|
|
@@ -2424,6 +2526,19 @@ async function updateQueueCounters() {
|
|
|
2424
2526
|
|
|
2425
2527
|
let threadCounts = new Map();
|
|
2426
2528
|
let unresponsiveCount = 0;
|
|
2529
|
+
// a replaced thread leaves with its thread id, so the series are rebuilt on every update
|
|
2530
|
+
metrics.threadEventLoopDelayMax.reset();
|
|
2531
|
+
metrics.threadEventLoopDelayP99.reset();
|
|
2532
|
+
for (let { labels, max, p99 } of eventLoopDelaySeries(threadsInfo)) {
|
|
2533
|
+
metrics.threadEventLoopDelayMax.set(labels, max);
|
|
2534
|
+
metrics.threadEventLoopDelayP99.set(labels, p99);
|
|
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
|
+
}
|
|
2427
2542
|
for (let workerThreadInfo of threadsInfo || []) {
|
|
2428
2543
|
let key = workerThreadInfo.type;
|
|
2429
2544
|
let metricKey = `${key}_total`;
|
|
@@ -2460,23 +2575,28 @@ async function updateQueueCounters() {
|
|
|
2460
2575
|
// `:paused` list no longer exists (a paused queue holds its jobs in `wait`), and a leftover
|
|
2461
2576
|
// `0:` wait-list marker from a 5.x install counts as a phantom waiting job. The `paused`
|
|
2462
2577
|
// gauge is kept at the 0 the getter reports so existing dashboards keep their series.
|
|
2463
|
-
|
|
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 = [
|
|
2464
2582
|
['notify', notifyQueue],
|
|
2465
|
-
['submit', submitQueue]
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
logger.error({ msg: 'Queue length count failed', queue, err });
|
|
2472
|
-
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;
|
|
2473
2591
|
}
|
|
2592
|
+
const stats = results[i].value;
|
|
2474
2593
|
|
|
2475
2594
|
metrics.queues.set({ queue: `${queue}`, state: `active` }, stats.active);
|
|
2476
2595
|
metrics.queues.set({ queue: `${queue}`, state: `delayed` }, stats.delayed);
|
|
2477
2596
|
metrics.queues.set({ queue: `${queue}`, state: `paused` }, stats.paused);
|
|
2478
2597
|
metrics.queues.set({ queue: `${queue}`, state: `waiting` }, stats.waiting);
|
|
2479
|
-
|
|
2598
|
+
metrics.queueFailed.set({ queue: `${queue}` }, stats.failed);
|
|
2599
|
+
});
|
|
2480
2600
|
|
|
2481
2601
|
// Update Redis metrics
|
|
2482
2602
|
try {
|
|
@@ -2618,468 +2738,507 @@ async function withRequestDeadline(message, run) {
|
|
|
2618
2738
|
}
|
|
2619
2739
|
}
|
|
2620
2740
|
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
// Return Prometheus metrics
|
|
2625
|
-
await updateQueueCounters();
|
|
2626
|
-
return promClient.register.metrics();
|
|
2627
|
-
|
|
2628
|
-
case 'structuredMetrics': {
|
|
2629
|
-
// Return structured metrics for API
|
|
2630
|
-
let connections = {};
|
|
2631
|
-
|
|
2632
|
-
for (let key of Object.keys(metrics.imapConnections.hashMap)) {
|
|
2633
|
-
if (key.indexOf('status:') === 0) {
|
|
2634
|
-
let metric = metrics.imapConnections.hashMap[key];
|
|
2635
|
-
connections[metric.labels.status] = metric.value;
|
|
2636
|
-
}
|
|
2637
|
-
}
|
|
2741
|
+
// Handlers for the commands workers send to the main thread, dispatched by onCommand(). A command
|
|
2742
|
+
// with no handler, and a handler that answers NOT_HANDLED, both reply with 999
|
|
2743
|
+
const NOT_HANDLED = 999;
|
|
2638
2744
|
|
|
2639
|
-
|
|
2640
|
-
|
|
2745
|
+
async function commandMetrics() {
|
|
2746
|
+
// Return Prometheus metrics
|
|
2747
|
+
await updateQueueCounters();
|
|
2748
|
+
return promClient.register.metrics();
|
|
2749
|
+
}
|
|
2641
2750
|
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2751
|
+
async function commandStructuredMetrics() {
|
|
2752
|
+
// Return structured metrics for API
|
|
2753
|
+
let connections = {};
|
|
2754
|
+
|
|
2755
|
+
for (let key of Object.keys(metrics.imapConnections.hashMap)) {
|
|
2756
|
+
if (key.indexOf('status:') === 0) {
|
|
2757
|
+
let metric = metrics.imapConnections.hashMap[key];
|
|
2758
|
+
connections[metric.labels.status] = metric.value;
|
|
2645
2759
|
}
|
|
2760
|
+
}
|
|
2646
2761
|
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
try {
|
|
2650
|
-
await licenseCheckHandler({
|
|
2651
|
-
subscriptionCheckTimeout: 60 * 1000
|
|
2652
|
-
});
|
|
2653
|
-
} catch (err) {
|
|
2654
|
-
// ignore
|
|
2655
|
-
}
|
|
2656
|
-
return licenseInfo;
|
|
2762
|
+
return { connections, redisPing: await getRedisPing() };
|
|
2763
|
+
}
|
|
2657
2764
|
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
}
|
|
2663
|
-
return licenseInfo;
|
|
2765
|
+
async function commandImapWorkerCount() {
|
|
2766
|
+
// Return number of available IMAP workers
|
|
2767
|
+
return { workers: availableIMAPWorkers.size };
|
|
2768
|
+
}
|
|
2664
2769
|
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2770
|
+
async function commandCheckLicense() {
|
|
2771
|
+
// Force license check
|
|
2772
|
+
try {
|
|
2773
|
+
await licenseCheckHandler({
|
|
2774
|
+
subscriptionCheckTimeout: 60 * 1000
|
|
2775
|
+
});
|
|
2776
|
+
} catch (err) {
|
|
2777
|
+
// ignore
|
|
2778
|
+
}
|
|
2779
|
+
return licenseInfo;
|
|
2780
|
+
}
|
|
2669
2781
|
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2782
|
+
async function commandLicense() {
|
|
2783
|
+
// Return license info with suspension status
|
|
2784
|
+
if (!licenseInfo.active && suspendedWorkerTypes.size) {
|
|
2785
|
+
return Object.assign({}, licenseInfo, { suspended: true });
|
|
2786
|
+
}
|
|
2787
|
+
return licenseInfo;
|
|
2788
|
+
}
|
|
2674
2789
|
|
|
2675
|
-
|
|
2790
|
+
async function commandUpdateLicense(worker, message) {
|
|
2791
|
+
// Update license from API
|
|
2792
|
+
try {
|
|
2793
|
+
const licenseFile = message.license;
|
|
2676
2794
|
|
|
2677
|
-
|
|
2795
|
+
let licenseData = await checkLicense(licenseFile);
|
|
2796
|
+
if (!licenseData) {
|
|
2797
|
+
throw new Error('Invalid license provided');
|
|
2798
|
+
}
|
|
2678
2799
|
|
|
2679
|
-
|
|
2680
|
-
licenseInfo.details = licenseData;
|
|
2681
|
-
licenseInfo.type = 'EmailEngine License';
|
|
2800
|
+
logger.info({ msg: 'License updated', license: redactLicense(licenseData), source: 'API' });
|
|
2682
2801
|
|
|
2683
|
-
|
|
2684
|
-
checkActiveLicense();
|
|
2802
|
+
await setLicense(licenseData, licenseFile);
|
|
2685
2803
|
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
return false;
|
|
2690
|
-
}
|
|
2691
|
-
}
|
|
2804
|
+
licenseInfo.active = true;
|
|
2805
|
+
licenseInfo.details = licenseData;
|
|
2806
|
+
licenseInfo.type = 'EmailEngine License';
|
|
2692
2807
|
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
try {
|
|
2696
|
-
await settings.removeLicense();
|
|
2808
|
+
// Re-enable workers
|
|
2809
|
+
checkActiveLicense();
|
|
2697
2810
|
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2811
|
+
return licenseInfo;
|
|
2812
|
+
} catch (err) {
|
|
2813
|
+
logger.warn({ msg: 'License update failed', source: 'API', err });
|
|
2814
|
+
return false;
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2701
2817
|
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
}
|
|
2707
|
-
}
|
|
2818
|
+
async function commandRemoveLicense() {
|
|
2819
|
+
// Remove existing license
|
|
2820
|
+
try {
|
|
2821
|
+
await settings.removeLicense();
|
|
2708
2822
|
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2823
|
+
licenseInfo.active = false;
|
|
2824
|
+
licenseInfo.details = false;
|
|
2825
|
+
licenseInfo.type = packageData.license;
|
|
2826
|
+
|
|
2827
|
+
return licenseInfo;
|
|
2828
|
+
} catch (err) {
|
|
2829
|
+
logger.error({ msg: 'License removal failed', err });
|
|
2830
|
+
return false;
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
|
|
2834
|
+
async function commandKillThread(worker, message) {
|
|
2835
|
+
// Terminate a specific thread
|
|
2836
|
+
for (let [, workerSet] of workers) {
|
|
2837
|
+
if (workerSet && workerSet.size) {
|
|
2838
|
+
for (let worker of workerSet) {
|
|
2839
|
+
if (worker.threadId === message.thread) {
|
|
2840
|
+
logger.info({ msg: 'Thread termination requested', thread: message.thread });
|
|
2841
|
+
return await worker.terminate();
|
|
2719
2842
|
}
|
|
2720
2843
|
}
|
|
2721
|
-
|
|
2722
|
-
return false;
|
|
2723
2844
|
}
|
|
2845
|
+
}
|
|
2724
2846
|
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
}
|
|
2738
|
-
return false;
|
|
2847
|
+
return false;
|
|
2848
|
+
}
|
|
2849
|
+
|
|
2850
|
+
async function commandSnapshotThread(worker, message) {
|
|
2851
|
+
// Get heap snapshot for debugging
|
|
2852
|
+
if (message.thread === 0) {
|
|
2853
|
+
// Main thread only - V8 operations should be done in main thread
|
|
2854
|
+
try {
|
|
2855
|
+
logger.info({ msg: 'Heap snapshot requested', thread: message.thread });
|
|
2856
|
+
const stream = v8.getHeapSnapshot();
|
|
2857
|
+
if (stream) {
|
|
2858
|
+
return { _transfer: true, _response: await download(stream) };
|
|
2739
2859
|
}
|
|
2860
|
+
} catch (err) {
|
|
2861
|
+
logger.error({ msg: 'Failed to generate heap snapshot', thread: message.thread, err });
|
|
2862
|
+
}
|
|
2863
|
+
return false;
|
|
2864
|
+
}
|
|
2740
2865
|
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
}
|
|
2753
|
-
} catch (err) {
|
|
2754
|
-
logger.error({ msg: 'Failed to generate heap snapshot for worker', thread: message.thread, err });
|
|
2755
|
-
}
|
|
2756
|
-
return false;
|
|
2866
|
+
// Worker thread - use worker's built-in method which is safer
|
|
2867
|
+
for (let [, workerSet] of workers) {
|
|
2868
|
+
if (workerSet && workerSet.size) {
|
|
2869
|
+
for (let worker of workerSet) {
|
|
2870
|
+
if (worker.threadId === message.thread) {
|
|
2871
|
+
try {
|
|
2872
|
+
logger.info({ msg: 'Heap snapshot requested', thread: message.thread });
|
|
2873
|
+
// Use worker's built-in getHeapSnapshot method instead of V8 API
|
|
2874
|
+
const stream = await worker.getHeapSnapshot({ exposeInternals: true, exposeNumericValues: true });
|
|
2875
|
+
if (stream) {
|
|
2876
|
+
return { _transfer: true, _response: await download(stream) };
|
|
2757
2877
|
}
|
|
2878
|
+
} catch (err) {
|
|
2879
|
+
logger.error({ msg: 'Failed to generate heap snapshot for worker', thread: message.thread, err });
|
|
2758
2880
|
}
|
|
2881
|
+
return false;
|
|
2759
2882
|
}
|
|
2760
2883
|
}
|
|
2761
|
-
|
|
2762
|
-
return false;
|
|
2763
2884
|
}
|
|
2885
|
+
}
|
|
2764
2886
|
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
try {
|
|
2768
|
-
return await bounceClassifier.classify(message.data.message);
|
|
2769
|
-
} catch (err) {
|
|
2770
|
-
// ignore
|
|
2771
|
-
logger.warn({
|
|
2772
|
-
msg: 'Failed to classify bounce response',
|
|
2773
|
-
bounceResponse: message.data.message,
|
|
2774
|
-
err
|
|
2775
|
-
});
|
|
2776
|
-
}
|
|
2777
|
-
return false;
|
|
2887
|
+
return false;
|
|
2888
|
+
}
|
|
2778
2889
|
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2890
|
+
async function commandBounceClassify(worker, message) {
|
|
2891
|
+
// Classify bounce response message
|
|
2892
|
+
try {
|
|
2893
|
+
return await bounceClassifier.classify(message.data.message);
|
|
2894
|
+
} catch (err) {
|
|
2895
|
+
// ignore
|
|
2896
|
+
logger.warn({
|
|
2897
|
+
msg: 'Failed to classify bounce response',
|
|
2898
|
+
bounceResponse: message.data.message,
|
|
2899
|
+
err
|
|
2900
|
+
});
|
|
2901
|
+
}
|
|
2902
|
+
return false;
|
|
2903
|
+
}
|
|
2783
2904
|
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2905
|
+
// OpenAI integration commands - run in the main process, where the metrics live
|
|
2906
|
+
async function commandGenerateSummary(worker, message) {
|
|
2907
|
+
const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
|
|
2908
|
+
requestOpts.user = message.data.account;
|
|
2787
2909
|
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
);
|
|
2792
|
-
const { usage } = response;
|
|
2793
|
-
|
|
2794
|
-
// the fitted email text the verbose mode adds stays out of the RPC and the log
|
|
2795
|
-
delete usage.text;
|
|
2796
|
-
|
|
2797
|
-
if (counted) {
|
|
2798
|
-
metrics.aiRequests.inc({ model, status: 'success' });
|
|
2799
|
-
for (const type of ['prompt', 'completion']) {
|
|
2800
|
-
const tokens = usage[`${type}Tokens`];
|
|
2801
|
-
if (tokens) {
|
|
2802
|
-
metrics.aiTokens.inc({ model, type }, tokens);
|
|
2803
|
-
}
|
|
2804
|
-
}
|
|
2805
|
-
}
|
|
2910
|
+
// the configuration page's test runs are not production traffic
|
|
2911
|
+
const counted = !message.data.options;
|
|
2912
|
+
const model = requestOpts.gptModel;
|
|
2806
2913
|
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2914
|
+
try {
|
|
2915
|
+
const response = await withRequestDeadline(message, signal =>
|
|
2916
|
+
generateSummary(message.data.message, openAiAPIKey, Object.assign(requestOpts, { signal }))
|
|
2917
|
+
);
|
|
2918
|
+
const { usage } = response;
|
|
2919
|
+
|
|
2920
|
+
// the fitted email text the verbose mode adds stays out of the RPC and the log
|
|
2921
|
+
delete usage.text;
|
|
2922
|
+
|
|
2923
|
+
if (counted) {
|
|
2924
|
+
metrics.aiRequests.inc({ model, status: 'success' });
|
|
2925
|
+
for (const type of ['prompt', 'completion']) {
|
|
2926
|
+
const tokens = usage[`${type}Tokens`];
|
|
2927
|
+
if (tokens) {
|
|
2928
|
+
metrics.aiTokens.inc({ model, type }, tokens);
|
|
2811
2929
|
}
|
|
2812
|
-
throw err;
|
|
2813
2930
|
}
|
|
2814
2931
|
}
|
|
2815
2932
|
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2933
|
+
return response;
|
|
2934
|
+
} catch (err) {
|
|
2935
|
+
if (counted) {
|
|
2936
|
+
metrics.aiRequests.inc({ model, status: 'failure' });
|
|
2819
2937
|
}
|
|
2938
|
+
throw err;
|
|
2939
|
+
}
|
|
2940
|
+
}
|
|
2820
2941
|
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2942
|
+
async function commandOpenAiListModels(worker, message) {
|
|
2943
|
+
const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
|
|
2944
|
+
return await withRequestDeadline(message, signal => openAiListModels(openAiAPIKey, Object.assign(requestOpts, { signal })));
|
|
2945
|
+
}
|
|
2824
2946
|
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
return {
|
|
2829
|
-
requested: apiWorkersRequested,
|
|
2830
|
-
fallback: apiWorkersRequested > 1 && !apiWorkerReusePort,
|
|
2831
|
-
reason: apiWorkerReusePortFallbackReason
|
|
2832
|
-
};
|
|
2833
|
-
}
|
|
2947
|
+
async function commandThreads() {
|
|
2948
|
+
return await getThreadsInfo();
|
|
2949
|
+
}
|
|
2834
2950
|
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2951
|
+
async function commandApiWorkerScaling() {
|
|
2952
|
+
// Reported on /admin/internals so operators can see when EENGINE_WORKERS_API > 1
|
|
2953
|
+
// was requested but only one worker started, and why (reason: 'platform' | 'port').
|
|
2954
|
+
return {
|
|
2955
|
+
requested: apiWorkersRequested,
|
|
2956
|
+
fallback: apiWorkersRequested > 1 && !apiWorkerReusePort,
|
|
2957
|
+
reason: apiWorkerReusePortFallbackReason
|
|
2958
|
+
};
|
|
2959
|
+
}
|
|
2839
2960
|
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
}
|
|
2845
|
-
}
|
|
2961
|
+
async function commandWorkerAccounts(worker, message) {
|
|
2962
|
+
// Get accounts assigned to a specific worker thread
|
|
2963
|
+
const { threadId, page = 1, pageSize = 20 } = message;
|
|
2964
|
+
const accounts = [];
|
|
2846
2965
|
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
const totalAccounts = accounts.length;
|
|
2852
|
-
const totalPages = Math.ceil(totalAccounts / pageSize) || 1;
|
|
2853
|
-
const currentPage = Math.min(Math.max(1, page), totalPages);
|
|
2854
|
-
const start = (currentPage - 1) * pageSize;
|
|
2855
|
-
const pagedAccounts = accounts.slice(start, start + pageSize);
|
|
2856
|
-
|
|
2857
|
-
return {
|
|
2858
|
-
accounts: pagedAccounts,
|
|
2859
|
-
total: totalAccounts,
|
|
2860
|
-
page: currentPage,
|
|
2861
|
-
pageSize,
|
|
2862
|
-
pages: totalPages
|
|
2863
|
-
};
|
|
2966
|
+
// Find worker by threadId and get its assigned accounts
|
|
2967
|
+
for (const [account, worker] of assigned) {
|
|
2968
|
+
if (worker.threadId === threadId) {
|
|
2969
|
+
accounts.push(account);
|
|
2864
2970
|
}
|
|
2971
|
+
}
|
|
2865
2972
|
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
}
|
|
2973
|
+
// Sort accounts for consistent ordering
|
|
2974
|
+
accounts.sort((a, b) => a.localeCompare(b));
|
|
2869
2975
|
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2976
|
+
// Paginate
|
|
2977
|
+
const totalAccounts = accounts.length;
|
|
2978
|
+
const totalPages = Math.ceil(totalAccounts / pageSize) || 1;
|
|
2979
|
+
const currentPage = Math.min(Math.max(1, page), totalPages);
|
|
2980
|
+
const start = (currentPage - 1) * pageSize;
|
|
2981
|
+
const pagedAccounts = accounts.slice(start, start + pageSize);
|
|
2876
2982
|
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2983
|
+
return {
|
|
2984
|
+
accounts: pagedAccounts,
|
|
2985
|
+
total: totalAccounts,
|
|
2986
|
+
page: currentPage,
|
|
2987
|
+
pageSize,
|
|
2988
|
+
pages: totalPages
|
|
2989
|
+
};
|
|
2990
|
+
}
|
|
2883
2991
|
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
// `unassigned` is `false` until assignAccounts() loads the account list from Redis on
|
|
2888
|
-
// its first run, which waits for an IMAP worker to report ready. An account created
|
|
2889
|
-
// before that used to throw here and fail the request with a 500. Skipping the add is
|
|
2890
|
-
// safe rather than merely quiet: the account is already in `ia:accounts` by the time
|
|
2891
|
-
// this message is sent, so the first load picks it up.
|
|
2892
|
-
if (unassigned) {
|
|
2893
|
-
unassigned.add(message.account);
|
|
2894
|
-
}
|
|
2895
|
-
assignAccounts()
|
|
2896
|
-
.then(() => sendWebhook(message.account, ACCOUNT_ADDED_NOTIFY, { account: message.account }))
|
|
2897
|
-
.catch(err => logger.error({ msg: 'Account assignment failed', err }));
|
|
2898
|
-
return;
|
|
2992
|
+
async function commandRateLimit(worker, message) {
|
|
2993
|
+
return await checkRateLimit(message.key, message.count, message.allowed, message.windowSize);
|
|
2994
|
+
}
|
|
2899
2995
|
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
{
|
|
2907
|
-
let assignedWorker = forgetAccount({ workerAssigned, assigned, unassigned }, message.account);
|
|
2908
|
-
if (assignedWorker) {
|
|
2909
|
-
// Notify worker to clean up
|
|
2910
|
-
call(assignedWorker, message)
|
|
2911
|
-
.then(() => logger.debug('Account cleanup completed'))
|
|
2912
|
-
.catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
|
|
2913
|
-
}
|
|
2914
|
-
}
|
|
2915
|
-
sendWebhook(message.account, ACCOUNT_DELETED_NOTIFY, { account: message.account }).catch(err =>
|
|
2916
|
-
logger.error({ msg: 'Account deletion webhook failed', account: message.account, err })
|
|
2917
|
-
);
|
|
2918
|
-
return;
|
|
2996
|
+
async function commandUnsubscribe(worker, message) {
|
|
2997
|
+
// Handle list unsubscribe
|
|
2998
|
+
sendWebhook(message.account, LIST_UNSUBSCRIBE_NOTIFY, message.payload).catch(err =>
|
|
2999
|
+
logger.error({ msg: 'Unsubscribe webhook failed', account: message.account, err })
|
|
3000
|
+
);
|
|
3001
|
+
}
|
|
2919
3002
|
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
case 'pause':
|
|
2927
|
-
case 'resume':
|
|
2928
|
-
case 'reconnect':
|
|
2929
|
-
// Forward to assigned worker
|
|
2930
|
-
if (assigned.has(message.account)) {
|
|
2931
|
-
let assignedWorker = assigned.get(message.account);
|
|
2932
|
-
call(assignedWorker, message)
|
|
2933
|
-
.then(() => logger.debug('Worker command completed'))
|
|
2934
|
-
.catch(err => logger.error({ msg: 'Worker command failed', account: message.account, cmd: message.cmd, err }));
|
|
2935
|
-
}
|
|
2936
|
-
return;
|
|
3003
|
+
async function commandSubscribe(worker, message) {
|
|
3004
|
+
// Handle list subscribe
|
|
3005
|
+
sendWebhook(message.account, LIST_SUBSCRIBE_NOTIFY, message.payload).catch(err =>
|
|
3006
|
+
logger.error({ msg: 'Subscribe webhook failed', account: message.account, err })
|
|
3007
|
+
);
|
|
3008
|
+
}
|
|
2937
3009
|
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
await spawnWorker(type);
|
|
2954
|
-
}
|
|
2955
|
-
}
|
|
2956
|
-
}
|
|
2957
|
-
break;
|
|
3010
|
+
async function commandNewAccount(worker, message) {
|
|
3011
|
+
// Handle new account.
|
|
3012
|
+
//
|
|
3013
|
+
// `unassigned` is `false` until assignAccounts() loads the account list from Redis on
|
|
3014
|
+
// its first run, which waits for an IMAP worker to report ready. An account created
|
|
3015
|
+
// before that used to throw here and fail the request with a 500. Skipping the add is
|
|
3016
|
+
// safe rather than merely quiet: the account is already in `ia:accounts` by the time
|
|
3017
|
+
// this message is sent, so the first load picks it up.
|
|
3018
|
+
if (unassigned) {
|
|
3019
|
+
unassigned.add(message.account);
|
|
3020
|
+
}
|
|
3021
|
+
assignAccounts()
|
|
3022
|
+
.then(() => sendWebhook(message.account, ACCOUNT_ADDED_NOTIFY, { account: message.account }))
|
|
3023
|
+
.catch(err => logger.error({ msg: 'Account assignment failed', err }));
|
|
3024
|
+
}
|
|
2958
3025
|
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
case 'submitMessage':
|
|
2977
|
-
case 'queueMessage':
|
|
2978
|
-
case 'listMessages':
|
|
2979
|
-
case 'getRawMessage':
|
|
2980
|
-
case 'getText':
|
|
2981
|
-
case 'getMessage':
|
|
2982
|
-
case 'getMessages':
|
|
2983
|
-
case 'updateMessage':
|
|
2984
|
-
case 'updateMessages':
|
|
2985
|
-
case 'listMailboxes':
|
|
2986
|
-
case 'moveMessage':
|
|
2987
|
-
case 'moveMessages':
|
|
2988
|
-
case 'deleteMessage':
|
|
2989
|
-
case 'deleteMessages':
|
|
2990
|
-
case 'getQuota':
|
|
2991
|
-
case 'createMailbox':
|
|
2992
|
-
case 'modifyMailbox':
|
|
2993
|
-
case 'deleteMailbox':
|
|
2994
|
-
case 'uploadMessage':
|
|
2995
|
-
case 'getAttachment':
|
|
2996
|
-
case 'listSignatures': {
|
|
2997
|
-
if (!assigned.has(message.account)) {
|
|
2998
|
-
throw NO_ACTIVE_HANDLER_RESP_ERR;
|
|
2999
|
-
}
|
|
3026
|
+
async function commandDeleteAccount(worker, message) {
|
|
3027
|
+
// Handle account deletion
|
|
3028
|
+
//
|
|
3029
|
+
// Guarded for the same reason as commandNewAccount() above, and here the throw was
|
|
3030
|
+
// answered with a 500 for a deletion that had in fact succeeded: the account was
|
|
3031
|
+
// already gone from Redis by the time this message was sent.
|
|
3032
|
+
let assignedWorker = forgetAccount({ workerAssigned, assigned, unassigned }, message.account);
|
|
3033
|
+
if (assignedWorker) {
|
|
3034
|
+
// Notify worker to clean up
|
|
3035
|
+
call(assignedWorker, message)
|
|
3036
|
+
.then(() => logger.debug('Account cleanup completed'))
|
|
3037
|
+
.catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
|
|
3038
|
+
}
|
|
3039
|
+
sendWebhook(message.account, ACCOUNT_DELETED_NOTIFY, { account: message.account }).catch(err =>
|
|
3040
|
+
logger.error({ msg: 'Account deletion webhook failed', account: message.account, err })
|
|
3041
|
+
);
|
|
3042
|
+
}
|
|
3000
3043
|
|
|
3001
|
-
|
|
3044
|
+
async function commandRunIndex() {
|
|
3045
|
+
return runIndex;
|
|
3046
|
+
}
|
|
3002
3047
|
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3048
|
+
async function commandForwardToAccountWorker(worker, message) {
|
|
3049
|
+
// Forward to assigned worker
|
|
3050
|
+
if (assigned.has(message.account)) {
|
|
3051
|
+
let assignedWorker = assigned.get(message.account);
|
|
3052
|
+
call(assignedWorker, message)
|
|
3053
|
+
.then(() => logger.debug('Worker command completed'))
|
|
3054
|
+
.catch(err => logger.error({ msg: 'Worker command failed', account: message.account, cmd: message.cmd, err }));
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3011
3057
|
|
|
3012
|
-
|
|
3058
|
+
async function commandReloadServer(worker, message) {
|
|
3059
|
+
// Reload proxy server
|
|
3060
|
+
let type = message.cmd.replace(/Reload$/, '');
|
|
3061
|
+
let hasWorkers = workers.has(type) && workers.get(type).size;
|
|
3062
|
+
if (hasWorkers) {
|
|
3063
|
+
// Kill existing workers
|
|
3064
|
+
for (let worker of workers.get(type).values()) {
|
|
3065
|
+
worker.terminate();
|
|
3013
3066
|
}
|
|
3067
|
+
} else {
|
|
3068
|
+
// Spawn new worker if enabled
|
|
3069
|
+
let serverEnabled = await settings.get(`${type}ServerEnabled`);
|
|
3070
|
+
if (serverEnabled) {
|
|
3071
|
+
await spawnWorker(type);
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
return NOT_HANDLED;
|
|
3075
|
+
}
|
|
3014
3076
|
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3077
|
+
async function commandReloadCertificates(worker, message) {
|
|
3078
|
+
// A renewed certificate, handed to a running listener. Forwarded to the worker
|
|
3079
|
+
// rather than terminating it: a restart would cut every session in flight, and
|
|
3080
|
+
// every listener can swap its secure context between handshakes. Sent to every
|
|
3081
|
+
// worker of the type, not just the one that ordered the certificate: the
|
|
3082
|
+
// reconciler is a singleton but the listeners are not.
|
|
3083
|
+
let type = message.cmd.replace(/ReloadCertificates$/, '');
|
|
3084
|
+
for (let worker of (workers.get(type) || new Set()).values()) {
|
|
3085
|
+
call(worker, message).catch(err => logger.error({ msg: 'Failed to reload certificates', type, worker: worker.threadId, err }));
|
|
3086
|
+
}
|
|
3087
|
+
return NOT_HANDLED;
|
|
3088
|
+
}
|
|
3020
3089
|
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3090
|
+
// IMAP operations - forward to assigned worker
|
|
3091
|
+
async function commandAccountOperation(worker, message) {
|
|
3092
|
+
if (!assigned.has(message.account)) {
|
|
3093
|
+
throw NO_ACTIVE_HANDLER_RESP_ERR;
|
|
3094
|
+
}
|
|
3024
3095
|
|
|
3025
|
-
|
|
3026
|
-
case 'googlePubSubRemove': {
|
|
3027
|
-
// Notify all webhook workers about PubSub app changes
|
|
3028
|
-
if (!workers.has('webhooks')) {
|
|
3029
|
-
return true;
|
|
3030
|
-
}
|
|
3031
|
-
let proms = [];
|
|
3032
|
-
for (let worker of workers.get('webhooks')) {
|
|
3033
|
-
proms.push(
|
|
3034
|
-
call(worker, message).catch(err => {
|
|
3035
|
-
logger.error({ msg: 'Failed to notify webhook worker about PubSub change', cmd: message.cmd, err });
|
|
3036
|
-
})
|
|
3037
|
-
);
|
|
3038
|
-
}
|
|
3039
|
-
await Promise.all(proms);
|
|
3040
|
-
return true;
|
|
3041
|
-
}
|
|
3096
|
+
let assignedWorker = assigned.get(message.account);
|
|
3042
3097
|
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3098
|
+
let transferList = [];
|
|
3099
|
+
// Handle transferable objects
|
|
3100
|
+
if (['getRawMessage', 'getAttachment'].includes(message.cmd) && message.port) {
|
|
3101
|
+
transferList.push(message.port);
|
|
3102
|
+
}
|
|
3103
|
+
if (['submitMessage', 'queueMessage'].includes(message.cmd) && typeof message.raw === 'object') {
|
|
3104
|
+
transferList.push(message.raw);
|
|
3105
|
+
}
|
|
3050
3106
|
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
call(assignedWorker, { cmd: 'externalNotify', account, historyId: message.historyId }).catch(err => {
|
|
3054
|
-
logger.error({ msg: 'External notification failed', cmd: 'externalNotify', account, historyId: message.historyId, err });
|
|
3055
|
-
})
|
|
3056
|
-
);
|
|
3057
|
-
}
|
|
3058
|
-
await Promise.all(proms);
|
|
3059
|
-
return true;
|
|
3060
|
-
}
|
|
3107
|
+
return await call(assignedWorker, message, transferList);
|
|
3108
|
+
}
|
|
3061
3109
|
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
3077
|
-
|
|
3078
|
-
|
|
3110
|
+
async function commandSubconnections(worker, message) {
|
|
3111
|
+
// Get submission connections
|
|
3112
|
+
if (!assigned.has(message.account)) {
|
|
3113
|
+
return [];
|
|
3114
|
+
}
|
|
3115
|
+
|
|
3116
|
+
let assignedWorker = assigned.get(message.account);
|
|
3117
|
+
return await call(assignedWorker, message, []);
|
|
3118
|
+
}
|
|
3119
|
+
|
|
3120
|
+
async function commandGooglePubSub(worker, message) {
|
|
3121
|
+
// Notify all webhook workers about PubSub app changes
|
|
3122
|
+
if (!workers.has('webhooks')) {
|
|
3123
|
+
return true;
|
|
3124
|
+
}
|
|
3125
|
+
let proms = [];
|
|
3126
|
+
for (let worker of workers.get('webhooks')) {
|
|
3127
|
+
proms.push(
|
|
3128
|
+
call(worker, message).catch(err => {
|
|
3129
|
+
logger.error({ msg: 'Failed to notify webhook worker about PubSub change', cmd: message.cmd, err });
|
|
3130
|
+
})
|
|
3131
|
+
);
|
|
3132
|
+
}
|
|
3133
|
+
await Promise.all(proms);
|
|
3134
|
+
return true;
|
|
3135
|
+
}
|
|
3136
|
+
|
|
3137
|
+
async function commandExternalNotify(worker, message) {
|
|
3138
|
+
// External notification (e.g., Google Push)
|
|
3139
|
+
let proms = [];
|
|
3140
|
+
for (let account of message.accounts || []) {
|
|
3141
|
+
if (!assigned.has(account)) {
|
|
3142
|
+
continue;
|
|
3079
3143
|
}
|
|
3144
|
+
|
|
3145
|
+
let assignedWorker = assigned.get(account);
|
|
3146
|
+
proms.push(
|
|
3147
|
+
call(assignedWorker, { cmd: 'externalNotify', account, historyId: message.historyId }).catch(err => {
|
|
3148
|
+
logger.error({ msg: 'External notification failed', cmd: 'externalNotify', account, historyId: message.historyId, err });
|
|
3149
|
+
})
|
|
3150
|
+
);
|
|
3080
3151
|
}
|
|
3152
|
+
await Promise.all(proms);
|
|
3153
|
+
return true;
|
|
3154
|
+
}
|
|
3081
3155
|
|
|
3082
|
-
|
|
3156
|
+
async function commandSubscriptionLifecycle(worker, message) {
|
|
3157
|
+
// MS Graph subscription lifecycle event (reauthorizationRequired, subscriptionRemoved)
|
|
3158
|
+
if (!assigned.has(message.account)) {
|
|
3159
|
+
logger.warn({
|
|
3160
|
+
msg: 'Subscription lifecycle event for unassigned account',
|
|
3161
|
+
account: message.account,
|
|
3162
|
+
event: message.event
|
|
3163
|
+
});
|
|
3164
|
+
return false;
|
|
3165
|
+
}
|
|
3166
|
+
let assignedWorker = assigned.get(message.account);
|
|
3167
|
+
return await call(assignedWorker, {
|
|
3168
|
+
cmd: 'subscriptionLifecycle',
|
|
3169
|
+
account: message.account,
|
|
3170
|
+
event: message.event,
|
|
3171
|
+
timeout: message.timeout
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
|
|
3175
|
+
// A Map rather than an object literal, so a command name like `constructor` or `__proto__` is an
|
|
3176
|
+
// unknown command and not an inherited property
|
|
3177
|
+
const COMMAND_HANDLERS = new Map([
|
|
3178
|
+
['metrics', commandMetrics],
|
|
3179
|
+
['structuredMetrics', commandStructuredMetrics],
|
|
3180
|
+
['imapWorkerCount', commandImapWorkerCount],
|
|
3181
|
+
['checkLicense', commandCheckLicense],
|
|
3182
|
+
['license', commandLicense],
|
|
3183
|
+
['updateLicense', commandUpdateLicense],
|
|
3184
|
+
['removeLicense', commandRemoveLicense],
|
|
3185
|
+
['kill-thread', commandKillThread],
|
|
3186
|
+
['snapshot-thread', commandSnapshotThread],
|
|
3187
|
+
['bounceClassify', commandBounceClassify],
|
|
3188
|
+
['generateSummary', commandGenerateSummary],
|
|
3189
|
+
['openAiListModels', commandOpenAiListModels],
|
|
3190
|
+
['threads', commandThreads],
|
|
3191
|
+
['apiWorkerScaling', commandApiWorkerScaling],
|
|
3192
|
+
['worker-accounts', commandWorkerAccounts],
|
|
3193
|
+
['rate-limit', commandRateLimit],
|
|
3194
|
+
['unsubscribe', commandUnsubscribe],
|
|
3195
|
+
['subscribe', commandSubscribe],
|
|
3196
|
+
['new', commandNewAccount],
|
|
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)],
|
|
3201
|
+
['runIndex', commandRunIndex],
|
|
3202
|
+
...['update', 'sync', 'pause', 'resume', 'reconnect'].map(cmd => [cmd, commandForwardToAccountWorker]),
|
|
3203
|
+
...['smtpReload', 'imapProxyReload'].map(cmd => [cmd, commandReloadServer]),
|
|
3204
|
+
...['apiReloadCertificates', 'smtpReloadCertificates', 'imapProxyReloadCertificates'].map(cmd => [cmd, commandReloadCertificates]),
|
|
3205
|
+
...[
|
|
3206
|
+
'submitMessage',
|
|
3207
|
+
'queueMessage',
|
|
3208
|
+
'listMessages',
|
|
3209
|
+
'getRawMessage',
|
|
3210
|
+
'getText',
|
|
3211
|
+
'getMessage',
|
|
3212
|
+
'getMessages',
|
|
3213
|
+
'updateMessage',
|
|
3214
|
+
'updateMessages',
|
|
3215
|
+
'listMailboxes',
|
|
3216
|
+
'moveMessage',
|
|
3217
|
+
'moveMessages',
|
|
3218
|
+
'deleteMessage',
|
|
3219
|
+
'deleteMessages',
|
|
3220
|
+
'getQuota',
|
|
3221
|
+
'createMailbox',
|
|
3222
|
+
'modifyMailbox',
|
|
3223
|
+
'deleteMailbox',
|
|
3224
|
+
'uploadMessage',
|
|
3225
|
+
'getAttachment',
|
|
3226
|
+
'listSignatures'
|
|
3227
|
+
].map(cmd => [cmd, commandAccountOperation]),
|
|
3228
|
+
['subconnections', commandSubconnections],
|
|
3229
|
+
['googlePubSub', commandGooglePubSub],
|
|
3230
|
+
['googlePubSubRemove', commandGooglePubSub],
|
|
3231
|
+
['externalNotify', commandExternalNotify],
|
|
3232
|
+
['subscriptionLifecycle', commandSubscriptionLifecycle]
|
|
3233
|
+
]);
|
|
3234
|
+
|
|
3235
|
+
async function onCommand(worker, message) {
|
|
3236
|
+
const handler = COMMAND_HANDLERS.get(message.cmd);
|
|
3237
|
+
if (handler) {
|
|
3238
|
+
return await handler(worker, message);
|
|
3239
|
+
}
|
|
3240
|
+
|
|
3241
|
+
return NOT_HANDLED;
|
|
3083
3242
|
}
|
|
3084
3243
|
|
|
3085
3244
|
// Metrics collection results
|
|
@@ -3191,12 +3350,6 @@ const closeQueues = cb => {
|
|
|
3191
3350
|
}
|
|
3192
3351
|
}
|
|
3193
3352
|
|
|
3194
|
-
for (let name of ['notify', 'submit', 'export']) {
|
|
3195
|
-
if (queueEvents[name]) {
|
|
3196
|
-
proms.push(queueEvents[name].close());
|
|
3197
|
-
}
|
|
3198
|
-
}
|
|
3199
|
-
|
|
3200
3353
|
if (!proms.length) {
|
|
3201
3354
|
return setImmediate(() => cb());
|
|
3202
3355
|
}
|
|
@@ -3286,13 +3439,11 @@ const settleWorkerFleet = async (label, promises, logFields) => {
|
|
|
3286
3439
|
};
|
|
3287
3440
|
|
|
3288
3441
|
/**
|
|
3289
|
-
*
|
|
3290
|
-
*
|
|
3442
|
+
* Loads the license from the configured license file and from EENGINE_PREPARED_LICENSE. Either one
|
|
3443
|
+
* failing is fatal: the process exits once the log is flushed
|
|
3444
|
+
* @returns {Promise<boolean>} true when startup has to stop
|
|
3291
3445
|
*/
|
|
3292
|
-
const
|
|
3293
|
-
// Generate unique run index
|
|
3294
|
-
runIndex = await redis.hincrby(`${REDIS_PREFIX}settings`, 'run', 1);
|
|
3295
|
-
|
|
3446
|
+
const importConfiguredLicenses = async () => {
|
|
3296
3447
|
// Process license file if provided
|
|
3297
3448
|
if (config.licensePath) {
|
|
3298
3449
|
try {
|
|
@@ -3310,7 +3461,8 @@ const startApplication = async () => {
|
|
|
3310
3461
|
await setLicense(licenseData, licenseFile);
|
|
3311
3462
|
} catch (err) {
|
|
3312
3463
|
logger.fatal({ msg: 'License verification failed', source: config.licensePath, err });
|
|
3313
|
-
|
|
3464
|
+
logger.flush(() => process.exit(13));
|
|
3465
|
+
return true;
|
|
3314
3466
|
}
|
|
3315
3467
|
}
|
|
3316
3468
|
|
|
@@ -3324,10 +3476,19 @@ const startApplication = async () => {
|
|
|
3324
3476
|
}
|
|
3325
3477
|
} catch (err) {
|
|
3326
3478
|
logger.fatal({ msg: 'License import failed', source: 'import', err });
|
|
3327
|
-
|
|
3479
|
+
logger.flush(() => process.exit(13));
|
|
3480
|
+
return true;
|
|
3328
3481
|
}
|
|
3329
3482
|
}
|
|
3330
3483
|
|
|
3484
|
+
return false;
|
|
3485
|
+
};
|
|
3486
|
+
|
|
3487
|
+
/**
|
|
3488
|
+
* Activates the license stored in Redis, if there is a valid one
|
|
3489
|
+
* @returns {Promise<void>}
|
|
3490
|
+
*/
|
|
3491
|
+
const loadStoredLicense = async () => {
|
|
3331
3492
|
// Load license from database
|
|
3332
3493
|
let licenseFile = await redis.hget(`${REDIS_PREFIX}settings`, 'license');
|
|
3333
3494
|
if (licenseFile) {
|
|
@@ -3350,12 +3511,13 @@ const startApplication = async () => {
|
|
|
3350
3511
|
if (!licenseInfo.active) {
|
|
3351
3512
|
logger.error({ msg: 'No active license. Running in limited mode.' });
|
|
3352
3513
|
}
|
|
3514
|
+
};
|
|
3353
3515
|
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3516
|
+
/**
|
|
3517
|
+
* One-time data migrations that run before the workers spawn. None of them is fatal
|
|
3518
|
+
* @returns {Promise<void>}
|
|
3519
|
+
*/
|
|
3520
|
+
const runStartupMigrations = async () => {
|
|
3359
3521
|
// Move any settings-based OAuth2 configuration into the app registry before workers spawn.
|
|
3360
3522
|
// A failure is not fatal: the source settings keys stay in place, so the migration retries
|
|
3361
3523
|
// on the next startup (the legacy config is simply not visible until it succeeds).
|
|
@@ -3380,7 +3542,13 @@ const startApplication = async () => {
|
|
|
3380
3542
|
} catch (err) {
|
|
3381
3543
|
logger.error({ msg: 'Failed to sweep the retired bounce store', err });
|
|
3382
3544
|
}
|
|
3545
|
+
};
|
|
3383
3546
|
|
|
3547
|
+
/**
|
|
3548
|
+
* Applies EENGINE_SETTINGS and records which keys it manages
|
|
3549
|
+
* @returns {Promise<void>}
|
|
3550
|
+
*/
|
|
3551
|
+
const applyPreparedSettings = async () => {
|
|
3384
3552
|
// Apply prepared settings
|
|
3385
3553
|
if (preparedSettings) {
|
|
3386
3554
|
logger.debug({ msg: 'Applying configuration', settingsKeys: Object.keys(preparedSettings) });
|
|
@@ -3396,13 +3564,13 @@ const startApplication = async () => {
|
|
|
3396
3564
|
} else {
|
|
3397
3565
|
await settings.clear('preparedSettingsKeys');
|
|
3398
3566
|
}
|
|
3567
|
+
};
|
|
3399
3568
|
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3569
|
+
/**
|
|
3570
|
+
* Seeds the SMTP server settings that have no stored value yet
|
|
3571
|
+
* @returns {Promise<void>}
|
|
3572
|
+
*/
|
|
3573
|
+
const seedSmtpServerSettings = async () => {
|
|
3406
3574
|
// SMTP server settings
|
|
3407
3575
|
let existingSmtpEnabled = await settings.get('smtpServerEnabled');
|
|
3408
3576
|
if (existingSmtpEnabled === null) {
|
|
@@ -3433,7 +3601,13 @@ const startApplication = async () => {
|
|
|
3433
3601
|
if (existingSmtpProxy === null) {
|
|
3434
3602
|
await settings.set('smtpServerProxy', SMTP_PROXY);
|
|
3435
3603
|
}
|
|
3604
|
+
};
|
|
3436
3605
|
|
|
3606
|
+
/**
|
|
3607
|
+
* Seeds the IMAP proxy settings that have no stored value yet
|
|
3608
|
+
* @returns {Promise<void>}
|
|
3609
|
+
*/
|
|
3610
|
+
const seedImapProxySettings = async () => {
|
|
3437
3611
|
// IMAP proxy settings
|
|
3438
3612
|
let existingImapProxyEnabled = await settings.get('imapProxyServerEnabled');
|
|
3439
3613
|
if (existingImapProxyEnabled === null) {
|
|
@@ -3459,7 +3633,13 @@ const startApplication = async () => {
|
|
|
3459
3633
|
if (existingImapProxyProxy === null) {
|
|
3460
3634
|
await settings.set('imapProxyServerProxy', IMAP_PROXY_PROXY);
|
|
3461
3635
|
}
|
|
3636
|
+
};
|
|
3462
3637
|
|
|
3638
|
+
/**
|
|
3639
|
+
* Seeds the API, service, webhook, script and token settings that have no stored value yet
|
|
3640
|
+
* @returns {Promise<void>}
|
|
3641
|
+
*/
|
|
3642
|
+
const seedServiceSettings = async () => {
|
|
3463
3643
|
// API proxy settings
|
|
3464
3644
|
let existingEnableApiProxy = await settings.get('enableApiProxy');
|
|
3465
3645
|
if (existingEnableApiProxy === null) {
|
|
@@ -3506,7 +3686,29 @@ const startApplication = async () => {
|
|
|
3506
3686
|
// disableTokens is the inverse of REQUIRE_API_AUTH
|
|
3507
3687
|
await settings.set('disableTokens', !REQUIRE_API_AUTH);
|
|
3508
3688
|
}
|
|
3689
|
+
};
|
|
3509
3690
|
|
|
3691
|
+
/**
|
|
3692
|
+
* Seeds every setting that has no stored value yet, in a fixed order
|
|
3693
|
+
* @returns {Promise<void>}
|
|
3694
|
+
*/
|
|
3695
|
+
const seedDefaultSettings = async () => {
|
|
3696
|
+
// Initialize required settings
|
|
3697
|
+
let existingServiceId = await settings.get('serviceId');
|
|
3698
|
+
if (existingServiceId === null) {
|
|
3699
|
+
await settings.set('serviceId', crypto.randomBytes(16).toString('hex'));
|
|
3700
|
+
}
|
|
3701
|
+
|
|
3702
|
+
await seedSmtpServerSettings();
|
|
3703
|
+
await seedImapProxySettings();
|
|
3704
|
+
await seedServiceSettings();
|
|
3705
|
+
};
|
|
3706
|
+
|
|
3707
|
+
/**
|
|
3708
|
+
* Imports EENGINE_PREPARED_TOKEN and EENGINE_PREPARED_PASSWORD. A failure is logged, not fatal
|
|
3709
|
+
* @returns {Promise<void>}
|
|
3710
|
+
*/
|
|
3711
|
+
const importPreparedCredentials = async () => {
|
|
3510
3712
|
// Import prepared token
|
|
3511
3713
|
if (preparedToken) {
|
|
3512
3714
|
try {
|
|
@@ -3544,7 +3746,13 @@ const startApplication = async () => {
|
|
|
3544
3746
|
logger.error({ msg: 'Password import failed', err });
|
|
3545
3747
|
}
|
|
3546
3748
|
}
|
|
3749
|
+
};
|
|
3547
3750
|
|
|
3751
|
+
/**
|
|
3752
|
+
* Warns about a missing encryption secret and makes sure the admin session cookie key exists
|
|
3753
|
+
* @returns {Promise<void>}
|
|
3754
|
+
*/
|
|
3755
|
+
const ensureInstanceSecrets = async () => {
|
|
3548
3756
|
if (!(await getSecret())) {
|
|
3549
3757
|
// Every consumer of the secret stores the value as it is when there is none, so without
|
|
3550
3758
|
// it the account passwords, OAuth2 tokens, webhook secrets and TLS keys sit in Redis in
|
|
@@ -3560,16 +3768,13 @@ const startApplication = async () => {
|
|
|
3560
3768
|
cookiePassword = crypto.randomBytes(32).toString('base64');
|
|
3561
3769
|
await settings.set('cookiePassword', cookiePassword);
|
|
3562
3770
|
}
|
|
3771
|
+
};
|
|
3563
3772
|
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
await reloadHttpProxyAgent();
|
|
3570
|
-
|
|
3571
|
-
// -- START WORKER THREADS
|
|
3572
|
-
|
|
3773
|
+
/**
|
|
3774
|
+
* Starts the API workers, several sharing the listen port when SO_REUSEPORT allows it
|
|
3775
|
+
* @returns {Promise<void>}
|
|
3776
|
+
*/
|
|
3777
|
+
const startApiWorkers = async () => {
|
|
3573
3778
|
// Start API server first for health checks.
|
|
3574
3779
|
// Optionally run several API workers that share the listen port via SO_REUSEPORT.
|
|
3575
3780
|
apiWorkersRequested = config.workers.api;
|
|
@@ -3620,10 +3825,13 @@ const startApplication = async () => {
|
|
|
3620
3825
|
// `attempted` can be below `requested` after the SO_REUSEPORT fallback above
|
|
3621
3826
|
let apiReady = (await settleWorkerFleet('API', apiPromises, { requested: apiWorkersRequested, attempted: apiPromises.length })).length;
|
|
3622
3827
|
logger.info({ msg: 'API workers started', requested: apiWorkersRequested, ready: apiReady });
|
|
3828
|
+
};
|
|
3623
3829
|
|
|
3624
|
-
|
|
3625
|
-
|
|
3626
|
-
|
|
3830
|
+
/**
|
|
3831
|
+
* Starts the IMAP workers and assigns the accounts to them
|
|
3832
|
+
* @returns {Promise<void>}
|
|
3833
|
+
*/
|
|
3834
|
+
const startImapWorkers = async () => {
|
|
3627
3835
|
// Start IMAP workers
|
|
3628
3836
|
let workerPromises = [];
|
|
3629
3837
|
for (let i = 0; i < config.workers.imap; i++) {
|
|
@@ -3646,7 +3854,14 @@ const startApplication = async () => {
|
|
|
3646
3854
|
} catch (err) {
|
|
3647
3855
|
logger.error({ msg: 'Initial account assignment failed', err });
|
|
3648
3856
|
}
|
|
3857
|
+
};
|
|
3649
3858
|
|
|
3859
|
+
/**
|
|
3860
|
+
* Starts the webhook, submission and export workers, then the SMTP server and the IMAP proxy if
|
|
3861
|
+
* they are enabled
|
|
3862
|
+
* @returns {Promise<void>}
|
|
3863
|
+
*/
|
|
3864
|
+
const startBackgroundWorkers = async () => {
|
|
3650
3865
|
// Start webhook workers
|
|
3651
3866
|
for (let i = 0; i < config.workers.webhooks; i++) {
|
|
3652
3867
|
await spawnWorker('webhooks');
|
|
@@ -3681,7 +3896,12 @@ const startApplication = async () => {
|
|
|
3681
3896
|
if (await settings.get('imapProxyServerEnabled')) {
|
|
3682
3897
|
await spawnWorker('imapProxy');
|
|
3683
3898
|
}
|
|
3899
|
+
};
|
|
3684
3900
|
|
|
3901
|
+
/**
|
|
3902
|
+
* Creates and starts the background metrics collector
|
|
3903
|
+
*/
|
|
3904
|
+
const startMetricsCollector = () => {
|
|
3685
3905
|
// Initialize and start the metrics collector after all workers are ready
|
|
3686
3906
|
metricsCollector = new MetricsCollector({
|
|
3687
3907
|
logger,
|
|
@@ -3725,6 +3945,57 @@ const startApplication = async () => {
|
|
|
3725
3945
|
logger.info({ msg: 'Background metrics collector initialized and started' });
|
|
3726
3946
|
};
|
|
3727
3947
|
|
|
3948
|
+
/**
|
|
3949
|
+
* Main application startup
|
|
3950
|
+
* @returns {Promise<void>}
|
|
3951
|
+
*/
|
|
3952
|
+
const startApplication = async () => {
|
|
3953
|
+
// Generate unique run index
|
|
3954
|
+
runIndex = await redis.hincrby(`${REDIS_PREFIX}settings`, 'run', 1);
|
|
3955
|
+
|
|
3956
|
+
// A license that was explicitly configured but cannot be loaded stops the startup
|
|
3957
|
+
if (await importConfiguredLicenses()) {
|
|
3958
|
+
return;
|
|
3959
|
+
}
|
|
3960
|
+
|
|
3961
|
+
await loadStoredLicense();
|
|
3962
|
+
|
|
3963
|
+
// Check for updates
|
|
3964
|
+
processCheckUpgrade().catch(err => {
|
|
3965
|
+
logger.warn({ msg: 'Update check failed', err });
|
|
3966
|
+
});
|
|
3967
|
+
|
|
3968
|
+
await runStartupMigrations();
|
|
3969
|
+
|
|
3970
|
+
await applyPreparedSettings();
|
|
3971
|
+
|
|
3972
|
+
await seedDefaultSettings();
|
|
3973
|
+
|
|
3974
|
+
await importPreparedCredentials();
|
|
3975
|
+
|
|
3976
|
+
await ensureInstanceSecrets();
|
|
3977
|
+
|
|
3978
|
+
// Redis reconnection is now handled by workers themselves
|
|
3979
|
+
// Workers will exit when Redis reconnects after disconnection,
|
|
3980
|
+
// and the server will automatically restart them
|
|
3981
|
+
|
|
3982
|
+
// Initialize HTTP proxy agent from settings/env vars before spawning workers
|
|
3983
|
+
await reloadHttpProxyAgent();
|
|
3984
|
+
|
|
3985
|
+
// -- START WORKER THREADS
|
|
3986
|
+
|
|
3987
|
+
await startApiWorkers();
|
|
3988
|
+
|
|
3989
|
+
// Small delay to allow API to start
|
|
3990
|
+
await new Promise(r => setTimeout(r, 100));
|
|
3991
|
+
|
|
3992
|
+
await startImapWorkers();
|
|
3993
|
+
|
|
3994
|
+
await startBackgroundWorkers();
|
|
3995
|
+
|
|
3996
|
+
startMetricsCollector();
|
|
3997
|
+
};
|
|
3998
|
+
|
|
3728
3999
|
// Start the application
|
|
3729
4000
|
startApplication()
|
|
3730
4001
|
.then(bounceClassifier.initialize)
|
|
@@ -3747,22 +4018,17 @@ startApplication()
|
|
|
3747
4018
|
// Start worker health monitoring
|
|
3748
4019
|
startHealthMonitoring();
|
|
3749
4020
|
|
|
3750
|
-
// Initialize queue event listeners
|
|
3751
|
-
for (let name of ['notify', 'submit', 'export']) {
|
|
3752
|
-
queueEvents[name] = logBullErrors(new QueueEvents(name, Object.assign({}, queueConf)), `queueEvents:${name}`);
|
|
3753
|
-
}
|
|
3754
|
-
|
|
3755
4021
|
// Periodic queue cleanup (every 6 hours)
|
|
3756
4022
|
const QUEUE_CLEANUP_INTERVAL = 6 * 60 * 60 * 1000;
|
|
3757
4023
|
|
|
3758
4024
|
async function cleanupQueues() {
|
|
3759
4025
|
const queues = [notifyQueue, submitQueue, exportQueue];
|
|
4026
|
+
const ages = queueCleanAges(await getFailedJobRetention());
|
|
3760
4027
|
for (const queue of queues) {
|
|
3761
4028
|
try {
|
|
3762
|
-
//
|
|
3763
|
-
await queue.clean(
|
|
3764
|
-
|
|
3765
|
-
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');
|
|
3766
4032
|
logger.trace({ msg: 'Queue cleanup completed', queue: queue.name });
|
|
3767
4033
|
} catch (err) {
|
|
3768
4034
|
logger.error({ msg: 'Queue cleanup failed', queue: queue.name, err });
|