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.
- package/.ncurc.js +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +74 -0
- package/Dockerfile +14 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +1 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +194 -165
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +78 -26
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +4 -3
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- 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 +130 -156
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +51 -11
- 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 -226
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- 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 +17 -1
- package/lib/get-raw-email.js +25 -107
- package/lib/health.js +75 -0
- 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/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth2-apps.js +630 -655
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- 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 +163 -39
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- 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/settings-page.js +6 -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/tracking-settings.js +35 -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 +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +54 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +21 -20
- package/sbom.json +304 -382
- package/server.js +149 -76
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +21 -31
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +102 -28
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- package/lib/email-client/outlook-fallback-poll.js +0 -30
|
@@ -6,7 +6,6 @@ const { ReconnectBackoff } = require('../reconnect-backoff');
|
|
|
6
6
|
const { detachImapClient } = require('./detach-client');
|
|
7
7
|
const { connectionUnavailableError } = require('./connection-errors');
|
|
8
8
|
const { isRefusedImapLogin } = require('./login-failure');
|
|
9
|
-
const { samePath } = require('../../utils/mailbox-path');
|
|
10
9
|
const EventEmitter = require('events').EventEmitter;
|
|
11
10
|
|
|
12
11
|
const MAX_WAIT_DELAY = 450; //ms
|
|
@@ -130,29 +129,9 @@ class Subconnection extends EventEmitter {
|
|
|
130
129
|
// base delay on every cycle when the mailbox itself can not be opened
|
|
131
130
|
this.reconnectBackoff.reset();
|
|
132
131
|
} catch (err) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
// getMailboxLock(). mailboxOpen() itself does not set the
|
|
137
|
-
// mailboxMissing marker
|
|
138
|
-
try {
|
|
139
|
-
let folders = await this.imapClient.run('LIST', '', this.mailbox.path, { listOnly: true });
|
|
140
|
-
// The path goes into the LIST command as the match pattern
|
|
141
|
-
// verbatim, so IMAP wildcards (% and *) in the folder name
|
|
142
|
-
// can match sibling folders. Only an entry naming the same
|
|
143
|
-
// folder proves the monitored mailbox still exists - matched
|
|
144
|
-
// through samePath() because a server is free to answer with
|
|
145
|
-
// a different case for INBOX than the one it listed earlier,
|
|
146
|
-
// and reading that as a missing folder disables the
|
|
147
|
-
// subconnection until the folder is seen again
|
|
148
|
-
if (!folders || !folders.some(folder => samePath(folder.path, this.mailbox.path))) {
|
|
149
|
-
err.mailboxMissing = true;
|
|
150
|
-
}
|
|
151
|
-
} catch (E) {
|
|
152
|
-
this.logger.debug({ msg: 'Failed to verify missing mailbox', path: this.mailbox.path, err: E });
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
132
|
+
// A SELECT refused with NO comes back with mailboxMissing set when the folder is gone:
|
|
133
|
+
// ImapFlow (2.6.0) checks it with an exact LIST match that ignores \NonExistent entries,
|
|
134
|
+
// which is what the LIST this used to run itself was for
|
|
156
135
|
if (err.mailboxMissing) {
|
|
157
136
|
// The monitored folder does not exist anymore, so retrying can
|
|
158
137
|
// not succeed. Shut the subconnection down and mark it as
|
|
@@ -208,7 +187,7 @@ class Subconnection extends EventEmitter {
|
|
|
208
187
|
if (this.imapClient) {
|
|
209
188
|
// close previous
|
|
210
189
|
let prevImapClient = this.imapClient;
|
|
211
|
-
prevImapClient.disabled = true;
|
|
190
|
+
prevImapClient.context.disabled = true;
|
|
212
191
|
try {
|
|
213
192
|
detachImapClient(prevImapClient, this.logger, { type: 'subConnection', previous: true, account: this.account });
|
|
214
193
|
prevImapClient.close();
|
|
@@ -234,7 +213,8 @@ class Subconnection extends EventEmitter {
|
|
|
234
213
|
let imapClient = createImapClient(
|
|
235
214
|
Object.assign({}, imapConfig, {
|
|
236
215
|
logger: this.logger,
|
|
237
|
-
expungeHandler: async payload => await this.expungeHandler(payload)
|
|
216
|
+
expungeHandler: async payload => await this.expungeHandler(payload),
|
|
217
|
+
context: { disabled: false }
|
|
238
218
|
})
|
|
239
219
|
);
|
|
240
220
|
this.parent.connections.add(imapClient);
|
|
@@ -242,8 +222,6 @@ class Subconnection extends EventEmitter {
|
|
|
242
222
|
|
|
243
223
|
this.imapClient = imapClient;
|
|
244
224
|
|
|
245
|
-
imapClient.subConnection = true;
|
|
246
|
-
|
|
247
225
|
imapClient.on('error', err => {
|
|
248
226
|
if (!imapClient) {
|
|
249
227
|
// The close handler already let go of this client. The missing-mailbox and
|
|
@@ -271,7 +249,7 @@ class Subconnection extends EventEmitter {
|
|
|
271
249
|
}
|
|
272
250
|
|
|
273
251
|
try {
|
|
274
|
-
if (!imapClient.disabled && imapClient === this.imapClient && !this._connecting) {
|
|
252
|
+
if (!imapClient.context?.disabled && imapClient === this.imapClient && !this._connecting) {
|
|
275
253
|
await this.reconnect();
|
|
276
254
|
}
|
|
277
255
|
} catch (err) {
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const { samePath } = require('../../utils/mailbox-path');
|
|
4
|
-
const { connectionClosedError, connectionNotAvailableError } = require('./connection-errors');
|
|
4
|
+
const { connectionClosedError, connectionNotAvailableError, syncInterrupted } = require('./connection-errors');
|
|
5
5
|
const crypto = require('crypto');
|
|
6
|
+
const { createTransaction } = require('../../redis-operations');
|
|
6
7
|
const { compareExisting, calculateFetchBackoff, readEnvValue, validUidValidity } = require('../../tools');
|
|
7
8
|
const config = require('@zone-eu/wild-config');
|
|
8
9
|
const { DEFAULT_FETCH_BATCH_SIZE, FETCH_RETRY_MAX_TIME, FETCH_RETRY_MIN_ATTEMPTS, MAILBOX_RESET_NOTIFY } = require('../../consts');
|
|
9
10
|
|
|
11
|
+
// Fetched messages compared with the index per read of it
|
|
12
|
+
const SYNC_CHUNK_SIZE = 500;
|
|
13
|
+
|
|
10
14
|
// Configurable batch size for fetching messages (default: 250)
|
|
11
15
|
const FETCH_BATCH_SIZE = Number(readEnvValue('EENGINE_FETCH_BATCH_SIZE') || config.service.fetchBatchSize) || DEFAULT_FETCH_BATCH_SIZE;
|
|
12
16
|
|
|
@@ -144,6 +148,31 @@ function shouldSeedLostIndex(storedStatus, mailboxStatus, previouslyConnected) {
|
|
|
144
148
|
return Number(previouslyConnected) > 1 && !(storedStatus && storedStatus.hasStoredState) && Number(mailboxStatus.messages) > 0;
|
|
145
149
|
}
|
|
146
150
|
|
|
151
|
+
/**
|
|
152
|
+
* The entry a fetched message is queued with for new message processing
|
|
153
|
+
* @param {Object} messageData - Fetched message
|
|
154
|
+
* @returns {string}
|
|
155
|
+
*/
|
|
156
|
+
function notificationEntry(messageData) {
|
|
157
|
+
return JSON.stringify({
|
|
158
|
+
uid: messageData.uid,
|
|
159
|
+
flags: messageData.flags,
|
|
160
|
+
internalDate: (messageData.internalDate && typeof messageData.internalDate.toISOString === 'function' && messageData.internalDate.toISOString()) || null
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Queues fetched messages for new message processing onto a transaction
|
|
166
|
+
* @param {Object} txn - Transaction from createTransaction()
|
|
167
|
+
* @param {string} notificationsKey - The mailbox's notifications queue
|
|
168
|
+
* @param {Object[]} messages - Fetched messages
|
|
169
|
+
*/
|
|
170
|
+
function queueNotifications(txn, notificationsKey, messages) {
|
|
171
|
+
for (const messageData of messages) {
|
|
172
|
+
txn.add('zadd', notificationsKey, messageData.uid, notificationEntry(messageData));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
147
176
|
/**
|
|
148
177
|
* Handles the synchronization of IMAP mailboxes
|
|
149
178
|
*/
|
|
@@ -373,33 +402,7 @@ class SyncOperations {
|
|
|
373
402
|
// ensure that messages are sorted by UID
|
|
374
403
|
messages = messages.sort((a, b) => a.uid - b.uid);
|
|
375
404
|
|
|
376
|
-
|
|
377
|
-
for (let messageData of messages) {
|
|
378
|
-
// Update uidNext if this is a new message
|
|
379
|
-
let updated = await this.connection.redis.hUpdateBigger(
|
|
380
|
-
this.mailbox.getMailboxKey(),
|
|
381
|
-
'uidNext',
|
|
382
|
-
messageData.uid + 1,
|
|
383
|
-
messageData.uid + 1
|
|
384
|
-
);
|
|
385
|
-
|
|
386
|
-
if (updated) {
|
|
387
|
-
// new email! Queue for processing
|
|
388
|
-
await this.connection.redis.zadd(
|
|
389
|
-
this.mailbox.getNotificationsKey(),
|
|
390
|
-
messageData.uid,
|
|
391
|
-
JSON.stringify({
|
|
392
|
-
uid: messageData.uid,
|
|
393
|
-
flags: messageData.flags,
|
|
394
|
-
internalDate:
|
|
395
|
-
(messageData.internalDate &&
|
|
396
|
-
typeof messageData.internalDate.toISOString === 'function' &&
|
|
397
|
-
messageData.internalDate.toISOString()) ||
|
|
398
|
-
null
|
|
399
|
-
})
|
|
400
|
-
);
|
|
401
|
-
}
|
|
402
|
-
}
|
|
405
|
+
await this.queueNewMessages(messages);
|
|
403
406
|
|
|
404
407
|
try {
|
|
405
408
|
// clear failure flag
|
|
@@ -429,7 +432,7 @@ class SyncOperations {
|
|
|
429
432
|
}
|
|
430
433
|
|
|
431
434
|
// Retry with exponential backoff
|
|
432
|
-
if (
|
|
435
|
+
if (syncInterrupted(imapClient, err)) {
|
|
433
436
|
// connection closed, throw so callers know sync was interrupted
|
|
434
437
|
throw connectionClosedError(err);
|
|
435
438
|
}
|
|
@@ -438,7 +441,7 @@ class SyncOperations {
|
|
|
438
441
|
this.logger.warn({ msg: 'FETCH failed, retrying', retryDelay: Math.round(fetchRetryDelay), err });
|
|
439
442
|
await new Promise(r => setTimeout(r, fetchRetryDelay));
|
|
440
443
|
|
|
441
|
-
if (
|
|
444
|
+
if (syncInterrupted(imapClient, err)) {
|
|
442
445
|
// connection closed, throw so callers know sync was interrupted
|
|
443
446
|
throw connectionClosedError(err);
|
|
444
447
|
}
|
|
@@ -458,6 +461,176 @@ class SyncOperations {
|
|
|
458
461
|
}
|
|
459
462
|
}
|
|
460
463
|
|
|
464
|
+
/**
|
|
465
|
+
* Fast sync: queues the fetched messages above the stored UIDNEXT for processing and moves the
|
|
466
|
+
* stored UIDNEXT past them
|
|
467
|
+
* @param {Object[]} messages - Fetched messages, sorted by UID
|
|
468
|
+
*/
|
|
469
|
+
async queueNewMessages(messages) {
|
|
470
|
+
if (!messages.length) {
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// One read and one transaction instead of two round trips per message. The messages are in
|
|
475
|
+
// UID order, so the ones a per-message HUPDATEBIGGER let through are exactly those above the
|
|
476
|
+
// stored value (all of them when it is missing or not a number). The transaction queues them
|
|
477
|
+
// and moves UIDNEXT together, so a failed write can no longer leave UIDNEXT past a message it
|
|
478
|
+
// did not queue. Runs under the mailbox lock, which is what keeps the read current
|
|
479
|
+
const mailboxKey = this.mailbox.getMailboxKey();
|
|
480
|
+
const storedUidNext = Number(await this.connection.redis.hget(mailboxKey, 'uidNext'));
|
|
481
|
+
const fresh = Number.isFinite(storedUidNext) ? messages.filter(messageData => messageData.uid + 1 > storedUidNext) : messages;
|
|
482
|
+
if (!fresh.length) {
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const txn = createTransaction(this.connection.redis, { logger: this.logger });
|
|
487
|
+
queueNotifications(txn, this.mailbox.getNotificationsKey(), fresh);
|
|
488
|
+
const uidNext = fresh[fresh.length - 1].uid + 1;
|
|
489
|
+
txn.add('hUpdateBigger', mailboxKey, 'uidNext', uidNext, uidNext);
|
|
490
|
+
await txn.execOrThrow();
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Full sync: compares a chunk of fetched messages with the index. The index is read once for
|
|
495
|
+
* the chunk, as every entry from the last compared UID to the chunk's last one, instead of once
|
|
496
|
+
* per message, which made a resync of an unchanged folder cost a round trip per message.
|
|
497
|
+
*
|
|
498
|
+
* The entries between two consecutive fetched messages are the messages the server no longer
|
|
499
|
+
* has, but only when nothing on the server lies between those two: their sequence numbers have
|
|
500
|
+
* to be adjacent. Otherwise one of them is a message the server answered without UID or FLAGS
|
|
501
|
+
* (a partial row), or the numbering shifted under an expunge during the pass, and any of the
|
|
502
|
+
* entries could be it, so they are left for the next pass. Deletions used to be worked out from
|
|
503
|
+
* how far an entry's position in the index had moved from its sequence number, which took the
|
|
504
|
+
* wrong entries whenever a message missing from the index sat among them: it reported that one
|
|
505
|
+
* deleted and kept the one actually gone
|
|
506
|
+
* @param {Object[]} messages - Fetched messages in UID order, all above position.uid
|
|
507
|
+
* @param {{uid: number, seq: number}} position - Last message compared, updated as the chunk is processed
|
|
508
|
+
*/
|
|
509
|
+
async syncFetchedChunk(messages, position) {
|
|
510
|
+
if (!messages.length) {
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
const stored = await this.mailbox.entryListRange(position.uid, messages[messages.length - 1].uid);
|
|
515
|
+
|
|
516
|
+
const fresh = [];
|
|
517
|
+
const changed = [];
|
|
518
|
+
const gone = [];
|
|
519
|
+
let next = 0;
|
|
520
|
+
for (const messageData of messages) {
|
|
521
|
+
const gap = [];
|
|
522
|
+
while (next < stored.length && stored[next].uid < messageData.uid) {
|
|
523
|
+
gap.push(stored[next++]);
|
|
524
|
+
}
|
|
525
|
+
const storedMessage = next < stored.length && stored[next].uid === messageData.uid ? stored[next++] : null;
|
|
526
|
+
|
|
527
|
+
if (gap.length) {
|
|
528
|
+
gone.push(...this.gapDeletions(gap, messageData.seq - position.seq - 1));
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
if (!storedMessage || !storedMessage.entry) {
|
|
532
|
+
// a message the index does not know
|
|
533
|
+
fresh.push(messageData);
|
|
534
|
+
} else {
|
|
535
|
+
const changes = compareExisting(storedMessage.entry, messageData);
|
|
536
|
+
if (changes) {
|
|
537
|
+
changed.push({ messageData, changes });
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
position.uid = messageData.uid;
|
|
542
|
+
position.seq = messageData.seq;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
await this.writeChunk(fresh, changed);
|
|
546
|
+
await this.expungeStoredMany(gone);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Writes what a chunk compared: the index entries of its new and changed messages and the
|
|
551
|
+
* notifications queue entries of the new ones, in one transaction, then reports each changed
|
|
552
|
+
* message. The index write can not refuse a message with a UID (it replaces whatever held the
|
|
553
|
+
* UID), so the new messages are queued alongside it
|
|
554
|
+
* @param {Object[]} fresh - Fetched messages the index did not know
|
|
555
|
+
* @param {Array<{messageData: Object, changes: Object}>} changed - Messages whose flags or labels changed
|
|
556
|
+
*/
|
|
557
|
+
async writeChunk(fresh, changed) {
|
|
558
|
+
if (!fresh.length && !changed.length) {
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
const txn = createTransaction(this.connection.redis, { logger: this.logger });
|
|
562
|
+
queueNotifications(txn, this.mailbox.getNotificationsKey(), this.mailbox.entryListSetMany(txn, fresh));
|
|
563
|
+
const indexed = new Set(
|
|
564
|
+
this.mailbox.entryListSetMany(
|
|
565
|
+
txn,
|
|
566
|
+
changed.map(entry => entry.messageData)
|
|
567
|
+
)
|
|
568
|
+
);
|
|
569
|
+
await txn.execOrThrow();
|
|
570
|
+
|
|
571
|
+
// one stored status read for the messages reported, not one per message
|
|
572
|
+
const statusCache = new Map();
|
|
573
|
+
for (const { messageData, changes } of changed) {
|
|
574
|
+
if (indexed.has(messageData)) {
|
|
575
|
+
await this.mailbox.processChanges(messageData, changes, statusCache);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* The index entries to report deleted from a gap: all of them when the server has nothing
|
|
582
|
+
* between the messages around it, none otherwise
|
|
583
|
+
* @param {Object[]} entries - Index entries, from entryListRange()
|
|
584
|
+
* @param {number} unseen - Server messages between the two fetched messages that were not compared
|
|
585
|
+
* @returns {number[]} UIDs
|
|
586
|
+
*/
|
|
587
|
+
gapDeletions(entries, unseen) {
|
|
588
|
+
if (unseen !== 0) {
|
|
589
|
+
this.logger.debug({ msg: 'Kept index entries next to messages not compared', entries: entries.length, unseen });
|
|
590
|
+
return [];
|
|
591
|
+
}
|
|
592
|
+
this.logger.trace({ msg: 'Deleted range', inloop: true, entries: entries.length });
|
|
593
|
+
return entries.map(entry => entry.uid);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Removes entries from the index, and their notifications queue entries, in one round trip and
|
|
598
|
+
* reports each message deleted
|
|
599
|
+
* @param {number[]} uids
|
|
600
|
+
*/
|
|
601
|
+
async expungeStoredMany(uids) {
|
|
602
|
+
const statusCache = new Map();
|
|
603
|
+
for (const deletedEntry of await this.mailbox.entryListExpungeMany(uids)) {
|
|
604
|
+
await this.mailbox.processDeleted(deletedEntry, { statusCache, dequeued: true });
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Full sync: reports the index entries past the last message compared as deleted, unless the
|
|
610
|
+
* server has messages past it that could not be compared (a partial row at the end), which used
|
|
611
|
+
* to be reported deleted as well
|
|
612
|
+
* @param {{uid: number, seq: number}} position - Last message compared
|
|
613
|
+
* @param {number} serverMessages - Messages in the folder
|
|
614
|
+
*/
|
|
615
|
+
async expungeTrailing(position, serverMessages) {
|
|
616
|
+
if (serverMessages > position.seq) {
|
|
617
|
+
this.logger.debug({ msg: 'Kept index entries past messages not compared', position, serverMessages });
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
// A chunk at a time: after a mass deletion this can be most of the folder. The cursor moves
|
|
621
|
+
// past each chunk read, so an entry the expunge refuses can not bring the same chunk back
|
|
622
|
+
let after = position.uid;
|
|
623
|
+
let uids;
|
|
624
|
+
do {
|
|
625
|
+
uids = await this.mailbox.entryListUidsAfter(after, SYNC_CHUNK_SIZE);
|
|
626
|
+
if (uids.length) {
|
|
627
|
+
this.logger.trace({ msg: 'Deleted range', inloop: false, entries: uids.length, after });
|
|
628
|
+
await this.expungeStoredMany(uids);
|
|
629
|
+
after = uids[uids.length - 1];
|
|
630
|
+
}
|
|
631
|
+
} while (uids.length === SYNC_CHUNK_SIZE);
|
|
632
|
+
}
|
|
633
|
+
|
|
461
634
|
/**
|
|
462
635
|
* Partial sync - fetches only changed messages using MODSEQ or UID range
|
|
463
636
|
* Used for incremental updates when we know something changed
|
|
@@ -523,19 +696,7 @@ class SyncOperations {
|
|
|
523
696
|
let seq = await this.mailbox.entryListSet(messageData);
|
|
524
697
|
if (seq) {
|
|
525
698
|
// Queue for processing
|
|
526
|
-
await this.connection.redis.zadd(
|
|
527
|
-
this.mailbox.getNotificationsKey(),
|
|
528
|
-
messageData.uid,
|
|
529
|
-
JSON.stringify({
|
|
530
|
-
uid: messageData.uid,
|
|
531
|
-
flags: messageData.flags,
|
|
532
|
-
internalDate:
|
|
533
|
-
(messageData.internalDate &&
|
|
534
|
-
typeof messageData.internalDate.toISOString === 'function' &&
|
|
535
|
-
messageData.internalDate.toISOString()) ||
|
|
536
|
-
null
|
|
537
|
-
})
|
|
538
|
-
);
|
|
699
|
+
await this.connection.redis.zadd(this.mailbox.getNotificationsKey(), messageData.uid, notificationEntry(messageData));
|
|
539
700
|
}
|
|
540
701
|
} else if ((changes = compareExisting(storedMessage.entry, messageData))) {
|
|
541
702
|
// Existing message with changes
|
|
@@ -573,7 +734,7 @@ class SyncOperations {
|
|
|
573
734
|
}
|
|
574
735
|
|
|
575
736
|
// Retry with exponential backoff
|
|
576
|
-
if (
|
|
737
|
+
if (syncInterrupted(imapClient, err)) {
|
|
577
738
|
// connection closed, throw so callers know sync was interrupted
|
|
578
739
|
throw connectionClosedError(err);
|
|
579
740
|
}
|
|
@@ -582,7 +743,7 @@ class SyncOperations {
|
|
|
582
743
|
this.logger.warn({ msg: 'FETCH failed, retrying', retryDelay: Math.round(fetchRetryDelay), err });
|
|
583
744
|
await new Promise(r => setTimeout(r, fetchRetryDelay));
|
|
584
745
|
|
|
585
|
-
if (
|
|
746
|
+
if (syncInterrupted(imapClient, err)) {
|
|
586
747
|
// connection closed, throw so callers know sync was interrupted
|
|
587
748
|
throw connectionClosedError(err);
|
|
588
749
|
}
|
|
@@ -617,9 +778,6 @@ class SyncOperations {
|
|
|
617
778
|
// Generate unique ID for this sync loop to track batch ordering
|
|
618
779
|
const loopId = crypto.randomUUID();
|
|
619
780
|
|
|
620
|
-
// Wait for next tick to ensure ImapFlow has processed all untagged responses from SELECT
|
|
621
|
-
await new Promise(resolve => setImmediate(resolve));
|
|
622
|
-
|
|
623
781
|
let mailboxStatus = this.mailbox.getMailboxStatus();
|
|
624
782
|
|
|
625
783
|
this.logger.debug({
|
|
@@ -629,12 +787,8 @@ class SyncOperations {
|
|
|
629
787
|
mailboxStatus
|
|
630
788
|
});
|
|
631
789
|
|
|
632
|
-
//
|
|
633
|
-
let
|
|
634
|
-
let changes;
|
|
635
|
-
|
|
636
|
-
// Get current message count for deletion detection
|
|
637
|
-
let storedMaxSeqOld = await this.connection.redis.zcard(this.mailbox.getMessagesKey());
|
|
790
|
+
// The last message compared with the index, see syncFetchedChunk()
|
|
791
|
+
let position = { uid: 0, seq: 0 };
|
|
638
792
|
|
|
639
793
|
let responseCounters = {
|
|
640
794
|
empty: 0,
|
|
@@ -655,7 +809,6 @@ class SyncOperations {
|
|
|
655
809
|
|
|
656
810
|
// Process messages in batches to avoid memory issues
|
|
657
811
|
let range = false;
|
|
658
|
-
let lastHighestUid = 0;
|
|
659
812
|
let batchNumber = 0;
|
|
660
813
|
let fetchStartTime = Date.now();
|
|
661
814
|
let totalFetchRetryCount = 0;
|
|
@@ -693,6 +846,7 @@ class SyncOperations {
|
|
|
693
846
|
totalMessages: mailboxStatus.messages
|
|
694
847
|
});
|
|
695
848
|
|
|
849
|
+
let pending = [];
|
|
696
850
|
for await (let messageData of imapClient.fetch(range, fields, opts)) {
|
|
697
851
|
if (!messageData) {
|
|
698
852
|
this.logger.debug({ msg: 'Empty FETCH response', code: 'empty_fetch', query: { range, fields, opts } });
|
|
@@ -713,12 +867,11 @@ class SyncOperations {
|
|
|
713
867
|
continue;
|
|
714
868
|
}
|
|
715
869
|
|
|
716
|
-
if (messageData.uid <=
|
|
870
|
+
if (messageData.uid <= (pending.length ? pending[pending.length - 1].uid : position.uid)) {
|
|
717
871
|
// already processed in the previous batch
|
|
718
872
|
// probably an older email was deleted which shifted message entries
|
|
719
873
|
continue;
|
|
720
874
|
}
|
|
721
|
-
lastHighestUid = messageData.uid;
|
|
722
875
|
|
|
723
876
|
responseCounters.messages++;
|
|
724
877
|
|
|
@@ -734,53 +887,15 @@ class SyncOperations {
|
|
|
734
887
|
// ignore Recent flag
|
|
735
888
|
messageData.flags.delete('\\Recent');
|
|
736
889
|
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
// New message
|
|
744
|
-
let seq = await this.mailbox.entryListSet(messageData);
|
|
745
|
-
if (seq) {
|
|
746
|
-
await this.connection.redis.zadd(
|
|
747
|
-
this.mailbox.getNotificationsKey(),
|
|
748
|
-
messageData.uid,
|
|
749
|
-
JSON.stringify({
|
|
750
|
-
uid: messageData.uid,
|
|
751
|
-
flags: messageData.flags,
|
|
752
|
-
internalDate:
|
|
753
|
-
(messageData.internalDate &&
|
|
754
|
-
typeof messageData.internalDate.toISOString === 'function' &&
|
|
755
|
-
messageData.internalDate.toISOString()) ||
|
|
756
|
-
null
|
|
757
|
-
})
|
|
758
|
-
);
|
|
759
|
-
}
|
|
760
|
-
} else {
|
|
761
|
-
// Check for deleted messages between stored and current sequence
|
|
762
|
-
let diff = storedMessage.seq - messageData.seq;
|
|
763
|
-
if (diff) {
|
|
764
|
-
this.logger.trace({ msg: 'Deleted range', inloop: true, diff, start: messageData.seq });
|
|
765
|
-
}
|
|
766
|
-
// Process deletions
|
|
767
|
-
for (let i = diff - 1; i >= 0; i--) {
|
|
768
|
-
let seq = messageData.seq + i;
|
|
769
|
-
let deletedEntry = await this.mailbox.entryListExpunge(seq);
|
|
770
|
-
if (deletedEntry) {
|
|
771
|
-
await this.mailbox.processDeleted(deletedEntry);
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
// Check for changes
|
|
776
|
-
if ((changes = compareExisting(storedMessage.entry, messageData))) {
|
|
777
|
-
let seq = await this.mailbox.entryListSet(messageData);
|
|
778
|
-
if (seq) {
|
|
779
|
-
await this.mailbox.processChanges(messageData, changes);
|
|
780
|
-
}
|
|
781
|
-
}
|
|
890
|
+
// Compared in chunks, see syncFetchedChunk(). A FETCH that fails before
|
|
891
|
+
// a chunk is compared fetches it again on the retry
|
|
892
|
+
pending.push(messageData);
|
|
893
|
+
if (pending.length >= SYNC_CHUNK_SIZE) {
|
|
894
|
+
await this.syncFetchedChunk(pending, position);
|
|
895
|
+
pending = [];
|
|
782
896
|
}
|
|
783
897
|
}
|
|
898
|
+
await this.syncFetchedChunk(pending, position);
|
|
784
899
|
|
|
785
900
|
try {
|
|
786
901
|
// clear failure flag
|
|
@@ -800,7 +915,7 @@ class SyncOperations {
|
|
|
800
915
|
|
|
801
916
|
fetchCompleted = true;
|
|
802
917
|
} catch (err) {
|
|
803
|
-
if (
|
|
918
|
+
if (syncInterrupted(imapClient, err)) {
|
|
804
919
|
// A connection dropped mid-FETCH is the most common way a full sync
|
|
805
920
|
// dies, and this path sets no syncError flag, so report it here
|
|
806
921
|
this.logger.warn({
|
|
@@ -852,7 +967,7 @@ class SyncOperations {
|
|
|
852
967
|
});
|
|
853
968
|
await new Promise(r => setTimeout(r, fetchRetryDelay));
|
|
854
969
|
|
|
855
|
-
if (
|
|
970
|
+
if (syncInterrupted(imapClient, err)) {
|
|
856
971
|
// connection closed, throw so callers know sync was interrupted
|
|
857
972
|
throw connectionClosedError(err);
|
|
858
973
|
}
|
|
@@ -891,29 +1006,7 @@ class SyncOperations {
|
|
|
891
1006
|
}
|
|
892
1007
|
|
|
893
1008
|
// Delete any messages that weren't seen in this sync
|
|
894
|
-
|
|
895
|
-
let diff = storedMaxSeq - seqMax;
|
|
896
|
-
if (diff) {
|
|
897
|
-
this.logger.trace({
|
|
898
|
-
msg: 'Deleted range',
|
|
899
|
-
inloop: false,
|
|
900
|
-
diff,
|
|
901
|
-
start: seqMax + 1,
|
|
902
|
-
messagesKey: this.mailbox.getMessagesKey(),
|
|
903
|
-
zcard: storedMaxSeq,
|
|
904
|
-
zcardOld: storedMaxSeqOld,
|
|
905
|
-
responseCounters
|
|
906
|
-
});
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
// Process remaining deletions
|
|
910
|
-
for (let i = diff - 1; i >= 0; i--) {
|
|
911
|
-
let seq = seqMax + i + 1;
|
|
912
|
-
let deletedEntry = await this.mailbox.entryListExpunge(seq);
|
|
913
|
-
if (deletedEntry) {
|
|
914
|
-
await this.mailbox.processDeleted(deletedEntry);
|
|
915
|
-
}
|
|
916
|
-
}
|
|
1009
|
+
await this.expungeTrailing(position, mailboxStatus.messages);
|
|
917
1010
|
|
|
918
1011
|
// Persist the pre-sync snapshot (plus the full-sync timestamp) so
|
|
919
1012
|
// any arrivals that landed during this FETCH are still detected as
|