emailengine-app 2.81.1 → 2.82.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 +12 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +52 -0
- package/Dockerfile +4 -2
- package/bin/emailengine.js +28 -18
- 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/bounce-store-sweep.js +63 -0
- package/lib/account/expected-identity.js +1 -1
- package/lib/account-assignment.js +207 -0
- package/lib/account.js +374 -878
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-routes.js +18 -29
- 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 +5 -14
- 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 +44 -236
- 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 +2 -2
- 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 +19 -19
- 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 +27 -5
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +41 -7
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +163 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +51 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +76 -17
- package/lib/delivery-error.js +2 -1
- 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 +628 -615
- 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 +170 -84
- package/lib/email-client/imap/mailbox.js +244 -535
- 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 +188 -64
- package/lib/email-client/message-builder.js +9 -14
- 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 +519 -617
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +1 -2
- package/lib/export.js +144 -41
- package/lib/gateway.js +20 -6
- package/lib/get-raw-email.js +26 -44
- 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 +13 -0
- package/lib/message-port-stream.js +64 -6
- package/lib/msgpack.js +1 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +22 -20
- package/lib/oauth/outlook.js +19 -16
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +4 -7
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +139 -44
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- 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/rate-limit.js +54 -15
- 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 +129 -262
- 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/tools.js +113 -52
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +27 -63
- 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 +80 -214
- package/lib/ui-routes/route-helpers.js +40 -44
- 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 +2 -0
- 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 +340 -336
- 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 +460 -1861
- package/translations/messages.pot +99 -99
- package/views/accounts/browse.hbs +10 -4
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- 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/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 +33 -23
- package/workers/export.js +55 -60
- package/workers/imap.js +134 -47
- package/workers/submit.js +3 -1
- 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/append-list.js +0 -63
- 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/lua/h-push.lua +0 -32
- 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');
|
|
@@ -127,7 +128,7 @@ const { settingsSchema } = require('./lib/schemas');
|
|
|
127
128
|
const settings = require('./lib/settings');
|
|
128
129
|
const { oauth2Apps } = require('./lib/oauth2-apps');
|
|
129
130
|
const { backfillAuthFailureDisabled } = require('./lib/account/auth-failure-backfill');
|
|
130
|
-
const {
|
|
131
|
+
const { sweepBounceStore } = require('./lib/account/bounce-store-sweep');
|
|
131
132
|
const { attachBeacon, persistBeaconMarkers } = require('./lib/license-beacon');
|
|
132
133
|
const tokens = require('./lib/tokens');
|
|
133
134
|
|
|
@@ -138,6 +139,16 @@ const { QueueEvents } = require('bullmq');
|
|
|
138
139
|
const getSecret = require('./lib/get-secret');
|
|
139
140
|
|
|
140
141
|
const { rejectWorkerCalls } = require('./lib/reject-worker-calls');
|
|
142
|
+
const {
|
|
143
|
+
pickLeastLoadedWorker,
|
|
144
|
+
rollbackAssignment,
|
|
145
|
+
releaseWorkerAccounts,
|
|
146
|
+
requeueFailedAccounts,
|
|
147
|
+
forgetAccount,
|
|
148
|
+
mapConcurrent,
|
|
149
|
+
shouldRequeueFailedAssignment,
|
|
150
|
+
planRebalance
|
|
151
|
+
} = require('./lib/account-assignment');
|
|
141
152
|
const { RespawnTracker } = require('./lib/respawn-backoff');
|
|
142
153
|
|
|
143
154
|
const msgpack = require('./lib/msgpack');
|
|
@@ -329,7 +340,6 @@ const THREAD_NAMES = {
|
|
|
329
340
|
api: 'HTTP and API server',
|
|
330
341
|
submit: 'Email sending worker',
|
|
331
342
|
export: 'Export worker',
|
|
332
|
-
documents: 'Document store indexing worker',
|
|
333
343
|
imapProxy: 'IMAP proxy server',
|
|
334
344
|
smtp: 'SMTP proxy server'
|
|
335
345
|
};
|
|
@@ -593,6 +603,18 @@ const metrics = {
|
|
|
593
603
|
labelNames: ['event']
|
|
594
604
|
}),
|
|
595
605
|
|
|
606
|
+
aiRequests: new promClient.Counter({
|
|
607
|
+
name: 'ai_requests',
|
|
608
|
+
help: 'AI summary requests',
|
|
609
|
+
labelNames: ['model', 'status']
|
|
610
|
+
}),
|
|
611
|
+
|
|
612
|
+
aiTokens: new promClient.Counter({
|
|
613
|
+
name: 'ai_tokens',
|
|
614
|
+
help: 'Tokens billed for AI summary requests',
|
|
615
|
+
labelNames: ['model', 'type']
|
|
616
|
+
}),
|
|
617
|
+
|
|
596
618
|
webhookReq: new promClient.Histogram({
|
|
597
619
|
name: 'webhook_req',
|
|
598
620
|
help: 'Duration of webhook requests',
|
|
@@ -745,6 +767,8 @@ let mids = 0; // Message ID counter
|
|
|
745
767
|
// Application state flags
|
|
746
768
|
let isClosing = false; // Is the application shutting down?
|
|
747
769
|
let assigning = false; // Is account assignment in progress?
|
|
770
|
+
// Unassign calls in flight at once while rebalanceOnto() holds the assignment lock
|
|
771
|
+
const REBALANCE_CONCURRENCY = 8;
|
|
748
772
|
|
|
749
773
|
// Account assignment tracking
|
|
750
774
|
let unassigned = false; // Set of unassigned accounts
|
|
@@ -759,7 +783,8 @@ const MAX_ASSIGN_RETRIES = 3; // Max consecutive safety-net retries before givin
|
|
|
759
783
|
// Worker management
|
|
760
784
|
let imapInitialWorkersLoaded = false; // Have all initial IMAP workers started?
|
|
761
785
|
let workers = new Map(); // Map of type -> Set of workers
|
|
762
|
-
const respawnTracker = new RespawnTracker(); // paces respawns for worker
|
|
786
|
+
const respawnTracker = new RespawnTracker(); // paces respawns for worker slots that keep crashing
|
|
787
|
+
let spawnSlotCounter = 0; // source of respawn slot ids, see spawnWorker()
|
|
763
788
|
|
|
764
789
|
// Shutdown drain budget. A worker with no in-flight job answers immediately, so this only costs
|
|
765
790
|
// real time when there is genuinely something to finish - which is exactly when waiting is worth
|
|
@@ -1074,13 +1099,15 @@ async function sendWebhook(account, event, data) {
|
|
|
1074
1099
|
|
|
1075
1100
|
/**
|
|
1076
1101
|
* Spawn a new worker thread of the specified type
|
|
1077
|
-
* @param {string} type - Worker type (imap, api, webhooks, submit,
|
|
1102
|
+
* @param {string} type - Worker type (imap, api, webhooks, submit, export, smtp, imapProxy)
|
|
1078
1103
|
* @param {Object} [opts] - Optional spawn options
|
|
1079
1104
|
* @param {Object} [opts.workerData] - Data passed to the worker thread (e.g. API worker index). The
|
|
1080
1105
|
* proxy in effect is added for every type, see lib/tools.js
|
|
1106
|
+
* @param {string} [slot] - Respawn slot this thread fills. A respawn passes its predecessor's slot
|
|
1107
|
+
* so the crash streak is counted per slot, not per worker type
|
|
1081
1108
|
* @returns {Promise<number|void>} Thread ID if successful
|
|
1082
1109
|
*/
|
|
1083
|
-
let spawnWorker = async (type, opts) => {
|
|
1110
|
+
let spawnWorker = async (type, opts, slot) => {
|
|
1084
1111
|
// Don't spawn workers during shutdown
|
|
1085
1112
|
if (isClosing) {
|
|
1086
1113
|
return;
|
|
@@ -1110,6 +1137,13 @@ let spawnWorker = async (type, opts) => {
|
|
|
1110
1137
|
await updateServerState(type, 'spawning');
|
|
1111
1138
|
}
|
|
1112
1139
|
|
|
1140
|
+
// A fresh spawn opens its own slot. Counting the crash streak per type made every short-lived
|
|
1141
|
+
// exit of ANY IMAP worker double the next respawn delay of all of them, so unrelated exits
|
|
1142
|
+
// pushed a restart past the 10s failsafe reassignment.
|
|
1143
|
+
if (!slot) {
|
|
1144
|
+
slot = `${type}:${++spawnSlotCounter}`;
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1113
1147
|
// Create new worker thread
|
|
1114
1148
|
let spawnedAt = Date.now();
|
|
1115
1149
|
let worker = new WorkerThread(pathlib.join(__dirname, 'workers', `${type.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}.js`), {
|
|
@@ -1186,7 +1220,12 @@ let spawnWorker = async (type, opts) => {
|
|
|
1186
1220
|
|
|
1187
1221
|
// Update server state for proxy servers
|
|
1188
1222
|
if (['smtp', 'imapProxy'].includes(type)) {
|
|
1189
|
-
|
|
1223
|
+
// Not awaited, so the rejection has to be handled here: a Redis reply error
|
|
1224
|
+
// (OOM, READONLY) would otherwise reach the global handler and take the whole
|
|
1225
|
+
// process down with it.
|
|
1226
|
+
updateServerState(type, suspendedWorkerTypes.has(type) ? 'suspended' : 'exited').catch(err =>
|
|
1227
|
+
logger.error({ msg: 'Unable to update server state', type, err })
|
|
1228
|
+
);
|
|
1190
1229
|
}
|
|
1191
1230
|
|
|
1192
1231
|
// Handle IMAP worker cleanup
|
|
@@ -1194,15 +1233,8 @@ let spawnWorker = async (type, opts) => {
|
|
|
1194
1233
|
availableIMAPWorkers.delete(worker);
|
|
1195
1234
|
|
|
1196
1235
|
// Reassign accounts from dead worker
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
workerAssigned.delete(worker);
|
|
1200
|
-
|
|
1201
|
-
for (let account of accountList) {
|
|
1202
|
-
assigned.delete(account);
|
|
1203
|
-
unassigned.add(account);
|
|
1204
|
-
}
|
|
1205
|
-
|
|
1236
|
+
let accountList = releaseWorkerAccounts({ workerAssigned, assigned, unassigned }, worker);
|
|
1237
|
+
if (accountList) {
|
|
1206
1238
|
logger[exitLevel]({
|
|
1207
1239
|
msg: 'Worker exited, moving accounts to unassigned',
|
|
1208
1240
|
accounts: accountList.size,
|
|
@@ -1294,13 +1326,13 @@ let spawnWorker = async (type, opts) => {
|
|
|
1294
1326
|
// Respawn worker after delay, preserving any spawn options (e.g. API worker index).
|
|
1295
1327
|
// The delay grows while a worker type keeps dying on startup, so a deterministic
|
|
1296
1328
|
// crash no longer respawns once a second forever.
|
|
1297
|
-
let respawnDelay = respawnTracker.recordExit(
|
|
1298
|
-
let streak = respawnTracker.streakFor(
|
|
1329
|
+
let respawnDelay = respawnTracker.recordExit(slot, Date.now() - spawnedAt);
|
|
1330
|
+
let streak = respawnTracker.streakFor(slot);
|
|
1299
1331
|
if (streak > 1) {
|
|
1300
|
-
logger.warn({ msg: 'Worker is crash looping, delaying respawn', type, consecutiveFailures: streak, respawnDelay });
|
|
1332
|
+
logger.warn({ msg: 'Worker is crash looping, delaying respawn', type, slot, consecutiveFailures: streak, respawnDelay });
|
|
1301
1333
|
}
|
|
1302
1334
|
await new Promise(r => setTimeout(r, respawnDelay));
|
|
1303
|
-
await spawnWorker(type, opts);
|
|
1335
|
+
await spawnWorker(type, opts, slot);
|
|
1304
1336
|
};
|
|
1305
1337
|
|
|
1306
1338
|
// Handle worker exit
|
|
@@ -1480,9 +1512,16 @@ let spawnWorker = async (type, opts) => {
|
|
|
1480
1512
|
redis.hincrby(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
|
|
1481
1513
|
}
|
|
1482
1514
|
|
|
1483
|
-
// Update Prometheus metrics
|
|
1515
|
+
// Update Prometheus metrics. prom-client throws synchronously on an unknown
|
|
1516
|
+
// label, a negative counter increment or a non-finite value, and this runs in
|
|
1517
|
+
// an event handler on the main thread, where a throw would take every worker
|
|
1518
|
+
// down with it.
|
|
1484
1519
|
if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
|
|
1485
|
-
|
|
1520
|
+
try {
|
|
1521
|
+
metrics[message.key][message.method](...message.args);
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
logger.error({ msg: 'Unable to apply worker metric', type, key: message.key, method: message.method, err });
|
|
1524
|
+
}
|
|
1486
1525
|
}
|
|
1487
1526
|
|
|
1488
1527
|
return;
|
|
@@ -1604,6 +1643,10 @@ let spawnWorker = async (type, opts) => {
|
|
|
1604
1643
|
unassignedAccounts: unassigned.size
|
|
1605
1644
|
});
|
|
1606
1645
|
}
|
|
1646
|
+
} else if (imapInitialWorkersLoaded) {
|
|
1647
|
+
// The failsafe timer already gave this worker's accounts to the
|
|
1648
|
+
// survivors (or it is an extra worker), so nothing is pending for it
|
|
1649
|
+
rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err }));
|
|
1607
1650
|
}
|
|
1608
1651
|
}
|
|
1609
1652
|
break;
|
|
@@ -1702,6 +1745,95 @@ async function call(worker, message, transferList) {
|
|
|
1702
1745
|
});
|
|
1703
1746
|
}
|
|
1704
1747
|
|
|
1748
|
+
/**
|
|
1749
|
+
* Whether an account is still registered, checked before a failed assignment is retried
|
|
1750
|
+
* @param {string} account
|
|
1751
|
+
* @returns {Promise<boolean>}
|
|
1752
|
+
*/
|
|
1753
|
+
async function isRegisteredAccount(account) {
|
|
1754
|
+
return !!(await redis.sismember(`${REDIS_PREFIX}ia:accounts`, account));
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/**
|
|
1758
|
+
* Tells an IMAP worker to close an account without deleting anything, used when the account moves
|
|
1759
|
+
* to another worker. Returns whether the worker confirmed it
|
|
1760
|
+
* @param {Worker} worker
|
|
1761
|
+
* @param {string} account
|
|
1762
|
+
* @returns {Promise<boolean>}
|
|
1763
|
+
*/
|
|
1764
|
+
async function unassignFromWorker(worker, account) {
|
|
1765
|
+
if (!onlineWorkers.has(worker)) {
|
|
1766
|
+
// An exited worker holds no connections
|
|
1767
|
+
return true;
|
|
1768
|
+
}
|
|
1769
|
+
try {
|
|
1770
|
+
await call(worker, { cmd: 'unassign', account });
|
|
1771
|
+
return true;
|
|
1772
|
+
} catch (err) {
|
|
1773
|
+
logger.error({ msg: 'Failed to unassign account from worker', account, threadId: worker.threadId, err });
|
|
1774
|
+
return false;
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
/**
|
|
1779
|
+
* Moves a fair share of accounts onto an IMAP worker that became ready while the rest of the fleet
|
|
1780
|
+
* already served every account. That is the normal outcome of a restart slower than the failsafe
|
|
1781
|
+
* reassignment timer, and nothing else ever gives such a worker any accounts
|
|
1782
|
+
* @param {Worker} worker - The worker that became ready
|
|
1783
|
+
* @returns {Promise<void>}
|
|
1784
|
+
*/
|
|
1785
|
+
async function rebalanceOnto(worker) {
|
|
1786
|
+
if (isClosing || !availableIMAPWorkers.has(worker)) {
|
|
1787
|
+
return;
|
|
1788
|
+
}
|
|
1789
|
+
if (assigning) {
|
|
1790
|
+
// A pass is running (typically the failsafe one); look again once it has settled
|
|
1791
|
+
setTimeout(() => rebalanceOnto(worker).catch(err => logger.error({ msg: 'Unable to rebalance accounts', err })), 5000).unref();
|
|
1792
|
+
return;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
let moves = planRebalance({ workerAssigned, availableWorkers: availableIMAPWorkers }, worker);
|
|
1796
|
+
if (!moves.length) {
|
|
1797
|
+
return;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
assigning = true;
|
|
1801
|
+
let moved = 0;
|
|
1802
|
+
try {
|
|
1803
|
+
// Every other assignment pass waits on the lock held here, and a fair share of a large
|
|
1804
|
+
// fleet is hundreds of round trips, so the unassign calls run a few at a time rather than
|
|
1805
|
+
// one after the other
|
|
1806
|
+
await mapConcurrent(moves, REBALANCE_CONCURRENCY, async ({ account, worker: donor }) => {
|
|
1807
|
+
// The donor may have lost the account (deleted, donor exited) while we awaited
|
|
1808
|
+
if (assigned.get(account) !== donor) {
|
|
1809
|
+
return;
|
|
1810
|
+
}
|
|
1811
|
+
// Only an account the donor has let go of can move, or it would sync in two workers
|
|
1812
|
+
if (!(await unassignFromWorker(donor, account))) {
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
if (assigned.get(account) !== donor) {
|
|
1816
|
+
return;
|
|
1817
|
+
}
|
|
1818
|
+
forgetAccount({ workerAssigned, assigned, unassigned }, account);
|
|
1819
|
+
unassigned.add(account);
|
|
1820
|
+
moved++;
|
|
1821
|
+
});
|
|
1822
|
+
} finally {
|
|
1823
|
+
assigning = false;
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
if (moved) {
|
|
1827
|
+
logger.info({ msg: 'Rebalancing accounts onto a restarted IMAP worker', threadId: worker.threadId, accounts: moved });
|
|
1828
|
+
}
|
|
1829
|
+
// Also run when nothing moved: an account added while this held the assignment lock found the
|
|
1830
|
+
// pass refused and is waiting in unassigned. Every worker is available again, so the pass
|
|
1831
|
+
// picks the least loaded one, which is the newcomer.
|
|
1832
|
+
if (moved || unassigned.size) {
|
|
1833
|
+
await assignAccounts();
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1705
1837
|
/**
|
|
1706
1838
|
* Assign unassigned accounts to available IMAP workers
|
|
1707
1839
|
* Uses load-aware distribution with round-robin for initial assignment
|
|
@@ -1715,6 +1847,11 @@ async function assignAccounts() {
|
|
|
1715
1847
|
}
|
|
1716
1848
|
|
|
1717
1849
|
assigning = true;
|
|
1850
|
+
// Collect accounts that fail assignment so we do not re-insert into
|
|
1851
|
+
// the Set we are iterating (re-insertion during for..of would cause
|
|
1852
|
+
// the same account to be visited again in the same pass). Returned to
|
|
1853
|
+
// unassigned in the finally block, so no throw can strand them.
|
|
1854
|
+
let failedAccounts = [];
|
|
1718
1855
|
try {
|
|
1719
1856
|
if (!unassigned) {
|
|
1720
1857
|
// First run - load all accounts from Redis
|
|
@@ -1741,20 +1878,10 @@ async function assignAccounts() {
|
|
|
1741
1878
|
workerLoadMap.set(worker, accountCount);
|
|
1742
1879
|
}
|
|
1743
1880
|
|
|
1744
|
-
// Sort workers by load (ascending) for even distribution
|
|
1745
|
-
let sortedWorkers = Array.from(workerLoadMap.entries())
|
|
1746
|
-
.sort((a, b) => a[1] - b[1])
|
|
1747
|
-
.map(entry => entry[0]);
|
|
1748
|
-
|
|
1749
1881
|
// Calculate target accounts per worker for even distribution
|
|
1750
1882
|
let totalAccounts = assigned.size + unassigned.size;
|
|
1751
1883
|
let targetPerWorker = Math.ceil(totalAccounts / availableIMAPWorkers.size);
|
|
1752
1884
|
|
|
1753
|
-
// Collect accounts that fail assignment so we do not re-insert into
|
|
1754
|
-
// the Set we are iterating (re-insertion during for..of would cause
|
|
1755
|
-
// the same account to be visited again in the same pass).
|
|
1756
|
-
let failedAccounts = [];
|
|
1757
|
-
|
|
1758
1885
|
// Assign each unassigned account
|
|
1759
1886
|
for (let account of unassigned) {
|
|
1760
1887
|
if (!availableIMAPWorkers.size) {
|
|
@@ -1773,24 +1900,12 @@ async function assignAccounts() {
|
|
|
1773
1900
|
// Use rendezvous hashing for consistent reassignment after failures
|
|
1774
1901
|
worker = selectRendezvousNode(account, Array.from(availableIMAPWorkers));
|
|
1775
1902
|
} else {
|
|
1776
|
-
// Use load-aware round-robin for initial assignment
|
|
1777
|
-
//
|
|
1778
|
-
worker =
|
|
1779
|
-
let currentLoad = workerLoadMap.get(w) || 0;
|
|
1780
|
-
return currentLoad < targetPerWorker;
|
|
1781
|
-
});
|
|
1782
|
-
|
|
1783
|
-
// If all workers reached target, use the least loaded one
|
|
1784
|
-
if (!worker) {
|
|
1785
|
-
worker = sortedWorkers[0];
|
|
1786
|
-
}
|
|
1903
|
+
// Use load-aware round-robin for initial assignment: the least loaded running
|
|
1904
|
+
// worker that hasn't reached the target, else the least loaded one
|
|
1905
|
+
worker = pickLeastLoadedWorker(availableIMAPWorkers, workerLoadMap, targetPerWorker);
|
|
1787
1906
|
|
|
1788
1907
|
// Update the load map for next iteration
|
|
1789
1908
|
workerLoadMap.set(worker, (workerLoadMap.get(worker) || 0) + 1);
|
|
1790
|
-
// Re-sort workers by updated load
|
|
1791
|
-
sortedWorkers = Array.from(workerLoadMap.entries())
|
|
1792
|
-
.sort((a, b) => a[1] - b[1])
|
|
1793
|
-
.map(entry => entry[0]);
|
|
1794
1909
|
}
|
|
1795
1910
|
|
|
1796
1911
|
// Track assignment
|
|
@@ -1810,18 +1925,25 @@ async function assignAccounts() {
|
|
|
1810
1925
|
runIndex
|
|
1811
1926
|
});
|
|
1812
1927
|
} catch (err) {
|
|
1813
|
-
// Roll back -- account was never actually assigned
|
|
1814
|
-
|
|
1815
|
-
assigned
|
|
1816
|
-
|
|
1817
|
-
if (
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1928
|
+
// Roll back -- account was never actually assigned. Also reverts the load map so
|
|
1929
|
+
// subsequent iterations see accurate counts
|
|
1930
|
+
rollbackAssignment({ workerAssigned, assigned, workerLoadMap }, account, worker, !isReassignment);
|
|
1931
|
+
|
|
1932
|
+
if (err.code === 'Timeout') {
|
|
1933
|
+
// A timed-out assign is still running in the worker and would connect the
|
|
1934
|
+
// account there after this pass has handed it to another worker, so the same
|
|
1935
|
+
// account would sync twice. Cancel it; the worker also drops an assignment
|
|
1936
|
+
// superseded this way, see assignConnection().
|
|
1937
|
+
unassignFromWorker(worker, account);
|
|
1822
1938
|
}
|
|
1823
|
-
|
|
1939
|
+
|
|
1824
1940
|
logger.error({ msg: 'Failed to assign account to worker', account, threadId: worker.threadId, err });
|
|
1941
|
+
|
|
1942
|
+
if (await shouldRequeueFailedAssignment(err, account, isRegisteredAccount)) {
|
|
1943
|
+
failedAccounts.push(account);
|
|
1944
|
+
} else {
|
|
1945
|
+
logger.info({ msg: 'Dropped assignment of an account that no longer exists', account });
|
|
1946
|
+
}
|
|
1825
1947
|
continue;
|
|
1826
1948
|
}
|
|
1827
1949
|
|
|
@@ -1831,11 +1953,6 @@ async function assignAccounts() {
|
|
|
1831
1953
|
}
|
|
1832
1954
|
}
|
|
1833
1955
|
|
|
1834
|
-
// Re-add failed accounts after iteration completes
|
|
1835
|
-
for (let account of failedAccounts) {
|
|
1836
|
-
unassigned.add(account);
|
|
1837
|
-
}
|
|
1838
|
-
|
|
1839
1956
|
// Log final distribution for monitoring
|
|
1840
1957
|
let distribution = [];
|
|
1841
1958
|
for (let worker of availableIMAPWorkers) {
|
|
@@ -1848,6 +1965,9 @@ async function assignAccounts() {
|
|
|
1848
1965
|
totalAssigned: assigned.size
|
|
1849
1966
|
});
|
|
1850
1967
|
} finally {
|
|
1968
|
+
// Re-add failed accounts after iteration completes
|
|
1969
|
+
requeueFailedAccounts({ assigned, unassigned }, failedAccounts);
|
|
1970
|
+
|
|
1851
1971
|
assigning = false;
|
|
1852
1972
|
|
|
1853
1973
|
// Safety net: if accounts remain unassigned, schedule a retry with backoff
|
|
@@ -2097,14 +2217,15 @@ let upgradeCheckTimer = false;
|
|
|
2097
2217
|
* @returns {Promise<void>}
|
|
2098
2218
|
*/
|
|
2099
2219
|
let upgradeCheckHandler = async () => {
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2220
|
+
// An up-to-date instance keeps checking too. The check used to return early, before
|
|
2221
|
+
// rescheduling, whenever no upgrade was already known, so the daily check stopped after its
|
|
2222
|
+
// first run on every instance that was current at the time.
|
|
2223
|
+
try {
|
|
2224
|
+
await processCheckUpgrade();
|
|
2225
|
+
} finally {
|
|
2226
|
+
upgradeCheckTimer = setTimeout(checkUpgrade, UPGRADE_CHECK_TIMEOUT);
|
|
2227
|
+
upgradeCheckTimer.unref();
|
|
2104
2228
|
}
|
|
2105
|
-
await processCheckUpgrade();
|
|
2106
|
-
upgradeCheckTimer = setTimeout(checkUpgrade, UPGRADE_CHECK_TIMEOUT);
|
|
2107
|
-
upgradeCheckTimer.unref();
|
|
2108
2229
|
};
|
|
2109
2230
|
|
|
2110
2231
|
/**
|
|
@@ -2188,7 +2309,8 @@ const processRedisPing = async () => {
|
|
|
2188
2309
|
redisPingCounter.push(duration);
|
|
2189
2310
|
// Keep last 300 measurements
|
|
2190
2311
|
if (redisPingCounter.length > 300) {
|
|
2191
|
-
|
|
2312
|
+
// keep the newest samples, the average is computed from the tail
|
|
2313
|
+
redisPingCounter = redisPingCounter.slice(-150);
|
|
2192
2314
|
}
|
|
2193
2315
|
return duration;
|
|
2194
2316
|
} catch (err) {
|
|
@@ -2292,8 +2414,7 @@ async function updateQueueCounters() {
|
|
|
2292
2414
|
// gauge is kept at the 0 the getter reports so existing dashboards keep their series.
|
|
2293
2415
|
for (let [queue, queueObj] of [
|
|
2294
2416
|
['notify', notifyQueue],
|
|
2295
|
-
['submit', submitQueue]
|
|
2296
|
-
['documents', documentsQueue]
|
|
2417
|
+
['submit', submitQueue]
|
|
2297
2418
|
]) {
|
|
2298
2419
|
let stats;
|
|
2299
2420
|
try {
|
|
@@ -2381,6 +2502,66 @@ const openAiRequestOpts = () => ({
|
|
|
2381
2502
|
dispatcher: httpAgent.fetch
|
|
2382
2503
|
});
|
|
2383
2504
|
|
|
2505
|
+
const aiValueSet = value => value !== undefined && value !== null && value !== '';
|
|
2506
|
+
|
|
2507
|
+
/**
|
|
2508
|
+
* Options for one request to the AI provider. The configuration page's test sends every field as
|
|
2509
|
+
* its form shows it, so the test runs with what the page shows; the sync path sends none and gets
|
|
2510
|
+
* the stored settings. The key is the exception: the form leaves it blank to keep the stored one
|
|
2511
|
+
* @param {Object} data - The command's data
|
|
2512
|
+
* @returns {Promise<{openAiAPIKey: string, requestOpts: Object}>}
|
|
2513
|
+
*/
|
|
2514
|
+
async function aiRequestOptions(data) {
|
|
2515
|
+
const stored = await settings.getMulti('openAiAPIKey', ...AI_SETTING_KEYS);
|
|
2516
|
+
const values = data.options || stored;
|
|
2517
|
+
|
|
2518
|
+
const openAiAPIKey = (data.options && data.options.openAiAPIKey) || stored.openAiAPIKey;
|
|
2519
|
+
if (!openAiAPIKey) {
|
|
2520
|
+
throw new Error(`OpenAI API key is not configured`);
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
const requestOpts = openAiRequestOpts();
|
|
2524
|
+
requestOpts.gptModel = aiValueSet(values.openAiModel) ? values.openAiModel : openAiDefaultModel;
|
|
2525
|
+
for (const [key, name] of [
|
|
2526
|
+
['openAiAPIUrl', 'baseApiUrl'],
|
|
2527
|
+
['openAiTemperature', 'temperature'],
|
|
2528
|
+
['openAiTopP', 'topP'],
|
|
2529
|
+
['openAiMaxTokens', 'maxTokens'],
|
|
2530
|
+
['openAiReasoningEffort', 'reasoningEffort'],
|
|
2531
|
+
['openAiPrompt', 'instructions']
|
|
2532
|
+
]) {
|
|
2533
|
+
if (aiValueSet(values[key])) {
|
|
2534
|
+
requestOpts[name] = values[key];
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
// which Authentication-Results header the summary may believe, decided by the worker that
|
|
2539
|
+
// knows the account
|
|
2540
|
+
if (data.trust) {
|
|
2541
|
+
requestOpts.trustedAuthservIds = data.trust.trustedAuthservIds;
|
|
2542
|
+
requestOpts.acceptUnnamedAuthentication = !!data.trust.acceptUnnamedAuthentication;
|
|
2543
|
+
}
|
|
2544
|
+
|
|
2545
|
+
return { openAiAPIKey, requestOpts };
|
|
2546
|
+
}
|
|
2547
|
+
|
|
2548
|
+
/**
|
|
2549
|
+
* Runs a provider request that is aborted when the RPC that asked for it has given up, so it does
|
|
2550
|
+
* not outlive its caller. The timer is cleared as the request ends rather than left to fire later
|
|
2551
|
+
* @param {Object} message - The RPC message, with the caller's timeout
|
|
2552
|
+
* @param {Function} run - Receives the abort signal, returns the request promise
|
|
2553
|
+
*/
|
|
2554
|
+
async function withRequestDeadline(message, run) {
|
|
2555
|
+
const controller = new AbortController();
|
|
2556
|
+
const timer = setTimeout(() => controller.abort(new Error('AI request timed out')), message.timeout || AI_REQUEST_TIMEOUT);
|
|
2557
|
+
timer.unref();
|
|
2558
|
+
try {
|
|
2559
|
+
return await run(controller.signal);
|
|
2560
|
+
} finally {
|
|
2561
|
+
clearTimeout(timer);
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
|
|
2384
2565
|
async function onCommand(worker, message) {
|
|
2385
2566
|
switch (message.cmd) {
|
|
2386
2567
|
case 'metrics':
|
|
@@ -2539,244 +2720,46 @@ async function onCommand(worker, message) {
|
|
|
2539
2720
|
}
|
|
2540
2721
|
return false;
|
|
2541
2722
|
|
|
2542
|
-
// OpenAI integration commands - run in main process
|
|
2723
|
+
// OpenAI integration commands - run in the main process, where the metrics live
|
|
2543
2724
|
case 'generateSummary': {
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2547
|
-
|
|
2548
|
-
if (!openAiAPIKey) {
|
|
2549
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2550
|
-
}
|
|
2551
|
-
|
|
2552
|
-
let openAiModel = message.data.openAiModel || (await settings.get('openAiModel'));
|
|
2553
|
-
if (openAiModel) {
|
|
2554
|
-
requestOpts.gptModel = openAiModel;
|
|
2555
|
-
}
|
|
2556
|
-
|
|
2557
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2558
|
-
if (openAiAPIUrl) {
|
|
2559
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2560
|
-
}
|
|
2561
|
-
|
|
2562
|
-
let openAiTemperature = message.data.openAiTemperature || (await settings.get('openAiTemperature'));
|
|
2563
|
-
if (openAiTemperature) {
|
|
2564
|
-
requestOpts.temperature = openAiTemperature;
|
|
2565
|
-
}
|
|
2566
|
-
|
|
2567
|
-
let openAiTopP = message.data.openAiTopP || (await settings.get('openAiTopP'));
|
|
2568
|
-
if (openAiTopP) {
|
|
2569
|
-
requestOpts.topP = openAiTopP;
|
|
2570
|
-
}
|
|
2571
|
-
|
|
2572
|
-
let openAiMaxTokens = message.data.openAiMaxTokens || (await settings.get('openAiMaxTokens'));
|
|
2573
|
-
if (openAiMaxTokens) {
|
|
2574
|
-
requestOpts.maxTokens = openAiMaxTokens;
|
|
2575
|
-
} else {
|
|
2576
|
-
// Set max tokens based on model
|
|
2577
|
-
switch (openAiModel.substring(0, 5)) {
|
|
2578
|
-
case 'gpt-3':
|
|
2579
|
-
requestOpts.maxTokens = 3000;
|
|
2580
|
-
break;
|
|
2581
|
-
case 'gpt-4':
|
|
2582
|
-
requestOpts.maxTokens = 6500;
|
|
2583
|
-
break;
|
|
2584
|
-
case 'gpt-5':
|
|
2585
|
-
default:
|
|
2586
|
-
requestOpts.maxTokens = 18000;
|
|
2587
|
-
break;
|
|
2588
|
-
}
|
|
2589
|
-
}
|
|
2590
|
-
|
|
2725
|
+
const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
|
|
2591
2726
|
requestOpts.user = message.data.account;
|
|
2592
2727
|
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
}
|
|
2597
|
-
|
|
2598
|
-
return await generateSummary(message.data.message, openAiAPIKey, requestOpts);
|
|
2599
|
-
}
|
|
2600
|
-
|
|
2601
|
-
case 'generateEmbeddings': {
|
|
2602
|
-
let requestOpts = openAiRequestOpts();
|
|
2603
|
-
|
|
2604
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2605
|
-
|
|
2606
|
-
if (!openAiAPIKey) {
|
|
2607
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2608
|
-
}
|
|
2609
|
-
|
|
2610
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2611
|
-
if (openAiAPIUrl) {
|
|
2612
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2613
|
-
}
|
|
2728
|
+
// the configuration page's test runs are not production traffic
|
|
2729
|
+
const counted = !message.data.options;
|
|
2730
|
+
const model = requestOpts.gptModel;
|
|
2614
2731
|
|
|
2615
|
-
|
|
2732
|
+
try {
|
|
2733
|
+
const response = await withRequestDeadline(message, signal =>
|
|
2734
|
+
generateSummary(message.data.message, openAiAPIKey, Object.assign(requestOpts, { signal }))
|
|
2735
|
+
);
|
|
2736
|
+
const { usage } = response;
|
|
2616
2737
|
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
return false;
|
|
2620
|
-
}
|
|
2738
|
+
// the fitted email text the verbose mode adds stays out of the RPC and the log
|
|
2739
|
+
delete usage.text;
|
|
2621
2740
|
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2741
|
+
if (counted) {
|
|
2742
|
+
metrics.aiRequests.inc({ model, status: 'success' });
|
|
2743
|
+
for (const type of ['prompt', 'completion']) {
|
|
2744
|
+
const tokens = usage[`${type}Tokens`];
|
|
2745
|
+
if (tokens) {
|
|
2746
|
+
metrics.aiTokens.inc({ model, type }, tokens);
|
|
2747
|
+
}
|
|
2627
2748
|
}
|
|
2628
2749
|
}
|
|
2629
|
-
}
|
|
2630
|
-
|
|
2631
|
-
return embeddings;
|
|
2632
|
-
}
|
|
2633
|
-
|
|
2634
|
-
case 'embeddingsQuery': {
|
|
2635
|
-
let requestOpts = openAiRequestOpts();
|
|
2636
|
-
|
|
2637
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2638
|
-
|
|
2639
|
-
if (!openAiAPIKey) {
|
|
2640
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2641
|
-
}
|
|
2642
|
-
|
|
2643
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2644
|
-
if (openAiAPIUrl) {
|
|
2645
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2646
|
-
}
|
|
2647
|
-
|
|
2648
|
-
let openAiModel = message.data.openAiModel || (await settings.get('documentStoreChatModel')) || (await settings.get('openAiModel'));
|
|
2649
|
-
if (openAiModel) {
|
|
2650
|
-
requestOpts.gptModel = openAiModel;
|
|
2651
|
-
}
|
|
2652
|
-
|
|
2653
|
-
// Set max tokens based on model
|
|
2654
|
-
switch (openAiModel.substring(0, 5)) {
|
|
2655
|
-
case 'gpt-3':
|
|
2656
|
-
requestOpts.maxTokens = 3000;
|
|
2657
|
-
break;
|
|
2658
|
-
case 'gpt-4':
|
|
2659
|
-
requestOpts.maxTokens = 6500;
|
|
2660
|
-
break;
|
|
2661
|
-
case 'gpt-5':
|
|
2662
|
-
default:
|
|
2663
|
-
requestOpts.maxTokens = 18000;
|
|
2664
|
-
break;
|
|
2665
|
-
}
|
|
2666
|
-
|
|
2667
|
-
requestOpts.user = message.data.account;
|
|
2668
|
-
requestOpts.temperature = 0.4;
|
|
2669
|
-
|
|
2670
|
-
requestOpts.question = message.data.question;
|
|
2671
|
-
requestOpts.contextChunks = message.data.contextChunks;
|
|
2672
|
-
requestOpts.userData = message.data.userData;
|
|
2673
|
-
|
|
2674
|
-
let response = await embeddingsQuery(openAiAPIKey, requestOpts);
|
|
2675
|
-
|
|
2676
|
-
// Clean and format response
|
|
2677
|
-
if (response?.['Message-ID']) {
|
|
2678
|
-
response.messageId = response?.['Message-ID'];
|
|
2679
|
-
delete response?.['Message-ID'];
|
|
2680
|
-
}
|
|
2681
|
-
if (response?.messageId) {
|
|
2682
|
-
response.messageId = [].concat(response?.messageId || []).map(value => (value || '').toString().trim().replace(/^<?/, '<').replace(/>?$/, '>'));
|
|
2683
|
-
}
|
|
2684
|
-
|
|
2685
|
-
if (response?.answer) {
|
|
2686
|
-
if (typeof response.answer === 'object') {
|
|
2687
|
-
response.answer = JSON.stringify(response.answer);
|
|
2688
|
-
} else {
|
|
2689
|
-
response.answer = response.answer.toString();
|
|
2690
|
-
}
|
|
2691
|
-
}
|
|
2692
|
-
|
|
2693
|
-
// Clean internal properties
|
|
2694
|
-
for (const key of Object.keys(response)) {
|
|
2695
|
-
if (/^_/.test(key)) {
|
|
2696
|
-
delete response[key];
|
|
2697
|
-
}
|
|
2698
|
-
}
|
|
2699
|
-
|
|
2700
|
-
return response;
|
|
2701
|
-
}
|
|
2702
|
-
|
|
2703
|
-
case 'questionQuery': {
|
|
2704
|
-
let requestOpts = openAiRequestOpts();
|
|
2705
|
-
|
|
2706
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2707
2750
|
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2713
|
-
if (openAiAPIUrl) {
|
|
2714
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2715
|
-
}
|
|
2716
|
-
|
|
2717
|
-
let openAiModel = message.data.openAiModel || 'gpt-3.5-turbo-instruct';
|
|
2718
|
-
if (openAiModel) {
|
|
2719
|
-
requestOpts.gptModel = openAiModel;
|
|
2720
|
-
}
|
|
2721
|
-
|
|
2722
|
-
requestOpts.user = message.data.account;
|
|
2723
|
-
|
|
2724
|
-
let response = await questionQuery(message.data.question, openAiAPIKey, requestOpts);
|
|
2725
|
-
|
|
2726
|
-
// Clean internal properties
|
|
2727
|
-
for (const key of Object.keys(response)) {
|
|
2728
|
-
if (/^_/.test(key)) {
|
|
2729
|
-
delete response[key];
|
|
2751
|
+
return response;
|
|
2752
|
+
} catch (err) {
|
|
2753
|
+
if (counted) {
|
|
2754
|
+
metrics.aiRequests.inc({ model, status: 'failure' });
|
|
2730
2755
|
}
|
|
2756
|
+
throw err;
|
|
2731
2757
|
}
|
|
2732
|
-
|
|
2733
|
-
return response;
|
|
2734
|
-
}
|
|
2735
|
-
|
|
2736
|
-
case 'generateChunkEmbeddings': {
|
|
2737
|
-
let requestOpts = openAiRequestOpts();
|
|
2738
|
-
|
|
2739
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2740
|
-
|
|
2741
|
-
if (!openAiAPIKey) {
|
|
2742
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2743
|
-
}
|
|
2744
|
-
|
|
2745
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2746
|
-
if (openAiAPIUrl) {
|
|
2747
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2748
|
-
}
|
|
2749
|
-
|
|
2750
|
-
requestOpts.user = message.data.account;
|
|
2751
|
-
|
|
2752
|
-
const data = await getChunkEmbeddings(message.data.message, openAiAPIKey, requestOpts);
|
|
2753
|
-
|
|
2754
|
-
return data;
|
|
2755
2758
|
}
|
|
2756
2759
|
|
|
2757
2760
|
case 'openAiListModels': {
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2761
|
-
|
|
2762
|
-
if (!openAiAPIKey) {
|
|
2763
|
-
throw new Error(`OpenAI API key is not configured`);
|
|
2764
|
-
}
|
|
2765
|
-
|
|
2766
|
-
let openAiAPIUrl = message.data.openAiAPIUrl || (await settings.get('openAiAPIUrl'));
|
|
2767
|
-
if (openAiAPIUrl) {
|
|
2768
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2769
|
-
}
|
|
2770
|
-
|
|
2771
|
-
requestOpts.user = message.data.account;
|
|
2772
|
-
|
|
2773
|
-
const data = await openAiListModels(openAiAPIKey, requestOpts);
|
|
2774
|
-
|
|
2775
|
-
return data;
|
|
2776
|
-
}
|
|
2777
|
-
|
|
2778
|
-
case 'openAiDefaultPrompt': {
|
|
2779
|
-
return openAiDefaultPrompt;
|
|
2761
|
+
const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
|
|
2762
|
+
return await withRequestDeadline(message, signal => openAiListModels(openAiAPIKey, Object.assign(requestOpts, { signal })));
|
|
2780
2763
|
}
|
|
2781
2764
|
|
|
2782
2765
|
case 'threads': {
|
|
@@ -2864,23 +2847,14 @@ async function onCommand(worker, message) {
|
|
|
2864
2847
|
// Guarded for the same reason as the `new` branch above, and here the throw was
|
|
2865
2848
|
// answered with a 500 for a deletion that had in fact succeeded: the account was
|
|
2866
2849
|
// already gone from Redis by the time this message was sent.
|
|
2867
|
-
|
|
2868
|
-
unassigned
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
if (!workerAssigned.get(assignedWorker).size) {
|
|
2875
|
-
// Last account on this worker
|
|
2876
|
-
workerAssigned.delete(assignedWorker);
|
|
2877
|
-
}
|
|
2850
|
+
{
|
|
2851
|
+
let assignedWorker = forgetAccount({ workerAssigned, assigned, unassigned }, message.account);
|
|
2852
|
+
if (assignedWorker) {
|
|
2853
|
+
// Notify worker to clean up
|
|
2854
|
+
call(assignedWorker, message)
|
|
2855
|
+
.then(() => logger.debug('Account cleanup completed'))
|
|
2856
|
+
.catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
|
|
2878
2857
|
}
|
|
2879
|
-
|
|
2880
|
-
// Notify worker to clean up
|
|
2881
|
-
call(assignedWorker, message)
|
|
2882
|
-
.then(() => logger.debug('Account cleanup completed'))
|
|
2883
|
-
.catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
|
|
2884
2858
|
}
|
|
2885
2859
|
sendWebhook(message.account, ACCOUNT_DELETED_NOTIFY, { account: message.account }).catch(err =>
|
|
2886
2860
|
logger.error({ msg: 'Account deletion webhook failed', account: message.account, err })
|
|
@@ -3053,17 +3027,35 @@ async function onCommand(worker, message) {
|
|
|
3053
3027
|
}
|
|
3054
3028
|
|
|
3055
3029
|
// Metrics collection results
|
|
3056
|
-
|
|
3030
|
+
// Connection states published so far, so a state no account is in any more is reported as 0
|
|
3031
|
+
// instead of keeping its last value
|
|
3032
|
+
let publishedConnectionStates = new Set();
|
|
3033
|
+
let collectingMetrics = false;
|
|
3057
3034
|
|
|
3058
3035
|
/**
|
|
3059
3036
|
* Collect IMAP connection metrics from all workers
|
|
3060
3037
|
* @returns {Promise<void>}
|
|
3061
3038
|
*/
|
|
3062
3039
|
async function collectMetrics() {
|
|
3063
|
-
//
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3040
|
+
// Runs every second but awaits a countConnections call per worker, each allowed the full command
|
|
3041
|
+
// timeout. Overlapping runs used to add into one shared result object while another run zeroed
|
|
3042
|
+
// it, so the gauge reported doubled or partial counts exactly when a worker was slow.
|
|
3043
|
+
if (collectingMetrics) {
|
|
3044
|
+
return;
|
|
3045
|
+
}
|
|
3046
|
+
collectingMetrics = true;
|
|
3047
|
+
try {
|
|
3048
|
+
await collectConnectionMetrics();
|
|
3049
|
+
} finally {
|
|
3050
|
+
collectingMetrics = false;
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
|
|
3054
|
+
async function collectConnectionMetrics() {
|
|
3055
|
+
let metricsResult = {};
|
|
3056
|
+
for (let status of publishedConnectionStates) {
|
|
3057
|
+
metricsResult[status] = 0;
|
|
3058
|
+
}
|
|
3067
3059
|
|
|
3068
3060
|
// Subscription state counters
|
|
3069
3061
|
let subscriptionResults = { valid: 0, expired: 0, unset: 0, failed: 0, pending: 0 };
|
|
@@ -3108,6 +3100,7 @@ async function collectMetrics() {
|
|
|
3108
3100
|
|
|
3109
3101
|
// Update Prometheus metrics for connections
|
|
3110
3102
|
Object.keys(metricsResult).forEach(status => {
|
|
3103
|
+
publishedConnectionStates.add(status);
|
|
3111
3104
|
metrics.imapConnections.set({ status }, metricsResult[status]);
|
|
3112
3105
|
});
|
|
3113
3106
|
|
|
@@ -3142,7 +3135,7 @@ const closeQueues = cb => {
|
|
|
3142
3135
|
}
|
|
3143
3136
|
}
|
|
3144
3137
|
|
|
3145
|
-
for (let name of ['notify', 'submit', '
|
|
3138
|
+
for (let name of ['notify', 'submit', 'export']) {
|
|
3146
3139
|
if (queueEvents[name]) {
|
|
3147
3140
|
proms.push(queueEvents[name].close());
|
|
3148
3141
|
}
|
|
@@ -3325,6 +3318,13 @@ const startApplication = async () => {
|
|
|
3325
3318
|
logger.error({ msg: 'Failed to backfill the auth-failure disable marker', err });
|
|
3326
3319
|
}
|
|
3327
3320
|
|
|
3321
|
+
// One-time delete of the store behind the retired `bounces` field; not fatal, the completion key is written last
|
|
3322
|
+
try {
|
|
3323
|
+
await sweepBounceStore();
|
|
3324
|
+
} catch (err) {
|
|
3325
|
+
logger.error({ msg: 'Failed to sweep the retired bounce store', err });
|
|
3326
|
+
}
|
|
3327
|
+
|
|
3328
3328
|
// Apply prepared settings
|
|
3329
3329
|
if (preparedSettings) {
|
|
3330
3330
|
logger.debug({ msg: 'Applying configuration', settingsKeys: Object.keys(preparedSettings) });
|
|
@@ -3601,9 +3601,14 @@ const startApplication = async () => {
|
|
|
3601
3601
|
await spawnWorker('export');
|
|
3602
3602
|
}
|
|
3603
3603
|
|
|
3604
|
-
//
|
|
3605
|
-
|
|
3606
|
-
|
|
3604
|
+
// The Document Store was removed in 2.82.0. An instance upgraded with it still switched on
|
|
3605
|
+
// is told where the feature went, here and on every admin page (workers/api.js), rather
|
|
3606
|
+
// than losing its search index quietly
|
|
3607
|
+
if (await settings.get('documentStoreEnabled')) {
|
|
3608
|
+
logger.warn({
|
|
3609
|
+
msg: 'The Document Store feature has been removed from EmailEngine. Downgrade if you still need it',
|
|
3610
|
+
lastVersionWithDocumentStore: LAST_DOCUMENT_STORE_VERSION
|
|
3611
|
+
});
|
|
3607
3612
|
}
|
|
3608
3613
|
|
|
3609
3614
|
// Start SMTP proxy if enabled
|
|
@@ -3682,16 +3687,15 @@ startApplication()
|
|
|
3682
3687
|
startHealthMonitoring();
|
|
3683
3688
|
|
|
3684
3689
|
// Initialize queue event listeners
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
queueEvents.export = new QueueEvents('export', Object.assign({}, queueConf));
|
|
3690
|
+
for (let name of ['notify', 'submit', 'export']) {
|
|
3691
|
+
queueEvents[name] = logBullErrors(new QueueEvents(name, Object.assign({}, queueConf)), `queueEvents:${name}`);
|
|
3692
|
+
}
|
|
3689
3693
|
|
|
3690
3694
|
// Periodic queue cleanup (every 6 hours)
|
|
3691
3695
|
const QUEUE_CLEANUP_INTERVAL = 6 * 60 * 60 * 1000;
|
|
3692
3696
|
|
|
3693
3697
|
async function cleanupQueues() {
|
|
3694
|
-
const queues = [notifyQueue, submitQueue,
|
|
3698
|
+
const queues = [notifyQueue, submitQueue, exportQueue];
|
|
3695
3699
|
for (const queue of queues) {
|
|
3696
3700
|
try {
|
|
3697
3701
|
// Clean completed jobs older than 24 hours
|