forked from postalsys/emailengine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3193 lines (2710 loc) · 112 KB
/
server.js
File metadata and controls
3193 lines (2710 loc) · 112 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 wild-config
* @see {@link https://emailengine.app}
*/
// Load environment variables if not already loaded
if (!process.env.EE_ENV_LOADED) {
require('dotenv').config({ quiet: true });
process.env.EE_ENV_LOADED = 'true';
}
// Attempt to change working directory to script location
try {
process.chdir(__dirname);
} catch (err) {
// ignore - may fail in some containerized environments
}
// Set process title for easier identification in process lists
process.title = 'emailengine';
// Ensure Node.js version supports structuredClone (Node 17+)
try {
structuredClone(true);
} catch (err) {
console.error(`Node.js version ${process.version} is not supported. Please upgrade to Node.js 17 or later.`);
process.exit(1);
}
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);
// Cache command line arguments before 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('wild-config');
const logger = require('./lib/logger');
// Import utility functions
const {
readEnvValue,
hasEnvValue,
download,
getDuration,
getByteSize,
getBoolean,
getWorkerCount,
selectRendezvousNode,
checkLicense,
checkForUpgrade,
setLicense,
getRedisStats,
threadStats,
retryAgent
} = 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
} = require('./lib/consts');
// Import core modules
const { webhooks: Webhooks } = require('./lib/webhooks');
const {
generateSummary,
generateEmbeddings,
getChunkEmbeddings,
embeddingsQuery,
questionQuery,
listModels: openAiListModels,
DEFAULT_USER_PROMPT: openAiDefaultPrompt
} = require('@postalsys/email-ai-tools');
const { fetch: fetchCmd } = require('undici');
const v8 = require('node:v8');
// Initialize Bugsnag error tracking if API key is provided
const Bugsnag = require('@bugsnag/js');
if (readEnvValue('BUGSNAG_API_KEY')) {
Bugsnag.start({
apiKey: readEnvValue('BUGSNAG_API_KEY'),
appVersion: packageData.version,
logger: {
debug(...args) {
logger.debug({ msg: args.shift(), worker: 'main', source: 'bugsnag', args: args.length ? args : undefined });
},
info(...args) {
logger.debug({ msg: args.shift(), worker: 'main', source: 'bugsnag', args: args.length ? args : undefined });
},
warn(...args) {
logger.warn({ msg: args.shift(), worker: 'main', source: 'bugsnag', args: args.length ? args : undefined });
},
error(...args) {
logger.error({ msg: args.shift(), worker: 'main', source: 'bugsnag', args: args.length ? args : undefined });
}
}
});
logger.notifyError = Bugsnag.notify.bind(Bugsnag);
}
// Import additional dependencies
const pathlib = require('path');
const { redis, queueConf } = require('./lib/db');
const promClient = require('prom-client');
const fs = require('fs').promises;
const crypto = require('crypto');
const { compare: cv } = require('compare-versions');
const Joi = require('joi');
const { settingsSchema } = require('./lib/schemas');
const settings = require('./lib/settings');
const tokens = require('./lib/tokens');
const { checkRateLimit } = require('./lib/rate-limit');
const { QueueEvents } = require('bullmq');
const getSecret = require('./lib/get-secret');
const msgpack = require('msgpack5')();
// 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 = getWorkerCount(readEnvValue('EENGINE_WORKERS') || config.workers.imap) || 4;
config.workers.webhooks = Number(readEnvValue('EENGINE_WORKERS_WEBHOOKS')) || config.workers.webhooks || 1;
config.workers.submit = Number(readEnvValue('EENGINE_WORKERS_SUBMIT')) || config.workers.submit || 1;
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 (will be removed in future versions)
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);
// 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
});
// 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';
// 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
};
/**
* Human-readable thread type names for display
* @const {Object<string, string>}
*/
const THREAD_NAMES = {
main: 'Main thread',
imap: 'IMAP worker',
webhooks: 'Webhook worker',
api: 'HTTP and API server',
submit: 'Email sending worker',
documents: 'Document store indexing 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 },
submit: { key: 'EENGINE_WORKERS_SUBMIT', value: config.workers.submit },
webhooks: { key: 'EENGINE_WORKERS_WEBHOOKS', value: config.workers.webhooks }
};
// Queue event handlers for different job queues
const queueEvents = {};
// Unique run index for this server instance
let runIndex;
// Prepared configuration handling
let preparedSettings = false;
const preparedSettingsString = readEnvValue('EENGINE_SETTINGS') || config.settings;
if (preparedSettingsString) {
// Parse and validate pre-configured settings
try {
const { error, value } = Joi.object(settingsSchema).validate(JSON.parse(preparedSettingsString), {
abortEarly: false,
stripUnknown: true,
convert: true
});
if (error) {
throw error;
}
preparedSettings = value;
} catch (err) {
logger.error({ msg: 'Invalid settings configuration provided', input: preparedSettingsString, 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.error({ msg: 'Invalid API token provided', input: preparedTokenString, 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.error({ msg: 'Invalid password hash provided', input: preparedPasswordString, 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']
}),
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'
}),
webhooks: new promClient.Counter({
name: 'webhooks',
help: 'Webhooks sent',
labelNames: ['status', 'event']
}),
events: new promClient.Counter({
name: 'events',
help: 'Events fired',
labelNames: ['event']
}),
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']
}),
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']
}),
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?
// 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
// Worker management
let imapInitialWorkersLoaded = false; // Have all initial IMAP workers started?
let workers = new Map(); // Map of type -> Set of workers
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
// Circuit breaker for worker communication
let workerCircuitBreakers = new WeakMap(); // Map of worker -> circuit breaker state
const CIRCUIT_FAILURE_THRESHOLD = 3; // Open circuit after 3 failures
const CIRCUIT_RESET_TIMEOUT = 30 * 1000; // Try to close circuit after 30s
const CIRCUIT_HALF_OPEN_ATTEMPTS = 1; // Number of test requests in half-open state
// 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 });
}
}
}
};
/**
* 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 });
// Use built-in timeout parameter of call function
const workerPromise = call(worker, {
cmd: 'resource-usage',
timeout: WORKER_STATS_TIMEOUT
}).catch(err => ({
// Return error info instead of throwing
resourceUsageError: {
error: err.message,
code: err.code || 'TIMEOUT',
unresponsive: err.code === 'Timeout'
}
}));
workerPromises.push(workerPromise);
}
}
}
// Wait for all workers to respond or timeout using allSettled
const results = await Promise.allSettled(workerPromises);
// Process results
results.forEach((result, index) => {
const { type, worker } = workerMetadata[index];
const resourceUsage =
result.status === 'fulfilled'
? result.value
: {
resourceUsageError: {
error: result.reason?.message || 'Unknown error',
code: 'PROMISE_REJECTED',
unresponsive: true
}
};
let threadData = Object.assign(
{
type,
threadId: worker.threadId,
resourceLimits: worker.resourceLimits
},
resourceUsage
);
// Add account count for IMAP workers
if (workerAssigned.has(worker)) {
threadData.accounts = workerAssigned.get(worker).size;
}
// Add health status
threadData.healthStatus = workerHealthStatus.get(worker) || 'unknown';
const lastHeartbeat = workerHeartbeats.get(worker);
if (lastHeartbeat) {
threadData.lastHeartbeat = lastHeartbeat;
threadData.timeSinceHeartbeat = Date.now() - lastHeartbeat;
}
// Add circuit breaker status
const circuit = getCircuitBreaker(worker);
threadData.circuitState = circuit.state;
threadData.circuitFailures = circuit.failures;
// Add worker metadata
let workerMeta = workersMeta.has(worker) ? workersMeta.get(worker) : {};
for (let key of Object.keys(workerMeta)) {
threadData[key] = workerMeta[key];
}
threadsInfo.push(threadData);
});
// 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;
}
/**
* Handle heartbeat from worker thread
* @param {Worker} worker - The worker thread
*/
function handleWorkerHeartbeat(worker) {
const now = Date.now();
workerHeartbeats.set(worker, now);
// Mark as healthy if it was previously unhealthy
const previousStatus = workerHealthStatus.get(worker);
if (previousStatus === 'unhealthy' || previousStatus === 'critical') {
logger.info({
msg: 'Worker recovered',
threadId: worker.threadId,
type: workersMeta.get(worker)?.type
});
}
workerHealthStatus.set(worker, 'healthy');
}
/**
* Check health of all worker threads
* @returns {Promise<void>}
*/
async function checkWorkerHealth() {
const now = Date.now();
for (let [type, workerSet] of workers) {
for (let worker of workerSet) {
const lastHeartbeat = workerHeartbeats.get(worker);
const currentStatus = workerHealthStatus.get(worker) || 'unknown';
if (!lastHeartbeat) {
// No heartbeat recorded yet, skip
continue;
}
const timeSinceHeartbeat = now - lastHeartbeat;
if (timeSinceHeartbeat > HEARTBEAT_RESTART_TIMEOUT && currentStatus !== 'restarting') {
// Worker is critically unresponsive, restart it
logger.error({
msg: 'Worker critically unresponsive, restarting',
threadId: worker.threadId,
type,
timeSinceHeartbeat: Math.round(timeSinceHeartbeat / 1000) + 's'
});
workerHealthStatus.set(worker, 'restarting');
// Terminate the worker (this will trigger automatic restart)
try {
await worker.terminate();
} catch (err) {
logger.error({
msg: 'Failed to terminate unresponsive worker',
threadId: worker.threadId,
type,
err
});
}
} else if (timeSinceHeartbeat > HEARTBEAT_TIMEOUT && currentStatus === 'healthy') {
// Worker is unhealthy but not critical yet
logger.warn({
msg: 'Worker unhealthy - no heartbeat',
threadId: worker.threadId,
type,
timeSinceHeartbeat: Math.round(timeSinceHeartbeat / 1000) + 's'
});
workerHealthStatus.set(worker, 'unhealthy');
}
}
}
}
/**
* Start worker health monitoring
*/
function startHealthMonitoring() {
// Check worker health every 5 seconds
setInterval(() => {
checkWorkerHealth().catch(err => {
logger.error({ msg: 'Worker health check failed', err });
});
}, 5000);
}
/**
* Get or initialize circuit breaker state for a worker
* @param {Worker} worker - The worker thread
* @returns {Object} Circuit breaker state
*/
function getCircuitBreaker(worker) {
if (!workerCircuitBreakers.has(worker)) {
workerCircuitBreakers.set(worker, {
state: 'closed', // closed, open, half-open
failures: 0,
lastFailureTime: null,
lastAttemptTime: null,
halfOpenAttempts: 0
});
}
return workerCircuitBreakers.get(worker);
}
/**
* Record a successful call to a worker
* @param {Worker} worker - The worker thread
*/
function recordCircuitSuccess(worker) {
const circuit = getCircuitBreaker(worker);
if (circuit.state === 'half-open') {
// Successful call in half-open state, close the circuit
logger.info({
msg: 'Circuit breaker closed after successful test',
threadId: worker.threadId,
type: workersMeta.get(worker)?.type
});
}
// Reset circuit to closed state
circuit.state = 'closed';
circuit.failures = 0;
circuit.lastFailureTime = null;
circuit.halfOpenAttempts = 0;
}
/**
* Record a failed call to a worker
* @param {Worker} worker - The worker thread
*/
function recordCircuitFailure(worker) {
const circuit = getCircuitBreaker(worker);
const now = Date.now();
circuit.failures++;
circuit.lastFailureTime = now;
if (circuit.state === 'half-open') {
// Failed in half-open state, reopen the circuit
circuit.state = 'open';
circuit.halfOpenAttempts = 0;
logger.warn({
msg: 'Circuit breaker reopened after failed test',
threadId: worker.threadId,
type: workersMeta.get(worker)?.type
});
} else if (circuit.failures >= CIRCUIT_FAILURE_THRESHOLD && circuit.state === 'closed') {
// Threshold reached, open the circuit
circuit.state = 'open';
logger.warn({
msg: 'Circuit breaker opened due to failures',
threadId: worker.threadId,
type: workersMeta.get(worker)?.type,
failures: circuit.failures
});
}
}
/**
* Check if circuit breaker allows a call to the worker
* @param {Worker} worker - The worker thread
* @returns {boolean} Whether the call is allowed
*/
function isCircuitOpen(worker) {
const circuit = getCircuitBreaker(worker);
const now = Date.now();
if (circuit.state === 'closed') {
return false; // Circuit is closed, allow calls
}
if (circuit.state === 'open') {
// Check if enough time has passed to try half-open
if (now - circuit.lastFailureTime > CIRCUIT_RESET_TIMEOUT) {
circuit.state = 'half-open';
circuit.halfOpenAttempts = 0;
logger.info({
msg: 'Circuit breaker entering half-open state',
threadId: worker.threadId,
type: workersMeta.get(worker)?.type
});
return false; // Allow one test call
}
return true; // Circuit is open, block calls
}
if (circuit.state === 'half-open') {
// Allow limited attempts in half-open state
if (circuit.halfOpenAttempts < CIRCUIT_HALF_OPEN_ATTEMPTS) {
circuit.halfOpenAttempts++;
return false; // Allow test call
}
return true; // Block additional calls until test succeeds
}
return false;
}
/**
* Send a webhook notification
* @param {string} account - Account ID
* @param {string} event - Event type
* @param {Object} data - Event data
* @returns {Promise<void>}
*/
async function sendWebhook(account, event, data) {
let serviceUrl = (await settings.get('serviceUrl')) || null;
let payload = {
serviceUrl,
account,
date: new Date().toISOString()
};
if (event) {
payload.event = event;