emailengine-app 2.81.1 → 2.82.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 +12 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +52 -0
- package/Dockerfile +4 -2
- package/bin/emailengine.js +28 -18
- package/config/default.toml +0 -5
- package/config/test.toml +0 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +70 -42
- package/getswagger.sh +0 -4
- package/lib/account/account-state.js +2 -110
- package/lib/account/bounce-store-sweep.js +63 -0
- package/lib/account/expected-identity.js +1 -1
- package/lib/account-assignment.js +207 -0
- package/lib/account.js +374 -878
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-routes.js +18 -29
- package/lib/api-routes/blocklist-routes.js +2 -2
- package/lib/api-routes/bull-board-routes.js +1 -6
- package/lib/api-routes/export-routes.js +2 -22
- package/lib/api-routes/gateway-routes.js +5 -14
- package/lib/api-routes/index.js +1 -13
- package/lib/api-routes/mailbox-routes.js +2 -7
- package/lib/api-routes/mcp-oauth-routes.js +2 -1
- package/lib/api-routes/mcp-routes.js +7 -7
- package/lib/api-routes/message-routes.js +44 -236
- package/lib/api-routes/mint-bounds.js +110 -0
- package/lib/api-routes/oauth2-app-routes.js +23 -32
- package/lib/api-routes/operation-impact.js +1 -1
- package/lib/api-routes/outbox-routes.js +2 -2
- package/lib/api-routes/permission-map.js +1 -7
- package/lib/api-routes/route-helpers.js +11 -5
- package/lib/api-routes/settings-routes.js +19 -19
- package/lib/api-routes/stats-routes.js +1 -1
- package/lib/api-routes/submit-routes.js +17 -18
- package/lib/api-routes/template-routes.js +4 -9
- package/lib/api-routes/token-routes.js +27 -5
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +41 -7
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +163 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +51 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +76 -17
- package/lib/delivery-error.js +2 -1
- package/lib/egress-fetch.js +54 -3
- package/lib/egress-filter.js +11 -0
- package/lib/email-client/api-retry.js +147 -0
- package/lib/email-client/base-client.js +628 -615
- package/lib/email-client/gmail/gmail-api.js +38 -125
- package/lib/email-client/gmail/send-request.js +1 -1
- package/lib/email-client/gmail-client.js +170 -84
- package/lib/email-client/imap/mailbox.js +244 -535
- package/lib/email-client/imap/stale-view.js +109 -0
- package/lib/email-client/imap/subconnection.js +46 -9
- package/lib/email-client/imap/sync-operations.js +5 -37
- package/lib/email-client/imap-client.js +188 -64
- package/lib/email-client/message-builder.js +9 -14
- package/lib/email-client/notification-handler.js +5 -219
- package/lib/email-client/outlook/graph-api.js +147 -126
- package/lib/email-client/outlook/send-request.js +10 -4
- package/lib/email-client/outlook-client.js +519 -617
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +1 -2
- package/lib/export.js +144 -41
- package/lib/gateway.js +20 -6
- package/lib/get-raw-email.js +26 -44
- package/lib/handlebars-helpers.js +31 -10
- package/lib/imap-proxy-auth.js +13 -29
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
- package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
- package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
- package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
- package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
- package/lib/imapproxy/imap-server.js +17 -177
- package/lib/imapproxy/proxy-handoff.js +235 -0
- package/lib/imapproxy/response-error.js +33 -0
- package/lib/imapproxy/upstream-client.js +2 -2
- package/lib/license-beacon.js +3 -9
- package/lib/llm-pre-process.js +182 -43
- package/lib/logger.js +1 -1
- package/lib/lua/ee-export-queue-add.lua +39 -0
- package/lib/lua/ee-get-idempotency.lua +15 -3
- package/lib/lua/ee-release-attempts.lua +23 -0
- package/lib/lua/ee-reserve-attempts.lua +42 -0
- package/lib/lua/h-set-bigger.lua +12 -2
- package/lib/lua/s-list-accounts.lua +6 -3
- package/lib/mcp/index.js +1 -2
- package/lib/mcp/listen.js +221 -18
- package/lib/mcp/oauth.js +44 -5
- package/lib/mcp/resources.js +8 -2
- package/lib/mcp/tools.js +13 -0
- package/lib/message-port-stream.js +64 -6
- package/lib/msgpack.js +1 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +22 -20
- package/lib/oauth/outlook.js +19 -16
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +4 -7
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +139 -44
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- package/lib/parse-message.js +21 -0
- package/lib/payload-examples-webhooks.json +4 -7
- package/lib/pbkdf2-phc.js +101 -0
- package/lib/privileged-settings.js +0 -14
- package/lib/rate-limit.js +54 -15
- package/lib/redis-scan-delete.js +56 -29
- package/lib/redis-url.js +3 -1
- package/lib/respawn-backoff.js +5 -4
- package/lib/response-stream.js +25 -4
- package/lib/rewrite-text-nodes.js +27 -40
- package/lib/routes-ui.js +0 -5
- package/lib/schemas.js +129 -262
- package/lib/sentry.js +21 -5
- package/lib/settings.js +58 -59
- package/lib/smtp-auth.js +6 -2
- package/lib/smtp-message-processor.js +28 -7
- package/lib/sso.js +7 -3
- package/lib/stream-encrypt.js +14 -13
- package/lib/swagger-options.js +3 -1
- package/lib/tls/provision.js +69 -3
- package/lib/tls/store.js +14 -1
- package/lib/tools.js +113 -52
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +27 -63
- package/lib/ui-routes/admin-config-routes.js +111 -134
- package/lib/ui-routes/admin-entities-routes.js +101 -191
- package/lib/ui-routes/ai-options.js +104 -0
- package/lib/ui-routes/auth-routes.js +98 -18
- package/lib/ui-routes/export-routes.js +3 -23
- package/lib/ui-routes/internals-routes.js +12 -9
- package/lib/ui-routes/network-config-routes.js +8 -18
- package/lib/ui-routes/oauth-config-routes.js +80 -214
- package/lib/ui-routes/route-helpers.js +40 -44
- package/lib/ui-routes/unsubscribe-routes.js +2 -2
- package/lib/utils/decode-headers.js +32 -5
- package/lib/utils/header-map.js +62 -1
- package/lib/utils/network.js +2 -0
- package/lib/web-safe-html.js +77 -4
- package/lib/webhook-request.js +9 -1
- package/lib/webhook-routing.js +27 -1
- package/lib/webhooks.js +120 -43
- package/lib/worker-rpc-error.js +43 -2
- package/list-generate.js +13 -2
- package/package.json +38 -46
- package/sbom.json +1 -1
- package/scripts/refresh-test-tokens.js +42 -14
- package/server.js +340 -336
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +7 -8
- package/static/js/ee-client.js +145 -70
- package/static/js/ui.js +350 -154
- package/static/licenses.html +460 -1861
- package/translations/messages.pot +99 -99
- package/views/accounts/browse.hbs +10 -4
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- package/views/layout/app.hbs +0 -22
- package/views/layout/login.hbs +2 -1
- package/views/partials/filter_editor_js.hbs +4 -3
- package/views/partials/side_menu.hbs +0 -4
- package/views/partials/ui/account-picker.hbs +6 -32
- package/views/partials/ui/model-picker.hbs +31 -0
- package/views/partials/ui/pagination.hbs +6 -1
- package/views/partials/ui/picker.hbs +47 -0
- package/views/unsubscribe.hbs +1 -1
- package/workers/api.js +33 -23
- package/workers/export.js +55 -60
- package/workers/imap.js +134 -47
- package/workers/submit.js +3 -1
- package/workers/webhooks.js +46 -27
- package/.githooks/pre-commit +0 -80
- package/.github/CODE_OF_CONDUCT.md +0 -76
- package/.github/contributing.md +0 -17
- package/.github/dependabot.yml +0 -22
- package/.github/docker-smoke-test.sh +0 -61
- package/.github/workflows/deploy.yml +0 -215
- package/.github/workflows/e2e.yml +0 -55
- package/.github/workflows/release.yaml +0 -217
- package/.github/workflows/test.yml +0 -307
- package/lib/api-routes/chat-routes.js +0 -535
- package/lib/append-list.js +0 -63
- package/lib/document-store.js +0 -75
- package/lib/es.js +0 -757
- package/lib/generate-text-preview.js +0 -61
- package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
- package/lib/lua/h-push.lua +0 -32
- package/lib/pre-process.js +0 -196
- package/lib/threads.js +0 -155
- package/lib/ui-routes/document-store-routes.js +0 -806
- package/playwright.config.js +0 -47
- package/views/config/document-store/chat.hbs +0 -286
- package/views/config/document-store/index.hbs +0 -146
- package/views/config/document-store/mappings/index.hbs +0 -108
- package/views/config/document-store/mappings/new.hbs +0 -68
- package/views/config/document-store/pre-processing/index.hbs +0 -103
- package/views/partials/document_store_header.hbs +0 -30
- package/workers/documents.js +0 -1128
|
@@ -9,7 +9,7 @@ const { oauth2Apps } = require('../oauth2-apps');
|
|
|
9
9
|
const getSecret = require('../get-secret');
|
|
10
10
|
const msgpack = require('../msgpack');
|
|
11
11
|
const he = require('he');
|
|
12
|
-
const { emitChangeEvent, prepareUrl, collectCidReferences,
|
|
12
|
+
const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
|
|
13
13
|
const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
|
|
14
14
|
const crypto = require('crypto');
|
|
15
15
|
const { Gateway } = require('../gateway');
|
|
@@ -29,9 +29,11 @@ const {
|
|
|
29
29
|
OUTLOOK_EXPIRATION_RENEW_TIME,
|
|
30
30
|
OUTLOOK_SUBSCRIPTION_LOCK_TTL,
|
|
31
31
|
OUTLOOK_MAX_RETRY_ATTEMPTS,
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY,
|
|
33
|
+
OUTLOOK_SUBSCRIPTION_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,
|
|
@@ -50,6 +52,17 @@ const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
|
|
|
50
52
|
// isSelfClearedErrorState() is what keeps a login from taking it along
|
|
51
53
|
const SUBSCRIPTION_SETUP_ERROR_CODE = 'SubscriptionSetupError';
|
|
52
54
|
|
|
55
|
+
// Graph accepts only x- prefixed names in internetMessageHeaders and rejects the whole message
|
|
56
|
+
// over any other one, so the threading headers of a reply or a forward are set through the
|
|
57
|
+
// MAPI properties Exchange builds them from (PidTagInReplyToId, PidTagInternetReferences)
|
|
58
|
+
const GRAPH_THREADING_PROPERTIES = new Map([
|
|
59
|
+
['in-reply-to', 'String 0x1042'],
|
|
60
|
+
['references', 'String 0x1039']
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
// MS Graph API only allows up to 5 custom headers
|
|
64
|
+
const MAX_GRAPH_CUSTOM_HEADERS = 5;
|
|
65
|
+
|
|
53
66
|
// MS Graph folder hierarchy is defined by id/parentFolderId, not by "/" in folder
|
|
54
67
|
// names. To build an unambiguous, reversible pathName we percent-encode "%" and "/"
|
|
55
68
|
// inside a single displayName segment, keeping the real "/" as the delimiter BETWEEN
|
|
@@ -105,9 +118,14 @@ function graphFailureStatus(err) {
|
|
|
105
118
|
return Number(err?.statusCode) >= 400 ? Number(err.statusCode) : 400;
|
|
106
119
|
}
|
|
107
120
|
|
|
121
|
+
// How often the same folder id missing from the cached listing may trigger a listing refresh
|
|
122
|
+
const LISTING_REFRESH_INTERVAL = 5 * 60 * 1000;
|
|
123
|
+
|
|
108
124
|
class OutlookClient extends BaseClient {
|
|
109
125
|
constructor(account, options) {
|
|
110
126
|
super(account, options);
|
|
127
|
+
// what the AI summary's authentication trust rule keys on, the way GmailClient sets its own
|
|
128
|
+
this.type = 'outlook';
|
|
111
129
|
|
|
112
130
|
// A failed init() is scheduled again by the worker, see BaseClient.scheduleInitRetry()
|
|
113
131
|
this.retriesInit = true;
|
|
@@ -123,6 +141,9 @@ class OutlookClient extends BaseClient {
|
|
|
123
141
|
// Path for API calls - 'me' for current user or specific user email for delegated access
|
|
124
142
|
this.oauth2UserPath = 'me'; // can be changed to `users/${encodeURIComponent('shared@example.com')}` for delegated access
|
|
125
143
|
|
|
144
|
+
// Folder id -> when a miss on it last refreshed the listing, see mayRefreshListingFor()
|
|
145
|
+
this.listingRefreshes = new Map();
|
|
146
|
+
|
|
126
147
|
// Flags for background processing
|
|
127
148
|
this.processingHistory = null;
|
|
128
149
|
this.renewWatchTimer = null;
|
|
@@ -256,6 +277,7 @@ class OutlookClient extends BaseClient {
|
|
|
256
277
|
this.state = 'connecting';
|
|
257
278
|
clearTimeout(this.renewWatchTimer);
|
|
258
279
|
clearTimeout(this.renewRetryTimer);
|
|
280
|
+
this.cancelDeferredRetryTimer();
|
|
259
281
|
this.cancelInitRetry();
|
|
260
282
|
await this.setStateVal();
|
|
261
283
|
|
|
@@ -382,6 +404,10 @@ class OutlookClient extends BaseClient {
|
|
|
382
404
|
// Reset subscription retry counts on reconnect - fresh auth = fresh slate
|
|
383
405
|
await this.resetSubscriptionRetryState();
|
|
384
406
|
|
|
407
|
+
// A recovery pass must not look back past the point announced messages were first
|
|
408
|
+
// 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());
|
|
410
|
+
|
|
385
411
|
// Set up webhook subscription for real-time updates
|
|
386
412
|
await this.ensureSubscription();
|
|
387
413
|
this.setupRenewWatchTimer();
|
|
@@ -394,6 +420,7 @@ class OutlookClient extends BaseClient {
|
|
|
394
420
|
}
|
|
395
421
|
|
|
396
422
|
// Start processing any pending webhook notifications
|
|
423
|
+
// (this also picks up the ones deferred for a retry before a restart)
|
|
397
424
|
this.triggerSync();
|
|
398
425
|
}
|
|
399
426
|
}
|
|
@@ -404,6 +431,7 @@ class OutlookClient extends BaseClient {
|
|
|
404
431
|
async close() {
|
|
405
432
|
clearTimeout(this.renewWatchTimer);
|
|
406
433
|
clearTimeout(this.renewRetryTimer);
|
|
434
|
+
this.cancelDeferredRetryTimer();
|
|
407
435
|
this.cancelInitRetry();
|
|
408
436
|
this.closed = true;
|
|
409
437
|
|
|
@@ -419,8 +447,8 @@ class OutlookClient extends BaseClient {
|
|
|
419
447
|
/**
|
|
420
448
|
* Performs an on-demand catch-up sync. Triggered by the "Run sync" action
|
|
421
449
|
* (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
|
|
450
|
+
* queries rather than a folder walk, so a manual sync refreshes the folder cache and queues
|
|
451
|
+
* the missed-notification recovery, which then runs and is retried like any other change.
|
|
424
452
|
*/
|
|
425
453
|
async syncMailboxes() {
|
|
426
454
|
if (this.closed) {
|
|
@@ -433,8 +461,19 @@ class OutlookClient extends BaseClient {
|
|
|
433
461
|
this.logger.warn({ msg: 'Failed to refresh folder cache for manual sync', account: this.account, err });
|
|
434
462
|
}
|
|
435
463
|
|
|
436
|
-
await this.
|
|
464
|
+
await this.accountObject.queueMissedRecovery();
|
|
465
|
+
this.recoverMissedNotifications();
|
|
466
|
+
|
|
467
|
+
return true;
|
|
468
|
+
}
|
|
437
469
|
|
|
470
|
+
/**
|
|
471
|
+
* Picks up a missed-notification recovery queued by the lifecycle webhook or by "Run sync".
|
|
472
|
+
* The request is already stored, so this only makes the next drain look for it
|
|
473
|
+
*/
|
|
474
|
+
recoverMissedNotifications() {
|
|
475
|
+
this.cancelDeferredRetryTimer();
|
|
476
|
+
this.retryDeferredEvents();
|
|
438
477
|
return true;
|
|
439
478
|
}
|
|
440
479
|
|
|
@@ -451,6 +490,7 @@ class OutlookClient extends BaseClient {
|
|
|
451
490
|
async delete() {
|
|
452
491
|
clearTimeout(this.renewWatchTimer);
|
|
453
492
|
clearTimeout(this.renewRetryTimer);
|
|
493
|
+
this.cancelDeferredRetryTimer();
|
|
454
494
|
this.cancelInitRetry();
|
|
455
495
|
this.closed = true;
|
|
456
496
|
|
|
@@ -505,11 +545,7 @@ class OutlookClient extends BaseClient {
|
|
|
505
545
|
if (!cachedListing || options?.statusQuery?.messages || (await this.renewMailboxFolderCache())) {
|
|
506
546
|
// Has changes or counters requested
|
|
507
547
|
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
|
-
}
|
|
548
|
+
await this.setCachedMailboxListing(mailboxListing);
|
|
513
549
|
|
|
514
550
|
if (!cachedListing && !options?.statusQuery?.messages) {
|
|
515
551
|
// Force delta update as it was not called previously
|
|
@@ -827,7 +863,7 @@ class OutlookClient extends BaseClient {
|
|
|
827
863
|
let raw;
|
|
828
864
|
|
|
829
865
|
try {
|
|
830
|
-
raw = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/$value`, 'get', Buffer.alloc(0), {
|
|
866
|
+
raw = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/$value`, 'get', Buffer.alloc(0), { returnBuffer: true });
|
|
831
867
|
} catch (err) {
|
|
832
868
|
switch (err.oauthRequest?.status) {
|
|
833
869
|
case 404: {
|
|
@@ -860,7 +896,7 @@ class OutlookClient extends BaseClient {
|
|
|
860
896
|
}
|
|
861
897
|
}
|
|
862
898
|
|
|
863
|
-
return raw ?
|
|
899
|
+
return raw && raw.length ? raw : null;
|
|
864
900
|
}
|
|
865
901
|
|
|
866
902
|
/**
|
|
@@ -1005,102 +1041,40 @@ class OutlookClient extends BaseClient {
|
|
|
1005
1041
|
return { deleted: false };
|
|
1006
1042
|
}
|
|
1007
1043
|
|
|
1008
|
-
//
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
let messageMap = new Map();
|
|
1013
|
-
|
|
1014
|
-
/**
|
|
1015
|
-
* Submit a batch of delete operations to Graph API
|
|
1016
|
-
* Uses requestWithRetry for automatic retry on rate limiting
|
|
1017
|
-
*/
|
|
1018
|
-
let submitBatch = async () => {
|
|
1019
|
-
let responseData;
|
|
1020
|
-
try {
|
|
1021
|
-
responseData = await this.requestWithRetry(`/$batch`, 'post', {
|
|
1022
|
-
requests: batch
|
|
1023
|
-
});
|
|
1024
|
-
for (let response of responseData?.responses || []) {
|
|
1025
|
-
let emailId = messageMap.get(response.id);
|
|
1026
|
-
if (response?.status >= 200 && response?.status < 300) {
|
|
1027
|
-
if (emailId) {
|
|
1028
|
-
updatedEmailIds.push(emailId);
|
|
1029
|
-
}
|
|
1030
|
-
} else {
|
|
1031
|
-
// Log individual batch item failures for debugging
|
|
1032
|
-
this.logger.warn({
|
|
1033
|
-
msg: 'Batch item failed',
|
|
1034
|
-
account: this.account,
|
|
1035
|
-
operation: 'delete',
|
|
1036
|
-
emailId,
|
|
1037
|
-
status: response?.status,
|
|
1038
|
-
error: response?.body?.error
|
|
1039
|
-
});
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
} catch (err) {
|
|
1043
|
-
this.logger.error({
|
|
1044
|
-
msg: 'Failed to run batch operation',
|
|
1045
|
-
account: this.account,
|
|
1046
|
-
operation: 'delete',
|
|
1047
|
-
err
|
|
1048
|
-
});
|
|
1049
|
-
throw err;
|
|
1050
|
-
} finally {
|
|
1051
|
-
batch = [];
|
|
1052
|
-
messageMap = new Map();
|
|
1053
|
-
}
|
|
1044
|
+
// Common headers for batch requests - include ImmutableId preference
|
|
1045
|
+
const batchHeaders = {
|
|
1046
|
+
'Content-Type': 'application/json',
|
|
1047
|
+
Prefer: 'IdType="ImmutableId"'
|
|
1054
1048
|
};
|
|
1055
1049
|
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
return {
|
|
1080
|
-
id: reqId,
|
|
1081
|
-
method: 'POST',
|
|
1082
|
-
url: `/${this.oauth2UserPath}/messages/${emailId}/move`,
|
|
1083
|
-
body: { destinationId: 'deleteditems' },
|
|
1084
|
-
headers: batchHeaders
|
|
1085
|
-
};
|
|
1086
|
-
}
|
|
1087
|
-
};
|
|
1088
|
-
|
|
1089
|
-
// Process messages in batches
|
|
1090
|
-
for (let emailId of emailIds) {
|
|
1091
|
-
batch.push(formatRequest(emailId));
|
|
1092
|
-
// submit batch when it reaches max size
|
|
1093
|
-
if (batch.length >= MAX_BATCH_SIZE) {
|
|
1094
|
-
await submitBatch(batch);
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
if (batch.length) {
|
|
1098
|
-
// submit remaining batch
|
|
1099
|
-
await submitBatch(batch);
|
|
1100
|
-
}
|
|
1050
|
+
// Throttled items are retried by the batch helper; whatever still fails is reported
|
|
1051
|
+
const { successIds: updatedEmailIds, failedIds } = await graphApi.executeBatchOperation(
|
|
1052
|
+
this,
|
|
1053
|
+
emailIds,
|
|
1054
|
+
(emailId, reqId) =>
|
|
1055
|
+
force
|
|
1056
|
+
? // Permanent delete
|
|
1057
|
+
{
|
|
1058
|
+
id: reqId,
|
|
1059
|
+
method: 'DELETE',
|
|
1060
|
+
url: `/${this.oauth2UserPath}/messages/${emailId}`,
|
|
1061
|
+
headers: batchHeaders
|
|
1062
|
+
}
|
|
1063
|
+
: // Move to trash
|
|
1064
|
+
{
|
|
1065
|
+
id: reqId,
|
|
1066
|
+
method: 'POST',
|
|
1067
|
+
url: `/${this.oauth2UserPath}/messages/${emailId}/move`,
|
|
1068
|
+
body: { destinationId: 'deleteditems' },
|
|
1069
|
+
headers: batchHeaders
|
|
1070
|
+
},
|
|
1071
|
+
'delete'
|
|
1072
|
+
);
|
|
1101
1073
|
|
|
1102
1074
|
return Object.assign(
|
|
1103
|
-
|
|
1075
|
+
// Nothing was deleted when every item failed
|
|
1076
|
+
{ deleted: updatedEmailIds.length > 0 },
|
|
1077
|
+
failedIds.length ? { failed: { emailIds: failedIds } } : {},
|
|
1104
1078
|
!force
|
|
1105
1079
|
? {
|
|
1106
1080
|
moved: {
|
|
@@ -1263,120 +1237,40 @@ class OutlookClient extends BaseClient {
|
|
|
1263
1237
|
let currentCategories = new Map();
|
|
1264
1238
|
|
|
1265
1239
|
if (needsCurrentCategories) {
|
|
1266
|
-
// Fetch current categories for all messages in batches
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
let
|
|
1270
|
-
|
|
1271
|
-
let submitFetchBatch = async () => {
|
|
1272
|
-
let responseData;
|
|
1273
|
-
try {
|
|
1274
|
-
responseData = await this.requestWithRetry(`/$batch`, 'post', {
|
|
1275
|
-
requests: fetchBatch
|
|
1276
|
-
});
|
|
1277
|
-
for (let response of responseData?.responses || []) {
|
|
1278
|
-
let emailId = fetchMessageMap.get(response.id);
|
|
1279
|
-
if (response?.status >= 200 && response?.status < 300 && response.body) {
|
|
1280
|
-
if (emailId) {
|
|
1281
|
-
currentCategories.set(emailId, response.body.categories || []);
|
|
1282
|
-
}
|
|
1283
|
-
} else if (emailId) {
|
|
1284
|
-
// Log individual batch item failures
|
|
1285
|
-
this.logger.warn({
|
|
1286
|
-
msg: 'Batch item failed',
|
|
1287
|
-
account: this.account,
|
|
1288
|
-
operation: 'fetchCategories',
|
|
1289
|
-
emailId,
|
|
1290
|
-
status: response?.status,
|
|
1291
|
-
error: response?.body?.error
|
|
1292
|
-
});
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
} catch (err) {
|
|
1296
|
-
// Without the current categories the PATCH below would replace every
|
|
1297
|
-
// message's category list with just the added labels, so a failed fetch
|
|
1298
|
-
// has to abort the update instead of being logged past
|
|
1299
|
-
this.logger.error({
|
|
1300
|
-
msg: 'Failed to fetch current categories',
|
|
1301
|
-
account: this.account,
|
|
1302
|
-
err
|
|
1303
|
-
});
|
|
1304
|
-
throw err;
|
|
1305
|
-
} finally {
|
|
1306
|
-
fetchBatch = [];
|
|
1307
|
-
fetchMessageMap = new Map();
|
|
1308
|
-
}
|
|
1309
|
-
};
|
|
1310
|
-
|
|
1311
|
-
for (let emailId of emailIds) {
|
|
1312
|
-
let reqId = `fetch_${++fetchIdGen}`;
|
|
1313
|
-
fetchMessageMap.set(reqId, emailId);
|
|
1314
|
-
fetchBatch.push({
|
|
1315
|
-
id: reqId,
|
|
1316
|
-
method: 'GET',
|
|
1317
|
-
url: `/${this.oauth2UserPath}/messages/${emailId}?$select=categories`,
|
|
1318
|
-
headers: {
|
|
1319
|
-
Prefer: 'IdType="ImmutableId"'
|
|
1320
|
-
}
|
|
1321
|
-
});
|
|
1322
|
-
|
|
1323
|
-
if (fetchBatch.length >= MAX_BATCH_SIZE) {
|
|
1324
|
-
await submitFetchBatch();
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
if (fetchBatch.length) {
|
|
1328
|
-
await submitFetchBatch();
|
|
1329
|
-
}
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
// Batch operation setup
|
|
1333
|
-
let batch = [];
|
|
1334
|
-
let idGen = 0;
|
|
1335
|
-
let updatedEmailIds = [];
|
|
1336
|
-
let messageMap = new Map();
|
|
1337
|
-
|
|
1338
|
-
let submitBatch = async () => {
|
|
1339
|
-
let responseData;
|
|
1240
|
+
// Fetch current categories for all messages in batches. A failed batch request has
|
|
1241
|
+
// to abort the update: without the current categories the PATCH below would replace
|
|
1242
|
+
// every message's category list with just the added labels
|
|
1243
|
+
let fetched;
|
|
1340
1244
|
try {
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1245
|
+
fetched = await graphApi.executeBatchOperation(
|
|
1246
|
+
this,
|
|
1247
|
+
emailIds,
|
|
1248
|
+
(emailId, reqId) => ({
|
|
1249
|
+
id: reqId,
|
|
1250
|
+
method: 'GET',
|
|
1251
|
+
url: `/${this.oauth2UserPath}/messages/${emailId}?$select=categories`,
|
|
1252
|
+
headers: {
|
|
1253
|
+
Prefer: 'IdType="ImmutableId"'
|
|
1349
1254
|
}
|
|
1350
|
-
}
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
msg: 'Batch item failed',
|
|
1354
|
-
account: this.account,
|
|
1355
|
-
operation: 'update',
|
|
1356
|
-
emailId,
|
|
1357
|
-
status: response?.status,
|
|
1358
|
-
error: response?.body?.error
|
|
1359
|
-
});
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1255
|
+
}),
|
|
1256
|
+
'fetchCategories'
|
|
1257
|
+
);
|
|
1362
1258
|
} catch (err) {
|
|
1363
1259
|
this.logger.error({
|
|
1364
|
-
msg: 'Failed to
|
|
1260
|
+
msg: 'Failed to fetch current categories',
|
|
1365
1261
|
account: this.account,
|
|
1366
|
-
operation: 'update',
|
|
1367
1262
|
err
|
|
1368
1263
|
});
|
|
1369
1264
|
throw err;
|
|
1370
|
-
} finally {
|
|
1371
|
-
batch = [];
|
|
1372
|
-
messageMap = new Map();
|
|
1373
1265
|
}
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1266
|
+
for (let [emailId, body] of fetched.bodies) {
|
|
1267
|
+
if (body) {
|
|
1268
|
+
currentCategories.set(emailId, body.categories || []);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1379
1272
|
|
|
1273
|
+
let formatRequest = (emailId, reqId) => {
|
|
1380
1274
|
let bodyUpdates = { ...flagUpdates };
|
|
1381
1275
|
|
|
1382
1276
|
// Handle categories for this specific message
|
|
@@ -1414,25 +1308,15 @@ class OutlookClient extends BaseClient {
|
|
|
1414
1308
|
};
|
|
1415
1309
|
};
|
|
1416
1310
|
|
|
1417
|
-
//
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
batch.push(formatRequest(emailId));
|
|
1425
|
-
// submit batch when it reaches max size
|
|
1426
|
-
if (batch.length >= MAX_BATCH_SIZE) {
|
|
1427
|
-
await submitBatch(batch);
|
|
1428
|
-
}
|
|
1429
|
-
}
|
|
1430
|
-
if (batch.length) {
|
|
1431
|
-
// submit remaining batch
|
|
1432
|
-
await submitBatch(batch);
|
|
1433
|
-
}
|
|
1311
|
+
// The category fetch for a message may have failed (logged above) - skipping it keeps its
|
|
1312
|
+
// existing categories instead of overwriting them with the additions
|
|
1313
|
+
let targetIds = needsCurrentCategories ? emailIds.filter(emailId => currentCategories.has(emailId)) : emailIds;
|
|
1314
|
+
let skippedIds = needsCurrentCategories ? emailIds.filter(emailId => !currentCategories.has(emailId)) : [];
|
|
1315
|
+
|
|
1316
|
+
const { successIds: updatedEmailIds, failedIds: updateFailedIds } = await graphApi.executeBatchOperation(this, targetIds, formatRequest, 'update');
|
|
1317
|
+
const failedIds = skippedIds.concat(updateFailedIds);
|
|
1434
1318
|
|
|
1435
|
-
return Object.assign({}, updates, { emailIds: updatedEmailIds });
|
|
1319
|
+
return Object.assign({}, updates, { emailIds: updatedEmailIds }, failedIds.length ? { failed: { emailIds: failedIds } } : {});
|
|
1436
1320
|
}
|
|
1437
1321
|
|
|
1438
1322
|
/**
|
|
@@ -1526,54 +1410,10 @@ class OutlookClient extends BaseClient {
|
|
|
1526
1410
|
return { path: targetFolder.pathName };
|
|
1527
1411
|
}
|
|
1528
1412
|
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
let messageMap = new Map();
|
|
1534
|
-
|
|
1535
|
-
let submitBatch = async () => {
|
|
1536
|
-
let responseData;
|
|
1537
|
-
try {
|
|
1538
|
-
responseData = await this.requestWithRetry(`/$batch`, 'post', {
|
|
1539
|
-
requests: batch
|
|
1540
|
-
});
|
|
1541
|
-
for (let response of responseData?.responses || []) {
|
|
1542
|
-
let emailId = messageMap.get(response.id);
|
|
1543
|
-
if (response?.status >= 200 && response?.status < 300) {
|
|
1544
|
-
if (emailId) {
|
|
1545
|
-
updatedEmailIds.push(emailId);
|
|
1546
|
-
}
|
|
1547
|
-
} else {
|
|
1548
|
-
// Log individual batch item failures for debugging
|
|
1549
|
-
this.logger.warn({
|
|
1550
|
-
msg: 'Batch item failed',
|
|
1551
|
-
account: this.account,
|
|
1552
|
-
operation: 'move',
|
|
1553
|
-
emailId,
|
|
1554
|
-
status: response?.status,
|
|
1555
|
-
error: response?.body?.error
|
|
1556
|
-
});
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
} catch (err) {
|
|
1560
|
-
this.logger.error({
|
|
1561
|
-
msg: 'Failed to run batch operation',
|
|
1562
|
-
account: this.account,
|
|
1563
|
-
operation: 'move',
|
|
1564
|
-
err
|
|
1565
|
-
});
|
|
1566
|
-
throw err;
|
|
1567
|
-
} finally {
|
|
1568
|
-
batch = [];
|
|
1569
|
-
messageMap = new Map();
|
|
1570
|
-
}
|
|
1571
|
-
};
|
|
1572
|
-
|
|
1573
|
-
let formatRequest = emailId => {
|
|
1574
|
-
let reqId = `msg_${++idGen}`;
|
|
1575
|
-
messageMap.set(reqId, emailId);
|
|
1576
|
-
return {
|
|
1413
|
+
const { successIds: updatedEmailIds, failedIds } = await graphApi.executeBatchOperation(
|
|
1414
|
+
this,
|
|
1415
|
+
emailIds,
|
|
1416
|
+
(emailId, reqId) => ({
|
|
1577
1417
|
id: reqId,
|
|
1578
1418
|
method: 'POST',
|
|
1579
1419
|
url: `/${this.oauth2UserPath}/messages/${emailId}/move`,
|
|
@@ -1582,23 +1422,11 @@ class OutlookClient extends BaseClient {
|
|
|
1582
1422
|
'Content-Type': 'application/json',
|
|
1583
1423
|
Prefer: 'IdType="ImmutableId"'
|
|
1584
1424
|
}
|
|
1585
|
-
}
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
// Process messages in batches
|
|
1589
|
-
for (let emailId of emailIds) {
|
|
1590
|
-
batch.push(formatRequest(emailId));
|
|
1591
|
-
// submit batch
|
|
1592
|
-
if (batch.length >= MAX_BATCH_SIZE) {
|
|
1593
|
-
await submitBatch(batch);
|
|
1594
|
-
}
|
|
1595
|
-
}
|
|
1596
|
-
if (batch.length) {
|
|
1597
|
-
// submit batch
|
|
1598
|
-
await submitBatch(batch);
|
|
1599
|
-
}
|
|
1425
|
+
}),
|
|
1426
|
+
'move'
|
|
1427
|
+
);
|
|
1600
1428
|
|
|
1601
|
-
return Object.assign({ path: targetFolder.pathName }, { emailIds: updatedEmailIds });
|
|
1429
|
+
return Object.assign({ path: targetFolder.pathName }, { emailIds: updatedEmailIds }, failedIds.length ? { failed: { emailIds: failedIds } } : {});
|
|
1602
1430
|
}
|
|
1603
1431
|
|
|
1604
1432
|
/**
|
|
@@ -1730,21 +1558,17 @@ class OutlookClient extends BaseClient {
|
|
|
1730
1558
|
}
|
|
1731
1559
|
}
|
|
1732
1560
|
|
|
1733
|
-
// Resolve the folder path and special use
|
|
1561
|
+
// Resolve the folder path and special use. The message exists even when its folder is not
|
|
1562
|
+
// in the listing (a hidden folder, one the crawl skips): it is returned without a path.
|
|
1563
|
+
// Answering 404 here made new-message processing report an existing message as missing
|
|
1734
1564
|
if (messageData.parentFolderId) {
|
|
1735
1565
|
let folder = await this.resolveFolder(messageData.parentFolderId, { byId: true });
|
|
1736
|
-
if (
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
};
|
|
1741
|
-
error.code = 'NotFound';
|
|
1742
|
-
error.statusCode = 404;
|
|
1743
|
-
throw error;
|
|
1566
|
+
if (folder) {
|
|
1567
|
+
path = folder.pathName;
|
|
1568
|
+
specialUse = folder.specialUse;
|
|
1569
|
+
} else {
|
|
1570
|
+
this.logger.debug({ msg: 'Message folder is not in the mailbox listing', emailId, folderId: messageData.parentFolderId });
|
|
1744
1571
|
}
|
|
1745
|
-
|
|
1746
|
-
path = folder.pathName;
|
|
1747
|
-
specialUse = folder.specialUse;
|
|
1748
1572
|
}
|
|
1749
1573
|
|
|
1750
1574
|
// Process email headers
|
|
@@ -1780,6 +1604,10 @@ class OutlookClient extends BaseClient {
|
|
|
1780
1604
|
showPath: options.showPath
|
|
1781
1605
|
});
|
|
1782
1606
|
|
|
1607
|
+
if (specialUse) {
|
|
1608
|
+
formattedMessage.messageSpecialUse = specialUse;
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1783
1611
|
// Mark as seen if requested
|
|
1784
1612
|
if (options.markAsSeen && (!formattedMessage.flags || !formattedMessage.flags.includes('\\Seen'))) {
|
|
1785
1613
|
try {
|
|
@@ -1792,10 +1620,8 @@ class OutlookClient extends BaseClient {
|
|
|
1792
1620
|
}
|
|
1793
1621
|
}
|
|
1794
1622
|
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
if (!options.skipBounces) {
|
|
1798
|
-
await this.attachBounces(formattedMessage);
|
|
1623
|
+
if (options.detectBounce) {
|
|
1624
|
+
await this.detectBounce(formattedMessage);
|
|
1799
1625
|
}
|
|
1800
1626
|
|
|
1801
1627
|
// Generate web-safe HTML if requested
|
|
@@ -1824,21 +1650,12 @@ class OutlookClient extends BaseClient {
|
|
|
1824
1650
|
}
|
|
1825
1651
|
|
|
1826
1652
|
// Replace cid: references with data URLs
|
|
1827
|
-
formattedMessage.text.html = formattedMessage.text.html
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
if (content.content) {
|
|
1831
|
-
return `data:${content.contentType || 'application/octet-stream'};base64,${content.content}`;
|
|
1832
|
-
}
|
|
1833
|
-
}
|
|
1834
|
-
return fullMatch;
|
|
1653
|
+
formattedMessage.text.html = embedCidImages(formattedMessage.text.html, contentId => {
|
|
1654
|
+
let { content } = attachmentMap.get(contentId) || {};
|
|
1655
|
+
return content?.content && { contentType: content.contentType, content: content.content };
|
|
1835
1656
|
});
|
|
1836
1657
|
}
|
|
1837
1658
|
|
|
1838
|
-
if (specialUse) {
|
|
1839
|
-
formattedMessage.messageSpecialUse = specialUse;
|
|
1840
|
-
}
|
|
1841
|
-
|
|
1842
1659
|
return formattedMessage;
|
|
1843
1660
|
}
|
|
1844
1661
|
|
|
@@ -1853,9 +1670,25 @@ class OutlookClient extends BaseClient {
|
|
|
1853
1670
|
options = options || {};
|
|
1854
1671
|
await this.prepare();
|
|
1855
1672
|
|
|
1856
|
-
//
|
|
1857
|
-
|
|
1673
|
+
// The export calls this once per batch of messages, so the cached listing is used when
|
|
1674
|
+
// there is one: a live listing is a full folder crawl, and doing that per batch burned the
|
|
1675
|
+
// account's Graph throttling budget on a large export. Folders missing from it are
|
|
1676
|
+
// resolved one by one below, which refreshes the cache when the folder is new
|
|
1677
|
+
const mailboxListing = (await this.getCachedMailboxListing()) || (await this.getMailboxListing());
|
|
1858
1678
|
const folderMap = new Map(mailboxListing.map(f => [f.id, f]));
|
|
1679
|
+
const lookupFolder = async folderId => {
|
|
1680
|
+
if (!folderMap.has(folderId)) {
|
|
1681
|
+
let folder = null;
|
|
1682
|
+
try {
|
|
1683
|
+
folder = (await this.resolveFolder(folderId, { byId: true })) || null;
|
|
1684
|
+
} catch (err) {
|
|
1685
|
+
this.logger.warn({ msg: 'Failed to resolve message folder', account: this.account, folderId, err });
|
|
1686
|
+
}
|
|
1687
|
+
// remembered either way, so a folder the listing never includes costs one lookup
|
|
1688
|
+
folderMap.set(folderId, folder);
|
|
1689
|
+
}
|
|
1690
|
+
return folderMap.get(folderId);
|
|
1691
|
+
};
|
|
1859
1692
|
|
|
1860
1693
|
const results = [];
|
|
1861
1694
|
let idGen = 0;
|
|
@@ -1984,7 +1817,7 @@ class OutlookClient extends BaseClient {
|
|
|
1984
1817
|
// Resolve folder from pre-fetched map (O(1) lookup)
|
|
1985
1818
|
let path, specialUse;
|
|
1986
1819
|
if (messageData.parentFolderId) {
|
|
1987
|
-
const folder =
|
|
1820
|
+
const folder = await lookupFolder(messageData.parentFolderId);
|
|
1988
1821
|
if (folder) {
|
|
1989
1822
|
path = folder.pathName;
|
|
1990
1823
|
specialUse = folder.specialUse;
|
|
@@ -2164,87 +1997,74 @@ class OutlookClient extends BaseClient {
|
|
|
2164
1997
|
convertMessageToUploadObject(emailObject) {
|
|
2165
1998
|
let messageUploadObj = {};
|
|
2166
1999
|
|
|
2000
|
+
let addHeader = (name, value) => {
|
|
2001
|
+
if (!name || !value) {
|
|
2002
|
+
return;
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
if (GRAPH_THREADING_PROPERTIES.has(name)) {
|
|
2006
|
+
let id = GRAPH_THREADING_PROPERTIES.get(name);
|
|
2007
|
+
// a caller-supplied In-Reply-To can sit next to the lowercase one a reference adds
|
|
2008
|
+
messageUploadObj.singleValueExtendedProperties = (messageUploadObj.singleValueExtendedProperties || []).filter(entry => entry.id !== id);
|
|
2009
|
+
messageUploadObj.singleValueExtendedProperties.push({ id, value: String(value) });
|
|
2010
|
+
return;
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
// Everything else Graph either fills in from message fields (From, Reply-To, Date, ...)
|
|
2014
|
+
// or refuses outright
|
|
2015
|
+
if (!/^x-/i.test(name)) {
|
|
2016
|
+
return;
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders || [];
|
|
2020
|
+
messageUploadObj.internetMessageHeaders.push({ name, value });
|
|
2021
|
+
};
|
|
2022
|
+
|
|
2023
|
+
let toGraphAddress = entry => ({
|
|
2024
|
+
emailAddress: entry.name ? { address: entry.address, name: entry.name } : { address: entry.address }
|
|
2025
|
+
});
|
|
2026
|
+
|
|
2167
2027
|
for (let key of Object.keys(emailObject)) {
|
|
2168
2028
|
switch (key) {
|
|
2169
2029
|
case 'from':
|
|
2170
|
-
messageUploadObj.from =
|
|
2171
|
-
emailAddress: {
|
|
2172
|
-
address: emailObject.from.address
|
|
2173
|
-
}
|
|
2174
|
-
};
|
|
2175
|
-
if (emailObject.from.name) {
|
|
2176
|
-
messageUploadObj.from.emailAddress.name = emailObject.from.name;
|
|
2177
|
-
}
|
|
2030
|
+
messageUploadObj.from = toGraphAddress(emailObject.from);
|
|
2178
2031
|
break;
|
|
2179
2032
|
|
|
2180
2033
|
case 'to':
|
|
2181
2034
|
case 'cc':
|
|
2182
|
-
case 'bcc':
|
|
2183
|
-
|
|
2184
|
-
messageUploadObj[entryKey] = [];
|
|
2185
|
-
for (let addressEntry of emailObject[key] || []) {
|
|
2186
|
-
let addressObj = {
|
|
2187
|
-
emailAddress: {
|
|
2188
|
-
address: addressEntry.address
|
|
2189
|
-
}
|
|
2190
|
-
};
|
|
2191
|
-
if (addressEntry.name) {
|
|
2192
|
-
addressObj.emailAddress.name = addressEntry.name;
|
|
2193
|
-
}
|
|
2194
|
-
messageUploadObj[entryKey].push(addressObj);
|
|
2195
|
-
}
|
|
2035
|
+
case 'bcc':
|
|
2036
|
+
messageUploadObj[`${key}Recipients`] = (emailObject[key] || []).map(toGraphAddress);
|
|
2196
2037
|
break;
|
|
2197
|
-
}
|
|
2198
2038
|
|
|
2199
2039
|
case 'subject':
|
|
2200
2040
|
messageUploadObj[key] = emailObject[key];
|
|
2201
2041
|
break;
|
|
2202
2042
|
|
|
2203
2043
|
case 'headers': {
|
|
2204
|
-
messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders || [];
|
|
2205
2044
|
for (let header of Object.keys(emailObject.headers)) {
|
|
2206
|
-
|
|
2207
|
-
name: header.toLowerCase(),
|
|
2208
|
-
value: emailObject.headers[header]
|
|
2209
|
-
});
|
|
2045
|
+
addHeader(header.toLowerCase(), emailObject.headers[header]);
|
|
2210
2046
|
}
|
|
2211
2047
|
break;
|
|
2212
2048
|
}
|
|
2213
2049
|
|
|
2214
2050
|
case 'headerLines': {
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
let
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
'subject',
|
|
2228
|
-
'mime-version',
|
|
2229
|
-
'content-type',
|
|
2230
|
-
'content-disposition',
|
|
2231
|
-
'message-id',
|
|
2232
|
-
'content-id'
|
|
2233
|
-
].includes(header.key) ||
|
|
2234
|
-
// MS Graph API only allows up to 5 custom headers
|
|
2235
|
-
messageUploadObj.internetMessageHeaders.length >= 5
|
|
2236
|
-
) {
|
|
2237
|
-
continue;
|
|
2238
|
-
}
|
|
2051
|
+
for (let header of emailObject.headerLines) {
|
|
2052
|
+
// mailparser keeps the whole line; unfold it, a long References header arrives split over several lines
|
|
2053
|
+
let value = header.line
|
|
2054
|
+
? header.line
|
|
2055
|
+
.substring(header.line.indexOf(':') + 1)
|
|
2056
|
+
.replace(/\r?\n[ \t]+/g, ' ')
|
|
2057
|
+
.trim()
|
|
2058
|
+
: '';
|
|
2059
|
+
addHeader(header.key, value);
|
|
2060
|
+
}
|
|
2061
|
+
break;
|
|
2062
|
+
}
|
|
2239
2063
|
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
name,
|
|
2245
|
-
value
|
|
2246
|
-
});
|
|
2247
|
-
}
|
|
2064
|
+
case 'replyTo': {
|
|
2065
|
+
let entries = [].concat(emailObject.replyTo || []).filter(entry => entry?.address);
|
|
2066
|
+
if (entries.length) {
|
|
2067
|
+
messageUploadObj.replyTo = entries.map(toGraphAddress);
|
|
2248
2068
|
}
|
|
2249
2069
|
break;
|
|
2250
2070
|
}
|
|
@@ -2274,9 +2094,12 @@ class OutlookClient extends BaseClient {
|
|
|
2274
2094
|
if (attachment.cid) {
|
|
2275
2095
|
// make sure that cid links to not use <content-id> format, otherwise this will be replaced
|
|
2276
2096
|
attachmentEntry.contentId = attachment.cid.replace(/^[\s<]*|[\s>]*$/g, '');
|
|
2277
|
-
|
|
2097
|
+
// the reference grammar keeps a leading "<", so cid:<id> is collected as "<id"
|
|
2098
|
+
if (cidReferences.has(attachmentEntry.contentId) || cidReferences.has(`<${attachmentEntry.contentId}`)) {
|
|
2278
2099
|
attachmentEntry.isInline = true;
|
|
2279
|
-
|
|
2100
|
+
// A literal replace: the Content-ID is caller input, and as a RegExp
|
|
2101
|
+
// source a ( [ or \ in it threw a SyntaxError
|
|
2102
|
+
emailObject.html = emailObject.html.replaceAll(`cid:<${attachmentEntry.contentId}>`, `cid:${attachmentEntry.contentId}`);
|
|
2280
2103
|
}
|
|
2281
2104
|
}
|
|
2282
2105
|
if (attachment.contentDisposition === 'inline') {
|
|
@@ -2302,8 +2125,9 @@ class OutlookClient extends BaseClient {
|
|
|
2302
2125
|
};
|
|
2303
2126
|
}
|
|
2304
2127
|
|
|
2305
|
-
if (messageUploadObj.internetMessageHeaders
|
|
2306
|
-
|
|
2128
|
+
if (messageUploadObj.internetMessageHeaders?.length > MAX_GRAPH_CUSTOM_HEADERS) {
|
|
2129
|
+
// keep the last ones, the headers added closest to sending
|
|
2130
|
+
messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders.slice(-MAX_GRAPH_CUSTOM_HEADERS);
|
|
2307
2131
|
}
|
|
2308
2132
|
|
|
2309
2133
|
return messageUploadObj;
|
|
@@ -2330,13 +2154,14 @@ class OutlookClient extends BaseClient {
|
|
|
2330
2154
|
}
|
|
2331
2155
|
|
|
2332
2156
|
// Parse raw message into structured format
|
|
2333
|
-
let { emailObject, messageId, referencedMessage
|
|
2157
|
+
let { emailObject, messageId, referencedMessage } = await this.prepareRawMessage(data, {
|
|
2334
2158
|
returnObject: true
|
|
2335
2159
|
});
|
|
2336
2160
|
|
|
2337
2161
|
let messageUploadObj = this.convertMessageToUploadObject(emailObject);
|
|
2338
2162
|
|
|
2339
|
-
|
|
2163
|
+
// may already hold the threading properties of a reply or a forward
|
|
2164
|
+
messageUploadObj.singleValueExtendedProperties = messageUploadObj.singleValueExtendedProperties || [];
|
|
2340
2165
|
|
|
2341
2166
|
// Set message flags using MAPI properties
|
|
2342
2167
|
// https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/pidtagmessageflags-canonical-property
|
|
@@ -2378,7 +2203,8 @@ class OutlookClient extends BaseClient {
|
|
|
2378
2203
|
response: err.oauthRequest?.response?.error?.message || `Invalid message format`
|
|
2379
2204
|
};
|
|
2380
2205
|
error.code = err.oauthRequest?.response?.error?.code || 'InvalidMessage';
|
|
2381
|
-
|
|
2206
|
+
// Graph refused the content, which is the caller's to fix, not a server fault
|
|
2207
|
+
error.statusCode = 400;
|
|
2382
2208
|
throw error;
|
|
2383
2209
|
}
|
|
2384
2210
|
|
|
@@ -2402,7 +2228,6 @@ class OutlookClient extends BaseClient {
|
|
|
2402
2228
|
if (data.reference && data.reference.message) {
|
|
2403
2229
|
response.reference = {
|
|
2404
2230
|
message: data.reference.message,
|
|
2405
|
-
documentStore: documentStoreUsed,
|
|
2406
2231
|
success: referencedMessage ? true : false
|
|
2407
2232
|
};
|
|
2408
2233
|
|
|
@@ -2606,11 +2431,10 @@ class OutlookClient extends BaseClient {
|
|
|
2606
2431
|
let gatewayObject;
|
|
2607
2432
|
if (data.gateway) {
|
|
2608
2433
|
gatewayObject = new Gateway({ gateway: data.gateway, redis: this.redis, secret: this.secret });
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
}
|
|
2434
|
+
// The message was queued for this gateway, so it must not go out through the
|
|
2435
|
+
// provider API instead: a missing gateway throws GatewayNotFound and the job is
|
|
2436
|
+
// discarded, a Redis failure is thrown as is and the job retries
|
|
2437
|
+
gatewayData = await gatewayObject.loadGatewayData();
|
|
2614
2438
|
}
|
|
2615
2439
|
|
|
2616
2440
|
if (gatewayData) {
|
|
@@ -3349,6 +3173,30 @@ class OutlookClient extends BaseClient {
|
|
|
3349
3173
|
return cachedListing;
|
|
3350
3174
|
}
|
|
3351
3175
|
|
|
3176
|
+
/**
|
|
3177
|
+
* Whether a folder id missing from the cached listing may trigger a listing refresh, at most
|
|
3178
|
+
* once per LISTING_REFRESH_INTERVAL for the same id
|
|
3179
|
+
*/
|
|
3180
|
+
mayRefreshListingFor(folderId) {
|
|
3181
|
+
const now = Date.now();
|
|
3182
|
+
if (this.listingRefreshes.get(folderId) > now - LISTING_REFRESH_INTERVAL) {
|
|
3183
|
+
return false;
|
|
3184
|
+
}
|
|
3185
|
+
if (this.listingRefreshes.size > 100) {
|
|
3186
|
+
this.listingRefreshes.clear();
|
|
3187
|
+
}
|
|
3188
|
+
this.listingRefreshes.set(folderId, now);
|
|
3189
|
+
return true;
|
|
3190
|
+
}
|
|
3191
|
+
|
|
3192
|
+
async setCachedMailboxListing(mailboxListing) {
|
|
3193
|
+
try {
|
|
3194
|
+
await this.redis.hset(this.getAccountCacheKey(), 'outlookMailboxListing', JSON.stringify(mailboxListing));
|
|
3195
|
+
} catch (err) {
|
|
3196
|
+
this.logger.error({ msg: 'Failed to cache mailbox listing', err });
|
|
3197
|
+
}
|
|
3198
|
+
}
|
|
3199
|
+
|
|
3352
3200
|
/**
|
|
3353
3201
|
* Get complete mailbox folder listing from Graph API
|
|
3354
3202
|
* Handles special use folders and nested folder structures
|
|
@@ -3463,10 +3311,28 @@ class OutlookClient extends BaseClient {
|
|
|
3463
3311
|
|
|
3464
3312
|
// Callers that resolve multiple folders can pass a pre-fetched listing to avoid
|
|
3465
3313
|
// repeated cache reads or Graph API folder crawls
|
|
3466
|
-
let
|
|
3314
|
+
let cachedListing = !options.mailboxListing && (await this.getCachedMailboxListing());
|
|
3315
|
+
let mailboxListing = options.mailboxListing || cachedListing || (await this.getMailboxListing());
|
|
3467
3316
|
|
|
3468
3317
|
if (options.byId) {
|
|
3469
|
-
|
|
3318
|
+
let folder = mailboxListing.find(entry => entry.id === path);
|
|
3319
|
+
if (!folder && cachedListing && this.mayRefreshListingFor(path) && (await this.renewMailboxFolderCache())) {
|
|
3320
|
+
// A folder created after the listing was cached: without the refresh a new message
|
|
3321
|
+
// in it was reported as missing instead of new. Only when the folder delta reports
|
|
3322
|
+
// a change (it also reports one when it fails), and once per missing folder in a
|
|
3323
|
+
// while, as a folder the listing never includes would otherwise cost a request, or
|
|
3324
|
+
// during an outage a full folder crawl, per message
|
|
3325
|
+
try {
|
|
3326
|
+
mailboxListing = await this.getMailboxListing();
|
|
3327
|
+
} catch (err) {
|
|
3328
|
+
// the delta check consumed the change, forget it so the next miss asks again
|
|
3329
|
+
await this.redis.hdel(this.getAccountKey(), 'outlookMailFoldersDeltaUrl');
|
|
3330
|
+
throw err;
|
|
3331
|
+
}
|
|
3332
|
+
await this.setCachedMailboxListing(mailboxListing);
|
|
3333
|
+
folder = mailboxListing.find(entry => entry.id === path);
|
|
3334
|
+
}
|
|
3335
|
+
return folder;
|
|
3470
3336
|
}
|
|
3471
3337
|
|
|
3472
3338
|
// Map IMAP special use tags to Outlook folder types
|
|
@@ -3544,7 +3410,7 @@ class OutlookClient extends BaseClient {
|
|
|
3544
3410
|
} catch (err) {
|
|
3545
3411
|
this.logger.error({ msg: 'Failed to acquire subscription renew lock', account: this.account, err });
|
|
3546
3412
|
this.scheduleSubscriptionRetry({
|
|
3547
|
-
delayMs:
|
|
3413
|
+
delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
|
|
3548
3414
|
reason: 'lock_error',
|
|
3549
3415
|
errorMsg: 'Subscription renew retry after lock error failed',
|
|
3550
3416
|
fn: () => this.renewSubscription({ force: false })
|
|
@@ -3678,7 +3544,8 @@ class OutlookClient extends BaseClient {
|
|
|
3678
3544
|
// Schedule retry with exponential backoff
|
|
3679
3545
|
const retryCount = outlookSubscription.state.retryCount;
|
|
3680
3546
|
if (retryCount < OUTLOOK_MAX_RETRY_ATTEMPTS) {
|
|
3681
|
-
const retryDelay =
|
|
3547
|
+
const retryDelay =
|
|
3548
|
+
Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, retryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
|
|
3682
3549
|
|
|
3683
3550
|
this.scheduleSubscriptionRetry({
|
|
3684
3551
|
delayMs: retryDelay,
|
|
@@ -3742,7 +3609,7 @@ class OutlookClient extends BaseClient {
|
|
|
3742
3609
|
// Do not forward clearExisting on retry: by the time the retry fires,
|
|
3743
3610
|
// another path may have created a valid subscription that should not be cleared.
|
|
3744
3611
|
this.scheduleSubscriptionRetry({
|
|
3745
|
-
delayMs:
|
|
3612
|
+
delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
|
|
3746
3613
|
reason: 'lock_error',
|
|
3747
3614
|
errorMsg: 'Subscription ensure retry after lock error failed',
|
|
3748
3615
|
fn: () => this.ensureSubscription()
|
|
@@ -3895,7 +3762,8 @@ class OutlookClient extends BaseClient {
|
|
|
3895
3762
|
if (outlookSubscription.state?.state === 'error') {
|
|
3896
3763
|
const createRetryCount = outlookSubscription.state.createRetryCount || 0;
|
|
3897
3764
|
if (createRetryCount < OUTLOOK_MAX_RETRY_ATTEMPTS) {
|
|
3898
|
-
const retryDelay =
|
|
3765
|
+
const retryDelay =
|
|
3766
|
+
Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, createRetryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
|
|
3899
3767
|
|
|
3900
3768
|
this.scheduleSubscriptionRetry({
|
|
3901
3769
|
delayMs: retryDelay,
|
|
@@ -4149,20 +4017,12 @@ class OutlookClient extends BaseClient {
|
|
|
4149
4017
|
if (attachmentResponse?.contentType && !attachmentResponse?.contentBytes) {
|
|
4150
4018
|
// fetch raw value instead, happens with message/rfc822 attachments
|
|
4151
4019
|
try {
|
|
4152
|
-
|
|
4153
|
-
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
}
|
|
4159
|
-
);
|
|
4160
|
-
if (rawAttachmentContentStr) {
|
|
4161
|
-
if (options.returnBase64) {
|
|
4162
|
-
content = Buffer.from(rawAttachmentContentStr).toString('base64');
|
|
4163
|
-
} else {
|
|
4164
|
-
content = Buffer.from(rawAttachmentContentStr);
|
|
4165
|
-
}
|
|
4020
|
+
// Raw bytes: a text round-trip would corrupt every non-UTF-8 byte of the message
|
|
4021
|
+
let rawAttachmentContent = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/attachments/${id}/$value`, 'get', Buffer.alloc(0), {
|
|
4022
|
+
returnBuffer: true
|
|
4023
|
+
});
|
|
4024
|
+
if (rawAttachmentContent?.length) {
|
|
4025
|
+
content = options.returnBase64 ? rawAttachmentContent.toString('base64') : rawAttachmentContent;
|
|
4166
4026
|
}
|
|
4167
4027
|
} catch (err) {
|
|
4168
4028
|
throw attachmentErrorHandler(err);
|
|
@@ -4184,15 +4044,23 @@ class OutlookClient extends BaseClient {
|
|
|
4184
4044
|
*/
|
|
4185
4045
|
triggerSync() {
|
|
4186
4046
|
if (this.processingHistory) {
|
|
4047
|
+
// Run again when this drain is done: whatever asked may have arrived after the drain
|
|
4048
|
+
// looked for it (an event queued after its last pull, a recovery request)
|
|
4049
|
+
this.syncRequested = true;
|
|
4187
4050
|
return;
|
|
4188
4051
|
}
|
|
4189
4052
|
this.processingHistory = true;
|
|
4053
|
+
this.syncRequested = false;
|
|
4190
4054
|
this.processHistory()
|
|
4191
4055
|
.catch(err => {
|
|
4192
4056
|
this.logger.error({ msg: 'Failed to process account history', account: this.account, err });
|
|
4193
4057
|
})
|
|
4194
4058
|
.finally(() => {
|
|
4195
4059
|
this.processingHistory = false;
|
|
4060
|
+
this.scheduleDeferredRetryTimer();
|
|
4061
|
+
if (this.syncRequested && !this.closed) {
|
|
4062
|
+
this.triggerSync();
|
|
4063
|
+
}
|
|
4196
4064
|
});
|
|
4197
4065
|
}
|
|
4198
4066
|
|
|
@@ -4202,62 +4070,91 @@ class OutlookClient extends BaseClient {
|
|
|
4202
4070
|
*/
|
|
4203
4071
|
async processHistory() {
|
|
4204
4072
|
let event;
|
|
4205
|
-
let newMessageOptions;
|
|
4206
4073
|
let processedAny = false;
|
|
4074
|
+
const context = {};
|
|
4207
4075
|
|
|
4208
|
-
|
|
4209
|
-
|
|
4076
|
+
// The event is already off the queue, so a failure must not abort the drain and lose the
|
|
4077
|
+
// events behind it. A transient one is deferred and retried instead
|
|
4078
|
+
const handle = async event => {
|
|
4079
|
+
try {
|
|
4080
|
+
await this.processChangeEvent(event, context);
|
|
4081
|
+
} catch (err) {
|
|
4082
|
+
await this.deferFailedChangeEvent(event, err);
|
|
4083
|
+
}
|
|
4084
|
+
};
|
|
4210
4085
|
|
|
4211
|
-
|
|
4212
|
-
|
|
4213
|
-
|
|
4214
|
-
|
|
4086
|
+
// Changes deferred for a retry go first, then the queue
|
|
4087
|
+
try {
|
|
4088
|
+
await this.processDueDeferredEvents(handle);
|
|
4089
|
+
} catch (err) {
|
|
4090
|
+
this.logger.error({ msg: 'Failed to process deferred mailbox changes', account: this.account, err });
|
|
4091
|
+
}
|
|
4215
4092
|
|
|
4216
|
-
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
|
|
4093
|
+
while ((event = await this.accountObject.pullQueueEvent()) !== null) {
|
|
4094
|
+
processedAny = true;
|
|
4095
|
+
await handle(event);
|
|
4096
|
+
}
|
|
4220
4097
|
|
|
4221
|
-
|
|
4222
|
-
|
|
4223
|
-
|
|
4224
|
-
|
|
4225
|
-
}
|
|
4098
|
+
if (processedAny) {
|
|
4099
|
+
await this._updateLastNotificationTime();
|
|
4100
|
+
}
|
|
4101
|
+
}
|
|
4226
4102
|
|
|
4227
|
-
|
|
4103
|
+
/**
|
|
4104
|
+
* Processes one change notification, throwing when it could not be processed
|
|
4105
|
+
* @param {Object} event - Queue event
|
|
4106
|
+
* @param {Object} context - Shared by the events of one drain, caches the fetch options
|
|
4107
|
+
*/
|
|
4108
|
+
async processChangeEvent(event, context) {
|
|
4109
|
+
switch (event.type) {
|
|
4110
|
+
case 'updated':
|
|
4111
|
+
await this.processUpdatedMessage(event.message);
|
|
4112
|
+
break;
|
|
4228
4113
|
|
|
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
|
-
}
|
|
4114
|
+
case 'deleted':
|
|
4115
|
+
await this.processDeletedMessage(event.message);
|
|
4116
|
+
break;
|
|
4242
4117
|
|
|
4243
|
-
|
|
4244
|
-
|
|
4245
|
-
|
|
4246
|
-
|
|
4247
|
-
|
|
4248
|
-
|
|
4118
|
+
case 'created': {
|
|
4119
|
+
let messageData = await this.prepareNewMessage(event.message, await this.getDrainFetchOptions(context));
|
|
4120
|
+
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
|
+
) {
|
|
4132
|
+
this.logger.debug({ msg: 'Ignore recently seen new email event', type: 'history-event', emailId: event.message });
|
|
4133
|
+
break;
|
|
4249
4134
|
}
|
|
4250
|
-
|
|
4135
|
+
|
|
4136
|
+
// processNew() clears messageData.path
|
|
4137
|
+
const path = messageData.path;
|
|
4138
|
+
await this.processNew(messageData, context.newMessageOptions);
|
|
4139
|
+
await this.markAnnounced(messageData.id, path);
|
|
4251
4140
|
}
|
|
4141
|
+
break;
|
|
4142
|
+
}
|
|
4252
4143
|
|
|
4253
|
-
|
|
4254
|
-
|
|
4144
|
+
case 'missedRecovery': {
|
|
4145
|
+
const since = await this.missedRecoveryStart(event.receivedAt);
|
|
4146
|
+
if (context.recoveredSince && context.recoveredSince <= since) {
|
|
4147
|
+
// an earlier request in the same drain already covered this window
|
|
4255
4148
|
break;
|
|
4149
|
+
}
|
|
4150
|
+
await this.syncMissedMessages({ since, options: await this.getDrainFetchOptions(context) });
|
|
4151
|
+
context.recoveredSince = since;
|
|
4152
|
+
break;
|
|
4256
4153
|
}
|
|
4257
|
-
}
|
|
4258
4154
|
|
|
4259
|
-
|
|
4260
|
-
|
|
4155
|
+
default:
|
|
4156
|
+
this.logger.debug({ msg: 'Ignoring unknown history event type', type: 'history-event', event });
|
|
4157
|
+
break;
|
|
4261
4158
|
}
|
|
4262
4159
|
}
|
|
4263
4160
|
|
|
@@ -4269,36 +4166,62 @@ class OutlookClient extends BaseClient {
|
|
|
4269
4166
|
}
|
|
4270
4167
|
}
|
|
4271
4168
|
|
|
4169
|
+
// Fetch options, resolved once per drain
|
|
4170
|
+
async getDrainFetchOptions(context) {
|
|
4171
|
+
if (!context.newMessageOptions) {
|
|
4172
|
+
context.newMessageOptions = await this.getMessageFetchOptions();
|
|
4173
|
+
context.newMessageOptions.showPath = true;
|
|
4174
|
+
}
|
|
4175
|
+
return context.newMessageOptions;
|
|
4176
|
+
}
|
|
4177
|
+
|
|
4272
4178
|
/**
|
|
4273
|
-
*
|
|
4274
|
-
*
|
|
4275
|
-
*
|
|
4276
|
-
*
|
|
4179
|
+
* Where a missed-notification recovery has to start looking. Graph retries an undeliverable
|
|
4180
|
+
* notification for hours before it gives up and reports it missed, so the lost changes can
|
|
4181
|
+
* be that old, and the last notification time is no bound: it moves on with every delivery
|
|
4182
|
+
* that did arrive in the meantime.
|
|
4183
|
+
*
|
|
4184
|
+
* Never further back than announced messages are remembered (older ones would be announced
|
|
4185
|
+
* again, and an account that was offline for days would flood its webhooks), than the point
|
|
4186
|
+
* they were first recorded, or than a previous recovery pass already reached
|
|
4187
|
+
* @param {number} receivedAt - When the recovery was requested (epoch ms)
|
|
4188
|
+
* @returns {Promise<number>} Epoch ms
|
|
4277
4189
|
*/
|
|
4278
|
-
async
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
//
|
|
4284
|
-
const
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4190
|
+
async missedRecoveryStart(receivedAt) {
|
|
4191
|
+
const [lastNotification, announcedSince, recoveredUntil] = (
|
|
4192
|
+
await this.redis.hmget(this.getAccountKey(), 'outlookLastNotification', 'outlookAnnouncedSince', 'outlookRecoveredUntil')
|
|
4193
|
+
).map(Number);
|
|
4194
|
+
|
|
4195
|
+
// 2-minute safety margin before the last known good notification and the last pass
|
|
4196
|
+
const margin = 2 * 60 * 1000;
|
|
4197
|
+
const wanted = Math.min(receivedAt - OUTLOOK_MISSED_LOOKBACK, lastNotification ? lastNotification - margin : Infinity);
|
|
4198
|
+
const trackedFrom = Math.max(Date.now() - OUTLOOK_ANNOUNCED_RETENTION, announcedSince || 0);
|
|
4199
|
+
const recoveredFrom = recoveredUntil ? recoveredUntil - margin : 0;
|
|
4200
|
+
|
|
4201
|
+
if (wanted < trackedFrom && recoveredFrom < trackedFrom) {
|
|
4202
|
+
this.logger.warn({
|
|
4203
|
+
msg: 'Missed notification recovery window truncated',
|
|
4204
|
+
account: this.account,
|
|
4205
|
+
wanted: new Date(wanted).toISOString(),
|
|
4206
|
+
since: new Date(trackedFrom).toISOString()
|
|
4207
|
+
});
|
|
4291
4208
|
}
|
|
4292
4209
|
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
|
|
4210
|
+
return Math.max(wanted, trackedFrom, recoveredFrom);
|
|
4211
|
+
}
|
|
4212
|
+
|
|
4213
|
+
/**
|
|
4214
|
+
* 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
|
|
4218
|
+
* @param {Object} opts
|
|
4219
|
+
* @param {number} opts.since - Epoch ms to look back to
|
|
4220
|
+
* @param {Object} opts.options - Message fetch options
|
|
4221
|
+
*/
|
|
4222
|
+
async syncMissedMessages({ since, options }) {
|
|
4223
|
+
const startedAt = Date.now();
|
|
4224
|
+
const sinceTime = new Date(since);
|
|
4302
4225
|
|
|
4303
4226
|
this.logger.info({
|
|
4304
4227
|
msg: 'Recovering missed notifications',
|
|
@@ -4306,139 +4229,85 @@ class OutlookClient extends BaseClient {
|
|
|
4306
4229
|
since: sinceTime.toISOString()
|
|
4307
4230
|
});
|
|
4308
4231
|
|
|
4309
|
-
let
|
|
4232
|
+
let checked = 0;
|
|
4233
|
+
let recoveredCount = 0;
|
|
4234
|
+
|
|
4310
4235
|
let reqUrl = `/${this.oauth2UserPath}/messages`;
|
|
4311
4236
|
let reqPayload = {
|
|
4312
4237
|
$filter: `receivedDateTime gt ${sinceTime.toISOString()}`,
|
|
4313
4238
|
$select: 'id,parentFolderId',
|
|
4314
4239
|
$top: 250,
|
|
4315
|
-
$orderby: 'receivedDateTime
|
|
4240
|
+
$orderby: 'receivedDateTime asc'
|
|
4316
4241
|
};
|
|
4317
4242
|
|
|
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
|
-
});
|
|
4353
|
-
|
|
4354
|
-
let newMessageOptions = await this.getMessageFetchOptions();
|
|
4355
|
-
newMessageOptions.showPath = true;
|
|
4243
|
+
// A failed page throws: the whole recovery is retried, and the messages it already
|
|
4244
|
+
// announced are skipped as announced
|
|
4245
|
+
while (reqUrl) {
|
|
4246
|
+
let pageResult = await this.request(reqUrl, 'get', reqPayload);
|
|
4247
|
+
let messages = pageResult?.value || [];
|
|
4248
|
+
checked += messages.length;
|
|
4356
4249
|
|
|
4357
|
-
|
|
4358
|
-
let folderMap = new Map();
|
|
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
|
-
}
|
|
4250
|
+
let announced = await this.getAnnounced(messages.map(msg => msg.id));
|
|
4385
4251
|
|
|
4386
|
-
|
|
4387
|
-
if (
|
|
4252
|
+
for (const msg of messages) {
|
|
4253
|
+
if (announced.has(msg.id)) {
|
|
4388
4254
|
continue;
|
|
4389
4255
|
}
|
|
4390
|
-
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
if (recentlySeen) {
|
|
4256
|
+
try {
|
|
4257
|
+
let messageData = await this.prepareNewMessage(msg.id, options);
|
|
4258
|
+
if (!messageData) {
|
|
4394
4259
|
continue;
|
|
4395
4260
|
}
|
|
4396
|
-
}
|
|
4397
4261
|
|
|
4398
|
-
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
|
|
4262
|
+
// processNew() clears messageData.path
|
|
4263
|
+
const path = messageData.path;
|
|
4264
|
+
await this.processNew(messageData, options);
|
|
4265
|
+
await this.markAnnounced(messageData.id, path);
|
|
4266
|
+
recoveredCount++;
|
|
4267
|
+
} catch (err) {
|
|
4268
|
+
await this.deferFailedChangeEvent({ type: 'created', message: msg.id }, err);
|
|
4269
|
+
}
|
|
4402
4270
|
}
|
|
4271
|
+
|
|
4272
|
+
reqUrl = pageResult?.['@odata.nextLink'] || null;
|
|
4273
|
+
reqPayload = null; // nextLink includes all query params
|
|
4403
4274
|
}
|
|
4404
4275
|
|
|
4405
4276
|
this.logger.info({
|
|
4406
4277
|
msg: 'Missed notification recovery completed',
|
|
4407
4278
|
account: this.account,
|
|
4408
|
-
checked
|
|
4279
|
+
checked,
|
|
4409
4280
|
recovered: recoveredCount
|
|
4410
4281
|
});
|
|
4411
4282
|
|
|
4283
|
+
// Everything received before the pass started has been looked at. hSetExists, so a pass
|
|
4284
|
+
// that outlives a deleted account does not recreate its record
|
|
4285
|
+
await this.redis.hSetExists(this.getAccountKey(), 'outlookRecoveredUntil', startedAt.toString());
|
|
4412
4286
|
await this._updateLastNotificationTime();
|
|
4287
|
+
}
|
|
4413
4288
|
|
|
4414
|
-
|
|
4289
|
+
// A message gone by the time a change notification is processed is a routine race: for every
|
|
4290
|
+
// genuine deletion the existence probe answers 404. Any other failure says nothing about the
|
|
4291
|
+
// message, so it is thrown for processHistory() to retry - a 5xx here used to be reported as
|
|
4292
|
+
// a deletion, and an update was dropped.
|
|
4293
|
+
fetchChangedMessage(emailId, fields) {
|
|
4294
|
+
return this.request(`/${this.oauth2UserPath}/messages/${emailId}`, 'get', { $select: fields.join(',') }).catch(err => {
|
|
4295
|
+
if (err.code === 'MessageNotFound' || err.statusCode === 404) {
|
|
4296
|
+
this.logger.debug({ msg: 'Failed to fetch message data', emailId, err });
|
|
4297
|
+
return null;
|
|
4298
|
+
}
|
|
4299
|
+
throw err;
|
|
4300
|
+
});
|
|
4415
4301
|
}
|
|
4416
4302
|
|
|
4417
4303
|
/**
|
|
4418
4304
|
* Process a deleted message event
|
|
4419
4305
|
* Verifies if actually deleted or just moved
|
|
4420
4306
|
*/
|
|
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
4307
|
async processDeletedMessage(emailId) {
|
|
4432
4308
|
// Verify if the message was actually deleted.
|
|
4433
4309
|
// 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
|
-
}
|
|
4310
|
+
let messageData = await this.fetchChangedMessage(emailId, ['id', 'parentFolderId']);
|
|
4442
4311
|
if (messageData) {
|
|
4443
4312
|
// The message still exists, so there's no need to notify about the deletion.
|
|
4444
4313
|
// The message was likely moved, but since we cannot determine the previous mailbox folder,
|
|
@@ -4459,15 +4328,7 @@ class OutlookClient extends BaseClient {
|
|
|
4459
4328
|
* Tracks flag changes and deduplicates repeated updates
|
|
4460
4329
|
*/
|
|
4461
4330
|
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
|
-
}
|
|
4331
|
+
let messageData = await this.fetchChangedMessage(emailId, ['id', 'isRead', 'isDraft', 'flag', 'conversationId', 'parentFolderId']);
|
|
4471
4332
|
if (!messageData) {
|
|
4472
4333
|
// do nothing, message not found
|
|
4473
4334
|
return;
|
|
@@ -4509,14 +4370,16 @@ class OutlookClient extends BaseClient {
|
|
|
4509
4370
|
changes
|
|
4510
4371
|
};
|
|
4511
4372
|
|
|
4512
|
-
// Check
|
|
4513
|
-
let
|
|
4514
|
-
|
|
4373
|
+
// Check the dedupe lock to see if we recently processed the update event for the same email
|
|
4374
|
+
let dedupeKey = `${messageData.id}:updated`;
|
|
4375
|
+
let dedupeValue = JSON.stringify(changes.flags.value);
|
|
4376
|
+
if (await this.isRecentlySeen(dedupeKey, dedupeValue)) {
|
|
4515
4377
|
this.logger.debug({ msg: 'Ignore recently seen updated email event', type: 'history-event', emailId: messageData.id, flags: changes.flags.value });
|
|
4516
4378
|
return;
|
|
4517
4379
|
}
|
|
4518
4380
|
|
|
4519
4381
|
await this.notify({ path, specialUse }, MESSAGE_UPDATED_NOTIFY, messageUpdate);
|
|
4382
|
+
await this.markSeen(dedupeKey, dedupeValue);
|
|
4520
4383
|
}
|
|
4521
4384
|
|
|
4522
4385
|
/**
|
|
@@ -4532,9 +4395,6 @@ class OutlookClient extends BaseClient {
|
|
|
4532
4395
|
options.headers = 'headers' in options ? options.headers : false;
|
|
4533
4396
|
}
|
|
4534
4397
|
|
|
4535
|
-
// The sync path never reads the bounces field
|
|
4536
|
-
options.skipBounces = true;
|
|
4537
|
-
|
|
4538
4398
|
let messageData;
|
|
4539
4399
|
try {
|
|
4540
4400
|
messageData = await this.getMessage(emailId, options);
|
|
@@ -4797,46 +4657,88 @@ class OutlookClient extends BaseClient {
|
|
|
4797
4657
|
}
|
|
4798
4658
|
|
|
4799
4659
|
/**
|
|
4800
|
-
*
|
|
4801
|
-
*
|
|
4660
|
+
* The dedupe buckets a key is looked up in, newest first: one bucket to the future, the
|
|
4661
|
+
* current 10 minute bucket, and one to the past
|
|
4802
4662
|
*/
|
|
4803
|
-
|
|
4804
|
-
// 10 minute buckets
|
|
4663
|
+
dedupeBucketKeys() {
|
|
4805
4664
|
let currentBucketTime = new Date(`${new Date().toISOString().substring(0, 15)}0:00.000Z`).getTime();
|
|
4665
|
+
return [-1, 0, 1].map(i => `${REDIS_PREFIX}bck:${new Date(currentBucketTime - i * 10 * 60 * 1000).toISOString()}`);
|
|
4666
|
+
}
|
|
4806
4667
|
|
|
4807
|
-
|
|
4808
|
-
|
|
4668
|
+
/**
|
|
4669
|
+
* Whether the same change was recently processed with the same value
|
|
4670
|
+
*/
|
|
4671
|
+
async isRecentlySeen(key, value = '1') {
|
|
4809
4672
|
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}`;
|
|
4673
|
+
for (let bucketKey of this.dedupeBucketKeys()) {
|
|
4815
4674
|
pipeline = pipeline.hget(bucketKey, key);
|
|
4816
4675
|
}
|
|
4817
4676
|
|
|
4818
4677
|
let pipelineRes = await pipeline.exec();
|
|
4819
4678
|
for (let [, bucketRes] of pipelineRes) {
|
|
4820
4679
|
if (bucketRes) {
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
}
|
|
4824
|
-
// There is a value, but it does not match the known last value
|
|
4825
|
-
break;
|
|
4680
|
+
// Always check newer first. If there is an outdated value in an older bucket, then we use the newer value
|
|
4681
|
+
return bucketRes === value;
|
|
4826
4682
|
}
|
|
4827
4683
|
}
|
|
4684
|
+
return false;
|
|
4685
|
+
}
|
|
4828
4686
|
|
|
4829
|
-
|
|
4830
|
-
|
|
4831
|
-
|
|
4687
|
+
/**
|
|
4688
|
+
* Records a processed change for isRecentlySeen(). Callers mark a change only once it was
|
|
4689
|
+
* processed, so a change that failed is not skipped as "recently seen" on its retry
|
|
4690
|
+
*/
|
|
4691
|
+
async markSeen(key, value = '1') {
|
|
4692
|
+
let bucketKey = this.dedupeBucketKeys()[1];
|
|
4832
4693
|
await this.redis
|
|
4833
4694
|
.multi()
|
|
4834
4695
|
.hset(bucketKey, key, value)
|
|
4835
4696
|
// make sure the bucket does not expire until the next one is already valid
|
|
4836
4697
|
.expire(bucketKey, 12 * 60)
|
|
4837
4698
|
.exec();
|
|
4699
|
+
}
|
|
4838
4700
|
|
|
4839
|
-
|
|
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
|
|
4704
|
+
getAnnouncedKey() {
|
|
4705
|
+
return `${REDIS_PREFIX}iam:${this.account}:announced`;
|
|
4706
|
+
}
|
|
4707
|
+
|
|
4708
|
+
/**
|
|
4709
|
+
* Marks a new message as announced, for both the dedupe buckets and the recovery pass
|
|
4710
|
+
*/
|
|
4711
|
+
async markAnnounced(messageId, path) {
|
|
4712
|
+
const now = Date.now();
|
|
4713
|
+
const announcedKey = this.getAnnouncedKey();
|
|
4714
|
+
const bucketKey = this.dedupeBucketKeys()[1];
|
|
4715
|
+
await this.redis
|
|
4716
|
+
.multi()
|
|
4717
|
+
.hset(bucketKey, `${messageId}:created`, path)
|
|
4718
|
+
.expire(bucketKey, 12 * 60)
|
|
4719
|
+
.zadd(announcedKey, now, messageId)
|
|
4720
|
+
.zremrangebyscore(announcedKey, '-inf', now - OUTLOOK_ANNOUNCED_RETENTION)
|
|
4721
|
+
.pexpire(announcedKey, OUTLOOK_ANNOUNCED_RETENTION)
|
|
4722
|
+
.exec();
|
|
4723
|
+
}
|
|
4724
|
+
|
|
4725
|
+
/**
|
|
4726
|
+
* @param {string[]} messageIds
|
|
4727
|
+
* @returns {Promise<Set<string>>} The ones announced within OUTLOOK_ANNOUNCED_RETENTION
|
|
4728
|
+
*/
|
|
4729
|
+
async getAnnounced(messageIds) {
|
|
4730
|
+
if (!messageIds.length) {
|
|
4731
|
+
return new Set();
|
|
4732
|
+
}
|
|
4733
|
+
const announcedKey = this.getAnnouncedKey();
|
|
4734
|
+
const cutoff = Date.now() - OUTLOOK_ANNOUNCED_RETENTION;
|
|
4735
|
+
// ZSCORE per ID rather than ZMSCORE, which needs Redis 6.2
|
|
4736
|
+
let pipeline = this.redis.pipeline();
|
|
4737
|
+
for (const messageId of messageIds) {
|
|
4738
|
+
pipeline = pipeline.zscore(announcedKey, messageId);
|
|
4739
|
+
}
|
|
4740
|
+
const results = await pipeline.exec();
|
|
4741
|
+
return new Set(messageIds.filter((id, i) => results[i][1] !== null && Number(results[i][1]) > cutoff));
|
|
4840
4742
|
}
|
|
4841
4743
|
|
|
4842
4744
|
/**
|