Files
mtusi2026lab5/src/jobs/admin.ts
T
celis a4a7b9d41a Реализовать лабораторную 5: очередь RabbitMQ, worker и outbox
- upload возвращает 202 после записи оригинала в staging/ и одной
  транзакции attachments + jobs + outbox
- relay outbox → RabbitMQ (quorum-очередь, publisher confirms) в каждой
  реплике API; sweeper возвращает работу с истёкшей арендой
- worker: аренда с fencing-токеном, варианты thumbnail/crop/optimized
  (sharp), retry с backoff и jitter, реестр failed, replay с аудитом,
  reprocess новой версией pipeline
- reconciler дочищает staging/ и variants/
- сценарии уровней 3–4, fault-injection трека 2 (14 сценариев,
  инварианты I1–I6), evidence и REPORT.md
2026-10-31 00:31:54 +03:00

83 lines
5.8 KiB
TypeScript

// Операторские команды над заданиями (выполняются в контейнере api: docker compose exec api node src/main.ts …).
// failed — реестр failed (аналог DLQ): job, вложение, код ошибки, попытки
// replay <attachment_id> — failed → queued: новая попытка той же логической job с аудитом;
// для done/queued/processing — отказ (повтор не дублирует успешную работу)
// reprocess --version=N — поставить job версии N для ready-вложений с более старой версией (трек 5);
// вложения в работе не затрагиваются — после разбора очереди команду повторяют
// show <attachment_id> — вложение, его jobs, попытки в outbox (время следующей), replay-аудит, варианты
import type { Pool } from 'pg';
import { UUID } from '../http/request.ts';
export async function adminCommand(db: Pool, args: string[]): Promise<void> {
const [cmd, arg] = args;
if (cmd === 'failed') {
const r = await db.query(`SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempts, j.error_code, rfc3339(j.updated_at) AS failed_at
FROM jobs j WHERE j.state = 'failed' ORDER BY j.updated_at`);
for (const row of r.rows) console.log(JSON.stringify(row));
console.log(JSON.stringify({ failed: r.rowCount }));
} else if (cmd === 'replay') {
if (!UUID.test(arg ?? '')) throw new Error('replay <attachment_id>');
console.log(JSON.stringify(await replay(db, arg.toLowerCase())));
} else if (cmd === 'reprocess') {
const version = Number(args.find((a) => a.startsWith('--version='))?.split('=')[1]);
if (!Number.isInteger(version) || version < 1) throw new Error('reprocess --version=N');
const r = await db.query(`WITH j AS (
INSERT INTO jobs (job_id, attachment_id, pipeline_version)
SELECT gen_random_uuid(), a.id, $1 FROM attachments a WHERE a.state = 'ready' AND a.pipeline_version < $1
ON CONFLICT (attachment_id, pipeline_version) DO NOTHING RETURNING job_id)
INSERT INTO outbox (job_id, attempt) SELECT job_id, 1 FROM j`, [version]);
console.log(JSON.stringify({ reprocess_version: version, enqueued: r.rowCount }));
} else if (cmd === 'show') {
if (!UUID.test(arg ?? '')) throw new Error('show <attachment_id>');
const q = async (sql: string) => (await db.query(sql, [arg.toLowerCase()])).rows;
console.log(JSON.stringify({
attachment: (await q(`SELECT id, state, pipeline_version, error_code, staging_key IS NOT NULL AS has_staging
FROM attachments WHERE id = $1`))[0] ?? null,
jobs: await q(`SELECT job_id, pipeline_version, state, attempts, error_code, rfc3339(lease_until) AS lease_until
FROM jobs WHERE attachment_id = $1 ORDER BY pipeline_version`),
outbox: await q(`SELECT j.pipeline_version, o.attempt, rfc3339(o.available_at) AS available_at, rfc3339(o.published_at) AS published_at
FROM outbox o JOIN jobs j ON j.job_id = o.job_id WHERE j.attachment_id = $1 ORDER BY o.id`),
replays: await q(`SELECT r.previous_error, r.previous_attempts, rfc3339(r.replayed_at) AS replayed_at
FROM job_replays r JOIN jobs j ON j.job_id = r.job_id WHERE j.attachment_id = $1 ORDER BY r.replayed_at`),
variants: await q(`SELECT pipeline_version, name, width, height, size_bytes, left(sha256, 12) AS sha256
FROM attachment_variants WHERE attachment_id = $1 ORDER BY pipeline_version, name`),
}));
} else {
throw new Error('jobs failed | replay <attachment_id> | reprocess --version=N | show <attachment_id>');
}
}
async function replay(db: Pool, attachmentId: string) {
const client = await db.connect();
try {
await client.query('BEGIN');
const j = (await client.query(`SELECT j.job_id, j.state, j.attempts, j.error_code, a.pipeline_version IS NULL AS initial
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE j.attachment_id = $1 ORDER BY j.pipeline_version DESC LIMIT 1 FOR UPDATE OF j`, [attachmentId])).rows[0];
if (!j) throw new Error('у вложения нет заданий');
if (j.state !== 'failed') {
await client.query('ROLLBACK');
return { replayed: false, reason: `job в состоянии ${j.state}: повтор не нужен` };
}
// Staging failed-вложения хранится STAGING_RETENTION_SECONDS; после очистки повторять нечего.
if (j.initial) {
const s = await client.query(`SELECT 1 FROM attachments WHERE id = $1 AND staging_key IS NOT NULL`, [attachmentId]);
if (!s.rowCount) throw new Error('исходник недоступен');
}
await client.query('INSERT INTO job_replays (job_id, previous_error, previous_attempts) VALUES ($1, $2, $3)', [j.job_id, j.error_code, j.attempts]);
// Новая серия попыток той же логической job: прежний эффект защищён ключом (attachment_id, version, name).
await client.query(`UPDATE jobs SET state = 'queued', attempts = 0, error_code = NULL, updated_at = clock_timestamp() WHERE job_id = $1`, [j.job_id]);
await client.query('INSERT INTO outbox (job_id, attempt) VALUES ($1, 1)', [j.job_id]);
if (j.initial) {
await client.query(`UPDATE attachments SET state = 'queued', error_code = NULL, updated_at = clock_timestamp() WHERE id = $1 AND state = 'failed'`, [attachmentId]);
}
await client.query('COMMIT');
return { replayed: true, job_id: j.job_id, previous_error: j.error_code, previous_attempts: j.attempts };
} catch (err) {
await client.query('ROLLBACK').catch(() => {});
throw err;
} finally {
client.release();
}
}