emailengine-app 2.88.0 → 2.90.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 +36 -45
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +58 -0
- package/Dockerfile +5 -1
- package/bin/healthcheck.js +1 -1
- package/copy-static-files.sh +0 -8
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +1 -4
- package/lib/account/field-codec.js +396 -0
- package/lib/account.js +158 -453
- package/lib/api-routes/account-routes.js +42 -6
- package/lib/api-routes/route-metadata.js +5 -2
- package/lib/api-routes/submit-routes.js +15 -2
- package/lib/api-token-auth.js +342 -274
- package/lib/arf-detect.js +174 -149
- package/lib/attachment-size.js +29 -0
- package/lib/autodetect-imap-settings.js +83 -234
- package/lib/consts.js +1 -5
- package/lib/db.js +1 -4
- package/lib/email-client/base-client.js +907 -780
- package/lib/email-client/gmail-client.js +557 -450
- package/lib/email-client/imap/cid-parts.js +61 -0
- package/lib/email-client/imap/mailbox.js +376 -422
- package/lib/email-client/imap/sync-operations.js +239 -178
- package/lib/email-client/new-message-steps.js +168 -2
- package/lib/email-client/outlook/graph-message.js +266 -0
- package/lib/email-client/outlook/subscription-expiry.js +30 -0
- package/lib/email-client/outlook-client.js +652 -808
- package/lib/get-raw-email.js +338 -232
- package/lib/get-secret.js +1 -4
- package/lib/license-subscription.js +77 -11
- package/lib/load-env.js +48 -0
- package/lib/logger.js +1 -4
- package/lib/mcp/tools.js +244 -207
- package/lib/metric-values.js +76 -0
- package/lib/metrics.js +320 -0
- package/lib/node-version.js +99 -12
- package/lib/oauth/gmail.js +39 -120
- package/lib/oauth/http-request.js +195 -0
- package/lib/oauth/mail-ru.js +24 -58
- package/lib/oauth/outlook.js +37 -137
- package/lib/oauth/pubsub/google.js +176 -117
- package/lib/oauth2-apps.js +440 -463
- package/lib/openapi/build-document.js +10 -10
- package/lib/read-env-value.js +1 -1
- package/lib/route-descriptors.js +78 -0
- package/lib/schemas.js +10 -1
- package/lib/sentry-integrations.js +299 -0
- package/lib/sentry.js +75 -27
- package/lib/settings.js +4 -1
- package/lib/sso-routes.js +249 -0
- package/lib/sso.js +29 -6
- package/lib/tools.js +5 -4
- package/lib/ui-routes/account-edit-form.js +198 -0
- package/lib/ui-routes/account-page.js +241 -0
- package/lib/ui-routes/account-routes.js +12 -318
- package/lib/ui-routes/auth-routes.js +10 -10
- package/lib/ui-routes/dashboard-routes.js +4 -0
- package/lib/ui-view-context.js +328 -0
- package/lib/utils/public-suffix.js +22 -101
- package/lib/web-safe-html.js +70 -13
- package/lib/worker-metrics.js +82 -0
- package/list-generate.js +57 -23
- package/package.json +34 -33
- package/sbom.json +380 -1612
- package/scripts/refresh-test-tokens.js +1 -1
- package/server.js +351 -707
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +18 -0
- package/static/js/ee-client.js +2619 -645
- package/static/js/ui.js +12 -2
- package/static/licenses.html +1055 -969
- package/translations/messages.pot +71 -60
- package/views/accounts/browse.hbs +19 -1
- package/views/dashboard.hbs +9 -0
- package/views/upgrade.hbs +25 -0
- package/workers/api.js +20 -451
- package/data/public_suffix_list.dat +0 -16597
- package/lib/net-tos-guard.js +0 -42
package/server.js
CHANGED
|
@@ -8,7 +8,6 @@
|
|
|
8
8
|
* proxy servers (SMTP, IMAP).
|
|
9
9
|
*
|
|
10
10
|
* @module server
|
|
11
|
-
* @requires dotenv
|
|
12
11
|
* @requires worker_threads
|
|
13
12
|
* @requires @zone-eu/wild-config
|
|
14
13
|
* @see {@link https://emailengine.app}
|
|
@@ -31,11 +30,8 @@ try {
|
|
|
31
30
|
// ignore - may fail in some containerized environments
|
|
32
31
|
}
|
|
33
32
|
|
|
34
|
-
// Load
|
|
35
|
-
|
|
36
|
-
require('dotenv').config({ quiet: true });
|
|
37
|
-
process.env.EE_ENV_LOADED = 'true';
|
|
38
|
-
}
|
|
33
|
+
// Load .env into process.env, if not already loaded
|
|
34
|
+
require('./lib/load-env').loadEnvOnce();
|
|
39
35
|
|
|
40
36
|
// Set process title for easier identification in process lists
|
|
41
37
|
process.title = 'emailengine';
|
|
@@ -50,28 +46,25 @@ try {
|
|
|
50
46
|
process.exit(1);
|
|
51
47
|
}
|
|
52
48
|
|
|
53
|
-
//
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
|
|
57
|
-
|
|
49
|
+
// Checked before anything else is required. Below MIN_NODE undici, which every thread loads at
|
|
50
|
+
// startup, throws when it is loaded, so an older runtime gets this message and the commands to fix it
|
|
51
|
+
// instead of a TypeError from inside a dependency. A one-click DigitalOcean droplet upgrades
|
|
52
|
+
// EmailEngine on its own but not the Node.js it runs on, and that log line is all its operator sees.
|
|
53
|
+
// A release that starts but is outside the supported range is only warned about here and on the
|
|
54
|
+
// dashboard (see lib/node-version.js for the two thresholds).
|
|
55
|
+
const { MIN_NODE, SUPPORTED_RANGE_LABEL, nodeSupport, nodeUpgradeHint } = require('./lib/node-version');
|
|
56
|
+
const nodeSupportLevel = nodeSupport(process.versions.node);
|
|
57
|
+
if (nodeSupportLevel === 'unsupported') {
|
|
58
|
+
console.error(`EmailEngine requires Node.js ${MIN_NODE} or newer, this is Node.js ${process.version}.\n\n${nodeUpgradeHint()}`);
|
|
58
59
|
process.exit(1);
|
|
59
60
|
}
|
|
61
|
+
if (nodeSupportLevel === 'outside-range') {
|
|
62
|
+
console.error(`Node.js ${process.version} is outside the range EmailEngine supports (${SUPPORTED_RANGE_LABEL}). It runs, but please upgrade Node.js.`);
|
|
63
|
+
}
|
|
60
64
|
|
|
61
|
-
// Within Node 20 the dependency tree itself asks for 20.19.0 (html-to-text 10, the entities release
|
|
62
|
-
// node-html-parser pulls in) or 20.18.1 (undici 7), which is what the engines field declares. npm
|
|
63
|
-
// treats that field as advice, and an older 20.x starts and then fails somewhere in a dependency at
|
|
64
|
-
// runtime, so it is named here. Only a warning: one-click DigitalOcean images upgrade EmailEngine on
|
|
65
|
-
// their own but not the Node they run on, and an instance that works today must not stop at its next
|
|
66
|
-
// self-upgrade over a minor version it may never exercise.
|
|
67
65
|
const { accountDataKey } = require('./lib/redis-keys');
|
|
66
|
+
const { resolveMetricKeys, statBuckets } = require('./lib/worker-metrics');
|
|
68
67
|
const { importPreparedPassword } = require('./lib/prepared-password');
|
|
69
|
-
const { MIN_SUPPORTED_NODE, isBelowSupportedNode } = require('./lib/node-version');
|
|
70
|
-
if (isBelowSupportedNode(process.versions.node)) {
|
|
71
|
-
console.error(
|
|
72
|
-
`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.`
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
68
|
|
|
76
69
|
const os = require('os');
|
|
77
70
|
|
|
@@ -117,9 +110,6 @@ const MetricsCollector = require('./lib/metrics-collector');
|
|
|
117
110
|
// Import constants
|
|
118
111
|
const {
|
|
119
112
|
MAX_DAYS_STATS,
|
|
120
|
-
MESSAGE_NEW_NOTIFY,
|
|
121
|
-
MESSAGE_DELETED_NOTIFY,
|
|
122
|
-
CONNECT_ERROR_NOTIFY,
|
|
123
113
|
REDIS_PREFIX,
|
|
124
114
|
ACCOUNT_ADDED_NOTIFY,
|
|
125
115
|
ACCOUNT_DELETED_NOTIFY,
|
|
@@ -151,10 +141,9 @@ const { pruneFailedContent } = require('./lib/outbox');
|
|
|
151
141
|
const { queueCleanAges } = require('./lib/queue-retention');
|
|
152
142
|
const { getFailedJobRetention } = require('./lib/env-setting-overrides');
|
|
153
143
|
const { packRpcError, unpackRpcError } = require('./lib/worker-rpc-error');
|
|
154
|
-
const promClient = require('
|
|
144
|
+
const { promClient, setupMetrics, connectionCounts } = require('./lib/metrics');
|
|
155
145
|
const fs = require('fs').promises;
|
|
156
146
|
const crypto = require('crypto');
|
|
157
|
-
const { compareVersions, parseVersion } = require('./lib/utils/version');
|
|
158
147
|
const Joi = require('joi');
|
|
159
148
|
const { settingsSchema } = require('./lib/schemas');
|
|
160
149
|
const settings = require('./lib/settings');
|
|
@@ -166,11 +155,14 @@ const { attachBeacon, persistBeaconMarkers } = require('./lib/license-beacon');
|
|
|
166
155
|
const {
|
|
167
156
|
decide,
|
|
168
157
|
startupPlan,
|
|
169
|
-
|
|
158
|
+
needsVersionRecheck,
|
|
159
|
+
subscriptionCheckState,
|
|
160
|
+
workerSuspensionChange,
|
|
170
161
|
checkInterval,
|
|
171
162
|
subscriptionView,
|
|
172
163
|
parseSuspension,
|
|
173
|
-
isSubscriptionLicense
|
|
164
|
+
isSubscriptionLicense,
|
|
165
|
+
toTime
|
|
174
166
|
} = require('./lib/license-subscription');
|
|
175
167
|
const tokens = require('./lib/tokens');
|
|
176
168
|
|
|
@@ -194,6 +186,7 @@ const { mapConcurrent } = require('./lib/utils/map-concurrent');
|
|
|
194
186
|
const { RespawnTracker, retryWithBackoff } = require('./lib/respawn-backoff');
|
|
195
187
|
const { legacySmtpOptionsInUse, REMOVAL_DATE } = require('./lib/deprecations');
|
|
196
188
|
const { heartbeatDiagnostics, eventLoopDelaySeries, threadHeapSeries } = require('./lib/thread-diagnostics');
|
|
189
|
+
const { licenseDaysRemaining, countThreads } = require('./lib/metric-values');
|
|
197
190
|
|
|
198
191
|
const msgpack = require('./lib/msgpack');
|
|
199
192
|
|
|
@@ -571,290 +564,8 @@ if (preparedPasswordString) {
|
|
|
571
564
|
}
|
|
572
565
|
}
|
|
573
566
|
|
|
574
|
-
//
|
|
575
|
-
const
|
|
576
|
-
collectDefaultMetrics({});
|
|
577
|
-
|
|
578
|
-
/**
|
|
579
|
-
* Prometheus metrics definitions for monitoring
|
|
580
|
-
* @const {Object}
|
|
581
|
-
*/
|
|
582
|
-
const metrics = {
|
|
583
|
-
threadStarts: new promClient.Counter({
|
|
584
|
-
name: 'thread_starts',
|
|
585
|
-
help: 'Number of started threads'
|
|
586
|
-
}),
|
|
587
|
-
|
|
588
|
-
threadStops: new promClient.Counter({
|
|
589
|
-
name: 'thread_stops',
|
|
590
|
-
help: 'Number of stopped threads'
|
|
591
|
-
}),
|
|
592
|
-
|
|
593
|
-
apiCall: new promClient.Counter({
|
|
594
|
-
name: 'api_call',
|
|
595
|
-
help: 'Number of API calls',
|
|
596
|
-
labelNames: ['method', 'statusCode', 'route']
|
|
597
|
-
}),
|
|
598
|
-
|
|
599
|
-
// Labelled by route, not by status: the counter above already splits by status, and a latency
|
|
600
|
-
// series per status code would multiply the route count for little an operator can act on
|
|
601
|
-
apiCallDuration: new promClient.Histogram({
|
|
602
|
-
name: 'api_call_duration_seconds',
|
|
603
|
-
help: 'Duration of API calls, from receiving the request to sending the response',
|
|
604
|
-
labelNames: ['method', 'route'],
|
|
605
|
-
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60]
|
|
606
|
-
}),
|
|
607
|
-
|
|
608
|
-
imapConnections: new promClient.Gauge({
|
|
609
|
-
name: 'imap_connections',
|
|
610
|
-
help: 'Current IMAP connection state',
|
|
611
|
-
labelNames: ['status']
|
|
612
|
-
}),
|
|
613
|
-
|
|
614
|
-
imapResponses: new promClient.Counter({
|
|
615
|
-
name: 'imap_responses',
|
|
616
|
-
help: 'IMAP responses',
|
|
617
|
-
labelNames: ['response', 'code']
|
|
618
|
-
}),
|
|
619
|
-
|
|
620
|
-
imapBytesSent: new promClient.Counter({
|
|
621
|
-
name: 'imap_bytes_sent',
|
|
622
|
-
help: 'IMAP bytes sent'
|
|
623
|
-
}),
|
|
624
|
-
|
|
625
|
-
imapBytesReceived: new promClient.Counter({
|
|
626
|
-
name: 'imap_bytes_received',
|
|
627
|
-
help: 'IMAP bytes received'
|
|
628
|
-
}),
|
|
629
|
-
|
|
630
|
-
oauth2TokenRefresh: new promClient.Counter({
|
|
631
|
-
name: 'oauth2_token_refresh',
|
|
632
|
-
help: 'OAuth2 access token refresh attempts',
|
|
633
|
-
labelNames: ['status', 'provider', 'statusCode']
|
|
634
|
-
}),
|
|
635
|
-
|
|
636
|
-
oauth2ApiRequest: new promClient.Counter({
|
|
637
|
-
name: 'oauth2_api_request',
|
|
638
|
-
help: 'OAuth2 API requests (MS Graph, Gmail API)',
|
|
639
|
-
labelNames: ['status', 'provider', 'statusCode']
|
|
640
|
-
}),
|
|
641
|
-
|
|
642
|
-
outlookMissedRecovery: new promClient.Counter({
|
|
643
|
-
name: 'outlook_missed_recovery',
|
|
644
|
-
help: 'MS Graph missed-notification recovery passes, by what asked for them and whether they found unannounced messages',
|
|
645
|
-
labelNames: ['reason', 'outcome']
|
|
646
|
-
}),
|
|
647
|
-
|
|
648
|
-
outlookMissedRecoveredMessages: new promClient.Counter({
|
|
649
|
-
name: 'outlook_missed_recovered_messages',
|
|
650
|
-
help: 'New messages announced by MS Graph missed-notification recovery instead of by a change notification',
|
|
651
|
-
labelNames: ['reason']
|
|
652
|
-
}),
|
|
653
|
-
|
|
654
|
-
outlookSubscriptions: new promClient.Gauge({
|
|
655
|
-
name: 'outlook_subscriptions',
|
|
656
|
-
help: 'MS Graph webhook subscription states',
|
|
657
|
-
labelNames: ['status']
|
|
658
|
-
}),
|
|
659
|
-
|
|
660
|
-
webhooks: new promClient.Counter({
|
|
661
|
-
name: 'webhooks',
|
|
662
|
-
help: 'Webhooks sent',
|
|
663
|
-
labelNames: ['status', 'event']
|
|
664
|
-
}),
|
|
665
|
-
|
|
666
|
-
events: new promClient.Counter({
|
|
667
|
-
name: 'events',
|
|
668
|
-
help: 'Events fired',
|
|
669
|
-
labelNames: ['event']
|
|
670
|
-
}),
|
|
671
|
-
|
|
672
|
-
aiRequests: new promClient.Counter({
|
|
673
|
-
name: 'ai_requests',
|
|
674
|
-
help: 'AI summary requests',
|
|
675
|
-
labelNames: ['model', 'status']
|
|
676
|
-
}),
|
|
677
|
-
|
|
678
|
-
aiTokens: new promClient.Counter({
|
|
679
|
-
name: 'ai_tokens',
|
|
680
|
-
help: 'Tokens billed for AI summary requests',
|
|
681
|
-
labelNames: ['model', 'type']
|
|
682
|
-
}),
|
|
683
|
-
|
|
684
|
-
webhookReq: new promClient.Histogram({
|
|
685
|
-
name: 'webhook_req',
|
|
686
|
-
help: 'Duration of webhook requests',
|
|
687
|
-
buckets: [100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000, 60 * 1000]
|
|
688
|
-
}),
|
|
689
|
-
|
|
690
|
-
queues: new promClient.Gauge({
|
|
691
|
-
name: 'queue_size',
|
|
692
|
-
help: 'Queue size',
|
|
693
|
-
labelNames: ['queue', 'state']
|
|
694
|
-
}),
|
|
695
|
-
|
|
696
|
-
queueFailed: new promClient.Gauge({
|
|
697
|
-
name: 'queue_failed_jobs',
|
|
698
|
-
help: 'Failed jobs a queue still retains (deliveries that were given up on)',
|
|
699
|
-
labelNames: ['queue']
|
|
700
|
-
}),
|
|
701
|
-
|
|
702
|
-
queuesProcessed: new promClient.Counter({
|
|
703
|
-
name: 'queues_processed',
|
|
704
|
-
help: 'Processed job count',
|
|
705
|
-
labelNames: ['queue', 'status']
|
|
706
|
-
}),
|
|
707
|
-
|
|
708
|
-
threads: new promClient.Gauge({
|
|
709
|
-
name: 'threads',
|
|
710
|
-
help: 'Worker Threads',
|
|
711
|
-
labelNames: ['type', 'recent']
|
|
712
|
-
}),
|
|
713
|
-
|
|
714
|
-
unresponsiveWorkers: new promClient.Gauge({
|
|
715
|
-
name: 'unresponsive_workers',
|
|
716
|
-
help: 'Number of unresponsive worker threads'
|
|
717
|
-
}),
|
|
718
|
-
|
|
719
|
-
threadEventLoopDelayMax: new promClient.Gauge({
|
|
720
|
-
name: 'thread_event_loop_delay_max_seconds',
|
|
721
|
-
help: 'Longest event loop delay of a thread over the last collection window (15s)',
|
|
722
|
-
labelNames: ['type', 'thread']
|
|
723
|
-
}),
|
|
724
|
-
|
|
725
|
-
threadEventLoopDelayP99: new promClient.Gauge({
|
|
726
|
-
name: 'thread_event_loop_delay_p99_seconds',
|
|
727
|
-
help: '99th percentile event loop delay of a thread over the last collection window (15s)',
|
|
728
|
-
labelNames: ['type', 'thread']
|
|
729
|
-
}),
|
|
730
|
-
|
|
731
|
-
threadHeapUsed: new promClient.Gauge({
|
|
732
|
-
name: 'thread_heap_used_bytes',
|
|
733
|
-
help: 'V8 heap in use by a thread, as of the last collection (15s)',
|
|
734
|
-
labelNames: ['type', 'thread']
|
|
735
|
-
}),
|
|
736
|
-
|
|
737
|
-
threadHeapTotal: new promClient.Gauge({
|
|
738
|
-
name: 'thread_heap_total_bytes',
|
|
739
|
-
help: 'V8 heap allocated by a thread, as of the last collection (15s)',
|
|
740
|
-
labelNames: ['type', 'thread']
|
|
741
|
-
}),
|
|
742
|
-
|
|
743
|
-
licenseDaysRemaining: new promClient.Gauge({
|
|
744
|
-
name: 'license_days_remaining',
|
|
745
|
-
help: 'Days until license expires (-1 for lifetime, 0 for no license)'
|
|
746
|
-
}),
|
|
747
|
-
|
|
748
|
-
emailengineConfig: new promClient.Gauge({
|
|
749
|
-
name: 'emailengine_config',
|
|
750
|
-
help: 'Configuration values',
|
|
751
|
-
labelNames: ['version', 'config']
|
|
752
|
-
}),
|
|
753
|
-
|
|
754
|
-
redisVersion: new promClient.Gauge({
|
|
755
|
-
name: 'redis_version',
|
|
756
|
-
help: 'Redis version',
|
|
757
|
-
labelNames: ['version']
|
|
758
|
-
}),
|
|
759
|
-
|
|
760
|
-
redisUptimeInSeconds: new promClient.Gauge({
|
|
761
|
-
name: 'redis_uptime_in_seconds',
|
|
762
|
-
help: 'Redis uptime in seconds'
|
|
763
|
-
}),
|
|
764
|
-
|
|
765
|
-
redisPing: new promClient.Gauge({
|
|
766
|
-
name: 'redis_latency',
|
|
767
|
-
help: 'Redis latency in nanoseconds'
|
|
768
|
-
}),
|
|
769
|
-
|
|
770
|
-
redisRejectedConnectionsTotal: new promClient.Gauge({
|
|
771
|
-
name: 'redis_rejected_connections_total',
|
|
772
|
-
help: 'Number of connections rejected by Redis'
|
|
773
|
-
}),
|
|
774
|
-
|
|
775
|
-
redisConfigMaxclients: new promClient.Gauge({
|
|
776
|
-
name: 'redis_config_maxclients',
|
|
777
|
-
help: 'Maximum client number for Redis'
|
|
778
|
-
}),
|
|
779
|
-
|
|
780
|
-
redisConnectedClients: new promClient.Gauge({
|
|
781
|
-
name: 'redis_connected_clients',
|
|
782
|
-
help: 'Number of client connections for Redis'
|
|
783
|
-
}),
|
|
784
|
-
|
|
785
|
-
redisSlowlogLength: new promClient.Gauge({
|
|
786
|
-
name: 'redis_slowlog_length',
|
|
787
|
-
help: 'Number of of entries in the Redis slow log'
|
|
788
|
-
}),
|
|
789
|
-
|
|
790
|
-
redisCommandsDurationSecondsTotal: new promClient.Gauge({
|
|
791
|
-
name: 'redis_commands_duration_seconds_total',
|
|
792
|
-
help: 'How many seconds spend on processing Redis commands'
|
|
793
|
-
}),
|
|
794
|
-
|
|
795
|
-
redisCommandsProcessedTotal: new promClient.Gauge({
|
|
796
|
-
name: 'redis_commands_processed_total',
|
|
797
|
-
help: 'How many commands processed by Redis'
|
|
798
|
-
}),
|
|
799
|
-
|
|
800
|
-
redisKeyspaceHitsTotal: new promClient.Gauge({
|
|
801
|
-
name: 'redis_keyspace_hits_total',
|
|
802
|
-
help: 'Number of successful lookup of keys in Redis'
|
|
803
|
-
}),
|
|
804
|
-
|
|
805
|
-
redisKeyspaceMissesTotal: new promClient.Gauge({
|
|
806
|
-
name: 'redis_keyspace_misses_total',
|
|
807
|
-
help: 'Number of failed lookup of keys in Redis'
|
|
808
|
-
}),
|
|
809
|
-
|
|
810
|
-
redisEvictedKeysTotal: new promClient.Gauge({
|
|
811
|
-
name: 'redis_evicted_keys_total',
|
|
812
|
-
help: 'Number of evicted keys due to maxmemory limit in Redis'
|
|
813
|
-
}),
|
|
814
|
-
|
|
815
|
-
redisMemoryUsedBytes: new promClient.Gauge({
|
|
816
|
-
name: 'redis_memory_used_bytes',
|
|
817
|
-
help: 'Total number of bytes allocated by Redis using its allocator'
|
|
818
|
-
}),
|
|
819
|
-
|
|
820
|
-
redisMemoryMaxBytes: new promClient.Gauge({
|
|
821
|
-
name: 'redis_memory_max_bytes',
|
|
822
|
-
help: 'The value of the Redis maxmemory configuration directive'
|
|
823
|
-
}),
|
|
824
|
-
|
|
825
|
-
redisMemFragmentationRatio: new promClient.Gauge({
|
|
826
|
-
name: 'redis_mem_fragmentation_ratio',
|
|
827
|
-
help: 'Ratio between used_memory_rss and used_memory in Redis'
|
|
828
|
-
}),
|
|
829
|
-
|
|
830
|
-
redisKeyCount: new promClient.Gauge({
|
|
831
|
-
name: 'redis_key_count',
|
|
832
|
-
help: 'Redis key counts',
|
|
833
|
-
labelNames: ['db']
|
|
834
|
-
}),
|
|
835
|
-
|
|
836
|
-
redisLastSaveTime: new promClient.Gauge({
|
|
837
|
-
name: 'redis_last_save_time',
|
|
838
|
-
help: 'Unix timestamp of the last RDB save time'
|
|
839
|
-
}),
|
|
840
|
-
|
|
841
|
-
redisOpsPerSec: new promClient.Gauge({
|
|
842
|
-
name: 'redis_instantaneous_ops_per_sec',
|
|
843
|
-
help: 'Throughput operations per second'
|
|
844
|
-
}),
|
|
845
|
-
|
|
846
|
-
redisCommandRuns: new promClient.Gauge({
|
|
847
|
-
name: 'redis_command_runs',
|
|
848
|
-
help: 'Redis command counts',
|
|
849
|
-
labelNames: ['command']
|
|
850
|
-
}),
|
|
851
|
-
|
|
852
|
-
redisCommandRunsFailed: new promClient.Gauge({
|
|
853
|
-
name: 'redis_command_runs_fail',
|
|
854
|
-
help: 'Redis command counts',
|
|
855
|
-
labelNames: ['command', 'status']
|
|
856
|
-
})
|
|
857
|
-
};
|
|
567
|
+
// Prometheus metrics (lib/metrics.js)
|
|
568
|
+
const metrics = setupMetrics();
|
|
858
569
|
|
|
859
570
|
// Inter-thread communication tracking
|
|
860
571
|
let callQueue = new Map(); // Tracks pending cross-thread calls
|
|
@@ -1471,6 +1182,28 @@ let spawnWorker = async (type, opts, slot) => {
|
|
|
1471
1182
|
});
|
|
1472
1183
|
});
|
|
1473
1184
|
|
|
1185
|
+
// The worker is up and accepts work: an IMAP worker becomes available for accounts, and
|
|
1186
|
+
// the spawn resolves. The two IMAP checks are apart on purpose: the worker joins the set
|
|
1187
|
+
// before the spawn resolves, and the reassignment runs after it
|
|
1188
|
+
const onWorkerReady = () => {
|
|
1189
|
+
if (type === 'imap') {
|
|
1190
|
+
// IMAP worker is ready to accept accounts
|
|
1191
|
+
availableIMAPWorkers.add(worker);
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
isOnline = true;
|
|
1195
|
+
|
|
1196
|
+
// Initialize heartbeat tracking
|
|
1197
|
+
workerHeartbeats.set(worker, Date.now());
|
|
1198
|
+
workerHealthStatus.set(worker, 'healthy');
|
|
1199
|
+
|
|
1200
|
+
resolve(worker.threadId);
|
|
1201
|
+
|
|
1202
|
+
if (type === 'imap') {
|
|
1203
|
+
onImapWorkerReady(worker);
|
|
1204
|
+
}
|
|
1205
|
+
};
|
|
1206
|
+
|
|
1474
1207
|
// Handle messages from worker
|
|
1475
1208
|
worker.on('message', message => {
|
|
1476
1209
|
// Update message count
|
|
@@ -1482,333 +1215,290 @@ let spawnWorker = async (type, opts, slot) => {
|
|
|
1482
1215
|
return;
|
|
1483
1216
|
}
|
|
1484
1217
|
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1218
|
+
switch (message.cmd) {
|
|
1219
|
+
// Handle heartbeat from worker
|
|
1220
|
+
case 'heartbeat':
|
|
1221
|
+
handleWorkerHeartbeat(worker);
|
|
1222
|
+
return;
|
|
1490
1223
|
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
return reject(unpackRpcError(message));
|
|
1498
|
-
} else {
|
|
1499
|
-
return resolve(message.response);
|
|
1500
|
-
}
|
|
1501
|
-
}
|
|
1224
|
+
// Handle response to a call; one nobody waits for anymore (timed out) is dropped
|
|
1225
|
+
case 'resp':
|
|
1226
|
+
if (message.mid && callQueue.has(message.mid)) {
|
|
1227
|
+
handleRpcResponse(message);
|
|
1228
|
+
}
|
|
1229
|
+
return;
|
|
1502
1230
|
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
if (response && typeof response === 'object' && response._transfer === true) {
|
|
1510
|
-
if (typeof response._response === 'object' && response._response && response._response.buffer) {
|
|
1511
|
-
transferList = [response._response.buffer];
|
|
1512
|
-
}
|
|
1513
|
-
response = response._response;
|
|
1514
|
-
}
|
|
1231
|
+
// Handle call from worker
|
|
1232
|
+
case 'call':
|
|
1233
|
+
if (message.mid) {
|
|
1234
|
+
handleRpcCall(worker, message);
|
|
1235
|
+
}
|
|
1236
|
+
return;
|
|
1515
1237
|
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
response
|
|
1520
|
-
};
|
|
1238
|
+
case 'metrics':
|
|
1239
|
+
recordWorkerMetrics(type, message);
|
|
1240
|
+
return;
|
|
1521
1241
|
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
// Log buffer info instead of full buffer
|
|
1526
|
-
if (Buffer.isBuffer(callPayload.response)) {
|
|
1527
|
-
callPayload.response = `Buffer <${callPayload.response.length}B>`;
|
|
1528
|
-
}
|
|
1242
|
+
case 'settings':
|
|
1243
|
+
forwardSettings(message);
|
|
1244
|
+
return;
|
|
1529
1245
|
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
.catch(err => {
|
|
1534
|
-
let callPayload = Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err));
|
|
1246
|
+
case 'change':
|
|
1247
|
+
forwardStateChange(message);
|
|
1248
|
+
return;
|
|
1535
1249
|
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
logger.error({ msg: 'Unable to send error response to worker', worker: worker.threadId, callPayload, err });
|
|
1540
|
-
}
|
|
1541
|
-
});
|
|
1250
|
+
case 'ready':
|
|
1251
|
+
onWorkerReady();
|
|
1252
|
+
return;
|
|
1542
1253
|
}
|
|
1254
|
+
});
|
|
1255
|
+
});
|
|
1256
|
+
};
|
|
1543
1257
|
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
}
|
|
1258
|
+
/**
|
|
1259
|
+
* Settles the pending call() a worker answered
|
|
1260
|
+
* @param {Object} message - `resp` message carrying the call's `mid`
|
|
1261
|
+
*/
|
|
1262
|
+
function handleRpcResponse(message) {
|
|
1263
|
+
let { resolve, reject, timer } = callQueue.get(message.mid);
|
|
1264
|
+
clearTimeout(timer);
|
|
1265
|
+
callQueue.delete(message.mid);
|
|
1266
|
+
if (message.error) {
|
|
1267
|
+
reject(unpackRpcError(message));
|
|
1268
|
+
} else {
|
|
1269
|
+
resolve(message.response);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1559
1272
|
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1273
|
+
/**
|
|
1274
|
+
* Runs a command a worker asked the main thread for and posts the answer back
|
|
1275
|
+
* @param {Worker} worker - The calling worker
|
|
1276
|
+
* @param {Object} message - `call` message carrying the command and its `mid`
|
|
1277
|
+
*/
|
|
1278
|
+
function handleRpcCall(worker, message) {
|
|
1279
|
+
onCommand(worker, message.message)
|
|
1280
|
+
.then(response => {
|
|
1281
|
+
let transferList;
|
|
1282
|
+
// Handle transferable objects
|
|
1283
|
+
if (response && typeof response === 'object' && response._transfer === true) {
|
|
1284
|
+
if (typeof response._response === 'object' && response._response && response._response.buffer) {
|
|
1285
|
+
transferList = [response._response.buffer];
|
|
1286
|
+
}
|
|
1287
|
+
response = response._response;
|
|
1288
|
+
}
|
|
1563
1289
|
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1290
|
+
let callPayload = {
|
|
1291
|
+
cmd: 'resp',
|
|
1292
|
+
mid: message.mid,
|
|
1293
|
+
response
|
|
1294
|
+
};
|
|
1569
1295
|
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
}
|
|
1578
|
-
break;
|
|
1579
|
-
}
|
|
1296
|
+
try {
|
|
1297
|
+
postMessage(worker, callPayload, null, transferList);
|
|
1298
|
+
} catch (err) {
|
|
1299
|
+
// Log buffer info instead of full buffer
|
|
1300
|
+
if (Buffer.isBuffer(callPayload.response)) {
|
|
1301
|
+
callPayload.response = `Buffer <${callPayload.response.length}B>`;
|
|
1302
|
+
}
|
|
1580
1303
|
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
try {
|
|
1587
|
-
metrics.apiCallDuration.observe({ method, route }, message.duration);
|
|
1588
|
-
} catch (err) {
|
|
1589
|
-
logger.error({ msg: 'Unable to apply worker metric', type, key: 'apiCallDuration', err });
|
|
1590
|
-
}
|
|
1591
|
-
}
|
|
1592
|
-
break;
|
|
1593
|
-
}
|
|
1304
|
+
logger.error({ msg: 'Unable to send response to worker', worker: worker.threadId, callPayload, err });
|
|
1305
|
+
}
|
|
1306
|
+
})
|
|
1307
|
+
.catch(err => {
|
|
1308
|
+
let callPayload = Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err));
|
|
1594
1309
|
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
}
|
|
1310
|
+
try {
|
|
1311
|
+
postMessage(worker, callPayload);
|
|
1312
|
+
} catch (err) {
|
|
1313
|
+
logger.error({ msg: 'Unable to send error response to worker', worker: worker.threadId, callPayload, err });
|
|
1314
|
+
}
|
|
1315
|
+
});
|
|
1316
|
+
}
|
|
1603
1317
|
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
.substr(0, 10)
|
|
1612
|
-
.replace(/[^0-9]+/g, '')}`;
|
|
1613
|
-
|
|
1614
|
-
// Create minute bucket
|
|
1615
|
-
let timeStr = `${now
|
|
1616
|
-
.toISOString()
|
|
1617
|
-
.substr(0, 16)
|
|
1618
|
-
.replace(/[^0-9]+/g, '')}`;
|
|
1619
|
-
|
|
1620
|
-
let hkey = `${REDIS_PREFIX}stats:${statUpdateKey}:${dateStr}`;
|
|
1621
|
-
|
|
1622
|
-
let update = redis
|
|
1623
|
-
.multi()
|
|
1624
|
-
.hincrby(hkey, timeStr, 1)
|
|
1625
|
-
.sadd(`${REDIS_PREFIX}stats:keys`, statUpdateKey)
|
|
1626
|
-
.expire(hkey, (MAX_DAYS_STATS + 1) * 24 * 3600); // Keep for configured days + 1
|
|
1627
|
-
|
|
1628
|
-
if (account && accountUpdateKey) {
|
|
1629
|
-
// Update account-specific counter
|
|
1630
|
-
let accountKey = accountDataKey(account);
|
|
1631
|
-
update = update.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1);
|
|
1632
|
-
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Applies a worker's `metrics` message: the dashboard counters in Redis and the Prometheus metric
|
|
1320
|
+
* @param {String} type - Type of the reporting worker
|
|
1321
|
+
* @param {Object} message - `metrics` message
|
|
1322
|
+
*/
|
|
1323
|
+
function recordWorkerMetrics(type, message) {
|
|
1324
|
+
let { account, statUpdateKey, accountUpdateKey } = resolveMetricKeys(message);
|
|
1633
1325
|
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1326
|
+
if (message.key === 'apiCall' && typeof message.duration === 'number' && Number.isFinite(message.duration)) {
|
|
1327
|
+
let { method, route } = message.args[0] || {};
|
|
1328
|
+
try {
|
|
1329
|
+
metrics.apiCallDuration.observe({ method, route }, message.duration);
|
|
1330
|
+
} catch (err) {
|
|
1331
|
+
logger.error({ msg: 'Unable to apply worker metric', type, key: 'apiCallDuration', err });
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1640
1334
|
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
// down with it.
|
|
1645
|
-
if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
|
|
1646
|
-
try {
|
|
1647
|
-
metrics[message.key][message.method](...message.args);
|
|
1648
|
-
} catch (err) {
|
|
1649
|
-
logger.error({ msg: 'Unable to apply worker metric', type, key: message.key, method: message.method, err });
|
|
1650
|
-
}
|
|
1651
|
-
}
|
|
1335
|
+
// Update Redis counters for dashboard stats
|
|
1336
|
+
if (statUpdateKey) {
|
|
1337
|
+
let { dateStr, timeStr } = statBuckets(new Date());
|
|
1652
1338
|
|
|
1653
|
-
|
|
1654
|
-
}
|
|
1339
|
+
let hkey = `${REDIS_PREFIX}stats:${statUpdateKey}:${dateStr}`;
|
|
1655
1340
|
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1341
|
+
let update = redis
|
|
1342
|
+
.multi()
|
|
1343
|
+
.hincrby(hkey, timeStr, 1)
|
|
1344
|
+
.sadd(`${REDIS_PREFIX}stats:keys`, statUpdateKey)
|
|
1345
|
+
.expire(hkey, (MAX_DAYS_STATS + 1) * 24 * 3600); // Keep for configured days + 1
|
|
1659
1346
|
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
logger.error({
|
|
1666
|
-
msg: 'Unable to forward settings to worker',
|
|
1667
|
-
worker: worker.threadId,
|
|
1668
|
-
settingsKeys: Object.keys(message.data || {}),
|
|
1669
|
-
err
|
|
1670
|
-
});
|
|
1671
|
-
}
|
|
1672
|
-
});
|
|
1347
|
+
if (account && accountUpdateKey) {
|
|
1348
|
+
// Update account-specific counter
|
|
1349
|
+
let accountKey = accountDataKey(account);
|
|
1350
|
+
update = update.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1);
|
|
1351
|
+
}
|
|
1673
1352
|
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
typeWorkers.forEach(worker => {
|
|
1681
|
-
try {
|
|
1682
|
-
postMessage(worker, message);
|
|
1683
|
-
} catch (err) {
|
|
1684
|
-
logger.error({ msg: 'Unable to forward settings to worker', type, worker: worker.threadId, err });
|
|
1685
|
-
}
|
|
1686
|
-
});
|
|
1687
|
-
}
|
|
1688
|
-
return;
|
|
1353
|
+
update.exec().catch(() => false);
|
|
1354
|
+
} else if (account && accountUpdateKey) {
|
|
1355
|
+
// Update only account-specific counter
|
|
1356
|
+
let accountKey = accountDataKey(account);
|
|
1357
|
+
redis.hIncrbyExists(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
|
|
1358
|
+
}
|
|
1689
1359
|
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
try {
|
|
1703
|
-
postMessage(worker, message, true);
|
|
1704
|
-
} catch (err) {
|
|
1705
|
-
logger.error({ msg: 'Unable to forward state change to worker', worker: worker.threadId, callPayload: message, err });
|
|
1706
|
-
}
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
break;
|
|
1710
|
-
}
|
|
1360
|
+
// Update Prometheus metrics. The Prometheus client throws synchronously on an unknown
|
|
1361
|
+
// label, a negative counter increment or a non-finite value, and this runs in
|
|
1362
|
+
// an event handler on the main thread, where a throw would take every worker
|
|
1363
|
+
// down with it.
|
|
1364
|
+
if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
|
|
1365
|
+
try {
|
|
1366
|
+
metrics[message.key][message.method](...message.args);
|
|
1367
|
+
} catch (err) {
|
|
1368
|
+
logger.error({ msg: 'Unable to apply worker metric', type, key: message.key, method: message.method, err });
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1711
1372
|
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
// Initialize heartbeat tracking
|
|
1721
|
-
workerHeartbeats.set(worker, Date.now());
|
|
1722
|
-
workerHealthStatus.set(worker, 'healthy');
|
|
1723
|
-
|
|
1724
|
-
resolve(worker.threadId);
|
|
1725
|
-
|
|
1726
|
-
logger.info({
|
|
1727
|
-
msg: 'IMAP worker ready',
|
|
1728
|
-
threadId: worker.threadId,
|
|
1729
|
-
currentWorkers: availableIMAPWorkers.size,
|
|
1730
|
-
expectedWorkers: config.workers.imap,
|
|
1731
|
-
unassignedCount: unassigned ? unassigned.size : 0,
|
|
1732
|
-
assignedCount: assigned.size,
|
|
1733
|
-
imapInitialWorkersLoaded,
|
|
1734
|
-
reassignmentPending
|
|
1735
|
-
});
|
|
1373
|
+
/**
|
|
1374
|
+
* Applies a settings change in the main thread and forwards it to every worker
|
|
1375
|
+
* @param {Object} message - `settings` message
|
|
1376
|
+
*/
|
|
1377
|
+
function forwardSettings(message) {
|
|
1378
|
+
// Reload the HTTP proxy agent in the main thread when proxy settings change
|
|
1379
|
+
maybeReloadHttpProxyAgent(message.data);
|
|
1736
1380
|
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
msg: 'All expected workers ready, reassigning unassigned accounts',
|
|
1751
|
-
workers: availableIMAPWorkers.size,
|
|
1752
|
-
unassigned: unassigned.size
|
|
1753
|
-
});
|
|
1754
|
-
assignAccounts().catch(err => logger.error({ msg: 'Unable to assign accounts', err }));
|
|
1755
|
-
} else {
|
|
1756
|
-
logger.warn({
|
|
1757
|
-
msg: 'All workers ready but no unassigned accounts found',
|
|
1758
|
-
workers: availableIMAPWorkers.size
|
|
1759
|
-
});
|
|
1760
|
-
}
|
|
1761
|
-
} else if (unassigned && unassigned.size > 0) {
|
|
1762
|
-
// Still waiting for more workers to restart
|
|
1763
|
-
logger.info({
|
|
1764
|
-
msg: 'Worker ready, waiting for all workers before reassignment',
|
|
1765
|
-
currentWorkers: availableIMAPWorkers.size,
|
|
1766
|
-
expectedWorkers: config.workers.imap,
|
|
1767
|
-
unassignedAccounts: unassigned.size
|
|
1768
|
-
});
|
|
1769
|
-
// The failsafe found no worker at all and stopped; give the rest
|
|
1770
|
-
// of the fleet the same time to come back from here
|
|
1771
|
-
if (!reassignmentTimer) {
|
|
1772
|
-
armReassignmentFailsafe();
|
|
1773
|
-
}
|
|
1774
|
-
}
|
|
1775
|
-
} else if (imapInitialWorkersLoaded) {
|
|
1776
|
-
// The failsafe timer already gave this worker's accounts to the
|
|
1777
|
-
// survivors (or it is an extra worker), so nothing is pending for it
|
|
1778
|
-
rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err }));
|
|
1779
|
-
}
|
|
1780
|
-
}
|
|
1781
|
-
break;
|
|
1381
|
+
// Forward settings changes to all IMAP workers
|
|
1382
|
+
availableIMAPWorkers.forEach(worker => {
|
|
1383
|
+
try {
|
|
1384
|
+
postMessage(worker, message);
|
|
1385
|
+
} catch (err) {
|
|
1386
|
+
logger.error({
|
|
1387
|
+
msg: 'Unable to forward settings to worker',
|
|
1388
|
+
worker: worker.threadId,
|
|
1389
|
+
settingsKeys: Object.keys(message.data || {}),
|
|
1390
|
+
err
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
});
|
|
1782
1394
|
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1395
|
+
// Forward settings changes to every other worker type (the IMAP workers were
|
|
1396
|
+
// handled above); each reloads its HTTP proxy agent from the 'settings' message
|
|
1397
|
+
for (let [type, typeWorkers] of workers) {
|
|
1398
|
+
if (type === 'imap') {
|
|
1399
|
+
continue;
|
|
1400
|
+
}
|
|
1401
|
+
typeWorkers.forEach(worker => {
|
|
1402
|
+
try {
|
|
1403
|
+
postMessage(worker, message);
|
|
1404
|
+
} catch (err) {
|
|
1405
|
+
logger.error({ msg: 'Unable to forward settings to worker', type, worker: worker.threadId, err });
|
|
1406
|
+
}
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1787
1410
|
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1411
|
+
/**
|
|
1412
|
+
* Handles a state change: a listener's own state is recorded here, everything else goes to the
|
|
1413
|
+
* API workers
|
|
1414
|
+
* @param {Object} message - `change` message
|
|
1415
|
+
*/
|
|
1416
|
+
function forwardStateChange(message) {
|
|
1417
|
+
switch (message.type) {
|
|
1418
|
+
case 'smtpServerState':
|
|
1419
|
+
case 'imapProxyServerState': {
|
|
1420
|
+
let serverType = message.type.replace(/ServerState$/, '');
|
|
1421
|
+
reportServerState(serverType, message.key, message.payload);
|
|
1422
|
+
break;
|
|
1423
|
+
}
|
|
1424
|
+
default:
|
|
1425
|
+
// Forward all other state changes to API workers
|
|
1426
|
+
for (let worker of workers.get('api') || []) {
|
|
1427
|
+
try {
|
|
1428
|
+
postMessage(worker, message, true);
|
|
1429
|
+
} catch (err) {
|
|
1430
|
+
logger.error({ msg: 'Unable to forward state change to worker', worker: worker.threadId, callPayload: message, err });
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1791
1435
|
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1436
|
+
/**
|
|
1437
|
+
* An IMAP worker came up: once the initial set has loaded, hand it the accounts waiting for a
|
|
1438
|
+
* worker, or rebalance onto it
|
|
1439
|
+
* @param {Worker} worker - The IMAP worker that is now available
|
|
1440
|
+
*/
|
|
1441
|
+
function onImapWorkerReady(worker) {
|
|
1442
|
+
logger.info({
|
|
1443
|
+
msg: 'IMAP worker ready',
|
|
1444
|
+
threadId: worker.threadId,
|
|
1445
|
+
currentWorkers: availableIMAPWorkers.size,
|
|
1446
|
+
expectedWorkers: config.workers.imap,
|
|
1447
|
+
unassignedCount: unassigned ? unassigned.size : 0,
|
|
1448
|
+
assignedCount: assigned.size,
|
|
1449
|
+
imapInitialWorkersLoaded,
|
|
1450
|
+
reassignmentPending
|
|
1451
|
+
});
|
|
1795
1452
|
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
isOnline = true;
|
|
1453
|
+
if (!imapInitialWorkersLoaded) {
|
|
1454
|
+
return;
|
|
1455
|
+
}
|
|
1800
1456
|
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1457
|
+
if (!reassignmentPending) {
|
|
1458
|
+
// The failsafe timer already gave this worker's accounts to the
|
|
1459
|
+
// survivors (or it is an extra worker), so nothing is pending for it
|
|
1460
|
+
rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err }));
|
|
1461
|
+
return;
|
|
1462
|
+
}
|
|
1804
1463
|
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1464
|
+
// Check if we now have the expected number of workers
|
|
1465
|
+
// This handles the case where a worker crashed and restarted
|
|
1466
|
+
if (availableIMAPWorkers.size === config.workers.imap) {
|
|
1467
|
+
// All workers are back - clear timer and reassign
|
|
1468
|
+
if (reassignmentTimer) {
|
|
1469
|
+
clearTimeout(reassignmentTimer);
|
|
1470
|
+
reassignmentTimer = null;
|
|
1471
|
+
}
|
|
1472
|
+
reassignmentPending = false;
|
|
1473
|
+
|
|
1474
|
+
if (unassigned && unassigned.size > 0) {
|
|
1475
|
+
logger.info({
|
|
1476
|
+
msg: 'All expected workers ready, reassigning unassigned accounts',
|
|
1477
|
+
workers: availableIMAPWorkers.size,
|
|
1478
|
+
unassigned: unassigned.size
|
|
1479
|
+
});
|
|
1480
|
+
assignAccounts().catch(err => logger.error({ msg: 'Unable to assign accounts', err }));
|
|
1481
|
+
} else {
|
|
1482
|
+
logger.warn({
|
|
1483
|
+
msg: 'All workers ready but no unassigned accounts found',
|
|
1484
|
+
workers: availableIMAPWorkers.size
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
} else if (unassigned && unassigned.size > 0) {
|
|
1488
|
+
// Still waiting for more workers to restart
|
|
1489
|
+
logger.info({
|
|
1490
|
+
msg: 'Worker ready, waiting for all workers before reassignment',
|
|
1491
|
+
currentWorkers: availableIMAPWorkers.size,
|
|
1492
|
+
expectedWorkers: config.workers.imap,
|
|
1493
|
+
unassignedAccounts: unassigned.size
|
|
1809
1494
|
});
|
|
1810
|
-
|
|
1811
|
-
|
|
1495
|
+
// The failsafe found no worker at all and stopped; give the rest
|
|
1496
|
+
// of the fleet the same time to come back from here
|
|
1497
|
+
if (!reassignmentTimer) {
|
|
1498
|
+
armReassignmentFailsafe();
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1812
1502
|
|
|
1813
1503
|
/**
|
|
1814
1504
|
* Call a command on a worker thread and wait for response
|
|
@@ -2188,6 +1878,18 @@ const setSuspension = suspension => {
|
|
|
2188
1878
|
}
|
|
2189
1879
|
};
|
|
2190
1880
|
|
|
1881
|
+
/**
|
|
1882
|
+
* Forgets the registered license in this thread, after settings.removeLicense()
|
|
1883
|
+
* @returns {void}
|
|
1884
|
+
*/
|
|
1885
|
+
const clearLicenseInfo = () => {
|
|
1886
|
+
licenseInfo.active = false;
|
|
1887
|
+
licenseInfo.details = false;
|
|
1888
|
+
delete licenseInfo.suspension;
|
|
1889
|
+
subscriptionDeadline = null;
|
|
1890
|
+
licenseInfo.type = packageData.license;
|
|
1891
|
+
};
|
|
1892
|
+
|
|
2191
1893
|
/**
|
|
2192
1894
|
* Applies one decision of lib/license-subscription.js to the stored state and to licenseInfo
|
|
2193
1895
|
* @param {Object} decision - decide() output
|
|
@@ -2201,11 +1903,7 @@ const applySubscriptionDecision = async (decision, data) => {
|
|
|
2201
1903
|
// what a license server that names no deadline and does not ask to keep the key gets
|
|
2202
1904
|
logger.warn({ msg: 'License validation failed', license: redactLicense(licenseInfo.details), data });
|
|
2203
1905
|
await settings.removeLicense();
|
|
2204
|
-
|
|
2205
|
-
licenseInfo.active = false;
|
|
2206
|
-
licenseInfo.details = false;
|
|
2207
|
-
delete licenseInfo.suspension;
|
|
2208
|
-
licenseInfo.type = packageData.license;
|
|
1906
|
+
clearLicenseInfo();
|
|
2209
1907
|
return;
|
|
2210
1908
|
}
|
|
2211
1909
|
|
|
@@ -2284,21 +1982,7 @@ let licenseCheckHandler = async opts => {
|
|
|
2284
1982
|
let subscriptionCheckTimeout = opts.subscriptionCheckTimeout || checkInterval({ subexp, subsusp });
|
|
2285
1983
|
|
|
2286
1984
|
// Check if we need to validate the license
|
|
2287
|
-
let checkKv =
|
|
2288
|
-
// an unreadable record means checking again, which also rewrites it
|
|
2289
|
-
let validatedVersion = kv && typeof kv === 'string' ? Buffer.from(kv, 'hex').toString() : null;
|
|
2290
|
-
if (parseVersion(validatedVersion) && compareVersions(packageData.version, validatedVersion) <= 0) {
|
|
2291
|
-
checkKv = false;
|
|
2292
|
-
}
|
|
2293
|
-
|
|
2294
|
-
if (ks && typeof ks === 'string') {
|
|
2295
|
-
let ksDate = new Date(parseInt(ks, 16));
|
|
2296
|
-
if (ksDate < now) {
|
|
2297
|
-
checkKv = true;
|
|
2298
|
-
}
|
|
2299
|
-
} else {
|
|
2300
|
-
checkKv = true;
|
|
2301
|
-
}
|
|
1985
|
+
let checkKv = needsVersionRecheck({ kv, ks, version: packageData.version, now });
|
|
2302
1986
|
|
|
2303
1987
|
// Clean up for lifetime licenses
|
|
2304
1988
|
if (licenseInfo.details && licenseInfo.details.lt) {
|
|
@@ -2306,15 +1990,12 @@ let licenseCheckHandler = async opts => {
|
|
|
2306
1990
|
subscriptionDeadline = null;
|
|
2307
1991
|
}
|
|
2308
1992
|
|
|
2309
|
-
// A suspended license is still registered and still checked, which is how it resumes
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
// A stored deadline that has passed suspends on its own, whether or not the license server
|
|
1993
|
+
// A suspended license is still registered and still checked, which is how it resumes. A
|
|
1994
|
+
// stored deadline that has passed suspends on its own, whether or not the license server
|
|
2313
1995
|
// can be reached to say so; its next answer decides what happens after that
|
|
2314
|
-
let localSuspension =
|
|
1996
|
+
let { subscriptionLicense, localSuspension } = subscriptionCheckState(licenseInfo, { subexp, subsusp, now });
|
|
2315
1997
|
if (localSuspension) {
|
|
2316
1998
|
await redis.hset(`${REDIS_PREFIX}settings`, 'subsusp', JSON.stringify(localSuspension));
|
|
2317
|
-
subsusp = JSON.stringify(localSuspension);
|
|
2318
1999
|
logger.warn({
|
|
2319
2000
|
msg: 'Subscription deadline passed, suspending until the license server says otherwise',
|
|
2320
2001
|
license: redactLicense(licenseInfo.details)
|
|
@@ -2387,7 +2068,8 @@ let licenseCheckHandler = async opts => {
|
|
|
2387
2068
|
}
|
|
2388
2069
|
|
|
2389
2070
|
// Handle no active license - suspend workers
|
|
2390
|
-
|
|
2071
|
+
let workerChange = workerSuspensionChange(licenseInfo.active, suspendedWorkerTypes.size);
|
|
2072
|
+
if (workerChange === 'suspend') {
|
|
2391
2073
|
// Said in the present tense, because that is what the loop below does. The line used to
|
|
2392
2074
|
// promise a 15 minute grace period that nothing anywhere implements, so an operator
|
|
2393
2075
|
// reading it waited for a window that had already closed.
|
|
@@ -2402,7 +2084,7 @@ let licenseCheckHandler = async opts => {
|
|
|
2402
2084
|
}
|
|
2403
2085
|
}
|
|
2404
2086
|
}
|
|
2405
|
-
} else if (
|
|
2087
|
+
} else if (workerChange === 'resume') {
|
|
2406
2088
|
// Re-enable workers after license activated
|
|
2407
2089
|
for (let type of suspendedWorkerTypes) {
|
|
2408
2090
|
suspendedWorkerTypes.delete(type);
|
|
@@ -2612,39 +2294,29 @@ function checkRedisPing() {
|
|
|
2612
2294
|
* @returns {Promise<void>}
|
|
2613
2295
|
*/
|
|
2614
2296
|
async function updateQueueCounters() {
|
|
2615
|
-
|
|
2297
|
+
setConfigMetrics();
|
|
2298
|
+
await setThreadMetrics();
|
|
2299
|
+
await setQueueMetrics();
|
|
2300
|
+
await setRedisMetrics();
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
// EmailEngine configuration and license metrics
|
|
2304
|
+
function setConfigMetrics() {
|
|
2616
2305
|
metrics.emailengineConfig.set({ version: 'v' + packageData.version }, 1);
|
|
2617
2306
|
metrics.emailengineConfig.set({ config: 'uvThreadpoolSize' }, Number(process.env.UV_THREADPOOL_SIZE));
|
|
2618
2307
|
metrics.emailengineConfig.set({ config: 'workersImap' }, config.workers.imap);
|
|
2619
2308
|
metrics.emailengineConfig.set({ config: 'workersWebhooks' }, config.workers.webhooks);
|
|
2620
2309
|
metrics.emailengineConfig.set({ config: 'workersSubmission' }, config.workers.submit);
|
|
2621
2310
|
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
if (licenseInfo.details.lt) {
|
|
2625
|
-
// Lifetime license
|
|
2626
|
-
metrics.licenseDaysRemaining.set(-1);
|
|
2627
|
-
} else if (licenseInfo.details.expires) {
|
|
2628
|
-
// Time-limited license
|
|
2629
|
-
let expiresAt = new Date(licenseInfo.details.expires).getTime();
|
|
2630
|
-
let daysRemaining = Math.max(0, Math.ceil((expiresAt - Date.now()) / (24 * 60 * 60 * 1000)));
|
|
2631
|
-
metrics.licenseDaysRemaining.set(daysRemaining);
|
|
2632
|
-
} else {
|
|
2633
|
-
// Subscription license (no fixed expiry)
|
|
2634
|
-
metrics.licenseDaysRemaining.set(-1);
|
|
2635
|
-
}
|
|
2636
|
-
} else {
|
|
2637
|
-
// No active license
|
|
2638
|
-
metrics.licenseDaysRemaining.set(0);
|
|
2639
|
-
}
|
|
2311
|
+
metrics.licenseDaysRemaining.set(licenseDaysRemaining(licenseInfo, Date.now()));
|
|
2312
|
+
}
|
|
2640
2313
|
|
|
2641
|
-
|
|
2314
|
+
// Worker thread metrics
|
|
2315
|
+
async function setThreadMetrics() {
|
|
2642
2316
|
let threadsInfo = await getThreadsInfo();
|
|
2643
2317
|
|
|
2644
2318
|
let now = Date.now();
|
|
2645
2319
|
|
|
2646
|
-
let threadCounts = new Map();
|
|
2647
|
-
let unresponsiveCount = 0;
|
|
2648
2320
|
// a replaced thread leaves with its thread id, so the series are rebuilt on every update
|
|
2649
2321
|
metrics.threadEventLoopDelayMax.reset();
|
|
2650
2322
|
metrics.threadEventLoopDelayP99.reset();
|
|
@@ -2658,27 +2330,8 @@ async function updateQueueCounters() {
|
|
|
2658
2330
|
metrics.threadHeapUsed.set(labels, used);
|
|
2659
2331
|
metrics.threadHeapTotal.set(labels, total);
|
|
2660
2332
|
}
|
|
2661
|
-
for (let workerThreadInfo of threadsInfo || []) {
|
|
2662
|
-
let key = workerThreadInfo.type;
|
|
2663
|
-
let metricKey = `${key}_total`;
|
|
2664
|
-
|
|
2665
|
-
// Check if thread is recent (started within METRIC_RECENT)
|
|
2666
|
-
let recent = now - workerThreadInfo.online < METRIC_RECENT;
|
|
2667
|
-
if (recent) {
|
|
2668
|
-
metricKey = `${key}_recent`;
|
|
2669
|
-
}
|
|
2670
|
-
|
|
2671
|
-
if (!threadCounts.has(metricKey)) {
|
|
2672
|
-
threadCounts.set(metricKey, 1);
|
|
2673
|
-
} else {
|
|
2674
|
-
threadCounts.set(metricKey, threadCounts.get(metricKey) + 1);
|
|
2675
|
-
}
|
|
2676
2333
|
|
|
2677
|
-
|
|
2678
|
-
if (workerThreadInfo.resourceUsageError && workerThreadInfo.resourceUsageError.unresponsive) {
|
|
2679
|
-
unresponsiveCount++;
|
|
2680
|
-
}
|
|
2681
|
-
}
|
|
2334
|
+
let { threadCounts, unresponsiveCount } = countThreads(threadsInfo, now, METRIC_RECENT);
|
|
2682
2335
|
|
|
2683
2336
|
// Set thread count metrics
|
|
2684
2337
|
for (let [key, value] of threadCounts.entries()) {
|
|
@@ -2688,15 +2341,17 @@ async function updateQueueCounters() {
|
|
|
2688
2341
|
|
|
2689
2342
|
// Set unresponsive workers metric
|
|
2690
2343
|
metrics.unresponsiveWorkers.set(unresponsiveCount);
|
|
2344
|
+
}
|
|
2691
2345
|
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2346
|
+
// Queue metrics, through BullMQ's own API (lib/queue-stats.js). Counting raw llen/zcard against
|
|
2347
|
+
// BullMQ's private key layout broke silently in the 5.x -> 6.x bump: the `:paused` list no longer
|
|
2348
|
+
// exists (a paused queue holds its jobs in `wait`), and a leftover `0:` wait-list marker from a
|
|
2349
|
+
// 5.x install counts as a phantom waiting job. The `paused` gauge is kept at the 0 the getter
|
|
2350
|
+
// reports so existing dashboards keep their series.
|
|
2351
|
+
//
|
|
2352
|
+
// A queue whose count fails is skipped rather than ending the update: returning here used to
|
|
2353
|
+
// leave every Redis gauge below it stale for as long as that one count kept failing.
|
|
2354
|
+
async function setQueueMetrics() {
|
|
2700
2355
|
const counted = [
|
|
2701
2356
|
['notify', notifyQueue],
|
|
2702
2357
|
['submit', submitQueue],
|
|
@@ -2716,8 +2371,10 @@ async function updateQueueCounters() {
|
|
|
2716
2371
|
metrics.queues.set({ queue: `${queue}`, state: `waiting` }, stats.waiting);
|
|
2717
2372
|
metrics.queueFailed.set({ queue: `${queue}` }, stats.failed);
|
|
2718
2373
|
});
|
|
2374
|
+
}
|
|
2719
2375
|
|
|
2720
|
-
|
|
2376
|
+
// Redis metrics
|
|
2377
|
+
async function setRedisMetrics() {
|
|
2721
2378
|
try {
|
|
2722
2379
|
let redisInfo = await getRedisStats(redis);
|
|
2723
2380
|
|
|
@@ -2869,16 +2526,7 @@ async function commandMetrics() {
|
|
|
2869
2526
|
|
|
2870
2527
|
async function commandStructuredMetrics() {
|
|
2871
2528
|
// Return structured metrics for API
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
for (let key of Object.keys(metrics.imapConnections.hashMap)) {
|
|
2875
|
-
if (key.indexOf('status:') === 0) {
|
|
2876
|
-
let metric = metrics.imapConnections.hashMap[key];
|
|
2877
|
-
connections[metric.labels.status] = metric.value;
|
|
2878
|
-
}
|
|
2879
|
-
}
|
|
2880
|
-
|
|
2881
|
-
return { connections, redisPing: await getRedisPing() };
|
|
2529
|
+
return { connections: await connectionCounts(metrics.imapConnections), redisPing: await getRedisPing() };
|
|
2882
2530
|
}
|
|
2883
2531
|
|
|
2884
2532
|
async function commandImapWorkerCount() {
|
|
@@ -2942,7 +2590,7 @@ async function commandUpdateLicense(worker, message) {
|
|
|
2942
2590
|
// the workers start, and the answer decides
|
|
2943
2591
|
let subscriptionLicense = isSubscriptionLicense(licenseData);
|
|
2944
2592
|
let [subexp, subsusp] = await redis.hmget(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp');
|
|
2945
|
-
subscriptionDeadline = subscriptionLicense
|
|
2593
|
+
subscriptionDeadline = subscriptionLicense ? toTime(subexp) : null;
|
|
2946
2594
|
setSuspension(subscriptionLicense ? parseSuspension(subsusp) : null);
|
|
2947
2595
|
|
|
2948
2596
|
if (!subscriptionLicense || (await licenseCheckHandler({ force: true })).outcome === 'busy') {
|
|
@@ -2963,11 +2611,7 @@ async function commandRemoveLicense() {
|
|
|
2963
2611
|
try {
|
|
2964
2612
|
await settings.removeLicense();
|
|
2965
2613
|
|
|
2966
|
-
|
|
2967
|
-
licenseInfo.details = false;
|
|
2968
|
-
delete licenseInfo.suspension;
|
|
2969
|
-
subscriptionDeadline = null;
|
|
2970
|
-
licenseInfo.type = packageData.license;
|
|
2614
|
+
clearLicenseInfo();
|
|
2971
2615
|
notifyApiLicenseState();
|
|
2972
2616
|
|
|
2973
2617
|
return licenseInfo;
|
|
@@ -3667,7 +3311,7 @@ const loadStoredLicense = async () => {
|
|
|
3667
3311
|
*/
|
|
3668
3312
|
const applyStartupSubscriptionState = async () => {
|
|
3669
3313
|
let [subexp, subsusp, subcheck] = await redis.hmget(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp', 'subcheck');
|
|
3670
|
-
subscriptionDeadline =
|
|
3314
|
+
subscriptionDeadline = toTime(subexp);
|
|
3671
3315
|
let plan = startupPlan({ details: licenseInfo.active && licenseInfo.details, subexp, subsusp, subcheck, now: Date.now() });
|
|
3672
3316
|
|
|
3673
3317
|
if (plan.suspension) {
|