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.
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +30 -0
- package/README.md +1 -1
- package/SECURITY.md +126 -47
- package/data/google-crawlers.json +1 -1
- package/gettext-extract.js +95 -15
- package/lib/api-routes/outbox-routes.js +132 -9
- package/lib/api-routes/permission-map.js +11 -1
- package/lib/consts.js +3 -5
- package/lib/email-client/base-client.js +44 -20
- package/lib/email-client/credential-errors.js +3 -31
- package/lib/email-client/imap/idle-settings.js +44 -0
- package/lib/email-client/imap/mailbox.js +19 -7
- package/lib/email-client/imap-client.js +3 -21
- package/lib/email-client/smtp-pool-manager.js +25 -6
- package/lib/enum-descriptions.js +7 -0
- package/lib/export.js +46 -42
- package/lib/field-usage.js +4 -0
- package/lib/handlebars-helpers.js +4 -0
- package/lib/imapproxy/imap-core/lib/commands/starttls.js +4 -2
- package/lib/imapproxy/imap-core/lib/imap-server.js +44 -11
- package/lib/imapproxy/proxy-handoff.js +10 -1
- package/lib/logger.js +3 -2
- package/lib/message-port-stream.js +23 -0
- package/lib/network-errors.js +50 -0
- package/lib/oauth/gmail.js +5 -1
- package/lib/oauth/mail-ru.js +5 -1
- package/lib/oauth/outlook.js +5 -1
- package/lib/oauth/pubsub/google.js +3 -2
- package/lib/oauth/token-fetch.js +2 -3
- package/lib/outbox.js +338 -10
- package/lib/queue-browser/definitions.js +132 -0
- package/lib/queue-browser/format.js +387 -0
- package/lib/queue-browser/index.js +568 -0
- package/lib/queue-job-actions.js +75 -0
- package/lib/queue-retention.js +53 -1
- package/lib/routes-ui.js +5 -0
- package/lib/schemas.js +42 -2
- package/lib/security-headers.js +2 -24
- package/lib/sub-script.js +10 -3
- package/lib/token-permission-view.js +1 -1
- package/lib/tools.js +16 -2
- package/lib/ui-routes/account-routes.js +6 -0
- package/lib/ui-routes/imap-idle-field.js +42 -0
- package/lib/ui-routes/queue-routes.js +371 -0
- package/lib/utils/status-error.js +21 -0
- package/package.json +18 -20
- package/prepare-bundle-deps.sh +1 -1
- package/sbom.json +1 -1
- package/server.js +10 -0
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +2 -0
- package/static/js/queues.js +117 -0
- package/static/licenses.html +127 -251
- package/translations/README.md +3 -2
- package/translations/messages.pot +280 -265
- package/views/accounts/account.hbs +31 -0
- package/views/accounts/edit.hbs +2 -0
- package/views/config/service.hbs +1 -2
- package/views/dashboard.hbs +2 -2
- package/views/partials/queue_cell_account.hbs +20 -0
- package/views/partials/queue_cell_failure.hbs +6 -0
- package/views/partials/queue_clean_items.hbs +9 -0
- package/views/partials/queue_clean_modal.hbs +9 -0
- package/views/partials/queue_entry_actions.hbs +41 -0
- package/views/partials/queue_job_actions.hbs +15 -0
- package/views/partials/queue_pause_controls.hbs +18 -0
- package/views/partials/queue_retention_note.hbs +49 -0
- package/views/partials/queue_rows_export.hbs +58 -0
- package/views/partials/queue_rows_notify.hbs +73 -0
- package/views/partials/queue_rows_submit.hbs +70 -0
- package/views/partials/side_menu.hbs +1 -1
- package/views/partials/ui/tooltip.hbs +5 -3
- package/views/queues/index.hbs +104 -0
- package/views/queues/job.hbs +224 -0
- package/views/queues/queue.hbs +93 -0
- package/views/webhooks/webhook.hbs +3 -0
- package/workers/api.js +0 -4
- package/workers/imap.js +10 -3
- package/workers/smtp.js +16 -1
- package/workers/submit.js +19 -5
- package/workers/webhooks.js +13 -0
- package/lib/api-routes/bull-board-routes.js +0 -56
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The queue browser behind /admin/queues: counts, listings, job details and the actions the
|
|
4
|
+
// pages offer, over the three BullMQ queues. Everything that touches Redis lives here; the
|
|
5
|
+
// wording and the per-job formatting are in ./format and ./definitions, which are pure.
|
|
6
|
+
//
|
|
7
|
+
// The submit queue is special in one way the generic BullMQ operations cannot see: a message's
|
|
8
|
+
// content lives outside its job, in the account's outbox hash. Removing a job without that
|
|
9
|
+
// content orphans the message in Redis, and retrying one whose content is gone sends nothing
|
|
10
|
+
// while reporting success, which is what the bull-board buttons this replaced used to do. So
|
|
11
|
+
// the submit queue's actions are lib/outbox's, which owns both halves; the per-queue table
|
|
12
|
+
// below is where that difference lives, and the rest of this module does not branch on it.
|
|
13
|
+
|
|
14
|
+
const config = require('@zone-eu/wild-config');
|
|
15
|
+
const { QUEUES_BY_NAME: QUEUE_OBJECTS_BY_NAME, exportQueue, redis } = require('../db');
|
|
16
|
+
const { readEnvValue } = require('../read-env-value');
|
|
17
|
+
const { accountsExist } = require('../account');
|
|
18
|
+
const { webhooks: Webhooks } = require('../webhooks');
|
|
19
|
+
const outbox = require('../outbox');
|
|
20
|
+
const settings = require('../settings');
|
|
21
|
+
const { buildRetentionPolicy, FAILED_JOB_RETENTION_COUNT } = require('../queue-retention');
|
|
22
|
+
const { maskSecrets } = require('../api-routes/route-helpers');
|
|
23
|
+
const { statusError } = require('../utils/status-error');
|
|
24
|
+
const { retryFailedJob, promoteDelayedJob, assertJobState } = require('../queue-job-actions');
|
|
25
|
+
const { QUEUES, QUEUES_BY_NAME, STATES, STATES_BY_NAME, STATE_NAMES, SCAN_LIMIT, BATCH_SIZE } = require('./definitions');
|
|
26
|
+
const { formatJob, matchesQuery, rawJob, humanSize, notifyPayloadSize, entryUrl } = require('./format');
|
|
27
|
+
|
|
28
|
+
// lib/db keys the API-addressable queues by name and leaves the export queue out on purpose;
|
|
29
|
+
// the browser shows it, read-only
|
|
30
|
+
const QUEUE_OBJECTS = Object.assign({ export: exportQueue }, QUEUE_OBJECTS_BY_NAME);
|
|
31
|
+
|
|
32
|
+
function queueObject(queueDef) {
|
|
33
|
+
return QUEUE_OBJECTS[queueDef.name];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The state of one job, for a route that has to know where an entry was before acting on it.
|
|
38
|
+
*
|
|
39
|
+
* @param {Object} queueDef - Queue definition
|
|
40
|
+
* @param {string} jobId - Job ID
|
|
41
|
+
* @returns {Promise<string|null>} BullMQ state, or null when there is no such job
|
|
42
|
+
*/
|
|
43
|
+
async function jobState(queueDef, jobId) {
|
|
44
|
+
const job = await queueObject(queueDef).getJob(jobId);
|
|
45
|
+
return job ? await job.getState() : null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Removes a job through BullMQ alone: refused, as `locked`, when a worker is running it.
|
|
50
|
+
*/
|
|
51
|
+
async function removeBullJob(queueDef, jobId, logger) {
|
|
52
|
+
const job = await queueObject(queueDef).getJob(jobId);
|
|
53
|
+
if (!job) {
|
|
54
|
+
return { removed: false };
|
|
55
|
+
}
|
|
56
|
+
if (await job.isActive()) {
|
|
57
|
+
return { removed: false, locked: true };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
await job.remove();
|
|
62
|
+
} catch (err) {
|
|
63
|
+
// the lock was taken between the check and the removal
|
|
64
|
+
logger.warn({ msg: 'Failed to remove a queue job', queue: queueDef.name, job: jobId, err });
|
|
65
|
+
return { removed: false, locked: true };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
logger.info({ msg: 'Removed queue job', queue: queueDef.name, job: jobId, event: job.name, account: job.data && job.data.account });
|
|
69
|
+
return { removed: true };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function retryBullJob(queueDef, jobId, logger) {
|
|
73
|
+
const job = await queueObject(queueDef).getJob(jobId);
|
|
74
|
+
if (!job) {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
await assertJobState(job, 'failed', queueDef.noun, 'retried');
|
|
78
|
+
await retryFailedJob(job, queueDef.noun);
|
|
79
|
+
logger.info({ msg: 'Retrying failed queue job', queue: queueDef.name, job: jobId, event: job.name, account: job.data && job.data.account });
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function promoteBullJob(queueDef, jobId, logger) {
|
|
84
|
+
const job = await queueObject(queueDef).getJob(jobId);
|
|
85
|
+
if (!job) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
await assertJobState(job, 'delayed', queueDef.noun, 'sent now');
|
|
89
|
+
await promoteDelayedJob(job, queueDef.noun);
|
|
90
|
+
logger.info({ msg: 'Promoted delayed queue job', queue: queueDef.name, job: jobId, event: job.name, account: job.data && job.data.account });
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Why a failed message offers no retry once its content is gone: shown on the Retry that is kept
|
|
95
|
+
// visible but disabled, so the reader learns why rather than wondering where it went
|
|
96
|
+
const CONTENT_GONE_REASON = 'The message content is no longer stored, so there is nothing to send. Submit the message again instead.';
|
|
97
|
+
|
|
98
|
+
// What each queue's actions do, and what its listing needs decorated. The submit entries are
|
|
99
|
+
// lib/outbox's own operations; `afterClean` is what a cleaned failed set leaves behind.
|
|
100
|
+
const QUEUE_OPS = {
|
|
101
|
+
submit: {
|
|
102
|
+
remove: ({ jobId, logger }) => outbox.del({ queueId: jobId, logger }).then(result => ({ removed: !!result.deleted, locked: !!result.locked })),
|
|
103
|
+
retry: ({ jobId, logger }) => outbox.retry({ queueId: jobId, logger }).then(Boolean),
|
|
104
|
+
promote: ({ jobId, logger }) => outbox.promote({ queueId: jobId, logger }).then(Boolean),
|
|
105
|
+
afterClean: ({ state, logger }) => (state === 'failed' ? outbox.pruneFailedContent({ logger }) : null),
|
|
106
|
+
// whether a failed message still has its content, which is what a retry needs
|
|
107
|
+
decorate: async entries => {
|
|
108
|
+
const failed = entries.filter(entry => entry.state === 'failed' && entry.account);
|
|
109
|
+
if (!failed.length) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const pipeline = redis.pipeline();
|
|
113
|
+
for (const entry of failed) {
|
|
114
|
+
pipeline.hexists(outbox.outboxKey(entry.account), entry.id);
|
|
115
|
+
}
|
|
116
|
+
const results = await pipeline.exec();
|
|
117
|
+
failed.forEach((entry, i) => {
|
|
118
|
+
const retriable = entry.canRetry;
|
|
119
|
+
entry.hasContent = !!(results[i] && results[i][1] === 1);
|
|
120
|
+
entry.canRetry = retriable && entry.hasContent;
|
|
121
|
+
// a failed message without content keeps its Retry visible, disabled, with the why
|
|
122
|
+
entry.retryBlockedReason = retriable && !entry.hasContent ? CONTENT_GONE_REASON : null;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
notify: {
|
|
127
|
+
remove: ({ queue, jobId, logger }) => removeBullJob(queue, jobId, logger),
|
|
128
|
+
retry: ({ queue, jobId, logger }) => retryBullJob(queue, jobId, logger),
|
|
129
|
+
promote: ({ queue, jobId, logger }) => promoteBullJob(queue, jobId, logger),
|
|
130
|
+
afterClean: () => null,
|
|
131
|
+
// the name of the webhook route a delivery was queued for, and whether it still exists
|
|
132
|
+
decorate: async (entries, logger) => {
|
|
133
|
+
const routeIds = Array.from(new Set(entries.map(entry => entry.routeId).filter(Boolean)));
|
|
134
|
+
const names = new Map();
|
|
135
|
+
await Promise.all(
|
|
136
|
+
routeIds.map(async routeId => {
|
|
137
|
+
try {
|
|
138
|
+
const meta = await Webhooks.getMeta(routeId);
|
|
139
|
+
names.set(routeId, meta && meta.name ? meta.name : null);
|
|
140
|
+
} catch (err) {
|
|
141
|
+
logger.error({ msg: 'Failed to resolve a webhook route', webhook: routeId, err });
|
|
142
|
+
}
|
|
143
|
+
})
|
|
144
|
+
);
|
|
145
|
+
for (const entry of entries) {
|
|
146
|
+
if (entry.routeId) {
|
|
147
|
+
entry.routeName = names.get(entry.routeId) || null;
|
|
148
|
+
// a route that no longer exists is skipped by the worker, which is worth saying
|
|
149
|
+
entry.routeKnown = !!names.get(entry.routeId);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
export: {
|
|
155
|
+
afterClean: () => null,
|
|
156
|
+
decorate: async () => {}
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* How many jobs a queue can run at once, and where that number comes from.
|
|
162
|
+
*
|
|
163
|
+
* The same expressions the main thread and the workers evaluate at startup, because the API
|
|
164
|
+
* worker holds its own copy of the config object and the main thread's env overrides never reach
|
|
165
|
+
* it.
|
|
166
|
+
*
|
|
167
|
+
* @param {Object} queueDef - Queue definition
|
|
168
|
+
* @returns {{workers: number, perWorker: number, total: number, workersEnv: string, concurrencyEnv: string}}
|
|
169
|
+
*/
|
|
170
|
+
function concurrencyInfo(queueDef) {
|
|
171
|
+
const { workersEnv, workersConfig, concurrencyEnv, concurrencyConfig } = queueDef.concurrency;
|
|
172
|
+
const workers = Number(readEnvValue(workersEnv)) || (config.workers && config.workers[workersConfig]) || 1;
|
|
173
|
+
const perWorker = Number(readEnvValue(concurrencyEnv)) || (config.queues && config.queues[concurrencyConfig]) || 1;
|
|
174
|
+
return { workers, perWorker, total: workers * perWorker, workersEnv, concurrencyEnv };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Job counts per state plus the paused flag, for one queue.
|
|
179
|
+
*
|
|
180
|
+
* @param {Object} queueDef - Queue definition
|
|
181
|
+
* @returns {Promise<Object>} `{ counts: {waiting, active, delayed, failed, completed}, isPaused }`
|
|
182
|
+
*/
|
|
183
|
+
async function queueCounts(queueDef) {
|
|
184
|
+
const queueObj = queueObject(queueDef);
|
|
185
|
+
const [raw, isPaused] = await Promise.all([queueObj.getJobCounts(...STATE_NAMES), queueObj.isPaused()]);
|
|
186
|
+
|
|
187
|
+
const counts = {};
|
|
188
|
+
for (const state of STATE_NAMES) {
|
|
189
|
+
counts[state] = Number(raw[state]) || 0;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return { counts, isPaused: !!isPaused };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The counts of every queue, keyed by name - what the pages poll.
|
|
197
|
+
*
|
|
198
|
+
* @returns {Promise<Object>}
|
|
199
|
+
*/
|
|
200
|
+
async function allCounts() {
|
|
201
|
+
const result = {};
|
|
202
|
+
await Promise.all(
|
|
203
|
+
QUEUES.map(async queueDef => {
|
|
204
|
+
result[queueDef.name] = await queueCounts(queueDef);
|
|
205
|
+
})
|
|
206
|
+
);
|
|
207
|
+
return result;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* What the retained failed-message content amounts to, for the overview.
|
|
212
|
+
*
|
|
213
|
+
* @returns {Promise<Object>} `{ count, bytes, bytesLabel, limits: {maxCount, maxBytes, maxBytesLabel, maxAgeDays} }`
|
|
214
|
+
*/
|
|
215
|
+
const toDays = seconds => Math.round(seconds / (24 * 3600));
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* What the overview says is kept: the options the webhook and submit jobs are queued with, read
|
|
219
|
+
* the way lib/webhooks.js and base-client.js read them. (Export jobs are not kept at all; the
|
|
220
|
+
* help text says so.)
|
|
221
|
+
*
|
|
222
|
+
* @param {number|null} queueKeep - The `queueKeep` setting as stored
|
|
223
|
+
* @returns {Object} `{ completedCount, failedCount, failedCountFloor, failedCountFromSetting, failedAgeDays }`
|
|
224
|
+
*/
|
|
225
|
+
function describeRetention(queueKeep) {
|
|
226
|
+
const { removeOnComplete, removeOnFail } = buildRetentionPolicy(queueKeep ?? true);
|
|
227
|
+
return {
|
|
228
|
+
// The failed count is the environment floor or the queueKeep setting, whichever is higher,
|
|
229
|
+
// so a page that says where the number comes from has to know which one won
|
|
230
|
+
failedCountFloor: FAILED_JOB_RETENTION_COUNT,
|
|
231
|
+
failedCountFromSetting: removeOnFail.count > FAILED_JOB_RETENTION_COUNT,
|
|
232
|
+
// a boolean here is BullMQ's "remove as soon as it completes"; server.js seeds the setting
|
|
233
|
+
// with a number at boot, so this is the unset case only
|
|
234
|
+
completedCount: typeof removeOnComplete === 'object' ? removeOnComplete.count : 0,
|
|
235
|
+
failedCount: removeOnFail.count,
|
|
236
|
+
failedAgeDays: toDays(removeOnFail.age)
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function failedContentSummary() {
|
|
241
|
+
const entries = await outbox.listRetainedFailedContent();
|
|
242
|
+
const bytes = entries.reduce((sum, entry) => sum + (Number(entry.size) || 0), 0);
|
|
243
|
+
return { count: entries.length, bytes, bytesLabel: humanSize(bytes), limits: failedContentLimits() };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The bounds on retained failed-message content, for the pages that say what can be retried.
|
|
248
|
+
*
|
|
249
|
+
* @returns {Object} `{ maxCount, maxBytes, maxBytesLabel, maxAgeDays, keepsContent }`
|
|
250
|
+
*/
|
|
251
|
+
function failedContentLimits() {
|
|
252
|
+
const limits = outbox.FAILED_CONTENT_LIMITS;
|
|
253
|
+
return {
|
|
254
|
+
maxCount: limits.maxCount,
|
|
255
|
+
maxBytes: limits.maxBytes,
|
|
256
|
+
maxBytesLabel: humanSize(limits.maxBytes),
|
|
257
|
+
maxAgeDays: toDays(limits.maxAge),
|
|
258
|
+
// either bound at zero keeps no content at all
|
|
259
|
+
keepsContent: limits.maxCount > 0 && limits.maxBytes > 0
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* What is kept of completed and failed jobs, for the pages that say so.
|
|
265
|
+
*
|
|
266
|
+
* @returns {Promise<Object>} See `describeRetention()`
|
|
267
|
+
*/
|
|
268
|
+
async function retention() {
|
|
269
|
+
return describeRetention(await settings.get('queueKeep'));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* What one account holds in the queues, for the card on its page: the messages still to send,
|
|
274
|
+
* the failed ones kept for a retry, and the links to the filtered listings.
|
|
275
|
+
*
|
|
276
|
+
* The account's outbox hash has one field per message that still has content, which is every
|
|
277
|
+
* pending message plus the failed ones retained for a retry; the retained set says which are
|
|
278
|
+
* which.
|
|
279
|
+
*
|
|
280
|
+
* @param {string} account - Account ID
|
|
281
|
+
* @returns {Promise<Object>} `{ pending, failed, url, failedUrl, webhooksUrl }`
|
|
282
|
+
*/
|
|
283
|
+
async function accountQueueSummary(account) {
|
|
284
|
+
const [outboxSize, retained] = await Promise.all([redis.hlen(outbox.outboxKey(account)), outbox.listRetainedFailedContent()]);
|
|
285
|
+
const failed = retained.filter(entry => entry.account === account).length;
|
|
286
|
+
const filter = `account=${encodeURIComponent(account)}`;
|
|
287
|
+
|
|
288
|
+
return {
|
|
289
|
+
pending: Math.max(outboxSize - failed, 0),
|
|
290
|
+
failed,
|
|
291
|
+
url: `/admin/queues/submit?${filter}`,
|
|
292
|
+
failedUrl: `/admin/queues/submit?state=failed&${filter}`,
|
|
293
|
+
webhooksUrl: `/admin/queues/notify?state=failed&${filter}`
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The overview page's model: every queue with its counts, paused flag and concurrency.
|
|
299
|
+
*
|
|
300
|
+
* @returns {Promise<Object>} `{ queues, states, failedContent, retention }`
|
|
301
|
+
*/
|
|
302
|
+
async function overview() {
|
|
303
|
+
const [statuses, failedContent, kept] = await Promise.all([Promise.all(QUEUES.map(queueCounts)), failedContentSummary(), retention()]);
|
|
304
|
+
|
|
305
|
+
const queues = QUEUES.map((queueDef, i) =>
|
|
306
|
+
Object.assign({}, queueDef, statuses[i], {
|
|
307
|
+
concurrency: concurrencyInfo(queueDef),
|
|
308
|
+
stateCounts: STATES.map(state =>
|
|
309
|
+
Object.assign({}, state, { count: statuses[i].counts[state.name], url: `/admin/queues/${queueDef.name}?state=${state.name}` })
|
|
310
|
+
)
|
|
311
|
+
})
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
return { queues, states: STATES, failedContent, retention: kept };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Reads the jobs for a list of IDs, in order, dropping the ones that vanished meanwhile.
|
|
319
|
+
*
|
|
320
|
+
* @param {Object} queueObj - BullMQ Queue
|
|
321
|
+
* @param {string[]} ids - Job IDs
|
|
322
|
+
* @param {Object} logger - Logger instance
|
|
323
|
+
* @returns {Promise<Object[]>} Jobs
|
|
324
|
+
*/
|
|
325
|
+
async function loadJobs(queueObj, ids, logger) {
|
|
326
|
+
const jobs = [];
|
|
327
|
+
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
|
|
328
|
+
const batch = await Promise.all(
|
|
329
|
+
ids.slice(i, i + BATCH_SIZE).map(async id => {
|
|
330
|
+
try {
|
|
331
|
+
return await queueObj.getJob(id);
|
|
332
|
+
} catch (err) {
|
|
333
|
+
logger.error({ msg: 'Failed to read a queue job', queue: queueObj.name, job: id, err });
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
})
|
|
337
|
+
);
|
|
338
|
+
for (const job of batch) {
|
|
339
|
+
if (job) {
|
|
340
|
+
jobs.push(job);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return jobs;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Fills in what a row cannot know from the job alone: whether the account still exists, plus
|
|
349
|
+
* whatever the queue's own decoration adds (a route name, a message's retained content).
|
|
350
|
+
*
|
|
351
|
+
* @param {Object} queueDef - Queue definition
|
|
352
|
+
* @param {Object[]} entries - Formatted entries
|
|
353
|
+
* @param {Object} logger - Logger instance
|
|
354
|
+
*/
|
|
355
|
+
async function decorateEntries(queueDef, entries, logger) {
|
|
356
|
+
if (!entries.length) {
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const [known] = await Promise.all([
|
|
361
|
+
accountsExist(redis, Array.from(new Set(entries.map(entry => entry.account).filter(Boolean)))),
|
|
362
|
+
QUEUE_OPS[queueDef.name].decorate(entries, logger)
|
|
363
|
+
]);
|
|
364
|
+
|
|
365
|
+
for (const entry of entries) {
|
|
366
|
+
entry.accountKnown = entry.account ? !!known.get(entry.account) : false;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* One page of a queue's jobs in a state, optionally filtered.
|
|
372
|
+
*
|
|
373
|
+
* Without a filter the page is read straight out of the state's list, so the cost is one page
|
|
374
|
+
* of jobs whatever the queue holds. With a filter the state is scanned from its head up to
|
|
375
|
+
* SCAN_LIMIT jobs and the matches paged in memory; the result says how far the scan went so the
|
|
376
|
+
* page can tell the reader when a busy queue was not searched to the end.
|
|
377
|
+
*
|
|
378
|
+
* @param {Object} options
|
|
379
|
+
* @param {Object} options.queue - Queue definition
|
|
380
|
+
* @param {string} options.state - Job state
|
|
381
|
+
* @param {number} [options.stateTotal] - How many jobs the state holds, when the caller counted already
|
|
382
|
+
* @param {number} [options.page] - Zero-based page
|
|
383
|
+
* @param {number} [options.pageSize] - Entries per page
|
|
384
|
+
* @param {string} [options.query] - Free-text filter
|
|
385
|
+
* @param {string} [options.account] - Account filter (exact)
|
|
386
|
+
* @param {string} [options.route] - Webhook route filter (exact, notify queue)
|
|
387
|
+
* @param {Object} options.logger - Logger instance
|
|
388
|
+
* @returns {Promise<Object>} `{ entries, total, page, pages, filtered, scanned, scanLimited, stateTotal }`
|
|
389
|
+
*/
|
|
390
|
+
async function listJobs(options) {
|
|
391
|
+
const { queue: queueDef, state, logger } = options;
|
|
392
|
+
const page = Math.max(Number(options.page) || 0, 0);
|
|
393
|
+
const pageSize = Math.max(Number(options.pageSize) || 20, 1);
|
|
394
|
+
const query = options.query || '';
|
|
395
|
+
const account = options.account || '';
|
|
396
|
+
const route = options.route || '';
|
|
397
|
+
|
|
398
|
+
const queueObj = queueObject(queueDef);
|
|
399
|
+
const asc = !STATES_BY_NAME.get(state).newestFirst;
|
|
400
|
+
|
|
401
|
+
const stateTotal = typeof options.stateTotal === 'number' ? options.stateTotal : Number((await queueObj.getJobCounts(state))[state]) || 0;
|
|
402
|
+
|
|
403
|
+
let entries;
|
|
404
|
+
let total;
|
|
405
|
+
let scanned = 0;
|
|
406
|
+
let scanLimited = false;
|
|
407
|
+
const filtered = !!(query || account || route);
|
|
408
|
+
|
|
409
|
+
if (!filtered) {
|
|
410
|
+
total = stateTotal;
|
|
411
|
+
const start = page * pageSize;
|
|
412
|
+
const ids = start < total ? await queueObj.getRanges([state], start, start + pageSize - 1, asc) : [];
|
|
413
|
+
const jobs = await loadJobs(queueObj, ids, logger);
|
|
414
|
+
entries = jobs.map(job => formatJob(queueDef, job, state));
|
|
415
|
+
} else {
|
|
416
|
+
// Every ID of the scan window in one read, then the jobs in batches
|
|
417
|
+
const ids = stateTotal ? await queueObj.getRanges([state], 0, SCAN_LIMIT - 1, asc) : [];
|
|
418
|
+
const jobs = await loadJobs(queueObj, ids, logger);
|
|
419
|
+
scanned = ids.length;
|
|
420
|
+
scanLimited = scanned >= SCAN_LIMIT && stateTotal > scanned;
|
|
421
|
+
|
|
422
|
+
const matches = jobs.filter(job => {
|
|
423
|
+
const data = job.data || {};
|
|
424
|
+
return (!account || data.account === account) && (!route || (data._route && data._route.id === route)) && matchesQuery(queueDef, job, query);
|
|
425
|
+
});
|
|
426
|
+
total = matches.length;
|
|
427
|
+
entries = matches.slice(page * pageSize, (page + 1) * pageSize).map(job => formatJob(queueDef, job, state));
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
await decorateEntries(queueDef, entries, logger);
|
|
431
|
+
|
|
432
|
+
return {
|
|
433
|
+
entries,
|
|
434
|
+
total,
|
|
435
|
+
page,
|
|
436
|
+
pages: Math.max(Math.ceil(total / pageSize), 1),
|
|
437
|
+
filtered,
|
|
438
|
+
scanned,
|
|
439
|
+
scanLimited,
|
|
440
|
+
stateTotal
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* One job, formatted for its detail page, with the raw record beside it.
|
|
446
|
+
*
|
|
447
|
+
* @param {Object} options
|
|
448
|
+
* @param {Object} options.queue - Queue definition
|
|
449
|
+
* @param {string} options.jobId - Job ID
|
|
450
|
+
* @param {Object} options.logger - Logger instance
|
|
451
|
+
* @returns {Promise<Object|null>} `{ entry, raw }`, or null when there is no such job
|
|
452
|
+
*/
|
|
453
|
+
async function getJob(options) {
|
|
454
|
+
const { queue: queueDef, jobId, logger } = options;
|
|
455
|
+
|
|
456
|
+
const job = await queueObject(queueDef).getJob(jobId);
|
|
457
|
+
if (!job) {
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const state = await job.getState();
|
|
462
|
+
if (state === 'unknown') {
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const entry = formatJob(queueDef, job, state);
|
|
467
|
+
await decorateEntries(queueDef, [entry], logger);
|
|
468
|
+
|
|
469
|
+
const raw = rawJob(job);
|
|
470
|
+
if (queueDef.name === 'submit') {
|
|
471
|
+
// The stored data of a submission names the proxy it was told to use, credentials
|
|
472
|
+
// included, and a failed one records the route it took. Masked the way the outbox API
|
|
473
|
+
// masks them, on a copy, so the page shows the record without echoing a password
|
|
474
|
+
raw.data = maskSecrets(structuredClone(raw.data || {}));
|
|
475
|
+
if (raw.progress) {
|
|
476
|
+
raw.progress = maskSecrets(structuredClone(raw.progress));
|
|
477
|
+
}
|
|
478
|
+
} else if (queueDef.name === 'notify') {
|
|
479
|
+
entry.payloadSizeLabel = humanSize(notifyPayloadSize(job));
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
return { entry, raw };
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Pauses or resumes a queue. A paused queue keeps accepting jobs; the workers stop taking them.
|
|
487
|
+
*
|
|
488
|
+
* @param {Object} queueDef - Queue definition
|
|
489
|
+
* @param {boolean} paused - Whether the queue should be paused
|
|
490
|
+
* @returns {Promise<boolean>} The queue's paused state afterwards
|
|
491
|
+
*/
|
|
492
|
+
async function setPaused(queueDef, paused) {
|
|
493
|
+
const queueObj = queueObject(queueDef);
|
|
494
|
+
if (paused) {
|
|
495
|
+
await queueObj.pause();
|
|
496
|
+
} else {
|
|
497
|
+
await queueObj.resume();
|
|
498
|
+
}
|
|
499
|
+
return !!(await queueObj.isPaused());
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Removes every finished job of a state: the completed or the failed set. For the submit queue a
|
|
504
|
+
* cleaned failed set takes the retained message contents with it, which is what BullMQ's own
|
|
505
|
+
* clean cannot do.
|
|
506
|
+
*
|
|
507
|
+
* @param {Object} options
|
|
508
|
+
* @param {Object} options.queue - Queue definition
|
|
509
|
+
* @param {string} options.state - `completed` or `failed`
|
|
510
|
+
* @param {Object} options.logger - Logger instance
|
|
511
|
+
* @returns {Promise<number>} How many jobs were removed
|
|
512
|
+
*/
|
|
513
|
+
async function cleanQueue(options) {
|
|
514
|
+
const { queue: queueDef, state, logger } = options;
|
|
515
|
+
if (!['completed', 'failed'].includes(state)) {
|
|
516
|
+
throw statusError('Only completed and failed jobs can be cleaned', 'NotCleanable', 409);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
const removed = await queueObject(queueDef).clean(0, 1000000, state);
|
|
520
|
+
await QUEUE_OPS[queueDef.name].afterClean({ state, logger });
|
|
521
|
+
|
|
522
|
+
logger.info({ msg: 'Queue cleaned', queue: queueDef.name, state, removed: removed.length });
|
|
523
|
+
return removed.length;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Runs one of the per-job actions, after checking the queue offers it.
|
|
528
|
+
*
|
|
529
|
+
* @param {string} action - remove, retry or promote
|
|
530
|
+
* @param {Object} options
|
|
531
|
+
* @param {Object} options.queue - Queue definition
|
|
532
|
+
* @param {string} options.jobId - Job ID
|
|
533
|
+
* @param {Object} options.logger - Logger instance
|
|
534
|
+
* @returns {Promise<Object|boolean>} For remove `{ removed, locked }`; otherwise false when there is no such job, true when done
|
|
535
|
+
* @throws {Error} With `statusCode` 409 when the queue does not offer the action or the job is in the wrong state
|
|
536
|
+
*/
|
|
537
|
+
async function runJobAction(action, options) {
|
|
538
|
+
const { queue: queueDef } = options;
|
|
539
|
+
const run = queueDef.actions[action] && QUEUE_OPS[queueDef.name][action];
|
|
540
|
+
if (!run) {
|
|
541
|
+
throw statusError(
|
|
542
|
+
`A ${queueDef.noun} cannot be ${action === 'remove' ? 'removed' : action === 'retry' ? 'retried' : 'promoted'} from here`,
|
|
543
|
+
'NotOffered',
|
|
544
|
+
409
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
return run(options);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
module.exports = {
|
|
551
|
+
QUEUES_BY_NAME,
|
|
552
|
+
STATES,
|
|
553
|
+
STATES_BY_NAME,
|
|
554
|
+
overview,
|
|
555
|
+
retention,
|
|
556
|
+
failedContentLimits,
|
|
557
|
+
accountQueueSummary,
|
|
558
|
+
allCounts,
|
|
559
|
+
queueCounts,
|
|
560
|
+
listJobs,
|
|
561
|
+
getJob,
|
|
562
|
+
jobState,
|
|
563
|
+
entryUrl,
|
|
564
|
+
setPaused,
|
|
565
|
+
cleanQueue,
|
|
566
|
+
runJobAction,
|
|
567
|
+
concurrencyInfo
|
|
568
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The actions the queue browser and the outbox API take on a BullMQ job, written once: a retry
|
|
4
|
+
// resets the attempt count, a promote needs a delayed job, a removal refuses a job a worker is
|
|
5
|
+
// running. The submit queue's own rules (the message content that lives beside the job) are
|
|
6
|
+
// layered on top of these by lib/outbox.js; the webhook queue uses them as they are.
|
|
7
|
+
//
|
|
8
|
+
// Dependency-free apart from the error shape, so lib/outbox.js can use it without a cycle
|
|
9
|
+
// through the queue browser.
|
|
10
|
+
|
|
11
|
+
const { statusError } = require('./utils/status-error');
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Puts a failed job back into the queue with a fresh set of attempts.
|
|
15
|
+
*
|
|
16
|
+
* Reset, not resumed: a job that used all its attempts would otherwise get one more and fail for
|
|
17
|
+
* good again on the first transient error. The stored progress still describes the failure, so it
|
|
18
|
+
* is replaced by the "queued" marker the submit worker writes for a new job; the worker overwrites
|
|
19
|
+
* it once it picks the job up.
|
|
20
|
+
*
|
|
21
|
+
* @param {Object} job - BullMQ job, already loaded and known to be in the failed state
|
|
22
|
+
* @param {string} noun - What the job is, for the refusal message ("message", "webhook delivery")
|
|
23
|
+
* @throws {Error} With `statusCode` 409 and `code` NotFailed when BullMQ refuses (the job left the
|
|
24
|
+
* failed set meanwhile, or a worker holds its lock)
|
|
25
|
+
*/
|
|
26
|
+
async function retryFailedJob(job, noun) {
|
|
27
|
+
try {
|
|
28
|
+
await job.retry('failed', { resetAttemptsMade: true, resetAttemptsStarted: true });
|
|
29
|
+
} catch (err) {
|
|
30
|
+
throw statusError(`The ${noun} could not be retried: ${err.message}`, 'NotFailed', 409);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
await job.updateProgress({ status: 'queued' });
|
|
35
|
+
} catch (err) {
|
|
36
|
+
// best effort, like every other progress write
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Runs a delayed job at the next opportunity instead of at its time.
|
|
42
|
+
*
|
|
43
|
+
* @param {Object} job - BullMQ job, already loaded and known to be in the delayed state
|
|
44
|
+
* @param {string} noun - What the job is, for the refusal message
|
|
45
|
+
* @throws {Error} With `statusCode` 409 and `code` NotDelayed when BullMQ refuses
|
|
46
|
+
*/
|
|
47
|
+
async function promoteDelayedJob(job, noun) {
|
|
48
|
+
try {
|
|
49
|
+
await job.promote();
|
|
50
|
+
} catch (err) {
|
|
51
|
+
throw statusError(`The ${noun} could not be promoted: ${err.message}`, 'NotDelayed', 409);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Asserts the state an action needs, in the words the pages and the API show.
|
|
57
|
+
*
|
|
58
|
+
* @param {Object} job - BullMQ job
|
|
59
|
+
* @param {string} state - The state the action applies to
|
|
60
|
+
* @param {string} noun - What the job is
|
|
61
|
+
* @param {string} verb - What the caller wants to do ("retried", "sent now")
|
|
62
|
+
* @throws {Error} With `statusCode` 409 and a code naming the state the job is not in
|
|
63
|
+
*/
|
|
64
|
+
async function assertJobState(job, state, noun, verb) {
|
|
65
|
+
if ((await job.getState()) !== state) {
|
|
66
|
+
const code = state === 'failed' ? 'NotFailed' : state === 'delayed' ? 'NotDelayed' : 'WrongState';
|
|
67
|
+
const sentence =
|
|
68
|
+
state === 'failed'
|
|
69
|
+
? `Only a ${noun} whose delivery has failed can be ${verb}`
|
|
70
|
+
: `Only a ${noun} waiting for its scheduled time or for its next attempt can be ${verb}`;
|
|
71
|
+
throw statusError(sentence, code, 409);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = { retryFailedJob, promoteDelayedJob, assertJobState };
|