emailengine-app 2.82.0 → 2.82.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.
Files changed (67) hide show
  1. package/.ncurc.js +23 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +51 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/bin/emailengine.js +77 -7
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +35 -10
  8. package/lib/api-routes/account-binding.js +58 -0
  9. package/lib/api-routes/account-routes.js +48 -9
  10. package/lib/api-routes/behavior-notes.js +4 -0
  11. package/lib/api-routes/gateway-routes.js +10 -2
  12. package/lib/api-routes/message-routes.js +10 -3
  13. package/lib/api-routes/outbox-routes.js +1 -1
  14. package/lib/api-routes/settings-routes.js +1 -2
  15. package/lib/api-routes/token-routes.js +1 -1
  16. package/lib/autodetect-imap-settings.js +146 -4
  17. package/lib/consts.js +12 -0
  18. package/lib/db.js +1 -19
  19. package/lib/delivery-error.js +68 -1
  20. package/lib/email-client/base-client.js +6 -13
  21. package/lib/email-client/credential-errors.js +21 -5
  22. package/lib/email-client/gmail-client.js +2 -2
  23. package/lib/email-client/imap-client.js +2 -1
  24. package/lib/email-client/message-builder.js +41 -11
  25. package/lib/email-client/outlook-client.js +263 -84
  26. package/lib/email-client/outlook-fallback-poll.js +30 -0
  27. package/lib/enum-descriptions.js +5 -1
  28. package/lib/export.js +8 -2
  29. package/lib/gateway.js +5 -0
  30. package/lib/get-secret.js +1 -21
  31. package/lib/mcp/tools.js +95 -36
  32. package/lib/oauth/gmail.js +42 -12
  33. package/lib/oauth/mail-ru.js +24 -17
  34. package/lib/oauth/outlook.js +34 -24
  35. package/lib/oauth/scope-checker.js +35 -1
  36. package/lib/oauth/scope-list.js +55 -0
  37. package/lib/oauth/token-fetch.js +47 -0
  38. package/lib/oauth2-apps.js +16 -47
  39. package/lib/outbox.js +2 -7
  40. package/lib/queue-retention.js +4 -2
  41. package/lib/read-env-value.js +33 -2
  42. package/lib/schemas.js +62 -15
  43. package/lib/token-audit-log.js +3 -2
  44. package/lib/tools.js +1 -1
  45. package/lib/ui-routes/account-routes.js +40 -7
  46. package/lib/ui-routes/oauth-config-routes.js +3 -14
  47. package/lib/ui-routes/outlook-subscription-view.js +36 -0
  48. package/lib/ui-routes/route-helpers.js +25 -37
  49. package/lib/ui-routes/special-use-paths.js +33 -0
  50. package/lib/utils/network.js +9 -17
  51. package/package.json +18 -18
  52. package/sbom.json +1 -1
  53. package/server.js +21 -3
  54. package/setup-production.sh +16 -7
  55. package/static/licenses.html +30 -20
  56. package/translations/messages.pot +74 -56
  57. package/views/account-workspace-error.hbs +30 -0
  58. package/views/accounts/account.hbs +14 -6
  59. package/views/accounts/edit.hbs +11 -2
  60. package/views/internals/index.hbs +1 -1
  61. package/views/partials/gmail_api_scopes.hbs +16 -0
  62. package/views/partials/oauth_form.hbs +67 -94
  63. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  64. package/views/partials/scope_info.hbs +14 -23
  65. package/workers/api.js +62 -27
  66. package/workers/imap.js +6 -3
  67. package/workers/submit.js +2 -5
@@ -10,6 +10,7 @@ const getSecret = require('../get-secret');
10
10
  const msgpack = require('../msgpack');
11
11
  const he = require('he');
12
12
  const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
13
+ const { parseFallbackPollInterval, FALLBACK_POLL_INTERVAL } = require('./outlook-fallback-poll');
13
14
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
14
15
  const crypto = require('crypto');
15
16
  const { Gateway } = require('../gateway');
@@ -46,12 +47,21 @@ const MAX_BATCH_SIZE = graphApi.MAX_BATCH_SIZE;
46
47
  // Subscription is renewed automatically. But just in case, check once in an hour
47
48
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
48
49
 
50
+ // When the announced set (see OutlookClient.getAnnouncedKey()) started being kept, the point a
51
+ // recovery pass never looks back past. Renamed along with the set when it became keyed by folder,
52
+ // so the first pass after an upgrade does not take the messages recorded in the old format for
53
+ // unannounced ones and announce hours of mail again
54
+ const ANNOUNCED_SINCE_FIELD = 'outlookAnnouncedInSince';
55
+
49
56
  // The `serverResponseCode` a failed change subscription is reported with, and the marker that
50
57
  // tells the report apart from anything else the account may have stored. Only this client reads
51
58
  // it: reportSubscriptionFailure() writes it, clearSubscriptionFailure() lifts it, and
52
59
  // isSelfClearedErrorState() is what keeps a login from taking it along
53
60
  const SUBSCRIPTION_SETUP_ERROR_CODE = 'SubscriptionSetupError';
54
61
 
62
+ // What the stored subscription state says while no Service URL is set, see recordMissingServiceUrl()
63
+ const MISSING_SERVICE_URL_ERROR = 'Subscription failed: the Service URL is not set';
64
+
55
65
  // Graph accepts only x- prefixed names in internetMessageHeaders and rejects the whole message
56
66
  // over any other one, so the threading headers of a reply or a forward are set through the
57
67
  // MAPI properties Exchange builds them from (PidTagInReplyToId, PidTagInternetReferences)
@@ -103,7 +113,7 @@ Supported operations status:
103
113
  ✅ deleteMailbox
104
114
  ✅ getAttachment
105
115
  ✅ submitMessage
106
- ✅ uploadMessage - only drafts. Cannot change draft status
116
+ ✅ uploadMessage - Graph creates a draft; the \Draft flag then sets PR_MESSAGE_FLAGS mfUnsent
107
117
  🟡 subconnections - not supported
108
118
  */
109
119
 
@@ -152,6 +162,11 @@ class OutlookClient extends BaseClient {
152
162
  this.renewRetryTimer = null;
153
163
  this.renewalInProgress = false; // In-memory flag to prevent concurrent subscription renewals
154
164
 
165
+ // Periodic missed-notification recovery, see setupFallbackPollTimer()
166
+ this.fallbackPollTimer = null;
167
+ this.fallbackPollInterval = FALLBACK_POLL_INTERVAL;
168
+ this.periodicRecoveryDue = false;
169
+
155
170
  // MS Graph webhook subscription state (for metrics)
156
171
  // Possible values: 'unset', 'valid', 'expired', 'failed', 'pending'
157
172
  this.subscriptionState = 'unset';
@@ -275,10 +290,7 @@ class OutlookClient extends BaseClient {
275
290
  */
276
291
  async init() {
277
292
  this.state = 'connecting';
278
- clearTimeout(this.renewWatchTimer);
279
- clearTimeout(this.renewRetryTimer);
280
- this.cancelDeferredRetryTimer();
281
- this.cancelInitRetry();
293
+ this.clearTimers();
282
294
  await this.setStateVal();
283
295
 
284
296
  await this.getAccount();
@@ -406,11 +418,12 @@ class OutlookClient extends BaseClient {
406
418
 
407
419
  // A recovery pass must not look back past the point announced messages were first
408
420
  // recorded, or its first run after an upgrade would announce hours of mail again
409
- await this.redis.hsetnx(this.getAccountKey(), 'outlookAnnouncedSince', Date.now().toString());
421
+ await this.redis.hsetnx(this.getAccountKey(), ANNOUNCED_SINCE_FIELD, Date.now().toString());
410
422
 
411
423
  // Set up webhook subscription for real-time updates
412
424
  await this.ensureSubscription();
413
425
  this.setupRenewWatchTimer();
426
+ this.setupFallbackPollTimer({ first: true });
414
427
 
415
428
  // Cache mailbox folder structure
416
429
  try {
@@ -425,14 +438,20 @@ class OutlookClient extends BaseClient {
425
438
  }
426
439
  }
427
440
 
428
- /**
429
- * Close the client connection and clean up resources
430
- */
431
- async close() {
441
+ // Every background timer of the client, stopped on connect, close and delete
442
+ clearTimers() {
432
443
  clearTimeout(this.renewWatchTimer);
433
444
  clearTimeout(this.renewRetryTimer);
445
+ clearTimeout(this.fallbackPollTimer);
434
446
  this.cancelDeferredRetryTimer();
435
447
  this.cancelInitRetry();
448
+ }
449
+
450
+ /**
451
+ * Close the client connection and clean up resources
452
+ */
453
+ async close() {
454
+ this.clearTimers();
436
455
  this.closed = true;
437
456
 
438
457
  if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
@@ -449,8 +468,11 @@ class OutlookClient extends BaseClient {
449
468
  * (PUT /v1/account/{account}/sync). Outlook syncs via webhook subscriptions and delta
450
469
  * queries rather than a folder walk, so a manual sync refreshes the folder cache and queues
451
470
  * the missed-notification recovery, which then runs and is retried like any other change.
471
+ * @param {Object} [opts]
472
+ * @param {number} [opts.since] - Epoch ms to look back to instead of the usual window. Reaches
473
+ * past what announced messages are remembered for, so it may announce messages again
452
474
  */
453
- async syncMailboxes() {
475
+ async syncMailboxes({ since } = {}) {
454
476
  if (this.closed) {
455
477
  return null;
456
478
  }
@@ -461,7 +483,7 @@ class OutlookClient extends BaseClient {
461
483
  this.logger.warn({ msg: 'Failed to refresh folder cache for manual sync', account: this.account, err });
462
484
  }
463
485
 
464
- await this.accountObject.queueMissedRecovery();
486
+ await this.accountObject.queueMissedRecovery({ reason: 'manual', since });
465
487
  this.recoverMissedNotifications();
466
488
 
467
489
  return true;
@@ -477,6 +499,70 @@ class OutlookClient extends BaseClient {
477
499
  return true;
478
500
  }
479
501
 
502
+ /**
503
+ * Arms the periodic missed-notification recovery (EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL).
504
+ * Graph loses change notifications without reporting it - a `missed` lifecycle event only
505
+ * covers the deliveries our endpoint failed - and a lost one interleaves with deliveries that
506
+ * do arrive, so the pass runs on every interval rather than after a quiet spell. Each pass
507
+ * starts where the previous one finished, so one that missed nothing is one listing request.
508
+ * The request lives in memory, not in the deferred store: a restart re-arms the timer, and a
509
+ * failed pass is left to the next one, which covers its window too.
510
+ * @param {Object} [opts]
511
+ * @param {boolean} [opts.first] - The first pass after a connect, which runs at a random point
512
+ * of the interval so a restart does not send every account's pass to Graph at once
513
+ */
514
+ setupFallbackPollTimer({ first = false } = {}) {
515
+ clearTimeout(this.fallbackPollTimer);
516
+ if (this.closed || !this.fallbackPollInterval) {
517
+ return;
518
+ }
519
+
520
+ const delay = first ? Math.floor(Math.random() * this.fallbackPollInterval) : this.fallbackPollInterval;
521
+ this.fallbackPollTimer = setTimeout(() => {
522
+ this.requestPeriodicRecovery();
523
+ this.setupFallbackPollTimer();
524
+ }, delay);
525
+ this.fallbackPollTimer.unref();
526
+ }
527
+
528
+ /**
529
+ * One tick of the periodic recovery. Only a connected account is checked: in any other state
530
+ * Graph either refuses the request (an authentication error, a tenant that disabled the
531
+ * service) or nothing should be syncing (a parked or closed account), and the timer keeps
532
+ * running so the pass resumes once the account recovers
533
+ */
534
+ requestPeriodicRecovery() {
535
+ if (this.closed || this.state !== 'connected') {
536
+ this.logger.debug({ msg: 'Skipped periodic missed notification recovery', account: this.account, state: this.state });
537
+ return;
538
+ }
539
+ this.periodicRecoveryDue = true;
540
+ this.triggerSync();
541
+ }
542
+
543
+ /**
544
+ * Runs the periodic recovery pass the timer asked for, if any, unless a recovery earlier in the
545
+ * same drain already covered its window
546
+ * @param {Object} context - The drain's shared context
547
+ */
548
+ async runPeriodicRecovery(context) {
549
+ if (!this.periodicRecoveryDue) {
550
+ return;
551
+ }
552
+ this.periodicRecoveryDue = false;
553
+
554
+ try {
555
+ const since = await this.missedRecoveryStart(Date.now());
556
+ if (context.recoveredSince && context.recoveredSince <= since) {
557
+ return;
558
+ }
559
+ await this.syncMissedMessages({ since, options: () => this.getDrainFetchOptions(context), reason: 'periodic' });
560
+ context.recoveredSince = since;
561
+ } catch (err) {
562
+ this.logger.warn({ msg: 'Periodic missed notification recovery failed', account: this.account, err });
563
+ }
564
+ }
565
+
480
566
  /**
481
567
  * Get the current connection state from Redis
482
568
  */
@@ -488,10 +574,7 @@ class OutlookClient extends BaseClient {
488
574
  * Delete the account and clean up resources
489
575
  */
490
576
  async delete() {
491
- clearTimeout(this.renewWatchTimer);
492
- clearTimeout(this.renewRetryTimer);
493
- this.cancelDeferredRetryTimer();
494
- this.cancelInitRetry();
577
+ this.clearTimers();
495
578
  this.closed = true;
496
579
 
497
580
  // Best-effort: delete MS Graph subscription
@@ -2843,14 +2926,21 @@ class OutlookClient extends BaseClient {
2843
2926
  }
2844
2927
 
2845
2928
  /**
2846
- * Reports that the account has no working change subscription left to fall back on - and for a
2847
- * Graph account there is no fallback: unlike the Gmail client there is no polling timer, so a
2848
- * subscription that cannot be established means the account never sees new mail again. Both the
2849
- * creation and the renewal paths retry with backoff and then give up; giving up used to write a
2850
- * log line and nothing else, so the account went on reporting `connected`. A tenant that
2851
- * disables the Exchange Online service principal (AADSTS500014) hits this without ever failing a
2852
- * token refresh, so no authentication error fires either - reported in the field after nine
2853
- * months of accounts looking healthy and syncing nothing.
2929
+ * Reports that the account has no working change subscription left. Both the creation and the
2930
+ * renewal paths retry with backoff and then give up here.
2931
+ *
2932
+ * What that means depends on whether the mailbox can still be read. When it can, the periodic
2933
+ * recovery pass (setupFallbackPollTimer()) keeps finding new messages without a subscription,
2934
+ * so the account stays `connected` - the same treatment a Gmail account with a dead Pub/Sub
2935
+ * watch gets - and the failure stays visible on the stored subscription state, which the API
2936
+ * and the account page report. Changes to and deletions of existing messages are only ever
2937
+ * learned from notifications, so they go unreported until a subscription works again.
2938
+ *
2939
+ * When the mailbox cannot be read, or the periodic pass is switched off, nothing syncs at all,
2940
+ * and the account is reported as a `connectError`. Before that existed, giving up wrote a log
2941
+ * line and nothing else: a tenant that disables the Exchange Online service principal
2942
+ * (AADSTS500014) fails every Graph mail call without ever failing a token refresh, and was
2943
+ * reported in the field after nine months of accounts looking healthy and syncing nothing.
2854
2944
  *
2855
2945
  * Sent as `connectError` rather than `authenticationError` on purpose: the credential is fine,
2856
2946
  * and re-authorizing does not lift a disabled service principal. It also keeps the failure away
@@ -2858,9 +2948,9 @@ class OutlookClient extends BaseClient {
2858
2948
  * offer the operator only a re-authorization that cannot help.
2859
2949
  *
2860
2950
  * NB! `connectError` is not in VALID_STATES, so this also makes the account's own operations
2861
- * (reading a message, moving one) answer 503 until a subscription works again. That is the
2862
- * intended reading for an account that cannot sync at all, and it is the only reading this
2863
- * state machine offers - there is no degraded-but-usable state.
2951
+ * (reading a message, moving one) answer 503 until the mailbox can be read again. The hourly
2952
+ * renewOrCreateSubscription() pass comes back through here while the subscription keeps
2953
+ * failing, so an account moves between the two outcomes as the tenant changes.
2864
2954
  *
2865
2955
  * setErrorState() suppresses a repeat of the same code, so a permanently broken tenant produces
2866
2956
  * one webhook per distinct failure rather than one per renewal cycle
@@ -2870,7 +2960,21 @@ class OutlookClient extends BaseClient {
2870
2960
  * @returns {Promise<void>}
2871
2961
  */
2872
2962
  async reportSubscriptionFailure(stage, state, retryCount) {
2873
- this.logger.error({ msg: `Max subscription ${stage} retries exceeded`, account: this.account, retryCount });
2963
+ const probe = await this.probeMailboxWithoutSubscription();
2964
+ if (probe.readable) {
2965
+ this.logger.warn({
2966
+ msg: `MS Graph subscription ${stage} failed, new messages are found by the periodic recovery pass until it works`,
2967
+ account: this.account,
2968
+ retryCount,
2969
+ error: state?.error
2970
+ });
2971
+
2972
+ // An earlier pass may have reported the account while its mailbox could not be read
2973
+ await this.clearSubscriptionFailure();
2974
+ return;
2975
+ }
2976
+
2977
+ this.logger.error({ msg: `Max subscription ${stage} retries exceeded`, account: this.account, retryCount, err: probe.err });
2874
2978
 
2875
2979
  try {
2876
2980
  await this.notify(false, CONNECT_ERROR_NOTIFY, {
@@ -2885,6 +2989,25 @@ class OutlookClient extends BaseClient {
2885
2989
  }
2886
2990
  }
2887
2991
 
2992
+ /**
2993
+ * Whether the periodic recovery pass can stand in for the subscription: it has to be on, and
2994
+ * Graph has to list the resource the pass reads. Any failure counts, a transient one included;
2995
+ * the next hourly pass asks again
2996
+ * @returns {Promise<{readable: boolean, err?: Error}>}
2997
+ */
2998
+ async probeMailboxWithoutSubscription() {
2999
+ if (!this.fallbackPollInterval) {
3000
+ return { readable: false };
3001
+ }
3002
+
3003
+ try {
3004
+ await this.request(`/${this.oauth2UserPath}/messages`, 'get', { $select: 'id', $top: 1 });
3005
+ return { readable: true };
3006
+ } catch (err) {
3007
+ return { readable: false, err };
3008
+ }
3009
+ }
3010
+
2888
3011
  /**
2889
3012
  * A failed change subscription is this client's own report to lift. A tenant that disabled the
2890
3013
  * Exchange Online service principal keeps refreshing tokens and logging in perfectly while no
@@ -2900,9 +3023,9 @@ class OutlookClient extends BaseClient {
2900
3023
  /**
2901
3024
  * Lifts the error state reportSubscriptionFailure() left behind, once a subscription is working
2902
3025
  * again - which is every path that concludes there is a working one, not only a renewal that
2903
- * had to make a request. A subscription 60 hours from expiry is checked hourly and renewed
2904
- * once, so an account reported while it had one would have stayed in `connectError` for two
2905
- * days with notifications arriving the whole time.
3026
+ * had to make a request - or once the mailbox can be read without one. A subscription 60 hours
3027
+ * from expiry is checked hourly and renewed once, so an account reported while it had one would
3028
+ * have stayed in `connectError` for two days with notifications arriving the whole time.
2906
3029
  *
2907
3030
  * Only touches a failure this client reported, so an unrelated error state is left for whatever
2908
3031
  * owns it. A report this process wrote is visible in `this.state`; the one way a standing
@@ -3068,17 +3191,18 @@ class OutlookClient extends BaseClient {
3068
3191
  * revoked - exhausts them within minutes and leaves the account with no subscription at all.
3069
3192
  * This pass used to read that count, find it at the cap and give up, waiting for a reconnect
3070
3193
  * that only a worker restart, an account update or a re-authorization brings; a tenant that
3071
- * fixed the cause an hour later was never noticed. Unlike the Gmail client there is no poller
3072
- * behind this to fall back on, so an account left unsubscribed syncs nothing at all while it
3073
- * waits. The counters are cleared before anything else is attempted, so an hour that could have
3194
+ * fixed the cause an hour later was never noticed. It is also what moves an account between
3195
+ * the two outcomes of reportSubscriptionFailure() while the subscription keeps failing.
3196
+ *
3197
+ * The counters are cleared before anything else is attempted, so an hour that could have
3074
3198
  * recovered gets the fast ladder back instead of one attempt every hour forever - a renewal
3075
3199
  * ladder as much as a creation one, since a subscription inside the renew window whose retries
3076
3200
  * are spent is not recreated by this pass at all and would otherwise never get another.
3077
3201
  *
3078
3202
  * A failing account is not heard twice, but it is logged twice: reportSubscriptionFailure()
3079
3203
  * stores the same serverResponseCode every pass, which is what setErrorState() suppresses a
3080
- * repeat notification on, while the log line it writes recurs hourly. The account stays in
3081
- * `connectError` until a creation actually succeeds.
3204
+ * repeat notification on, while the log line it writes recurs hourly. A reported account stays
3205
+ * in `connectError` until a creation succeeds or its mailbox can be listed again.
3082
3206
  *
3083
3207
  * @returns {Promise<void>}
3084
3208
  */
@@ -3580,6 +3704,33 @@ class OutlookClient extends BaseClient {
3580
3704
  }
3581
3705
  }
3582
3706
 
3707
+ /**
3708
+ * A subscription cannot be created without a Service URL, since Graph has nowhere to deliver
3709
+ * notifications to. That used to be a log line and nothing else, so the account page showed no
3710
+ * subscription problem at all; it is recorded on the stored subscription state now, which the
3711
+ * API and the page report. It is not reported as an account error: one instance-wide setting
3712
+ * would put every Outlook account into `connectError` at once, while each of them keeps finding
3713
+ * new messages through the periodic recovery pass. A subscription that already exists is left
3714
+ * alone, since it keeps notifying the address it was created with and renewing it needs no
3715
+ * Service URL, and an unchanged record is not written again on every hourly pass
3716
+ * @returns {Promise<void>}
3717
+ */
3718
+ async recordMissingServiceUrl() {
3719
+ try {
3720
+ const outlookSubscription = await this.getStoredSubscription();
3721
+ if (outlookSubscription.id || outlookSubscription.state?.error === MISSING_SERVICE_URL_ERROR) {
3722
+ return;
3723
+ }
3724
+
3725
+ outlookSubscription.state = { state: 'error', error: MISSING_SERVICE_URL_ERROR, time: Date.now() };
3726
+ await this.saveStoredSubscription(outlookSubscription);
3727
+ this.subscriptionState = 'failed';
3728
+ } catch (err) {
3729
+ // Best effort: init() awaits ensureSubscription()
3730
+ this.logger.error({ msg: 'Failed to record the missing Service URL', account: this.account, err });
3731
+ }
3732
+ }
3733
+
3583
3734
  /**
3584
3735
  * Ensure webhook subscription exists and is valid
3585
3736
  * Creates new subscription or renews existing one
@@ -3593,7 +3744,8 @@ class OutlookClient extends BaseClient {
3593
3744
  let notificationBaseUrl = (await settings.get('notificationBaseUrl')) || serviceUrl || '';
3594
3745
 
3595
3746
  if (!serviceUrl) {
3596
- this.logger.error({ msg: 'Cannot create MS Graph subscription, service URL is not set' });
3747
+ this.logger.error({ msg: 'Cannot create MS Graph subscription, service URL is not set', account: this.account });
3748
+ await this.recordMissingServiceUrl();
3597
3749
  return false;
3598
3750
  }
3599
3751
 
@@ -4083,13 +4235,15 @@ class OutlookClient extends BaseClient {
4083
4235
  }
4084
4236
  };
4085
4237
 
4086
- // Changes deferred for a retry go first, then the queue
4238
+ // Changes deferred for a retry go first, then the periodic recovery, then the queue
4087
4239
  try {
4088
4240
  await this.processDueDeferredEvents(handle);
4089
4241
  } catch (err) {
4090
4242
  this.logger.error({ msg: 'Failed to process deferred mailbox changes', account: this.account, err });
4091
4243
  }
4092
4244
 
4245
+ await this.runPeriodicRecovery(context);
4246
+
4093
4247
  while ((event = await this.accountObject.pullQueueEvent()) !== null) {
4094
4248
  processedAny = true;
4095
4249
  await handle(event);
@@ -4118,17 +4272,11 @@ class OutlookClient extends BaseClient {
4118
4272
  case 'created': {
4119
4273
  let messageData = await this.prepareNewMessage(event.message, await this.getDrainFetchOptions(context));
4120
4274
  if (messageData) {
4121
- // When an email is sent, multiple "created" events are triggered: one for the draft and one for the sent mail folder.
4122
- // However, since we process the event with a delay, we only observe the message stored in the Sent Mail folder.
4123
- // This happens because the message was already moved there by the time we began processing the initial event from the drafts folder.
4124
-
4125
- // Check rolling bucket lock to see if we recently processed the same new email event for the same folder
4126
- // A retry runs up to an hour later, past the short-lived dedupe buckets, while a
4127
- // recovery pass may have announced the message in the meantime
4128
- if (
4129
- (await this.isRecentlySeen(`${messageData.id}:created`, messageData.path)) ||
4130
- (event.attempt && (await this.getAnnounced([messageData.id])).has(messageData.id))
4131
- ) {
4275
+ // The announced set catches a duplicate notification, a retry, and a delivery
4276
+ // Graph kept retrying for hours after a recovery pass announced the message.
4277
+ // It is checked after the fetch because it is keyed by folder too, see
4278
+ // getAnnouncedKey()
4279
+ if ((await this.getAnnounced([messageData])).has(messageData.id)) {
4132
4280
  this.logger.debug({ msg: 'Ignore recently seen new email event', type: 'history-event', emailId: event.message });
4133
4281
  break;
4134
4282
  }
@@ -4142,12 +4290,14 @@ class OutlookClient extends BaseClient {
4142
4290
  }
4143
4291
 
4144
4292
  case 'missedRecovery': {
4145
- const since = await this.missedRecoveryStart(event.receivedAt);
4293
+ // An explicit start (Run sync `since`) is the operator's call and skips every floor
4294
+ const since = event.since || (await this.missedRecoveryStart(event.receivedAt));
4146
4295
  if (context.recoveredSince && context.recoveredSince <= since) {
4147
4296
  // an earlier request in the same drain already covered this window
4148
4297
  break;
4149
4298
  }
4150
- await this.syncMissedMessages({ since, options: await this.getDrainFetchOptions(context) });
4299
+ // a request stored before the reason was recorded came from the lifecycle webhook
4300
+ await this.syncMissedMessages({ since, options: () => this.getDrainFetchOptions(context), reason: event.reason || 'missed' });
4151
4301
  context.recoveredSince = since;
4152
4302
  break;
4153
4303
  }
@@ -4189,7 +4339,7 @@ class OutlookClient extends BaseClient {
4189
4339
  */
4190
4340
  async missedRecoveryStart(receivedAt) {
4191
4341
  const [lastNotification, announcedSince, recoveredUntil] = (
4192
- await this.redis.hmget(this.getAccountKey(), 'outlookLastNotification', 'outlookAnnouncedSince', 'outlookRecoveredUntil')
4342
+ await this.redis.hmget(this.getAccountKey(), 'outlookLastNotification', ANNOUNCED_SINCE_FIELD, 'outlookRecoveredUntil')
4193
4343
  ).map(Number);
4194
4344
 
4195
4345
  // 2-minute safety margin before the last known good notification and the last pass
@@ -4212,20 +4362,27 @@ class OutlookClient extends BaseClient {
4212
4362
 
4213
4363
  /**
4214
4364
  * Recover messages missed due to failed webhook delivery. Queued by the Graph 'missed'
4215
- * lifecycle event and by "Run sync" (see Account.queueMissedRecovery()), and run from the
4216
- * change drain, so a failure is retried like any other change. Lists the messages received
4217
- * since `since` oldest first, a page at a time, and announces the ones not announced yet
4365
+ * lifecycle event, by "Run sync" and by the periodic pass (see Account.queueMissedRecovery()),
4366
+ * and run from the change drain, so a failure is retried like any other change. Lists the
4367
+ * messages received since `since` oldest first, a page at a time, and announces the ones not
4368
+ * announced yet
4218
4369
  * @param {Object} opts
4219
4370
  * @param {number} opts.since - Epoch ms to look back to
4220
- * @param {Object} opts.options - Message fetch options
4371
+ * @param {Object|Function} opts.options - Message fetch options, or an async function returning
4372
+ * them, called only once a message needs fetching (a pass usually finds none)
4373
+ * @param {string} [opts.reason] - What asked for the pass: 'missed', 'manual' or 'periodic'
4221
4374
  */
4222
- async syncMissedMessages({ since, options }) {
4375
+ async syncMissedMessages({ since, options, reason = 'missed' }) {
4223
4376
  const startedAt = Date.now();
4224
4377
  const sinceTime = new Date(since);
4378
+ // a periodic pass that found nothing logs at debug, or every account would log each interval
4379
+ const periodic = reason === 'periodic';
4380
+ let fetchOptions = typeof options === 'function' ? null : options || {};
4225
4381
 
4226
- this.logger.info({
4382
+ this.logger[periodic ? 'debug' : 'info']({
4227
4383
  msg: 'Recovering missed notifications',
4228
4384
  account: this.account,
4385
+ reason,
4229
4386
  since: sinceTime.toISOString()
4230
4387
  });
4231
4388
 
@@ -4247,25 +4404,32 @@ class OutlookClient extends BaseClient {
4247
4404
  let messages = pageResult?.value || [];
4248
4405
  checked += messages.length;
4249
4406
 
4250
- let announced = await this.getAnnounced(messages.map(msg => msg.id));
4407
+ // The folder of each listed message, from the cached listing, so the ones already
4408
+ // announced are skipped without a fetch. One whose folder is not in the listing yet is
4409
+ // fetched and checked by the folder the fetch resolved
4410
+ const listing = messages.length ? (await this.getCachedMailboxListing()) || (await this.getMailboxListing()) : [];
4411
+ const folderPaths = new Map(listing.map(entry => [entry.id, entry.pathName]));
4412
+ const candidates = messages.map(msg => ({ id: msg.id, path: folderPaths.get(msg.parentFolderId) }));
4413
+ const announced = await this.getAnnounced(candidates.filter(candidate => candidate.path));
4251
4414
 
4252
- for (const msg of messages) {
4253
- if (announced.has(msg.id)) {
4415
+ for (const candidate of candidates) {
4416
+ if (announced.has(candidate.id)) {
4254
4417
  continue;
4255
4418
  }
4256
4419
  try {
4257
- let messageData = await this.prepareNewMessage(msg.id, options);
4258
- if (!messageData) {
4420
+ fetchOptions = fetchOptions || (await options());
4421
+ let messageData = await this.prepareNewMessage(candidate.id, fetchOptions);
4422
+ if (!messageData || (!candidate.path && (await this.getAnnounced([messageData])).has(messageData.id))) {
4259
4423
  continue;
4260
4424
  }
4261
4425
 
4262
4426
  // processNew() clears messageData.path
4263
4427
  const path = messageData.path;
4264
- await this.processNew(messageData, options);
4428
+ await this.processNew(messageData, fetchOptions);
4265
4429
  await this.markAnnounced(messageData.id, path);
4266
4430
  recoveredCount++;
4267
4431
  } catch (err) {
4268
- await this.deferFailedChangeEvent({ type: 'created', message: msg.id }, err);
4432
+ await this.deferFailedChangeEvent({ type: 'created', message: candidate.id }, err);
4269
4433
  }
4270
4434
  }
4271
4435
 
@@ -4273,13 +4437,20 @@ class OutlookClient extends BaseClient {
4273
4437
  reqPayload = null; // nextLink includes all query params
4274
4438
  }
4275
4439
 
4276
- this.logger.info({
4440
+ this.logger[periodic && !recoveredCount ? 'debug' : 'info']({
4277
4441
  msg: 'Missed notification recovery completed',
4278
4442
  account: this.account,
4443
+ reason,
4444
+ since: sinceTime.toISOString(),
4279
4445
  checked,
4280
4446
  recovered: recoveredCount
4281
4447
  });
4282
4448
 
4449
+ metricsMeta({ account: this.account }, this.logger, 'outlookMissedRecovery', 'inc', { reason, outcome: recoveredCount ? 'recovered' : 'none' });
4450
+ if (recoveredCount) {
4451
+ metricsMeta({ account: this.account }, this.logger, 'outlookMissedRecoveredMessages', 'inc', { reason }, recoveredCount);
4452
+ }
4453
+
4283
4454
  // Everything received before the pass started has been looked at. hSetExists, so a pass
4284
4455
  // that outlives a deleted account does not recreate its record
4285
4456
  await this.redis.hSetExists(this.getAccountKey(), 'outlookRecoveredUntil', startedAt.toString());
@@ -4698,47 +4869,55 @@ class OutlookClient extends BaseClient {
4698
4869
  .exec();
4699
4870
  }
4700
4871
 
4701
- // Messages announced as new over the last OUTLOOK_ANNOUNCED_RETENTION, by message ID. The
4702
- // short-lived dedupe buckets cover a burst of duplicate notifications; this covers a recovery
4703
- // pass that looks back hours
4872
+ // Messages announced as new over the last OUTLOOK_ANNOUNCED_RETENTION - the one record a
4873
+ // `created` notification and a recovery pass are both checked against. Keyed by message ID and
4874
+ // folder: an immutable ID survives the move from Drafts to Sent Items when a draft is sent, and
4875
+ // the sent copy is announced as new in its own folder, as it always was. The folder in the
4876
+ // member is why this is not the `announced` set earlier versions kept by ID alone, see
4877
+ // ANNOUNCED_SINCE_FIELD
4704
4878
  getAnnouncedKey() {
4705
- return `${REDIS_PREFIX}iam:${this.account}:announced`;
4879
+ return `${REDIS_PREFIX}iam:${this.account}:announced-in`;
4880
+ }
4881
+
4882
+ announcedMember(messageId, path) {
4883
+ // a Graph ID never contains a tab, a folder path may contain anything
4884
+ return `${messageId}\t${path || ''}`;
4706
4885
  }
4707
4886
 
4708
4887
  /**
4709
- * Marks a new message as announced, for both the dedupe buckets and the recovery pass
4888
+ * Marks a new message as announced in a folder, see getAnnounced()
4889
+ * @param {string} messageId
4890
+ * @param {string} path - The folder it was announced in
4710
4891
  */
4711
4892
  async markAnnounced(messageId, path) {
4712
4893
  const now = Date.now();
4713
4894
  const announcedKey = this.getAnnouncedKey();
4714
- const bucketKey = this.dedupeBucketKeys()[1];
4715
4895
  await this.redis
4716
4896
  .multi()
4717
- .hset(bucketKey, `${messageId}:created`, path)
4718
- .expire(bucketKey, 12 * 60)
4719
- .zadd(announcedKey, now, messageId)
4897
+ .zadd(announcedKey, now, this.announcedMember(messageId, path))
4720
4898
  .zremrangebyscore(announcedKey, '-inf', now - OUTLOOK_ANNOUNCED_RETENTION)
4721
4899
  .pexpire(announcedKey, OUTLOOK_ANNOUNCED_RETENTION)
4722
4900
  .exec();
4723
4901
  }
4724
4902
 
4725
4903
  /**
4726
- * @param {string[]} messageIds
4727
- * @returns {Promise<Set<string>>} The ones announced within OUTLOOK_ANNOUNCED_RETENTION
4904
+ * @param {{id: string, path: string}[]} messages - Messages and the folder each is in now
4905
+ * @returns {Promise<Set<string>>} The IDs of the ones announced in that folder within
4906
+ * OUTLOOK_ANNOUNCED_RETENTION
4728
4907
  */
4729
- async getAnnounced(messageIds) {
4730
- if (!messageIds.length) {
4908
+ async getAnnounced(messages) {
4909
+ if (!messages.length) {
4731
4910
  return new Set();
4732
4911
  }
4733
4912
  const announcedKey = this.getAnnouncedKey();
4734
4913
  const cutoff = Date.now() - OUTLOOK_ANNOUNCED_RETENTION;
4735
- // ZSCORE per ID rather than ZMSCORE, which needs Redis 6.2
4914
+ // ZSCORE per message rather than ZMSCORE, which needs Redis 6.2
4736
4915
  let pipeline = this.redis.pipeline();
4737
- for (const messageId of messageIds) {
4738
- pipeline = pipeline.zscore(announcedKey, messageId);
4916
+ for (const { id, path } of messages) {
4917
+ pipeline = pipeline.zscore(announcedKey, this.announcedMember(id, path));
4739
4918
  }
4740
4919
  const results = await pipeline.exec();
4741
- return new Set(messageIds.filter((id, i) => results[i][1] !== null && Number(results[i][1]) > cutoff));
4920
+ return new Set(messages.filter((message, i) => results[i][1] !== null && Number(results[i][1]) > cutoff).map(message => message.id));
4742
4921
  }
4743
4922
 
4744
4923
  /**
@@ -4820,4 +4999,4 @@ class OutlookClient extends BaseClient {
4820
4999
  }
4821
5000
  }
4822
5001
 
4823
- module.exports = { OutlookClient, encodeFolderSegment, decodeFolderSegment };
5002
+ module.exports = { OutlookClient, encodeFolderSegment, decodeFolderSegment, parseFallbackPollInterval };
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ const { readEnvValue, getDuration } = require('../tools');
4
+
5
+ const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
6
+ const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
7
+
8
+ /**
9
+ * Reads EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: a duration, 0 switching the periodic pass off.
10
+ * Anything unreadable gets the default, and a positive value is never shorter than ten seconds, so
11
+ * a typo cannot point every account at Graph in a loop
12
+ * @param {*} value - The raw environment value
13
+ * @returns {number} Milliseconds, 0 when the pass is off
14
+ */
15
+ function parseFallbackPollInterval(value) {
16
+ // blank is "unset", which getDuration() would read as 0, the value that switches the pass off
17
+ const raw = String(value ?? '').trim();
18
+ const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
19
+ if (!Number.isFinite(duration) || duration < 0) {
20
+ return DEFAULT_FALLBACK_POLL_INTERVAL;
21
+ }
22
+ return duration && Math.max(duration, MIN_FALLBACK_POLL_INTERVAL);
23
+ }
24
+
25
+ // The interval of the periodic missed-notification recovery pass (OutlookClient.setupFallbackPollTimer()).
26
+ // Its own module so the admin UI, which runs in the API worker, reads the same value the account
27
+ // workers run with
28
+ const FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
29
+
30
+ module.exports = { parseFallbackPollInterval, FALLBACK_POLL_INTERVAL };