emailengine-app 2.81.0 → 2.81.2
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 +6 -1
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +32 -0
- package/Dockerfile +2 -2
- package/data/google-crawlers.json +1 -1
- package/lib/account/bounce-store-sweep.js +63 -0
- package/lib/account-assignment.js +70 -0
- package/lib/account.js +123 -22
- package/lib/api-routes/message-routes.js +4 -1
- package/lib/arf-detect.js +8 -1
- package/lib/consts.js +9 -0
- package/lib/db.js +0 -6
- package/lib/email-client/base-client.js +253 -94
- package/lib/email-client/gmail-client.js +95 -35
- package/lib/email-client/imap/mailbox.js +105 -230
- package/lib/email-client/outlook-client.js +325 -220
- package/lib/export.js +11 -2
- package/lib/msgpack.js +1 -6
- package/lib/schemas.js +7 -20
- package/package.json +21 -21
- package/sbom.json +1 -1
- package/server.js +25 -49
- package/static/licenses.html +70 -46
- package/translations/messages.pot +30 -30
- package/workers/api.js +13 -3
- package/workers/imap.js +8 -1
- package/lib/append-list.js +0 -63
- package/lib/lua/h-push.lua +0 -32
|
@@ -32,6 +32,8 @@ const {
|
|
|
32
32
|
OUTLOOK_RETRY_BASE_DELAY,
|
|
33
33
|
OUTLOOK_RETRY_MAX_DELAY,
|
|
34
34
|
OUTLOOK_CLOCK_SKEW_BUFFER,
|
|
35
|
+
OUTLOOK_MISSED_LOOKBACK,
|
|
36
|
+
OUTLOOK_ANNOUNCED_RETENTION,
|
|
35
37
|
MESSAGE_UPDATED_NOTIFY,
|
|
36
38
|
MESSAGE_DELETED_NOTIFY,
|
|
37
39
|
MESSAGE_MISSING_NOTIFY,
|
|
@@ -105,6 +107,9 @@ function graphFailureStatus(err) {
|
|
|
105
107
|
return Number(err?.statusCode) >= 400 ? Number(err.statusCode) : 400;
|
|
106
108
|
}
|
|
107
109
|
|
|
110
|
+
// How often the same folder id missing from the cached listing may trigger a listing refresh
|
|
111
|
+
const LISTING_REFRESH_INTERVAL = 5 * 60 * 1000;
|
|
112
|
+
|
|
108
113
|
class OutlookClient extends BaseClient {
|
|
109
114
|
constructor(account, options) {
|
|
110
115
|
super(account, options);
|
|
@@ -123,6 +128,9 @@ class OutlookClient extends BaseClient {
|
|
|
123
128
|
// Path for API calls - 'me' for current user or specific user email for delegated access
|
|
124
129
|
this.oauth2UserPath = 'me'; // can be changed to `users/${encodeURIComponent('shared@example.com')}` for delegated access
|
|
125
130
|
|
|
131
|
+
// Folder id -> when a miss on it last refreshed the listing, see mayRefreshListingFor()
|
|
132
|
+
this.listingRefreshes = new Map();
|
|
133
|
+
|
|
126
134
|
// Flags for background processing
|
|
127
135
|
this.processingHistory = null;
|
|
128
136
|
this.renewWatchTimer = null;
|
|
@@ -256,6 +264,7 @@ class OutlookClient extends BaseClient {
|
|
|
256
264
|
this.state = 'connecting';
|
|
257
265
|
clearTimeout(this.renewWatchTimer);
|
|
258
266
|
clearTimeout(this.renewRetryTimer);
|
|
267
|
+
this.cancelDeferredRetryTimer();
|
|
259
268
|
this.cancelInitRetry();
|
|
260
269
|
await this.setStateVal();
|
|
261
270
|
|
|
@@ -382,6 +391,10 @@ class OutlookClient extends BaseClient {
|
|
|
382
391
|
// Reset subscription retry counts on reconnect - fresh auth = fresh slate
|
|
383
392
|
await this.resetSubscriptionRetryState();
|
|
384
393
|
|
|
394
|
+
// A recovery pass must not look back past the point announced messages were first
|
|
395
|
+
// recorded, or its first run after an upgrade would announce hours of mail again
|
|
396
|
+
await this.redis.hsetnx(this.getAccountKey(), 'outlookAnnouncedSince', Date.now().toString());
|
|
397
|
+
|
|
385
398
|
// Set up webhook subscription for real-time updates
|
|
386
399
|
await this.ensureSubscription();
|
|
387
400
|
this.setupRenewWatchTimer();
|
|
@@ -394,6 +407,7 @@ class OutlookClient extends BaseClient {
|
|
|
394
407
|
}
|
|
395
408
|
|
|
396
409
|
// Start processing any pending webhook notifications
|
|
410
|
+
// (this also picks up the ones deferred for a retry before a restart)
|
|
397
411
|
this.triggerSync();
|
|
398
412
|
}
|
|
399
413
|
}
|
|
@@ -404,6 +418,7 @@ class OutlookClient extends BaseClient {
|
|
|
404
418
|
async close() {
|
|
405
419
|
clearTimeout(this.renewWatchTimer);
|
|
406
420
|
clearTimeout(this.renewRetryTimer);
|
|
421
|
+
this.cancelDeferredRetryTimer();
|
|
407
422
|
this.cancelInitRetry();
|
|
408
423
|
this.closed = true;
|
|
409
424
|
|
|
@@ -419,8 +434,8 @@ class OutlookClient extends BaseClient {
|
|
|
419
434
|
/**
|
|
420
435
|
* Performs an on-demand catch-up sync. Triggered by the "Run sync" action
|
|
421
436
|
* (PUT /v1/account/{account}/sync). Outlook syncs via webhook subscriptions and delta
|
|
422
|
-
* queries rather than a folder walk, so a manual sync refreshes the folder cache and
|
|
423
|
-
* the missed-notification recovery
|
|
437
|
+
* queries rather than a folder walk, so a manual sync refreshes the folder cache and queues
|
|
438
|
+
* the missed-notification recovery, which then runs and is retried like any other change.
|
|
424
439
|
*/
|
|
425
440
|
async syncMailboxes() {
|
|
426
441
|
if (this.closed) {
|
|
@@ -433,8 +448,19 @@ class OutlookClient extends BaseClient {
|
|
|
433
448
|
this.logger.warn({ msg: 'Failed to refresh folder cache for manual sync', account: this.account, err });
|
|
434
449
|
}
|
|
435
450
|
|
|
436
|
-
await this.
|
|
451
|
+
await this.accountObject.queueMissedRecovery();
|
|
452
|
+
this.recoverMissedNotifications();
|
|
453
|
+
|
|
454
|
+
return true;
|
|
455
|
+
}
|
|
437
456
|
|
|
457
|
+
/**
|
|
458
|
+
* Picks up a missed-notification recovery queued by the lifecycle webhook or by "Run sync".
|
|
459
|
+
* The request is already stored, so this only makes the next drain look for it
|
|
460
|
+
*/
|
|
461
|
+
recoverMissedNotifications() {
|
|
462
|
+
this.cancelDeferredRetryTimer();
|
|
463
|
+
this.retryDeferredEvents();
|
|
438
464
|
return true;
|
|
439
465
|
}
|
|
440
466
|
|
|
@@ -451,6 +477,7 @@ class OutlookClient extends BaseClient {
|
|
|
451
477
|
async delete() {
|
|
452
478
|
clearTimeout(this.renewWatchTimer);
|
|
453
479
|
clearTimeout(this.renewRetryTimer);
|
|
480
|
+
this.cancelDeferredRetryTimer();
|
|
454
481
|
this.cancelInitRetry();
|
|
455
482
|
this.closed = true;
|
|
456
483
|
|
|
@@ -505,11 +532,7 @@ class OutlookClient extends BaseClient {
|
|
|
505
532
|
if (!cachedListing || options?.statusQuery?.messages || (await this.renewMailboxFolderCache())) {
|
|
506
533
|
// Has changes or counters requested
|
|
507
534
|
mailboxListing = await this.getMailboxListing();
|
|
508
|
-
|
|
509
|
-
await this.redis.hset(this.getAccountCacheKey(), 'outlookMailboxListing', JSON.stringify(mailboxListing));
|
|
510
|
-
} catch (err) {
|
|
511
|
-
this.logger.error({ msg: 'Failed to cache mailbox listing', err });
|
|
512
|
-
}
|
|
535
|
+
await this.setCachedMailboxListing(mailboxListing);
|
|
513
536
|
|
|
514
537
|
if (!cachedListing && !options?.statusQuery?.messages) {
|
|
515
538
|
// Force delta update as it was not called previously
|
|
@@ -1780,6 +1803,10 @@ class OutlookClient extends BaseClient {
|
|
|
1780
1803
|
showPath: options.showPath
|
|
1781
1804
|
});
|
|
1782
1805
|
|
|
1806
|
+
if (specialUse) {
|
|
1807
|
+
formattedMessage.messageSpecialUse = specialUse;
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1783
1810
|
// Mark as seen if requested
|
|
1784
1811
|
if (options.markAsSeen && (!formattedMessage.flags || !formattedMessage.flags.includes('\\Seen'))) {
|
|
1785
1812
|
try {
|
|
@@ -1792,10 +1819,8 @@ class OutlookClient extends BaseClient {
|
|
|
1792
1819
|
}
|
|
1793
1820
|
}
|
|
1794
1821
|
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
if (!options.skipBounces) {
|
|
1798
|
-
await this.attachBounces(formattedMessage);
|
|
1822
|
+
if (options.detectBounce) {
|
|
1823
|
+
await this.detectBounce(formattedMessage);
|
|
1799
1824
|
}
|
|
1800
1825
|
|
|
1801
1826
|
// Generate web-safe HTML if requested
|
|
@@ -1835,10 +1860,6 @@ class OutlookClient extends BaseClient {
|
|
|
1835
1860
|
});
|
|
1836
1861
|
}
|
|
1837
1862
|
|
|
1838
|
-
if (specialUse) {
|
|
1839
|
-
formattedMessage.messageSpecialUse = specialUse;
|
|
1840
|
-
}
|
|
1841
|
-
|
|
1842
1863
|
return formattedMessage;
|
|
1843
1864
|
}
|
|
1844
1865
|
|
|
@@ -3349,6 +3370,30 @@ class OutlookClient extends BaseClient {
|
|
|
3349
3370
|
return cachedListing;
|
|
3350
3371
|
}
|
|
3351
3372
|
|
|
3373
|
+
/**
|
|
3374
|
+
* Whether a folder id missing from the cached listing may trigger a listing refresh, at most
|
|
3375
|
+
* once per LISTING_REFRESH_INTERVAL for the same id
|
|
3376
|
+
*/
|
|
3377
|
+
mayRefreshListingFor(folderId) {
|
|
3378
|
+
const now = Date.now();
|
|
3379
|
+
if (this.listingRefreshes.get(folderId) > now - LISTING_REFRESH_INTERVAL) {
|
|
3380
|
+
return false;
|
|
3381
|
+
}
|
|
3382
|
+
if (this.listingRefreshes.size > 100) {
|
|
3383
|
+
this.listingRefreshes.clear();
|
|
3384
|
+
}
|
|
3385
|
+
this.listingRefreshes.set(folderId, now);
|
|
3386
|
+
return true;
|
|
3387
|
+
}
|
|
3388
|
+
|
|
3389
|
+
async setCachedMailboxListing(mailboxListing) {
|
|
3390
|
+
try {
|
|
3391
|
+
await this.redis.hset(this.getAccountCacheKey(), 'outlookMailboxListing', JSON.stringify(mailboxListing));
|
|
3392
|
+
} catch (err) {
|
|
3393
|
+
this.logger.error({ msg: 'Failed to cache mailbox listing', err });
|
|
3394
|
+
}
|
|
3395
|
+
}
|
|
3396
|
+
|
|
3352
3397
|
/**
|
|
3353
3398
|
* Get complete mailbox folder listing from Graph API
|
|
3354
3399
|
* Handles special use folders and nested folder structures
|
|
@@ -3463,10 +3508,28 @@ class OutlookClient extends BaseClient {
|
|
|
3463
3508
|
|
|
3464
3509
|
// Callers that resolve multiple folders can pass a pre-fetched listing to avoid
|
|
3465
3510
|
// repeated cache reads or Graph API folder crawls
|
|
3466
|
-
let
|
|
3511
|
+
let cachedListing = !options.mailboxListing && (await this.getCachedMailboxListing());
|
|
3512
|
+
let mailboxListing = options.mailboxListing || cachedListing || (await this.getMailboxListing());
|
|
3467
3513
|
|
|
3468
3514
|
if (options.byId) {
|
|
3469
|
-
|
|
3515
|
+
let folder = mailboxListing.find(entry => entry.id === path);
|
|
3516
|
+
if (!folder && cachedListing && this.mayRefreshListingFor(path) && (await this.renewMailboxFolderCache())) {
|
|
3517
|
+
// A folder created after the listing was cached: without the refresh a new message
|
|
3518
|
+
// in it was reported as missing instead of new. Only when the folder delta reports
|
|
3519
|
+
// a change (it also reports one when it fails), and once per missing folder in a
|
|
3520
|
+
// while, as a folder the listing never includes would otherwise cost a request, or
|
|
3521
|
+
// during an outage a full folder crawl, per message
|
|
3522
|
+
try {
|
|
3523
|
+
mailboxListing = await this.getMailboxListing();
|
|
3524
|
+
} catch (err) {
|
|
3525
|
+
// the delta check consumed the change, forget it so the next miss asks again
|
|
3526
|
+
await this.redis.hdel(this.getAccountKey(), 'outlookMailFoldersDeltaUrl');
|
|
3527
|
+
throw err;
|
|
3528
|
+
}
|
|
3529
|
+
await this.setCachedMailboxListing(mailboxListing);
|
|
3530
|
+
folder = mailboxListing.find(entry => entry.id === path);
|
|
3531
|
+
}
|
|
3532
|
+
return folder;
|
|
3470
3533
|
}
|
|
3471
3534
|
|
|
3472
3535
|
// Map IMAP special use tags to Outlook folder types
|
|
@@ -4184,15 +4247,23 @@ class OutlookClient extends BaseClient {
|
|
|
4184
4247
|
*/
|
|
4185
4248
|
triggerSync() {
|
|
4186
4249
|
if (this.processingHistory) {
|
|
4250
|
+
// Run again when this drain is done: whatever asked may have arrived after the drain
|
|
4251
|
+
// looked for it (an event queued after its last pull, a recovery request)
|
|
4252
|
+
this.syncRequested = true;
|
|
4187
4253
|
return;
|
|
4188
4254
|
}
|
|
4189
4255
|
this.processingHistory = true;
|
|
4256
|
+
this.syncRequested = false;
|
|
4190
4257
|
this.processHistory()
|
|
4191
4258
|
.catch(err => {
|
|
4192
4259
|
this.logger.error({ msg: 'Failed to process account history', account: this.account, err });
|
|
4193
4260
|
})
|
|
4194
4261
|
.finally(() => {
|
|
4195
4262
|
this.processingHistory = false;
|
|
4263
|
+
this.scheduleDeferredRetryTimer();
|
|
4264
|
+
if (this.syncRequested && !this.closed) {
|
|
4265
|
+
this.triggerSync();
|
|
4266
|
+
}
|
|
4196
4267
|
});
|
|
4197
4268
|
}
|
|
4198
4269
|
|
|
@@ -4202,62 +4273,91 @@ class OutlookClient extends BaseClient {
|
|
|
4202
4273
|
*/
|
|
4203
4274
|
async processHistory() {
|
|
4204
4275
|
let event;
|
|
4205
|
-
let newMessageOptions;
|
|
4206
4276
|
let processedAny = false;
|
|
4277
|
+
const context = {};
|
|
4207
4278
|
|
|
4208
|
-
|
|
4209
|
-
|
|
4279
|
+
// The event is already off the queue, so a failure must not abort the drain and lose the
|
|
4280
|
+
// events behind it. A transient one is deferred and retried instead
|
|
4281
|
+
const handle = async event => {
|
|
4282
|
+
try {
|
|
4283
|
+
await this.processChangeEvent(event, context);
|
|
4284
|
+
} catch (err) {
|
|
4285
|
+
await this.deferFailedChangeEvent(event, err);
|
|
4286
|
+
}
|
|
4287
|
+
};
|
|
4210
4288
|
|
|
4211
|
-
|
|
4212
|
-
|
|
4213
|
-
|
|
4214
|
-
|
|
4289
|
+
// Changes deferred for a retry go first, then the queue
|
|
4290
|
+
try {
|
|
4291
|
+
await this.processDueDeferredEvents(handle);
|
|
4292
|
+
} catch (err) {
|
|
4293
|
+
this.logger.error({ msg: 'Failed to process deferred mailbox changes', account: this.account, err });
|
|
4294
|
+
}
|
|
4215
4295
|
|
|
4216
|
-
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
|
|
4296
|
+
while ((event = await this.accountObject.pullQueueEvent()) !== null) {
|
|
4297
|
+
processedAny = true;
|
|
4298
|
+
await handle(event);
|
|
4299
|
+
}
|
|
4220
4300
|
|
|
4221
|
-
|
|
4222
|
-
|
|
4223
|
-
|
|
4224
|
-
|
|
4225
|
-
}
|
|
4301
|
+
if (processedAny) {
|
|
4302
|
+
await this._updateLastNotificationTime();
|
|
4303
|
+
}
|
|
4304
|
+
}
|
|
4226
4305
|
|
|
4227
|
-
|
|
4306
|
+
/**
|
|
4307
|
+
* Processes one change notification, throwing when it could not be processed
|
|
4308
|
+
* @param {Object} event - Queue event
|
|
4309
|
+
* @param {Object} context - Shared by the events of one drain, caches the fetch options
|
|
4310
|
+
*/
|
|
4311
|
+
async processChangeEvent(event, context) {
|
|
4312
|
+
switch (event.type) {
|
|
4313
|
+
case 'updated':
|
|
4314
|
+
await this.processUpdatedMessage(event.message);
|
|
4315
|
+
break;
|
|
4228
4316
|
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
|
|
4232
|
-
// When an email is sent, multiple "created" events are triggered: one for the draft and one for the sent mail folder.
|
|
4233
|
-
// However, since we process the event with a delay, we only observe the message stored in the Sent Mail folder.
|
|
4234
|
-
// This happens because the message was already moved there by the time we began processing the initial event from the drafts folder.
|
|
4235
|
-
|
|
4236
|
-
// Check rolling bucket lock to see if we recently processed the same new email event for the same folder
|
|
4237
|
-
let recentlySeen = await this.rollingBucketLock(`${messageData.id}:created`, messageData.path);
|
|
4238
|
-
if (recentlySeen) {
|
|
4239
|
-
this.logger.debug({ msg: 'Ignore recently seen new email event', type: 'history-event', emailId: event.message });
|
|
4240
|
-
break;
|
|
4241
|
-
}
|
|
4317
|
+
case 'deleted':
|
|
4318
|
+
await this.processDeletedMessage(event.message);
|
|
4319
|
+
break;
|
|
4242
4320
|
|
|
4243
|
-
|
|
4244
|
-
|
|
4245
|
-
|
|
4246
|
-
|
|
4247
|
-
|
|
4248
|
-
|
|
4321
|
+
case 'created': {
|
|
4322
|
+
let messageData = await this.prepareNewMessage(event.message, await this.getDrainFetchOptions(context));
|
|
4323
|
+
if (messageData) {
|
|
4324
|
+
// When an email is sent, multiple "created" events are triggered: one for the draft and one for the sent mail folder.
|
|
4325
|
+
// However, since we process the event with a delay, we only observe the message stored in the Sent Mail folder.
|
|
4326
|
+
// This happens because the message was already moved there by the time we began processing the initial event from the drafts folder.
|
|
4327
|
+
|
|
4328
|
+
// Check rolling bucket lock to see if we recently processed the same new email event for the same folder
|
|
4329
|
+
// A retry runs up to an hour later, past the short-lived dedupe buckets, while a
|
|
4330
|
+
// recovery pass may have announced the message in the meantime
|
|
4331
|
+
if (
|
|
4332
|
+
(await this.isRecentlySeen(`${messageData.id}:created`, messageData.path)) ||
|
|
4333
|
+
(event.attempt && (await this.getAnnounced([messageData.id])).has(messageData.id))
|
|
4334
|
+
) {
|
|
4335
|
+
this.logger.debug({ msg: 'Ignore recently seen new email event', type: 'history-event', emailId: event.message });
|
|
4336
|
+
break;
|
|
4249
4337
|
}
|
|
4250
|
-
|
|
4338
|
+
|
|
4339
|
+
// processNew() clears messageData.path
|
|
4340
|
+
const path = messageData.path;
|
|
4341
|
+
await this.processNew(messageData, context.newMessageOptions);
|
|
4342
|
+
await this.markAnnounced(messageData.id, path);
|
|
4251
4343
|
}
|
|
4344
|
+
break;
|
|
4345
|
+
}
|
|
4252
4346
|
|
|
4253
|
-
|
|
4254
|
-
|
|
4347
|
+
case 'missedRecovery': {
|
|
4348
|
+
const since = await this.missedRecoveryStart(event.receivedAt);
|
|
4349
|
+
if (context.recoveredSince && context.recoveredSince <= since) {
|
|
4350
|
+
// an earlier request in the same drain already covered this window
|
|
4255
4351
|
break;
|
|
4352
|
+
}
|
|
4353
|
+
await this.syncMissedMessages({ since, options: await this.getDrainFetchOptions(context) });
|
|
4354
|
+
context.recoveredSince = since;
|
|
4355
|
+
break;
|
|
4256
4356
|
}
|
|
4257
|
-
}
|
|
4258
4357
|
|
|
4259
|
-
|
|
4260
|
-
|
|
4358
|
+
default:
|
|
4359
|
+
this.logger.debug({ msg: 'Ignoring unknown history event type', type: 'history-event', event });
|
|
4360
|
+
break;
|
|
4261
4361
|
}
|
|
4262
4362
|
}
|
|
4263
4363
|
|
|
@@ -4269,36 +4369,62 @@ class OutlookClient extends BaseClient {
|
|
|
4269
4369
|
}
|
|
4270
4370
|
}
|
|
4271
4371
|
|
|
4372
|
+
// Fetch options, resolved once per drain
|
|
4373
|
+
async getDrainFetchOptions(context) {
|
|
4374
|
+
if (!context.newMessageOptions) {
|
|
4375
|
+
context.newMessageOptions = await this.getMessageFetchOptions();
|
|
4376
|
+
context.newMessageOptions.showPath = true;
|
|
4377
|
+
}
|
|
4378
|
+
return context.newMessageOptions;
|
|
4379
|
+
}
|
|
4380
|
+
|
|
4272
4381
|
/**
|
|
4273
|
-
*
|
|
4274
|
-
*
|
|
4275
|
-
*
|
|
4276
|
-
*
|
|
4382
|
+
* Where a missed-notification recovery has to start looking. Graph retries an undeliverable
|
|
4383
|
+
* notification for hours before it gives up and reports it missed, so the lost changes can
|
|
4384
|
+
* be that old, and the last notification time is no bound: it moves on with every delivery
|
|
4385
|
+
* that did arrive in the meantime.
|
|
4386
|
+
*
|
|
4387
|
+
* Never further back than announced messages are remembered (older ones would be announced
|
|
4388
|
+
* again, and an account that was offline for days would flood its webhooks), than the point
|
|
4389
|
+
* they were first recorded, or than a previous recovery pass already reached
|
|
4390
|
+
* @param {number} receivedAt - When the recovery was requested (epoch ms)
|
|
4391
|
+
* @returns {Promise<number>} Epoch ms
|
|
4277
4392
|
*/
|
|
4278
|
-
async
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
//
|
|
4284
|
-
const
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4393
|
+
async missedRecoveryStart(receivedAt) {
|
|
4394
|
+
const [lastNotification, announcedSince, recoveredUntil] = (
|
|
4395
|
+
await this.redis.hmget(this.getAccountKey(), 'outlookLastNotification', 'outlookAnnouncedSince', 'outlookRecoveredUntil')
|
|
4396
|
+
).map(Number);
|
|
4397
|
+
|
|
4398
|
+
// 2-minute safety margin before the last known good notification and the last pass
|
|
4399
|
+
const margin = 2 * 60 * 1000;
|
|
4400
|
+
const wanted = Math.min(receivedAt - OUTLOOK_MISSED_LOOKBACK, lastNotification ? lastNotification - margin : Infinity);
|
|
4401
|
+
const trackedFrom = Math.max(Date.now() - OUTLOOK_ANNOUNCED_RETENTION, announcedSince || 0);
|
|
4402
|
+
const recoveredFrom = recoveredUntil ? recoveredUntil - margin : 0;
|
|
4403
|
+
|
|
4404
|
+
if (wanted < trackedFrom && recoveredFrom < trackedFrom) {
|
|
4405
|
+
this.logger.warn({
|
|
4406
|
+
msg: 'Missed notification recovery window truncated',
|
|
4407
|
+
account: this.account,
|
|
4408
|
+
wanted: new Date(wanted).toISOString(),
|
|
4409
|
+
since: new Date(trackedFrom).toISOString()
|
|
4410
|
+
});
|
|
4291
4411
|
}
|
|
4292
4412
|
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
|
|
4413
|
+
return Math.max(wanted, trackedFrom, recoveredFrom);
|
|
4414
|
+
}
|
|
4415
|
+
|
|
4416
|
+
/**
|
|
4417
|
+
* Recover messages missed due to failed webhook delivery. Queued by the Graph 'missed'
|
|
4418
|
+
* lifecycle event and by "Run sync" (see Account.queueMissedRecovery()), and run from the
|
|
4419
|
+
* change drain, so a failure is retried like any other change. Lists the messages received
|
|
4420
|
+
* since `since` oldest first, a page at a time, and announces the ones not announced yet
|
|
4421
|
+
* @param {Object} opts
|
|
4422
|
+
* @param {number} opts.since - Epoch ms to look back to
|
|
4423
|
+
* @param {Object} opts.options - Message fetch options
|
|
4424
|
+
*/
|
|
4425
|
+
async syncMissedMessages({ since, options }) {
|
|
4426
|
+
const startedAt = Date.now();
|
|
4427
|
+
const sinceTime = new Date(since);
|
|
4302
4428
|
|
|
4303
4429
|
this.logger.info({
|
|
4304
4430
|
msg: 'Recovering missed notifications',
|
|
@@ -4306,139 +4432,85 @@ class OutlookClient extends BaseClient {
|
|
|
4306
4432
|
since: sinceTime.toISOString()
|
|
4307
4433
|
});
|
|
4308
4434
|
|
|
4309
|
-
let
|
|
4435
|
+
let checked = 0;
|
|
4436
|
+
let recoveredCount = 0;
|
|
4437
|
+
|
|
4310
4438
|
let reqUrl = `/${this.oauth2UserPath}/messages`;
|
|
4311
4439
|
let reqPayload = {
|
|
4312
4440
|
$filter: `receivedDateTime gt ${sinceTime.toISOString()}`,
|
|
4313
4441
|
$select: 'id,parentFolderId',
|
|
4314
4442
|
$top: 250,
|
|
4315
|
-
$orderby: 'receivedDateTime
|
|
4443
|
+
$orderby: 'receivedDateTime asc'
|
|
4316
4444
|
};
|
|
4317
4445
|
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
if (messages.length >= 1000) {
|
|
4325
|
-
messages.length = 1000;
|
|
4326
|
-
break;
|
|
4327
|
-
}
|
|
4328
|
-
}
|
|
4329
|
-
|
|
4330
|
-
if (pageResult['@odata.nextLink']) {
|
|
4331
|
-
reqUrl = pageResult['@odata.nextLink'];
|
|
4332
|
-
reqPayload = null; // nextLink includes all query params
|
|
4333
|
-
} else {
|
|
4334
|
-
reqUrl = null;
|
|
4335
|
-
}
|
|
4336
|
-
}
|
|
4337
|
-
} catch (err) {
|
|
4338
|
-
this.logger.error({ msg: 'Failed to query recent messages for missed notification recovery', account: this.account, err });
|
|
4339
|
-
await this.redis.del(cooldownKey);
|
|
4340
|
-
return false;
|
|
4341
|
-
}
|
|
4342
|
-
|
|
4343
|
-
if (!messages.length) {
|
|
4344
|
-
this.logger.debug({ msg: 'No recent messages found during missed notification recovery', account: this.account });
|
|
4345
|
-
return true;
|
|
4346
|
-
}
|
|
4347
|
-
|
|
4348
|
-
this.logger.info({
|
|
4349
|
-
msg: 'Found recent messages for missed notification recovery',
|
|
4350
|
-
account: this.account,
|
|
4351
|
-
count: messages.length
|
|
4352
|
-
});
|
|
4446
|
+
// A failed page throws: the whole recovery is retried, and the messages it already
|
|
4447
|
+
// announced are skipped as announced
|
|
4448
|
+
while (reqUrl) {
|
|
4449
|
+
let pageResult = await this.request(reqUrl, 'get', reqPayload);
|
|
4450
|
+
let messages = pageResult?.value || [];
|
|
4451
|
+
checked += messages.length;
|
|
4353
4452
|
|
|
4354
|
-
|
|
4355
|
-
newMessageOptions.showPath = true;
|
|
4453
|
+
let announced = await this.getAnnounced(messages.map(msg => msg.id));
|
|
4356
4454
|
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
let cachedListing = await this.getCachedMailboxListing();
|
|
4360
|
-
if (cachedListing) {
|
|
4361
|
-
for (let msg of messages) {
|
|
4362
|
-
if (msg.parentFolderId && !folderMap.has(msg.parentFolderId)) {
|
|
4363
|
-
let folder = cachedListing.find(entry => entry.id === msg.parentFolderId);
|
|
4364
|
-
if (folder) {
|
|
4365
|
-
folderMap.set(msg.parentFolderId, folder);
|
|
4366
|
-
}
|
|
4367
|
-
}
|
|
4368
|
-
}
|
|
4369
|
-
}
|
|
4370
|
-
|
|
4371
|
-
let recoveredCount = 0;
|
|
4372
|
-
|
|
4373
|
-
for (const msg of messages) {
|
|
4374
|
-
try {
|
|
4375
|
-
// Pre-filter: check rollingBucketLock BEFORE the expensive getMessage() call
|
|
4376
|
-
let preFilterChecked = false;
|
|
4377
|
-
let folder = folderMap.get(msg.parentFolderId);
|
|
4378
|
-
if (folder) {
|
|
4379
|
-
let recentlySeen = await this.rollingBucketLock(`${msg.id}:created`, folder.pathName);
|
|
4380
|
-
if (recentlySeen) {
|
|
4381
|
-
continue;
|
|
4382
|
-
}
|
|
4383
|
-
preFilterChecked = true;
|
|
4384
|
-
}
|
|
4385
|
-
|
|
4386
|
-
let messageData = await this.prepareNewMessage(msg.id, newMessageOptions);
|
|
4387
|
-
if (!messageData) {
|
|
4455
|
+
for (const msg of messages) {
|
|
4456
|
+
if (announced.has(msg.id)) {
|
|
4388
4457
|
continue;
|
|
4389
4458
|
}
|
|
4390
|
-
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
if (recentlySeen) {
|
|
4459
|
+
try {
|
|
4460
|
+
let messageData = await this.prepareNewMessage(msg.id, options);
|
|
4461
|
+
if (!messageData) {
|
|
4394
4462
|
continue;
|
|
4395
4463
|
}
|
|
4396
|
-
}
|
|
4397
4464
|
|
|
4398
|
-
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
|
|
4465
|
+
// processNew() clears messageData.path
|
|
4466
|
+
const path = messageData.path;
|
|
4467
|
+
await this.processNew(messageData, options);
|
|
4468
|
+
await this.markAnnounced(messageData.id, path);
|
|
4469
|
+
recoveredCount++;
|
|
4470
|
+
} catch (err) {
|
|
4471
|
+
await this.deferFailedChangeEvent({ type: 'created', message: msg.id }, err);
|
|
4472
|
+
}
|
|
4402
4473
|
}
|
|
4474
|
+
|
|
4475
|
+
reqUrl = pageResult?.['@odata.nextLink'] || null;
|
|
4476
|
+
reqPayload = null; // nextLink includes all query params
|
|
4403
4477
|
}
|
|
4404
4478
|
|
|
4405
4479
|
this.logger.info({
|
|
4406
4480
|
msg: 'Missed notification recovery completed',
|
|
4407
4481
|
account: this.account,
|
|
4408
|
-
checked
|
|
4482
|
+
checked,
|
|
4409
4483
|
recovered: recoveredCount
|
|
4410
4484
|
});
|
|
4411
4485
|
|
|
4486
|
+
// Everything received before the pass started has been looked at. hSetExists, so a pass
|
|
4487
|
+
// that outlives a deleted account does not recreate its record
|
|
4488
|
+
await this.redis.hSetExists(this.getAccountKey(), 'outlookRecoveredUntil', startedAt.toString());
|
|
4412
4489
|
await this._updateLastNotificationTime();
|
|
4490
|
+
}
|
|
4413
4491
|
|
|
4414
|
-
|
|
4492
|
+
// A message gone by the time a change notification is processed is a routine race: for every
|
|
4493
|
+
// genuine deletion the existence probe answers 404. Any other failure says nothing about the
|
|
4494
|
+
// message, so it is thrown for processHistory() to retry - a 5xx here used to be reported as
|
|
4495
|
+
// a deletion, and an update was dropped.
|
|
4496
|
+
fetchChangedMessage(emailId, fields) {
|
|
4497
|
+
return this.request(`/${this.oauth2UserPath}/messages/${emailId}`, 'get', { $select: fields.join(',') }).catch(err => {
|
|
4498
|
+
if (err.code === 'MessageNotFound' || err.statusCode === 404) {
|
|
4499
|
+
this.logger.debug({ msg: 'Failed to fetch message data', emailId, err });
|
|
4500
|
+
return null;
|
|
4501
|
+
}
|
|
4502
|
+
throw err;
|
|
4503
|
+
});
|
|
4415
4504
|
}
|
|
4416
4505
|
|
|
4417
4506
|
/**
|
|
4418
4507
|
* Process a deleted message event
|
|
4419
4508
|
* Verifies if actually deleted or just moved
|
|
4420
4509
|
*/
|
|
4421
|
-
// A message gone by the time a change notification is processed is a routine race: for every
|
|
4422
|
-
// genuine deletion the existence probe answers 404. Only unexpected failures deserve error.
|
|
4423
|
-
logMessageFetchFailure(emailId, err) {
|
|
4424
|
-
if (err.code === 'MessageNotFound' || err.statusCode === 404) {
|
|
4425
|
-
this.logger.debug({ msg: 'Failed to fetch message data', emailId, err });
|
|
4426
|
-
} else {
|
|
4427
|
-
this.logger.error({ msg: 'Failed to fetch message data', emailId, err });
|
|
4428
|
-
}
|
|
4429
|
-
}
|
|
4430
|
-
|
|
4431
4510
|
async processDeletedMessage(emailId) {
|
|
4432
4511
|
// Verify if the message was actually deleted.
|
|
4433
4512
|
// If the email was moved, we receive both a 'deleted' and a 'created' event with the same ID.
|
|
4434
|
-
let messageData;
|
|
4435
|
-
try {
|
|
4436
|
-
messageData = await this.request(`/${this.oauth2UserPath}/messages/${emailId}`, 'get', {
|
|
4437
|
-
$select: ['id', 'parentFolderId'].join(',')
|
|
4438
|
-
});
|
|
4439
|
-
} catch (err) {
|
|
4440
|
-
this.logMessageFetchFailure(emailId, err);
|
|
4441
|
-
}
|
|
4513
|
+
let messageData = await this.fetchChangedMessage(emailId, ['id', 'parentFolderId']);
|
|
4442
4514
|
if (messageData) {
|
|
4443
4515
|
// The message still exists, so there's no need to notify about the deletion.
|
|
4444
4516
|
// The message was likely moved, but since we cannot determine the previous mailbox folder,
|
|
@@ -4459,15 +4531,7 @@ class OutlookClient extends BaseClient {
|
|
|
4459
4531
|
* Tracks flag changes and deduplicates repeated updates
|
|
4460
4532
|
*/
|
|
4461
4533
|
async processUpdatedMessage(emailId) {
|
|
4462
|
-
let messageData;
|
|
4463
|
-
|
|
4464
|
-
try {
|
|
4465
|
-
messageData = await this.request(`/${this.oauth2UserPath}/messages/${emailId}`, 'get', {
|
|
4466
|
-
$select: ['id', 'isRead', 'isDraft', 'flag', 'conversationId', 'parentFolderId'].join(',')
|
|
4467
|
-
});
|
|
4468
|
-
} catch (err) {
|
|
4469
|
-
this.logMessageFetchFailure(emailId, err);
|
|
4470
|
-
}
|
|
4534
|
+
let messageData = await this.fetchChangedMessage(emailId, ['id', 'isRead', 'isDraft', 'flag', 'conversationId', 'parentFolderId']);
|
|
4471
4535
|
if (!messageData) {
|
|
4472
4536
|
// do nothing, message not found
|
|
4473
4537
|
return;
|
|
@@ -4509,14 +4573,16 @@ class OutlookClient extends BaseClient {
|
|
|
4509
4573
|
changes
|
|
4510
4574
|
};
|
|
4511
4575
|
|
|
4512
|
-
// Check
|
|
4513
|
-
let
|
|
4514
|
-
|
|
4576
|
+
// Check the dedupe lock to see if we recently processed the update event for the same email
|
|
4577
|
+
let dedupeKey = `${messageData.id}:updated`;
|
|
4578
|
+
let dedupeValue = JSON.stringify(changes.flags.value);
|
|
4579
|
+
if (await this.isRecentlySeen(dedupeKey, dedupeValue)) {
|
|
4515
4580
|
this.logger.debug({ msg: 'Ignore recently seen updated email event', type: 'history-event', emailId: messageData.id, flags: changes.flags.value });
|
|
4516
4581
|
return;
|
|
4517
4582
|
}
|
|
4518
4583
|
|
|
4519
4584
|
await this.notify({ path, specialUse }, MESSAGE_UPDATED_NOTIFY, messageUpdate);
|
|
4585
|
+
await this.markSeen(dedupeKey, dedupeValue);
|
|
4520
4586
|
}
|
|
4521
4587
|
|
|
4522
4588
|
/**
|
|
@@ -4532,9 +4598,6 @@ class OutlookClient extends BaseClient {
|
|
|
4532
4598
|
options.headers = 'headers' in options ? options.headers : false;
|
|
4533
4599
|
}
|
|
4534
4600
|
|
|
4535
|
-
// The sync path never reads the bounces field
|
|
4536
|
-
options.skipBounces = true;
|
|
4537
|
-
|
|
4538
4601
|
let messageData;
|
|
4539
4602
|
try {
|
|
4540
4603
|
messageData = await this.getMessage(emailId, options);
|
|
@@ -4797,46 +4860,88 @@ class OutlookClient extends BaseClient {
|
|
|
4797
4860
|
}
|
|
4798
4861
|
|
|
4799
4862
|
/**
|
|
4800
|
-
*
|
|
4801
|
-
*
|
|
4863
|
+
* The dedupe buckets a key is looked up in, newest first: one bucket to the future, the
|
|
4864
|
+
* current 10 minute bucket, and one to the past
|
|
4802
4865
|
*/
|
|
4803
|
-
|
|
4804
|
-
// 10 minute buckets
|
|
4866
|
+
dedupeBucketKeys() {
|
|
4805
4867
|
let currentBucketTime = new Date(`${new Date().toISOString().substring(0, 15)}0:00.000Z`).getTime();
|
|
4868
|
+
return [-1, 0, 1].map(i => `${REDIS_PREFIX}bck:${new Date(currentBucketTime - i * 10 * 60 * 1000).toISOString()}`);
|
|
4869
|
+
}
|
|
4806
4870
|
|
|
4807
|
-
|
|
4808
|
-
|
|
4871
|
+
/**
|
|
4872
|
+
* Whether the same change was recently processed with the same value
|
|
4873
|
+
*/
|
|
4874
|
+
async isRecentlySeen(key, value = '1') {
|
|
4809
4875
|
let pipeline = this.redis.multi();
|
|
4810
|
-
|
|
4811
|
-
// Always check newer first. In this case, if there is an outdated value in an older bucket, then we use the newer value
|
|
4812
|
-
for (let i = -1; i < buckets; i++) {
|
|
4813
|
-
let bucketTime = new Date(currentBucketTime - i * 10 * 60 * 1000).toISOString();
|
|
4814
|
-
let bucketKey = `${REDIS_PREFIX}bck:${bucketTime}`;
|
|
4876
|
+
for (let bucketKey of this.dedupeBucketKeys()) {
|
|
4815
4877
|
pipeline = pipeline.hget(bucketKey, key);
|
|
4816
4878
|
}
|
|
4817
4879
|
|
|
4818
4880
|
let pipelineRes = await pipeline.exec();
|
|
4819
4881
|
for (let [, bucketRes] of pipelineRes) {
|
|
4820
4882
|
if (bucketRes) {
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
}
|
|
4824
|
-
// There is a value, but it does not match the known last value
|
|
4825
|
-
break;
|
|
4883
|
+
// Always check newer first. If there is an outdated value in an older bucket, then we use the newer value
|
|
4884
|
+
return bucketRes === value;
|
|
4826
4885
|
}
|
|
4827
4886
|
}
|
|
4887
|
+
return false;
|
|
4888
|
+
}
|
|
4828
4889
|
|
|
4829
|
-
|
|
4830
|
-
|
|
4831
|
-
|
|
4890
|
+
/**
|
|
4891
|
+
* Records a processed change for isRecentlySeen(). Callers mark a change only once it was
|
|
4892
|
+
* processed, so a change that failed is not skipped as "recently seen" on its retry
|
|
4893
|
+
*/
|
|
4894
|
+
async markSeen(key, value = '1') {
|
|
4895
|
+
let bucketKey = this.dedupeBucketKeys()[1];
|
|
4832
4896
|
await this.redis
|
|
4833
4897
|
.multi()
|
|
4834
4898
|
.hset(bucketKey, key, value)
|
|
4835
4899
|
// make sure the bucket does not expire until the next one is already valid
|
|
4836
4900
|
.expire(bucketKey, 12 * 60)
|
|
4837
4901
|
.exec();
|
|
4902
|
+
}
|
|
4838
4903
|
|
|
4839
|
-
|
|
4904
|
+
// Messages announced as new over the last OUTLOOK_ANNOUNCED_RETENTION, by message ID. The
|
|
4905
|
+
// short-lived dedupe buckets cover a burst of duplicate notifications; this covers a recovery
|
|
4906
|
+
// pass that looks back hours
|
|
4907
|
+
getAnnouncedKey() {
|
|
4908
|
+
return `${REDIS_PREFIX}iam:${this.account}:announced`;
|
|
4909
|
+
}
|
|
4910
|
+
|
|
4911
|
+
/**
|
|
4912
|
+
* Marks a new message as announced, for both the dedupe buckets and the recovery pass
|
|
4913
|
+
*/
|
|
4914
|
+
async markAnnounced(messageId, path) {
|
|
4915
|
+
const now = Date.now();
|
|
4916
|
+
const announcedKey = this.getAnnouncedKey();
|
|
4917
|
+
const bucketKey = this.dedupeBucketKeys()[1];
|
|
4918
|
+
await this.redis
|
|
4919
|
+
.multi()
|
|
4920
|
+
.hset(bucketKey, `${messageId}:created`, path)
|
|
4921
|
+
.expire(bucketKey, 12 * 60)
|
|
4922
|
+
.zadd(announcedKey, now, messageId)
|
|
4923
|
+
.zremrangebyscore(announcedKey, '-inf', now - OUTLOOK_ANNOUNCED_RETENTION)
|
|
4924
|
+
.pexpire(announcedKey, OUTLOOK_ANNOUNCED_RETENTION)
|
|
4925
|
+
.exec();
|
|
4926
|
+
}
|
|
4927
|
+
|
|
4928
|
+
/**
|
|
4929
|
+
* @param {string[]} messageIds
|
|
4930
|
+
* @returns {Promise<Set<string>>} The ones announced within OUTLOOK_ANNOUNCED_RETENTION
|
|
4931
|
+
*/
|
|
4932
|
+
async getAnnounced(messageIds) {
|
|
4933
|
+
if (!messageIds.length) {
|
|
4934
|
+
return new Set();
|
|
4935
|
+
}
|
|
4936
|
+
const announcedKey = this.getAnnouncedKey();
|
|
4937
|
+
const cutoff = Date.now() - OUTLOOK_ANNOUNCED_RETENTION;
|
|
4938
|
+
// ZSCORE per ID rather than ZMSCORE, which needs Redis 6.2
|
|
4939
|
+
let pipeline = this.redis.pipeline();
|
|
4940
|
+
for (const messageId of messageIds) {
|
|
4941
|
+
pipeline = pipeline.zscore(announcedKey, messageId);
|
|
4942
|
+
}
|
|
4943
|
+
const results = await pipeline.exec();
|
|
4944
|
+
return new Set(messageIds.filter((id, i) => results[i][1] !== null && Number(results[i][1]) > cutoff));
|
|
4840
4945
|
}
|
|
4841
4946
|
|
|
4842
4947
|
/**
|