emailengine-app 2.83.2 → 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 (63) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +20 -0
  3. package/README.md +1 -1
  4. package/SECURITY.md +126 -47
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/api-routes/outbox-routes.js +132 -9
  7. package/lib/api-routes/permission-map.js +11 -1
  8. package/lib/consts.js +0 -4
  9. package/lib/email-client/imap/idle-settings.js +44 -0
  10. package/lib/email-client/imap/mailbox.js +19 -7
  11. package/lib/email-client/imap-client.js +3 -21
  12. package/lib/enum-descriptions.js +7 -0
  13. package/lib/export.js +2 -6
  14. package/lib/field-usage.js +4 -0
  15. package/lib/handlebars-helpers.js +4 -0
  16. package/lib/outbox.js +338 -10
  17. package/lib/queue-browser/definitions.js +132 -0
  18. package/lib/queue-browser/format.js +387 -0
  19. package/lib/queue-browser/index.js +568 -0
  20. package/lib/queue-job-actions.js +75 -0
  21. package/lib/queue-retention.js +53 -1
  22. package/lib/routes-ui.js +5 -0
  23. package/lib/schemas.js +42 -2
  24. package/lib/security-headers.js +2 -24
  25. package/lib/token-permission-view.js +1 -1
  26. package/lib/ui-routes/account-routes.js +6 -0
  27. package/lib/ui-routes/imap-idle-field.js +42 -0
  28. package/lib/ui-routes/queue-routes.js +371 -0
  29. package/lib/utils/status-error.js +21 -0
  30. package/package.json +15 -17
  31. package/prepare-bundle-deps.sh +1 -1
  32. package/sbom.json +1 -1
  33. package/server.js +10 -0
  34. package/static/css/flyonui.css +1 -1
  35. package/static/css/src/app.tailwind.css +2 -0
  36. package/static/js/queues.js +117 -0
  37. package/static/licenses.html +122 -246
  38. package/translations/messages.pot +57 -42
  39. package/views/accounts/account.hbs +31 -0
  40. package/views/accounts/edit.hbs +2 -0
  41. package/views/config/service.hbs +1 -2
  42. package/views/dashboard.hbs +2 -2
  43. package/views/partials/queue_cell_account.hbs +20 -0
  44. package/views/partials/queue_cell_failure.hbs +6 -0
  45. package/views/partials/queue_clean_items.hbs +9 -0
  46. package/views/partials/queue_clean_modal.hbs +9 -0
  47. package/views/partials/queue_entry_actions.hbs +41 -0
  48. package/views/partials/queue_job_actions.hbs +15 -0
  49. package/views/partials/queue_pause_controls.hbs +18 -0
  50. package/views/partials/queue_retention_note.hbs +49 -0
  51. package/views/partials/queue_rows_export.hbs +58 -0
  52. package/views/partials/queue_rows_notify.hbs +73 -0
  53. package/views/partials/queue_rows_submit.hbs +70 -0
  54. package/views/partials/side_menu.hbs +1 -1
  55. package/views/partials/ui/tooltip.hbs +5 -3
  56. package/views/queues/index.hbs +104 -0
  57. package/views/queues/job.hbs +224 -0
  58. package/views/queues/queue.hbs +93 -0
  59. package/views/webhooks/webhook.hbs +3 -0
  60. package/workers/api.js +0 -4
  61. package/workers/submit.js +19 -5
  62. package/workers/webhooks.js +13 -0
  63. package/lib/api-routes/bull-board-routes.js +0 -56
@@ -74,6 +74,10 @@ const FIELD_USAGE = {
74
74
  'Set this only after a server has actually misbehaved. A handful of IMAP servers advertise IMAP4rev2 support and then answer incorrectly, and this forces EmailEngine back to IMAP4rev1 for that account.\n\n' +
75
75
  'It has no effect on accounts that authenticate with OAuth2.',
76
76
 
77
+ maxIdleTime:
78
+ 'Leave this unset unless the server, or something between it and EmailEngine, drops idle connections. Some providers close an IDLE session after a few minutes without saying BYE, which shows up as a reconnect every few minutes. Set a value below that limit, for instance 120000 for a connection that drops after about four and a half minutes, and EmailEngine ends and restarts IDLE that often, so the connection never looks idle.\n\n' +
79
+ 'A handful of providers (Yahoo, Rambler, 163.com) already get a built-in value; one set here takes precedence over it. Unlike `disableIMAP4rev2` it also applies to accounts that authenticate with OAuth2. Changing it reconnects the account.',
80
+
77
81
  // No description of what `full` and `fast` do: the row lists both values with their own
78
82
  // descriptions from lib/enum-descriptions.js a few lines under this note, and saying it
79
83
  // twice on one row is what that split exists to avoid.
@@ -62,6 +62,10 @@ function registerHandlebarsHelpers(handlebars, { gt }) {
62
62
  // hash values: text=(concat "Up to " (formatInteger n locale) " lines")
63
63
  handlebars.registerHelper('concat', (...args) => args.slice(0, -1).join(''));
64
64
 
65
+ // a line break inside a composed string, for a ui/tooltip body rendered multiline:
66
+ // (concat "first line" (newline) "second line")
67
+ handlebars.registerHelper('newline', () => '\n');
68
+
65
69
  // Ternary for subexpressions: placeholder=(when hasPass "set..." "")
66
70
  handlebars.registerHelper('when', (cond, truthyValue, falsyValue) => (cond ? truthyValue : typeof falsyValue === 'string' ? falsyValue : ''));
67
71
 
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
+ };
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+
3
+ // What the queue browser knows about each BullMQ queue and each job state: the wording, the order
4
+ // things are listed in, and which actions apply. Dependency-free on purpose - the formatters and
5
+ // the tests read it without opening Redis, and the routes read it to validate what a URL names.
6
+
7
+ // The job states a queue is browsed by, in the order the tabs show them. BullMQ 6 has no `paused`
8
+ // state (a paused queue holds its jobs in `waiting`), and `prioritized` and `waiting-children`
9
+ // are never used here, so they are not offered.
10
+ const STATES = [
11
+ {
12
+ name: 'waiting',
13
+ label: 'Waiting',
14
+ variant: 'info',
15
+ description: 'Ready to run as soon as a worker is free. A paused queue holds its jobs here',
16
+ // Listed first-in first-out, so the top of the list is what runs next
17
+ newestFirst: false
18
+ },
19
+ {
20
+ name: 'active',
21
+ label: 'Active',
22
+ variant: 'primary',
23
+ description: 'Being processed by a worker right now',
24
+ newestFirst: false
25
+ },
26
+ {
27
+ name: 'delayed',
28
+ label: 'Delayed',
29
+ variant: 'neutral',
30
+ description: 'Waiting for a scheduled time, or for the backoff before the next attempt. Soonest first',
31
+ newestFirst: false
32
+ },
33
+ {
34
+ name: 'failed',
35
+ label: 'Failed',
36
+ variant: 'error',
37
+ description: 'Given up on: every attempt failed, or the failure was permanent. Most recent first',
38
+ newestFirst: true
39
+ },
40
+ {
41
+ name: 'completed',
42
+ label: 'Completed',
43
+ variant: 'success',
44
+ description: 'Finished successfully. Kept only while the completed job history limit allows. Most recent first',
45
+ newestFirst: true
46
+ }
47
+ ];
48
+
49
+ const STATE_NAMES = STATES.map(state => state.name);
50
+
51
+ const STATES_BY_NAME = new Map(STATES.map(state => [state.name, state]));
52
+
53
+ // The queues, in the order the overview shows them.
54
+ //
55
+ // `keepsFinished` says whether completed and failed jobs stay in the queue for a while: the export
56
+ // queue's are removed the moment they end (lib/export.js), its exports being managed from the
57
+ // account page. `concurrency` names where the per-worker job concurrency and the worker thread count come from,
58
+ // so the overview can say how many jobs the queue can run at once. `actions` is what the browser
59
+ // offers on a job of this queue: exports are driven from the account's own export pages, where
60
+ // cancelling one also removes its file, so the export queue is read-only here.
61
+ const QUEUES = [
62
+ {
63
+ name: 'notify',
64
+ label: 'Webhooks',
65
+ title: 'Webhooks queue',
66
+ noun: 'webhook delivery',
67
+ nounPlural: 'webhook deliveries',
68
+ icon: 'icon-[tabler--webhook]',
69
+ description: 'Every email event that may trigger a webhook. An event no webhook is configured for completes without sending anything.',
70
+ // what the search box says it looks through
71
+ searchHint: 'Search by event, route, account, subject or message ID',
72
+ concurrency: { workersEnv: 'EENGINE_WORKERS_WEBHOOKS', workersConfig: 'webhooks', concurrencyEnv: 'EENGINE_NOTIFY_QC', concurrencyConfig: 'notify' },
73
+ keepsFinished: true,
74
+ actions: { retry: true, promote: true, remove: true }
75
+ },
76
+ {
77
+ name: 'submit',
78
+ label: 'Outgoing messages',
79
+ title: 'Outgoing messages queue',
80
+ noun: 'message',
81
+ nounPlural: 'messages',
82
+ icon: 'icon-[tabler--send]',
83
+ description: 'Messages queued for delivery through SMTP or the provider API, including scheduled sends and retries.',
84
+ searchHint: 'Search by subject, address, account, message or queue ID',
85
+ concurrency: { workersEnv: 'EENGINE_WORKERS_SUBMIT', workersConfig: 'submit', concurrencyEnv: 'EENGINE_SUBMIT_QC', concurrencyConfig: 'submit' },
86
+ keepsFinished: true,
87
+ actions: { retry: true, promote: true, remove: true }
88
+ },
89
+ {
90
+ name: 'export',
91
+ label: 'Exports',
92
+ title: 'Exports queue',
93
+ noun: 'export',
94
+ nounPlural: 'exports',
95
+ icon: 'icon-[tabler--package-export]',
96
+ description: 'Mailbox exports waiting for an export worker. An export itself is managed from its account page.',
97
+ searchHint: 'Search by export or account ID',
98
+ concurrency: { workersEnv: 'EENGINE_WORKERS_EXPORT', workersConfig: 'export', concurrencyEnv: 'EENGINE_EXPORT_QC', concurrencyConfig: 'export' },
99
+ keepsFinished: false,
100
+ actions: { retry: false, promote: false, remove: false }
101
+ }
102
+ ];
103
+
104
+ const QUEUE_NAMES = QUEUES.map(queue => queue.name);
105
+
106
+ const QUEUES_BY_NAME = new Map(QUEUES.map(queue => [queue.name, queue]));
107
+
108
+ // The default tab of a queue page. Waiting rather than "whatever is non-empty": a default that
109
+ // moves between visits is a page the reader cannot form a habit on, and the overview links every
110
+ // count straight to its own tab anyway.
111
+ const DEFAULT_STATE = 'waiting';
112
+
113
+ // How many jobs a filtered listing reads before it stops looking. A BullMQ queue has no index by
114
+ // account or by anything else in the payload, so a filter is a scan of the state's list, and a
115
+ // scan that reads every job of a busy queue would read every webhook payload with it. Within this
116
+ // bound the search is exact; past it the page says how far it looked.
117
+ const SCAN_LIMIT = 500;
118
+
119
+ // Jobs read per round trip while listing or scanning
120
+ const BATCH_SIZE = 50;
121
+
122
+ module.exports = {
123
+ STATES,
124
+ STATE_NAMES,
125
+ STATES_BY_NAME,
126
+ QUEUES,
127
+ QUEUE_NAMES,
128
+ QUEUES_BY_NAME,
129
+ DEFAULT_STATE,
130
+ SCAN_LIMIT,
131
+ BATCH_SIZE
132
+ };