emailengine-app 2.84.2 → 2.86.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 +29 -9
- package/.prettierignore +5 -1
- package/.prettierrc.js +2 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +107 -0
- package/Dockerfile +20 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +2 -2
- package/bin/emailengine.js +434 -408
- package/config/default.toml +2 -0
- package/copy-static-files.sh +41 -14
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +16563 -0
- package/eslint.config.js +81 -99
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +230 -170
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/format.js +4 -3
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +255 -38
- package/lib/api-routes/blocklist-routes.js +91 -4
- package/lib/api-routes/delivery-test-routes.js +27 -4
- package/lib/api-routes/export-routes.js +28 -2
- package/lib/api-routes/gateway-routes.js +110 -12
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +44 -5
- package/lib/api-routes/message-routes.js +112 -10
- package/lib/api-routes/oauth2-app-routes.js +63 -23
- package/lib/api-routes/outbox-routes.js +97 -52
- package/lib/api-routes/permission-map.js +67 -7
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +34 -6
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +337 -309
- package/lib/api-routes/template-routes.js +45 -8
- package/lib/api-routes/token-routes.js +152 -100
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +132 -6
- package/lib/bounce-detect.js +397 -205
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -45
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +137 -184
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +60 -22
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +372 -242
- package/lib/email-client/imap/subconnection.js +8 -30
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +228 -164
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/notification-handler.js +1 -2
- package/lib/email-client/outlook-client.js +372 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/gateway.js +19 -4
- package/lib/get-raw-email.js +25 -107
- package/lib/hapi-request-logger.js +107 -0
- package/lib/health.js +75 -0
- package/lib/imapproxy/imap-core/README.md +6 -5
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/mcp/tools.js +37 -8
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +36 -0
- package/lib/oauth/outlook-mailbox.js +35 -0
- package/lib/oauth/state.js +24 -0
- package/lib/oauth2-apps.js +631 -656
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/pbkdf2-phc.js +1 -1
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +164 -40
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/sso.js +1 -1
- package/lib/swagger-options.js +1 -1
- package/lib/thread-diagnostics.js +63 -0
- package/lib/timezones.js +109 -0
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +7 -6
- package/lib/tools.js +48 -51
- package/lib/totp.js +2 -5
- package/lib/translations.js +1 -2
- package/lib/ui-routes/account-routes.js +475 -454
- package/lib/ui-routes/account-setup.js +99 -0
- package/lib/ui-routes/admin-config-routes.js +152 -100
- package/lib/ui-routes/admin-entities-routes.js +93 -21
- package/lib/ui-routes/auth-routes.js +90 -38
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/internals-routes.js +5 -0
- package/lib/ui-routes/oauth-config-routes.js +124 -82
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/route-helpers.js +19 -3
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/ui-routes/tls-config-routes.js +58 -15
- package/lib/utils/back-off.js +82 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/murmurhash3.js +66 -0
- package/lib/utils/public-suffix.js +122 -0
- package/lib/utils/random-id.js +26 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/utils/version.js +74 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +56 -0
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +93 -45
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +37 -38
- package/sbom.json +7902 -1
- package/server.js +784 -518
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +225 -1060
- package/translations/messages.pot +62 -63
- package/views/config/ai.hbs +1 -1
- package/views/config/security.hbs +24 -2
- package/views/config/service.hbs +47 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/internals/index.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/views/partials/webhook_form.hbs +1 -1
- package/views/suppression-lists/index.hbs +1 -1
- package/workers/api.js +840 -611
- package/workers/export.js +17 -632
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +18 -448
- package/lib/email-client/outlook-fallback-poll.js +0 -30
package/workers/export.js
CHANGED
|
@@ -6,31 +6,12 @@ const packageData = require('../package.json');
|
|
|
6
6
|
const config = require('@zone-eu/wild-config');
|
|
7
7
|
const logger = require('../lib/logger');
|
|
8
8
|
|
|
9
|
-
const {
|
|
10
|
-
REDIS_PREFIX,
|
|
11
|
-
EXPORT_COMPLETED_NOTIFY,
|
|
12
|
-
EXPORT_FAILED_NOTIFY,
|
|
13
|
-
DEFAULT_EXPORT_MAX_MESSAGE_SIZE,
|
|
14
|
-
DEFAULT_EXPORT_MAX_MESSAGES,
|
|
15
|
-
DEFAULT_EXPORT_MAX_SIZE
|
|
16
|
-
} = require('../lib/consts');
|
|
9
|
+
const { REDIS_PREFIX, EXPORT_COMPLETED_NOTIFY, EXPORT_FAILED_NOTIFY } = require('../lib/consts');
|
|
17
10
|
const { getDuration, readEnvValue, threadStats } = require('../lib/tools');
|
|
18
11
|
const { webhooks: Webhooks } = require('../lib/webhooks');
|
|
19
12
|
const settings = require('../lib/settings');
|
|
20
|
-
const {
|
|
21
|
-
|
|
22
|
-
isTransientError,
|
|
23
|
-
isSkippableError,
|
|
24
|
-
isFolderMissingError,
|
|
25
|
-
isRetryableError,
|
|
26
|
-
resolveExportLimit,
|
|
27
|
-
isExportLimitReached,
|
|
28
|
-
parseActiveEntry,
|
|
29
|
-
getExportKey,
|
|
30
|
-
exportFilePath,
|
|
31
|
-
openExportOutput,
|
|
32
|
-
ACTIVE_EXPORTS_KEY
|
|
33
|
-
} = require('../lib/export');
|
|
13
|
+
const { Export, parseActiveEntry, getExportKey, ACTIVE_EXPORTS_KEY } = require('../lib/export');
|
|
14
|
+
const { createExportJobs } = require('../lib/export-worker');
|
|
34
15
|
|
|
35
16
|
const { initSentry } = require('../lib/sentry');
|
|
36
17
|
initSentry('export');
|
|
@@ -54,16 +35,6 @@ const EXPORT_TIMEOUT = getDuration(readEnvValue('EENGINE_EXPORT_TIMEOUT')) || DE
|
|
|
54
35
|
|
|
55
36
|
const EXPORT_QC = (readEnvValue('EENGINE_EXPORT_QC') && Number(readEnvValue('EENGINE_EXPORT_QC'))) || config.queues.export || 1;
|
|
56
37
|
|
|
57
|
-
const BATCH_SIZE = 100;
|
|
58
|
-
const LIST_PAGE_SIZE = 1000;
|
|
59
|
-
const FOLDER_INDEX_MAX_RETRIES = 3;
|
|
60
|
-
const FOLDER_INDEX_RETRY_DELAY_MS = 1000;
|
|
61
|
-
|
|
62
|
-
const IMAP_MESSAGE_MAX_RETRIES = 3;
|
|
63
|
-
const IMAP_MESSAGE_RETRY_BASE_DELAY = 2000;
|
|
64
|
-
const ACCOUNT_CHECK_INTERVAL = 60 * 1000;
|
|
65
|
-
const LOCK_EXTENSION_INTERVAL = 5 * 60 * 1000;
|
|
66
|
-
|
|
67
38
|
let callQueue = new Map();
|
|
68
39
|
let mids = 0;
|
|
69
40
|
|
|
@@ -125,609 +96,23 @@ async function notify(account, event, data) {
|
|
|
125
96
|
data
|
|
126
97
|
};
|
|
127
98
|
|
|
128
|
-
await Webhooks.
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// Returns a throttled callback that extends both the BullMQ job lock and the export's Redis key
|
|
132
|
-
// expiry on the LOCK_EXTENSION_INTERVAL cadence. Long-running indexing/exporting loops call it
|
|
133
|
-
// freely; the lock/expiry are refreshed at most once per interval. Without this the lock could lapse
|
|
134
|
-
// (stalling and reprocessing the job) and the export keys could expire mid-run.
|
|
135
|
-
function createLeaseExtender(job, account, exportId) {
|
|
136
|
-
let lastExtension = Date.now();
|
|
137
|
-
return async function maybeExtendLease() {
|
|
138
|
-
if (Date.now() - lastExtension <= LOCK_EXTENSION_INTERVAL) {
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
await Promise.all([
|
|
142
|
-
job.extendLock(job.token, 10 * 60 * 1000).catch(err => {
|
|
143
|
-
logger.warn({ msg: 'Failed to extend job lock', account, exportId, err });
|
|
144
|
-
}),
|
|
145
|
-
Export.extendExpiry(account, exportId).catch(err => {
|
|
146
|
-
logger.warn({ msg: 'Failed to extend export expiry', account, exportId, err });
|
|
147
|
-
})
|
|
148
|
-
]);
|
|
149
|
-
lastExtension = Date.now();
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
async function indexMessages(job, exportData) {
|
|
154
|
-
const { account, exportId } = job.data;
|
|
155
|
-
const folders = JSON.parse(exportData.folders || '[]');
|
|
156
|
-
const startDate = new Date(Number(exportData.startDate));
|
|
157
|
-
const endDate = new Date(Number(exportData.endDate));
|
|
158
|
-
const indexingStartTime = new Date();
|
|
159
|
-
|
|
160
|
-
const accountData = await redis.hgetall(`${REDIS_PREFIX}iad:${account}`);
|
|
161
|
-
if (!accountData || !accountData.account) {
|
|
162
|
-
const err = new Error('Account not found or has been deleted');
|
|
163
|
-
err.code = 'AccountNotFound';
|
|
164
|
-
err.statusCode = 404;
|
|
165
|
-
throw err;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
const accountObject = new Account({
|
|
169
|
-
account,
|
|
170
|
-
redis,
|
|
171
|
-
call,
|
|
172
|
-
secret: await getSecret(),
|
|
173
|
-
timeout: EXPORT_TIMEOUT
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
let mailboxes;
|
|
177
|
-
try {
|
|
178
|
-
mailboxes = await accountObject.listMailboxes();
|
|
179
|
-
} catch (err) {
|
|
180
|
-
throw new Error(`Failed to list mailboxes: ${err.message}`, { cause: err });
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
const foldersToProcess = resolveFolders(folders, mailboxes);
|
|
184
|
-
|
|
185
|
-
await Export.update(account, exportId, { foldersTotal: foldersToProcess.length });
|
|
186
|
-
|
|
187
|
-
const maxMessages = resolveExportLimit(await settings.get('exportMaxMessages'), DEFAULT_EXPORT_MAX_MESSAGES);
|
|
188
|
-
|
|
189
|
-
logger.info({ msg: 'Starting export indexing', account, exportId, foldersToProcess: foldersToProcess.length, maxMessages: maxMessages || 'unlimited' });
|
|
190
|
-
|
|
191
|
-
let totalIndexed = 0;
|
|
192
|
-
let truncated = false;
|
|
193
|
-
const maybeExtendLease = createLeaseExtender(job, account, exportId);
|
|
194
|
-
|
|
195
|
-
for (let i = 0; i < foldersToProcess.length; i++) {
|
|
196
|
-
await maybeExtendLease();
|
|
197
|
-
|
|
198
|
-
if (await Export.isCancelled(account, exportId)) {
|
|
199
|
-
const err = new Error('Export cancelled by user');
|
|
200
|
-
err.code = 'ExportCancelled';
|
|
201
|
-
throw err;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
const folderPath = foldersToProcess[i];
|
|
205
|
-
let attempt = 0;
|
|
206
|
-
|
|
207
|
-
while (true) {
|
|
208
|
-
try {
|
|
209
|
-
const remaining = maxMessages ? maxMessages - totalIndexed : 0;
|
|
210
|
-
const queued = await indexFolder(accountObject, account, exportId, folderPath, startDate, endDate, indexingStartTime, remaining);
|
|
211
|
-
totalIndexed += queued;
|
|
212
|
-
|
|
213
|
-
logger.trace({
|
|
214
|
-
msg: 'Folder indexed',
|
|
215
|
-
account,
|
|
216
|
-
exportId,
|
|
217
|
-
folder: folderPath,
|
|
218
|
-
foldersScanned: i + 1,
|
|
219
|
-
foldersTotal: foldersToProcess.length,
|
|
220
|
-
totalIndexed
|
|
221
|
-
});
|
|
222
|
-
|
|
223
|
-
break;
|
|
224
|
-
} catch (err) {
|
|
225
|
-
attempt++;
|
|
226
|
-
// A folder that was deleted mid-export is handled inside indexFolder (treated as empty),
|
|
227
|
-
// so any error reaching here is a real failure. Only transient errors are worth retrying;
|
|
228
|
-
// a permanent error (deleted account, auth failure, unexpected server response) is not
|
|
229
|
-
// specific to this folder and would repeat for the rest, so fail the whole export. Silently
|
|
230
|
-
// skipping folders and marking an incomplete export "completed" hides data loss from the caller.
|
|
231
|
-
if (!isTransientError(err) || attempt >= FOLDER_INDEX_MAX_RETRIES) {
|
|
232
|
-
logger.error({
|
|
233
|
-
msg: 'Failed to index folder, failing export',
|
|
234
|
-
account,
|
|
235
|
-
exportId,
|
|
236
|
-
folder: folderPath,
|
|
237
|
-
attempts: attempt,
|
|
238
|
-
err
|
|
239
|
-
});
|
|
240
|
-
err.message = `Failed to index folder "${folderPath}": ${err.message}`;
|
|
241
|
-
throw err;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
const delay = FOLDER_INDEX_RETRY_DELAY_MS * Math.pow(2, attempt - 1);
|
|
245
|
-
logger.warn({
|
|
246
|
-
msg: 'Folder indexing failed, retrying',
|
|
247
|
-
account,
|
|
248
|
-
exportId,
|
|
249
|
-
folder: folderPath,
|
|
250
|
-
attempt,
|
|
251
|
-
maxRetries: FOLDER_INDEX_MAX_RETRIES,
|
|
252
|
-
delayMs: delay,
|
|
253
|
-
err
|
|
254
|
-
});
|
|
255
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
// The folder indexed successfully (failures throw above); count it toward progress.
|
|
260
|
-
await Export.update(account, exportId, { foldersScanned: i + 1 });
|
|
261
|
-
|
|
262
|
-
if (isExportLimitReached(totalIndexed, maxMessages)) {
|
|
263
|
-
truncated = true;
|
|
264
|
-
logger.warn({
|
|
265
|
-
msg: 'Export indexing truncated: message limit reached',
|
|
266
|
-
account,
|
|
267
|
-
exportId,
|
|
268
|
-
totalIndexed,
|
|
269
|
-
limit: maxMessages
|
|
270
|
-
});
|
|
271
|
-
break;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
if (truncated) {
|
|
276
|
-
await Export.update(account, exportId, { truncated: '1' });
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
function resolveFolders(folders, mailboxes) {
|
|
281
|
-
const resolveFolder = folder => {
|
|
282
|
-
if (folder.startsWith('\\')) {
|
|
283
|
-
const match = mailboxes.find(mb => mb.specialUse === folder);
|
|
284
|
-
return match ? match.path : null;
|
|
285
|
-
}
|
|
286
|
-
return folder;
|
|
287
|
-
};
|
|
288
|
-
|
|
289
|
-
if (!folders || folders.length === 0) {
|
|
290
|
-
// If \All folder exists (Gmail/Outlook), use it; otherwise export all except Junk and Trash
|
|
291
|
-
const allMailFolder = mailboxes.find(mb => mb.specialUse === '\\All');
|
|
292
|
-
if (allMailFolder) {
|
|
293
|
-
return [allMailFolder.path];
|
|
294
|
-
}
|
|
295
|
-
return mailboxes.filter(mb => !['\\Junk', '\\Trash'].includes(mb.specialUse)).map(mb => mb.path);
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
return folders.map(resolveFolder).filter(Boolean);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
async function indexFolder(accountObject, account, exportId, folderPath, startDate, endDate, indexingStartTime, maxMessages) {
|
|
302
|
-
let cursor = null;
|
|
303
|
-
let queued = 0;
|
|
304
|
-
|
|
305
|
-
while (true) {
|
|
306
|
-
const searchCriteria = { since: startDate };
|
|
307
|
-
if (endDate < indexingStartTime) {
|
|
308
|
-
searchCriteria.before = endDate;
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
const listOptions = {
|
|
312
|
-
path: folderPath,
|
|
313
|
-
pageSize: LIST_PAGE_SIZE,
|
|
314
|
-
search: searchCriteria,
|
|
315
|
-
metadataOnly: true,
|
|
316
|
-
cursor
|
|
317
|
-
};
|
|
318
|
-
|
|
319
|
-
let result;
|
|
320
|
-
try {
|
|
321
|
-
result = await accountObject.listMessages(listOptions);
|
|
322
|
-
} catch (err) {
|
|
323
|
-
// Other errors (e.g. a deleted account) propagate
|
|
324
|
-
if (isFolderMissingError(err)) {
|
|
325
|
-
// The folder disappeared mid-export - treat it as empty instead of failing the export
|
|
326
|
-
logger.warn({ msg: 'Export folder was not found, skipping', account, exportId, folder: folderPath, err });
|
|
327
|
-
return queued;
|
|
328
|
-
}
|
|
329
|
-
throw err;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
for (const msg of result.messages || []) {
|
|
333
|
-
if (maxMessages && queued >= maxMessages) {
|
|
334
|
-
return queued;
|
|
335
|
-
}
|
|
336
|
-
await Export.queueMessage(account, exportId, {
|
|
337
|
-
folder: folderPath,
|
|
338
|
-
messageId: msg.id || msg.emailId,
|
|
339
|
-
uid: msg.uid,
|
|
340
|
-
size: msg.size || 0,
|
|
341
|
-
date: msg.date ? new Date(msg.date).getTime() : Date.now()
|
|
342
|
-
});
|
|
343
|
-
queued++;
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
if (maxMessages && queued >= maxMessages) {
|
|
347
|
-
return queued;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
cursor = result.nextPageCursor;
|
|
351
|
-
if (!cursor) {
|
|
352
|
-
break;
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
return queued;
|
|
99
|
+
await Webhooks.enqueue(event, payload);
|
|
357
100
|
}
|
|
358
101
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
// Preserve an explicit 0 ("unlimited" per the API contract); only fall back when unset/invalid.
|
|
367
|
-
const maxBytes = Number.isFinite(rawMaxBytes) ? rawMaxBytes : 5 * 1024 * 1024;
|
|
368
|
-
const maxMessageSize = resolveExportLimit(await settings.get('exportMaxMessageSize'), DEFAULT_EXPORT_MAX_MESSAGE_SIZE);
|
|
369
|
-
const maxExportSize = resolveExportLimit(await settings.get('exportMaxSize'), DEFAULT_EXPORT_MAX_SIZE);
|
|
370
|
-
const isEncrypted = exportData.isEncrypted === '1';
|
|
371
|
-
|
|
372
|
-
const accountObject = new Account({
|
|
373
|
-
account,
|
|
374
|
-
redis,
|
|
375
|
-
call,
|
|
376
|
-
secret: await getSecret(),
|
|
377
|
-
timeout: EXPORT_TIMEOUT
|
|
378
|
-
});
|
|
379
|
-
|
|
380
|
-
// Everything that can fail before the export starts writing runs before the output file is
|
|
381
|
-
// opened: a failure here used to leave the file descriptor (and the unlinked file's disk space)
|
|
382
|
-
// held for the life of the worker.
|
|
383
|
-
const accountData = await accountObject.loadAccountData(account);
|
|
384
|
-
const isApiAccount = await accountObject.isApiClient(accountData);
|
|
385
|
-
|
|
386
|
-
const output = await openExportOutput(filePath, isEncrypted ? await getSecret() : null);
|
|
387
|
-
const gzipStream = output.input;
|
|
388
|
-
const fileStream = output.output;
|
|
389
|
-
|
|
390
|
-
function writeWithBackpressure(data) {
|
|
391
|
-
if (output.error()) {
|
|
392
|
-
return Promise.reject(output.error());
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
if (gzipStream.write(data)) {
|
|
396
|
-
return Promise.resolve();
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
return new Promise((resolve, reject) => {
|
|
400
|
-
const cleanup = () => {
|
|
401
|
-
gzipStream.removeListener('drain', onDrain);
|
|
402
|
-
gzipStream.removeListener('error', onError);
|
|
403
|
-
};
|
|
404
|
-
const onDrain = () => {
|
|
405
|
-
cleanup();
|
|
406
|
-
resolve();
|
|
407
|
-
};
|
|
408
|
-
const onError = err => {
|
|
409
|
-
cleanup();
|
|
410
|
-
reject(err);
|
|
411
|
-
};
|
|
412
|
-
gzipStream.once('drain', onDrain);
|
|
413
|
-
gzipStream.once('error', onError);
|
|
414
|
-
});
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
let processed = 0;
|
|
418
|
-
let totalBytesWritten = 0;
|
|
419
|
-
let processingError = null;
|
|
420
|
-
let sizeLimitReached = false;
|
|
421
|
-
|
|
422
|
-
let lastAccountCheck = Date.now();
|
|
423
|
-
// Refreshes the job lock and export key expiry on a fixed cadence; called from the main loop and
|
|
424
|
-
// from inside the retry backoff so a batch stuck retrying does not let the lock lapse.
|
|
425
|
-
const maybeExtendLease = createLeaseExtender(job, account, exportId);
|
|
426
|
-
|
|
427
|
-
const MESSAGE_FETCH_BATCH_SIZE = 10; // Batch size for parallel message fetching
|
|
428
|
-
const MAX_BATCH_RETRIES = 5; // Max retries for rate-limited or transient per-message errors within a batch
|
|
429
|
-
const BATCH_RETRY_BASE_DELAY = 5000; // Base delay for batch retry backoff (5 seconds)
|
|
430
|
-
|
|
431
|
-
async function processMessage(message, entry) {
|
|
432
|
-
message.path = entry.folder;
|
|
433
|
-
|
|
434
|
-
if (includeAttachments && message.attachments && message.attachments.length) {
|
|
435
|
-
for (const attachment of message.attachments) {
|
|
436
|
-
try {
|
|
437
|
-
if (attachment.size && attachment.size > maxMessageSize) {
|
|
438
|
-
attachment.contentError = `Attachment too large (${attachment.size} bytes, limit ${maxMessageSize})`;
|
|
439
|
-
continue;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
const stream = await accountObject.getAttachment(attachment.id);
|
|
443
|
-
const chunks = [];
|
|
444
|
-
let totalSize = 0;
|
|
445
|
-
|
|
446
|
-
for await (const chunk of stream) {
|
|
447
|
-
totalSize += chunk.length;
|
|
448
|
-
if (totalSize > maxMessageSize) {
|
|
449
|
-
if (typeof stream.destroy === 'function') {
|
|
450
|
-
stream.destroy();
|
|
451
|
-
await new Promise(resolve => {
|
|
452
|
-
const CLEANUP_TIMEOUT_MS = 1000;
|
|
453
|
-
stream.once('close', resolve);
|
|
454
|
-
setTimeout(resolve, CLEANUP_TIMEOUT_MS);
|
|
455
|
-
});
|
|
456
|
-
}
|
|
457
|
-
throw new Error(`Attachment exceeds size limit (>${maxMessageSize} bytes)`);
|
|
458
|
-
}
|
|
459
|
-
chunks.push(chunk);
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
attachment.content = Buffer.concat(chunks).toString('base64');
|
|
463
|
-
} catch (attachErr) {
|
|
464
|
-
attachment.contentError = attachErr.message;
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
const line = JSON.stringify(message) + '\n';
|
|
470
|
-
await writeWithBackpressure(line);
|
|
471
|
-
totalBytesWritten += Buffer.byteLength(line);
|
|
472
|
-
|
|
473
|
-
await Export.incrementExported(account, exportId, Buffer.byteLength(line));
|
|
474
|
-
processed++;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
try {
|
|
478
|
-
while (true) {
|
|
479
|
-
if (output.error()) {
|
|
480
|
-
throw output.error();
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
if (sizeLimitReached) {
|
|
484
|
-
break;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
await maybeExtendLease();
|
|
488
|
-
|
|
489
|
-
if (await Export.isCancelled(account, exportId)) {
|
|
490
|
-
const err = new Error('Export cancelled by user');
|
|
491
|
-
err.code = 'ExportCancelled';
|
|
492
|
-
throw err;
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
if (Date.now() - lastAccountCheck > ACCOUNT_CHECK_INTERVAL) {
|
|
496
|
-
const accountCheck = await redis.hgetall(`${REDIS_PREFIX}iad:${account}`);
|
|
497
|
-
if (!accountCheck || !accountCheck.account) {
|
|
498
|
-
const err = new Error('Account was deleted during export');
|
|
499
|
-
err.code = 'AccountDeleted';
|
|
500
|
-
throw err;
|
|
501
|
-
}
|
|
502
|
-
lastAccountCheck = Date.now();
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
const batch = await Export.getNextBatch(account, exportId, BATCH_SIZE);
|
|
506
|
-
if (batch.length === 0) {
|
|
507
|
-
break;
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
const entriesToFetch = [];
|
|
511
|
-
for (const entry of batch) {
|
|
512
|
-
if (includeAttachments && entry.size > maxMessageSize) {
|
|
513
|
-
await Export.incrementSkipped(account, exportId);
|
|
514
|
-
} else {
|
|
515
|
-
entriesToFetch.push(entry);
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
if (entriesToFetch.length === 0) {
|
|
520
|
-
continue;
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
if (isApiAccount && entriesToFetch.length > 1) {
|
|
524
|
-
for (let i = 0; i < entriesToFetch.length; i += MESSAGE_FETCH_BATCH_SIZE) {
|
|
525
|
-
if (output.error()) {
|
|
526
|
-
throw output.error();
|
|
527
|
-
}
|
|
528
|
-
if (sizeLimitReached) {
|
|
529
|
-
break;
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
let fetchBatch = entriesToFetch.slice(i, i + MESSAGE_FETCH_BATCH_SIZE);
|
|
533
|
-
let batchRetry = 0;
|
|
534
|
-
|
|
535
|
-
while (fetchBatch.length > 0) {
|
|
536
|
-
const messageIds = fetchBatch.map(e => e.messageId);
|
|
537
|
-
const messageResults = await accountObject.getMessages(messageIds, { textType, maxBytes });
|
|
538
|
-
|
|
539
|
-
const resultMap = new Map();
|
|
540
|
-
for (const result of messageResults) {
|
|
541
|
-
resultMap.set(result.messageId, result);
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
const retryEntries = [];
|
|
545
|
-
|
|
546
|
-
for (const entry of fetchBatch) {
|
|
547
|
-
const result = resultMap.get(entry.messageId);
|
|
548
|
-
|
|
549
|
-
if (result && result.error) {
|
|
550
|
-
const err = result.error;
|
|
551
|
-
// A single transient blip (rate limit, dropped batch response, network/5xx)
|
|
552
|
-
// must not fail an entire multi-message export; only give up once the retry
|
|
553
|
-
// budget is exhausted. See isRetryableError for the full classification.
|
|
554
|
-
const isRetryable = isRetryableError(err);
|
|
555
|
-
|
|
556
|
-
if (isSkippableError(err)) {
|
|
557
|
-
logger.warn({
|
|
558
|
-
msg: 'Skipping message during export',
|
|
559
|
-
account,
|
|
560
|
-
exportId,
|
|
561
|
-
messageId: entry.messageId,
|
|
562
|
-
folder: entry.folder,
|
|
563
|
-
reason: err.message || err.code
|
|
564
|
-
});
|
|
565
|
-
await Export.incrementSkipped(account, exportId);
|
|
566
|
-
} else if (isRetryable && batchRetry < MAX_BATCH_RETRIES) {
|
|
567
|
-
retryEntries.push(entry);
|
|
568
|
-
} else {
|
|
569
|
-
const error = new Error(err.message);
|
|
570
|
-
error.code = err.code;
|
|
571
|
-
error.statusCode = err.statusCode;
|
|
572
|
-
throw error;
|
|
573
|
-
}
|
|
574
|
-
} else if (result && result.data) {
|
|
575
|
-
await processMessage(result.data, entry);
|
|
576
|
-
if (isExportLimitReached(totalBytesWritten, maxExportSize)) {
|
|
577
|
-
sizeLimitReached = true;
|
|
578
|
-
break;
|
|
579
|
-
}
|
|
580
|
-
} else {
|
|
581
|
-
logger.warn({
|
|
582
|
-
msg: 'Skipping message during export',
|
|
583
|
-
account,
|
|
584
|
-
exportId,
|
|
585
|
-
messageId: entry.messageId,
|
|
586
|
-
folder: entry.folder,
|
|
587
|
-
reason: 'Message not found in batch results'
|
|
588
|
-
});
|
|
589
|
-
await Export.incrementSkipped(account, exportId);
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
if (sizeLimitReached) {
|
|
594
|
-
break;
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
if (retryEntries.length > 0) {
|
|
598
|
-
batchRetry++;
|
|
599
|
-
const delay = BATCH_RETRY_BASE_DELAY * Math.pow(2, batchRetry - 1) + Math.random() * 1000;
|
|
600
|
-
logger.warn({
|
|
601
|
-
msg: 'Retrying failed messages during export batch',
|
|
602
|
-
account,
|
|
603
|
-
exportId,
|
|
604
|
-
retryCount: retryEntries.length,
|
|
605
|
-
attempt: batchRetry,
|
|
606
|
-
maxAttempts: MAX_BATCH_RETRIES,
|
|
607
|
-
delayMs: Math.round(delay)
|
|
608
|
-
});
|
|
609
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
610
|
-
await maybeExtendLease();
|
|
611
|
-
fetchBatch = retryEntries;
|
|
612
|
-
} else {
|
|
613
|
-
break;
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
} else {
|
|
618
|
-
for (const entry of entriesToFetch) {
|
|
619
|
-
if (output.error()) {
|
|
620
|
-
throw output.error();
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
let message = null;
|
|
624
|
-
let fetchError = null;
|
|
625
|
-
|
|
626
|
-
for (let attempt = 1; attempt <= IMAP_MESSAGE_MAX_RETRIES; attempt++) {
|
|
627
|
-
try {
|
|
628
|
-
message = await accountObject.getMessage(entry.messageId, { textType, maxBytes });
|
|
629
|
-
break; // Success - exit retry loop
|
|
630
|
-
} catch (err) {
|
|
631
|
-
if (isSkippableError(err)) {
|
|
632
|
-
fetchError = err;
|
|
633
|
-
break;
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
if (isTransientError(err) && attempt < IMAP_MESSAGE_MAX_RETRIES) {
|
|
637
|
-
const delay = IMAP_MESSAGE_RETRY_BASE_DELAY * Math.pow(2, attempt - 1);
|
|
638
|
-
logger.warn({
|
|
639
|
-
msg: 'Message fetch failed, retrying',
|
|
640
|
-
account,
|
|
641
|
-
exportId,
|
|
642
|
-
messageId: entry.messageId,
|
|
643
|
-
folder: entry.folder,
|
|
644
|
-
attempt,
|
|
645
|
-
maxAttempts: IMAP_MESSAGE_MAX_RETRIES,
|
|
646
|
-
delayMs: delay,
|
|
647
|
-
err
|
|
648
|
-
});
|
|
649
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
650
|
-
continue;
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
fetchError = err;
|
|
654
|
-
break;
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
if (message) {
|
|
659
|
-
await processMessage(message, entry);
|
|
660
|
-
if (isExportLimitReached(totalBytesWritten, maxExportSize)) {
|
|
661
|
-
sizeLimitReached = true;
|
|
662
|
-
break;
|
|
663
|
-
}
|
|
664
|
-
} else if (fetchError && isSkippableError(fetchError)) {
|
|
665
|
-
logger.warn({
|
|
666
|
-
msg: 'Skipping message during export',
|
|
667
|
-
account,
|
|
668
|
-
exportId,
|
|
669
|
-
messageId: entry.messageId,
|
|
670
|
-
folder: entry.folder,
|
|
671
|
-
reason: fetchError.message || fetchError.code
|
|
672
|
-
});
|
|
673
|
-
await Export.incrementSkipped(account, exportId);
|
|
674
|
-
} else if (fetchError) {
|
|
675
|
-
throw fetchError;
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
logger.trace({ msg: 'Export batch processed', account, exportId, messagesExported: processed });
|
|
681
|
-
}
|
|
682
|
-
} catch (err) {
|
|
683
|
-
processingError = err;
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
const FINALIZATION_TIMEOUT = 30000;
|
|
687
|
-
await new Promise((resolve, reject) => {
|
|
688
|
-
if (output.error()) {
|
|
689
|
-
// The chain already failed and pipeline() tore it down, so no 'finish' or 'error'
|
|
690
|
-
// is coming; waiting would only run out the timeout
|
|
691
|
-
output.destroy();
|
|
692
|
-
return reject(output.error());
|
|
693
|
-
}
|
|
694
|
-
const timeout = setTimeout(() => {
|
|
695
|
-
output.destroy();
|
|
696
|
-
reject(output.error() || new Error('Stream finalization timed out'));
|
|
697
|
-
}, FINALIZATION_TIMEOUT);
|
|
698
|
-
gzipStream.end();
|
|
699
|
-
fileStream.once('finish', () => {
|
|
700
|
-
clearTimeout(timeout);
|
|
701
|
-
resolve();
|
|
702
|
-
});
|
|
703
|
-
fileStream.once('error', err => {
|
|
704
|
-
clearTimeout(timeout);
|
|
705
|
-
reject(output.error() || err);
|
|
706
|
-
});
|
|
707
|
-
});
|
|
708
|
-
|
|
709
|
-
if (processingError) {
|
|
710
|
-
throw processingError;
|
|
711
|
-
}
|
|
712
|
-
if (output.error()) {
|
|
713
|
-
throw output.error();
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
// Written after the file is closed, so a failure here cannot leave the streams open
|
|
717
|
-
if (sizeLimitReached) {
|
|
718
|
-
logger.warn({
|
|
719
|
-
msg: 'Export truncated: size limit reached',
|
|
102
|
+
const { indexMessages, exportMessages } = createExportJobs({
|
|
103
|
+
redis,
|
|
104
|
+
settings,
|
|
105
|
+
getSecret,
|
|
106
|
+
logger,
|
|
107
|
+
createAccount: async account =>
|
|
108
|
+
new Account({
|
|
720
109
|
account,
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
})
|
|
726
|
-
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
logger.info({ msg: 'Export messages completed', account, exportId, messagesExported: processed, bytesWritten: totalBytesWritten });
|
|
730
|
-
}
|
|
110
|
+
redis,
|
|
111
|
+
call,
|
|
112
|
+
secret: await getSecret(),
|
|
113
|
+
timeout: EXPORT_TIMEOUT
|
|
114
|
+
})
|
|
115
|
+
});
|
|
731
116
|
|
|
732
117
|
const exportWorker = new Worker(
|
|
733
118
|
'export',
|
package/workers/imap.js
CHANGED
|
@@ -432,6 +432,18 @@ class ConnectionHandler {
|
|
|
432
432
|
}
|
|
433
433
|
}
|
|
434
434
|
|
|
435
|
+
/**
|
|
436
|
+
* Removes what the provider keeps for the account, ahead of its deletion, see
|
|
437
|
+
* BaseClient.releaseRemoteResources()
|
|
438
|
+
*/
|
|
439
|
+
async teardownConnection(account) {
|
|
440
|
+
const accountObject = this.accounts.get(account);
|
|
441
|
+
if (!accountObject?.connection) {
|
|
442
|
+
return false;
|
|
443
|
+
}
|
|
444
|
+
return await accountObject.connection.releaseRemoteResources();
|
|
445
|
+
}
|
|
446
|
+
|
|
435
447
|
async updateConnection(account) {
|
|
436
448
|
logger.info({ msg: 'Account update requested', account });
|
|
437
449
|
if (this.accounts.has(account)) {
|
|
@@ -1006,6 +1018,7 @@ class ConnectionHandler {
|
|
|
1006
1018
|
return await this.syncConnection(message.account, { since: message.since });
|
|
1007
1019
|
|
|
1008
1020
|
case 'delete':
|
|
1021
|
+
case 'teardown':
|
|
1009
1022
|
case 'unassign':
|
|
1010
1023
|
case 'update':
|
|
1011
1024
|
case 'pause':
|