emailengine-app 2.81.2 → 2.82.1
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 +33 -10
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +71 -0
- package/DOCKER_DEPLOYMENT.md +13 -12
- package/Dockerfile +2 -0
- package/bin/emailengine.js +105 -25
- package/config/default.toml +0 -5
- package/config/test.toml +0 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +70 -42
- package/getswagger.sh +0 -4
- package/lib/account/account-state.js +2 -110
- package/lib/account/expected-identity.js +1 -1
- package/lib/account-assignment.js +138 -1
- package/lib/account.js +289 -869
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-binding.js +58 -0
- package/lib/api-routes/account-routes.js +65 -37
- package/lib/api-routes/behavior-notes.js +4 -0
- package/lib/api-routes/blocklist-routes.js +2 -2
- package/lib/api-routes/bull-board-routes.js +1 -6
- package/lib/api-routes/export-routes.js +2 -22
- package/lib/api-routes/gateway-routes.js +15 -16
- package/lib/api-routes/index.js +1 -13
- package/lib/api-routes/mailbox-routes.js +2 -7
- package/lib/api-routes/mcp-oauth-routes.js +2 -1
- package/lib/api-routes/mcp-routes.js +7 -7
- package/lib/api-routes/message-routes.js +50 -238
- package/lib/api-routes/mint-bounds.js +110 -0
- package/lib/api-routes/oauth2-app-routes.js +23 -32
- package/lib/api-routes/operation-impact.js +1 -1
- package/lib/api-routes/outbox-routes.js +3 -3
- package/lib/api-routes/permission-map.js +1 -7
- package/lib/api-routes/route-helpers.js +11 -5
- package/lib/api-routes/settings-routes.js +20 -21
- package/lib/api-routes/stats-routes.js +1 -1
- package/lib/api-routes/submit-routes.js +17 -18
- package/lib/api-routes/template-routes.js +4 -9
- package/lib/api-routes/token-routes.js +28 -6
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +33 -6
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +305 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +54 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +77 -30
- package/lib/delivery-error.js +70 -2
- package/lib/egress-fetch.js +54 -3
- package/lib/egress-filter.js +11 -0
- package/lib/email-client/api-retry.js +147 -0
- package/lib/email-client/base-client.js +383 -536
- package/lib/email-client/credential-errors.js +21 -5
- package/lib/email-client/gmail/gmail-api.js +38 -125
- package/lib/email-client/gmail/send-request.js +1 -1
- package/lib/email-client/gmail-client.js +77 -51
- package/lib/email-client/imap/mailbox.js +158 -324
- package/lib/email-client/imap/stale-view.js +109 -0
- package/lib/email-client/imap/subconnection.js +46 -9
- package/lib/email-client/imap/sync-operations.js +5 -37
- package/lib/email-client/imap-client.js +190 -65
- package/lib/email-client/message-builder.js +50 -25
- package/lib/email-client/notification-handler.js +5 -219
- package/lib/email-client/outlook/graph-api.js +147 -126
- package/lib/email-client/outlook/send-request.js +10 -4
- package/lib/email-client/outlook-client.js +389 -463
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +6 -3
- package/lib/export.js +141 -41
- package/lib/gateway.js +25 -6
- package/lib/get-raw-email.js +26 -44
- package/lib/get-secret.js +1 -21
- package/lib/handlebars-helpers.js +31 -10
- package/lib/imap-proxy-auth.js +13 -29
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
- package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
- package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
- package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
- package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
- package/lib/imapproxy/imap-server.js +17 -177
- package/lib/imapproxy/proxy-handoff.js +235 -0
- package/lib/imapproxy/response-error.js +33 -0
- package/lib/imapproxy/upstream-client.js +2 -2
- package/lib/license-beacon.js +3 -9
- package/lib/llm-pre-process.js +182 -43
- package/lib/logger.js +1 -1
- package/lib/lua/ee-export-queue-add.lua +39 -0
- package/lib/lua/ee-get-idempotency.lua +15 -3
- package/lib/lua/ee-release-attempts.lua +23 -0
- package/lib/lua/ee-reserve-attempts.lua +42 -0
- package/lib/lua/h-set-bigger.lua +12 -2
- package/lib/lua/s-list-accounts.lua +6 -3
- package/lib/mcp/index.js +1 -2
- package/lib/mcp/listen.js +221 -18
- package/lib/mcp/oauth.js +44 -5
- package/lib/mcp/resources.js +8 -2
- package/lib/mcp/tools.js +108 -36
- package/lib/message-port-stream.js +64 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +64 -32
- package/lib/oauth/mail-ru.js +24 -17
- package/lib/oauth/outlook.js +53 -40
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +39 -8
- package/lib/oauth/scope-list.js +55 -0
- package/lib/oauth/token-fetch.js +47 -0
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +154 -90
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- package/lib/outbox.js +2 -7
- package/lib/parse-message.js +21 -0
- package/lib/payload-examples-webhooks.json +4 -7
- package/lib/pbkdf2-phc.js +101 -0
- package/lib/privileged-settings.js +0 -14
- package/lib/queue-retention.js +4 -2
- package/lib/rate-limit.js +54 -15
- package/lib/read-env-value.js +33 -2
- package/lib/redis-scan-delete.js +56 -29
- package/lib/redis-url.js +3 -1
- package/lib/respawn-backoff.js +5 -4
- package/lib/response-stream.js +25 -4
- package/lib/rewrite-text-nodes.js +27 -40
- package/lib/routes-ui.js +0 -5
- package/lib/schemas.js +180 -253
- package/lib/sentry.js +21 -5
- package/lib/settings.js +58 -59
- package/lib/smtp-auth.js +6 -2
- package/lib/smtp-message-processor.js +28 -7
- package/lib/sso.js +7 -3
- package/lib/stream-encrypt.js +14 -13
- package/lib/swagger-options.js +3 -1
- package/lib/tls/provision.js +69 -3
- package/lib/tls/store.js +14 -1
- package/lib/token-audit-log.js +3 -2
- package/lib/tools.js +114 -53
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +67 -70
- package/lib/ui-routes/admin-config-routes.js +111 -134
- package/lib/ui-routes/admin-entities-routes.js +101 -191
- package/lib/ui-routes/ai-options.js +104 -0
- package/lib/ui-routes/auth-routes.js +98 -18
- package/lib/ui-routes/export-routes.js +3 -23
- package/lib/ui-routes/internals-routes.js +12 -9
- package/lib/ui-routes/network-config-routes.js +8 -18
- package/lib/ui-routes/oauth-config-routes.js +83 -228
- package/lib/ui-routes/route-helpers.js +63 -67
- package/lib/ui-routes/special-use-paths.js +33 -0
- package/lib/ui-routes/unsubscribe-routes.js +2 -2
- package/lib/utils/decode-headers.js +32 -5
- package/lib/utils/header-map.js +62 -1
- package/lib/utils/network.js +11 -17
- package/lib/web-safe-html.js +77 -4
- package/lib/webhook-request.js +9 -1
- package/lib/webhook-routing.js +27 -1
- package/lib/webhooks.js +120 -43
- package/lib/worker-rpc-error.js +43 -2
- package/list-generate.js +13 -2
- package/package.json +38 -46
- package/sbom.json +1 -1
- package/scripts/refresh-test-tokens.js +42 -14
- package/server.js +338 -292
- package/setup-production.sh +16 -7
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +7 -8
- package/static/js/ee-client.js +145 -70
- package/static/js/ui.js +350 -154
- package/static/licenses.html +349 -1740
- package/translations/messages.pot +129 -111
- package/views/account-workspace-error.hbs +30 -0
- package/views/accounts/account.hbs +9 -4
- package/views/accounts/browse.hbs +10 -4
- package/views/accounts/edit.hbs +11 -2
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +0 -22
- package/views/layout/login.hbs +2 -1
- package/views/partials/filter_editor_js.hbs +4 -3
- package/views/partials/gmail_api_scopes.hbs +16 -0
- package/views/partials/oauth_form.hbs +67 -94
- package/views/partials/oauth_pubsub_app_select.hbs +43 -0
- package/views/partials/scope_info.hbs +14 -23
- package/views/partials/side_menu.hbs +0 -4
- package/views/partials/ui/account-picker.hbs +6 -32
- package/views/partials/ui/model-picker.hbs +31 -0
- package/views/partials/ui/pagination.hbs +6 -1
- package/views/partials/ui/picker.hbs +47 -0
- package/views/unsubscribe.hbs +1 -1
- package/workers/api.js +82 -47
- package/workers/export.js +55 -60
- package/workers/imap.js +132 -49
- package/workers/submit.js +5 -6
- package/workers/webhooks.js +46 -27
- package/.githooks/pre-commit +0 -80
- package/.github/CODE_OF_CONDUCT.md +0 -76
- package/.github/contributing.md +0 -17
- package/.github/dependabot.yml +0 -22
- package/.github/docker-smoke-test.sh +0 -61
- package/.github/workflows/deploy.yml +0 -215
- package/.github/workflows/e2e.yml +0 -55
- package/.github/workflows/release.yaml +0 -217
- package/.github/workflows/test.yml +0 -307
- package/lib/api-routes/chat-routes.js +0 -535
- package/lib/document-store.js +0 -75
- package/lib/es.js +0 -757
- package/lib/generate-text-preview.js +0 -61
- package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
- package/lib/pre-process.js +0 -196
- package/lib/threads.js +0 -155
- package/lib/ui-routes/document-store-routes.js +0 -806
- package/playwright.config.js +0 -47
- package/views/config/document-store/chat.hbs +0 -286
- package/views/config/document-store/index.hbs +0 -146
- package/views/config/document-store/mappings/index.hbs +0 -108
- package/views/config/document-store/mappings/new.hbs +0 -68
- package/views/config/document-store/pre-processing/index.hbs +0 -103
- package/views/partials/document_store_header.hbs +0 -30
- package/workers/documents.js +0 -1128
package/server.js
CHANGED
|
@@ -14,6 +14,12 @@
|
|
|
14
14
|
* @see {@link https://emailengine.app}
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
// No native addons (CLAUDE.md "Pure JavaScript only"). bullmq depends on msgpackr, whose optional
|
|
18
|
+
// dependency msgpackr-extract is a node-gyp addon that npm and Docker installs pick up and load
|
|
19
|
+
// when present, while the pkg binary decodes in JavaScript. This makes every install decode the
|
|
20
|
+
// same way. Set before anything can require bullmq; worker threads share this environment.
|
|
21
|
+
process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED = 'true';
|
|
22
|
+
|
|
17
23
|
// Load environment variables if not already loaded
|
|
18
24
|
if (!process.env.EE_ENV_LOADED) {
|
|
19
25
|
require('dotenv').config({ quiet: true });
|
|
@@ -89,20 +95,15 @@ const {
|
|
|
89
95
|
ACCOUNT_ADDED_NOTIFY,
|
|
90
96
|
ACCOUNT_DELETED_NOTIFY,
|
|
91
97
|
LIST_UNSUBSCRIBE_NOTIFY,
|
|
92
|
-
LIST_SUBSCRIBE_NOTIFY
|
|
98
|
+
LIST_SUBSCRIBE_NOTIFY,
|
|
99
|
+
LAST_DOCUMENT_STORE_VERSION,
|
|
100
|
+
AI_REQUEST_TIMEOUT,
|
|
101
|
+
AI_SETTING_KEYS
|
|
93
102
|
} = require('./lib/consts');
|
|
94
103
|
|
|
95
104
|
// Import core modules
|
|
96
105
|
const { webhooks: Webhooks } = require('./lib/webhooks');
|
|
97
|
-
const {
|
|
98
|
-
generateSummary,
|
|
99
|
-
generateEmbeddings,
|
|
100
|
-
getChunkEmbeddings,
|
|
101
|
-
embeddingsQuery,
|
|
102
|
-
questionQuery,
|
|
103
|
-
listModels: openAiListModels,
|
|
104
|
-
DEFAULT_USER_PROMPT: openAiDefaultPrompt
|
|
105
|
-
} = require('@postalsys/email-ai-tools');
|
|
106
|
+
const { generateSummary, listModels: openAiListModels, DEFAULT_MODEL: openAiDefaultModel } = require('@postalsys/email-ai-tools');
|
|
106
107
|
const { fetch: fetchCmd } = require('undici');
|
|
107
108
|
|
|
108
109
|
const bounceClassifier = require('@postalsys/bounce-classifier');
|
|
@@ -115,7 +116,7 @@ initSentry('main');
|
|
|
115
116
|
|
|
116
117
|
// Import additional dependencies
|
|
117
118
|
const pathlib = require('path');
|
|
118
|
-
const { redis, queueConf, notifyQueue, submitQueue,
|
|
119
|
+
const { redis, queueConf, notifyQueue, submitQueue, exportQueue, logBullErrors } = require('./lib/db');
|
|
119
120
|
const { queueStats } = require('./lib/queue-stats');
|
|
120
121
|
const { packRpcError, unpackRpcError } = require('./lib/worker-rpc-error');
|
|
121
122
|
const promClient = require('prom-client');
|
|
@@ -128,7 +129,6 @@ const settings = require('./lib/settings');
|
|
|
128
129
|
const { oauth2Apps } = require('./lib/oauth2-apps');
|
|
129
130
|
const { backfillAuthFailureDisabled } = require('./lib/account/auth-failure-backfill');
|
|
130
131
|
const { sweepBounceStore } = require('./lib/account/bounce-store-sweep');
|
|
131
|
-
const { documentStoreFeatureEnabled } = require('./lib/document-store');
|
|
132
132
|
const { attachBeacon, persistBeaconMarkers } = require('./lib/license-beacon');
|
|
133
133
|
const tokens = require('./lib/tokens');
|
|
134
134
|
|
|
@@ -139,7 +139,16 @@ const { QueueEvents } = require('bullmq');
|
|
|
139
139
|
const getSecret = require('./lib/get-secret');
|
|
140
140
|
|
|
141
141
|
const { rejectWorkerCalls } = require('./lib/reject-worker-calls');
|
|
142
|
-
const {
|
|
142
|
+
const {
|
|
143
|
+
pickLeastLoadedWorker,
|
|
144
|
+
rollbackAssignment,
|
|
145
|
+
releaseWorkerAccounts,
|
|
146
|
+
requeueFailedAccounts,
|
|
147
|
+
forgetAccount,
|
|
148
|
+
mapConcurrent,
|
|
149
|
+
shouldRequeueFailedAssignment,
|
|
150
|
+
planRebalance
|
|
151
|
+
} = require('./lib/account-assignment');
|
|
143
152
|
const { RespawnTracker } = require('./lib/respawn-backoff');
|
|
144
153
|
|
|
145
154
|
const msgpack = require('./lib/msgpack');
|
|
@@ -214,6 +223,9 @@ config.dbs.redis = readEnvValue('EENGINE_REDIS') || readEnvValue('REDIS_URL') ||
|
|
|
214
223
|
config.workers.imap = getWorkerCount(readEnvValue('EENGINE_WORKERS') || config.workers.imap) || 4;
|
|
215
224
|
config.workers.webhooks = Number(readEnvValue('EENGINE_WORKERS_WEBHOOKS')) || config.workers.webhooks || 1;
|
|
216
225
|
config.workers.submit = Number(readEnvValue('EENGINE_WORKERS_SUBMIT')) || config.workers.submit || 1;
|
|
226
|
+
// The Workers page has labelled this row EENGINE_WORKERS_EXPORT since the export worker shipped, while
|
|
227
|
+
// only --workers.export and [workers] export were read, so an operator who set it saw no effect
|
|
228
|
+
config.workers.export = Number(readEnvValue('EENGINE_WORKERS_EXPORT')) || config.workers.export || 1;
|
|
217
229
|
// API worker count. Values >1 require SO_REUSEPORT (Linux); on unsupported platforms it falls back to 1 at startup.
|
|
218
230
|
// Uses getWorkerCount() for parity with EENGINE_WORKERS (supports "cpus"); Math.floor avoids a fractional
|
|
219
231
|
// count over-spawning, Math.max keeps at least one API worker.
|
|
@@ -331,7 +343,6 @@ const THREAD_NAMES = {
|
|
|
331
343
|
api: 'HTTP and API server',
|
|
332
344
|
submit: 'Email sending worker',
|
|
333
345
|
export: 'Export worker',
|
|
334
|
-
documents: 'Document store indexing worker',
|
|
335
346
|
imapProxy: 'IMAP proxy server',
|
|
336
347
|
smtp: 'SMTP proxy server'
|
|
337
348
|
};
|
|
@@ -345,7 +356,7 @@ const THREAD_CONFIG_VALUES = {
|
|
|
345
356
|
api: { key: 'EENGINE_WORKERS_API', value: config.workers.api },
|
|
346
357
|
submit: { key: 'EENGINE_WORKERS_SUBMIT', value: config.workers.submit },
|
|
347
358
|
webhooks: { key: 'EENGINE_WORKERS_WEBHOOKS', value: config.workers.webhooks },
|
|
348
|
-
export: { key: 'EENGINE_WORKERS_EXPORT', value: config.workers.export
|
|
359
|
+
export: { key: 'EENGINE_WORKERS_EXPORT', value: config.workers.export }
|
|
349
360
|
};
|
|
350
361
|
|
|
351
362
|
// Queue event handlers for different job queues
|
|
@@ -577,6 +588,18 @@ const metrics = {
|
|
|
577
588
|
labelNames: ['status', 'provider', 'statusCode']
|
|
578
589
|
}),
|
|
579
590
|
|
|
591
|
+
outlookMissedRecovery: new promClient.Counter({
|
|
592
|
+
name: 'outlook_missed_recovery',
|
|
593
|
+
help: 'MS Graph missed-notification recovery passes, by what asked for them and whether they found unannounced messages',
|
|
594
|
+
labelNames: ['reason', 'outcome']
|
|
595
|
+
}),
|
|
596
|
+
|
|
597
|
+
outlookMissedRecoveredMessages: new promClient.Counter({
|
|
598
|
+
name: 'outlook_missed_recovered_messages',
|
|
599
|
+
help: 'New messages announced by MS Graph missed-notification recovery instead of by a change notification',
|
|
600
|
+
labelNames: ['reason']
|
|
601
|
+
}),
|
|
602
|
+
|
|
580
603
|
outlookSubscriptions: new promClient.Gauge({
|
|
581
604
|
name: 'outlook_subscriptions',
|
|
582
605
|
help: 'MS Graph webhook subscription states',
|
|
@@ -595,6 +618,18 @@ const metrics = {
|
|
|
595
618
|
labelNames: ['event']
|
|
596
619
|
}),
|
|
597
620
|
|
|
621
|
+
aiRequests: new promClient.Counter({
|
|
622
|
+
name: 'ai_requests',
|
|
623
|
+
help: 'AI summary requests',
|
|
624
|
+
labelNames: ['model', 'status']
|
|
625
|
+
}),
|
|
626
|
+
|
|
627
|
+
aiTokens: new promClient.Counter({
|
|
628
|
+
name: 'ai_tokens',
|
|
629
|
+
help: 'Tokens billed for AI summary requests',
|
|
630
|
+
labelNames: ['model', 'type']
|
|
631
|
+
}),
|
|
632
|
+
|
|
598
633
|
webhookReq: new promClient.Histogram({
|
|
599
634
|
name: 'webhook_req',
|
|
600
635
|
help: 'Duration of webhook requests',
|
|
@@ -747,6 +782,8 @@ let mids = 0; // Message ID counter
|
|
|
747
782
|
// Application state flags
|
|
748
783
|
let isClosing = false; // Is the application shutting down?
|
|
749
784
|
let assigning = false; // Is account assignment in progress?
|
|
785
|
+
// Unassign calls in flight at once while rebalanceOnto() holds the assignment lock
|
|
786
|
+
const REBALANCE_CONCURRENCY = 8;
|
|
750
787
|
|
|
751
788
|
// Account assignment tracking
|
|
752
789
|
let unassigned = false; // Set of unassigned accounts
|
|
@@ -761,7 +798,8 @@ const MAX_ASSIGN_RETRIES = 3; // Max consecutive safety-net retries before givin
|
|
|
761
798
|
// Worker management
|
|
762
799
|
let imapInitialWorkersLoaded = false; // Have all initial IMAP workers started?
|
|
763
800
|
let workers = new Map(); // Map of type -> Set of workers
|
|
764
|
-
const respawnTracker = new RespawnTracker(); // paces respawns for worker
|
|
801
|
+
const respawnTracker = new RespawnTracker(); // paces respawns for worker slots that keep crashing
|
|
802
|
+
let spawnSlotCounter = 0; // source of respawn slot ids, see spawnWorker()
|
|
765
803
|
|
|
766
804
|
// Shutdown drain budget. A worker with no in-flight job answers immediately, so this only costs
|
|
767
805
|
// real time when there is genuinely something to finish - which is exactly when waiting is worth
|
|
@@ -1076,13 +1114,15 @@ async function sendWebhook(account, event, data) {
|
|
|
1076
1114
|
|
|
1077
1115
|
/**
|
|
1078
1116
|
* Spawn a new worker thread of the specified type
|
|
1079
|
-
* @param {string} type - Worker type (imap, api, webhooks, submit,
|
|
1117
|
+
* @param {string} type - Worker type (imap, api, webhooks, submit, export, smtp, imapProxy)
|
|
1080
1118
|
* @param {Object} [opts] - Optional spawn options
|
|
1081
1119
|
* @param {Object} [opts.workerData] - Data passed to the worker thread (e.g. API worker index). The
|
|
1082
1120
|
* proxy in effect is added for every type, see lib/tools.js
|
|
1121
|
+
* @param {string} [slot] - Respawn slot this thread fills. A respawn passes its predecessor's slot
|
|
1122
|
+
* so the crash streak is counted per slot, not per worker type
|
|
1083
1123
|
* @returns {Promise<number|void>} Thread ID if successful
|
|
1084
1124
|
*/
|
|
1085
|
-
let spawnWorker = async (type, opts) => {
|
|
1125
|
+
let spawnWorker = async (type, opts, slot) => {
|
|
1086
1126
|
// Don't spawn workers during shutdown
|
|
1087
1127
|
if (isClosing) {
|
|
1088
1128
|
return;
|
|
@@ -1112,6 +1152,13 @@ let spawnWorker = async (type, opts) => {
|
|
|
1112
1152
|
await updateServerState(type, 'spawning');
|
|
1113
1153
|
}
|
|
1114
1154
|
|
|
1155
|
+
// A fresh spawn opens its own slot. Counting the crash streak per type made every short-lived
|
|
1156
|
+
// exit of ANY IMAP worker double the next respawn delay of all of them, so unrelated exits
|
|
1157
|
+
// pushed a restart past the 10s failsafe reassignment.
|
|
1158
|
+
if (!slot) {
|
|
1159
|
+
slot = `${type}:${++spawnSlotCounter}`;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1115
1162
|
// Create new worker thread
|
|
1116
1163
|
let spawnedAt = Date.now();
|
|
1117
1164
|
let worker = new WorkerThread(pathlib.join(__dirname, 'workers', `${type.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}.js`), {
|
|
@@ -1188,7 +1235,12 @@ let spawnWorker = async (type, opts) => {
|
|
|
1188
1235
|
|
|
1189
1236
|
// Update server state for proxy servers
|
|
1190
1237
|
if (['smtp', 'imapProxy'].includes(type)) {
|
|
1191
|
-
|
|
1238
|
+
// Not awaited, so the rejection has to be handled here: a Redis reply error
|
|
1239
|
+
// (OOM, READONLY) would otherwise reach the global handler and take the whole
|
|
1240
|
+
// process down with it.
|
|
1241
|
+
updateServerState(type, suspendedWorkerTypes.has(type) ? 'suspended' : 'exited').catch(err =>
|
|
1242
|
+
logger.error({ msg: 'Unable to update server state', type, err })
|
|
1243
|
+
);
|
|
1192
1244
|
}
|
|
1193
1245
|
|
|
1194
1246
|
// Handle IMAP worker cleanup
|
|
@@ -1289,13 +1341,13 @@ let spawnWorker = async (type, opts) => {
|
|
|
1289
1341
|
// Respawn worker after delay, preserving any spawn options (e.g. API worker index).
|
|
1290
1342
|
// The delay grows while a worker type keeps dying on startup, so a deterministic
|
|
1291
1343
|
// crash no longer respawns once a second forever.
|
|
1292
|
-
let respawnDelay = respawnTracker.recordExit(
|
|
1293
|
-
let streak = respawnTracker.streakFor(
|
|
1344
|
+
let respawnDelay = respawnTracker.recordExit(slot, Date.now() - spawnedAt);
|
|
1345
|
+
let streak = respawnTracker.streakFor(slot);
|
|
1294
1346
|
if (streak > 1) {
|
|
1295
|
-
logger.warn({ msg: 'Worker is crash looping, delaying respawn', type, consecutiveFailures: streak, respawnDelay });
|
|
1347
|
+
logger.warn({ msg: 'Worker is crash looping, delaying respawn', type, slot, consecutiveFailures: streak, respawnDelay });
|
|
1296
1348
|
}
|
|
1297
1349
|
await new Promise(r => setTimeout(r, respawnDelay));
|
|
1298
|
-
await spawnWorker(type, opts);
|
|
1350
|
+
await spawnWorker(type, opts, slot);
|
|
1299
1351
|
};
|
|
1300
1352
|
|
|
1301
1353
|
// Handle worker exit
|
|
@@ -1475,9 +1527,16 @@ let spawnWorker = async (type, opts) => {
|
|
|
1475
1527
|
redis.hincrby(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
|
|
1476
1528
|
}
|
|
1477
1529
|
|
|
1478
|
-
// Update Prometheus metrics
|
|
1530
|
+
// Update Prometheus metrics. prom-client throws synchronously on an unknown
|
|
1531
|
+
// label, a negative counter increment or a non-finite value, and this runs in
|
|
1532
|
+
// an event handler on the main thread, where a throw would take every worker
|
|
1533
|
+
// down with it.
|
|
1479
1534
|
if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
|
|
1480
|
-
|
|
1535
|
+
try {
|
|
1536
|
+
metrics[message.key][message.method](...message.args);
|
|
1537
|
+
} catch (err) {
|
|
1538
|
+
logger.error({ msg: 'Unable to apply worker metric', type, key: message.key, method: message.method, err });
|
|
1539
|
+
}
|
|
1481
1540
|
}
|
|
1482
1541
|
|
|
1483
1542
|
return;
|
|
@@ -1599,6 +1658,10 @@ let spawnWorker = async (type, opts) => {
|
|
|
1599
1658
|
unassignedAccounts: unassigned.size
|
|
1600
1659
|
});
|
|
1601
1660
|
}
|
|
1661
|
+
} else if (imapInitialWorkersLoaded) {
|
|
1662
|
+
// The failsafe timer already gave this worker's accounts to the
|
|
1663
|
+
// survivors (or it is an extra worker), so nothing is pending for it
|
|
1664
|
+
rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err }));
|
|
1602
1665
|
}
|
|
1603
1666
|
}
|
|
1604
1667
|
break;
|
|
@@ -1697,6 +1760,95 @@ async function call(worker, message, transferList) {
|
|
|
1697
1760
|
});
|
|
1698
1761
|
}
|
|
1699
1762
|
|
|
1763
|
+
/**
|
|
1764
|
+
* Whether an account is still registered, checked before a failed assignment is retried
|
|
1765
|
+
* @param {string} account
|
|
1766
|
+
* @returns {Promise<boolean>}
|
|
1767
|
+
*/
|
|
1768
|
+
async function isRegisteredAccount(account) {
|
|
1769
|
+
return !!(await redis.sismember(`${REDIS_PREFIX}ia:accounts`, account));
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
/**
|
|
1773
|
+
* Tells an IMAP worker to close an account without deleting anything, used when the account moves
|
|
1774
|
+
* to another worker. Returns whether the worker confirmed it
|
|
1775
|
+
* @param {Worker} worker
|
|
1776
|
+
* @param {string} account
|
|
1777
|
+
* @returns {Promise<boolean>}
|
|
1778
|
+
*/
|
|
1779
|
+
async function unassignFromWorker(worker, account) {
|
|
1780
|
+
if (!onlineWorkers.has(worker)) {
|
|
1781
|
+
// An exited worker holds no connections
|
|
1782
|
+
return true;
|
|
1783
|
+
}
|
|
1784
|
+
try {
|
|
1785
|
+
await call(worker, { cmd: 'unassign', account });
|
|
1786
|
+
return true;
|
|
1787
|
+
} catch (err) {
|
|
1788
|
+
logger.error({ msg: 'Failed to unassign account from worker', account, threadId: worker.threadId, err });
|
|
1789
|
+
return false;
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
/**
|
|
1794
|
+
* Moves a fair share of accounts onto an IMAP worker that became ready while the rest of the fleet
|
|
1795
|
+
* already served every account. That is the normal outcome of a restart slower than the failsafe
|
|
1796
|
+
* reassignment timer, and nothing else ever gives such a worker any accounts
|
|
1797
|
+
* @param {Worker} worker - The worker that became ready
|
|
1798
|
+
* @returns {Promise<void>}
|
|
1799
|
+
*/
|
|
1800
|
+
async function rebalanceOnto(worker) {
|
|
1801
|
+
if (isClosing || !availableIMAPWorkers.has(worker)) {
|
|
1802
|
+
return;
|
|
1803
|
+
}
|
|
1804
|
+
if (assigning) {
|
|
1805
|
+
// A pass is running (typically the failsafe one); look again once it has settled
|
|
1806
|
+
setTimeout(() => rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err })), 5000).unref();
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
let moves = planRebalance({ workerAssigned, availableWorkers: availableIMAPWorkers }, worker);
|
|
1811
|
+
if (!moves.length) {
|
|
1812
|
+
return;
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
assigning = true;
|
|
1816
|
+
let moved = 0;
|
|
1817
|
+
try {
|
|
1818
|
+
// Every other assignment pass waits on the lock held here, and a fair share of a large
|
|
1819
|
+
// fleet is hundreds of round trips, so the unassign calls run a few at a time rather than
|
|
1820
|
+
// one after the other
|
|
1821
|
+
await mapConcurrent(moves, REBALANCE_CONCURRENCY, async ({ account, worker: donor }) => {
|
|
1822
|
+
// The donor may have lost the account (deleted, donor exited) while we awaited
|
|
1823
|
+
if (assigned.get(account) !== donor) {
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
// Only an account the donor has let go of can move, or it would sync in two workers
|
|
1827
|
+
if (!(await unassignFromWorker(donor, account))) {
|
|
1828
|
+
return;
|
|
1829
|
+
}
|
|
1830
|
+
if (assigned.get(account) !== donor) {
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1833
|
+
forgetAccount({ workerAssigned, assigned, unassigned }, account);
|
|
1834
|
+
unassigned.add(account);
|
|
1835
|
+
moved++;
|
|
1836
|
+
});
|
|
1837
|
+
} finally {
|
|
1838
|
+
assigning = false;
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
if (moved) {
|
|
1842
|
+
logger.info({ msg: 'Rebalancing accounts onto a restarted IMAP worker', threadId: worker.threadId, accounts: moved });
|
|
1843
|
+
}
|
|
1844
|
+
// Also run when nothing moved: an account added while this held the assignment lock found the
|
|
1845
|
+
// pass refused and is waiting in unassigned. Every worker is available again, so the pass
|
|
1846
|
+
// picks the least loaded one, which is the newcomer.
|
|
1847
|
+
if (moved || unassigned.size) {
|
|
1848
|
+
await assignAccounts();
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1700
1852
|
/**
|
|
1701
1853
|
* Assign unassigned accounts to available IMAP workers
|
|
1702
1854
|
* Uses load-aware distribution with round-robin for initial assignment
|
|
@@ -1791,8 +1943,22 @@ async function assignAccounts() {
|
|
|
1791
1943
|
// Roll back -- account was never actually assigned. Also reverts the load map so
|
|
1792
1944
|
// subsequent iterations see accurate counts
|
|
1793
1945
|
rollbackAssignment({ workerAssigned, assigned, workerLoadMap }, account, worker, !isReassignment);
|
|
1794
|
-
|
|
1946
|
+
|
|
1947
|
+
if (err.code === 'Timeout') {
|
|
1948
|
+
// A timed-out assign is still running in the worker and would connect the
|
|
1949
|
+
// account there after this pass has handed it to another worker, so the same
|
|
1950
|
+
// account would sync twice. Cancel it; the worker also drops an assignment
|
|
1951
|
+
// superseded this way, see assignConnection().
|
|
1952
|
+
unassignFromWorker(worker, account);
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1795
1955
|
logger.error({ msg: 'Failed to assign account to worker', account, threadId: worker.threadId, err });
|
|
1956
|
+
|
|
1957
|
+
if (await shouldRequeueFailedAssignment(err, account, isRegisteredAccount)) {
|
|
1958
|
+
failedAccounts.push(account);
|
|
1959
|
+
} else {
|
|
1960
|
+
logger.info({ msg: 'Dropped assignment of an account that no longer exists', account });
|
|
1961
|
+
}
|
|
1796
1962
|
continue;
|
|
1797
1963
|
}
|
|
1798
1964
|
|
|
@@ -1976,7 +2142,10 @@ let licenseCheckHandler = async opts => {
|
|
|
1976
2142
|
|
|
1977
2143
|
// Handle no active license - suspend workers
|
|
1978
2144
|
if (!licenseInfo.active && !suspendedWorkerTypes.size) {
|
|
1979
|
-
|
|
2145
|
+
// Said in the present tense, because that is what the loop below does. The line used to
|
|
2146
|
+
// promise a 15 minute grace period that nothing anywhere implements, so an operator
|
|
2147
|
+
// reading it waited for a window that had already closed.
|
|
2148
|
+
logger.info({ msg: 'No active license. Suspending every worker except the API server.' });
|
|
1980
2149
|
|
|
1981
2150
|
// Suspend all worker types except API
|
|
1982
2151
|
for (let type of ['imap', 'submit', 'smtp', 'webhooks', 'imapProxy']) {
|
|
@@ -2066,14 +2235,15 @@ let upgradeCheckTimer = false;
|
|
|
2066
2235
|
* @returns {Promise<void>}
|
|
2067
2236
|
*/
|
|
2068
2237
|
let upgradeCheckHandler = async () => {
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2238
|
+
// An up-to-date instance keeps checking too. The check used to return early, before
|
|
2239
|
+
// rescheduling, whenever no upgrade was already known, so the daily check stopped after its
|
|
2240
|
+
// first run on every instance that was current at the time.
|
|
2241
|
+
try {
|
|
2242
|
+
await processCheckUpgrade();
|
|
2243
|
+
} finally {
|
|
2244
|
+
upgradeCheckTimer = setTimeout(checkUpgrade, UPGRADE_CHECK_TIMEOUT);
|
|
2245
|
+
upgradeCheckTimer.unref();
|
|
2073
2246
|
}
|
|
2074
|
-
await processCheckUpgrade();
|
|
2075
|
-
upgradeCheckTimer = setTimeout(checkUpgrade, UPGRADE_CHECK_TIMEOUT);
|
|
2076
|
-
upgradeCheckTimer.unref();
|
|
2077
2247
|
};
|
|
2078
2248
|
|
|
2079
2249
|
/**
|
|
@@ -2157,7 +2327,8 @@ const processRedisPing = async () => {
|
|
|
2157
2327
|
redisPingCounter.push(duration);
|
|
2158
2328
|
// Keep last 300 measurements
|
|
2159
2329
|
if (redisPingCounter.length > 300) {
|
|
2160
|
-
|
|
2330
|
+
// keep the newest samples, the average is computed from the tail
|
|
2331
|
+
redisPingCounter = redisPingCounter.slice(-150);
|
|
2161
2332
|
}
|
|
2162
2333
|
return duration;
|
|
2163
2334
|
} catch (err) {
|
|
@@ -2261,8 +2432,7 @@ async function updateQueueCounters() {
|
|
|
2261
2432
|
// gauge is kept at the 0 the getter reports so existing dashboards keep their series.
|
|
2262
2433
|
for (let [queue, queueObj] of [
|
|
2263
2434
|
['notify', notifyQueue],
|
|
2264
|
-
['submit', submitQueue]
|
|
2265
|
-
['documents', documentsQueue]
|
|
2435
|
+
['submit', submitQueue]
|
|
2266
2436
|
]) {
|
|
2267
2437
|
let stats;
|
|
2268
2438
|
try {
|
|
@@ -2350,6 +2520,66 @@ const openAiRequestOpts = () => ({
|
|
|
2350
2520
|
dispatcher: httpAgent.fetch
|
|
2351
2521
|
});
|
|
2352
2522
|
|
|
2523
|
+
const aiValueSet = value => value !== undefined && value !== null && value !== '';
|
|
2524
|
+
|
|
2525
|
+
/**
|
|
2526
|
+
* Options for one request to the AI provider. The configuration page's test sends every field as
|
|
2527
|
+
* its form shows it, so the test runs with what the page shows; the sync path sends none and gets
|
|
2528
|
+
* the stored settings. The key is the exception: the form leaves it blank to keep the stored one
|
|
2529
|
+
* @param {Object} data - The command's data
|
|
2530
|
+
* @returns {Promise<{openAiAPIKey: string, requestOpts: Object}>}
|
|
2531
|
+
*/
|
|
2532
|
+
async function aiRequestOptions(data) {
|
|
2533
|
+
const stored = await settings.getMulti('openAiAPIKey', ...AI_SETTING_KEYS);
|
|
2534
|
+
const values = data.options || stored;
|
|
2535
|
+
|
|
2536
|
+
const openAiAPIKey = (data.options && data.options.openAiAPIKey) || stored.openAiAPIKey;
|
|
2537
|
+
if (!openAiAPIKey) {
|
|
2538
|
+
throw new Error(`OpenAI API key is not configured`);
|
|
2539
|
+
}
|
|
2540
|
+
|
|
2541
|
+
const requestOpts = openAiRequestOpts();
|
|
2542
|
+
requestOpts.gptModel = aiValueSet(values.openAiModel) ? values.openAiModel : openAiDefaultModel;
|
|
2543
|
+
for (const [key, name] of [
|
|
2544
|
+
['openAiAPIUrl', 'baseApiUrl'],
|
|
2545
|
+
['openAiTemperature', 'temperature'],
|
|
2546
|
+
['openAiTopP', 'topP'],
|
|
2547
|
+
['openAiMaxTokens', 'maxTokens'],
|
|
2548
|
+
['openAiReasoningEffort', 'reasoningEffort'],
|
|
2549
|
+
['openAiPrompt', 'instructions']
|
|
2550
|
+
]) {
|
|
2551
|
+
if (aiValueSet(values[key])) {
|
|
2552
|
+
requestOpts[name] = values[key];
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
|
|
2556
|
+
// which Authentication-Results header the summary may believe, decided by the worker that
|
|
2557
|
+
// knows the account
|
|
2558
|
+
if (data.trust) {
|
|
2559
|
+
requestOpts.trustedAuthservIds = data.trust.trustedAuthservIds;
|
|
2560
|
+
requestOpts.acceptUnnamedAuthentication = !!data.trust.acceptUnnamedAuthentication;
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
return { openAiAPIKey, requestOpts };
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
/**
|
|
2567
|
+
* Runs a provider request that is aborted when the RPC that asked for it has given up, so it does
|
|
2568
|
+
* not outlive its caller. The timer is cleared as the request ends rather than left to fire later
|
|
2569
|
+
* @param {Object} message - The RPC message, with the caller's timeout
|
|
2570
|
+
* @param {Function} run - Receives the abort signal, returns the request promise
|
|
2571
|
+
*/
|
|
2572
|
+
async function withRequestDeadline(message, run) {
|
|
2573
|
+
const controller = new AbortController();
|
|
2574
|
+
const timer = setTimeout(() => controller.abort(new Error('AI request timed out')), message.timeout || AI_REQUEST_TIMEOUT);
|
|
2575
|
+
timer.unref();
|
|
2576
|
+
try {
|
|
2577
|
+
return await run(controller.signal);
|
|
2578
|
+
} finally {
|
|
2579
|
+
clearTimeout(timer);
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
|
|
2353
2583
|
async function onCommand(worker, message) {
|
|
2354
2584
|
switch (message.cmd) {
|
|
2355
2585
|
case 'metrics':
|
|
@@ -2508,244 +2738,46 @@ async function onCommand(worker, message) {
|
|
|
2508
2738
|
}
|
|
2509
2739
|
return false;
|
|
2510
2740
|
|
|
2511
|
-
// OpenAI integration commands - run in main process
|
|
2741
|
+
// OpenAI integration commands - run in the main process, where the metrics live
|
|
2512
2742
|
case 'generateSummary': {
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2516
|
-
|
|
2517
|
-
if (!openAiAPIKey) {
|
|
2518
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2519
|
-
}
|
|
2520
|
-
|
|
2521
|
-
let openAiModel = message.data.openAiModel || (await settings.get('openAiModel'));
|
|
2522
|
-
if (openAiModel) {
|
|
2523
|
-
requestOpts.gptModel = openAiModel;
|
|
2524
|
-
}
|
|
2525
|
-
|
|
2526
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2527
|
-
if (openAiAPIUrl) {
|
|
2528
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2529
|
-
}
|
|
2530
|
-
|
|
2531
|
-
let openAiTemperature = message.data.openAiTemperature || (await settings.get('openAiTemperature'));
|
|
2532
|
-
if (openAiTemperature) {
|
|
2533
|
-
requestOpts.temperature = openAiTemperature;
|
|
2534
|
-
}
|
|
2535
|
-
|
|
2536
|
-
let openAiTopP = message.data.openAiTopP || (await settings.get('openAiTopP'));
|
|
2537
|
-
if (openAiTopP) {
|
|
2538
|
-
requestOpts.topP = openAiTopP;
|
|
2539
|
-
}
|
|
2540
|
-
|
|
2541
|
-
let openAiMaxTokens = message.data.openAiMaxTokens || (await settings.get('openAiMaxTokens'));
|
|
2542
|
-
if (openAiMaxTokens) {
|
|
2543
|
-
requestOpts.maxTokens = openAiMaxTokens;
|
|
2544
|
-
} else {
|
|
2545
|
-
// Set max tokens based on model
|
|
2546
|
-
switch (openAiModel.substring(0, 5)) {
|
|
2547
|
-
case 'gpt-3':
|
|
2548
|
-
requestOpts.maxTokens = 3000;
|
|
2549
|
-
break;
|
|
2550
|
-
case 'gpt-4':
|
|
2551
|
-
requestOpts.maxTokens = 6500;
|
|
2552
|
-
break;
|
|
2553
|
-
case 'gpt-5':
|
|
2554
|
-
default:
|
|
2555
|
-
requestOpts.maxTokens = 18000;
|
|
2556
|
-
break;
|
|
2557
|
-
}
|
|
2558
|
-
}
|
|
2559
|
-
|
|
2743
|
+
const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
|
|
2560
2744
|
requestOpts.user = message.data.account;
|
|
2561
2745
|
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
}
|
|
2566
|
-
|
|
2567
|
-
return await generateSummary(message.data.message, openAiAPIKey, requestOpts);
|
|
2568
|
-
}
|
|
2569
|
-
|
|
2570
|
-
case 'generateEmbeddings': {
|
|
2571
|
-
let requestOpts = openAiRequestOpts();
|
|
2572
|
-
|
|
2573
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2574
|
-
|
|
2575
|
-
if (!openAiAPIKey) {
|
|
2576
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2577
|
-
}
|
|
2746
|
+
// the configuration page's test runs are not production traffic
|
|
2747
|
+
const counted = !message.data.options;
|
|
2748
|
+
const model = requestOpts.gptModel;
|
|
2578
2749
|
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
requestOpts.user = message.data.account;
|
|
2750
|
+
try {
|
|
2751
|
+
const response = await withRequestDeadline(message, signal =>
|
|
2752
|
+
generateSummary(message.data.message, openAiAPIKey, Object.assign(requestOpts, { signal }))
|
|
2753
|
+
);
|
|
2754
|
+
const { usage } = response;
|
|
2585
2755
|
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
return false;
|
|
2589
|
-
}
|
|
2756
|
+
// the fitted email text the verbose mode adds stays out of the RPC and the log
|
|
2757
|
+
delete usage.text;
|
|
2590
2758
|
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2759
|
+
if (counted) {
|
|
2760
|
+
metrics.aiRequests.inc({ model, status: 'success' });
|
|
2761
|
+
for (const type of ['prompt', 'completion']) {
|
|
2762
|
+
const tokens = usage[`${type}Tokens`];
|
|
2763
|
+
if (tokens) {
|
|
2764
|
+
metrics.aiTokens.inc({ model, type }, tokens);
|
|
2765
|
+
}
|
|
2596
2766
|
}
|
|
2597
2767
|
}
|
|
2598
|
-
}
|
|
2599
|
-
|
|
2600
|
-
return embeddings;
|
|
2601
|
-
}
|
|
2602
|
-
|
|
2603
|
-
case 'embeddingsQuery': {
|
|
2604
|
-
let requestOpts = openAiRequestOpts();
|
|
2605
|
-
|
|
2606
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2607
|
-
|
|
2608
|
-
if (!openAiAPIKey) {
|
|
2609
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2610
|
-
}
|
|
2611
|
-
|
|
2612
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2613
|
-
if (openAiAPIUrl) {
|
|
2614
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2615
|
-
}
|
|
2616
|
-
|
|
2617
|
-
let openAiModel = message.data.openAiModel || (await settings.get('documentStoreChatModel')) || (await settings.get('openAiModel'));
|
|
2618
|
-
if (openAiModel) {
|
|
2619
|
-
requestOpts.gptModel = openAiModel;
|
|
2620
|
-
}
|
|
2621
|
-
|
|
2622
|
-
// Set max tokens based on model
|
|
2623
|
-
switch (openAiModel.substring(0, 5)) {
|
|
2624
|
-
case 'gpt-3':
|
|
2625
|
-
requestOpts.maxTokens = 3000;
|
|
2626
|
-
break;
|
|
2627
|
-
case 'gpt-4':
|
|
2628
|
-
requestOpts.maxTokens = 6500;
|
|
2629
|
-
break;
|
|
2630
|
-
case 'gpt-5':
|
|
2631
|
-
default:
|
|
2632
|
-
requestOpts.maxTokens = 18000;
|
|
2633
|
-
break;
|
|
2634
|
-
}
|
|
2635
|
-
|
|
2636
|
-
requestOpts.user = message.data.account;
|
|
2637
|
-
requestOpts.temperature = 0.4;
|
|
2638
|
-
|
|
2639
|
-
requestOpts.question = message.data.question;
|
|
2640
|
-
requestOpts.contextChunks = message.data.contextChunks;
|
|
2641
|
-
requestOpts.userData = message.data.userData;
|
|
2642
|
-
|
|
2643
|
-
let response = await embeddingsQuery(openAiAPIKey, requestOpts);
|
|
2644
|
-
|
|
2645
|
-
// Clean and format response
|
|
2646
|
-
if (response?.['Message-ID']) {
|
|
2647
|
-
response.messageId = response?.['Message-ID'];
|
|
2648
|
-
delete response?.['Message-ID'];
|
|
2649
|
-
}
|
|
2650
|
-
if (response?.messageId) {
|
|
2651
|
-
response.messageId = [].concat(response?.messageId || []).map(value => (value || '').toString().trim().replace(/^<?/, '<').replace(/>?$/, '>'));
|
|
2652
|
-
}
|
|
2653
|
-
|
|
2654
|
-
if (response?.answer) {
|
|
2655
|
-
if (typeof response.answer === 'object') {
|
|
2656
|
-
response.answer = JSON.stringify(response.answer);
|
|
2657
|
-
} else {
|
|
2658
|
-
response.answer = response.answer.toString();
|
|
2659
|
-
}
|
|
2660
|
-
}
|
|
2661
|
-
|
|
2662
|
-
// Clean internal properties
|
|
2663
|
-
for (const key of Object.keys(response)) {
|
|
2664
|
-
if (/^_/.test(key)) {
|
|
2665
|
-
delete response[key];
|
|
2666
|
-
}
|
|
2667
|
-
}
|
|
2668
|
-
|
|
2669
|
-
return response;
|
|
2670
|
-
}
|
|
2671
|
-
|
|
2672
|
-
case 'questionQuery': {
|
|
2673
|
-
let requestOpts = openAiRequestOpts();
|
|
2674
2768
|
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
}
|
|
2680
|
-
|
|
2681
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2682
|
-
if (openAiAPIUrl) {
|
|
2683
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2684
|
-
}
|
|
2685
|
-
|
|
2686
|
-
let openAiModel = message.data.openAiModel || 'gpt-3.5-turbo-instruct';
|
|
2687
|
-
if (openAiModel) {
|
|
2688
|
-
requestOpts.gptModel = openAiModel;
|
|
2689
|
-
}
|
|
2690
|
-
|
|
2691
|
-
requestOpts.user = message.data.account;
|
|
2692
|
-
|
|
2693
|
-
let response = await questionQuery(message.data.question, openAiAPIKey, requestOpts);
|
|
2694
|
-
|
|
2695
|
-
// Clean internal properties
|
|
2696
|
-
for (const key of Object.keys(response)) {
|
|
2697
|
-
if (/^_/.test(key)) {
|
|
2698
|
-
delete response[key];
|
|
2769
|
+
return response;
|
|
2770
|
+
} catch (err) {
|
|
2771
|
+
if (counted) {
|
|
2772
|
+
metrics.aiRequests.inc({ model, status: 'failure' });
|
|
2699
2773
|
}
|
|
2774
|
+
throw err;
|
|
2700
2775
|
}
|
|
2701
|
-
|
|
2702
|
-
return response;
|
|
2703
|
-
}
|
|
2704
|
-
|
|
2705
|
-
case 'generateChunkEmbeddings': {
|
|
2706
|
-
let requestOpts = openAiRequestOpts();
|
|
2707
|
-
|
|
2708
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2709
|
-
|
|
2710
|
-
if (!openAiAPIKey) {
|
|
2711
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2712
|
-
}
|
|
2713
|
-
|
|
2714
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2715
|
-
if (openAiAPIUrl) {
|
|
2716
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2717
|
-
}
|
|
2718
|
-
|
|
2719
|
-
requestOpts.user = message.data.account;
|
|
2720
|
-
|
|
2721
|
-
const data = await getChunkEmbeddings(message.data.message, openAiAPIKey, requestOpts);
|
|
2722
|
-
|
|
2723
|
-
return data;
|
|
2724
2776
|
}
|
|
2725
2777
|
|
|
2726
2778
|
case 'openAiListModels': {
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2730
|
-
|
|
2731
|
-
if (!openAiAPIKey) {
|
|
2732
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2733
|
-
}
|
|
2734
|
-
|
|
2735
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2736
|
-
if (openAiAPIUrl) {
|
|
2737
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2738
|
-
}
|
|
2739
|
-
|
|
2740
|
-
requestOpts.user = message.data.account;
|
|
2741
|
-
|
|
2742
|
-
const data = await openAiListModels(openAiAPIKey, requestOpts);
|
|
2743
|
-
|
|
2744
|
-
return data;
|
|
2745
|
-
}
|
|
2746
|
-
|
|
2747
|
-
case 'openAiDefaultPrompt': {
|
|
2748
|
-
return openAiDefaultPrompt;
|
|
2779
|
+
const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
|
|
2780
|
+
return await withRequestDeadline(message, signal => openAiListModels(openAiAPIKey, Object.assign(requestOpts, { signal })));
|
|
2749
2781
|
}
|
|
2750
2782
|
|
|
2751
2783
|
case 'threads': {
|
|
@@ -2833,23 +2865,14 @@ async function onCommand(worker, message) {
|
|
|
2833
2865
|
// Guarded for the same reason as the `new` branch above, and here the throw was
|
|
2834
2866
|
// answered with a 500 for a deletion that had in fact succeeded: the account was
|
|
2835
2867
|
// already gone from Redis by the time this message was sent.
|
|
2836
|
-
|
|
2837
|
-
unassigned
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
if (!workerAssigned.get(assignedWorker).size) {
|
|
2844
|
-
// Last account on this worker
|
|
2845
|
-
workerAssigned.delete(assignedWorker);
|
|
2846
|
-
}
|
|
2868
|
+
{
|
|
2869
|
+
let assignedWorker = forgetAccount({ workerAssigned, assigned, unassigned }, message.account);
|
|
2870
|
+
if (assignedWorker) {
|
|
2871
|
+
// Notify worker to clean up
|
|
2872
|
+
call(assignedWorker, message)
|
|
2873
|
+
.then(() => logger.debug('Account cleanup completed'))
|
|
2874
|
+
.catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
|
|
2847
2875
|
}
|
|
2848
|
-
|
|
2849
|
-
// Notify worker to clean up
|
|
2850
|
-
call(assignedWorker, message)
|
|
2851
|
-
.then(() => logger.debug('Account cleanup completed'))
|
|
2852
|
-
.catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
|
|
2853
2876
|
}
|
|
2854
2877
|
sendWebhook(message.account, ACCOUNT_DELETED_NOTIFY, { account: message.account }).catch(err =>
|
|
2855
2878
|
logger.error({ msg: 'Account deletion webhook failed', account: message.account, err })
|
|
@@ -3022,17 +3045,35 @@ async function onCommand(worker, message) {
|
|
|
3022
3045
|
}
|
|
3023
3046
|
|
|
3024
3047
|
// Metrics collection results
|
|
3025
|
-
|
|
3048
|
+
// Connection states published so far, so a state no account is in any more is reported as 0
|
|
3049
|
+
// instead of keeping its last value
|
|
3050
|
+
let publishedConnectionStates = new Set();
|
|
3051
|
+
let collectingMetrics = false;
|
|
3026
3052
|
|
|
3027
3053
|
/**
|
|
3028
3054
|
* Collect IMAP connection metrics from all workers
|
|
3029
3055
|
* @returns {Promise<void>}
|
|
3030
3056
|
*/
|
|
3031
3057
|
async function collectMetrics() {
|
|
3032
|
-
//
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3058
|
+
// Runs every second but awaits a countConnections call per worker, each allowed the full command
|
|
3059
|
+
// timeout. Overlapping runs used to add into one shared result object while another run zeroed
|
|
3060
|
+
// it, so the gauge reported doubled or partial counts exactly when a worker was slow.
|
|
3061
|
+
if (collectingMetrics) {
|
|
3062
|
+
return;
|
|
3063
|
+
}
|
|
3064
|
+
collectingMetrics = true;
|
|
3065
|
+
try {
|
|
3066
|
+
await collectConnectionMetrics();
|
|
3067
|
+
} finally {
|
|
3068
|
+
collectingMetrics = false;
|
|
3069
|
+
}
|
|
3070
|
+
}
|
|
3071
|
+
|
|
3072
|
+
async function collectConnectionMetrics() {
|
|
3073
|
+
let metricsResult = {};
|
|
3074
|
+
for (let status of publishedConnectionStates) {
|
|
3075
|
+
metricsResult[status] = 0;
|
|
3076
|
+
}
|
|
3036
3077
|
|
|
3037
3078
|
// Subscription state counters
|
|
3038
3079
|
let subscriptionResults = { valid: 0, expired: 0, unset: 0, failed: 0, pending: 0 };
|
|
@@ -3077,6 +3118,7 @@ async function collectMetrics() {
|
|
|
3077
3118
|
|
|
3078
3119
|
// Update Prometheus metrics for connections
|
|
3079
3120
|
Object.keys(metricsResult).forEach(status => {
|
|
3121
|
+
publishedConnectionStates.add(status);
|
|
3080
3122
|
metrics.imapConnections.set({ status }, metricsResult[status]);
|
|
3081
3123
|
});
|
|
3082
3124
|
|
|
@@ -3111,7 +3153,7 @@ const closeQueues = cb => {
|
|
|
3111
3153
|
}
|
|
3112
3154
|
}
|
|
3113
3155
|
|
|
3114
|
-
for (let name of ['notify', 'submit', '
|
|
3156
|
+
for (let name of ['notify', 'submit', 'export']) {
|
|
3115
3157
|
if (queueEvents[name]) {
|
|
3116
3158
|
proms.push(queueEvents[name].close());
|
|
3117
3159
|
}
|
|
@@ -3573,13 +3615,18 @@ const startApplication = async () => {
|
|
|
3573
3615
|
}
|
|
3574
3616
|
|
|
3575
3617
|
// Start export workers
|
|
3576
|
-
for (let i = 0; i <
|
|
3618
|
+
for (let i = 0; i < config.workers.export; i++) {
|
|
3577
3619
|
await spawnWorker('export');
|
|
3578
3620
|
}
|
|
3579
3621
|
|
|
3580
|
-
//
|
|
3581
|
-
|
|
3582
|
-
|
|
3622
|
+
// The Document Store was removed in 2.82.0. An instance upgraded with it still switched on
|
|
3623
|
+
// is told where the feature went, here and on every admin page (workers/api.js), rather
|
|
3624
|
+
// than losing its search index quietly
|
|
3625
|
+
if (await settings.get('documentStoreEnabled')) {
|
|
3626
|
+
logger.warn({
|
|
3627
|
+
msg: 'The Document Store feature has been removed from EmailEngine. Downgrade if you still need it',
|
|
3628
|
+
lastVersionWithDocumentStore: LAST_DOCUMENT_STORE_VERSION
|
|
3629
|
+
});
|
|
3583
3630
|
}
|
|
3584
3631
|
|
|
3585
3632
|
// Start SMTP proxy if enabled
|
|
@@ -3658,16 +3705,15 @@ startApplication()
|
|
|
3658
3705
|
startHealthMonitoring();
|
|
3659
3706
|
|
|
3660
3707
|
// Initialize queue event listeners
|
|
3661
|
-
|
|
3662
|
-
|
|
3663
|
-
|
|
3664
|
-
queueEvents.export = new QueueEvents('export', Object.assign({}, queueConf));
|
|
3708
|
+
for (let name of ['notify', 'submit', 'export']) {
|
|
3709
|
+
queueEvents[name] = logBullErrors(new QueueEvents(name, Object.assign({}, queueConf)), `queueEvents:${name}`);
|
|
3710
|
+
}
|
|
3665
3711
|
|
|
3666
3712
|
// Periodic queue cleanup (every 6 hours)
|
|
3667
3713
|
const QUEUE_CLEANUP_INTERVAL = 6 * 60 * 60 * 1000;
|
|
3668
3714
|
|
|
3669
3715
|
async function cleanupQueues() {
|
|
3670
|
-
const queues = [notifyQueue, submitQueue,
|
|
3716
|
+
const queues = [notifyQueue, submitQueue, exportQueue];
|
|
3671
3717
|
for (const queue of queues) {
|
|
3672
3718
|
try {
|
|
3673
3719
|
// Clean completed jobs older than 24 hours
|