emailengine-app 2.85.0 → 2.87.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 +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +97 -0
- package/DOCKER_DEPLOYMENT.md +2 -1
- package/Dockerfile +16 -3
- package/ENVIRONMENT.md +139 -0
- package/README.md +5 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +285 -195
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +91 -32
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +25 -5
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +134 -158
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +59 -11
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +380 -227
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/outlook-client.js +378 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/field-usage.js +1 -1
- package/lib/gateway.js +17 -1
- package/lib/get-raw-email.js +35 -108
- package/lib/health.js +75 -0
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth/gmail.js +54 -29
- package/lib/oauth2-apps.js +630 -655
- package/lib/otp.js +66 -0
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +225 -41
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/swagger-options.js +2 -2
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +59 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +28 -26
- package/sbom.json +600 -678
- package/server.js +149 -76
- package/static/css/flyonui.css +1 -1
- package/static/js/ace/ace.js +1 -1
- package/static/js/ee-client.js +650 -196
- package/static/licenses.html +49 -59
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/layout/app.hbs +9 -6
- package/views/legal.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +112 -37
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- package/lib/email-client/outlook-fallback-poll.js +0 -30
package/lib/queue-retention.js
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const { readEnvValue } = require('./read-env-value');
|
|
4
|
-
|
|
5
3
|
// Retention policies for BullMQ job entries.
|
|
6
4
|
//
|
|
7
|
-
// This module is deliberately dependency-free (no Redis, no settings) so it can be unit tested
|
|
5
|
+
// This module is deliberately dependency-free (no Redis, no settings, no environment) so it can be unit tested
|
|
8
6
|
// directly. Four call sites used to build these policies inline from the `queueKeep` setting and
|
|
9
7
|
// had already drifted apart: three read the setting with `?? true` and one with `|| true`, which
|
|
10
8
|
// silently turned an explicit `queueKeep = 0` into "keep everything".
|
|
@@ -19,8 +17,26 @@ const COMPLETED_JOB_RETENTION_AGE = 24 * 3600;
|
|
|
19
17
|
// Both are overridable because the right bound depends on payload size: a `messageNew` webhook
|
|
20
18
|
// carries up to `notifyTextSize` (2MB by default) of message text, and a receiver that is down
|
|
21
19
|
// turns every event into a retained entry.
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
//
|
|
21
|
+
// Both are settings (queueKeepFailedAge, queueKeepFailed) and environment variables, which
|
|
22
|
+
// lib/env-setting-overrides.js resolves, the environment winning; the values below are only the
|
|
23
|
+
// defaults. Every caller passes the resolved bounds in, so there is one parser for the variables.
|
|
24
|
+
const FAILED_JOB_RETENTION_AGE_DEFAULT = 7 * 24 * 3600;
|
|
25
|
+
const FAILED_JOB_RETENTION_COUNT_DEFAULT = 500;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {{age: number, count: number}} failedRetention
|
|
29
|
+
* @returns {{age: number, count: number}} The same bounds, checked
|
|
30
|
+
*/
|
|
31
|
+
function requireFailedRetention(failedRetention) {
|
|
32
|
+
const age = Number(failedRetention?.age);
|
|
33
|
+
const count = Number(failedRetention?.count);
|
|
34
|
+
if (!(age > 0) || !(count > 0)) {
|
|
35
|
+
// the bounds come from getFailedJobRetention(); a default here would ignore the setting
|
|
36
|
+
throw new TypeError('The failed-job retention bounds are required, see getFailedJobRetention()');
|
|
37
|
+
}
|
|
38
|
+
return { age, count };
|
|
39
|
+
}
|
|
24
40
|
|
|
25
41
|
/**
|
|
26
42
|
* Builds the `removeOnComplete` / `removeOnFail` pair for a queue job.
|
|
@@ -28,23 +44,27 @@ const FAILED_JOB_RETENTION_COUNT = Number(readEnvValue('EENGINE_QUEUE_KEEP_FAILE
|
|
|
28
44
|
* A job reaches the failed set only after every retry is exhausted, which for a webhook means the
|
|
29
45
|
* event is gone. `queueKeep` defaults to 0, so applying it to failures too (the previous behavior)
|
|
30
46
|
* deleted that record the moment it was written and left nothing but a log line behind. Failures
|
|
31
|
-
* therefore get their own floor: at least `
|
|
32
|
-
*
|
|
47
|
+
* therefore get their own floor: at least `failedRetention.count` entries for `failedRetention.age`
|
|
48
|
+
* seconds, regardless of how few completed entries are wanted.
|
|
33
49
|
*
|
|
34
50
|
* BullMQ reads these values as "when to remove", not "how much to keep": `true` removes the entry
|
|
35
51
|
* immediately, `false` keeps it forever, a number keeps the last N, and `{age, count}` keeps
|
|
36
52
|
* entries younger than `age` up to `count` of them.
|
|
37
53
|
*
|
|
38
54
|
* @param {boolean|number} queueKeep - The `queueKeep` setting: entries to retain, or a boolean
|
|
55
|
+
* @param {{age: number, count: number}} failedRetention - The failed-job bounds in effect (age in
|
|
56
|
+
* seconds), as getFailedJobRetention() resolves them
|
|
39
57
|
* @returns {{removeOnComplete: boolean|Object, removeOnFail: boolean|Object}} BullMQ job options
|
|
40
58
|
*/
|
|
41
|
-
function buildRetentionPolicy(queueKeep) {
|
|
59
|
+
function buildRetentionPolicy(queueKeep, failedRetention) {
|
|
60
|
+
const { age: failedAge, count: failedCount } = requireFailedRetention(failedRetention);
|
|
61
|
+
|
|
42
62
|
const removeOnComplete = typeof queueKeep === 'number' ? { age: COMPLETED_JOB_RETENTION_AGE, count: queueKeep } : queueKeep;
|
|
43
63
|
|
|
44
64
|
// Always bounded, and widened when the operator asked to keep more entries than the floor
|
|
45
65
|
const removeOnFail = {
|
|
46
|
-
age:
|
|
47
|
-
count: typeof queueKeep === 'number' ? Math.max(queueKeep,
|
|
66
|
+
age: failedAge,
|
|
67
|
+
count: typeof queueKeep === 'number' ? Math.max(queueKeep, failedCount) : failedCount
|
|
48
68
|
};
|
|
49
69
|
|
|
50
70
|
return { removeOnComplete, removeOnFail };
|
|
@@ -99,12 +119,28 @@ function selectFailedContentToDrop(entries, limits) {
|
|
|
99
119
|
return drop.reverse();
|
|
100
120
|
}
|
|
101
121
|
|
|
122
|
+
/**
|
|
123
|
+
* Ages for the periodic queue clean in server.js, in milliseconds as BullMQ's clean() takes them
|
|
124
|
+
* (the retention ages above are seconds, as removeOnComplete/removeOnFail take them). The clean used
|
|
125
|
+
* hardcoded 24 hours and 7 days, so a longer failed-job retention kept failed jobs no longer than a
|
|
126
|
+
* week anyway
|
|
127
|
+
* @param {{age: number, count: number}} failedRetention - As getFailedJobRetention() resolves it
|
|
128
|
+
* @returns {{ completed: number, failed: number }}
|
|
129
|
+
*/
|
|
130
|
+
function queueCleanAges(failedRetention) {
|
|
131
|
+
return {
|
|
132
|
+
completed: COMPLETED_JOB_RETENTION_AGE * 1000,
|
|
133
|
+
failed: requireFailedRetention(failedRetention).age * 1000
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
102
137
|
module.exports = {
|
|
103
138
|
buildRetentionPolicy,
|
|
139
|
+
queueCleanAges,
|
|
104
140
|
selectFailedContentToDrop,
|
|
105
141
|
COMPLETED_JOB_RETENTION_AGE,
|
|
106
|
-
|
|
107
|
-
|
|
142
|
+
FAILED_JOB_RETENTION_AGE_DEFAULT,
|
|
143
|
+
FAILED_JOB_RETENTION_COUNT_DEFAULT,
|
|
108
144
|
DEFAULT_FAILED_CONTENT_RETENTION_COUNT,
|
|
109
145
|
DEFAULT_FAILED_CONTENT_RETENTION_SIZE
|
|
110
146
|
};
|
package/lib/queue-stats.js
CHANGED
|
@@ -22,13 +22,18 @@ const COUNTED_STATES = ['active', 'delayed', 'waiting'];
|
|
|
22
22
|
* Counts the pending jobs of a queue and reports whether the queue is paused.
|
|
23
23
|
*
|
|
24
24
|
* @param {Object} queueObj - BullMQ Queue instance
|
|
25
|
+
* @param {Object} [opts]
|
|
26
|
+
* @param {boolean} [opts.failed] - Also count the failed jobs the queue still retains, in the same
|
|
27
|
+
* read, as `failed`. Kept out of `total` and out of the published payloads: a failed job is not
|
|
28
|
+
* pending work, it is the record that a delivery was given up on, which is what /metrics alerts on
|
|
25
29
|
* @returns {Promise<Object>} `active`, `delayed` and `waiting` counts plus their `total`, the
|
|
26
30
|
* `isPaused` flag, and a `paused` count that is always 0 - BullMQ 6 no longer parks jobs in a
|
|
27
31
|
* separate paused list, so a paused queue holds them in `waiting` and they are counted there.
|
|
28
32
|
* The key is kept because it is part of both published payloads.
|
|
29
33
|
*/
|
|
30
|
-
async function queueStats(queueObj) {
|
|
31
|
-
const
|
|
34
|
+
async function queueStats(queueObj, opts = {}) {
|
|
35
|
+
const states = opts.failed ? COUNTED_STATES.concat('failed') : COUNTED_STATES;
|
|
36
|
+
const [counts, isPaused] = await Promise.all([queueObj.getJobCounts(...states), queueObj.isPaused()]);
|
|
32
37
|
|
|
33
38
|
const stats = {
|
|
34
39
|
paused: 0,
|
|
@@ -43,6 +48,10 @@ async function queueStats(queueObj) {
|
|
|
43
48
|
}
|
|
44
49
|
stats.total = total;
|
|
45
50
|
|
|
51
|
+
if (opts.failed) {
|
|
52
|
+
stats.failed = Number(counts.failed) || 0;
|
|
53
|
+
}
|
|
54
|
+
|
|
46
55
|
return stats;
|
|
47
56
|
}
|
|
48
57
|
|
package/lib/read-env-value.js
CHANGED
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
// would create). Still re-exported from lib/tools.js, which is where most callers reach it.
|
|
6
6
|
|
|
7
7
|
const Fs = require('fs');
|
|
8
|
+
|
|
9
|
+
// lib/logger.js takes its constants from lib/logger-consts.js rather than lib/consts.js, which reads
|
|
10
|
+
// its own variables through this helper, so the logger can be required here directly
|
|
8
11
|
const logger = require('./logger');
|
|
9
12
|
|
|
10
13
|
// The keys that lib/db.js and lib/get-secret.js used to resolve through private copies of this
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Dashboard warnings about how Redis manages its memory, derived from INFO. Pure, so the decisions
|
|
4
|
+
// can be tested without a Redis to put into each state.
|
|
5
|
+
//
|
|
6
|
+
// EmailEngine uses Redis as a database, not a cache. Any eviction silently drops sync state, which
|
|
7
|
+
// makes already-synced messages look new and triggers duplicate webhooks. With the required
|
|
8
|
+
// noeviction policy the failure is the other one: once used memory reaches maxmemory, Redis refuses
|
|
9
|
+
// every write with an OOM reply, and sync, delivery and webhooks stop together. Neither eviction
|
|
10
|
+
// warning fires for that, so a separate one says how close to the limit Redis is.
|
|
11
|
+
|
|
12
|
+
const { humanSize } = require('./queue-browser/format');
|
|
13
|
+
|
|
14
|
+
// Share of maxmemory at which the dashboard starts warning, and at which the warning turns red
|
|
15
|
+
const MEMORY_WARNING_RATIO = 0.8;
|
|
16
|
+
const MEMORY_DANGER_RATIO = 0.95;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Warning about eviction, either already happened or allowed by the configured policy
|
|
20
|
+
* @param {Object} redisInfo - Parsed INFO output
|
|
21
|
+
* @returns {Object|null} Warning entry, or null
|
|
22
|
+
*/
|
|
23
|
+
function evictionWarning(redisInfo) {
|
|
24
|
+
let maxmemoryPolicy = typeof redisInfo.maxmemory_policy === 'string' ? redisInfo.maxmemory_policy : null;
|
|
25
|
+
let maxmemory = Number(redisInfo.maxmemory) || 0;
|
|
26
|
+
let evictedKeys = Number(redisInfo.evicted_keys) || 0;
|
|
27
|
+
|
|
28
|
+
if (evictedKeys > 0) {
|
|
29
|
+
// Definitive: Redis has already evicted keys
|
|
30
|
+
return {
|
|
31
|
+
key: 'evicted-keys',
|
|
32
|
+
color: 'danger',
|
|
33
|
+
title: 'Redis eviction detected',
|
|
34
|
+
details: [
|
|
35
|
+
`Redis has evicted ${evictedKeys.toLocaleString('en-US')} key${evictedKeys === 1 ? '' : 's'} after reaching its memory limit.`,
|
|
36
|
+
'EmailEngine uses Redis as its primary database, not a cache. Evicted keys cause already-synced messages to be reprocessed - generating duplicate webhooks - and can lead to data loss.',
|
|
37
|
+
'Set the Redis "maxmemory-policy" to "noeviction" and provision enough memory so Redis never reaches its limit.'
|
|
38
|
+
]
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (maxmemoryPolicy && maxmemoryPolicy !== 'noeviction') {
|
|
43
|
+
// Latent risk: an eviction policy is configured but nothing has been evicted yet
|
|
44
|
+
return {
|
|
45
|
+
key: 'maxmemory-policy',
|
|
46
|
+
color: maxmemory > 0 ? 'danger' : 'warning',
|
|
47
|
+
title: 'Unsafe Redis eviction policy',
|
|
48
|
+
details: [
|
|
49
|
+
`The Redis "maxmemory-policy" is set to "${maxmemoryPolicy}", but EmailEngine requires "noeviction".`,
|
|
50
|
+
'With any other policy, Redis can delete EmailEngine sync state under memory pressure, causing already-synced messages to be reprocessed - generating duplicate webhooks - and possible data loss.',
|
|
51
|
+
'Set "maxmemory-policy noeviction" and make sure Redis has enough memory for your workload.'
|
|
52
|
+
]
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Warning about used memory approaching maxmemory. Without a maxmemory there is no limit for
|
|
61
|
+
* Redis to refuse writes at, so nothing is reported
|
|
62
|
+
* @param {Object} redisInfo - Parsed INFO output
|
|
63
|
+
* @returns {Object|null} Warning entry, or null
|
|
64
|
+
*/
|
|
65
|
+
function memoryLimitWarning(redisInfo) {
|
|
66
|
+
let maxmemory = Number(redisInfo.maxmemory) || 0;
|
|
67
|
+
let usedMemory = Number(redisInfo.used_memory) || 0;
|
|
68
|
+
if (maxmemory <= 0 || usedMemory <= 0) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let ratio = usedMemory / maxmemory;
|
|
73
|
+
if (ratio < MEMORY_WARNING_RATIO) {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
key: 'memory-limit',
|
|
79
|
+
color: ratio >= MEMORY_DANGER_RATIO ? 'danger' : 'warning',
|
|
80
|
+
title: 'Redis is close to its memory limit',
|
|
81
|
+
details: [
|
|
82
|
+
`Redis is using ${humanSize(usedMemory)} of its ${humanSize(maxmemory)} "maxmemory" limit (${Math.min(Math.round(ratio * 100), 100)}%).`,
|
|
83
|
+
'Once the limit is reached Redis refuses every write, and syncing, sending and webhook delivery stop until memory is freed.',
|
|
84
|
+
'Raise "maxmemory", or find what is growing: a webhook backlog for a receiver that is down, account logs, or failed queue entries.'
|
|
85
|
+
]
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* All memory warnings for the dashboard, in display order
|
|
91
|
+
* @param {Object} redisInfo - Parsed INFO output
|
|
92
|
+
* @returns {Object[]} Warning entries
|
|
93
|
+
*/
|
|
94
|
+
function redisMemoryWarnings(redisInfo) {
|
|
95
|
+
redisInfo = redisInfo || {};
|
|
96
|
+
return [evictionWarning(redisInfo), memoryLimitWarning(redisInfo)].filter(Boolean);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = { redisMemoryWarnings };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// ioredis calls `reconnectOnError` for every error REPLY, not for connection errors: a refused
|
|
4
|
+
// write under `maxmemory` (OOM), a WRONGTYPE, a NOSCRIPT before the script is loaded again, and an
|
|
5
|
+
// error raised by a BullMQ Lua script all pass through it. Answering true to all of them dropped the
|
|
6
|
+
// connection on each one, and the IMAP worker exits on every Redis reconnect (workers/imap.js), so a
|
|
7
|
+
// full Redis turned into a loop of worker restarts and account resyncs, each writing more to a
|
|
8
|
+
// database that was already refusing writes.
|
|
9
|
+
//
|
|
10
|
+
// The only reply a reconnect fixes is READONLY: the client is still connected to a node that was
|
|
11
|
+
// demoted in a failover, and reconnecting reaches the new primary. Returning 2 makes ioredis resend
|
|
12
|
+
// the command once it has.
|
|
13
|
+
|
|
14
|
+
const RESEND_AFTER_RECONNECT = 2;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Decides whether an error reply means the connection should be re-established
|
|
18
|
+
* @param {Error} err - The error reply ioredis received
|
|
19
|
+
* @returns {number|boolean} 2 to reconnect and resend the command, false to just reject it
|
|
20
|
+
*/
|
|
21
|
+
function reconnectOnErrorReply(err) {
|
|
22
|
+
let message = (err && typeof err.message === 'string' && err.message) || '';
|
|
23
|
+
if (/^READONLY\b/.test(message)) {
|
|
24
|
+
return RESEND_AFTER_RECONNECT;
|
|
25
|
+
}
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
module.exports = { reconnectOnErrorReply, RESEND_AFTER_RECONNECT };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* How long an API request took, for the api_call_duration_seconds histogram. Read off Hapi's
|
|
5
|
+
* request.info in the 'response' event, where `completed` is set once the response was sent.
|
|
6
|
+
* A request the client abandoned has no `completed` but a `responded`, and either one is a better
|
|
7
|
+
* end than the time the event happens to run.
|
|
8
|
+
*
|
|
9
|
+
* @param {Object} info - Hapi request.info
|
|
10
|
+
* @returns {number|null} Seconds, or null when the request carries no usable timestamps
|
|
11
|
+
*/
|
|
12
|
+
function apiCallDuration(info) {
|
|
13
|
+
if (!info || !Number.isFinite(info.received) || info.received <= 0) {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
const end = [info.completed, info.responded].find(value => Number.isFinite(value) && value > 0);
|
|
17
|
+
if (!end || end < info.received) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
return (end - info.received) / 1000;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
module.exports = { apiCallDuration };
|
package/lib/respawn-backoff.js
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
// stays up resets its own key immediately. server.js keys it by spawn slot (one per thread it
|
|
12
12
|
// supervises), so exits of sibling workers of the same type do not add up.
|
|
13
13
|
|
|
14
|
+
const { setTimeout: setTimeoutPromise } = require('node:timers/promises');
|
|
15
|
+
|
|
14
16
|
const DEFAULT_BASE_DELAY = 1000;
|
|
15
17
|
const DEFAULT_MAX_DELAY = 60 * 1000;
|
|
16
18
|
|
|
@@ -88,8 +90,41 @@ class RespawnTracker {
|
|
|
88
90
|
}
|
|
89
91
|
}
|
|
90
92
|
|
|
93
|
+
/**
|
|
94
|
+
* Calls `fn` until it resolves, waiting `delayFor(attempt)` between failures. For the Redis reads
|
|
95
|
+
* a respawn has to make before it can start a thread (is the listener enabled): a failure there
|
|
96
|
+
* (Redis refusing commands under maxmemory, a failover) used to end the respawn chain for good,
|
|
97
|
+
* and the worker stayed down until the process restarted.
|
|
98
|
+
*
|
|
99
|
+
* @param {Function} fn - The read to make
|
|
100
|
+
* @param {Object} opts
|
|
101
|
+
* @param {Function} opts.delayFor - Delay before retry n (1 based), e.g. RespawnTracker#delayFor
|
|
102
|
+
* @param {Function} [opts.shouldStop] - True once the process is shutting down; the retries stop
|
|
103
|
+
* and the call resolves with undefined
|
|
104
|
+
* @param {Function} [opts.onError] - Called with the error and the delay before the retry
|
|
105
|
+
* @param {Function} [opts.sleep] - Waits the given milliseconds
|
|
106
|
+
* @returns {Promise<*>} What `fn` resolved with
|
|
107
|
+
*/
|
|
108
|
+
async function retryWithBackoff(fn, opts) {
|
|
109
|
+
const { delayFor, shouldStop = () => false, onError = () => {}, sleep = setTimeoutPromise } = opts;
|
|
110
|
+
|
|
111
|
+
for (let attempt = 1; !shouldStop(); attempt++) {
|
|
112
|
+
try {
|
|
113
|
+
return await fn();
|
|
114
|
+
} catch (err) {
|
|
115
|
+
if (shouldStop()) {
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
const delay = delayFor(attempt);
|
|
119
|
+
onError(err, delay);
|
|
120
|
+
await sleep(delay);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
91
125
|
module.exports = {
|
|
92
126
|
RespawnTracker,
|
|
127
|
+
retryWithBackoff,
|
|
93
128
|
DEFAULT_BASE_DELAY,
|
|
94
129
|
DEFAULT_MAX_DELAY,
|
|
95
130
|
DEFAULT_STABLE_UPTIME
|
|
@@ -3,64 +3,12 @@
|
|
|
3
3
|
const Rewriter = require('@zone-eu/mailsplit/lib/node-rewriter');
|
|
4
4
|
const Splitter = require('@zone-eu/mailsplit/lib/message-splitter');
|
|
5
5
|
const Joiner = require('@zone-eu/mailsplit/lib/message-joiner');
|
|
6
|
-
const
|
|
7
|
-
const {
|
|
8
|
-
const iconv = require('iconv-lite');
|
|
6
|
+
const libmime = require('libmime');
|
|
7
|
+
const { pipeline } = require('stream');
|
|
9
8
|
const LeWindows = require('nodemailer/lib/mime-node/le-windows');
|
|
10
9
|
const { markParseFailure } = require('./smtp-message-processor');
|
|
11
10
|
const logger = require('./logger').child({ component: 'rewrite-text-nodes' });
|
|
12
11
|
|
|
13
|
-
class JPDecoder extends Transform {
|
|
14
|
-
constructor(charset) {
|
|
15
|
-
super();
|
|
16
|
-
|
|
17
|
-
this.charset = charset;
|
|
18
|
-
this.chunks = [];
|
|
19
|
-
this.chunklen = 0;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
_transform(chunk, encoding, done) {
|
|
23
|
-
if (typeof chunk === 'string') {
|
|
24
|
-
chunk = Buffer.from(chunk, encoding);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
this.chunks.push(chunk);
|
|
28
|
-
this.chunklen += chunk.length;
|
|
29
|
-
done();
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
_flush(done) {
|
|
33
|
-
let input = Buffer.concat(this.chunks, this.chunklen);
|
|
34
|
-
try {
|
|
35
|
-
let output = encodingJapanese.convert(input, {
|
|
36
|
-
to: 'UNICODE', // to_encoding
|
|
37
|
-
from: this.charset, // from_encoding
|
|
38
|
-
type: 'string'
|
|
39
|
-
});
|
|
40
|
-
if (typeof output === 'string') {
|
|
41
|
-
output = Buffer.from(output);
|
|
42
|
-
}
|
|
43
|
-
this.push(output);
|
|
44
|
-
} catch (err) {
|
|
45
|
-
logger.debug({ msg: 'Failed to convert Japanese charset, keeping original content', charset: this.charset, err });
|
|
46
|
-
// keep as is on errors
|
|
47
|
-
this.push(input);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
done();
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const createDecodeStream = charset => {
|
|
55
|
-
charset = (charset || 'ascii').toString().trim().toLowerCase();
|
|
56
|
-
if (/^jis|^iso-?2022-?jp|^EUCJP/i.test(charset)) {
|
|
57
|
-
// special case not supported by iconv-lite
|
|
58
|
-
return new JPDecoder(charset);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
return iconv.decodeStream(charset);
|
|
62
|
-
};
|
|
63
|
-
|
|
64
12
|
/**
|
|
65
13
|
* Rewrites text content in email messages
|
|
66
14
|
* @param {String|Buffer|ReadableStream} source RFC822 formatted email message
|
|
@@ -111,18 +59,24 @@ function rewriteTextNodes(source, options) {
|
|
|
111
59
|
let encoded = !!data.node.charset;
|
|
112
60
|
let decoder = data.decoder;
|
|
113
61
|
|
|
62
|
+
// A part in a charset that can not be decoded (unknown, or refused like UTF-7) is passed
|
|
63
|
+
// through untouched with its own label. It used to be relabelled utf-8 with the
|
|
64
|
+
// original bytes kept, which garbled it: a label as common as x-cp1251 failed that way,
|
|
65
|
+
// because the name reached iconv-lite without being normalized first
|
|
66
|
+
let decodable = true;
|
|
67
|
+
|
|
114
68
|
if (encoded && !['ascii', 'usascii', 'utf8'].includes(data.node.charset.toLowerCase().replace(/[^a-z0-9]+/g, ''))) {
|
|
115
|
-
|
|
69
|
+
let decodeStream = libmime.createDecodeStream(data.node.charset);
|
|
70
|
+
if (decodeStream.supported) {
|
|
116
71
|
let contentStream = decoder;
|
|
117
|
-
let decodeStream = createDecodeStream(data.node.charset);
|
|
118
72
|
contentStream.on('error', err => {
|
|
119
73
|
decodeStream.emit('error', err);
|
|
120
74
|
});
|
|
121
75
|
contentStream.pipe(decodeStream);
|
|
122
76
|
decoder = decodeStream;
|
|
123
|
-
}
|
|
124
|
-
logger.debug({ msg: '
|
|
125
|
-
|
|
77
|
+
} else {
|
|
78
|
+
logger.debug({ msg: 'Unsupported charset, keeping the text part as it is', charset: data.node.charset });
|
|
79
|
+
decodable = false;
|
|
126
80
|
}
|
|
127
81
|
}
|
|
128
82
|
|
|
@@ -149,6 +103,12 @@ function rewriteTextNodes(source, options) {
|
|
|
149
103
|
|
|
150
104
|
decoder.on('end', () => {
|
|
151
105
|
const htmlBuf = Buffer.concat(chunks, chunklen);
|
|
106
|
+
|
|
107
|
+
if (!decodable) {
|
|
108
|
+
data.encoder.end(htmlBuf);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
152
112
|
let html = htmlBuf.toString('utf-8');
|
|
153
113
|
|
|
154
114
|
// enforce utf-8
|