Files
mtusi2026lab6/src/jobs/admin.ts
T
celis 51b02a541d Реализовать лабораторную 6: OpenTelemetry, Grafana, SLO и burn-rate alerts
- api и worker отдают traces, metrics и logs по OTLP в Collector
  (memory_limiter, redaction, batch, ограниченная очередь и retry);
  хранилища: Prometheus (OTLP receiver), Loki, Tempo; Grafana с
  provisioning datasources и dashboard «Messenger lab6»
- W3C trace context через outbox и RabbitMQ: producer/consumer spans
  связывают upload, публикации и попытки worker в одном trace
- SLO доступности API (SLI на HAProxy) и времени до ready, multiwindow
  burn-rate alerts, ApiHighErrorRate, JobQueueLagGrowing,
  DbPoolSaturated, TelemetryExportFailing; unit-тесты promtool, runbooks
- кампания трека 2 (k6, 6 отказов по расписанию), разбор и графики;
  проверки сигналов и истории telemetry, evidence и REPORT.md
2026-10-31 01:45:56 +03:00

89 lines
6.4 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).
// created_at — момент повторного приёма: time-to-ready и возраст задания (lag alert) считаются от replay,
// а не от исходной загрузки, уже учтённой в SLO как failed.
await client.query(`UPDATE jobs SET state = 'queued', attempts = 0, error_code = NULL, created_at = clock_timestamp(),
updated_at = clock_timestamp() WHERE job_id = $1`, [j.job_id]);
// Trace context последней публикации: повтор оператора виден в том же trace, что и исходная загрузка.
await client.query(`INSERT INTO outbox (job_id, attempt, traceparent, tracestate)
SELECT $1, 1, l.traceparent, l.tracestate FROM (SELECT 1) one
LEFT JOIN LATERAL (SELECT traceparent, tracestate FROM outbox WHERE job_id = $1 ORDER BY id DESC LIMIT 1) l ON true`, [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();
}
}