Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
4057 lines (3524 loc) · 156 KB
/
Copy pathserver.js
File metadata and controls
4057 lines (3524 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/**
* EmailEngine Main Server Module
*
* This is the main entry point for EmailEngine - a self-hosted email automation platform.
* It manages worker threads for IMAP connections, webhooks, email submission, and various
* proxy servers (SMTP, IMAP).
*
* @module server
* @requires dotenv
* @requires worker_threads
* @requires @zone-eu/wild-config
* @see {@link https://emailengine.app}
*/
// No native addons (CLAUDE.md "Pure JavaScript only"). bullmq depends on msgpackr, whose optional
// dependency msgpackr-extract is a node-gyp addon that npm and Docker installs pick up and load
// when present, while the pkg binary decodes in JavaScript. This makes every install decode the
// same way. Set before anything can require bullmq; worker threads share this environment.
process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED = 'true';
// Attempt to change working directory to script location. Before anything reads a file by a
// relative path: `.env` below and the `config/` directory wild-config loads (including executable
// `.js` configuration files, run with the real require) are both resolved against the working
// directory, and the directory the operator happened to start from is not where this instance's
// configuration lives
try {
process.chdir(__dirname);
} catch (err) {
// ignore - may fail in some containerized environments
}
// Load environment variables if not already loaded
if (!process.env.EE_ENV_LOADED) {
require('dotenv').config({ quiet: true });
process.env.EE_ENV_LOADED = 'true';
}
// Set process title for easier identification in process lists
process.title = 'emailengine';
// EmailEngine and its dependencies need Node 20 or newer. Checked before anything is required, so an
// older runtime gets this line instead of a syntax error from a dependency. The check used to be a
// structuredClone probe, which only caught Node 16 and older.
if (Number(process.versions.node.split('.')[0]) < 20) {
console.error(`Node.js version ${process.version} is not supported. Please upgrade to Node.js 20 or later.`);
process.exit(1);
}
// Within Node 20 the dependency tree itself asks for 20.19.0 (html-to-text 10, the entities release
// node-html-parser pulls in) or 20.18.1 (undici 7), which is what the engines field declares. npm
// treats that field as advice, and an older 20.x starts and then fails somewhere in a dependency at
// runtime, so it is named here. Only a warning: one-click DigitalOcean images upgrade EmailEngine on
// their own but not the Node they run on, and an instance that works today must not stop at its next
// self-upgrade over a minor version it may never exercise.
const { MIN_SUPPORTED_NODE, isBelowSupportedNode } = require('./lib/node-version');
if (isBelowSupportedNode(process.versions.node)) {
console.error(
`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.`
);
}
const os = require('os');
// Set UV thread pool size for better async I/O performance
// Defaults to number of CPU cores (minimum 4)
process.env.UV_THREADPOOL_SIZE =
process.env.UV_THREADPOOL_SIZE && !isNaN(process.env.UV_THREADPOOL_SIZE) ? Number(process.env.UV_THREADPOOL_SIZE) : Math.max(os.cpus().length, 4);
// Disable Tensorflow warnings
process.env.TF_CPP_MIN_LOG_LEVEL = '2';
// Cache command line arguments before @zone-eu/wild-config processes them
const argv = process.argv.slice(2);
const { Worker: WorkerThread, SHARE_ENV } = require('worker_threads');
const packageData = require('./package.json');
const config = require('@zone-eu/wild-config');
const logger = require('./lib/logger');
// Import utility functions
const {
readEnvValue,
hasEnvValue,
download,
getDuration,
getByteSize,
getBoolean,
workerPoolSize,
selectRendezvousNode,
checkLicense,
checkForUpgrade,
setLicense,
getRedisStats,
threadStats,
httpAgent,
reloadHttpProxyAgent,
maybeReloadHttpProxyAgent,
redactValidationError
} = require('./lib/tools');
const MetricsCollector = require('./lib/metrics-collector');
// Import constants
const {
MAX_DAYS_STATS,
MESSAGE_NEW_NOTIFY,
MESSAGE_DELETED_NOTIFY,
CONNECT_ERROR_NOTIFY,
REDIS_PREFIX,
ACCOUNT_ADDED_NOTIFY,
ACCOUNT_DELETED_NOTIFY,
LIST_UNSUBSCRIBE_NOTIFY,
LIST_SUBSCRIBE_NOTIFY,
LAST_DOCUMENT_STORE_VERSION,
AI_REQUEST_TIMEOUT,
AI_SETTING_KEYS
} = require('./lib/consts');
// Import core modules
const { webhooks: Webhooks } = require('./lib/webhooks');
const { generateSummary, listModels: openAiListModels, DEFAULT_MODEL: openAiDefaultModel } = require('@postalsys/email-ai-tools');
const { fetch: fetchCmd } = require('undici');
const bounceClassifier = require('@postalsys/bounce-classifier');
const v8 = require('node:v8');
// Initialize Sentry error tracking if a DSN is provided
const { initSentry } = require('./lib/sentry');
initSentry('main');
// Import additional dependencies
const pathlib = require('path');
const { redis, notifyQueue, submitQueue, exportQueue } = require('./lib/db');
const { queueStats } = require('./lib/queue-stats');
const { pruneFailedContent } = require('./lib/outbox');
const { queueCleanAges } = require('./lib/queue-retention');
const { getFailedJobRetention } = require('./lib/env-setting-overrides');
const { packRpcError, unpackRpcError } = require('./lib/worker-rpc-error');
const promClient = require('prom-client');
const fs = require('fs').promises;
const crypto = require('crypto');
const { compareVersions, parseVersion } = require('./lib/utils/version');
const Joi = require('joi');
const { settingsSchema } = require('./lib/schemas');
const settings = require('./lib/settings');
const { oauth2Apps } = require('./lib/oauth2-apps');
const { backfillAuthFailureDisabled } = require('./lib/account/auth-failure-backfill');
const { sweepBounceStore } = require('./lib/account/bounce-store-sweep');
const { attachBeacon, persistBeaconMarkers } = require('./lib/license-beacon');
const tokens = require('./lib/tokens');
const { checkRateLimit } = require('./lib/rate-limit');
const getSecret = require('./lib/get-secret');
const { rejectWorkerCalls } = require('./lib/reject-worker-calls');
const {
pickLeastLoadedWorker,
rollbackAssignment,
assignRetryDelay,
QUICK_ASSIGN_RETRIES,
releaseWorkerAccounts,
requeueFailedAccounts,
forgetAccount,
shouldRequeueFailedAssignment,
planRebalance
} = require('./lib/account-assignment');
const { mapConcurrent } = require('./lib/utils/map-concurrent');
const { RespawnTracker, retryWithBackoff } = require('./lib/respawn-backoff');
const { legacySmtpOptionsInUse, REMOVAL_DATE } = require('./lib/deprecations');
const { heartbeatDiagnostics, eventLoopDelaySeries, threadHeapSeries } = require('./lib/thread-diagnostics');
const msgpack = require('./lib/msgpack');
// Initialize default configuration values if not set
config.service = config.service || {};
// Default worker thread counts
config.workers = config.workers || {
imap: 4, // IMAP connection handlers
webhooks: 1, // Webhook processors
submit: 1, // Email submission workers
imapProxy: 1 // IMAP proxy server
};
config.dbs = config.dbs || {
redis: 'redis://127.0.0.1:6379/8'
};
config.log = config.log || {
level: 'trace'
};
config.api = config.api || {
port: 3000,
host: '127.0.0.1'
};
// SMTP proxy server configuration
config.smtp = config.smtp || {
enabled: false,
port: 2525,
host: '127.0.0.1',
secret: '',
proxy: false
};
// IMAP proxy server configuration
config['imap-proxy'] = config['imap-proxy'] || {
enabled: false,
port: 2993,
host: '127.0.0.1',
secret: '',
proxy: false
};
// Application start timestamp
const NOW = Date.now();
// Initialize metrics collector (will be configured and started later)
let metricsCollector = null;
// Timeout configuration
const DEFAULT_EENGINE_TIMEOUT = 10 * 1000;
const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.service.commandTimeout) || DEFAULT_EENGINE_TIMEOUT;
// Size limits
const DEFAULT_MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024; // 5MB
// License check intervals
const SUBSCRIPTION_CHECK_TIMEOUT = 1 * 24 * 60 * 60 * 1000; // 24 hours
const SUBSCRIPTION_RECHECK_TIMEOUT = 1 * 60 * 60 * 1000; // 1 hour
const SUBSCRIPTION_ALLOW_DELAY = 28 * 24 * 60 * 60 * 1000; // 28 days grace period
// Delay between account connection setups (to avoid overwhelming the system)
const CONNECTION_SETUP_DELAY = getDuration(readEnvValue('EENGINE_CONNECTION_SETUP_DELAY') || config.service.setupDelay) || 0;
// Override configuration with environment variables
config.api.maxSize = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
config.dbs.redis = readEnvValue('EENGINE_REDIS') || readEnvValue('REDIS_URL') || config.dbs.redis;
config.workers.imap = workerPoolSize(readEnvValue('EENGINE_WORKERS'), config.workers.imap, 4);
config.workers.webhooks = workerPoolSize(readEnvValue('EENGINE_WORKERS_WEBHOOKS'), config.workers.webhooks);
config.workers.submit = workerPoolSize(readEnvValue('EENGINE_WORKERS_SUBMIT'), config.workers.submit);
// The Workers page has labelled this row EENGINE_WORKERS_EXPORT since the export worker shipped, while
// only --workers.export and [workers] export were read, so an operator who set it saw no effect
config.workers.export = workerPoolSize(readEnvValue('EENGINE_WORKERS_EXPORT'), config.workers.export);
// API worker count. Values >1 require SO_REUSEPORT (Linux); on unsupported platforms it falls back to 1 at startup.
config.workers.api = workerPoolSize(readEnvValue('EENGINE_WORKERS_API'), config.workers.api);
config.api.port =
(hasEnvValue('EENGINE_PORT') && Number(readEnvValue('EENGINE_PORT'))) || (hasEnvValue('PORT') && Number(readEnvValue('PORT'))) || config.api.port;
config.api.host = readEnvValue('EENGINE_HOST') || config.api.host;
config.log.level = readEnvValue('EENGINE_LOG_LEVEL') || config.log.level;
// Legacy SMTP configuration options, removed after REMOVAL_DATE (lib/deprecations.js). They only
// seed the SMTP server settings on a first start; the admin UI and the settings API own them after that
const SMTP_ENABLED = hasEnvValue('EENGINE_SMTP_ENABLED') ? getBoolean(readEnvValue('EENGINE_SMTP_ENABLED')) : getBoolean(config.smtp.enabled);
const SMTP_SECRET = readEnvValue('EENGINE_SMTP_SECRET') || config.smtp.secret;
const SMTP_PORT = (readEnvValue('EENGINE_SMTP_PORT') && Number(readEnvValue('EENGINE_SMTP_PORT'))) || Number(config.smtp.port) || 2525;
const SMTP_HOST = readEnvValue('EENGINE_SMTP_HOST') || config.smtp.host || '127.0.0.1';
const SMTP_PROXY = hasEnvValue('EENGINE_SMTP_PROXY') ? getBoolean(readEnvValue('EENGINE_SMTP_PROXY')) : getBoolean(config.smtp.proxy);
// IMAP proxy configuration
const IMAP_PROXY_ENABLED = hasEnvValue('EENGINE_IMAP_PROXY_ENABLED')
? getBoolean(readEnvValue('EENGINE_IMAP_PROXY_ENABLED'))
: getBoolean(config['imap-proxy'].enabled);
const IMAP_PROXY_SECRET = readEnvValue('EENGINE_IMAP_PROXY_SECRET') || config['imap-proxy'].secret;
const IMAP_PROXY_PORT =
(readEnvValue('EENGINE_IMAP_PROXY_PORT') && Number(readEnvValue('EENGINE_IMAP_PROXY_PORT'))) || Number(config['imap-proxy'].port) || 2993;
const IMAP_PROXY_HOST = readEnvValue('EENGINE_IMAP_PROXY_HOST') || config['imap-proxy'].host || '127.0.0.1';
const IMAP_PROXY_PROXY = hasEnvValue('EENGINE_IMAP_PROXY_PROXY')
? getBoolean(readEnvValue('EENGINE_IMAP_PROXY_PROXY'))
: getBoolean(config['imap-proxy'].proxy);
// Metrics collection interval - consider connections recent if started within 10 minutes
const METRIC_RECENT = 10 * 60 * 1000; // 10min
// API proxy configuration
const HAS_API_PROXY_SET = hasEnvValue('EENGINE_API_PROXY') || typeof config.api.proxy !== 'undefined';
const API_PROXY = hasEnvValue('EENGINE_API_PROXY') ? getBoolean(readEnvValue('EENGINE_API_PROXY')) : getBoolean(config.api.proxy);
// API authentication requirement configuration (default: true)
const REQUIRE_API_AUTH = hasEnvValue('EENGINE_REQUIRE_API_AUTH') ? getBoolean(readEnvValue('EENGINE_REQUIRE_API_AUTH')) : null;
// Opt-out for the license-validation feature beacon (telemetry rides on the existing license call)
const BEACON_DISABLED = hasEnvValue('EENGINE_BEACON_DISABLED') ? getBoolean(readEnvValue('EENGINE_BEACON_DISABLED')) : false;
// Opt-out for the GitHub releases update check, the only background network
// call that is not tied to a subscription license. With this and a perpetual
// license an instance makes no background calls at all (strict-egress and
// air-gapped deployments).
const UPDATE_CHECK_DISABLED = hasEnvValue('EENGINE_UPDATE_CHECK_DISABLED') ? getBoolean(readEnvValue('EENGINE_UPDATE_CHECK_DISABLED')) : false;
// OAuth2 token access configuration
const ENABLE_OAUTH_TOKENS_API = hasEnvValue('EENGINE_ENABLE_OAUTH_TOKENS_API') ? getBoolean(readEnvValue('EENGINE_ENABLE_OAUTH_TOKENS_API')) : null;
// Log startup information
logger.info({
msg: 'EmailEngine starting up',
version: packageData.version,
node: process.versions.node,
uvThreadpoolSize: Number(process.env.UV_THREADPOOL_SIZE),
workersImap: config.workers.imap,
workersWebhooks: config.workers.webhooks,
workersSubmission: config.workers.submit
});
const legacySmtpOptions = legacySmtpOptionsInUse({ hasEnvValue, smtpConfig: config.smtp });
if (legacySmtpOptions.length) {
logger.warn({
msg: 'Deprecated SMTP server options are set, configure the SMTP server in the admin UI or through the settings API instead',
options: legacySmtpOptions,
removal: REMOVAL_DATE
});
}
// Standard response for when no active worker is available
const NO_ACTIVE_HANDLER_RESP_ERR = new Error('No active handler for requested account. Try again later.');
NO_ACTIVE_HANDLER_RESP_ERR.statusCode = 503;
NO_ACTIVE_HANDLER_RESP_ERR.code = 'WorkerNotAvailable';
// Shared rejection for in-flight calls whose target worker terminated mid-request.
// Reused across concurrent rejections - never attach per-call fields to this instance.
const WORKER_DIED_RESP_ERR = new Error('Worker handling the request terminated before completion. Try again.');
WORKER_DIED_RESP_ERR.statusCode = 503;
WORKER_DIED_RESP_ERR.code = 'WorkerNotAvailable';
// Update check intervals
const UPGRADE_CHECK_TIMEOUT = 1 * 24 * 3600 * 1000; // 24 hours
const LICENSE_CHECK_TIMEOUT = 20 * 60 * 1000; // 20 minutes
const MAX_LICENSE_CHECK_DELAY = 30 * 24 * 60 * 60 * 1000; // 30 days
/**
* License information object
* @typedef {Object} LicenseInfo
* @property {boolean} active - Whether license is active
* @property {Object|boolean} details - License details or false if no license
* @property {string} type - License type description
*/
const licenseInfo = {
active: false,
details: false,
type: packageData.license
};
/**
* Copy of license details that is safe for logging (the raw license key is removed)
* @param {Object|boolean} license - License details object
* @returns {Object|boolean} Redacted copy
*/
const redactLicense = license => {
if (!license || typeof license !== 'object') {
return license;
}
let copy = Object.assign({}, license);
delete copy.key;
return copy;
};
/**
* Human-readable thread type names for display
* @const {Object<string, string>}
*/
const THREAD_NAMES = {
main: 'Main thread',
imap: 'Email worker',
webhooks: 'Webhook worker',
api: 'HTTP and API server',
submit: 'Email sending worker',
export: 'Export worker',
imapProxy: 'IMAP proxy server',
smtp: 'SMTP proxy server'
};
/**
* Configuration key-value mappings for different thread types
* @const {Object<string, {key: string, value: number}>}
*/
const THREAD_CONFIG_VALUES = {
imap: { key: 'EENGINE_WORKERS', value: config.workers.imap },
api: { key: 'EENGINE_WORKERS_API', value: config.workers.api },
submit: { key: 'EENGINE_WORKERS_SUBMIT', value: config.workers.submit },
webhooks: { key: 'EENGINE_WORKERS_WEBHOOKS', value: config.workers.webhooks },
export: { key: 'EENGINE_WORKERS_EXPORT', value: config.workers.export }
};
// Unique run index for this server instance
let runIndex;
// Whether multiple API workers may share the listen port via SO_REUSEPORT.
// Determined once at startup by probeReusePort(); false means a single API worker.
let apiWorkerReusePort = false;
// Requested API worker count (EENGINE_WORKERS_API), surfaced on /admin/internals so operators can
// see when more workers were requested than could be started. Whether we fell back to a single
// worker is derived: `apiWorkersRequested > 1 && !apiWorkerReusePort`.
let apiWorkersRequested = 1;
// Why a multi-worker request fell back to a single API worker, surfaced on /admin/internals so the
// banner can state the real cause. Set during probeReusePort():
// - 'platform': SO_REUSEPORT is unsupported on this OS/Node build (Linux with Node < 23.1, macOS, Windows)
// - 'port': the probe could not test the port (transient conflict / permission), so support is unknown
// Stays null when SO_REUSEPORT is supported or only one worker was requested.
let apiWorkerReusePortFallbackReason = null;
/**
* Probe whether SO_REUSEPORT can load-balance across multiple sockets on this
* platform. Binds two listeners to the same host:port with reusePort enabled;
* both must succeed for load balancing to work. It is unsupported on macOS,
* Windows, and Node < 23.1, where either the first bind fails outright (e.g.
* ENOTSUP) or - when the reusePort option is silently ignored (Node < 23.1) -
* the first bind succeeds as a plain bind and the second fails with EADDRINUSE.
* The `stage` field tells the caller where the probe failed so it can separate a
* genuine platform/capability limitation from a transient port conflict:
* - 'probe': the first bind failed, so the port could not even be tested. An
* EADDRINUSE/EACCES code here means the port is unavailable (transient); any
* other code means the platform rejected reusePort.
* - 'reuse': the first bind succeeded but the second did not, so reusePort is
* not honored on this platform/Node - a capability limitation, even though
* the failing code is EADDRINUSE.
* - null: SO_REUSEPORT is supported.
* @param {string} host - Bind address
* @param {number} port - Listen port
* @returns {Promise<{supported: boolean, code: (string|null), stage: (string|null)}>}
* Whether SO_REUSEPORT load balancing works, the failing bind's error code (or
* null), and which bind failed ('probe', 'reuse', or null when supported)
*/
async function probeReusePort(host, port) {
const net = require('net');
const open = () =>
new Promise(resolve => {
let srv = net.createServer();
srv.once('error', err => resolve({ srv: null, code: (err && err.code) || null }));
try {
srv.listen({ host, port, reusePort: true }, () => resolve({ srv, code: null }));
} catch (err) {
resolve({ srv: null, code: (err && err.code) || null });
}
});
const close = srv =>
new Promise(resolve => {
if (!srv) {
return resolve();
}
srv.close(() => resolve());
});
let first = await open();
if (!first.srv) {
// Could not even bind the first probe socket, so the port itself could not be tested.
return { supported: false, code: first.code, stage: 'probe' };
}
let second = await open();
await close(first.srv);
await close(second.srv);
if (second.srv) {
return { supported: true, code: null, stage: null };
}
// The first bind succeeded but a second listener on the same host:port did not, so the kernel is
// not load-balancing via SO_REUSEPORT - the option was accepted/ignored but not honored (e.g.
// Linux with Node < 23.1, where reusePort is an unrecognized listen() option). This is a platform
// limitation, not a port conflict, even though the failing code is EADDRINUSE.
return { supported: false, code: second.code, stage: 'reuse' };
}
/**
* Compute per-worker spawn options. API workers receive their index and whether to
* bind with SO_REUSEPORT; other worker types need no extra workerData. Keeps the
* startup and respawn paths deriving spawn options from a single place.
* @param {string} type - Worker type
* @param {number} workerIndex - Zero-based index within the worker type
* @returns {Object|undefined} Spawn options for spawnWorker(), or undefined
*/
const workerSpawnOpts = (type, workerIndex) => (type === 'api' ? { workerData: { workerIndex, reusePort: apiWorkerReusePort } } : undefined);
// Prepared configuration handling
let preparedSettings = false;
const preparedSettingsString = readEnvValue('EENGINE_SETTINGS') || config.settings;
if (preparedSettingsString) {
// Parse and validate pre-configured settings
try {
const parsedSettings = JSON.parse(preparedSettingsString);
const { error, value } = Joi.object(settingsSchema).validate(parsedSettings, {
abortEarly: false,
stripUnknown: true,
convert: true
});
if (error) {
throw error;
}
// stripUnknown drops unknown keys without an error, which silently swallows both typos
// and keys that used to be settings - most notably the legacy gmail*/outlook*/mailRu*
// OAuth2 keys that moved into the OAuth2 app registry. Booting on regardless is right
// (an upgraded install must not be bricked by a stale env variable), but the drop has
// to be visible: for the legacy keys the operator has to create an OAuth2 app instead,
// because nothing reads these values anymore.
if (parsedSettings && typeof parsedSettings === 'object') {
const droppedKeys = Object.keys(parsedSettings).filter(key => !Object.hasOwn(settingsSchema, key));
if (droppedKeys.length) {
logger.error({
msg: 'Ignoring unknown keys in the prepared settings. Settings-based OAuth2 configuration is not supported anymore - use an OAuth2 app instead',
keys: droppedKeys
});
}
}
preparedSettings = value;
} catch (err) {
// A joi failure here carries every submitted setting - including smtpServerPassword,
// imapProxyServerPassword and serviceSecret - and this logger has no redaction of its own
logger.fatal({ msg: 'Invalid settings configuration provided', err: redactValidationError(err) });
logger.flush(() => process.exit(1));
}
}
// Prepared token handling for pre-configured API tokens
let preparedToken = false;
const preparedTokenString = readEnvValue('EENGINE_PREPARED_TOKEN') || config.preparedToken;
if (preparedTokenString) {
try {
preparedToken = msgpack.decode(Buffer.from(preparedTokenString, 'base64url'));
if (!preparedToken || !/^[0-9a-f]{64}$/i.test(preparedToken.id)) {
throw new Error('Token format is invalid');
}
} catch (err) {
logger.fatal({ msg: 'Invalid API token provided', inputLength: preparedTokenString.length, err });
logger.flush(() => process.exit(1));
}
}
// Prepared password handling for pre-configured admin passwords
let preparedPassword = false;
const preparedPasswordString = readEnvValue('EENGINE_PREPARED_PASSWORD') || config.preparedPassword;
if (preparedPasswordString) {
try {
preparedPassword = Buffer.from(preparedPasswordString, 'base64url').toString();
if (!preparedPassword || preparedPassword.indexOf('$pbkdf2') !== 0) {
throw new Error('Password format is invalid');
}
} catch (err) {
logger.fatal({ msg: 'Invalid password hash provided', err });
logger.flush(() => process.exit(1));
}
}
// Initialize Prometheus metrics collection
const collectDefaultMetrics = promClient.collectDefaultMetrics;
collectDefaultMetrics({});
/**
* Prometheus metrics definitions for monitoring
* @const {Object}
*/
const metrics = {
threadStarts: new promClient.Counter({
name: 'thread_starts',
help: 'Number of started threads'
}),
threadStops: new promClient.Counter({
name: 'thread_stops',
help: 'Number of stopped threads'
}),
apiCall: new promClient.Counter({
name: 'api_call',
help: 'Number of API calls',
labelNames: ['method', 'statusCode', 'route']
}),
// Labelled by route, not by status: the counter above already splits by status, and a latency
// series per status code would multiply the route count for little an operator can act on
apiCallDuration: new promClient.Histogram({
name: 'api_call_duration_seconds',
help: 'Duration of API calls, from receiving the request to sending the response',
labelNames: ['method', 'route'],
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60]
}),
imapConnections: new promClient.Gauge({
name: 'imap_connections',
help: 'Current IMAP connection state',
labelNames: ['status']
}),
imapResponses: new promClient.Counter({
name: 'imap_responses',
help: 'IMAP responses',
labelNames: ['response', 'code']
}),
imapBytesSent: new promClient.Counter({
name: 'imap_bytes_sent',
help: 'IMAP bytes sent'
}),
imapBytesReceived: new promClient.Counter({
name: 'imap_bytes_received',
help: 'IMAP bytes received'
}),
oauth2TokenRefresh: new promClient.Counter({
name: 'oauth2_token_refresh',
help: 'OAuth2 access token refresh attempts',
labelNames: ['status', 'provider', 'statusCode']
}),
oauth2ApiRequest: new promClient.Counter({
name: 'oauth2_api_request',
help: 'OAuth2 API requests (MS Graph, Gmail API)',
labelNames: ['status', 'provider', 'statusCode']
}),
outlookMissedRecovery: new promClient.Counter({
name: 'outlook_missed_recovery',
help: 'MS Graph missed-notification recovery passes, by what asked for them and whether they found unannounced messages',
labelNames: ['reason', 'outcome']
}),
outlookMissedRecoveredMessages: new promClient.Counter({
name: 'outlook_missed_recovered_messages',
help: 'New messages announced by MS Graph missed-notification recovery instead of by a change notification',
labelNames: ['reason']
}),
outlookSubscriptions: new promClient.Gauge({
name: 'outlook_subscriptions',
help: 'MS Graph webhook subscription states',
labelNames: ['status']
}),
webhooks: new promClient.Counter({
name: 'webhooks',
help: 'Webhooks sent',
labelNames: ['status', 'event']
}),
events: new promClient.Counter({
name: 'events',
help: 'Events fired',
labelNames: ['event']
}),
aiRequests: new promClient.Counter({
name: 'ai_requests',
help: 'AI summary requests',
labelNames: ['model', 'status']
}),
aiTokens: new promClient.Counter({
name: 'ai_tokens',
help: 'Tokens billed for AI summary requests',
labelNames: ['model', 'type']
}),
webhookReq: new promClient.Histogram({
name: 'webhook_req',
help: 'Duration of webhook requests',
buckets: [100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000, 60 * 1000]
}),
queues: new promClient.Gauge({
name: 'queue_size',
help: 'Queue size',
labelNames: ['queue', 'state']
}),
queueFailed: new promClient.Gauge({
name: 'queue_failed_jobs',
help: 'Failed jobs a queue still retains (deliveries that were given up on)',
labelNames: ['queue']
}),
queuesProcessed: new promClient.Counter({
name: 'queues_processed',
help: 'Processed job count',
labelNames: ['queue', 'status']
}),
threads: new promClient.Gauge({
name: 'threads',
help: 'Worker Threads',
labelNames: ['type', 'recent']
}),
unresponsiveWorkers: new promClient.Gauge({
name: 'unresponsive_workers',
help: 'Number of unresponsive worker threads'
}),
threadEventLoopDelayMax: new promClient.Gauge({
name: 'thread_event_loop_delay_max_seconds',
help: 'Longest event loop delay of a thread over the last collection window (15s)',
labelNames: ['type', 'thread']
}),
threadEventLoopDelayP99: new promClient.Gauge({
name: 'thread_event_loop_delay_p99_seconds',
help: '99th percentile event loop delay of a thread over the last collection window (15s)',
labelNames: ['type', 'thread']
}),
threadHeapUsed: new promClient.Gauge({
name: 'thread_heap_used_bytes',
help: 'V8 heap in use by a thread, as of the last collection (15s)',
labelNames: ['type', 'thread']
}),
threadHeapTotal: new promClient.Gauge({
name: 'thread_heap_total_bytes',
help: 'V8 heap allocated by a thread, as of the last collection (15s)',
labelNames: ['type', 'thread']
}),
licenseDaysRemaining: new promClient.Gauge({
name: 'license_days_remaining',
help: 'Days until license expires (-1 for lifetime, 0 for no license)'
}),
emailengineConfig: new promClient.Gauge({
name: 'emailengine_config',
help: 'Configuration values',
labelNames: ['version', 'config']
}),
redisVersion: new promClient.Gauge({
name: 'redis_version',
help: 'Redis version',
labelNames: ['version']
}),
redisUptimeInSeconds: new promClient.Gauge({
name: 'redis_uptime_in_seconds',
help: 'Redis uptime in seconds'
}),
redisPing: new promClient.Gauge({
name: 'redis_latency',
help: 'Redis latency in nanoseconds'
}),
redisRejectedConnectionsTotal: new promClient.Gauge({
name: 'redis_rejected_connections_total',
help: 'Number of connections rejected by Redis'
}),
redisConfigMaxclients: new promClient.Gauge({
name: 'redis_config_maxclients',
help: 'Maximum client number for Redis'
}),
redisConnectedClients: new promClient.Gauge({
name: 'redis_connected_clients',
help: 'Number of client connections for Redis'
}),
redisSlowlogLength: new promClient.Gauge({
name: 'redis_slowlog_length',
help: 'Number of of entries in the Redis slow log'
}),
redisCommandsDurationSecondsTotal: new promClient.Gauge({
name: 'redis_commands_duration_seconds_total',
help: 'How many seconds spend on processing Redis commands'
}),
redisCommandsProcessedTotal: new promClient.Gauge({
name: 'redis_commands_processed_total',
help: 'How many commands processed by Redis'
}),
redisKeyspaceHitsTotal: new promClient.Gauge({
name: 'redis_keyspace_hits_total',
help: 'Number of successful lookup of keys in Redis'
}),
redisKeyspaceMissesTotal: new promClient.Gauge({
name: 'redis_keyspace_misses_total',
help: 'Number of failed lookup of keys in Redis'
}),
redisEvictedKeysTotal: new promClient.Gauge({
name: 'redis_evicted_keys_total',
help: 'Number of evicted keys due to maxmemory limit in Redis'
}),
redisMemoryUsedBytes: new promClient.Gauge({
name: 'redis_memory_used_bytes',
help: 'Total number of bytes allocated by Redis using its allocator'
}),
redisMemoryMaxBytes: new promClient.Gauge({
name: 'redis_memory_max_bytes',
help: 'The value of the Redis maxmemory configuration directive'
}),
redisMemFragmentationRatio: new promClient.Gauge({
name: 'redis_mem_fragmentation_ratio',
help: 'Ratio between used_memory_rss and used_memory in Redis'
}),
redisKeyCount: new promClient.Gauge({
name: 'redis_key_count',
help: 'Redis key counts',
labelNames: ['db']
}),
redisLastSaveTime: new promClient.Gauge({
name: 'redis_last_save_time',
help: 'Unix timestamp of the last RDB save time'
}),
redisOpsPerSec: new promClient.Gauge({
name: 'redis_instantaneous_ops_per_sec',
help: 'Throughput operations per second'
}),
redisCommandRuns: new promClient.Gauge({
name: 'redis_command_runs',
help: 'Redis command counts',
labelNames: ['command']
}),
redisCommandRunsFailed: new promClient.Gauge({
name: 'redis_command_runs_fail',
help: 'Redis command counts',
labelNames: ['command', 'status']
})
};
// Inter-thread communication tracking
let callQueue = new Map(); // Tracks pending cross-thread calls
let mids = 0; // Message ID counter
// Application state flags
let isClosing = false; // Is the application shutting down?
let assigning = false; // Is account assignment in progress?
// Unassign calls in flight at once while rebalanceOnto() holds the assignment lock
const REBALANCE_CONCURRENCY = 8;
// Account assignment tracking
let unassigned = false; // Set of unassigned accounts
let assigned = new Map(); // Map of account -> worker
let workerAssigned = new WeakMap(); // Map of worker -> Set of accounts
let onlineWorkers = new WeakSet(); // Set of workers that are online
let reassignmentTimer = null; // Timer for failsafe reassignment
let reassignmentPending = false; // Flag to track if reassignment is pending
const REASSIGNMENT_FAILSAFE_DELAY = 10 * 1000; // How long an exited IMAP worker gets to restart before its accounts move
let assignRetryCount = 0; // Counter for safety-net retries in assignAccounts
let assignRetryTimer = null; // The pending safety-net retry, so passes do not stack them
// Worker management
let imapInitialWorkersLoaded = false; // Have all initial IMAP workers started?
let workers = new Map(); // Map of type -> Set of workers
const respawnTracker = new RespawnTracker(); // paces respawns for worker slots that keep crashing
let spawnSlotCounter = 0; // source of respawn slot ids, see spawnWorker()
// Shutdown drain budget. A worker with no in-flight job answers immediately, so this only costs
// real time when there is genuinely something to finish - which is exactly when waiting is worth
// it, because the alternative is a re-sent message. Kept under Docker's 10s default SIGKILL grace
// so the drain completes rather than being cut halfway.
const SHUTDOWN_DRAIN_TIMEOUT = 8000;
const WORKER_DRAIN_TIMEOUT = 7000;
let workersMeta = new WeakMap(); // Worker metadata
let availableIMAPWorkers = new Set(); // IMAP workers ready to accept accounts
// Worker health monitoring
let workerHeartbeats = new WeakMap(); // Map of worker -> last heartbeat timestamp
let workerHealthStatus = new WeakMap(); // Map of worker -> health status
const HEARTBEAT_TIMEOUT = 30 * 1000; // 30 seconds before marking unhealthy
const HEARTBEAT_RESTART_TIMEOUT = 60 * 1000; // 60 seconds before auto-restart
// Suspended worker types (when no license is active)
let suspendedWorkerTypes = new Set();
/**
* Send a message to a worker thread with safety checks
* @param {Worker} worker - The worker thread to send to
* @param {Object} payload - Message payload
* @param {boolean} ignoreOffline - Whether to ignore offline status
* @param {Array} transferList - Transferable objects
* @returns {boolean} Success status
* @throws {Error} If worker is offline and ignoreOffline is false
*/
const postMessage = (worker, payload, ignoreOffline, transferList) => {
// Check if worker is online
if (!onlineWorkers.has(worker)) {
if (ignoreOffline) {
return false;
}
throw new Error('Worker thread is not available');
}
// Send the message
let result = worker.postMessage(payload, transferList);
// Update worker metadata
let workerMeta = workersMeta.has(worker) ? workersMeta.get(worker) : {};
workerMeta.called = workerMeta.called ? ++workerMeta.called : 1;
workersMeta.set(worker, workerMeta);
return result;
};
/**
* Update server state in Redis and notify API workers
* @param {string} type - Server type ('smtp' or 'imapProxy')
* @param {string} state - New state
* @param {Object} payload - Optional payload data
* @returns {Promise<void>}
*/
let updateServerState = async (type, state, payload) => {
// Store state in Redis
await redis.hset(`${REDIS_PREFIX}${type}`, 'state', state);
if (payload) {
await redis.hset(`${REDIS_PREFIX}${type}`, 'payload', JSON.stringify(payload));
}
// Notify all API workers about the state change
if (workers.has('api')) {
for (let worker of workers.get('api')) {
let callPayload = {
cmd: 'change',
type: `${type}ServerState`,
key: state,
payload: payload || null
};
try {
postMessage(worker, callPayload, true);
} catch (err) {
logger.error({ msg: 'Unable to notify worker about state change', worker: worker.threadId, callPayload, err });
}
}
}
};
/**
* updateServerState() as a report: never rejects. The listener state is what the admin UI shows,
* and a write Redis refuses (OOM, READONLY) must neither keep a worker from starting nor reach
* the global handler from a call nobody awaits
* @param {string} type - Server type ('smtp' or 'imapProxy')
* @param {string} state - New state
* @param {Object} [payload] - Optional payload data
* @returns {Promise<void>}
*/
const reportServerState = (type, state, payload) =>
updateServerState(type, state, payload).catch(err => logger.error({ msg: 'Unable to update server state', type, state, err }));
/**
* Get detailed information about all threads
* @returns {Promise<Array>} Array of thread information objects
*/
async function getThreadsInfo() {
// Use metrics collector if available
if (metricsCollector) {
let threadsInfo = await metricsCollector.getThreadsInfo();
// Add human-readable descriptions and configuration info
threadsInfo.forEach(threadInfo => {
threadInfo.description = THREAD_NAMES[threadInfo.type];
if (THREAD_CONFIG_VALUES[threadInfo.type]) {
threadInfo.config = THREAD_CONFIG_VALUES[threadInfo.type];
}
});
return threadsInfo;
}
// Fallback to original implementation if collector not initialized
// This should only happen during startup or if collector fails
// Start with main thread info
let threadsInfo = [Object.assign({ type: 'main', isMain: true, threadId: 0, online: NOW }, threadStats.usage())];
// Define a short timeout for unresponsive workers (500ms)
const WORKER_STATS_TIMEOUT = 500;
// Collect info from all worker threads with timeout handling
const workerPromises = [];
const workerMetadata = [];
for (let [type, workerSet] of workers) {
if (workerSet && workerSet.size) {
for (let worker of workerSet) {
// Store metadata for later processing
workerMetadata.push({ type, worker });