mirror of
https://github.com/wekan/wekan.git
synced 2026-11-24 20:45:00 -05:00
Summarize recipients without mail payloads, paginate with bounded memory, and coordinate pause/resume/cancel with sender reservations. Persist holds, cancellation cutoffs and idempotent request receipts so replay cannot undo newer actions or cancel later messages. Verify current administrator access, interrupted commands, lost write acknowledgements, stable cancellation and private collection boundaries with MongoDB and Chromium tests. Keep translations limited to English source labels. Thanks to xet7 !
83 lines
4.9 KiB
JavaScript
83 lines
4.9 KiB
JavaScript
const { withSyncLease } = require('./syncLease');
|
|
const ACTIONS = ['pause', 'resume', 'cancel'];
|
|
const REQUEST_ID = /^[A-Za-z0-9_-]{20,64}$/;
|
|
const PAYLOAD_FIELDS = { html: '', subject: '', language: '', cardId: '', nextAttemptAt: '', lastFailure: '' };
|
|
|
|
// A stable request receipt prevents a reconnect from repeating an old cancel
|
|
// against mail queued later. Generation fencing also makes an interrupted old
|
|
// request harmless after a newer operator action has already taken effect.
|
|
async function controlEmailOutbox({ jobs, controls, commands, leases, userId, action, requestId, actorId,
|
|
assertAdmin, now = () => new Date(), leaseOptions = {} }) {
|
|
if (typeof userId !== 'string' || !userId || userId.length > 200 ||
|
|
!ACTIONS.includes(action) || typeof requestId !== 'string' || !REQUEST_ID.test(requestId) ||
|
|
typeof actorId !== 'string' || !actorId || typeof assertAdmin !== 'function') throw new Error('invalid-email-control');
|
|
return withSyncLease(leases, userId, async ({ assertCurrent }) => {
|
|
const guard = async () => { await assertCurrent(); await assertAdmin(); };
|
|
await guard();
|
|
let command = await commands.findOne({ _id: requestId });
|
|
if (command && (command.userId !== userId || command.action !== action || command.actorId !== actorId)) {
|
|
throw new Error('email-control-identity-mismatch');
|
|
}
|
|
if (command?.status === 'completed' || command?.status === 'superseded') return { status: command.status };
|
|
let current = await controls.findOne({ _id: userId });
|
|
if (!command) {
|
|
command = { _id: requestId, userId, action, actorId, cutoff: now(),
|
|
generation: (current?.generation || 0) + 1, status: 'pending' };
|
|
try { await commands.insertOne(command); }
|
|
catch (error) {
|
|
const saved = await commands.findOne({ _id: requestId });
|
|
if (!saved || saved.userId !== userId || saved.action !== action || saved.actorId !== actorId ||
|
|
saved.generation !== command.generation || +saved.cutoff !== +command.cutoff) throw error;
|
|
}
|
|
const saved = await commands.findOne({ _id: requestId });
|
|
if (!saved || saved.generation !== command.generation || +saved.cutoff !== +command.cutoff) throw new Error('email-control-not-stored');
|
|
}
|
|
await guard();
|
|
const finish = async status => {
|
|
try { await commands.updateOne({ _id: requestId, status: 'pending' }, { $set: { status, finishedAt: now() } }); }
|
|
catch (error) {
|
|
if ((await commands.findOne({ _id: requestId }))?.status !== status) throw error;
|
|
}
|
|
if ((await commands.findOne({ _id: requestId }))?.status !== status) throw new Error('email-control-not-confirmed');
|
|
await guard();
|
|
return { status };
|
|
};
|
|
if ((current?.generation || 0) > command.generation ||
|
|
(current?.generation === command.generation && current.lastRequestId !== requestId)) {
|
|
return finish('superseded');
|
|
}
|
|
if ((current?.generation || 0) < command.generation) {
|
|
if ((current?.generation || 0) !== command.generation - 1) throw new Error('email-control-generation-mismatch');
|
|
const set = { generation: command.generation, lastRequestId: requestId,
|
|
lastAction: action, changedAt: command.cutoff, changedBy: actorId };
|
|
if (action !== 'cancel') set.paused = action === 'pause';
|
|
else set.cancelBefore = new Date(Math.max(+current?.cancelBefore || 0, +command.cutoff));
|
|
const selector = { _id: userId, generation: current?.generation ?? { $exists: false } };
|
|
try {
|
|
await controls.updateOne(selector, { $set: set, $inc: { [`${action}Count`]: 1 } }, { upsert: true });
|
|
} catch (error) {
|
|
const saved = await controls.findOne({ _id: userId });
|
|
if (saved?.generation !== command.generation || saved.lastRequestId !== requestId) throw error;
|
|
}
|
|
current = await controls.findOne({ _id: userId });
|
|
}
|
|
if (current?.generation !== command.generation || current.lastRequestId !== requestId) {
|
|
throw new Error('email-control-generation-mismatch');
|
|
}
|
|
await guard();
|
|
const pending = { userId, state: 'pending', createdAt: { $lte: command.cutoff } };
|
|
if (action === 'cancel') {
|
|
try { await jobs.updateMany(pending, { $set: { state: 'cancelled', finishedAt: now() }, $unset: PAYLOAD_FIELDS }); }
|
|
catch (error) { if (await jobs.countDocuments(pending)) throw error; }
|
|
if (await jobs.countDocuments(pending)) throw new Error('email-control-cancel-incomplete');
|
|
} else if (action === 'resume') {
|
|
const waiting = { ...pending, nextAttemptAt: { $gt: command.cutoff } };
|
|
try { await jobs.updateMany(pending, { $set: { nextAttemptAt: command.cutoff } }); }
|
|
catch (error) { if (await jobs.countDocuments(waiting)) throw error; }
|
|
if (await jobs.countDocuments(waiting)) throw new Error('email-control-resume-incomplete');
|
|
}
|
|
return finish('completed');
|
|
}, { ...leaseOptions, now });
|
|
}
|
|
module.exports = { controlEmailOutbox, ACTIONS, PAYLOAD_FIELDS };
|