emailengine-app 2.87.0 → 2.87.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.
Files changed (60) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +19 -0
  4. package/Dockerfile +3 -4
  5. package/bin/emailengine.js +2 -4
  6. package/bin/healthcheck.js +20 -0
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +3 -7
  9. package/lib/account/auth-failure-backfill.js +3 -2
  10. package/lib/account/expected-identity.js +2 -2
  11. package/lib/account.js +9 -8
  12. package/lib/api-listener.js +40 -0
  13. package/lib/api-token-auth.js +406 -0
  14. package/lib/autodetect-imap-settings.js +36 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/email-client/base-client.js +23 -107
  17. package/lib/email-client/gmail-client.js +7 -4
  18. package/lib/email-client/imap/mailbox.js +89 -96
  19. package/lib/email-client/imap/sync-operations.js +13 -6
  20. package/lib/email-client/imap-client.js +28 -7
  21. package/lib/email-client/new-message-steps.js +162 -0
  22. package/lib/email-client/outlook-client.js +4 -2
  23. package/lib/env-setting-overrides.js +6 -2
  24. package/lib/export-worker.js +3 -2
  25. package/lib/export.js +43 -4
  26. package/lib/get-boolean.js +38 -0
  27. package/lib/health-probe.js +71 -0
  28. package/lib/imapproxy/imap-server.js +4 -55
  29. package/lib/net-tos-guard.js +42 -0
  30. package/lib/oauth2-apps.js +2 -1
  31. package/lib/read-env-value.js +19 -7
  32. package/lib/redis-keys.js +19 -0
  33. package/lib/redis-operations.js +7 -3
  34. package/lib/security-headers.js +18 -0
  35. package/lib/session-default.js +50 -0
  36. package/lib/settings.js +2 -1
  37. package/lib/stream-encrypt.js +71 -20
  38. package/lib/sub-script.js +8 -2
  39. package/lib/submit-lock.js +84 -0
  40. package/lib/submit-processor.js +283 -0
  41. package/lib/templates.js +6 -3
  42. package/lib/tls/context.js +2 -16
  43. package/lib/tools.js +8 -30
  44. package/lib/utils/redis-errors.js +44 -0
  45. package/lib/webhook-delivery.js +3 -4
  46. package/lib/worker-rpc-error.js +10 -5
  47. package/lib/worker-rpc.js +138 -0
  48. package/package.json +17 -19
  49. package/sbom.json +370 -1446
  50. package/server.js +6 -5
  51. package/static/css/flyonui.css +2 -2
  52. package/static/licenses.html +253 -1366
  53. package/translations/messages.pot +16 -16
  54. package/workers/api.js +41 -465
  55. package/workers/export.js +14 -55
  56. package/workers/imap-proxy.js +5 -18
  57. package/workers/imap.js +27 -49
  58. package/workers/smtp.js +7 -69
  59. package/workers/submit.js +21 -279
  60. package/workers/webhooks.js +7 -72
@@ -0,0 +1,283 @@
1
+ 'use strict';
2
+
3
+ // The submit queue's job processor, moved out of workers/submit.js so a test can run the real thing
4
+ // against real BullMQ jobs: the worker cannot be loaded from a test (it starts consuming on
5
+ // require), and what has to be pinned here is the order of events around a crash, which only the
6
+ // real processor and a real queue show.
7
+ //
8
+ // What this does NOT do is forget that a message was sent. The marker sendQueuedOnce() writes
9
+ // (lib/submit-lock.js) is the only record that a retry must not send again, and it is needed until
10
+ // BullMQ has recorded the job as completed: a worker that dies after the send and before that
11
+ // record leaves a job that runs again. Clearing it here, before the processor returned, let that
12
+ // run send the message a second time. completeSubmission() clears it from the worker's
13
+ // 'completed' event, which BullMQ emits only once the completion is stored; a job that never
14
+ // completes keeps its marker until the marker expires.
15
+
16
+ const { UnrecoverableError } = require('bullmq');
17
+
18
+ const { decodeQueueEntry, outboxKey } = require('./outbox');
19
+ const { shouldDiscardJob, willBeFinalAttempt, nextAttemptWhileProcessing } = require('./delivery-error');
20
+ const { isAlreadySent } = require('./submit-progress');
21
+ const { clearSent } = require('./submit-lock');
22
+
23
+ /**
24
+ * Jobs queued by old versions carry the queue entry id as `qId`
25
+ * @param {Object} job - BullMQ job, its data updated in place
26
+ */
27
+ function normalizeQueueId(job) {
28
+ if (!job.data.queueId && job.data.qId) {
29
+ job.data.queueId = job.data.qId;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Builds the submit queue processor
35
+ * @param {Object} deps
36
+ * @param {Object} deps.redis - ioredis client
37
+ * @param {Object} deps.logger
38
+ * @param {Object} deps.submitQueue - the BullMQ queue the jobs belong to, read back for a job's stored progress
39
+ * @param {Function} deps.getAccount - async (accountId) => object with submitMessage(queueEntry)
40
+ * @returns {Function} async (job) => processes one queued message
41
+ */
42
+ function createSubmitProcessor({ redis, logger, submitQueue, getAccount }) {
43
+ return async job => {
44
+ normalizeQueueId(job);
45
+
46
+ // A job re-run after a stall (heartbeat kill, crash, a shutdown drain that could not cover
47
+ // a long SMTP transaction plus the Sent-folder upload) comes back with the progress its
48
+ // previous run stored. Once that says the MTA accepted the message, sending again would
49
+ // deliver a duplicate under the same queueId: the message is done, only the bookkeeping
50
+ // after the 250 was cut short. The catch below covers the same state for a run that got
51
+ // as far as throwing; this covers the run that never got to throw anything.
52
+ if (isAlreadySent(job.progress)) {
53
+ logger.info({
54
+ msg: 'Skipping re-run of an already sent message',
55
+ action: 'submit',
56
+ queue: job.queue.name,
57
+ code: 'result_success',
58
+ job: job.id,
59
+ event: job.name,
60
+ account: job.data.account,
61
+ queueId: job.data.queueId,
62
+ messageId: job.data.messageId,
63
+ progress: job.progress.status,
64
+ attemptsMade: job.attemptsMade
65
+ });
66
+ return;
67
+ }
68
+
69
+ let queueEntryBuf = await redis.hgetBuffer(outboxKey(job.data.account), job.data.queueId);
70
+ if (!queueEntryBuf) {
71
+ // nothing to do here
72
+ try {
73
+ await redis.hdel(outboxKey(job.data.account), job.data.queueId);
74
+ } catch (err) {
75
+ // ignore
76
+ }
77
+ return;
78
+ }
79
+
80
+ let queueEntry;
81
+ try {
82
+ // Rejects a value that decodes to something other than a map as well, otherwise the
83
+ // job metadata assignment below throws a TypeError against it and the entry is retried
84
+ // as a failed delivery instead of being dropped as the corrupt entry it is
85
+ queueEntry = decodeQueueEntry(queueEntryBuf);
86
+ } catch (err) {
87
+ logger.error({ msg: 'Failed to parse queued email entry', job: job.id, account: job.data.account, queueId: job.data.queueId, err });
88
+ try {
89
+ await redis.hdel(outboxKey(job.data.account), job.data.queueId);
90
+ } catch (err) {
91
+ // ignore
92
+ }
93
+ return;
94
+ }
95
+
96
+ let accountObject = await getAccount(job.data.account);
97
+
98
+ logger.trace({
99
+ msg: 'Processing message',
100
+ action: 'submit',
101
+ queue: job.queue.name,
102
+ code: 'processing',
103
+ job: job.id,
104
+ event: job.name,
105
+ data: job.data,
106
+ account: job.data.account
107
+ });
108
+
109
+ try {
110
+ try {
111
+ // try to update
112
+ await job.updateProgress({
113
+ status: 'processing'
114
+ });
115
+ } catch (err) {
116
+ // ignore
117
+ }
118
+
119
+ let nextAttempt = nextAttemptWhileProcessing(job);
120
+
121
+ queueEntry.job = {
122
+ id: job.id,
123
+ attemptsMade: job.attemptsMade,
124
+ attempts: job.opts.attempts,
125
+ nextAttempt: nextAttempt ? new Date(nextAttempt).toISOString() : false
126
+ };
127
+
128
+ let res = await accountObject.submitMessage(queueEntry);
129
+
130
+ logger.trace({
131
+ msg: 'Submitted queued message for delivery',
132
+ action: 'submit',
133
+ queue: job.queue.name,
134
+ code: 'result_success',
135
+ job: job.id,
136
+ event: job.name,
137
+ data: job.data,
138
+ account: job.data.account
139
+ });
140
+
141
+ try {
142
+ // try to update
143
+ await job.updateProgress({
144
+ status: 'submitted',
145
+ response: res.response
146
+ });
147
+ } catch (err) {
148
+ // ignore
149
+ }
150
+ } catch (err) {
151
+ // The message went out even though this run failed: an earlier attempt sent it and its
152
+ // call failed after the fact (AlreadySent, lib/submit-lock.js), or this run failed after
153
+ // the accept
154
+ let alreadySent = err.code === 'AlreadySent';
155
+ if (!alreadySent) {
156
+ try {
157
+ const submitJobEntry = await submitQueue.getJob(job.id);
158
+ alreadySent = !!submitJobEntry && isAlreadySent(submitJobEntry.progress);
159
+ } catch (err) {
160
+ logger.error({
161
+ msg: 'Failed to fetch job status',
162
+ job: job.id,
163
+ account: job.data.account,
164
+ err
165
+ });
166
+ }
167
+ }
168
+ if (alreadySent) {
169
+ logger.info({
170
+ msg: 'Message was already sent, counting the job as sent',
171
+ action: 'submit',
172
+ queue: job.queue.name,
173
+ code: 'result_success',
174
+ job: job.id,
175
+ event: job.name,
176
+ account: job.data.account,
177
+ queueId: job.data.queueId,
178
+ err
179
+ });
180
+ try {
181
+ // The retry wrote 'processing' over the sent state
182
+ await job.updateProgress({ status: 'submitted' });
183
+ } catch (err) {
184
+ // ignore
185
+ }
186
+ return;
187
+ }
188
+
189
+ const discardJob = shouldDiscardJob(err, job);
190
+ const isFinalAttempt = discardJob || willBeFinalAttempt(job);
191
+
192
+ logger[isFinalAttempt ? 'error' : 'warn']({
193
+ msg: 'Message submission failed',
194
+ action: 'submit',
195
+ queue: job.queue.name,
196
+ code: 'result_fail',
197
+ job: job.id,
198
+ event: job.name,
199
+ data: job.data,
200
+ account: job.data.account,
201
+ err
202
+ });
203
+
204
+ try {
205
+ // try to update
206
+ await job.updateProgress({
207
+ status: 'error',
208
+ error: {
209
+ message: err.message,
210
+ code: err.code,
211
+ statusCode: err.statusCode,
212
+ // the SMTP reply code, when there was a reply: what decides whether the
213
+ // failure is permanent (lib/delivery-error.js), kept so the queue browser
214
+ // can say so without a rule of its own
215
+ responseCode: err.responseCode
216
+ },
217
+ networkRouting: err.info?.networkRouting
218
+ });
219
+ } catch (err) {
220
+ // ignore
221
+ }
222
+
223
+ if (discardJob) {
224
+ // Do not retry after a permanent rejection (5xx except 503, which is transient).
225
+ // BullMQ 6 removed Job#discard(), so the way to end a job before its attempts are
226
+ // spent is to throw UnrecoverableError. The stack is carried over because the
227
+ // 'failed' handler reports job.stacktrace[0] as the error in the failure webhook -
228
+ // constructing a bare UnrecoverableError would replace the SMTP reason with
229
+ // "UnrecoverableError" there.
230
+ let unrecoverableErr = new UnrecoverableError(err.message);
231
+ unrecoverableErr.stack = err.stack;
232
+ unrecoverableErr.code = err.code;
233
+ unrecoverableErr.responseCode = err.responseCode;
234
+ unrecoverableErr.statusCode = err.statusCode;
235
+
236
+ logger.info({
237
+ msg: 'Job discarded',
238
+ job: job.id,
239
+ account: queueEntry.account,
240
+ queueId: job.data.queueId,
241
+ messageId: job.data.messageId,
242
+ errorCode: err.code,
243
+ responseCode: err.responseCode
244
+ });
245
+
246
+ throw unrecoverableErr;
247
+ }
248
+
249
+ throw err;
250
+ }
251
+ };
252
+ }
253
+
254
+ /**
255
+ * The bookkeeping of a job BullMQ has recorded as completed: the stored message content and the
256
+ * sent marker both go. Called from the worker's 'completed' event, never from the processor
257
+ * @param {Object} job - the completed BullMQ job
258
+ * @param {Object} deps
259
+ * @param {Object} deps.redis - ioredis client
260
+ * @param {Object} deps.logger
261
+ */
262
+ async function completeSubmission(job, { redis, logger }) {
263
+ normalizeQueueId(job);
264
+
265
+ if (!job.data.account || !job.data.queueId) {
266
+ return;
267
+ }
268
+
269
+ // Independent writes, sent together: a failure of one must not keep the other from running
270
+ const { account, queueId } = job.data;
271
+ await Promise.all([
272
+ redis.hdel(outboxKey(account), queueId).catch(err => {
273
+ logger.error({ msg: 'Failed to remove queue entry', account, queueId, messageId: job.data.messageId, err });
274
+ }),
275
+ // A marker that could not be cleared expires on its own, and until then it only stops a job
276
+ // that is already done from running again
277
+ clearSent(redis, account, queueId).catch(err => {
278
+ logger.warn({ msg: 'Failed to clear the sent marker of a completed message', job: job.id, account, err });
279
+ })
280
+ ]);
281
+ }
282
+
283
+ module.exports = { createSubmitProcessor, completeSubmission, normalizeQueueId };
package/lib/templates.js CHANGED
@@ -87,10 +87,13 @@ class TemplateHandler {
87
87
  // The inverse of generateId(): an 8-byte timestamp, a 4-byte counter, then the account id.
88
88
  // Anything shorter than the fixed 12-byte header cannot be an id this module issued, and the
89
89
  // routes accept any string up to 256 characters, so a malformed id is refused as "not found"
90
- // here rather than failing on the header read.
90
+ // here rather than failing on the header read. The same goes for a header whose timestamp is no
91
+ // time a Date can hold (a template name typed in place of an id decodes to one), which made
92
+ // toISOString() throw a RangeError.
91
93
  unpackId(id) {
92
94
  let idBuf = Buffer.from(id, 'base64');
93
- if (idBuf.length < 4 + 8) {
95
+ let created = idBuf.length >= 4 + 8 ? new Date(Number(idBuf.readBigUInt64BE(0))) : null;
96
+ if (!created || isNaN(created.getTime())) {
94
97
  let err = new Error('Document was not found');
95
98
  err.code = 'NotFound';
96
99
  err.statusCode = 404;
@@ -99,7 +102,7 @@ class TemplateHandler {
99
102
 
100
103
  return {
101
104
  counter: idBuf.readUInt32BE(8),
102
- created: new Date(Number(idBuf.readBigUInt64BE(0))).toISOString(),
105
+ created: created.toISOString(),
103
106
  account: idBuf.subarray(4 + 8).toString()
104
107
  };
105
108
  }
@@ -21,12 +21,12 @@
21
21
  // and the API's HTTPS listener, so anything it does is done once per client.
22
22
 
23
23
  const tls = require('tls');
24
- const config = require('@zone-eu/wild-config');
25
24
 
26
25
  const settings = require('../settings');
27
- const { hasEnvValue, readEnvValue, getBoolean } = require('../tools');
28
26
  const { hostnamesFrom, getSelfSignedCertificate, parseCertificate, describeX509 } = require('./store');
29
27
  const { TLS_CERTIFICATE_SETTINGS, SELF_SIGNED_ID, listenerByKey } = require('./listeners');
28
+ // Whether the API listener serves TLS; resolved in a leaf module the Docker health check shares
29
+ const { apiTlsConfig } = require('../api-listener');
30
30
  const { sourcesFor, listCertificates, entryForName, listenerView } = require('./catalog');
31
31
 
32
32
  /**
@@ -39,20 +39,6 @@ function fullChain(material) {
39
39
  return material.ca && material.ca.length ? [material.cert].concat(material.ca).join('\n') : material.cert;
40
40
  }
41
41
 
42
- /**
43
- * Whether, and how, the API listener serves TLS: EENGINE_API_TLS and `[api.tls]`.
44
- *
45
- * Read from the environment and the config file, which every process shares, so the API worker
46
- * (which builds its listener from it) and the certificate reconciler (which asks whether any
47
- * listener would serve a certificate) cannot answer differently.
48
- *
49
- * @returns {Object|false} The `[api.tls]` options to build the listener from, or false when the
50
- * API serves plain HTTP
51
- */
52
- function apiTlsConfig() {
53
- return hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGINE_API_TLS')) && (config.api.tls || {}) : config.api.tls || false;
54
- }
55
-
56
42
  // How a listener negotiates, as opposed to what it serves. These belong to the listener rather
57
43
  // than to any one certificate, and they travel with the resolved options because installing a
58
44
  // context replaces it whole: tls.Server.setSecureContext() reverts everything absent from its
package/lib/tools.js CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  'use strict';
4
4
 
5
+ // Before anything that makes an HTTP request, see the module
6
+ require('./net-tos-guard');
7
+ const { accountDataKey } = require('./redis-keys');
5
8
  const { filterEmptyObjectValues } = require('./utils/filter-empty');
6
9
 
7
10
  const msgpack = require('./msgpack');
@@ -71,7 +74,8 @@ const tls = require('tls');
71
74
  const net = require('net');
72
75
  const { SocksClient } = require('socks');
73
76
  const { createWebhookLookup, WEBHOOK_EGRESS_POLICY } = require('./webhook-egress');
74
- const { readEnvValue } = require('./read-env-value');
77
+ const { readEnvValue, hasEnvValue } = require('./read-env-value');
78
+ const { getBoolean } = require('./get-boolean');
75
79
 
76
80
  const AGENT_OPTS = {
77
81
  strictContentLength: false,
@@ -1587,31 +1591,7 @@ module.exports = {
1587
1591
  return scoredAddresses[0].address;
1588
1592
  },
1589
1593
 
1590
- getBoolean(value) {
1591
- if (typeof value === 'boolean') {
1592
- return value;
1593
- }
1594
-
1595
- if (typeof value === 'string') {
1596
- value = value.trim();
1597
- }
1598
-
1599
- if (typeof value === 'string' && !isNaN(value) && /^[0-9]+$/.test(value)) {
1600
- value = Number(value);
1601
- }
1602
-
1603
- if (typeof value === 'number') {
1604
- return !!value;
1605
- }
1606
-
1607
- if (typeof value === 'string') {
1608
- // `on` and `enabled` are what several operators write in env files, and joi and
1609
- // resolveHttpProxy() already read `on` as true
1610
- return /^(y|true|on$|enabled$)/i.test(value);
1611
- }
1612
-
1613
- return false; // ????
1614
- },
1594
+ getBoolean,
1615
1595
 
1616
1596
  async checkLicense(license) {
1617
1597
  let verifyKeys = [
@@ -2826,9 +2806,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2826
2806
  return false;
2827
2807
  },
2828
2808
 
2829
- hasEnvValue(key) {
2830
- return key in process.env || `${key}_FILE` in process.env;
2831
- },
2809
+ hasEnvValue,
2832
2810
 
2833
2811
  /**
2834
2812
  * Reads a comma-separated environment value as a trimmed, blank-free array.
@@ -3001,7 +2979,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
3001
2979
  let hopsAllowed = 20;
3002
2980
 
3003
2981
  while (redirect++ < hopsAllowed) {
3004
- let oauth2DataStr = await redis.hget(`${REDIS_PREFIX}iad:${account}`, 'oauth2');
2982
+ let oauth2DataStr = await redis.hget(accountDataKey(account), 'oauth2');
3005
2983
  if (!oauth2DataStr) {
3006
2984
  let error = new Error(`Missing account data for delegated account "${account}"`);
3007
2985
  throw error;
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ // Which Redis reply errors say "not now" rather than "never". Dependency-free, so pure modules and
4
+ // their tests can ask.
5
+ //
6
+ // A cut connection never reaches the code as an error (ioredis runs with maxRetriesPerRequest null
7
+ // and sends the command again once it has reconnected), so these replies are how a Redis problem
8
+ // does reach it: OOM for every write and script while used memory is over maxmemory, LOADING while a
9
+ // restarted Redis loads its dataset, BUSY while a script runs past its time limit, READONLY and
10
+ // MASTERDOWN around a failover, MISCONF while snapshots fail, the cluster ones while slots move. All
11
+ // of them clear up without anything changing on our side, so a caller that holds work durably (a
12
+ // queued arrival, a retried job) keeps it rather than drop it.
13
+
14
+ const TRANSIENT_REPLY = /^(OOM|LOADING|BUSY|READONLY|MASTERDOWN|MISCONF|TRYAGAIN|CLUSTERDOWN|NOREPLICAS)\b/;
15
+
16
+ /**
17
+ * Whether an error is a Redis reply that a later attempt can get past. EXECABORT counts when every
18
+ * command that failed inside the transaction did so for such a reason (ioredis collects them in
19
+ * `previousErrors`); a transaction refused for a syntax error fails the same way every time. An
20
+ * error that wraps one (its `cause`) counts as well
21
+ * @param {Error} err
22
+ * @returns {boolean}
23
+ */
24
+ function isTransientRedisError(err, depth = 0) {
25
+ if (!err || depth > 5) {
26
+ return false;
27
+ }
28
+ if (err.name !== 'ReplyError' || typeof err.message !== 'string') {
29
+ return isTransientRedisError(err.cause, depth + 1);
30
+ }
31
+ if (TRANSIENT_REPLY.test(err.message)) {
32
+ return true;
33
+ }
34
+ return (
35
+ /^EXECABORT\b/.test(err.message) &&
36
+ Array.isArray(err.previousErrors) &&
37
+ err.previousErrors.length > 0 &&
38
+ // An explicit callback: every() would hand in the index as the depth, so the seventh
39
+ // failed command of a transaction read as past the depth limit, a permanent error
40
+ err.previousErrors.every(previous => isTransientRedisError(previous, depth + 1))
41
+ );
42
+ }
43
+
44
+ module.exports = { isTransientRedisError };
@@ -6,6 +6,7 @@
6
6
  // decisions were only tested through the helpers it calls. Everything with a side effect is passed
7
7
  // in, see createWebhookProcessor().
8
8
 
9
+ const { accountDataKey } = require('./redis-keys');
9
10
  const { UnrecoverableError, DelayedError } = require('bullmq');
10
11
 
11
12
  const { redactUrlCredentials, splitUrlCredentials } = require('./tools');
@@ -21,13 +22,11 @@ const {
21
22
  deliveryCustomHeaders,
22
23
  isRouteMappingMissing
23
24
  } = require('./webhook-routing');
24
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
25
+ const { ACCOUNT_DELETED_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
25
26
 
26
27
  // The payload fields of `data` that are logged as they are; anything else only marks it partial
27
28
  const LOGGED_DATA_KEYS = new Set(['id', 'uid', 'path', 'messageId']);
28
29
 
29
- const getAccountKey = account => `${REDIS_PREFIX}iad:${account}`;
30
-
31
30
  /**
32
31
  * Log context shared by every line about one job
33
32
  * @param {Object} job - BullMQ job
@@ -152,7 +151,7 @@ async function waitOutPenalty(job, token, webhooks, deps) {
152
151
  */
153
152
  async function planDelivery(job, token, deps) {
154
153
  const { redis, settings, logger, openAccountField } = deps;
155
- let accountKey = getAccountKey(job.data.account);
154
+ let accountKey = accountDataKey(job.data.account);
156
155
 
157
156
  // Keep the route id reachable for the completed/failed event handlers, which see this same
158
157
  // job instance after _route has been deleted from the payload. Stashed before the early
@@ -14,10 +14,8 @@
14
14
  // one place makes that dependency explicit and unit-testable (see test/worker-rpc-error-test.js).
15
15
  // `permanent` is nodemailer's own verdict on that reply, which the predicate prefers when present.
16
16
  //
17
- // These helpers are used at the delivery-error RPC path - the imap/submit workers and the main-thread
18
- // hub (server.js) that relays between them. The other workers (webhooks/export/smtp/api)
19
- // keep their own inline resp-handler copies: they never carry a delivery error, so `responseCode`
20
- // does not apply to them. Route a delivery error through a new worker and it must switch to these too.
17
+ // Every worker's RPC goes through these helpers (lib/worker-rpc.js on the worker side, server.js as
18
+ // the hub that relays between workers), so a field added here reaches every hop.
21
19
  const RPC_ERROR_FIELDS = ['code', 'statusCode', 'responseCode', 'permanent', 'info'];
22
20
 
23
21
  /**
@@ -27,7 +25,14 @@ const RPC_ERROR_FIELDS = ['code', 'statusCode', 'responseCode', 'permanent', 'in
27
25
  * @returns {Object} Payload with `error` (the message) plus every present RPC_ERROR_FIELD
28
26
  */
29
27
  function packRpcError(err) {
30
- let payload = { error: err.message };
28
+ // A command may reject with something that is not an Error (a string, undefined). Reading
29
+ // .message off that used to throw inside the reply handler, a rejection nothing caught
30
+ if (!err || typeof err !== 'object') {
31
+ return { error: String(err) };
32
+ }
33
+ // Never empty: the receiving side tells an error reply from a result by this field being set,
34
+ // so an Error with no message would otherwise arrive as a successful, empty response
35
+ let payload = { error: err.message || err.name || 'Error' };
31
36
  for (let field of RPC_ERROR_FIELDS) {
32
37
  if (err[field] != null) {
33
38
  payload[field] = err[field];
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ // The worker side of the RPC protocol between a worker thread and the main thread (server.js).
4
+ //
5
+ // A worker calls the main thread with `{ cmd: 'call', mid, message }` and gets back
6
+ // `{ cmd: 'resp', mid, response }` or `{ cmd: 'resp', mid, error, ...fields }`; the main thread
7
+ // calls a worker the same way. Every worker used to carry its own copy of both halves, and the
8
+ // copies had drifted: some rebuilt errors without `responseCode` and `permanent`, one call() did
9
+ // not guard postMessage, and no reply guarded against a response that cannot be cloned, which
10
+ // would surface as a rejection nothing handles and end the worker. Errors cross the hop through
11
+ // lib/worker-rpc-error.js, the same field list everywhere.
12
+ //
13
+ // The main thread's hub (server.js) routes calls between workers and keeps its own bookkeeping
14
+ // (the worker each call went to, rejecting them when it exits), so it does not use this module.
15
+
16
+ const { packRpcError, unpackRpcError } = require('./worker-rpc-error');
17
+
18
+ /**
19
+ * Creates the calling half: call() sends a command to the main thread and settles when its
20
+ * response arrives or the timeout passes, handleResponse() settles a call from a received message.
21
+ *
22
+ * @param {Object} opts
23
+ * @param {Object} opts.port - the MessagePort to talk over (parentPort)
24
+ * @param {Number} opts.defaultTimeout - lowest timeout in ms, a command may ask for longer
25
+ * @param {String} opts.timeoutTag - short marker in the timeout message that names the worker
26
+ * @returns {{ call: Function, handleResponse: Function, pendingCount: Function }}
27
+ */
28
+ function createRpcClient({ port, defaultTimeout, timeoutTag }) {
29
+ const pending = new Map();
30
+ let mids = 0;
31
+
32
+ function call(message, transferList) {
33
+ return new Promise((resolve, reject) => {
34
+ const mid = `${Date.now()}:${++mids}`;
35
+
36
+ const ttl = Math.max(message.timeout || 0, defaultTimeout || 0);
37
+ const timer = setTimeout(() => {
38
+ pending.delete(mid);
39
+ const err = new Error(`Timeout waiting for command response [${timeoutTag}]`);
40
+ err.statusCode = 504;
41
+ err.code = 'Timeout';
42
+ err.ttl = ttl;
43
+ reject(err);
44
+ }, ttl);
45
+
46
+ pending.set(mid, { resolve, reject, timer });
47
+
48
+ try {
49
+ port.postMessage({ cmd: 'call', mid, message }, transferList);
50
+ } catch (err) {
51
+ clearTimeout(timer);
52
+ pending.delete(mid);
53
+ reject(err);
54
+ }
55
+ });
56
+ }
57
+
58
+ /**
59
+ * Settles the call a response belongs to
60
+ * @param {Object} message - a received message
61
+ * @returns {Boolean} true when the message was the response to a pending call
62
+ */
63
+ function handleResponse(message) {
64
+ if (!message || message.cmd !== 'resp' || !message.mid || !pending.has(message.mid)) {
65
+ return false;
66
+ }
67
+
68
+ const { resolve, reject, timer } = pending.get(message.mid);
69
+ clearTimeout(timer);
70
+ pending.delete(message.mid);
71
+
72
+ if (message.error) {
73
+ reject(unpackRpcError(message));
74
+ } else {
75
+ resolve(message.response);
76
+ }
77
+ return true;
78
+ }
79
+
80
+ return { call, handleResponse, pendingCount: () => pending.size };
81
+ }
82
+
83
+ /**
84
+ * Runs a command the main thread sent and posts its result back. Never rejects: a response that
85
+ * cannot be sent (a value postMessage cannot clone, a closed port) is answered with an error
86
+ * instead, and a failure to send even that is logged rather than left to the global handler.
87
+ *
88
+ * @param {Object} port - the MessagePort to answer over (parentPort)
89
+ * @param {Object} message - the received `{ cmd: 'call', mid, message }`
90
+ * @param {Function} handler - async (command) => response
91
+ * @param {Object} opts
92
+ * @param {Object} opts.logger - where an undeliverable response is reported
93
+ * @param {Function} [opts.onError] - (err, message) => void, sees a command's error before it is sent
94
+ * @returns {Promise<void>}
95
+ */
96
+ async function respond(port, message, handler, { logger, onError }) {
97
+ const mid = message.mid;
98
+
99
+ const send = payload => {
100
+ try {
101
+ port.postMessage(payload);
102
+ } catch (err) {
103
+ try {
104
+ port.postMessage(Object.assign({ cmd: 'resp', mid }, packRpcError(err)));
105
+ } catch (fallbackErr) {
106
+ logger.error({ msg: 'Failed to send a command response', mid, err: fallbackErr });
107
+ }
108
+ }
109
+ };
110
+
111
+ let response;
112
+ try {
113
+ response = await handler(message.message);
114
+ } catch (err) {
115
+ if (onError) {
116
+ try {
117
+ onError(err, message);
118
+ } catch (hookErr) {
119
+ logger.error({ msg: 'Failed to process a command error', mid, err: hookErr });
120
+ }
121
+ }
122
+ send(Object.assign({ cmd: 'resp', mid }, packRpcError(err)));
123
+ return;
124
+ }
125
+
126
+ send({ cmd: 'resp', mid, response });
127
+ }
128
+
129
+ /**
130
+ * Whether a received message is a command for this worker to run
131
+ * @param {Object} message
132
+ * @returns {Boolean}
133
+ */
134
+ function isCall(message) {
135
+ return !!(message && message.cmd === 'call' && message.mid);
136
+ }
137
+
138
+ module.exports = { createRpcClient, respond, isCall };