emailengine-app 2.81.2 → 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 -11
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +27 -0
- package/Dockerfile +2 -0
- 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/expected-identity.js +1 -1
- package/lib/account-assignment.js +138 -1
- package/lib/account.js +254 -859
- 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 +40 -235
- 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 +33 -6
- 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 +42 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +76 -11
- 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 +377 -523
- 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 +76 -50
- 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 +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 +194 -397
- 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 +133 -39
- 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/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 +122 -242
- 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 +33 -41
- package/sbom.json +1 -1
- package/scripts/refresh-test-tokens.js +42 -14
- package/server.js +317 -289
- 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 +434 -1835
- package/translations/messages.pot +97 -97
- 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 +20 -20
- package/workers/export.js +55 -60
- package/workers/imap.js +126 -46
- 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/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');
|
|
@@ -331,7 +340,6 @@ const THREAD_NAMES = {
|
|
|
331
340
|
api: 'HTTP and API server',
|
|
332
341
|
submit: 'Email sending worker',
|
|
333
342
|
export: 'Export worker',
|
|
334
|
-
documents: 'Document store indexing worker',
|
|
335
343
|
imapProxy: 'IMAP proxy server',
|
|
336
344
|
smtp: 'SMTP proxy server'
|
|
337
345
|
};
|
|
@@ -595,6 +603,18 @@ const metrics = {
|
|
|
595
603
|
labelNames: ['event']
|
|
596
604
|
}),
|
|
597
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
|
+
|
|
598
618
|
webhookReq: new promClient.Histogram({
|
|
599
619
|
name: 'webhook_req',
|
|
600
620
|
help: 'Duration of webhook requests',
|
|
@@ -747,6 +767,8 @@ let mids = 0; // Message ID counter
|
|
|
747
767
|
// Application state flags
|
|
748
768
|
let isClosing = false; // Is the application shutting down?
|
|
749
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;
|
|
750
772
|
|
|
751
773
|
// Account assignment tracking
|
|
752
774
|
let unassigned = false; // Set of unassigned accounts
|
|
@@ -761,7 +783,8 @@ const MAX_ASSIGN_RETRIES = 3; // Max consecutive safety-net retries before givin
|
|
|
761
783
|
// Worker management
|
|
762
784
|
let imapInitialWorkersLoaded = false; // Have all initial IMAP workers started?
|
|
763
785
|
let workers = new Map(); // Map of type -> Set of workers
|
|
764
|
-
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()
|
|
765
788
|
|
|
766
789
|
// Shutdown drain budget. A worker with no in-flight job answers immediately, so this only costs
|
|
767
790
|
// real time when there is genuinely something to finish - which is exactly when waiting is worth
|
|
@@ -1076,13 +1099,15 @@ async function sendWebhook(account, event, data) {
|
|
|
1076
1099
|
|
|
1077
1100
|
/**
|
|
1078
1101
|
* Spawn a new worker thread of the specified type
|
|
1079
|
-
* @param {string} type - Worker type (imap, api, webhooks, submit,
|
|
1102
|
+
* @param {string} type - Worker type (imap, api, webhooks, submit, export, smtp, imapProxy)
|
|
1080
1103
|
* @param {Object} [opts] - Optional spawn options
|
|
1081
1104
|
* @param {Object} [opts.workerData] - Data passed to the worker thread (e.g. API worker index). The
|
|
1082
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
|
|
1083
1108
|
* @returns {Promise<number|void>} Thread ID if successful
|
|
1084
1109
|
*/
|
|
1085
|
-
let spawnWorker = async (type, opts) => {
|
|
1110
|
+
let spawnWorker = async (type, opts, slot) => {
|
|
1086
1111
|
// Don't spawn workers during shutdown
|
|
1087
1112
|
if (isClosing) {
|
|
1088
1113
|
return;
|
|
@@ -1112,6 +1137,13 @@ let spawnWorker = async (type, opts) => {
|
|
|
1112
1137
|
await updateServerState(type, 'spawning');
|
|
1113
1138
|
}
|
|
1114
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
|
+
|
|
1115
1147
|
// Create new worker thread
|
|
1116
1148
|
let spawnedAt = Date.now();
|
|
1117
1149
|
let worker = new WorkerThread(pathlib.join(__dirname, 'workers', `${type.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}.js`), {
|
|
@@ -1188,7 +1220,12 @@ let spawnWorker = async (type, opts) => {
|
|
|
1188
1220
|
|
|
1189
1221
|
// Update server state for proxy servers
|
|
1190
1222
|
if (['smtp', 'imapProxy'].includes(type)) {
|
|
1191
|
-
|
|
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
|
+
);
|
|
1192
1229
|
}
|
|
1193
1230
|
|
|
1194
1231
|
// Handle IMAP worker cleanup
|
|
@@ -1289,13 +1326,13 @@ let spawnWorker = async (type, opts) => {
|
|
|
1289
1326
|
// Respawn worker after delay, preserving any spawn options (e.g. API worker index).
|
|
1290
1327
|
// The delay grows while a worker type keeps dying on startup, so a deterministic
|
|
1291
1328
|
// crash no longer respawns once a second forever.
|
|
1292
|
-
let respawnDelay = respawnTracker.recordExit(
|
|
1293
|
-
let streak = respawnTracker.streakFor(
|
|
1329
|
+
let respawnDelay = respawnTracker.recordExit(slot, Date.now() - spawnedAt);
|
|
1330
|
+
let streak = respawnTracker.streakFor(slot);
|
|
1294
1331
|
if (streak > 1) {
|
|
1295
|
-
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 });
|
|
1296
1333
|
}
|
|
1297
1334
|
await new Promise(r => setTimeout(r, respawnDelay));
|
|
1298
|
-
await spawnWorker(type, opts);
|
|
1335
|
+
await spawnWorker(type, opts, slot);
|
|
1299
1336
|
};
|
|
1300
1337
|
|
|
1301
1338
|
// Handle worker exit
|
|
@@ -1475,9 +1512,16 @@ let spawnWorker = async (type, opts) => {
|
|
|
1475
1512
|
redis.hincrby(accountKey, `stats:count:${accountUpdateKey}`, 1).catch(() => false);
|
|
1476
1513
|
}
|
|
1477
1514
|
|
|
1478
|
-
// 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.
|
|
1479
1519
|
if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
|
|
1480
|
-
|
|
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
|
+
}
|
|
1481
1525
|
}
|
|
1482
1526
|
|
|
1483
1527
|
return;
|
|
@@ -1599,6 +1643,10 @@ let spawnWorker = async (type, opts) => {
|
|
|
1599
1643
|
unassignedAccounts: unassigned.size
|
|
1600
1644
|
});
|
|
1601
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 }));
|
|
1602
1650
|
}
|
|
1603
1651
|
}
|
|
1604
1652
|
break;
|
|
@@ -1697,6 +1745,95 @@ async function call(worker, message, transferList) {
|
|
|
1697
1745
|
});
|
|
1698
1746
|
}
|
|
1699
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
|
+
|
|
1700
1837
|
/**
|
|
1701
1838
|
* Assign unassigned accounts to available IMAP workers
|
|
1702
1839
|
* Uses load-aware distribution with round-robin for initial assignment
|
|
@@ -1791,8 +1928,22 @@ async function assignAccounts() {
|
|
|
1791
1928
|
// Roll back -- account was never actually assigned. Also reverts the load map so
|
|
1792
1929
|
// subsequent iterations see accurate counts
|
|
1793
1930
|
rollbackAssignment({ workerAssigned, assigned, workerLoadMap }, account, worker, !isReassignment);
|
|
1794
|
-
|
|
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);
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1795
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
|
+
}
|
|
1796
1947
|
continue;
|
|
1797
1948
|
}
|
|
1798
1949
|
|
|
@@ -2066,14 +2217,15 @@ let upgradeCheckTimer = false;
|
|
|
2066
2217
|
* @returns {Promise<void>}
|
|
2067
2218
|
*/
|
|
2068
2219
|
let upgradeCheckHandler = async () => {
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
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();
|
|
2073
2228
|
}
|
|
2074
|
-
await processCheckUpgrade();
|
|
2075
|
-
upgradeCheckTimer = setTimeout(checkUpgrade, UPGRADE_CHECK_TIMEOUT);
|
|
2076
|
-
upgradeCheckTimer.unref();
|
|
2077
2229
|
};
|
|
2078
2230
|
|
|
2079
2231
|
/**
|
|
@@ -2157,7 +2309,8 @@ const processRedisPing = async () => {
|
|
|
2157
2309
|
redisPingCounter.push(duration);
|
|
2158
2310
|
// Keep last 300 measurements
|
|
2159
2311
|
if (redisPingCounter.length > 300) {
|
|
2160
|
-
|
|
2312
|
+
// keep the newest samples, the average is computed from the tail
|
|
2313
|
+
redisPingCounter = redisPingCounter.slice(-150);
|
|
2161
2314
|
}
|
|
2162
2315
|
return duration;
|
|
2163
2316
|
} catch (err) {
|
|
@@ -2261,8 +2414,7 @@ async function updateQueueCounters() {
|
|
|
2261
2414
|
// gauge is kept at the 0 the getter reports so existing dashboards keep their series.
|
|
2262
2415
|
for (let [queue, queueObj] of [
|
|
2263
2416
|
['notify', notifyQueue],
|
|
2264
|
-
['submit', submitQueue]
|
|
2265
|
-
['documents', documentsQueue]
|
|
2417
|
+
['submit', submitQueue]
|
|
2266
2418
|
]) {
|
|
2267
2419
|
let stats;
|
|
2268
2420
|
try {
|
|
@@ -2350,6 +2502,66 @@ const openAiRequestOpts = () => ({
|
|
|
2350
2502
|
dispatcher: httpAgent.fetch
|
|
2351
2503
|
});
|
|
2352
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
|
+
|
|
2353
2565
|
async function onCommand(worker, message) {
|
|
2354
2566
|
switch (message.cmd) {
|
|
2355
2567
|
case 'metrics':
|
|
@@ -2508,244 +2720,46 @@ async function onCommand(worker, message) {
|
|
|
2508
2720
|
}
|
|
2509
2721
|
return false;
|
|
2510
2722
|
|
|
2511
|
-
// OpenAI integration commands - run in main process
|
|
2723
|
+
// OpenAI integration commands - run in the main process, where the metrics live
|
|
2512
2724
|
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
|
-
|
|
2725
|
+
const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
|
|
2560
2726
|
requestOpts.user = message.data.account;
|
|
2561
2727
|
|
|
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'));
|
|
2728
|
+
// the configuration page's test runs are not production traffic
|
|
2729
|
+
const counted = !message.data.options;
|
|
2730
|
+
const model = requestOpts.gptModel;
|
|
2574
2731
|
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
if (openAiAPIUrl) {
|
|
2581
|
-
requestOpts.baseApiUrl = openAiAPIUrl;
|
|
2582
|
-
}
|
|
2583
|
-
|
|
2584
|
-
requestOpts.user = message.data.account;
|
|
2732
|
+
try {
|
|
2733
|
+
const response = await withRequestDeadline(message, signal =>
|
|
2734
|
+
generateSummary(message.data.message, openAiAPIKey, Object.assign(requestOpts, { signal }))
|
|
2735
|
+
);
|
|
2736
|
+
const { usage } = response;
|
|
2585
2737
|
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
return false;
|
|
2589
|
-
}
|
|
2738
|
+
// the fitted email text the verbose mode adds stays out of the RPC and the log
|
|
2739
|
+
delete usage.text;
|
|
2590
2740
|
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
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
|
+
}
|
|
2596
2748
|
}
|
|
2597
2749
|
}
|
|
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
|
-
|
|
2675
|
-
let openAiAPIKey = message.data.openAiAPIKey || (await settings.get('openAiAPIKey'));
|
|
2676
2750
|
|
|
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];
|
|
2751
|
+
return response;
|
|
2752
|
+
} catch (err) {
|
|
2753
|
+
if (counted) {
|
|
2754
|
+
metrics.aiRequests.inc({ model, status: 'failure' });
|
|
2699
2755
|
}
|
|
2756
|
+
throw err;
|
|
2700
2757
|
}
|
|
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
2758
|
}
|
|
2725
2759
|
|
|
2726
2760
|
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;
|
|
2761
|
+
const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
|
|
2762
|
+
return await withRequestDeadline(message, signal => openAiListModels(openAiAPIKey, Object.assign(requestOpts, { signal })));
|
|
2749
2763
|
}
|
|
2750
2764
|
|
|
2751
2765
|
case 'threads': {
|
|
@@ -2833,23 +2847,14 @@ async function onCommand(worker, message) {
|
|
|
2833
2847
|
// Guarded for the same reason as the `new` branch above, and here the throw was
|
|
2834
2848
|
// answered with a 500 for a deletion that had in fact succeeded: the account was
|
|
2835
2849
|
// 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
|
-
}
|
|
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 }));
|
|
2847
2857
|
}
|
|
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
2858
|
}
|
|
2854
2859
|
sendWebhook(message.account, ACCOUNT_DELETED_NOTIFY, { account: message.account }).catch(err =>
|
|
2855
2860
|
logger.error({ msg: 'Account deletion webhook failed', account: message.account, err })
|
|
@@ -3022,17 +3027,35 @@ async function onCommand(worker, message) {
|
|
|
3022
3027
|
}
|
|
3023
3028
|
|
|
3024
3029
|
// Metrics collection results
|
|
3025
|
-
|
|
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;
|
|
3026
3034
|
|
|
3027
3035
|
/**
|
|
3028
3036
|
* Collect IMAP connection metrics from all workers
|
|
3029
3037
|
* @returns {Promise<void>}
|
|
3030
3038
|
*/
|
|
3031
3039
|
async function collectMetrics() {
|
|
3032
|
-
//
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
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
|
+
}
|
|
3036
3059
|
|
|
3037
3060
|
// Subscription state counters
|
|
3038
3061
|
let subscriptionResults = { valid: 0, expired: 0, unset: 0, failed: 0, pending: 0 };
|
|
@@ -3077,6 +3100,7 @@ async function collectMetrics() {
|
|
|
3077
3100
|
|
|
3078
3101
|
// Update Prometheus metrics for connections
|
|
3079
3102
|
Object.keys(metricsResult).forEach(status => {
|
|
3103
|
+
publishedConnectionStates.add(status);
|
|
3080
3104
|
metrics.imapConnections.set({ status }, metricsResult[status]);
|
|
3081
3105
|
});
|
|
3082
3106
|
|
|
@@ -3111,7 +3135,7 @@ const closeQueues = cb => {
|
|
|
3111
3135
|
}
|
|
3112
3136
|
}
|
|
3113
3137
|
|
|
3114
|
-
for (let name of ['notify', 'submit', '
|
|
3138
|
+
for (let name of ['notify', 'submit', 'export']) {
|
|
3115
3139
|
if (queueEvents[name]) {
|
|
3116
3140
|
proms.push(queueEvents[name].close());
|
|
3117
3141
|
}
|
|
@@ -3577,9 +3601,14 @@ const startApplication = async () => {
|
|
|
3577
3601
|
await spawnWorker('export');
|
|
3578
3602
|
}
|
|
3579
3603
|
|
|
3580
|
-
//
|
|
3581
|
-
|
|
3582
|
-
|
|
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
|
+
});
|
|
3583
3612
|
}
|
|
3584
3613
|
|
|
3585
3614
|
// Start SMTP proxy if enabled
|
|
@@ -3658,16 +3687,15 @@ startApplication()
|
|
|
3658
3687
|
startHealthMonitoring();
|
|
3659
3688
|
|
|
3660
3689
|
// Initialize queue event listeners
|
|
3661
|
-
|
|
3662
|
-
|
|
3663
|
-
|
|
3664
|
-
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
|
+
}
|
|
3665
3693
|
|
|
3666
3694
|
// Periodic queue cleanup (every 6 hours)
|
|
3667
3695
|
const QUEUE_CLEANUP_INTERVAL = 6 * 60 * 60 * 1000;
|
|
3668
3696
|
|
|
3669
3697
|
async function cleanupQueues() {
|
|
3670
|
-
const queues = [notifyQueue, submitQueue,
|
|
3698
|
+
const queues = [notifyQueue, submitQueue, exportQueue];
|
|
3671
3699
|
for (const queue of queues) {
|
|
3672
3700
|
try {
|
|
3673
3701
|
// Clean completed jobs older than 24 hours
|