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
|
@@ -11,7 +11,7 @@ const he = require('he');
|
|
|
11
11
|
const { BaseClient, metricsMeta } = require('./base-client');
|
|
12
12
|
const { isTransientCredentialError } = require('./credential-errors');
|
|
13
13
|
const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
|
|
14
|
-
const { emitChangeEvent, toCamelCase, collectCidReferences,
|
|
14
|
+
const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
|
|
15
15
|
const { Gateway } = require('../gateway');
|
|
16
16
|
|
|
17
17
|
const {
|
|
@@ -321,6 +321,7 @@ class GmailClient extends BaseClient {
|
|
|
321
321
|
|
|
322
322
|
this.state = 'connecting';
|
|
323
323
|
this.cancelInitRetry();
|
|
324
|
+
this.cancelDeferredRetryTimer();
|
|
324
325
|
await this.setStateVal();
|
|
325
326
|
|
|
326
327
|
await this.getAccount();
|
|
@@ -513,6 +514,7 @@ class GmailClient extends BaseClient {
|
|
|
513
514
|
clearTimeout(this.renewWatchTimer);
|
|
514
515
|
clearTimeout(this.fallbackPollingTimer);
|
|
515
516
|
this.cancelInitRetry();
|
|
517
|
+
this.cancelDeferredRetryTimer();
|
|
516
518
|
this.closed = true;
|
|
517
519
|
|
|
518
520
|
// A graceful close means the in-flight history entry did not kill this
|
|
@@ -589,6 +591,7 @@ class GmailClient extends BaseClient {
|
|
|
589
591
|
clearTimeout(this.renewWatchTimer);
|
|
590
592
|
clearTimeout(this.fallbackPollingTimer);
|
|
591
593
|
this.cancelInitRetry();
|
|
594
|
+
this.cancelDeferredRetryTimer();
|
|
592
595
|
this.closed = true;
|
|
593
596
|
|
|
594
597
|
// Clean up cached data
|
|
@@ -1333,10 +1336,8 @@ class GmailClient extends BaseClient {
|
|
|
1333
1336
|
}
|
|
1334
1337
|
}
|
|
1335
1338
|
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
if (!options.skipBounces) {
|
|
1339
|
-
await this.attachBounces(formattedMessage);
|
|
1339
|
+
if (options.detectBounce) {
|
|
1340
|
+
await this.detectBounce(formattedMessage);
|
|
1340
1341
|
}
|
|
1341
1342
|
|
|
1342
1343
|
// Generate web-safe HTML if requested
|
|
@@ -1366,14 +1367,9 @@ class GmailClient extends BaseClient {
|
|
|
1366
1367
|
}
|
|
1367
1368
|
|
|
1368
1369
|
// Replace CID references with data URIs
|
|
1369
|
-
formattedMessage.text.html = formattedMessage.text.html
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
if (content.content) {
|
|
1373
|
-
return `data:${content.contentType || 'application/octet-stream'};base64,${content.content.toString('base64')}`;
|
|
1374
|
-
}
|
|
1375
|
-
}
|
|
1376
|
-
return fullMatch;
|
|
1370
|
+
formattedMessage.text.html = embedCidImages(formattedMessage.text.html, contentId => {
|
|
1371
|
+
let { content } = attachmentMap.get(contentId) || {};
|
|
1372
|
+
return content?.content && { contentType: content.contentType, content: content.content.toString('base64') };
|
|
1377
1373
|
});
|
|
1378
1374
|
}
|
|
1379
1375
|
|
|
@@ -1522,7 +1518,7 @@ class GmailClient extends BaseClient {
|
|
|
1522
1518
|
}
|
|
1523
1519
|
|
|
1524
1520
|
// Generate raw message
|
|
1525
|
-
let { raw, messageId, referencedMessage
|
|
1521
|
+
let { raw, messageId, referencedMessage } = await this.prepareRawMessage(data);
|
|
1526
1522
|
if (raw?.buffer) {
|
|
1527
1523
|
// convert from a Uint8Array to a Buffer
|
|
1528
1524
|
raw = Buffer.from(raw);
|
|
@@ -1567,7 +1563,6 @@ class GmailClient extends BaseClient {
|
|
|
1567
1563
|
response.reference = {};
|
|
1568
1564
|
if (data.reference.message) {
|
|
1569
1565
|
response.reference.message = data.reference.message;
|
|
1570
|
-
response.reference.documentStore = documentStoreUsed;
|
|
1571
1566
|
response.reference.success = referencedMessage ? true : false;
|
|
1572
1567
|
if (!referencedMessage) {
|
|
1573
1568
|
response.reference.error = 'Referenced message was not found';
|
|
@@ -1668,11 +1663,10 @@ class GmailClient extends BaseClient {
|
|
|
1668
1663
|
let gatewayObject;
|
|
1669
1664
|
if (data.gateway) {
|
|
1670
1665
|
gatewayObject = new Gateway({ gateway: data.gateway, redis: this.redis, secret: this.secret });
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
}
|
|
1666
|
+
// The message was queued for this gateway, so it must not go out through the
|
|
1667
|
+
// provider API instead: a missing gateway throws GatewayNotFound and the job is
|
|
1668
|
+
// discarded, a Redis failure is thrown as is and the job retries
|
|
1669
|
+
gatewayData = await gatewayObject.loadGatewayData();
|
|
1676
1670
|
}
|
|
1677
1671
|
|
|
1678
1672
|
if (gatewayData) {
|
|
@@ -1701,7 +1695,9 @@ class GmailClient extends BaseClient {
|
|
|
1701
1695
|
|
|
1702
1696
|
let submitInfo;
|
|
1703
1697
|
try {
|
|
1704
|
-
|
|
1698
|
+
// noRetry: a send is never repeated, not even after a 429 - a socket that drops after
|
|
1699
|
+
// Gmail accepted the message would otherwise deliver it twice
|
|
1700
|
+
submitInfo = await this.request(`${GMAIL_API_BASE}${targetEndpoint}`, 'post', payload, { contentType, noRetry: true });
|
|
1705
1701
|
} catch (err) {
|
|
1706
1702
|
// Report the failure the way the SMTP path does (messageDeliveryError webhook,
|
|
1707
1703
|
// feedback key) before the job decides whether to retry
|
|
@@ -1709,6 +1705,21 @@ class GmailClient extends BaseClient {
|
|
|
1709
1705
|
throw err;
|
|
1710
1706
|
}
|
|
1711
1707
|
|
|
1708
|
+
// Record the accept before anything else can throw: once Gmail has the message, a failure
|
|
1709
|
+
// in the bookkeeping below must not make the job retry and send it a second time
|
|
1710
|
+
// (isAlreadySent() in the submit worker keys on this progress state). Written once: the
|
|
1711
|
+
// Message-ID Gmail may rewrite is read back below and reaches the caller through the
|
|
1712
|
+
// messageSent notification and the job result, not through a second progress write
|
|
1713
|
+
try {
|
|
1714
|
+
await submitJobEntry.updateProgress({
|
|
1715
|
+
status: 'smtp-completed',
|
|
1716
|
+
messageId,
|
|
1717
|
+
originalMessageId: messageId
|
|
1718
|
+
});
|
|
1719
|
+
} catch (err) {
|
|
1720
|
+
this.logger.warn({ msg: 'Failed to update submit job progress', queueId, messageId, err });
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1712
1723
|
if (data.draft && !data.draft.draftId) {
|
|
1713
1724
|
// The draft resource could not be resolved at queue time, so the draft was sent as
|
|
1714
1725
|
// a raw copy - remove the original draft message (the Gmail API can only move it
|
|
@@ -1723,38 +1734,32 @@ class GmailClient extends BaseClient {
|
|
|
1723
1734
|
}
|
|
1724
1735
|
*/
|
|
1725
1736
|
|
|
1726
|
-
|
|
1737
|
+
// Gmail may rewrite the Message-ID, so the sent copy is read back for the real value.
|
|
1738
|
+
// Best effort: the message is already sent, a failed read only costs the rewritten id
|
|
1739
|
+
let gmailMessageId = messageId;
|
|
1727
1740
|
if (submitInfo?.id) {
|
|
1728
1741
|
// Detect send-only mode using centralized scope checker
|
|
1729
1742
|
const scopes = accountData.oauth2?.accessToken?.scope || accountData.oauth2?.scope || [];
|
|
1730
1743
|
const { hasSendScope, hasReadScope } = checkAccountScopes('gmail', scopes);
|
|
1731
1744
|
const isSendOnly = hasSendScope && !hasReadScope;
|
|
1732
1745
|
|
|
1746
|
+
// Send-only accounts cannot read messages back, they keep the original messageId
|
|
1733
1747
|
if (!isSendOnly) {
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1748
|
+
try {
|
|
1749
|
+
let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${submitInfo.id}`, 'get', {
|
|
1750
|
+
format: 'metadata',
|
|
1751
|
+
metadataHeaders: 'message-id'
|
|
1752
|
+
});
|
|
1753
|
+
let messageIdHeader = messageEntry?.payload?.headers?.find(h => /^Message-ID$/i.test(h.name));
|
|
1754
|
+
if (messageIdHeader?.value) {
|
|
1755
|
+
gmailMessageId = messageIdHeader.value;
|
|
1756
|
+
}
|
|
1757
|
+
} catch (err) {
|
|
1758
|
+
this.logger.warn({ msg: 'Failed to read the Message-ID of a sent message', queueId, messageId, gmailId: submitInfo.id, err });
|
|
1759
|
+
}
|
|
1744
1760
|
}
|
|
1745
1761
|
}
|
|
1746
1762
|
|
|
1747
|
-
try {
|
|
1748
|
-
// try to update job progress
|
|
1749
|
-
await submitJobEntry.updateProgress({
|
|
1750
|
-
status: 'smtp-completed',
|
|
1751
|
-
messageId: gmailMessageId,
|
|
1752
|
-
originalMessageId: messageId
|
|
1753
|
-
});
|
|
1754
|
-
} catch (err) {
|
|
1755
|
-
// ignore
|
|
1756
|
-
}
|
|
1757
|
-
|
|
1758
1763
|
// Send success notification
|
|
1759
1764
|
await this.notify(false, EMAIL_SENT_NOTIFY, {
|
|
1760
1765
|
messageId: gmailMessageId,
|
|
@@ -2119,19 +2124,8 @@ class GmailClient extends BaseClient {
|
|
|
2119
2124
|
timeSinceNotification
|
|
2120
2125
|
});
|
|
2121
2126
|
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
if (historyId) {
|
|
2125
|
-
// Trigger sync to check for any missed changes
|
|
2126
|
-
this.triggerSync(Number(historyId), Number(historyId));
|
|
2127
|
-
}
|
|
2128
|
-
} catch (err) {
|
|
2129
|
-
this.logger.error({
|
|
2130
|
-
msg: 'Failed to trigger fallback sync',
|
|
2131
|
-
account: this.account,
|
|
2132
|
-
err
|
|
2133
|
-
});
|
|
2134
|
-
}
|
|
2127
|
+
// Trigger sync to check for any missed changes
|
|
2128
|
+
this.triggerSyncFromCursor();
|
|
2135
2129
|
}
|
|
2136
2130
|
|
|
2137
2131
|
// Restart the timer
|
|
@@ -2475,23 +2469,25 @@ class GmailClient extends BaseClient {
|
|
|
2475
2469
|
}
|
|
2476
2470
|
encodedTextSize[type] += node.body.size;
|
|
2477
2471
|
|
|
2478
|
-
// Track part IDs and optionally extract content
|
|
2472
|
+
// Track part IDs and optionally extract content. A zero-size part carries
|
|
2473
|
+
// no body.data at all, so only parts with content are decoded (as getText does)
|
|
2474
|
+
const hasData = typeof node.body.data === 'string';
|
|
2479
2475
|
switch (type) {
|
|
2480
2476
|
case 'plain':
|
|
2481
2477
|
textParts[0].push(node.partId);
|
|
2482
|
-
if ([type, '*'].includes(options.textType)) {
|
|
2478
|
+
if (hasData && [type, '*'].includes(options.textType)) {
|
|
2483
2479
|
textContents[0].push(Buffer.from(node.body.data, 'base64'));
|
|
2484
2480
|
}
|
|
2485
2481
|
break;
|
|
2486
2482
|
case 'html':
|
|
2487
2483
|
textParts[1].push(node.partId);
|
|
2488
|
-
if ([type, '*'].includes(options.textType)) {
|
|
2484
|
+
if (hasData && [type, '*'].includes(options.textType)) {
|
|
2489
2485
|
textContents[1].push(Buffer.from(node.body.data, 'base64'));
|
|
2490
2486
|
}
|
|
2491
2487
|
break;
|
|
2492
2488
|
default:
|
|
2493
2489
|
textParts[2].push(node.partId);
|
|
2494
|
-
if (['*'].includes(options.textType)) {
|
|
2490
|
+
if (hasData && ['*'].includes(options.textType)) {
|
|
2495
2491
|
textContents[0].push(Buffer.from(node.body.data, 'base64'));
|
|
2496
2492
|
}
|
|
2497
2493
|
break;
|
|
@@ -2946,17 +2942,15 @@ class GmailClient extends BaseClient {
|
|
|
2946
2942
|
})
|
|
2947
2943
|
.finally(() => {
|
|
2948
2944
|
this.processingHistory = false;
|
|
2945
|
+
this.scheduleDeferredRetryTimer();
|
|
2949
2946
|
// Process any queued sync notifications
|
|
2950
2947
|
if (this.pendingHistoryId && this.pendingHistoryId > processedHistoryId) {
|
|
2951
2948
|
const pending = this.pendingHistoryId;
|
|
2952
2949
|
this.pendingHistoryId = null;
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
toHistoryId: pending
|
|
2958
|
-
});
|
|
2959
|
-
this.triggerSync(processedHistoryId, pending);
|
|
2950
|
+
// From the stored cursor, not from where the finished run was headed: a run that
|
|
2951
|
+
// failed partway left the cursor behind that, and the entries in between would
|
|
2952
|
+
// never be fetched
|
|
2953
|
+
this.triggerSyncFromCursor(pending);
|
|
2960
2954
|
} else {
|
|
2961
2955
|
this.pendingHistoryId = null;
|
|
2962
2956
|
}
|
|
@@ -2967,8 +2961,26 @@ class GmailClient extends BaseClient {
|
|
|
2967
2961
|
* Processes a single history entry for changes
|
|
2968
2962
|
* @param {Object} historyEntry - Gmail history entry
|
|
2969
2963
|
*/
|
|
2970
|
-
async processHistoryEntry(historyEntry) {
|
|
2971
|
-
|
|
2964
|
+
async processHistoryEntry(historyEntry, context) {
|
|
2965
|
+
const historyContext = context || (await this.getHistoryContext());
|
|
2966
|
+
const { newMessageOptions } = historyContext;
|
|
2967
|
+
|
|
2968
|
+
// The label list is cached for an hour, so a label created since is unknown to it and its
|
|
2969
|
+
// changes were silently dropped. An unknown id refreshes the list once per run; an id that
|
|
2970
|
+
// is still unknown after that is reported as is rather than dropped
|
|
2971
|
+
const resolveLabelName = async labelId => {
|
|
2972
|
+
let label = historyContext.labels?.find(entry => entry.id === labelId);
|
|
2973
|
+
if (!label && !historyContext.labelsRefreshed) {
|
|
2974
|
+
historyContext.labelsRefreshed = true;
|
|
2975
|
+
try {
|
|
2976
|
+
historyContext.labels = await this.getLabels(true);
|
|
2977
|
+
} catch (err) {
|
|
2978
|
+
this.logger.warn({ msg: 'Failed to refresh the label list', account: this.account, err });
|
|
2979
|
+
}
|
|
2980
|
+
label = historyContext.labels?.find(entry => entry.id === labelId);
|
|
2981
|
+
}
|
|
2982
|
+
return label ? label.name : labelId;
|
|
2983
|
+
};
|
|
2972
2984
|
|
|
2973
2985
|
/**
|
|
2974
2986
|
* Processes label changes and sends update notifications
|
|
@@ -3018,10 +3030,7 @@ class GmailClient extends BaseClient {
|
|
|
3018
3030
|
// ignore category labels
|
|
3019
3031
|
} else {
|
|
3020
3032
|
// resolve Path for the label
|
|
3021
|
-
|
|
3022
|
-
if (label) {
|
|
3023
|
-
changes.labels[addedProp].push(label.name);
|
|
3024
|
-
}
|
|
3033
|
+
changes.labels[addedProp].push(await resolveLabelName(labelId));
|
|
3025
3034
|
}
|
|
3026
3035
|
break;
|
|
3027
3036
|
}
|
|
@@ -3081,8 +3090,8 @@ class GmailClient extends BaseClient {
|
|
|
3081
3090
|
await this.notify(this, MESSAGE_DELETED_NOTIFY, messageUpdate);
|
|
3082
3091
|
}
|
|
3083
3092
|
|
|
3084
|
-
// Process new messages
|
|
3085
|
-
|
|
3093
|
+
// Process new messages. Each is fetched on its own, so one that fails is retried on its own
|
|
3094
|
+
// and does not take the rest of the entry with it
|
|
3086
3095
|
for (let entry of historyEntry?.messagesAdded || []) {
|
|
3087
3096
|
if (!entry?.message) {
|
|
3088
3097
|
continue;
|
|
@@ -3097,13 +3106,62 @@ class GmailClient extends BaseClient {
|
|
|
3097
3106
|
category: messageCategory
|
|
3098
3107
|
};
|
|
3099
3108
|
|
|
3100
|
-
|
|
3109
|
+
await this.processAddedMessage(eventEntry, newMessageOptions);
|
|
3110
|
+
}
|
|
3111
|
+
}
|
|
3112
|
+
|
|
3113
|
+
/**
|
|
3114
|
+
* Fetches a message reported as added and announces it, deferring it for a retry on failure
|
|
3115
|
+
* @param {Object} eventEntry - Message event data
|
|
3116
|
+
* @param {Object} options - Message fetch options
|
|
3117
|
+
* @param {Object} [event] - The deferred change being retried, when this is a retry
|
|
3118
|
+
*/
|
|
3119
|
+
async processAddedMessage(eventEntry, options, event) {
|
|
3120
|
+
try {
|
|
3121
|
+
const messageData = await this.prepareNewMessage(eventEntry, options);
|
|
3101
3122
|
if (messageData) {
|
|
3102
|
-
await this.processNew(messageData,
|
|
3123
|
+
await this.processNew(messageData, options);
|
|
3103
3124
|
}
|
|
3125
|
+
} catch (err) {
|
|
3126
|
+
await this.deferFailedChangeEvent(event || { type: 'created', message: eventEntry }, err);
|
|
3104
3127
|
}
|
|
3105
3128
|
}
|
|
3106
3129
|
|
|
3130
|
+
/**
|
|
3131
|
+
* What every history entry of a run needs from the API and the settings, resolved once per
|
|
3132
|
+
* run. Fetched before any entry is processed, so a failure here ends the run with the cursor
|
|
3133
|
+
* where it was and the next run fetches the same entries again: deferring each entry instead
|
|
3134
|
+
* would replay its label changes hours later, over whatever changed since
|
|
3135
|
+
* @returns {Promise<{labels: Object[], newMessageOptions: Object}>}
|
|
3136
|
+
*/
|
|
3137
|
+
async getHistoryContext() {
|
|
3138
|
+
const [labels, newMessageOptions] = await Promise.all([this.getLabels(), this.getMessageFetchOptions()]);
|
|
3139
|
+
return { labels, newMessageOptions };
|
|
3140
|
+
}
|
|
3141
|
+
|
|
3142
|
+
retryDeferredEvents() {
|
|
3143
|
+
// the same run a fallback poll makes, which picks up the due changes
|
|
3144
|
+
this.triggerSyncFromCursor();
|
|
3145
|
+
}
|
|
3146
|
+
|
|
3147
|
+
/**
|
|
3148
|
+
* Starts a history run from the stored cursor
|
|
3149
|
+
* @param {number} [updatedHistoryId] - Where the run is headed, the cursor itself by default
|
|
3150
|
+
*/
|
|
3151
|
+
triggerSyncFromCursor(updatedHistoryId) {
|
|
3152
|
+
this.redis
|
|
3153
|
+
.hget(this.getAccountKey(), 'googleHistoryId')
|
|
3154
|
+
.then(historyId => {
|
|
3155
|
+
if (historyId && !this.closed) {
|
|
3156
|
+
this.logger.debug({ msg: 'Processing history from the stored cursor', account: this.account, historyId, updatedHistoryId });
|
|
3157
|
+
this.triggerSync(Number(historyId), Math.max(Number(historyId), updatedHistoryId || 0));
|
|
3158
|
+
}
|
|
3159
|
+
})
|
|
3160
|
+
.catch(err => {
|
|
3161
|
+
this.logger.error({ msg: 'Failed to read the history cursor', account: this.account, err });
|
|
3162
|
+
});
|
|
3163
|
+
}
|
|
3164
|
+
|
|
3107
3165
|
/**
|
|
3108
3166
|
* Processes Gmail history changes since last sync
|
|
3109
3167
|
* @param {number} currentHistoryId - Starting history ID
|
|
@@ -3113,6 +3171,18 @@ class GmailClient extends BaseClient {
|
|
|
3113
3171
|
let newestHistoryId = currentHistoryId;
|
|
3114
3172
|
let lastHistoryId = currentHistoryId;
|
|
3115
3173
|
|
|
3174
|
+
// Resolved on first use, and once for the whole run, a failure included
|
|
3175
|
+
let contextPromise;
|
|
3176
|
+
const getContext = () => (contextPromise = contextPromise || this.getHistoryContext());
|
|
3177
|
+
|
|
3178
|
+
// Messages deferred for a retry, every one of them a message reported as added. A context
|
|
3179
|
+
// failure is thrown, and processDueDeferredEvents() defers the message for it
|
|
3180
|
+
try {
|
|
3181
|
+
await this.processDueDeferredEvents(async event => this.processAddedMessage(event.message, (await getContext()).newMessageOptions, event));
|
|
3182
|
+
} catch (err) {
|
|
3183
|
+
this.logger.error({ msg: 'Failed to process deferred mailbox changes', account: this.account, err });
|
|
3184
|
+
}
|
|
3185
|
+
|
|
3116
3186
|
// The history cursor only advances after an entry is processed, so an
|
|
3117
3187
|
// entry that kills the worker (OOM, heartbeat restart) is refetched by
|
|
3118
3188
|
// the restarted worker and would loop forever. The in-flight marker
|
|
@@ -3166,8 +3236,17 @@ class GmailClient extends BaseClient {
|
|
|
3166
3236
|
type: 'historyIdExpired',
|
|
3167
3237
|
message: 'Some email changes may have been missed due to expired history ID'
|
|
3168
3238
|
});
|
|
3169
|
-
// Set to newest known value
|
|
3239
|
+
// Set to newest known value. A fallback poll or a retry is headed nowhere past
|
|
3240
|
+
// the expired cursor, so ask for the current one, or every run would 404 again
|
|
3170
3241
|
newestHistoryId = updatedHistoryId;
|
|
3242
|
+
if (!(updatedHistoryId > currentHistoryId)) {
|
|
3243
|
+
try {
|
|
3244
|
+
const profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
|
|
3245
|
+
newestHistoryId = Number(profileRes?.historyId) || newestHistoryId;
|
|
3246
|
+
} catch (profileErr) {
|
|
3247
|
+
this.logger.warn({ msg: 'Failed to fetch the current history ID', account: this.account, err: profileErr });
|
|
3248
|
+
}
|
|
3249
|
+
}
|
|
3171
3250
|
return;
|
|
3172
3251
|
}
|
|
3173
3252
|
default:
|
|
@@ -3175,6 +3254,10 @@ class GmailClient extends BaseClient {
|
|
|
3175
3254
|
}
|
|
3176
3255
|
}
|
|
3177
3256
|
|
|
3257
|
+
// Before any entry is marked in flight: a failure here ends the run with the cursor
|
|
3258
|
+
// where it was, see getHistoryContext()
|
|
3259
|
+
const context = historyRes?.history?.length ? await getContext() : null;
|
|
3260
|
+
|
|
3178
3261
|
// Process each history entry
|
|
3179
3262
|
for (let entry of historyRes?.history || []) {
|
|
3180
3263
|
let historyEntryId = Number(entry?.id) || null;
|
|
@@ -3187,7 +3270,7 @@ class GmailClient extends BaseClient {
|
|
|
3187
3270
|
// whose events were lost so they can be recovered manually
|
|
3188
3271
|
let messageIds = (entry?.messagesAdded || []).map(added => added?.message?.id).filter(id => id);
|
|
3189
3272
|
this.logger.error({
|
|
3190
|
-
msg: 'Skipping history entry that repeatedly killed the worker',
|
|
3273
|
+
msg: 'Skipping history entry that repeatedly failed or killed the worker',
|
|
3191
3274
|
account: this.account,
|
|
3192
3275
|
entryId: entry?.id,
|
|
3193
3276
|
attempts,
|
|
@@ -3195,7 +3278,7 @@ class GmailClient extends BaseClient {
|
|
|
3195
3278
|
});
|
|
3196
3279
|
await emitChangeEvent(this.logger, this.account, 'syncWarning', {
|
|
3197
3280
|
type: 'historyEntrySkipped',
|
|
3198
|
-
message: 'Processing a history entry repeatedly killed the sync worker, its changes were skipped',
|
|
3281
|
+
message: 'Processing a history entry repeatedly failed or killed the sync worker, its changes were skipped',
|
|
3199
3282
|
historyId: entry?.id,
|
|
3200
3283
|
messageIds
|
|
3201
3284
|
});
|
|
@@ -3210,7 +3293,8 @@ class GmailClient extends BaseClient {
|
|
|
3210
3293
|
}
|
|
3211
3294
|
|
|
3212
3295
|
try {
|
|
3213
|
-
|
|
3296
|
+
// A message in the entry that fails to fetch is deferred on its own inside
|
|
3297
|
+
await this.processHistoryEntry(entry, context);
|
|
3214
3298
|
await advanceHistoryCursor(historyEntryId);
|
|
3215
3299
|
} catch (err) {
|
|
3216
3300
|
this.logger.error({
|
|
@@ -3223,6 +3307,11 @@ class GmailClient extends BaseClient {
|
|
|
3223
3307
|
labelsRemoved: entry?.labelsRemoved?.length,
|
|
3224
3308
|
err
|
|
3225
3309
|
});
|
|
3310
|
+
// End the run here, with the cursor on the last entry that went through: the
|
|
3311
|
+
// next run starts from this entry again. Moving past it lost its label changes
|
|
3312
|
+
// and deletions without a trace. The in-flight marker stays, so an entry that
|
|
3313
|
+
// keeps failing is skipped with a syncWarning after the attempt limit above
|
|
3314
|
+
throw err;
|
|
3226
3315
|
}
|
|
3227
3316
|
}
|
|
3228
3317
|
|
|
@@ -3263,9 +3352,6 @@ class GmailClient extends BaseClient {
|
|
|
3263
3352
|
options.headers = 'headers' in options ? options.headers : false;
|
|
3264
3353
|
}
|
|
3265
3354
|
|
|
3266
|
-
// The sync path never reads the bounces field
|
|
3267
|
-
options.skipBounces = true;
|
|
3268
|
-
|
|
3269
3355
|
let messageData;
|
|
3270
3356
|
try {
|
|
3271
3357
|
messageData = await this.getMessage(eventEntry.id, options);
|