emailengine-app 2.81.2 → 2.82.1
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 +33 -10
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +71 -0
- package/DOCKER_DEPLOYMENT.md +13 -12
- package/Dockerfile +2 -0
- package/bin/emailengine.js +105 -25
- 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/expected-identity.js +1 -1
- package/lib/account-assignment.js +138 -1
- package/lib/account.js +289 -869
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-binding.js +58 -0
- package/lib/api-routes/account-routes.js +65 -37
- package/lib/api-routes/behavior-notes.js +4 -0
- 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 +15 -16
- 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 +50 -238
- 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 +3 -3
- 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 +20 -21
- 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 +28 -6
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +33 -6
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +305 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +54 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +77 -30
- package/lib/delivery-error.js +70 -2
- 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 +383 -536
- package/lib/email-client/credential-errors.js +21 -5
- 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 +77 -51
- package/lib/email-client/imap/mailbox.js +158 -324
- 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 +190 -65
- package/lib/email-client/message-builder.js +50 -25
- 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 +389 -463
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +6 -3
- package/lib/export.js +141 -41
- package/lib/gateway.js +25 -6
- package/lib/get-raw-email.js +26 -44
- package/lib/get-secret.js +1 -21
- 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 +108 -36
- package/lib/message-port-stream.js +64 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +64 -32
- package/lib/oauth/mail-ru.js +24 -17
- package/lib/oauth/outlook.js +53 -40
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +39 -8
- package/lib/oauth/scope-list.js +55 -0
- package/lib/oauth/token-fetch.js +47 -0
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +154 -90
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- package/lib/outbox.js +2 -7
- 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/queue-retention.js +4 -2
- package/lib/rate-limit.js +54 -15
- package/lib/read-env-value.js +33 -2
- 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 +180 -253
- 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/token-audit-log.js +3 -2
- package/lib/tools.js +114 -53
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +67 -70
- 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 +83 -228
- package/lib/ui-routes/route-helpers.js +63 -67
- package/lib/ui-routes/special-use-paths.js +33 -0
- 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 +11 -17
- 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 +338 -292
- package/setup-production.sh +16 -7
- 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 +349 -1740
- package/translations/messages.pot +129 -111
- package/views/account-workspace-error.hbs +30 -0
- package/views/accounts/account.hbs +9 -4
- package/views/accounts/browse.hbs +10 -4
- package/views/accounts/edit.hbs +11 -2
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- package/views/internals/index.hbs +1 -1
- 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/gmail_api_scopes.hbs +16 -0
- package/views/partials/oauth_form.hbs +67 -94
- package/views/partials/oauth_pubsub_app_select.hbs +43 -0
- package/views/partials/scope_info.hbs +14 -23
- 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 +82 -47
- package/workers/export.js +55 -60
- package/workers/imap.js +132 -49
- package/workers/submit.js +5 -6
- 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/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/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
package/lib/bounce-detect.js
CHANGED
|
@@ -22,10 +22,10 @@
|
|
|
22
22
|
* @requires mailparser - For parsing email messages
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
-
const { decodeHeaders } = require('./utils/decode-headers');
|
|
25
|
+
const { decodeHeaders, capHeaderBlock, MAX_HEADER_BLOCK_SIZE } = require('./utils/decode-headers');
|
|
26
26
|
const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
|
|
27
27
|
const { pushHeaderValue } = require('./utils/header-map');
|
|
28
|
-
const
|
|
28
|
+
const { parseMessage } = require('./parse-message');
|
|
29
29
|
const { toCamelCase } = require('./utils/to-camel-case');
|
|
30
30
|
|
|
31
31
|
// Wording of a notice that reports a delay rather than a failure. Sendmail and qmail-style MTAs
|
|
@@ -71,6 +71,11 @@ function splitAddressType(value) {
|
|
|
71
71
|
return { label: value.substring(0, splitPos).trim(), value: value.substring(splitPos + 1).trim() };
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
// Options for every parseMessage() call here. None of them reads the HTML, and without
|
|
75
|
+
// keepCidLinks mailparser inlines every cid: image as a data URL once per reference, which a small
|
|
76
|
+
// message can grow past the maximum string length, outside any promise.
|
|
77
|
+
const PARSER_OPTIONS = { keepDeliveryStatus: true, skipTextToHtml: true, skipImageLinks: true, keepCidLinks: true };
|
|
78
|
+
|
|
74
79
|
/**
|
|
75
80
|
* Splits the body of a message/delivery-status part into its header blocks
|
|
76
81
|
*
|
|
@@ -84,8 +89,7 @@ function splitAddressType(value) {
|
|
|
84
89
|
*/
|
|
85
90
|
function decodeDeliveryStatusBlocks(content) {
|
|
86
91
|
return (
|
|
87
|
-
(content
|
|
88
|
-
.toString()
|
|
92
|
+
capHeaderBlock(content)
|
|
89
93
|
.replace(/\r\n|\r/g, '\n')
|
|
90
94
|
.split(/\n{2,}/)
|
|
91
95
|
.map(block => decodeHeaders(block))
|
|
@@ -333,7 +337,7 @@ async function bounceDetect(sourceStream) {
|
|
|
333
337
|
parsed = sourceStream.parsed;
|
|
334
338
|
} else {
|
|
335
339
|
// Parse the email, keeping delivery status attachments intact
|
|
336
|
-
parsed = await
|
|
340
|
+
parsed = await parseMessage(sourceStream, PARSER_OPTIONS);
|
|
337
341
|
}
|
|
338
342
|
|
|
339
343
|
let result = {};
|
|
@@ -399,7 +403,7 @@ async function bounceDetect(sourceStream) {
|
|
|
399
403
|
|
|
400
404
|
// Process RFC822 headers attachment (contains headers of the original message)
|
|
401
405
|
if (messageHeaders) {
|
|
402
|
-
parsedMessageHeaders = decodeHeaders(
|
|
406
|
+
parsedMessageHeaders = decodeHeaders(messageHeaders.content);
|
|
403
407
|
result = Object.assign(result, parseDeliveryHeaders(parsedMessageHeaders));
|
|
404
408
|
}
|
|
405
409
|
|
|
@@ -407,7 +411,7 @@ async function bounceDetect(sourceStream) {
|
|
|
407
411
|
if (originalMessage) {
|
|
408
412
|
try {
|
|
409
413
|
// Parse the original message to extract its headers
|
|
410
|
-
let parsedOriginal = await
|
|
414
|
+
let parsedOriginal = await parseMessage(originalMessage.content, PARSER_OPTIONS);
|
|
411
415
|
if (parsedOriginal) {
|
|
412
416
|
// Build headers object from headerLines for consistent access
|
|
413
417
|
let headers = {};
|
|
@@ -442,7 +446,7 @@ async function bounceDetect(sourceStream) {
|
|
|
442
446
|
if (!messageHeaders) {
|
|
443
447
|
messageHeaders = originalAttachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822-headers');
|
|
444
448
|
if (messageHeaders) {
|
|
445
|
-
let headerEntries = decodeHeaders(
|
|
449
|
+
let headerEntries = decodeHeaders(messageHeaders.content);
|
|
446
450
|
result = Object.assign(result, parseDeliveryHeaders(headerEntries));
|
|
447
451
|
}
|
|
448
452
|
}
|
|
@@ -490,11 +494,11 @@ async function bounceDetect(sourceStream) {
|
|
|
490
494
|
|
|
491
495
|
if (isZohoBounce) {
|
|
492
496
|
try {
|
|
493
|
-
let parsedOriginal = await
|
|
497
|
+
let parsedOriginal = await parseMessage(zohoOriginalMessage.content, PARSER_OPTIONS);
|
|
494
498
|
// Zoho sometimes includes headers in the text body with no actual header structure
|
|
495
499
|
if (parsedOriginal && parsedOriginal.text && (!parsedOriginal.headerLines || !parsedOriginal.headerLines.filter(h => h.key).length)) {
|
|
496
500
|
// Remove leading spaces that indicate header continuation
|
|
497
|
-
let headerContent = (parsedOriginal.text
|
|
501
|
+
let headerContent = capHeaderBlock(parsedOriginal.text).replace(/^ (?=[^ ])/gm, '');
|
|
498
502
|
|
|
499
503
|
// Additional validation: content should look like email headers
|
|
500
504
|
// Check for common header patterns (Received:, Message-ID:, Date:, From:)
|
|
@@ -544,7 +548,9 @@ async function bounceDetect(sourceStream) {
|
|
|
544
548
|
* <user@example.com>: host mx.example.com[1.2.3.4] said:
|
|
545
549
|
* 550 5.1.1 No such user (in reply to RCPT TO command)
|
|
546
550
|
*/
|
|
547
|
-
|
|
551
|
+
// The address classes exclude '<' and whitespace and are bounded, so a run of '<' or of
|
|
552
|
+
// unterminated addresses can not make every start position scan to the end of the text
|
|
553
|
+
let m = text.match(/<([^<>@\s]{1,256}@[^<>\s]{1,256})>:\s*host\s+([a-z0-9._-]+)\s*(?:\[([^\]]+)\])?\s+said:/im);
|
|
548
554
|
if (m) {
|
|
549
555
|
// Find the end of the error message (double newline or end of string)
|
|
550
556
|
let end = text.substr(m.index + m[0].length).match(/\r?\n\r?\n|$/);
|
|
@@ -615,7 +621,9 @@ async function bounceDetect(sourceStream) {
|
|
|
615
621
|
*
|
|
616
622
|
* 550-5.7.1 [1.2.3.4 11] Our system has detected that this message is not RFC 5322 compliant...
|
|
617
623
|
*/
|
|
618
|
-
|
|
624
|
+
// [ \t]* rather than \s*: with the m flag every line start is a candidate, and \s* let each
|
|
625
|
+
// of them run across all the following blank lines (quadratic on a run of newlines)
|
|
626
|
+
let m = text.match(/^[ \t]*[45]\d{2}[\s-](\d+\.\d+\.\d+)[\s-]/im);
|
|
619
627
|
if (m) {
|
|
620
628
|
let end = text.substr(m.index + m[0].length).match(/\r?\n\r?\n|$/);
|
|
621
629
|
if (end) {
|
|
@@ -650,7 +658,7 @@ async function bounceDetect(sourceStream) {
|
|
|
650
658
|
* 550: 5.1.1 <user@example.com>: Recipient address rejected: User unknown in relay recipient table
|
|
651
659
|
*/
|
|
652
660
|
// Use bounded quantifier to prevent ReDoS
|
|
653
|
-
let m = text.match(/\n<([
|
|
661
|
+
let m = text.match(/\n<([^<>@\s]{1,256}@[^<>\s]{1,256})>:[\s\r\n]{1,100}/);
|
|
654
662
|
if (m) {
|
|
655
663
|
result.recipient = result.recipient || m[1];
|
|
656
664
|
|
|
@@ -796,7 +804,7 @@ async function bounceDetect(sourceStream) {
|
|
|
796
804
|
// Check if this block starts with or contains our recipient email
|
|
797
805
|
if (block.includes(result.recipient)) {
|
|
798
806
|
// Look for "host ... :" pattern followed by error message
|
|
799
|
-
const hostMatch = block.match(/\shost\s+[^\n:]
|
|
807
|
+
const hostMatch = block.match(/\shost\s+[^\n:]{1,256}:\s*(.+)/s);
|
|
800
808
|
if (hostMatch && hostMatch[1]) {
|
|
801
809
|
const message = hostMatch[1].replace(/\s+/g, ' ').trim();
|
|
802
810
|
if (message) {
|
|
@@ -896,7 +904,8 @@ async function bounceDetect(sourceStream) {
|
|
|
896
904
|
* Message could not be delivered to mobile.
|
|
897
905
|
* Error: No valid recipients for this MM
|
|
898
906
|
*/
|
|
899
|
-
|
|
907
|
+
// Bounded, so a line of repeated "Error:" does not rescan the line from every occurrence
|
|
908
|
+
let m = text.match(/(?:Message could not be delivered|Error:[^\n]{0,256}?(?:Invalid|No valid|not taken)[^\n]{0,512})/i);
|
|
900
909
|
if (m) {
|
|
901
910
|
result.action = result.action || 'failed';
|
|
902
911
|
result.response = result.response || {};
|
|
@@ -1014,4 +1023,4 @@ function applyDeliveryReport(parsed, messageInfo, logger) {
|
|
|
1014
1023
|
return true;
|
|
1015
1024
|
}
|
|
1016
1025
|
|
|
1017
|
-
module.exports = { bounceDetect, decodeDeliveryStatus, parseDeliveryReport, applyDeliveryReport };
|
|
1026
|
+
module.exports = { bounceDetect, decodeDeliveryStatus, parseDeliveryReport, applyDeliveryReport, PARSER_OPTIONS, MAX_HEADER_BLOCK_SIZE };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The calendar event EmailEngine reports from an iCalendar attachment (text/calendar or
|
|
4
|
+
// application/ics). Shared by the IMAP sync (lib/email-client/imap/mailbox.js) and the API
|
|
5
|
+
// clients (lib/email-client/base-client.js), which used to carry two copies of this parse.
|
|
6
|
+
//
|
|
7
|
+
// A DTSTART or DTEND carrying a TZID is resolved against the VTIMEZONE embedded in the same
|
|
8
|
+
// VCALENDAR (ical.js 2.x; 1.x read such a value as floating, in the server's own zone), so the
|
|
9
|
+
// ISO timestamps are the instant the invite means wherever EmailEngine happens to run.
|
|
10
|
+
|
|
11
|
+
const ical = require('ical.js');
|
|
12
|
+
|
|
13
|
+
const CALENDAR_CONTENT_TYPES = ['text/calendar', 'application/ics'];
|
|
14
|
+
|
|
15
|
+
// text/calendar before application/ics: when an invite arrives as both, the first attachment
|
|
16
|
+
// seen for an event UID is the one reported, and text/calendar is the part the sending client
|
|
17
|
+
// marked as the calendar payload
|
|
18
|
+
function sortCalendarAttachments(a, b) {
|
|
19
|
+
if (a.contentType !== b.contentType) {
|
|
20
|
+
if (a.contentType === 'text/calendar') {
|
|
21
|
+
return -1;
|
|
22
|
+
}
|
|
23
|
+
if (b.contentType === 'text/calendar') {
|
|
24
|
+
return 1;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return a.contentType.localeCompare(b.contentType);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Reads the first VEVENT of an iCalendar document
|
|
32
|
+
*
|
|
33
|
+
* @param {string|Buffer} content - iCalendar text
|
|
34
|
+
* @returns {object|null} The event fields, or null when the document holds no VEVENT with a UID
|
|
35
|
+
* @throws When the content is not parseable iCalendar data
|
|
36
|
+
*/
|
|
37
|
+
function parseCalendarEvent(content) {
|
|
38
|
+
const comp = new ical.Component(ical.parse(content.toString()));
|
|
39
|
+
|
|
40
|
+
const vevent = comp.getFirstSubcomponent('vevent');
|
|
41
|
+
if (!vevent) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// REQUEST, CANCEL, REPLY and so on
|
|
46
|
+
const methodProp = comp.getFirstProperty('method');
|
|
47
|
+
|
|
48
|
+
const event = new ical.Event(vevent);
|
|
49
|
+
if (!event.uid) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let timezone;
|
|
54
|
+
const vtz = comp.getFirstSubcomponent('vtimezone');
|
|
55
|
+
if (vtz) {
|
|
56
|
+
const tz = new ical.Timezone(vtz);
|
|
57
|
+
timezone = tz && tz.tzid;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
let startDate = event.startDate && event.startDate.toJSDate();
|
|
61
|
+
// Without a DTEND the end is a copy of the start, and with neither the getter throws. A
|
|
62
|
+
// cancellation may carry no DTSTART at all (RFC 5546 3.2.5), so the end is only read when
|
|
63
|
+
// there is something to answer it from
|
|
64
|
+
let endDate = startDate || vevent.hasProperty('dtend') ? event.endDate && event.endDate.toJSDate() : null;
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
eventId: event.uid,
|
|
68
|
+
method: methodProp ? methodProp.getFirstValue() : null,
|
|
69
|
+
summary: event.summary || null,
|
|
70
|
+
description: event.description || null,
|
|
71
|
+
timezone: timezone || null,
|
|
72
|
+
startDate: startDate ? startDate.toISOString() : null,
|
|
73
|
+
endDate: endDate ? endDate.toISOString() : null,
|
|
74
|
+
organizer: event.organizer && typeof event.organizer === 'string' ? event.organizer : null
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = { CALENDAR_CONTENT_TYPES, sortCalendarAttachments, parseCalendarEvent };
|
package/lib/consts.js
CHANGED
|
@@ -130,6 +130,24 @@ module.exports = {
|
|
|
130
130
|
DEFAULT_MAX_ATTACHMENT_SIZE: 5 * 1024 * 1024,
|
|
131
131
|
DEFAULT_MAX_SMTP_MESSAGE_SIZE: 25 * 1024 * 1024, // 25MB
|
|
132
132
|
|
|
133
|
+
// The settings a built-in listener reads only when its worker starts (enabled, port, host, the
|
|
134
|
+
// TLS switch) and the command that restarts that one worker. One table for the API settings
|
|
135
|
+
// route and the admin listener pages, so a write from either restarts exactly the listener
|
|
136
|
+
// that changed; the API route used to leave a listener on its old address until something
|
|
137
|
+
// else restarted it.
|
|
138
|
+
LISTENER_RELOADS: {
|
|
139
|
+
smtp: {
|
|
140
|
+
keys: ['smtpServerEnabled', 'smtpServerPort', 'smtpServerHost', 'smtpServerTLSEnabled'],
|
|
141
|
+
cmd: 'smtpReload',
|
|
142
|
+
action: 'request_reload_smtp'
|
|
143
|
+
},
|
|
144
|
+
imapProxy: {
|
|
145
|
+
keys: ['imapProxyServerEnabled', 'imapProxyServerPort', 'imapProxyServerHost', 'imapProxyServerTLSEnabled'],
|
|
146
|
+
cmd: 'imapProxyReload',
|
|
147
|
+
action: 'request_reload_imap_proxy'
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
|
|
133
151
|
// IF IMAP authentications fail more than provided value, then disable IMAP for the account
|
|
134
152
|
DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME: 3 * 24 * 3600 * 1000, // 3 days
|
|
135
153
|
|
|
@@ -271,11 +289,19 @@ module.exports = {
|
|
|
271
289
|
},
|
|
272
290
|
|
|
273
291
|
URL_FETCH_TIMEOUT: Number((process.env.EENGINE_FETCH_TIMEOUT || '').toString().trim()) || 90 * 1000,
|
|
274
|
-
URL_FETCH_RETRY_MAX: 5,
|
|
275
292
|
|
|
276
293
|
// hard limit for subscript execution (does not include waiting for promises)
|
|
277
294
|
SUBSCRIPT_RUNTIME_TIMEOUT: 30 * 1000,
|
|
278
295
|
|
|
296
|
+
// How long one request to the AI provider may take: the RPC that asks for it gives up after
|
|
297
|
+
// this, and the request in the main thread is aborted at the same time so it does not outlive
|
|
298
|
+
// its caller
|
|
299
|
+
AI_REQUEST_TIMEOUT: 2 * 60 * 1000,
|
|
300
|
+
|
|
301
|
+
// The settings the AI page edits besides the key, in the order the page shows them. The main
|
|
302
|
+
// thread reads the same keys for every request to the provider
|
|
303
|
+
AI_SETTING_KEYS: ['openAiModel', 'openAiAPIUrl', 'openAiPrompt', 'openAiTemperature', 'openAiTopP', 'openAiReasoningEffort', 'openAiMaxTokens'],
|
|
304
|
+
|
|
279
305
|
// how long is an authentication form valid
|
|
280
306
|
MAX_FORM_TTL: 1 * 24 * 3600 * 1000,
|
|
281
307
|
|
|
@@ -332,6 +358,16 @@ module.exports = {
|
|
|
332
358
|
// the path and delimiter after the pick.
|
|
333
359
|
MAILBOX_RESPONSE_FIELDS: ['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'],
|
|
334
360
|
|
|
361
|
+
// The special-use folders an account may override, each stored on the account as
|
|
362
|
+
// `imap.<type>MailPath`. EmailEngine detects these folders from the server's own flags; an
|
|
363
|
+
// override is for a server that flags none of them, or flags the wrong one.
|
|
364
|
+
//
|
|
365
|
+
// One list because four places have to agree on it: the IMAP client turns it into the
|
|
366
|
+
// specialUseHints it passes to LIST, lib/schemas.js declares a field per entry for the account
|
|
367
|
+
// create and update schemas, and the admin edit form offers an input per entry. Only the client
|
|
368
|
+
// and the form used to carry a copy, and the form's had four of the five missing.
|
|
369
|
+
SPECIAL_USE_PATH_TYPES: ['sent', 'drafts', 'junk', 'trash', 'archive'],
|
|
370
|
+
|
|
335
371
|
// nanoseconds
|
|
336
372
|
ALLOWED_REDIS_LATENCY: 5 * 1000000,
|
|
337
373
|
|
|
@@ -340,8 +376,12 @@ module.exports = {
|
|
|
340
376
|
FETCH_RETRY_INTERVAL: 1000,
|
|
341
377
|
FETCH_RETRY_EXPONENTIAL: 2,
|
|
342
378
|
FETCH_RETRY_MAX: 60 * 1000,
|
|
343
|
-
|
|
344
|
-
|
|
379
|
+
// A FETCH is retried while its sync holds the folder's mailbox lock, which blocks IDLE, EXISTS
|
|
380
|
+
// handling and every API command routed to that connection. A server refusing the same FETCH
|
|
381
|
+
// every time (a corrupt message) used to hold the lock for a day; now the pass gives up after a
|
|
382
|
+
// few minutes, releases the lock, and the next resync pass tries again
|
|
383
|
+
FETCH_RETRY_MAX_TIME: 5 * 60 * 1000, // maximum retry duration under the lock
|
|
384
|
+
FETCH_RETRY_MIN_ATTEMPTS: 5, // minimum attempts before time limit applies
|
|
345
385
|
DEFAULT_FETCH_BATCH_SIZE: 1000,
|
|
346
386
|
|
|
347
387
|
// MS Graph webhook subscription settings
|
|
@@ -354,14 +394,18 @@ module.exports = {
|
|
|
354
394
|
OUTLOOK_SUBSCRIPTION_LOCK_TTL: 4 * 60 * 1000, // ms - lock TTL for subscription operations (ioredfour uses ms)
|
|
355
395
|
OUTLOOK_MAX_BATCH_SIZE: 20, // MS Graph batch request limit
|
|
356
396
|
OUTLOOK_MAX_RETRY_ATTEMPTS: 3, // Maximum retry attempts for rate-limited requests
|
|
357
|
-
|
|
358
|
-
|
|
397
|
+
// Backoff for the subscription create/renew retries, which run in the background with no caller
|
|
398
|
+
// waiting on them (API requests use the shared policy in lib/email-client/api-retry.js)
|
|
399
|
+
OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY: 30, // seconds
|
|
400
|
+
OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY: 120, // seconds
|
|
359
401
|
OUTLOOK_CLOCK_SKEW_BUFFER: 60 * 1000, // ms - buffer for clock skew between EmailEngine and MS Graph servers
|
|
360
402
|
// Graph retries an undeliverable change notification for up to 4 hours before dropping it and
|
|
361
403
|
// sending a `missed` lifecycle event, so the lost changes can be that old when recovery runs
|
|
362
404
|
OUTLOOK_MISSED_LOOKBACK: 4 * 60 * 60 * 1000, // ms
|
|
363
405
|
// How long announced new messages are remembered, so a recovery pass does not announce them again
|
|
364
406
|
OUTLOOK_ANNOUNCED_RETENTION: 6 * 60 * 60 * 1000, // ms
|
|
407
|
+
// How far back a manual sync of a Graph account may be asked to look (PUT /v1/account/{account}/sync `since`)
|
|
408
|
+
OUTLOOK_SYNC_MAX_LOOKBACK: 30 * 24 * 60 * 60 * 1000, // ms
|
|
365
409
|
|
|
366
410
|
// Google Pub/Sub subscription defaults
|
|
367
411
|
GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL: '2678400s', // 31 days in seconds (Google's default)
|
|
@@ -385,6 +429,11 @@ module.exports = {
|
|
|
385
429
|
// Error codes meaning "the IMAP connection is gone", as opposed to the command itself failing
|
|
386
430
|
CONNECTION_CLOSING_CODES: new Set(['IMAPConnectionClosing', 'EConnectionClosed', 'NoConnection']),
|
|
387
431
|
|
|
432
|
+
// The last release that shipped the Document Store (Elasticsearch indexing, chat with
|
|
433
|
+
// emails, unified search). Named by the removal warning an instance shows while the
|
|
434
|
+
// `documentStoreEnabled` setting is still on
|
|
435
|
+
LAST_DOCUMENT_STORE_VERSION: '2.81.2',
|
|
436
|
+
|
|
388
437
|
// Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
|
|
389
438
|
// ValidationError carries the full submitted payload in `_original` and the offending value in
|
|
390
439
|
// each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Every ImapFlow client EmailEngine creates is created here, whatever the connection is for (an
|
|
4
|
+
// account's primary and command connections, a subconnection, the verification probes, the IMAP
|
|
5
|
+
// proxy's upstream), so an option every connection needs is set once. test/fips-guardrail-test.js
|
|
6
|
+
// refuses a `new ImapFlow(` anywhere else.
|
|
7
|
+
//
|
|
8
|
+
// idHashAlgorithm: ImapFlow derives a fallback message id from path:uidValidity:uid when the server
|
|
9
|
+
// provides no email id, with MD5 unless told otherwise, and an OpenSSL FIPS provider has no MD5, so
|
|
10
|
+
// every FETCH would fail on such a host. EmailEngine never reads that id (new messages are
|
|
11
|
+
// deduplicated on emailId or Message-ID, and the value only appears in a log line), so the
|
|
12
|
+
// algorithm is free to differ from ImapFlow's default on every installation.
|
|
13
|
+
|
|
14
|
+
const { ImapFlow } = require('imapflow');
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {Object} config - Connection options, applied over the defaults
|
|
18
|
+
* @returns {ImapFlow}
|
|
19
|
+
*/
|
|
20
|
+
function createImapClient(config) {
|
|
21
|
+
return new ImapFlow({ idHashAlgorithm: 'sha256', ...config });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { createImapClient };
|
package/lib/db.js
CHANGED
|
@@ -11,6 +11,7 @@ const pathlib = require('path');
|
|
|
11
11
|
const redisUrl = require('./redis-url');
|
|
12
12
|
const { threadId } = require('worker_threads');
|
|
13
13
|
const logger = require('./logger');
|
|
14
|
+
const { readEnvValue } = require('./read-env-value');
|
|
14
15
|
const { REDIS_PREFIX } = require('./consts');
|
|
15
16
|
const Path = require('path');
|
|
16
17
|
const { isMainThread } = require('worker_threads');
|
|
@@ -19,28 +20,9 @@ config.dbs = config.dbs || {
|
|
|
19
20
|
redis: 'redis://127.0.0.1:6379/8'
|
|
20
21
|
};
|
|
21
22
|
|
|
22
|
-
const { Queue
|
|
23
|
+
const { Queue } = require('bullmq');
|
|
23
24
|
const Redis = require('ioredis');
|
|
24
25
|
|
|
25
|
-
// duplicate function declaration to avoid requiring tools.js
|
|
26
|
-
const readEnvValue = key => {
|
|
27
|
-
if (key in process.env) {
|
|
28
|
-
return process.env[key];
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
|
|
32
|
-
try {
|
|
33
|
-
// try to load from file
|
|
34
|
-
process.env[key] = fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n$/, '');
|
|
35
|
-
logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
|
|
36
|
-
} catch (err) {
|
|
37
|
-
logger.error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
|
|
38
|
-
process.env[key] = '';
|
|
39
|
-
}
|
|
40
|
-
return process.env[key];
|
|
41
|
-
}
|
|
42
|
-
};
|
|
43
|
-
|
|
44
26
|
const redisConf = readEnvValue('EENGINE_REDIS') || readEnvValue('REDIS_URL') || config.dbs.redis;
|
|
45
27
|
const REDIS_CONF = Object.assign(
|
|
46
28
|
{
|
|
@@ -116,10 +98,25 @@ module.exports.queueConf = {
|
|
|
116
98
|
prefix: `${REDIS_PREFIX}bull`
|
|
117
99
|
};
|
|
118
100
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
101
|
+
/**
|
|
102
|
+
* Routes the 'error' events of a BullMQ Worker, Queue or QueueEvents to the log.
|
|
103
|
+
* With no listener BullMQ catches the unhandled-'error' throw itself and prints it with
|
|
104
|
+
* console.error, so the error never reached pino or Sentry, and nothing crashed either
|
|
105
|
+
* @param {EventEmitter} emitter - The BullMQ object
|
|
106
|
+
* @param {string} component - What it is, e.g. 'queue:notify' or 'worker:submit'
|
|
107
|
+
* @returns {EventEmitter} The same object
|
|
108
|
+
*/
|
|
109
|
+
const logBullErrors = (emitter, component) => {
|
|
110
|
+
emitter.on('error', err => {
|
|
111
|
+
logger.error({ msg: 'Queue error', component, err });
|
|
112
|
+
});
|
|
113
|
+
return emitter;
|
|
114
|
+
};
|
|
115
|
+
module.exports.logBullErrors = logBullErrors;
|
|
116
|
+
|
|
117
|
+
const notifyQueue = logBullErrors(new Queue('notify', module.exports.queueConf), 'queue:notify');
|
|
118
|
+
const submitQueue = logBullErrors(new Queue('submit', module.exports.queueConf), 'queue:submit');
|
|
119
|
+
const exportQueue = logBullErrors(new Queue('export', module.exports.queueConf), 'queue:export');
|
|
123
120
|
|
|
124
121
|
const zExpungeScript = fs.readFileSync(pathlib.join(__dirname, '/lua/z-expunge.lua'), 'utf-8');
|
|
125
122
|
const zSetScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-set.lua'), 'utf-8');
|
|
@@ -139,6 +136,9 @@ const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrb
|
|
|
139
136
|
const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
|
|
140
137
|
const eeListRemoveScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-remove.lua'), 'utf-8');
|
|
141
138
|
const eeGetIdempotencyScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-get-idempotency.lua'), 'utf-8');
|
|
139
|
+
const eeReserveAttemptsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-reserve-attempts.lua'), 'utf-8');
|
|
140
|
+
const eeReleaseAttemptsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-release-attempts.lua'), 'utf-8');
|
|
141
|
+
const eeExportQueueAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-export-queue-add.lua'), 'utf-8');
|
|
142
142
|
|
|
143
143
|
redis.defineCommand('zExpunge', {
|
|
144
144
|
numberOfKeys: 2,
|
|
@@ -230,10 +230,24 @@ redis.defineCommand('eeGetIdempotency', {
|
|
|
230
230
|
lua: eeGetIdempotencyScript
|
|
231
231
|
});
|
|
232
232
|
|
|
233
|
+
// The budget scripts take one key per budget, so the key count is passed as the first argument
|
|
234
|
+
// (lib/rate-limit.js reserveAttempts / releaseAttempts)
|
|
235
|
+
redis.defineCommand('eeReserveAttempts', {
|
|
236
|
+
lua: eeReserveAttemptsScript
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
redis.defineCommand('eeReleaseAttempts', {
|
|
240
|
+
lua: eeReleaseAttemptsScript
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
redis.defineCommand('eeExportQueueAdd', {
|
|
244
|
+
numberOfKeys: 2,
|
|
245
|
+
lua: eeExportQueueAddScript
|
|
246
|
+
});
|
|
247
|
+
|
|
233
248
|
module.exports.redis = redis;
|
|
234
249
|
module.exports.notifyQueue = notifyQueue;
|
|
235
250
|
module.exports.submitQueue = submitQueue;
|
|
236
|
-
module.exports.documentsQueue = documentsQueue;
|
|
237
251
|
module.exports.exportQueue = exportQueue;
|
|
238
252
|
|
|
239
253
|
// Queues addressable by the name the API and the stats payload use for them. `export` is
|
|
@@ -241,15 +255,48 @@ module.exports.exportQueue = exportQueue;
|
|
|
241
255
|
// against this same set of names.
|
|
242
256
|
module.exports.QUEUES_BY_NAME = {
|
|
243
257
|
notify: notifyQueue,
|
|
244
|
-
submit: submitQueue
|
|
245
|
-
documents: documentsQueue
|
|
258
|
+
submit: submitQueue
|
|
246
259
|
};
|
|
247
260
|
|
|
248
|
-
// do not set up the flow producer by default
|
|
249
|
-
module.exports.getFlowProducer = () => new FlowProducer(module.exports.queueConf /*, Redis*/);
|
|
250
|
-
|
|
251
261
|
module.exports.REDIS_CONF = REDIS_CONF;
|
|
252
262
|
|
|
263
|
+
/**
|
|
264
|
+
* Calls `onReconnect` when a client that had been ready becomes ready again after losing its
|
|
265
|
+
* connection. ioredis emits 'end' only on a final close (retryStrategy returning a non-number, which
|
|
266
|
+
* the one above never does), so an ordinary reconnect is close -> reconnecting -> ready and a
|
|
267
|
+
* watcher that waited for 'end' never fired
|
|
268
|
+
* @param {Redis} client - ioredis client
|
|
269
|
+
* @param {Function} onReconnect - Called on the first 'ready' after a lost connection
|
|
270
|
+
* @param {Function} [onDisconnect] - Called once when a stable connection is lost
|
|
271
|
+
*/
|
|
272
|
+
module.exports.watchRedisReconnect = (client, onReconnect, onDisconnect) => {
|
|
273
|
+
let hasSeenStableConnection = client.status === 'ready';
|
|
274
|
+
let wasDisconnected = false;
|
|
275
|
+
|
|
276
|
+
const lost = () => {
|
|
277
|
+
// A failed first connection is not a reconnect; only a connection that was ready counts
|
|
278
|
+
if (hasSeenStableConnection && !wasDisconnected) {
|
|
279
|
+
wasDisconnected = true;
|
|
280
|
+
if (onDisconnect) {
|
|
281
|
+
onDisconnect();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
client.on('close', lost);
|
|
287
|
+
client.on('reconnecting', lost);
|
|
288
|
+
client.on('end', lost);
|
|
289
|
+
|
|
290
|
+
client.on('ready', () => {
|
|
291
|
+
if (wasDisconnected) {
|
|
292
|
+
wasDisconnected = false;
|
|
293
|
+
onReconnect();
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
hasSeenStableConnection = true;
|
|
297
|
+
});
|
|
298
|
+
};
|
|
299
|
+
|
|
253
300
|
let redisConnected = false;
|
|
254
301
|
const showRedisError = (msg, err, forceClose) => {
|
|
255
302
|
if (isMainThread && (forceClose || (!redisConnected && process.stdout.isTTY && isMainThread && !process.env.ENCRYPT_SECRET))) {
|
package/lib/delivery-error.js
CHANGED
|
@@ -19,7 +19,8 @@ const NON_RETRYABLE_CODES = new Set([
|
|
|
19
19
|
'ETLS', // TLS handshake failed
|
|
20
20
|
'EENVELOPE', // invalid sender/recipients
|
|
21
21
|
'EMESSAGE', // message content error
|
|
22
|
-
'EPROTOCOL' // SMTP protocol mismatch
|
|
22
|
+
'EPROTOCOL', // SMTP protocol mismatch
|
|
23
|
+
'GatewayNotFound' // the gateway the message was queued for no longer exists
|
|
23
24
|
]);
|
|
24
25
|
|
|
25
26
|
/**
|
|
@@ -111,4 +112,71 @@ function isFinalFailedAttempt(job) {
|
|
|
111
112
|
return !!job.finishedOn || job.attemptsMade >= (job.opts.attempts || 1);
|
|
112
113
|
}
|
|
113
114
|
|
|
114
|
-
|
|
115
|
+
// The same phase difference decides the retry TIME reported as `nextAttempt`, and the two call sites
|
|
116
|
+
// read a job in the two different phases, so they used to carry exponents that differ by one and
|
|
117
|
+
// looked like one of them was wrong. BullMQ's exponential strategy delays retry number r by
|
|
118
|
+
// 2^(r-1) * backoff.delay (Backoffs.builtinStrategies.exponential), and Job#shouldRetryJob() calls it
|
|
119
|
+
// with attemptsMade + 1, so the wait after the attempt numbered k fails is 2^(k-1) * delay. Verified
|
|
120
|
+
// against bullmq 6.3.11. Jitter is deliberately not applied: submissions are queued with
|
|
121
|
+
// jitter: 0.2, which spreads the real wait over [0.8, 1.0) of this figure, so what is reported is
|
|
122
|
+
// the latest the retry can happen. The schema calls it approximate for that reason.
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* How long BullMQ waits before retrying, once the attempt numbered `attemptNumber` has failed.
|
|
126
|
+
*
|
|
127
|
+
* @param {Number} attemptNumber - 1-based number of the attempt that failed
|
|
128
|
+
* @param {Object} job - BullMQ job, for its backoff options
|
|
129
|
+
* @returns {Number} Delay in milliseconds (0 when the job has no exponential backoff)
|
|
130
|
+
*/
|
|
131
|
+
function retryDelayAfterAttempt(attemptNumber, job) {
|
|
132
|
+
const backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
|
|
133
|
+
return Math.pow(2, attemptNumber - 1) * backoffDelay;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Inside a job processor: when would a failure of the CURRENTLY RUNNING attempt be retried?
|
|
138
|
+
* attemptsMade is not yet incremented here, so the running attempt is attemptsMade + 1.
|
|
139
|
+
*
|
|
140
|
+
* @param {Object} job - BullMQ job (mid-processing)
|
|
141
|
+
* @returns {Number|false} Epoch milliseconds, or false when this attempt is the job's last
|
|
142
|
+
*/
|
|
143
|
+
function nextAttemptWhileProcessing(job) {
|
|
144
|
+
if (willBeFinalAttempt(job)) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
return Math.round(job.processedOn + retryDelayAfterAttempt(job.attemptsMade + 1, job));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Reading a job back out of Redis (the outbox listing): when is its next attempt due? attemptsMade
|
|
152
|
+
* already counts the attempt that failed, so that attempt is attemptsMade itself.
|
|
153
|
+
*
|
|
154
|
+
* @param {Object} job - BullMQ job as stored
|
|
155
|
+
* @param {Number} scheduled - Epoch milliseconds the job was queued for, used while nothing has failed
|
|
156
|
+
* @returns {Number|false} Epoch milliseconds, or false when every attempt has been used up
|
|
157
|
+
*/
|
|
158
|
+
function nextAttemptOfStoredJob(job, scheduled) {
|
|
159
|
+
// isFinalFailedAttempt() rather than the attempts bound alone, for its finishedOn clause: a job
|
|
160
|
+
// the submit worker ended early with UnrecoverableError (every permanent SMTP rejection) is listed
|
|
161
|
+
// by the outbox with attempts left over, and reporting a retry time for a delivery that is dead
|
|
162
|
+
// for good is exactly the figure this module exists to get right
|
|
163
|
+
if (isFinalFailedAttempt(job)) {
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
if (!job.attemptsMade) {
|
|
167
|
+
// Nothing has failed yet, so the job is still waiting for its scheduled time
|
|
168
|
+
return scheduled;
|
|
169
|
+
}
|
|
170
|
+
return Math.round(job.processedOn + retryDelayAfterAttempt(job.attemptsMade, job));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = {
|
|
174
|
+
NON_RETRYABLE_CODES,
|
|
175
|
+
isPermanentDeliveryError,
|
|
176
|
+
shouldDiscardJob,
|
|
177
|
+
willBeFinalAttempt,
|
|
178
|
+
isFinalFailedAttempt,
|
|
179
|
+
retryDelayAfterAttempt,
|
|
180
|
+
nextAttemptWhileProcessing,
|
|
181
|
+
nextAttemptOfStoredJob
|
|
182
|
+
};
|