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