emailengine-app 2.83.1 → 2.84.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.
Files changed (83) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +1 -1
  4. package/SECURITY.md +126 -47
  5. package/data/google-crawlers.json +1 -1
  6. package/gettext-extract.js +95 -15
  7. package/lib/api-routes/outbox-routes.js +132 -9
  8. package/lib/api-routes/permission-map.js +11 -1
  9. package/lib/consts.js +3 -5
  10. package/lib/email-client/base-client.js +44 -20
  11. package/lib/email-client/credential-errors.js +3 -31
  12. package/lib/email-client/imap/idle-settings.js +44 -0
  13. package/lib/email-client/imap/mailbox.js +19 -7
  14. package/lib/email-client/imap-client.js +3 -21
  15. package/lib/email-client/smtp-pool-manager.js +25 -6
  16. package/lib/enum-descriptions.js +7 -0
  17. package/lib/export.js +46 -42
  18. package/lib/field-usage.js +4 -0
  19. package/lib/handlebars-helpers.js +4 -0
  20. package/lib/imapproxy/imap-core/lib/commands/starttls.js +4 -2
  21. package/lib/imapproxy/imap-core/lib/imap-server.js +44 -11
  22. package/lib/imapproxy/proxy-handoff.js +10 -1
  23. package/lib/logger.js +3 -2
  24. package/lib/message-port-stream.js +23 -0
  25. package/lib/network-errors.js +50 -0
  26. package/lib/oauth/gmail.js +5 -1
  27. package/lib/oauth/mail-ru.js +5 -1
  28. package/lib/oauth/outlook.js +5 -1
  29. package/lib/oauth/pubsub/google.js +3 -2
  30. package/lib/oauth/token-fetch.js +2 -3
  31. package/lib/outbox.js +338 -10
  32. package/lib/queue-browser/definitions.js +132 -0
  33. package/lib/queue-browser/format.js +387 -0
  34. package/lib/queue-browser/index.js +568 -0
  35. package/lib/queue-job-actions.js +75 -0
  36. package/lib/queue-retention.js +53 -1
  37. package/lib/routes-ui.js +5 -0
  38. package/lib/schemas.js +42 -2
  39. package/lib/security-headers.js +2 -24
  40. package/lib/sub-script.js +10 -3
  41. package/lib/token-permission-view.js +1 -1
  42. package/lib/tools.js +16 -2
  43. package/lib/ui-routes/account-routes.js +6 -0
  44. package/lib/ui-routes/imap-idle-field.js +42 -0
  45. package/lib/ui-routes/queue-routes.js +371 -0
  46. package/lib/utils/status-error.js +21 -0
  47. package/package.json +18 -20
  48. package/prepare-bundle-deps.sh +1 -1
  49. package/sbom.json +1 -1
  50. package/server.js +10 -0
  51. package/static/css/flyonui.css +1 -1
  52. package/static/css/src/app.tailwind.css +2 -0
  53. package/static/js/queues.js +117 -0
  54. package/static/licenses.html +127 -251
  55. package/translations/README.md +3 -2
  56. package/translations/messages.pot +280 -265
  57. package/views/accounts/account.hbs +31 -0
  58. package/views/accounts/edit.hbs +2 -0
  59. package/views/config/service.hbs +1 -2
  60. package/views/dashboard.hbs +2 -2
  61. package/views/partials/queue_cell_account.hbs +20 -0
  62. package/views/partials/queue_cell_failure.hbs +6 -0
  63. package/views/partials/queue_clean_items.hbs +9 -0
  64. package/views/partials/queue_clean_modal.hbs +9 -0
  65. package/views/partials/queue_entry_actions.hbs +41 -0
  66. package/views/partials/queue_job_actions.hbs +15 -0
  67. package/views/partials/queue_pause_controls.hbs +18 -0
  68. package/views/partials/queue_retention_note.hbs +49 -0
  69. package/views/partials/queue_rows_export.hbs +58 -0
  70. package/views/partials/queue_rows_notify.hbs +73 -0
  71. package/views/partials/queue_rows_submit.hbs +70 -0
  72. package/views/partials/side_menu.hbs +1 -1
  73. package/views/partials/ui/tooltip.hbs +5 -3
  74. package/views/queues/index.hbs +104 -0
  75. package/views/queues/job.hbs +224 -0
  76. package/views/queues/queue.hbs +93 -0
  77. package/views/webhooks/webhook.hbs +3 -0
  78. package/workers/api.js +0 -4
  79. package/workers/imap.js +10 -3
  80. package/workers/smtp.js +16 -1
  81. package/workers/submit.js +19 -5
  82. package/workers/webhooks.js +13 -0
  83. package/lib/api-routes/bull-board-routes.js +0 -56
@@ -15,6 +15,11 @@ const { Writable, Readable, pipeline } = require('stream');
15
15
  const DEFAULT_CREDIT_WINDOW = 1024 * 1024;
16
16
  const ACK_BATCH_FRACTION = 4;
17
17
 
18
+ // How long a write may wait for credit before the transfer is abandoned. A consumer that stops
19
+ // reading without disconnecting never cancels, and the IMAP download feeding this writer would
20
+ // hold the account's mailbox lock for as long as its socket lived.
21
+ const DEFAULT_STALL_TIMEOUT = 5 * 60 * 1000;
22
+
18
23
  class MessagePortWritable extends Writable {
19
24
  constructor(messagePort, opts) {
20
25
  super();
@@ -24,6 +29,9 @@ class MessagePortWritable extends Writable {
24
29
  this.credit = (opts && opts.creditWindow) || DEFAULT_CREDIT_WINDOW;
25
30
  this.pendingWrite = null;
26
31
 
32
+ this.stallTimeout = (opts && opts.stallTimeout) || DEFAULT_STALL_TIMEOUT;
33
+ this.stallTimer = null;
34
+
27
35
  // The reader side posts { cancel: true } when it is torn down (e.g. the
28
36
  // HTTP client aborted the download). Stop the transfer so the upstream
29
37
  // source - and the IMAP lock it holds - is released.
@@ -37,7 +45,11 @@ class MessagePortWritable extends Writable {
37
45
  if (this.pendingWrite && this.credit > 0) {
38
46
  let done = this.pendingWrite;
39
47
  this.pendingWrite = null;
48
+ clearTimeout(this.stallTimer);
40
49
  done();
50
+ } else if (this.pendingWrite) {
51
+ // Credit is still short, but the reader did take something: that is progress
52
+ this.stallTimer.refresh();
41
53
  }
42
54
  }
43
55
  };
@@ -110,6 +122,12 @@ class MessagePortWritable extends Writable {
110
122
  }
111
123
  // Out of credit: the next write waits until the reader has taken some of what was sent
112
124
  this.pendingWrite = done;
125
+ this.stallTimer = setTimeout(() => {
126
+ let err = new Error('Message stream consumer stopped reading');
127
+ err.code = 'ConsumerStalled';
128
+ this.destroy(err);
129
+ }, this.stallTimeout);
130
+ this.stallTimer.unref();
113
131
  }
114
132
 
115
133
  _final(done) {
@@ -121,6 +139,7 @@ class MessagePortWritable extends Writable {
121
139
  _destroy(err, done) {
122
140
  // A write waiting for credit is abandoned with the stream; destroy() does not wait for it
123
141
  this.pendingWrite = null;
142
+ clearTimeout(this.stallTimer);
124
143
 
125
144
  // Abnormal termination: tell the reader so a truncated transfer is not
126
145
  // mistaken for a complete message, then release the port.
@@ -278,6 +297,10 @@ function pipeToMessagePort(source, writable, logger) {
278
297
  }
279
298
  return;
280
299
  }
300
+ if (err.code === 'ConsumerStalled') {
301
+ logger.warn?.({ msg: 'Message stream transfer abandoned, the consumer stopped reading', err });
302
+ return;
303
+ }
281
304
  if (typeof logger.error === 'function') {
282
305
  logger.error({ msg: 'Message stream transfer failed', err });
283
306
  }
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ // How a failed outbound HTTP request is told apart from a refused or broken one. undici raises
4
+ // every connection failure as a generic TypeError ("fetch failed", "terminated") with the real
5
+ // DNS/socket/timeout error on err.cause, so a check of err.code alone misses all of them.
6
+ //
7
+ // Dependency-free apart from consts, so lib/logger.js can use it without a require cycle.
8
+
9
+ const { TRANSIENT_NETWORK_CODES } = require('./consts');
10
+
11
+ // How far down a cause chain the transient check looks. A chain is not guaranteed to be finite - an
12
+ // error may cite itself - so the walk is bounded rather than trusting it to end.
13
+ const MAX_CAUSE_DEPTH = 5;
14
+
15
+ /**
16
+ * Failing to reach a remote endpoint is a connection problem, not a rejected credential or a bug.
17
+ *
18
+ * The whole cause chain is searched, not one level: a caller that wraps an undici failure in an
19
+ * error of its own pushes the code one level deeper (lib/oauth/external-account-signer.js does
20
+ * exactly that for its Workload Identity Federation requests).
21
+ *
22
+ * @param {Error} err - The error to check
23
+ * @returns {boolean} True if the error, or anything it was caused by, is a transient network failure
24
+ */
25
+ function isTransientNetworkError(err) {
26
+ for (let cause = err, depth = 0; cause && typeof cause === 'object' && depth < MAX_CAUSE_DEPTH; cause = cause.cause, depth++) {
27
+ if (TRANSIENT_NETWORK_CODES.has(cause.code)) {
28
+ return true;
29
+ }
30
+ }
31
+
32
+ return false;
33
+ }
34
+
35
+ /**
36
+ * Copies the code of an undici failure from err.cause onto the error itself, so callers that read
37
+ * err.code (and the webhook and log payloads built from it) see ECONNRESET or UND_ERR_BODY_TIMEOUT
38
+ * rather than nothing. Leaves an error that already carries a code alone.
39
+ *
40
+ * @param {Error} err - The error thrown by fetch()
41
+ * @returns {Error} The same error
42
+ */
43
+ function promoteCauseCode(err) {
44
+ if (err && !err.code && err.cause && err.cause.code) {
45
+ err.code = err.cause.code;
46
+ }
47
+ return err;
48
+ }
49
+
50
+ module.exports = { isTransientNetworkError, promoteCauseCode };
@@ -5,6 +5,7 @@ const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, pa
5
5
  const crypto = require('crypto');
6
6
 
7
7
  const { fetch: fetchCmd } = require('undici');
8
+ const { promoteCauseCode } = require('../network-errors');
8
9
 
9
10
  const { ExternalAccountSigner } = require('./external-account-signer');
10
11
  const { fetchTokenRequest } = require('./token-fetch');
@@ -733,7 +734,10 @@ class GmailOauth {
733
734
 
734
735
  let startTime = Date.now();
735
736
 
736
- let res = await fetchCmd(url, reqData);
737
+ let res = await fetchCmd(url, reqData).catch(err => {
738
+ // undici puts the network code on err.cause; callers read err.code
739
+ throw promoteCauseCode(err);
740
+ });
737
741
 
738
742
  let reqTime = Date.now() - startTime;
739
743
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  const packageData = require('../../package.json');
4
4
  const { fetch: fetchCmd } = require('undici');
5
+ const { promoteCauseCode } = require('../network-errors');
5
6
  const { fetchTokenRequest } = require('./token-fetch');
6
7
  const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
7
8
 
@@ -304,7 +305,10 @@ class MailRuOauth {
304
305
  const requestUrl = new URL(url);
305
306
  requestUrl.searchParams.set('access_token', accessToken);
306
307
 
307
- let res = await fetchCmd(requestUrl.href, reqData);
308
+ let res = await fetchCmd(requestUrl.href, reqData).catch(err => {
309
+ // undici puts the network code on err.cause; callers read err.code
310
+ throw promoteCauseCode(err);
311
+ });
308
312
 
309
313
  if (!res.ok) {
310
314
  let err = new Error('OAuth2 request failed');
@@ -4,6 +4,7 @@ const packageData = require('../../package.json');
4
4
  const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
5
5
 
6
6
  const { fetch: fetchCmd } = require('undici');
7
+ const { promoteCauseCode } = require('../network-errors');
7
8
  const { fetchTokenRequest } = require('./token-fetch');
8
9
 
9
10
  // Individual MS Graph API scope names for detection
@@ -594,7 +595,10 @@ class OutlookOauth {
594
595
  }
595
596
 
596
597
  let startTime = Date.now();
597
- let res = await fetchCmd(url, reqData);
598
+ let res = await fetchCmd(url, reqData).catch(err => {
599
+ // undici puts the network code on err.cause; callers read err.code
600
+ throw promoteCauseCode(err);
601
+ });
598
602
  let reqTime = Date.now() - startTime;
599
603
 
600
604
  if (!res.ok) {
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const { redis } = require('../../db');
4
- const { REDIS_PREFIX, TRANSIENT_NETWORK_CODES } = require('../../consts');
4
+ const { REDIS_PREFIX } = require('../../consts');
5
+ const { isTransientNetworkError } = require('../../network-errors');
5
6
  const logger = require('../../logger').child({
6
7
  component: 'google-subscriber'
7
8
  });
@@ -298,7 +299,7 @@ class PubSubInstance {
298
299
  throw err;
299
300
  }
300
301
  // Transient network errors are expected for long-polling connections
301
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
302
+ if (isTransientNetworkError(err)) {
302
303
  logger.warn({ msg: 'Transient error pulling subscription messages', app: this.app, code: err.code });
303
304
  err.retryDelay = 5000;
304
305
  err.eeLogged = true;
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { fetch: fetchCmd } = require('undici');
4
4
  const { httpAgent } = require('../tools');
5
+ const { promoteCauseCode } = require('../network-errors');
5
6
 
6
7
  /**
7
8
  * Performs a token-endpoint request, and says which endpoint failed when the request never got there.
@@ -35,9 +36,7 @@ async function fetchTokenRequest(url, options, context, route) {
35
36
  } catch (err) {
36
37
  // The cause carries the actionable code. Promoted onto the error itself so the connectError
37
38
  // webhook has something to report - the transient check consults both, so no verdict changes.
38
- if (!err.code && err.cause && err.cause.code) {
39
- err.code = err.cause.code;
40
- }
39
+ promoteCauseCode(err);
41
40
 
42
41
  err.tokenRequest = Object.assign({ url, method: (options && options.method) || 'get', error: err.message, errorCode: err.code }, context);
43
42
  err.message = `Token request to ${url} failed${err.code ? ` [${err.code}]` : ''}: ${(err.cause && err.cause.message) || err.message}`;
package/lib/outbox.js CHANGED
@@ -4,6 +4,17 @@ const { submitQueue, redis } = require('./db');
4
4
  const { REDIS_PREFIX } = require('../lib/consts');
5
5
  const msgpack = require('./msgpack');
6
6
  const { nextAttemptOfStoredJob } = require('./delivery-error');
7
+ const { readEnvValue } = require('./read-env-value');
8
+ const { getByteSize } = require('./tools');
9
+ const { statusError } = require('./utils/status-error');
10
+ const { retryFailedJob, promoteDelayedJob, assertJobState } = require('./queue-job-actions');
11
+ const {
12
+ selectFailedContentToDrop,
13
+ FAILED_JOB_RETENTION_AGE,
14
+ FAILED_JOB_RETENTION_COUNT,
15
+ DEFAULT_FAILED_CONTENT_RETENTION_COUNT,
16
+ DEFAULT_FAILED_CONTENT_RETENTION_SIZE
17
+ } = require('./queue-retention');
7
18
 
8
19
  // Job reads and removals are issued in bounded batches. ioredis writes each command as it is
9
20
  // issued, so a batch costs one round trip rather than one per job, while the bound keeps an account
@@ -20,6 +31,47 @@ function outboxKey(account) {
20
31
  return `${REDIS_PREFIX}iaq:${account}`;
21
32
  }
22
33
 
34
+ // The contents retained for messages whose delivery failed for good, so they can be retried: a
35
+ // hash whose field names the account and the queue ID and whose value records when the failure
36
+ // happened and how large the content is. A hash rather than a sorted set because every operation
37
+ // but the trim addresses one message, and a hash field is removed by name; the trim reads the
38
+ // whole thing, which the count bound keeps small. Its own key rather than a field convention
39
+ // inside the account hashes, because the bounds apply across every account at once, and `iaqf`
40
+ // cannot collide with an account's `iaq:<account>` hash, whatever the account is called.
41
+ const FAILED_CONTENT_KEY = `${REDIS_PREFIX}iaqf`;
42
+
43
+ function retainedField(account, queueId) {
44
+ return JSON.stringify([account, queueId]);
45
+ }
46
+
47
+ /**
48
+ * An environment bound, with `0` meaning "none" rather than "the default".
49
+ *
50
+ * @param {string} key - Environment variable
51
+ * @param {Function} parse - Parser for a value that is set
52
+ * @param {number} defaultValue - Used when the variable is unset or unparsable
53
+ * @returns {number}
54
+ */
55
+ function envBound(key, parse, defaultValue) {
56
+ const raw = readEnvValue(key);
57
+ if (raw === undefined || raw === null || raw === '') {
58
+ return defaultValue;
59
+ }
60
+ const value = parse(raw);
61
+ return typeof value === 'number' && value >= 0 && !isNaN(value) ? value : defaultValue;
62
+ }
63
+
64
+ // How much failed content is kept. Setting either count or size to 0 keeps none, which is the
65
+ // behavior before retries existed: the content went the moment the last attempt failed. The
66
+ // count is capped at the failed-job retention count and the age is the failed-job age, so
67
+ // BullMQ's own `removeOnFail` policy never removes a job before its content is dropped here -
68
+ // the record of a failure always outlives the content it would need to retry.
69
+ const FAILED_CONTENT_LIMITS = {
70
+ maxCount: Math.min(envBound('EENGINE_QUEUE_KEEP_FAILED_CONTENT', Number, DEFAULT_FAILED_CONTENT_RETENTION_COUNT), FAILED_JOB_RETENTION_COUNT),
71
+ maxBytes: envBound('EENGINE_QUEUE_KEEP_FAILED_CONTENT_SIZE', getByteSize, DEFAULT_FAILED_CONTENT_RETENTION_SIZE),
72
+ maxAge: FAILED_JOB_RETENTION_AGE
73
+ };
74
+
23
75
  /**
24
76
  * Decodes a message stored in an account's outbox hash.
25
77
  *
@@ -46,14 +98,14 @@ function decodeQueueEntry(entryBuf) {
46
98
  return queueEntry;
47
99
  }
48
100
 
49
- function formatQueueEntry(job) {
101
+ function formatQueueEntry(job, state) {
50
102
  let scheduled = job.timestamp + (Number(job.opts.delay) || 0);
51
103
 
52
104
  let nextAttempt = nextAttemptOfStoredJob(job, scheduled);
53
105
 
54
106
  return Object.assign(job.data, {
55
107
  created: new Date(Number(job.data.created || job.timestamp)).toISOString(),
56
- //status: job.name,
108
+ state,
57
109
  progress: job.progress,
58
110
  attemptsMade: job.attemptsMade,
59
111
  attempts: job.opts.attempts,
@@ -122,7 +174,9 @@ async function list(options) {
122
174
  let ranges = selectPageRanges(JOB_STATES, jobCounts, page * pageSize, pageSize);
123
175
 
124
176
  let idsPerRange = await Promise.all(ranges.map(range => submitQueue.getRanges([range.state], range.start, range.end, true)));
125
- let jobIds = idsPerRange.flat();
177
+ // Each ID is read from a known state's list, which is what the entry reports as its state -
178
+ // there is no second round trip asking the job
179
+ let jobIds = idsPerRange.flatMap((ids, i) => ids.map(jobId => ({ jobId, state: ranges[i].state })));
126
180
 
127
181
  // Queue#getJobs() is this same id-fetch-plus-getJob, but with an unbounded Promise.all and no
128
182
  // per-entry error handling: one unreadable job would reject the whole page. Batched here
@@ -130,9 +184,10 @@ async function list(options) {
130
184
  let messages = [];
131
185
  for (let i = 0; i < jobIds.length; i += BATCH_SIZE) {
132
186
  let batch = await Promise.all(
133
- jobIds.slice(i, i + BATCH_SIZE).map(async jobId => {
187
+ jobIds.slice(i, i + BATCH_SIZE).map(async ({ jobId, state }) => {
134
188
  try {
135
- return await submitQueue.getJob(jobId);
189
+ let job = await submitQueue.getJob(jobId);
190
+ return job ? formatQueueEntry(job, state) : null;
136
191
  } catch (err) {
137
192
  logger.error({ msg: 'Failed to retrieve message info from outbox', jobId, err });
138
193
  return null;
@@ -140,9 +195,9 @@ async function list(options) {
140
195
  })
141
196
  );
142
197
 
143
- for (let job of batch) {
144
- if (job) {
145
- messages.push(formatQueueEntry(job));
198
+ for (let entry of batch) {
199
+ if (entry) {
200
+ messages.push(entry);
146
201
  }
147
202
  }
148
203
  }
@@ -189,6 +244,7 @@ async function del(options) {
189
244
  // Delete message content
190
245
  try {
191
246
  let res = await redis.hdel(outboxKey(job.data.account), job.data.queueId);
247
+ await releaseFailedContent({ account: job.data.account, queueId: job.data.queueId });
192
248
  logger.info({ msg: 'Removed queued message', res, account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId });
193
249
  } catch (err) {
194
250
  logger.error({ msg: 'Failed to remove queued message', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId, err });
@@ -230,7 +286,7 @@ async function get(options) {
230
286
  throw err;
231
287
  }
232
288
 
233
- return formatQueueEntry(job);
289
+ return formatQueueEntry(job, await job.getState());
234
290
  }
235
291
 
236
292
  /**
@@ -262,6 +318,15 @@ async function get(options) {
262
318
  async function removeJobs(queueIds, options) {
263
319
  const { account, logger } = options;
264
320
 
321
+ // The retained failed contents among these go with the outbox hash the caller unlinks
322
+ if (queueIds.length) {
323
+ try {
324
+ await redis.hdel(FAILED_CONTENT_KEY, ...queueIds.map(queueId => retainedField(account, queueId)));
325
+ } catch (err) {
326
+ logger.error({ msg: 'Failed to release the retained failed messages of an account', account, err });
327
+ }
328
+ }
329
+
265
330
  let removed = 0;
266
331
 
267
332
  for (let i = 0; i < queueIds.length; i += BATCH_SIZE) {
@@ -287,6 +352,269 @@ async function removeJobs(queueIds, options) {
287
352
  return removed;
288
353
  }
289
354
 
355
+ /**
356
+ * The retained failed contents, as the hash holds them.
357
+ *
358
+ * @returns {Promise<Array<{account: string, queueId: string, size: number, finishedOn: number, field: string}>>}
359
+ * An entry whose field cannot be read carries `unreadable: true` and is dropped by the next prune
360
+ */
361
+ async function listRetainedFailedContent() {
362
+ const raw = await redis.hgetall(FAILED_CONTENT_KEY);
363
+
364
+ const entries = [];
365
+ for (const [field, value] of Object.entries(raw || {})) {
366
+ let decoded;
367
+ let record;
368
+ try {
369
+ decoded = JSON.parse(field);
370
+ record = JSON.parse(value);
371
+ } catch (err) {
372
+ decoded = null;
373
+ }
374
+ if (Array.isArray(decoded) && typeof decoded[0] === 'string' && typeof decoded[1] === 'string' && record && typeof record === 'object') {
375
+ entries.push({ account: decoded[0], queueId: decoded[1], size: Number(record.s) || 0, finishedOn: Number(record.t) || 0, field });
376
+ } else {
377
+ entries.push({ account: null, queueId: null, size: 0, finishedOn: 0, field, unreadable: true });
378
+ }
379
+ }
380
+
381
+ return entries;
382
+ }
383
+
384
+ /**
385
+ * Removes the content of the given retained entries and forgets them.
386
+ *
387
+ * @param {Array<Object>} entries - Entries from listRetainedFailedContent()
388
+ * @param {Object} [options]
389
+ * @param {Object} [options.logger] - Logger instance
390
+ * @returns {Promise<number>} How many entries were dropped
391
+ */
392
+ async function dropFailedContent(entries, options) {
393
+ if (!entries.length) {
394
+ return 0;
395
+ }
396
+
397
+ const logger = (options && options.logger) || null;
398
+
399
+ const pipeline = redis.multi();
400
+ for (const entry of entries) {
401
+ if (entry.account) {
402
+ pipeline.hdel(outboxKey(entry.account), entry.queueId);
403
+ }
404
+ }
405
+ pipeline.hdel(FAILED_CONTENT_KEY, ...entries.map(entry => entry.field));
406
+ await pipeline.exec();
407
+
408
+ if (logger) {
409
+ for (const entry of entries) {
410
+ logger.info({ msg: 'Dropped the content of a failed message', account: entry.account, queueId: entry.queueId, size: entry.size });
411
+ }
412
+ }
413
+
414
+ return entries.length;
415
+ }
416
+
417
+ /**
418
+ * Keeps the content of a message whose delivery just failed for good, so it can be retried.
419
+ *
420
+ * Called from the submit worker's `failed` handler in place of the deletion it used to do. The
421
+ * bounds in FAILED_CONTENT_LIMITS are applied on every call, so the set never holds more than
422
+ * `maxCount` entries or `maxBytes` of content: whatever has to go to make room for this one goes
423
+ * now, oldest first, and this one itself goes at once when it does not fit (a message larger than
424
+ * the whole size bound, or a bound of zero).
425
+ *
426
+ * @param {Object} options
427
+ * @param {string} options.account - Account ID
428
+ * @param {string} options.queueId - Queue ID, also the job ID
429
+ * @param {number} [options.finishedOn] - When the last attempt failed (defaults to now)
430
+ * @param {Object} [options.logger] - Logger instance
431
+ * @returns {Promise<boolean>} Whether the content is retained after the bounds were applied
432
+ */
433
+ async function retainFailedContent(options) {
434
+ const { account, queueId, logger } = options;
435
+
436
+ const size = await redis.hstrlen(outboxKey(account), queueId);
437
+ if (!size) {
438
+ // the content is already gone, so there is nothing to retain
439
+ return false;
440
+ }
441
+
442
+ const field = retainedField(account, queueId);
443
+ const [, [, raw]] = await redis
444
+ .multi()
445
+ .hset(FAILED_CONTENT_KEY, field, JSON.stringify({ t: options.finishedOn || Date.now(), s: size }))
446
+ .hgetall(FAILED_CONTENT_KEY)
447
+ .exec();
448
+
449
+ const entries = [];
450
+ for (const [entryField, value] of Object.entries(raw || {})) {
451
+ try {
452
+ const [entryAccount, entryQueueId] = JSON.parse(entryField);
453
+ const record = JSON.parse(value);
454
+ entries.push({ account: entryAccount, queueId: entryQueueId, size: Number(record.s) || 0, finishedOn: Number(record.t) || 0, field: entryField });
455
+ } catch (err) {
456
+ // unreadable entries are the prune's business
457
+ }
458
+ }
459
+
460
+ const drop = selectFailedContentToDrop(entries, FAILED_CONTENT_LIMITS);
461
+ await dropFailedContent(drop, { logger });
462
+
463
+ return !drop.some(entry => entry.field === field);
464
+ }
465
+
466
+ /**
467
+ * Forgets a retained content without deleting it, because the message is live again (retried) or
468
+ * its content was deleted by the caller. A no-op for a message that was never retained.
469
+ *
470
+ * @param {Object} options
471
+ * @param {string} options.account - Account ID
472
+ * @param {string} options.queueId - Queue ID
473
+ */
474
+ async function releaseFailedContent(options) {
475
+ await redis.hdel(FAILED_CONTENT_KEY, retainedField(options.account, options.queueId));
476
+ }
477
+
478
+ /**
479
+ * Applies the retention bounds to everything retained, and reconciles the set with the queue.
480
+ *
481
+ * The bounds are applied on every retain, so this mostly catches age. The reconciliation is what
482
+ * makes a job removed by a path this module does not see - a clean of the failed set, BullMQ's
483
+ * own removal of an aged-out job - take its content with it: a retained content whose job is gone
484
+ * is dropped. One whose job is no longer in the failed state is released to the worker, which
485
+ * deletes the content when the job finishes; every retry today goes through retry() below, which
486
+ * releases, so this is a guard against a future path that does not. Run by the periodic queue
487
+ * cleanup and after a clean of the failed set.
488
+ *
489
+ * @param {Object} [options]
490
+ * @param {Object} [options.logger] - Logger instance
491
+ * @returns {Promise<{dropped: number, released: number}>}
492
+ */
493
+ async function pruneFailedContent(options) {
494
+ const logger = (options && options.logger) || null;
495
+
496
+ const entries = await listRetainedFailedContent();
497
+ if (!entries.length) {
498
+ return { dropped: 0, released: 0 };
499
+ }
500
+
501
+ const dropping = new Map(entries.filter(entry => entry.unreadable).map(entry => [entry.field, entry]));
502
+ for (const entry of selectFailedContentToDrop(
503
+ entries.filter(entry => !entry.unreadable),
504
+ FAILED_CONTENT_LIMITS
505
+ )) {
506
+ dropping.set(entry.field, entry);
507
+ }
508
+
509
+ const remaining = entries.filter(entry => !dropping.has(entry.field));
510
+ const states = await Promise.all(
511
+ remaining.map(async entry => {
512
+ try {
513
+ return await submitQueue.getJobState(entry.queueId);
514
+ } catch (err) {
515
+ if (logger) {
516
+ logger.error({ msg: 'Failed to check the job of a retained failed message', account: entry.account, queueId: entry.queueId, err });
517
+ }
518
+ return null;
519
+ }
520
+ })
521
+ );
522
+
523
+ const release = [];
524
+ remaining.forEach((entry, i) => {
525
+ if (states[i] === 'unknown') {
526
+ dropping.set(entry.field, entry);
527
+ } else if (states[i] && states[i] !== 'failed') {
528
+ release.push(entry.field);
529
+ }
530
+ });
531
+
532
+ const dropped = await dropFailedContent([...dropping.values()], { logger });
533
+ if (release.length) {
534
+ await redis.hdel(FAILED_CONTENT_KEY, ...release);
535
+ }
536
+
537
+ return { dropped, released: release.length };
538
+ }
539
+
540
+ /**
541
+ * Puts a message whose delivery failed for good back into the queue with a fresh set of attempts.
542
+ *
543
+ * Only a failed message can be retried, and only while its content is still retained: the
544
+ * submit worker completes a job it finds no content for without sending anything, so a retry of
545
+ * such a job would report success for a message that never left. That is what the bull-board
546
+ * Retry button used to do, which is why this refuses instead.
547
+ *
548
+ * @param {Object} options
549
+ * @param {string} options.queueId - Queue ID
550
+ * @param {Object} options.logger - Logger instance
551
+ * @returns {Promise<Object|false>} `{ retried, queueId, messageId }`, or false when there is no such message
552
+ * @throws {Error} With `statusCode` 409 and a `code` naming why the message cannot be retried
553
+ */
554
+ async function retry(options) {
555
+ const { queueId, logger } = options;
556
+
557
+ const job = await submitQueue.getJob(queueId);
558
+ if (!job) {
559
+ return false;
560
+ }
561
+
562
+ await assertJobState(job, 'failed', 'message', 'retried');
563
+
564
+ if (!(await redis.hexists(outboxKey(job.data.account), job.id))) {
565
+ throw statusError('The content of this message is no longer stored, so it cannot be retried. Submit the message again', 'ContentGone', 409);
566
+ }
567
+
568
+ await retryFailedJob(job, 'message');
569
+ await releaseFailedContent({ account: job.data.account, queueId: job.id });
570
+
571
+ logger.info({ msg: 'Retrying failed message', account: job.data.account, queueId: job.id, messageId: job.data.messageId });
572
+
573
+ return { retried: true, queueId: job.id, messageId: job.data.messageId };
574
+ }
575
+
576
+ /**
577
+ * Sends a message waiting in the delayed set now: one scheduled with `sendAt`, or one waiting out
578
+ * the backoff before its next attempt.
579
+ *
580
+ * @param {Object} options
581
+ * @param {string} options.queueId - Queue ID
582
+ * @param {Object} options.logger - Logger instance
583
+ * @returns {Promise<Object|false>} `{ promoted, queueId, messageId }`, or false when there is no such message
584
+ * @throws {Error} With `statusCode` 409 and `code` NotDelayed when the message is not waiting for a time
585
+ */
586
+ async function promote(options) {
587
+ const { queueId, logger } = options;
588
+
589
+ const job = await submitQueue.getJob(queueId);
590
+ if (!job) {
591
+ return false;
592
+ }
593
+
594
+ await assertJobState(job, 'delayed', 'message', 'sent now');
595
+ await promoteDelayedJob(job, 'message');
596
+
597
+ logger.info({ msg: 'Promoted queued message', account: job.data.account, queueId: job.id, messageId: job.data.messageId });
598
+
599
+ return { promoted: true, queueId: job.id, messageId: job.data.messageId };
600
+ }
601
+
290
602
  // selectPageRanges and JOB_STATES are exported for the pagination tests: exercising the arithmetic
291
603
  // through list() alone would need a queue populated across all four states to cover the cases.
292
- module.exports = { list, del, get, removeJobs, decodeQueueEntry, selectPageRanges, JOB_STATES };
604
+ module.exports = {
605
+ list,
606
+ del,
607
+ get,
608
+ retry,
609
+ promote,
610
+ removeJobs,
611
+ decodeQueueEntry,
612
+ retainFailedContent,
613
+ pruneFailedContent,
614
+ listRetainedFailedContent,
615
+ selectPageRanges,
616
+ outboxKey,
617
+ JOB_STATES,
618
+ FAILED_CONTENT_KEY,
619
+ FAILED_CONTENT_LIMITS
620
+ };