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
@@ -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
+ };
@@ -0,0 +1,387 @@
1
+ 'use strict';
2
+
3
+ // Turns a BullMQ job into what the queue browser shows for it: a webhook delivery, an outgoing
4
+ // message or an export, rather than "job #123 with data {...}". Pure functions over the job's
5
+ // stored fields, so the wording and the failure classification can be tested without Redis.
6
+
7
+ const { nextAttemptOfStoredJob, isPermanentDeliveryError } = require('../delivery-error');
8
+ const { STATES_BY_NAME } = require('./definitions');
9
+
10
+ // Error codes nodemailer and the socket layer use for "could not get a connection at all"
11
+ const CONNECTION_CODES = new Set(['ECONNECTION', 'ETIMEDOUT', 'ESOCKET', 'EDNS', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ECONNRESET', 'EPROTOCOL', 'ETLS']);
12
+
13
+ // What each kind of failure is called: the sentence for a detail page and the word or two a
14
+ // listing row has room for. `{status}` is the HTTP or SMTP status the worker recorded.
15
+ const FAILURE_KINDS = {
16
+ auth: { label: 'Authentication failed at the outgoing server', short: 'Auth failed' },
17
+ unreachable: { label: 'Could not reach the outgoing server', short: 'Unreachable' },
18
+ rejected: { label: 'Rejected by the receiving server', short: 'Rejected {status}' },
19
+ refused: { label: 'Temporarily refused by the receiving server', short: 'Refused {status}' },
20
+ timeout: { label: 'The endpoint did not answer in time', short: 'Timed out' },
21
+ redirect: { label: 'The endpoint answered with a redirect', short: 'Redirected' },
22
+ blocked: { label: 'Destination blocked by the egress policy', short: 'Blocked' },
23
+ http: { label: 'The endpoint answered {status}', short: 'HTTP {status}' },
24
+ endpoint: { label: 'Could not reach the endpoint', short: 'Unreachable' },
25
+ failed: { label: 'Delivery failed', short: 'Failed' },
26
+ export: { label: 'Export failed', short: 'Failed' }
27
+ };
28
+
29
+ function isoOrNull(value) {
30
+ const time = Number(value);
31
+ return time ? new Date(time).toISOString() : null;
32
+ }
33
+
34
+ /**
35
+ * Formats a byte count for people: "1.2 MB", "840 B".
36
+ *
37
+ * @param {number} bytes
38
+ * @returns {string}
39
+ */
40
+ function humanSize(bytes) {
41
+ const value = Number(bytes) || 0;
42
+ if (value < 1024) {
43
+ return `${value} B`;
44
+ }
45
+ const units = ['KB', 'MB', 'GB', 'TB'];
46
+ let size = value / 1024;
47
+ let unit = 0;
48
+ while (size >= 1024 && unit < units.length - 1) {
49
+ size /= 1024;
50
+ unit++;
51
+ }
52
+ return `${size < 10 ? size.toFixed(1) : Math.round(size)} ${units[unit]}`;
53
+ }
54
+
55
+ /**
56
+ * The recorded outcome of the last attempt, as the workers store it: `{status: 'error', error:
57
+ * {message, code, statusCode, responseCode}}` on the job's progress field after a failed
58
+ * attempt, and `{status: 'delivered', statusCode, duration}` as the webhook worker's return
59
+ * value after a delivery. Anything else (a plain number, the `{status: 'queued'}` marker)
60
+ * carries no outcome.
61
+ */
62
+ function recordedOutcome(job) {
63
+ for (const value of [job.progress, job.returnvalue]) {
64
+ if (value && typeof value === 'object' && value.status) {
65
+ return value;
66
+ }
67
+ }
68
+ return null;
69
+ }
70
+
71
+ /**
72
+ * Classifies a failure of a submission, from what the submit worker recorded.
73
+ *
74
+ * Whether it is permanent is lib/delivery-error.js's call, made on the same fields the worker
75
+ * decided with (the SMTP reply code before the nodemailer error code); nothing here reads a
76
+ * status as a verdict of its own.
77
+ */
78
+ function submitFailureKind(recorded) {
79
+ const permanent = isPermanentDeliveryError(recorded);
80
+ const responseCode = Number(recorded.responseCode) || null;
81
+ if (recorded.code === 'EAUTH') {
82
+ return { kind: 'auth', permanent };
83
+ }
84
+ if (responseCode) {
85
+ return { kind: permanent ? 'rejected' : 'refused', permanent, status: responseCode };
86
+ }
87
+ if (CONNECTION_CODES.has(recorded.code)) {
88
+ return { kind: 'unreachable', permanent: false };
89
+ }
90
+ return { kind: 'failed', permanent };
91
+ }
92
+
93
+ /**
94
+ * Classifies a failure of a webhook delivery, from what the webhook worker recorded.
95
+ */
96
+ function notifyFailureKind(recorded) {
97
+ const statusCode = Number(recorded.statusCode) || null;
98
+ switch (recorded.code) {
99
+ case 'ETIMEDOUT':
100
+ return { kind: 'timeout', permanent: false };
101
+ case 'EREDIRECTNOTFOLLOWED':
102
+ return { kind: 'redirect', permanent: true, status: statusCode };
103
+ case 'EEGRESSBLOCKED':
104
+ return { kind: 'blocked', permanent: true };
105
+ default:
106
+ if (statusCode) {
107
+ return { kind: 'http', permanent: false, status: statusCode };
108
+ }
109
+ if (CONNECTION_CODES.has(recorded.code)) {
110
+ return { kind: 'endpoint', permanent: false };
111
+ }
112
+ return { kind: 'failed', permanent: false };
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Explains why a job failed, in the terms the worker that ran it uses.
118
+ *
119
+ * Reads the error the worker recorded on the job (its code and status are exact) and falls back
120
+ * to the text of BullMQ's `failedReason`, which is all a job from before the workers recorded
121
+ * anything has. A job whose last attempt failed but that is waiting for its next one is explained
122
+ * the same way, so the delayed list can say what it is retrying from.
123
+ *
124
+ * @param {string} queueName - notify, submit or export
125
+ * @param {Object} job - BullMQ job as stored
126
+ * @returns {Object|null} `{ kind, label, shortLabel, reason, code, statusCode, permanent }`, or
127
+ * null when nothing has failed. `label` is the sentence for the detail page, `shortLabel` the
128
+ * word or two a listing row has room for
129
+ */
130
+ function describeFailure(queueName, job) {
131
+ const outcome = recordedOutcome(job);
132
+ const recorded = outcome && outcome.status === 'error' && outcome.error && typeof outcome.error === 'object' ? outcome.error : {};
133
+ const reason = job.failedReason || recorded.message || null;
134
+ if (!reason) {
135
+ return null;
136
+ }
137
+
138
+ let classified;
139
+ switch (queueName) {
140
+ case 'submit':
141
+ classified = submitFailureKind(recorded);
142
+ break;
143
+ case 'notify':
144
+ classified = notifyFailureKind(recorded);
145
+ break;
146
+ default:
147
+ classified = { kind: 'export', permanent: false };
148
+ }
149
+
150
+ // The workers end a job early with UnrecoverableError when retrying cannot help; BullMQ keeps
151
+ // the class name at the head of the stored stack, which is the one signal an older job has
152
+ const stackHead = Array.isArray(job.stacktrace) && job.stacktrace.length ? String(job.stacktrace[0]).split('\n')[0] : '';
153
+ const permanent = classified.permanent || /^UnrecoverableError\b/.test(stackHead);
154
+
155
+ const wording = FAILURE_KINDS[classified.kind];
156
+ const status = classified.status ? String(classified.status) : '';
157
+ const fill = text => text.replace(' {status}', status ? ` ${status}` : '').replace('{status}', status);
158
+
159
+ return {
160
+ kind: classified.kind,
161
+ label: fill(wording.label),
162
+ shortLabel: fill(wording.short),
163
+ reason: String(reason),
164
+ code: recorded.code || null,
165
+ statusCode: classified.status || Number(recorded.statusCode) || null,
166
+ permanent
167
+ };
168
+ }
169
+
170
+ /**
171
+ * The one timestamp a listing row shows for an entry, with the word that says what it is:
172
+ * when a delayed entry is due, when a running one started, when a finished one finished, and
173
+ * otherwise when it was queued.
174
+ */
175
+ function whenOf(queueDef, state, times) {
176
+ switch (state) {
177
+ case 'delayed':
178
+ return { label: times.isRetryWait ? 'Retry' : 'Scheduled', time: times.dueAt };
179
+ case 'active':
180
+ return { label: 'Started', time: times.processedOn };
181
+ case 'failed':
182
+ return { label: 'Failed', time: times.finishedOn };
183
+ case 'completed':
184
+ return { label: queueDef.name === 'submit' ? 'Sent' : 'Finished', time: times.finishedOn };
185
+ default:
186
+ return { label: 'Queued', time: times.created };
187
+ }
188
+ }
189
+
190
+ /**
191
+ * The fields every row and detail view carries, whatever the queue.
192
+ */
193
+ function formatCommon(queueDef, job, state) {
194
+ const stateInfo = STATES_BY_NAME.get(state) || { name: state, label: state, variant: 'neutral' };
195
+ const attempts = Number(job.opts && job.opts.attempts) || 1;
196
+ const attemptsMade = Number(job.attemptsMade) || 0;
197
+
198
+ const scheduledMs = Number(job.timestamp) + (Number(job.opts && job.opts.delay) || 0);
199
+ const nextAttemptMs = nextAttemptOfStoredJob(job, scheduledMs);
200
+
201
+ const isRetryWait = state === 'delayed' && attemptsMade > 0;
202
+ const times = {
203
+ created: isoOrNull(job.timestamp),
204
+ // A delayed entry is either scheduled (nothing has run yet) or waiting out a backoff
205
+ dueAt: state === 'delayed' ? (attemptsMade ? isoOrNull(nextAttemptMs) : new Date(scheduledMs).toISOString()) : null,
206
+ isRetryWait,
207
+ processedOn: isoOrNull(job.processedOn),
208
+ finishedOn: isoOrNull(job.finishedOn)
209
+ };
210
+
211
+ const outcome = recordedOutcome(job);
212
+
213
+ return Object.assign(
214
+ {
215
+ id: String(job.id),
216
+ queue: queueDef.name,
217
+ url: entryUrl(queueDef.name, job.id),
218
+ state,
219
+ stateInfo,
220
+ account: (job.data && job.data.account) || null,
221
+ scheduled: new Date(scheduledMs).toISOString(),
222
+ attemptsMade,
223
+ attempts,
224
+ // Attempt numbers for people: "attempt 3 of 10" while running, "3 of 10 attempts" after
225
+ attemptsLabel: `${attemptsMade} of ${attempts}`,
226
+ when: whenOf(queueDef, state, times),
227
+ failure: describeFailure(queueDef.name, job),
228
+ // What the worker recorded of the last outcome, beyond the error
229
+ outcome,
230
+ duration: outcome && Number(outcome.duration) ? Number(outcome.duration) : null,
231
+ canPromote: !!queueDef.actions.promote && state === 'delayed',
232
+ canRetry: !!queueDef.actions.retry && state === 'failed',
233
+ canRemove: !!queueDef.actions.remove && state !== 'active'
234
+ },
235
+ times
236
+ );
237
+ }
238
+
239
+ function formatSubmit(queueDef, job, state) {
240
+ const data = job.data || {};
241
+ const envelope = data.envelope || {};
242
+ const to = Array.isArray(envelope.to) ? envelope.to : envelope.to ? [envelope.to] : [];
243
+
244
+ return Object.assign(formatCommon(queueDef, job, state), {
245
+ title: data.subject || '(no subject)',
246
+ subject: data.subject || null,
247
+ messageId: data.messageId || null,
248
+ from: envelope.from || null,
249
+ to,
250
+ toFirst: to[0] || null,
251
+ toMore: to.length > 1 ? to.length - 1 : 0,
252
+ gateway: data.gateway || null,
253
+ source: data.source || null,
254
+ idempotencyKey: data.idempotencyKey || null,
255
+ // 'delayed' names a scheduled send, 'queued' an immediate one; the job name is set once
256
+ isScheduledSend: job.name === 'delayed',
257
+ // Filled in by the Redis-backed listing, which knows whether the content is still stored
258
+ hasContent: null
259
+ });
260
+ }
261
+
262
+ function formatNotify(queueDef, job, state) {
263
+ const data = job.data || {};
264
+ const route = data._route && typeof data._route === 'object' ? data._route : null;
265
+ const payload = data.data && typeof data.data === 'object' ? data.data : {};
266
+
267
+ return Object.assign(formatCommon(queueDef, job, state), {
268
+ title: job.name,
269
+ event: job.name,
270
+ eventId: data.eventId || null,
271
+ date: data.date || null,
272
+ path: data.path || null,
273
+ specialUse: data.specialUse || null,
274
+ routeId: route ? route.id : null,
275
+ // resolved by the Redis-backed listing, which can look the route up
276
+ routeName: null,
277
+ hasMapping: !!(route && route.mapping !== undefined),
278
+ // What the event is about, for the row: a message's subject, an account's new state
279
+ about: payload.subject || payload.messageId || (payload.state ? `state: ${payload.state}` : null),
280
+ messageId: payload.messageId || null
281
+ });
282
+ }
283
+
284
+ function formatExport(queueDef, job, state) {
285
+ const data = job.data || {};
286
+ return Object.assign(formatCommon(queueDef, job, state), {
287
+ title: `Export ${data.exportId || job.id}`,
288
+ exportId: data.exportId || String(job.id)
289
+ });
290
+ }
291
+
292
+ const FORMATTERS = { submit: formatSubmit, notify: formatNotify, export: formatExport };
293
+
294
+ /**
295
+ * The page of one entry in the browser.
296
+ *
297
+ * @param {string} queueName - Queue name
298
+ * @param {string|number} jobId - Job ID
299
+ * @returns {string} Path
300
+ */
301
+ function entryUrl(queueName, jobId) {
302
+ return `/admin/queues/${queueName}/jobs/${encodeURIComponent(jobId)}`;
303
+ }
304
+
305
+ /**
306
+ * Formats a job of a queue for the browser.
307
+ *
308
+ * @param {Object} queueDef - Queue definition from ./definitions
309
+ * @param {Object} job - BullMQ job as stored
310
+ * @param {string} state - The state the job was listed from
311
+ * @returns {Object} Row or detail model
312
+ */
313
+ function formatJob(queueDef, job, state) {
314
+ return (FORMATTERS[queueDef.name] || formatExport)(queueDef, job, state);
315
+ }
316
+
317
+ /**
318
+ * The size of what a webhook delivery posts: the mapped payload when a route mapped it, the
319
+ * event payload otherwise. Measured on the detail page only, because serializing every row's
320
+ * payload (up to notifyTextSize of message text each) just to print a size is not worth it.
321
+ *
322
+ * @param {Object} job - BullMQ job as stored
323
+ * @returns {number} Bytes
324
+ */
325
+ function notifyPayloadSize(job) {
326
+ const data = job.data || {};
327
+ const route = data._route && typeof data._route === 'object' ? data._route : null;
328
+ try {
329
+ return Buffer.byteLength(JSON.stringify(route && route.mapping !== undefined ? route.mapping : data));
330
+ } catch (err) {
331
+ return 0;
332
+ }
333
+ }
334
+
335
+ // The fields a person would search a queue by, per queue
336
+ const SEARCH_FIELDS = {
337
+ submit: (job, data) => {
338
+ const envelope = data.envelope || {};
339
+ return [data.messageId, data.subject, data.gateway, data.idempotencyKey, envelope.from, ...(Array.isArray(envelope.to) ? envelope.to : [envelope.to])];
340
+ },
341
+ notify: (job, data) => {
342
+ const payload = data.data && typeof data.data === 'object' ? data.data : {};
343
+ return [job.name, data._route && data._route.id, data.path, payload.messageId, payload.subject, data.eventId];
344
+ },
345
+ export: (job, data) => [data.exportId]
346
+ };
347
+
348
+ /**
349
+ * Whether a job matches a free-text filter: a substring match over the fields a person would
350
+ * search a queue by. Case-insensitive; an empty filter matches everything.
351
+ *
352
+ * @param {Object} queueDef - Queue definition
353
+ * @param {Object} job - BullMQ job as stored
354
+ * @param {string} query - Filter text, already trimmed
355
+ * @returns {boolean}
356
+ */
357
+ function matchesQuery(queueDef, job, query) {
358
+ const needle = String(query || '').toLowerCase();
359
+ if (!needle) {
360
+ return true;
361
+ }
362
+
363
+ const data = job.data || {};
364
+ const fields = [job.id, data.account, ...(SEARCH_FIELDS[queueDef.name] || SEARCH_FIELDS.export)(job, data)];
365
+
366
+ return fields.some(field => field !== null && field !== undefined && String(field).toLowerCase().includes(needle));
367
+ }
368
+
369
+ /**
370
+ * The raw job, for the collapsed section of the detail page: what a support case asks for, in
371
+ * the shape BullMQ stores it.
372
+ *
373
+ * @param {Object} job - BullMQ job as stored
374
+ * @returns {Object} `{ name, data, opts, progress, returnvalue, stacktrace }`
375
+ */
376
+ function rawJob(job) {
377
+ return {
378
+ name: job.name,
379
+ data: job.data,
380
+ opts: job.opts,
381
+ progress: job.progress && typeof job.progress === 'object' ? job.progress : null,
382
+ returnvalue: job.returnvalue !== null && job.returnvalue !== undefined ? job.returnvalue : null,
383
+ stacktrace: Array.isArray(job.stacktrace) && job.stacktrace.length ? job.stacktrace.join('\n\n') : null
384
+ };
385
+ }
386
+
387
+ module.exports = { formatJob, describeFailure, matchesQuery, rawJob, humanSize, notifyPayloadSize, entryUrl, FAILURE_KINDS };