ЛР 7: mTLS, OpenBao и проверка компрометации worker
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
// Операторские команды над заданиями (выполняются в контейнере 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// RabbitMQ: формат сообщения job (contracts/jobs.schema.json), публикация с publisher confirm.
|
||||
// Топология (exchange attachments → quorum-очередь attachments.process) и пользователи создаются из
|
||||
// definitions при старте брокера (scripts/init-secrets.sh); у API право только писать в exchange.
|
||||
import amqp, { type ChannelModel, type ConfirmChannel } from 'amqplib';
|
||||
import { serviceTls } from '../security.ts';
|
||||
import { UUID } from '../http/request.ts';
|
||||
import { log } from '../otel.ts';
|
||||
|
||||
export const EXCHANGE = 'attachments';
|
||||
export const ROUTING_KEY = 'process';
|
||||
export const QUEUE = 'attachments.process';
|
||||
|
||||
// В сообщении только идентификаторы: ни байтов, ни ключей S3, ни credentials. Worker берёт данные из БД.
|
||||
export type Job = {
|
||||
schema_version: 1;
|
||||
job_id: string;
|
||||
type: 'attachment.process.v1';
|
||||
attachment_id: string;
|
||||
pipeline_version: number;
|
||||
attempt: number;
|
||||
created_at: string;
|
||||
traceparent?: string; // W3C trace context PRODUCER span (lab6), см. src/jobs/relay.ts
|
||||
tracestate?: string;
|
||||
};
|
||||
|
||||
const TRACEPARENT = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
|
||||
|
||||
// Проверка входящего сообщения по jobs.schema.json; null — сообщение не по контракту.
|
||||
export function parseJob(content: Buffer): Job | null {
|
||||
let j: Record<string, unknown>;
|
||||
try {
|
||||
j = JSON.parse(content.toString('utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const keys = ['schema_version', 'job_id', 'type', 'attachment_id', 'pipeline_version', 'attempt', 'created_at', 'traceparent', 'tracestate'];
|
||||
const ok = typeof j === 'object' && j !== null && Object.keys(j).every((k) => keys.includes(k))
|
||||
&& j.schema_version === 1 && j.type === 'attachment.process.v1'
|
||||
&& typeof j.job_id === 'string' && UUID.test(j.job_id) && typeof j.attachment_id === 'string' && UUID.test(j.attachment_id)
|
||||
&& Number.isInteger(j.pipeline_version) && (j.pipeline_version as number) >= 1
|
||||
&& Number.isInteger(j.attempt) && (j.attempt as number) >= 1
|
||||
&& typeof j.created_at === 'string' && !Number.isNaN(Date.parse(j.created_at))
|
||||
&& (j.traceparent === undefined || (typeof j.traceparent === 'string' && TRACEPARENT.test(j.traceparent)))
|
||||
&& (j.tracestate === undefined || (typeof j.tracestate === 'string' && j.tracestate.length <= 512));
|
||||
return ok ? (j as unknown as Job) : null;
|
||||
}
|
||||
|
||||
export function brokerConnect(timeout: number) {
|
||||
return amqp.connect('amqps://rabbitmq:5671/messenger?heartbeat=10', {
|
||||
...serviceTls(), timeout, credentials: amqp.credentials.external(),
|
||||
});
|
||||
}
|
||||
|
||||
export type Publisher = { publish(jobs: Job[]): Promise<void> };
|
||||
|
||||
// Ленивое соединение: брокер может быть недоступен — тогда publish бросает ошибку, а задания остаются в outbox.
|
||||
export function createPublisher(): Publisher {
|
||||
let channel: Promise<ConfirmChannel> | null = null;
|
||||
let conn: ChannelModel | null = null;
|
||||
const open = async () => {
|
||||
conn = await brokerConnect(2000);
|
||||
const reset = () => { channel = null; };
|
||||
conn.on('error', reset);
|
||||
conn.on('close', reset);
|
||||
const ch = await conn.createConfirmChannel();
|
||||
ch.on('error', reset);
|
||||
ch.on('close', reset);
|
||||
// mandatory + return: сообщение без маршрута (сломана топология) не исчезает молча.
|
||||
ch.on('return', (m) => log('error', 'broker.unroutable', `брокер вернул неотмаршрутизированное сообщение ${m.properties.messageId}`));
|
||||
return ch;
|
||||
};
|
||||
return {
|
||||
async publish(jobs) {
|
||||
channel ??= open().catch((err) => { channel = null; throw err; });
|
||||
const ch = await channel;
|
||||
for (const job of jobs) {
|
||||
ch.publish(EXCHANGE, ROUTING_KEY, Buffer.from(JSON.stringify(job)), {
|
||||
persistent: true, mandatory: true, contentType: 'application/json', messageId: `${job.job_id}:${job.attempt}`,
|
||||
});
|
||||
}
|
||||
// Publisher confirm: брокер записал сообщения в quorum-очередь (на диск). Только после этого outbox отмечается.
|
||||
// Зависший брокер не держит транзакцию relay вечно: через 5 с соединение закрывается, строки остаются в outbox.
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
channel = null;
|
||||
conn?.close().catch(() => {});
|
||||
reject(new Error('нет publisher confirm за 5 с'));
|
||||
}, 5000);
|
||||
});
|
||||
try {
|
||||
await Promise.race([ch.waitForConfirms(), timeout]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Метрики заданий (contracts/observability.md), общие для API (relay, sweeper) и worker.
|
||||
// Атрибуты только низкой кардинальности: тип job, исход, код ошибки; идентификаторы — в логах и spans.
|
||||
import { meter } from '../otel.ts';
|
||||
|
||||
export const JOB_TYPE = 'attachment.process.v1';
|
||||
|
||||
// Длительность одной обработки сообщения worker-ом; _count по outcome — счётчик обработанных/ошибочных jobs.
|
||||
// outcome: done | retry | failed | noop | discarded | error (сбой вне попытки, сообщение вернётся в очередь).
|
||||
export const jobDuration = meter.createHistogram('messenger.job.duration', {
|
||||
unit: 's',
|
||||
description: 'Processing time of one job delivery by the worker',
|
||||
advice: { explicitBucketBoundaries: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60] },
|
||||
});
|
||||
|
||||
// От durable acceptance (COMMIT задания при загрузке) до публикации ready (outcome=ready) или до терминальной
|
||||
// ошибки (outcome=failed, error.type = error_code). Время считает PostgreSQL одними часами для обеих точек.
|
||||
// Граница 30 с совпадает с порогом SLO time-to-ready (infra/prometheus/rules/slo.yml).
|
||||
export const timeToReady = meter.createHistogram('messenger.attachment.time_to_ready', {
|
||||
unit: 's',
|
||||
description: 'Time from durable upload acceptance to published ready (or terminal failure)',
|
||||
advice: { explicitBucketBoundaries: [0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600] },
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
// Relay transactional outbox → RabbitMQ и восстановление зависшей работы. Работает в каждой реплике API.
|
||||
// publishDue: строки outbox, у которых наступил available_at, блокируются FOR UPDATE SKIP LOCKED (две реплики
|
||||
// не публикуют одну строку одновременно), публикуются с publisher confirm и только потом отмечаются.
|
||||
// Падение после confirm, но до отметки → повторная публикация → дубль, который worker распознаёт по job.
|
||||
// sweep: истёкшая аренда (worker умер/завис) → новая попытка или failed retry_exhausted; queued без живого
|
||||
// сообщения (потеряно брокером, отброшено delivery-limit) → публикуется снова. Источник истины — БД.
|
||||
// Lab6: каждое сообщение публикуется в PRODUCER span, дочернем к контексту строки outbox (запрос загрузки,
|
||||
// попытка worker-а или, у sweeper, предыдущая публикация той же job), и несёт traceparent/tracestate этого span
|
||||
// в теле (contracts/jobs.schema.json) — worker продолжает тот же trace. Здесь же метрики очереди по БД.
|
||||
import { ROOT_CONTEXT, SpanKind, SpanStatusCode, context, trace, type Span } from '@opentelemetry/api';
|
||||
import type { Pool, PoolClient, QueryConfig } from 'pg';
|
||||
import type { JobsConfig } from '../config.ts';
|
||||
import { failpoint } from '../failpoints.ts';
|
||||
import { contextFrom, log, meter, traceCarrier, tracer } from '../otel.ts';
|
||||
import { EXCHANGE, QUEUE, ROUTING_KEY, type Job, type Publisher } from './broker.ts';
|
||||
import { JOB_TYPE, timeToReady } from './metrics.ts';
|
||||
|
||||
const BATCH = 100;
|
||||
|
||||
export function startRelay(db: Pool, publisher: Publisher, cfg: JobsConfig) {
|
||||
let busy = false;
|
||||
let again = false;
|
||||
let failing = false; // лог ошибки брокера один раз на серию, а не каждые 500 мс
|
||||
|
||||
async function publishBatch(client: PoolClient): Promise<number> {
|
||||
const r = await client.query(`SELECT o.id, o.attempt, o.traceparent, o.tracestate, rfc3339(o.created_at) AS created_at,
|
||||
j.job_id, j.attachment_id, j.pipeline_version, a.filename
|
||||
FROM outbox o JOIN jobs j ON j.job_id = o.job_id JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE o.published_at IS NULL AND o.available_at <= clock_timestamp()
|
||||
ORDER BY o.id LIMIT ${BATCH} FOR UPDATE OF o SKIP LOCKED`);
|
||||
if (!r.rowCount) return 0;
|
||||
const spans: Span[] = [];
|
||||
const jobs: Job[] = r.rows.map((row) => {
|
||||
const parent = contextFrom(row);
|
||||
const span = tracer.startSpan(`publish ${EXCHANGE}`, {
|
||||
kind: SpanKind.PRODUCER,
|
||||
attributes: {
|
||||
'messaging.system': 'rabbitmq', 'messaging.operation.type': 'send', 'messaging.operation.name': 'publish',
|
||||
'messaging.destination.name': EXCHANGE, 'messaging.rabbitmq.destination.routing_key': ROUTING_KEY,
|
||||
'messaging.message.id': `${row.job_id}:${row.attempt}`, 'messenger.job.id': row.job_id,
|
||||
'messenger.job.attempt': row.attempt, 'messenger.attachment.id': row.attachment_id,
|
||||
},
|
||||
}, parent);
|
||||
spans.push(span);
|
||||
const { traceparent, tracestate } = traceCarrier(trace.setSpan(parent, span));
|
||||
return {
|
||||
schema_version: 1, job_id: row.job_id, type: JOB_TYPE, attachment_id: row.attachment_id,
|
||||
pipeline_version: row.pipeline_version, attempt: row.attempt, created_at: row.created_at,
|
||||
...(traceparent ? { traceparent } : {}), ...(tracestate ? { tracestate } : {}),
|
||||
};
|
||||
});
|
||||
try {
|
||||
await publisher.publish(jobs);
|
||||
} catch (err) {
|
||||
for (const span of spans) {
|
||||
span.recordException({ name: (err as Error).name, message: 'Ошибка публикации' });
|
||||
span.setStatus({ code: SpanStatusCode.ERROR, message: 'не опубликовано, строка остаётся в outbox' });
|
||||
span.end();
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
spans.forEach((span, i) => {
|
||||
context.with(trace.setSpan(context.active(), span), () => log('info', 'job.published',
|
||||
`job опубликована в ${EXCHANGE}, попытка ${jobs[i].attempt}`,
|
||||
{ 'messenger.job.id': jobs[i].job_id, 'messenger.job.attempt': jobs[i].attempt, 'messenger.attachment.id': jobs[i].attachment_id }));
|
||||
span.end();
|
||||
});
|
||||
for (const row of r.rows) await failpoint(db, 'relay_after_publish', row.attachment_id, row.filename);
|
||||
await client.query('UPDATE outbox SET published_at = clock_timestamp() WHERE id = ANY($1::bigint[])', [r.rows.map((row) => row.id)]);
|
||||
return r.rows.length;
|
||||
}
|
||||
|
||||
async function publishDue(): Promise<void> {
|
||||
if (busy) {
|
||||
again = true;
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
try {
|
||||
do {
|
||||
again = false;
|
||||
const client = await db.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const n = await publishBatch(client);
|
||||
await client.query('COMMIT');
|
||||
if (failing) log('info', 'relay.publish_restored', 'relay: публикация восстановлена');
|
||||
failing = false;
|
||||
if (n === BATCH) again = true;
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
if (!failing) log('warn', 'relay.publish_deferred', `relay: публикация отложена, задания ждут в outbox: ${(err as Error).message}`);
|
||||
failing = true;
|
||||
again = false;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
} while (again);
|
||||
} catch (err) {
|
||||
if (!failing) log('error', 'relay.db_unavailable', `relay: нет соединения с БД: ${(err as Error).message}`);
|
||||
failing = true;
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function sweep(): Promise<void> {
|
||||
let client: PoolClient | undefined;
|
||||
let exhausted: { age: number }[] = [];
|
||||
try {
|
||||
client = await db.connect();
|
||||
await client.query('BEGIN');
|
||||
// Одна реплика за раз: остальные пропускают такт.
|
||||
if ((await client.query('SELECT pg_try_advisory_xact_lock(5005) AS ok')).rows[0].ok) {
|
||||
const r = await client.query(`WITH e AS (
|
||||
UPDATE jobs SET state = CASE WHEN attempts >= $1 THEN 'failed' ELSE 'queued' END,
|
||||
error_code = CASE WHEN attempts >= $1 THEN 'retry_exhausted' END,
|
||||
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
|
||||
WHERE state = 'processing' AND lease_until < clock_timestamp()
|
||||
RETURNING job_id, attachment_id, state, attempts, error_code, extract(epoch FROM clock_timestamp() - created_at)::float8 AS age),
|
||||
s AS (UPDATE attachments a SET state = e.state, error_code = e.error_code, updated_at = clock_timestamp() FROM e
|
||||
WHERE a.id = e.attachment_id AND a.pipeline_version IS NULL AND a.state IN ('queued', 'processing') RETURNING a.id),
|
||||
o AS (INSERT INTO outbox (job_id, attempt, traceparent, tracestate)
|
||||
SELECT e.job_id, e.attempts + 1, l.traceparent, l.tracestate FROM e
|
||||
LEFT JOIN LATERAL (SELECT traceparent, tracestate FROM outbox WHERE job_id = e.job_id ORDER BY id DESC LIMIT 1) l ON true
|
||||
WHERE e.state = 'queued')
|
||||
SELECT e.state, e.age, s.id IS NOT NULL AS initial FROM e LEFT JOIN s ON s.id = e.attachment_id`, [cfg.maxAttempts]);
|
||||
// Повторная публикация продолжает trace предыдущей: контекст копируется из последней строки outbox job.
|
||||
const stale = await client.query(`INSERT INTO outbox (job_id, attempt, traceparent, tracestate)
|
||||
SELECT j.job_id, j.attempts + 1, l.traceparent, l.tracestate FROM jobs j
|
||||
LEFT JOIN LATERAL (SELECT traceparent, tracestate FROM outbox WHERE job_id = j.job_id ORDER BY id DESC LIMIT 1) l ON true
|
||||
WHERE j.state = 'queued' AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.job_id
|
||||
AND (o.published_at IS NULL OR o.published_at > clock_timestamp() - make_interval(secs => $1)))`, [cfg.republishSeconds]);
|
||||
const requeued = r.rows.filter((row) => row.state === 'queued').length;
|
||||
const failed = r.rows.filter((row) => row.state === 'failed');
|
||||
exhausted = failed.filter((row) => row.initial);
|
||||
if (requeued || failed.length || stale.rowCount) {
|
||||
log('warn', 'sweeper.recovered', `sweeper: аренда истекла — повтор ${requeued}, failed ${failed.length}; переопубликовано queued ${stale.rowCount}`,
|
||||
{ requeued, failed: failed.length, republished: stale.rowCount ?? 0 });
|
||||
}
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
// Исчерпание попыток после смерти worker-ов — терминальная ошибка для SLO time-to-ready (после COMMIT).
|
||||
for (const row of exhausted) timeToReady.record(row.age, { 'job.type': JOB_TYPE, outcome: 'failed', 'error.type': 'retry_exhausted' });
|
||||
} catch (err) {
|
||||
await client?.query('ROLLBACK').catch(() => {});
|
||||
log('error', 'sweeper.error', `sweeper: ${(err as Error).message}`);
|
||||
} finally {
|
||||
client?.release();
|
||||
}
|
||||
if (!failing) void publishDue();
|
||||
}
|
||||
|
||||
// Очередь по источнику истины (БД): видна и при остановленном worker (растёт возраст), и при недоступном брокере
|
||||
// (копится outbox). Каждая реплика API сообщает одно и то же — в PromQL берётся max по репликам.
|
||||
const attrs = { queue: QUEUE };
|
||||
const backlog = meter.createObservableGauge('messenger.jobs.backlog', { unit: '{job}', description: 'Unfinished jobs by state' });
|
||||
const oldest = meter.createObservableGauge('messenger.jobs.oldest_age', { unit: 's', description: 'Age of the oldest unfinished job since durable acceptance' });
|
||||
const pending = meter.createObservableGauge('messenger.outbox.pending', { unit: '{message}', description: 'Outbox rows not yet confirmed by the broker' });
|
||||
meter.addBatchObservableCallback(async (result) => {
|
||||
try {
|
||||
// query_timeout — на клиенте: statement_timeout сервера не сработает, если PostgreSQL заморожен; зависший сбор
|
||||
// задержал бы экспорт всех метрик API и занял соединение пула. При ошибке пул закрывает это соединение.
|
||||
const q = (await db.query({ query_timeout: 2000, text: `SELECT count(*) FILTER (WHERE state = 'queued')::int AS queued,
|
||||
count(*) FILTER (WHERE state = 'processing')::int AS processing,
|
||||
COALESCE(extract(epoch FROM clock_timestamp() - min(created_at)), 0)::float8 AS oldest,
|
||||
(SELECT count(*)::int FROM outbox WHERE published_at IS NULL) AS pending
|
||||
FROM jobs WHERE state IN ('queued', 'processing')` } as QueryConfig)).rows[0]; // query_timeout нет в @types/pg QueryConfig
|
||||
result.observe(backlog, q.queued, { ...attrs, state: 'queued' });
|
||||
result.observe(backlog, q.processing, { ...attrs, state: 'processing' });
|
||||
result.observe(oldest, q.oldest, attrs);
|
||||
result.observe(pending, q.pending, attrs);
|
||||
} catch {
|
||||
// БД недоступна: точек нет, на графике разрыв; причину покажут ошибки API и readiness.
|
||||
}
|
||||
}, [backlog, oldest, pending]);
|
||||
|
||||
const timers = [setInterval(publishDue, 500), setInterval(sweep, 5000)];
|
||||
return {
|
||||
// Вне контекста запроса: пакет может содержать задания разных загрузок, его SQL не относится к этому trace.
|
||||
kick: () => context.with(ROOT_CONTEXT, () => void publishDue()),
|
||||
stop: () => timers.forEach(clearInterval),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// Варианты изображения (libvips через sharp). Параметры зависят от версии pipeline; результат версии N
|
||||
// всегда один и тот же набор: thumbnail, crop, optimized.
|
||||
// thumbnail — JPEG, вписан в 256×256 без увеличения, EXIF orientation применяется, alpha на белом,
|
||||
// размеры округляются вниз (не меньше 1 px): 320×200 → 256×160;
|
||||
// crop — JPEG, центрированный квадрат 128×128 (маленький исходник увеличивается);
|
||||
// optimized — WebP, вписан в 1280×1280 без увеличения; метаданные (EXIF/XMP/ICC) не копируются — sharp
|
||||
// по умолчанию их отбрасывает, цвета приводятся к sRGB.
|
||||
// Ограничения: пиксели проверяются по заголовку до декодирования (limitInputPixels), время — timeout libvips,
|
||||
// память — один поток libvips на процесс, без кэша операций, и лимит памяти контейнера worker.
|
||||
import { createHash } from 'node:crypto';
|
||||
import sharp, { type Sharp } from 'sharp';
|
||||
|
||||
sharp.cache(false);
|
||||
sharp.concurrency(1);
|
||||
|
||||
export class PermanentError extends Error {
|
||||
code: string;
|
||||
constructor(code: string, message: string) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
// Версия 2 (трек 5): другое качество и лёгкая резкость — заметно иной результат той же логической работы.
|
||||
const PIPELINES: Record<number, { jpeg: number; webp: number; sharpen: boolean }> = {
|
||||
1: { jpeg: 82, webp: 80, sharpen: false },
|
||||
2: { jpeg: 90, webp: 85, sharpen: true },
|
||||
};
|
||||
export const SUPPORTED_VERSIONS = Object.keys(PIPELINES).map(Number);
|
||||
|
||||
export type Rendered = {
|
||||
name: 'thumbnail' | 'crop' | 'optimized';
|
||||
content_type: 'image/jpeg' | 'image/webp';
|
||||
ext: string;
|
||||
data: Buffer;
|
||||
width: number;
|
||||
height: number;
|
||||
size_bytes: number;
|
||||
sha256: string;
|
||||
};
|
||||
|
||||
export async function render(source: Buffer, version: number, maxPixels: number, timeoutSeconds: number): Promise<Rendered[]> {
|
||||
const p = PIPELINES[version];
|
||||
if (!p) throw new PermanentError('unsupported_pipeline', `pipeline v${version} не поддерживается`);
|
||||
const input = () => sharp(source, { limitInputPixels: maxPixels, sequentialRead: true }).timeout({ seconds: timeoutSeconds });
|
||||
try {
|
||||
const meta = await input().metadata();
|
||||
if (!meta.width || !meta.height || !['png', 'jpeg'].includes(meta.format ?? '')) throw new PermanentError('invalid_image', 'не PNG/JPEG');
|
||||
const turned = (meta.orientation ?? 1) >= 5; // EXIF 5–8: после поворота ширина и высота меняются местами
|
||||
const width = turned ? meta.height : meta.width;
|
||||
const height = turned ? meta.width : meta.height;
|
||||
const inside = (box: number) => {
|
||||
const k = Math.min(box / width, box / height, 1);
|
||||
return [Math.max(1, Math.floor(width * k)), Math.max(1, Math.floor(height * k))];
|
||||
};
|
||||
const [tw, th] = inside(256);
|
||||
const [ow, oh] = inside(1280);
|
||||
const oriented = () => {
|
||||
const img = input().autoOrient();
|
||||
return p.sharpen ? img.sharpen() : img;
|
||||
};
|
||||
return [
|
||||
await output('thumbnail', oriented().flatten({ background: '#ffffff' }).resize(tw, th, { fit: 'fill' }).jpeg({ quality: p.jpeg, mozjpeg: true })),
|
||||
await output('crop', oriented().flatten({ background: '#ffffff' }).resize(128, 128, { fit: 'cover', position: 'centre' }).jpeg({ quality: p.jpeg, mozjpeg: true })),
|
||||
await output('optimized', oriented().resize(ow, oh, { fit: 'fill' }).webp({ quality: p.webp, effort: 4 })),
|
||||
];
|
||||
} catch (err) {
|
||||
if (err instanceof PermanentError) throw err;
|
||||
const message = (err as Error).message ?? '';
|
||||
// Ошибки libvips — свойство входного файла: повтор не поможет.
|
||||
throw /timeout/i.test(message)
|
||||
? new PermanentError('processing_timeout', 'обработка дольше лимита')
|
||||
: new PermanentError('invalid_image', message.split('\n')[0].slice(0, 200));
|
||||
}
|
||||
}
|
||||
|
||||
async function output(name: Rendered['name'], img: Sharp): Promise<Rendered> {
|
||||
const { data, info } = await img.toBuffer({ resolveWithObject: true });
|
||||
const webp = info.format === 'webp';
|
||||
return {
|
||||
name, content_type: webp ? 'image/webp' : 'image/jpeg', ext: webp ? 'webp' : 'jpg', data,
|
||||
width: info.width, height: info.height, size_bytes: data.length, sha256: createHash('sha256').update(data).digest('hex'),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
// Worker: отдельный процесс, читает quorum-очередь attachments.process (at least once, ручной ack).
|
||||
// Порядок одной попытки — каждое окно отказа безопасно:
|
||||
// 1. захват: jobs queued → processing, attempts+1, аренда с fencing-токеном (одна транзакция);
|
||||
// 2. исходник из S3 (ключ — из БД, не из сообщения), сверка размера и SHA-256 с метаданными;
|
||||
// 3. рендер вариантов; запись объектов под ключами с токеном попытки; копия оригинала staging → originals;
|
||||
// 4. фиксация (одна транзакция): job done только у владельца аренды, вложение ready только если более новая
|
||||
// версия ещё не опубликована, строки вариантов по ключу эффекта (attachment_id, pipeline_version, name);
|
||||
// 5. удаление staging, затем ack.
|
||||
// Падение до 4 — аренда истечёт, sweeper (relay) вернёт работу в очередь; чужие объекты попытки уберёт
|
||||
// reconciler. Падение после 4 — redelivery видит job done и подтверждает без повторной работы.
|
||||
// Lab6: сообщение обрабатывается в CONSUMER span, дочернем к PRODUCER span из traceparent сообщения (тот же trace,
|
||||
// что и загрузка); внутри — spans захвата, S3, рендера и фиксации. Повтор сохраняет контекст попытки в outbox,
|
||||
// поэтому следующие публикация и обработка продолжают этот trace.
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { SpanKind, SpanStatusCode, context, trace } from '@opentelemetry/api';
|
||||
import type { ConsumeMessage } from 'amqplib';
|
||||
import type { Pool } from 'pg';
|
||||
import { envInt, jobsConfig, s3Config, secret } from '../config.ts';
|
||||
import { createPool } from '../db.ts';
|
||||
import { failpoint } from '../failpoints.ts';
|
||||
import { contextFrom, flushTelemetry, inSpan, log, meter, traceCarrier, tracer } from '../otel.ts';
|
||||
import { createStorage, type Storage } from '../storage/s3.ts';
|
||||
import { QUEUE, brokerConnect, parseJob, type Job } from './broker.ts';
|
||||
import { JOB_TYPE, jobDuration, timeToReady } from './metrics.ts';
|
||||
import { PermanentError, render } from './render.ts';
|
||||
|
||||
type Claim = {
|
||||
job: Job;
|
||||
token: string;
|
||||
attempts: number;
|
||||
version: number;
|
||||
initial: boolean; // первая обработка (вложение ещё не ready): публикуем оригинал, синхронизируем статус
|
||||
a: { id: string; filename: string; staging_key: string; object_key: string; size_bytes: number; sha256: string };
|
||||
};
|
||||
|
||||
// Исход обработки одного сообщения: атрибут span и метрики messenger.job.duration.
|
||||
type Outcome = 'done' | 'retry' | 'failed' | 'noop' | 'discarded' | 'invalid' | 'error';
|
||||
|
||||
// Технические идентификаторы для логов/spans: нужны, чтобы найти конкретную загрузку (данные синтетические).
|
||||
const ids = (c: Claim) => ({ 'messenger.job.id': c.job.job_id, 'messenger.job.attempt': c.attempts, 'messenger.attachment.id': c.a.id });
|
||||
|
||||
export async function runWorker(): Promise<void> {
|
||||
const cfg = jobsConfig();
|
||||
const concurrency = envInt('WORKER_CONCURRENCY', 2);
|
||||
const maxPixels = envInt('MAX_IMAGE_PIXELS', 40000000);
|
||||
const db = createPool(secret('DATABASE_URL'), concurrency + 2);
|
||||
const s3 = createStorage(s3Config());
|
||||
const conn = await connect();
|
||||
let stopping = false;
|
||||
// Потеря соединения или канала (в том числе consumer_timeout брокера) — выход; Docker перезапустит процесс,
|
||||
// неподтверждённые сообщения брокер отдаст снова.
|
||||
const lost = (what: string) => () => {
|
||||
if (stopping) return;
|
||||
log('error', 'worker.broker_lost', `${what} с брокером закрыт(о)`);
|
||||
void flushTelemetry().finally(() => process.exit(1));
|
||||
};
|
||||
conn.on('close', lost('соединение'));
|
||||
conn.on('error', (err) => log('error', 'worker.broker_error', `брокер: ${err.name}`));
|
||||
const ch = await conn.createChannel();
|
||||
ch.on('close', lost('канал'));
|
||||
ch.on('error', (err) => log('error', 'worker.channel_error', `канал: ${err.name}`));
|
||||
await ch.prefetch(concurrency); // не больше concurrency неподтверждённых сообщений на worker
|
||||
const leaseSeconds = cfg.timeoutSeconds + 15;
|
||||
let inflight = 0;
|
||||
// Насыщение worker-а: занятые слоты и ёмкость (= prefetch) каждой реплики.
|
||||
meter.createObservableGauge('messenger.worker.busy', { unit: '{job}', description: 'Jobs being processed now' })
|
||||
.addCallback((r) => r.observe(inflight));
|
||||
meter.createObservableGauge('messenger.worker.capacity', { unit: '{job}', description: 'Max concurrent jobs (prefetch)' })
|
||||
.addCallback((r) => r.observe(concurrency));
|
||||
|
||||
const opts = { cfg, maxPixels, leaseSeconds };
|
||||
const { consumerTag } = await ch.consume(QUEUE, (msg) => {
|
||||
if (!msg) return; // очередь удалена или consumer отменён брокером
|
||||
inflight++;
|
||||
consume(db, s3, msg, opts)
|
||||
.then(() => ch.ack(msg), async () => {
|
||||
// Сюда попадают только сбои БД/брокера вне попытки (например, БД недоступна при захвате): вернуть позже.
|
||||
await sleep(2000);
|
||||
ch.nack(msg, false, true);
|
||||
})
|
||||
.finally(() => { inflight--; });
|
||||
}, { noAck: false });
|
||||
log('info', 'worker.started', `worker: очередь ${QUEUE}, prefetch ${concurrency}, попыток ${cfg.maxAttempts}, таймаут ${cfg.timeoutSeconds} с`);
|
||||
|
||||
const stop = async () => {
|
||||
log('info', 'worker.stopping', 'SIGTERM: новые сообщения не принимаются, дожидаюсь текущих');
|
||||
await ch.cancel(consumerTag).catch(() => {});
|
||||
for (let i = 0; inflight && i < 100; i++) await sleep(100);
|
||||
stopping = true;
|
||||
await conn.close().catch(() => {});
|
||||
await flushTelemetry();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', stop);
|
||||
process.on('SIGINT', stop);
|
||||
}
|
||||
|
||||
// Брокер недоступен при старте (рестарт брокера, worker поднят раньше) — ждать с backoff, а не падать в цикле.
|
||||
async function connect() {
|
||||
for (let delay = 1000; ; delay = Math.min(delay * 2, 15000)) {
|
||||
try {
|
||||
return await brokerConnect(5000);
|
||||
} catch (err) {
|
||||
log('warn', 'worker.broker_unavailable', `брокер недоступен (${(err as Error).name}), повтор через ${delay} мс`);
|
||||
await sleep(delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Opts = { cfg: ReturnType<typeof jobsConfig>; maxPixels: number; leaseSeconds: number };
|
||||
|
||||
// Одно сообщение — один CONSUMER span. Исключение (сбой вне попытки) пробрасывается: сообщение вернётся в очередь.
|
||||
async function consume(db: Pool, s3: Storage, msg: ConsumeMessage, o: Opts): Promise<void> {
|
||||
const job = parseJob(msg.content);
|
||||
const parent = contextFrom(job ?? {});
|
||||
const span = tracer.startSpan(`process ${QUEUE}`, {
|
||||
kind: SpanKind.CONSUMER,
|
||||
attributes: {
|
||||
'messaging.system': 'rabbitmq', 'messaging.operation.type': 'process', 'messaging.destination.name': QUEUE,
|
||||
'messaging.message.id': msg.properties.messageId ?? '', 'messenger.redelivered': msg.fields.redelivered,
|
||||
...(job ? { 'messenger.job.id': job.job_id, 'messenger.job.attempt': job.attempt, 'messenger.attachment.id': job.attachment_id } : {}),
|
||||
},
|
||||
}, parent);
|
||||
const ctx = trace.setSpan(parent, span);
|
||||
const started = performance.now();
|
||||
let outcome: Outcome = 'error';
|
||||
try {
|
||||
outcome = await context.with(ctx, () => handle(db, s3, job, o));
|
||||
} catch (err) {
|
||||
span.recordException({ name: (err as Error).name, message: 'Ошибка обработки' });
|
||||
context.with(ctx, () => log('error', 'job.requeued', `job не обработан, вернётся в очередь: ${(err as Error).name}`,
|
||||
{ 'messenger.job.id': job?.job_id ?? '' }));
|
||||
throw err;
|
||||
} finally {
|
||||
if (!['done', 'noop', 'discarded'].includes(outcome)) span.setStatus({ code: SpanStatusCode.ERROR });
|
||||
span.setAttribute('messenger.job.outcome', outcome);
|
||||
span.end();
|
||||
jobDuration.record((performance.now() - started) / 1000, { 'job.type': JOB_TYPE, outcome });
|
||||
}
|
||||
}
|
||||
|
||||
// Ошибка бизнес-уровня здесь не бросается: она переводит job в retry/failed, сообщение подтверждается.
|
||||
async function handle(db: Pool, s3: Storage, job: Job | null, o: Opts): Promise<Outcome> {
|
||||
if (!job) {
|
||||
log('error', 'job.invalid_message', 'сообщение не по jobs.schema.json отброшено');
|
||||
return 'invalid';
|
||||
}
|
||||
const claim = await inSpan('claim job', {}, () => claimJob(db, job, o.leaseSeconds));
|
||||
if (!claim) return 'noop';
|
||||
const written: string[] = [];
|
||||
let reason = 'storage_unavailable'; // безопасная причина временной ошибки (в jobs.error_code, без текста исключения)
|
||||
try {
|
||||
await failpoint(db, 'worker_after_claim', claim.a.id, claim.a.filename); // до любого side effect
|
||||
const source = await readSource(s3, claim);
|
||||
const variants = await inSpan('render variants', { 'messenger.pipeline.version': claim.version, 'messenger.source.bytes': claim.a.size_bytes },
|
||||
() => render(source, claim.version, o.maxPixels, o.cfg.timeoutSeconds));
|
||||
for (const v of variants) {
|
||||
// Токен попытки в ключе: проигравшая аренду попытка не перезапишет объекты победителя.
|
||||
const key = `variants/${claim.a.id}/v${claim.version}/${v.name}-${claim.token.slice(0, 8)}.${v.ext}`;
|
||||
await s3.putBuffer(key, v.data, v.content_type);
|
||||
written.push(key);
|
||||
}
|
||||
if (claim.initial) await s3.copy(claim.a.staging_key, claim.a.object_key); // тот же ключ при повторе
|
||||
await failpoint(db, 'worker_after_side_effect', claim.a.id, claim.a.filename);
|
||||
reason = 'database_unavailable';
|
||||
const age = await inSpan('commit result', {}, () => commit(db, claim, variants.map((v, i) => ({ ...v, key: written[i] }))));
|
||||
if (age === null) {
|
||||
await removeAll(s3, written);
|
||||
return 'discarded';
|
||||
}
|
||||
await failpoint(db, 'worker_after_commit', claim.a.id, claim.a.filename); // результат зафиксирован, ack ещё нет
|
||||
// Staging больше не нужен; если удаление не удалось, остаток уберёт reconciler.
|
||||
if (claim.initial) {
|
||||
await s3.remove(claim.a.staging_key).catch((err) => log('warn', 'job.staging_not_removed', `staging не удалён: ${err.name}`, ids(claim)));
|
||||
timeToReady.record(age, { 'job.type': JOB_TYPE, outcome: 'ready' });
|
||||
}
|
||||
log('info', 'job.ready', `job v${claim.version} попытка ${claim.attempts}: ready через ${age.toFixed(2)} с после приёма`,
|
||||
{ ...ids(claim), 'messenger.time_to_ready_s': Math.round(age * 1000) / 1000 });
|
||||
return 'done';
|
||||
} catch (err) {
|
||||
await removeAll(s3, written);
|
||||
return failOrRetry(db, claim, err, o.cfg, reason);
|
||||
}
|
||||
}
|
||||
|
||||
async function claimJob(db: Pool, job: Job, leaseSeconds: number): Promise<Claim | null> {
|
||||
const client = await db.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const token = randomUUID();
|
||||
// Захват только ожидаемой попытки: сообщение старой попытки (redelivery после падения) — no-op,
|
||||
// живую аренду другого worker не трогаем — при его смерти работу вернёт sweeper.
|
||||
const r = await client.query(`UPDATE jobs SET state = 'processing', attempts = attempts + 1, lease_token = $2,
|
||||
lease_until = clock_timestamp() + make_interval(secs => $3), updated_at = clock_timestamp()
|
||||
WHERE job_id = $1 AND attempts + 1 = $4
|
||||
AND (state = 'queued' OR (state = 'processing' AND lease_until < clock_timestamp()))
|
||||
RETURNING attachment_id, pipeline_version, attempts`, [job.job_id, token, leaseSeconds, job.attempt]);
|
||||
if (!r.rowCount) {
|
||||
await client.query('COMMIT');
|
||||
const s = await db.query('SELECT state, attempts FROM jobs WHERE job_id = $1', [job.job_id]);
|
||||
log('info', 'job.noop', `job попытка ${job.attempt}: no-op (${s.rows[0] ? `${s.rows[0].state}, попыток ${s.rows[0].attempts}` : 'неизвестная job'})`,
|
||||
{ 'messenger.job.id': job.job_id, 'messenger.job.attempt': job.attempt });
|
||||
return null;
|
||||
}
|
||||
const { attachment_id, pipeline_version, attempts } = r.rows[0];
|
||||
const a = (await client.query(`SELECT id, filename, staging_key, object_key, size_bytes, sha256, state, pipeline_version
|
||||
FROM attachments WHERE id = $1 FOR UPDATE`, [attachment_id])).rows[0];
|
||||
// Результат этой или более новой версии уже опубликован: старая job не должна ничего перезаписать.
|
||||
if (a.pipeline_version !== null && a.pipeline_version >= pipeline_version) {
|
||||
await client.query(`UPDATE jobs SET state = 'superseded', lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
|
||||
WHERE job_id = $1`, [job.job_id]);
|
||||
await client.query('COMMIT');
|
||||
log('info', 'job.superseded', `job v${pipeline_version}: superseded (опубликована v${a.pipeline_version})`, { 'messenger.job.id': job.job_id });
|
||||
return null;
|
||||
}
|
||||
const initial = a.pipeline_version === null;
|
||||
if (initial) await client.query(`UPDATE attachments SET state = 'processing', updated_at = clock_timestamp() WHERE id = $1 AND state = 'queued'`, [a.id]);
|
||||
await client.query('COMMIT');
|
||||
return { job, token, attempts, version: pipeline_version, initial, a };
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
// Исходник: при первой обработке — staging, при переобработке новой версией — опубликованный оригинал.
|
||||
// Читается не больше size_bytes + 1 байт и сверяется с доверенными метаданными из БД.
|
||||
async function readSource(s3: Storage, claim: Claim): Promise<Buffer> {
|
||||
const body = await s3.get(claim.initial ? claim.a.staging_key : claim.a.object_key);
|
||||
if (!body) throw new PermanentError('source_missing', 'исходник отсутствует в S3');
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
for await (const chunk of body) {
|
||||
size += chunk.length;
|
||||
if (size > claim.a.size_bytes) {
|
||||
body.destroy();
|
||||
break;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
}
|
||||
const data = Buffer.concat(chunks);
|
||||
if (size !== claim.a.size_bytes || createHash('sha256').update(data).digest('hex') !== claim.a.sha256) {
|
||||
throw new PermanentError('source_corrupted', 'исходник не совпадает с метаданными');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
type Stored = { name: string; content_type: string; size_bytes: number; width: number; height: number; sha256: string; key: string };
|
||||
|
||||
// Возвращает секунды от приёма загрузки (jobs.created_at) до публикации ready или null, если результат отброшен.
|
||||
async function commit(db: Pool, claim: Claim, variants: Stored[]): Promise<number | null> {
|
||||
const client = await db.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
// Fencing: если аренда истекла и работу забрал другой worker, токен уже не совпадает.
|
||||
const done = await client.query(`UPDATE jobs SET state = 'done', lease_token = NULL, lease_until = NULL, error_code = NULL,
|
||||
updated_at = clock_timestamp() WHERE job_id = $1 AND lease_token = $2 AND state = 'processing'
|
||||
RETURNING extract(epoch FROM clock_timestamp() - created_at)::float8 AS age`, [claim.job.job_id, claim.token]);
|
||||
if (!done.rowCount) {
|
||||
await client.query('ROLLBACK');
|
||||
log('warn', 'job.lease_lost', `job попытка ${claim.attempts}: аренда потеряна, результат отброшен`, ids(claim));
|
||||
return null;
|
||||
}
|
||||
const ready = await client.query(`UPDATE attachments SET state = 'ready', pipeline_version = $2, error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND (pipeline_version IS NULL OR pipeline_version < $2)`, [claim.a.id, claim.version]);
|
||||
if (!ready.rowCount) {
|
||||
await client.query(`UPDATE jobs SET state = 'superseded' WHERE job_id = $1`, [claim.job.job_id]);
|
||||
await client.query('COMMIT');
|
||||
log('info', 'job.superseded', `job v${claim.version}: superseded при фиксации`, ids(claim));
|
||||
return null;
|
||||
}
|
||||
for (const v of variants) {
|
||||
await client.query(`INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, [claim.a.id, claim.version, v.name, v.key, v.content_type, v.size_bytes, v.width, v.height, v.sha256]);
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
return done.rows[0].age;
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
// Постоянная ошибка (свойство файла) → failed сразу. Временная → новая попытка через outbox с backoff и jitter,
|
||||
// пока attempts < JOB_MAX_ATTEMPTS, затем failed retry_exhausted. Всё — только у владельца аренды.
|
||||
// У job в error_code — последняя причина (и для queued), у вложения — только финальный код failed.
|
||||
// Lab6: новая строка outbox несёт контекст текущего CONSUMER span — повтор продолжит тот же trace.
|
||||
// Лог, исключение в span и метрика — только если UPDATE с fencing изменил job: проигравшая аренду попытка → discarded.
|
||||
async function failOrRetry(db: Pool, claim: Claim, err: unknown, cfg: Opts['cfg'], reason: string): Promise<'retry' | 'failed' | 'discarded'> {
|
||||
const permanent = err instanceof PermanentError ? err.code : null;
|
||||
const exhausted = !permanent && claim.attempts >= cfg.maxAttempts;
|
||||
const state = permanent || exhausted ? 'failed' : 'queued';
|
||||
const code = permanent ?? (exhausted ? 'retry_exhausted' : null);
|
||||
const delayMs = Math.min(60000, cfg.retryBaseMs * 2 ** (claim.attempts - 1)) * (0.5 + Math.random() / 2);
|
||||
const { traceparent, tracestate } = traceCarrier();
|
||||
const client = await db.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const r = await client.query(`UPDATE jobs SET state = $3, error_code = $4, lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
|
||||
WHERE job_id = $1 AND lease_token = $2 RETURNING extract(epoch FROM clock_timestamp() - created_at)::float8 AS age`,
|
||||
[claim.job.job_id, claim.token, state, code ?? reason]);
|
||||
if (r.rowCount) {
|
||||
if (state === 'queued') {
|
||||
await client.query(`INSERT INTO outbox (job_id, attempt, available_at, traceparent, tracestate)
|
||||
VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3), $4, $5)`, [claim.job.job_id, claim.attempts + 1, delayMs / 1000, traceparent, tracestate]);
|
||||
}
|
||||
if (claim.initial) {
|
||||
await client.query(`UPDATE attachments SET state = $2, error_code = $3, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND pipeline_version IS NULL AND state IN ('queued', 'processing')`, [claim.a.id, state, code]);
|
||||
}
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
if (!r.rowCount) {
|
||||
log('warn', 'job.lease_lost', `job попытка ${claim.attempts}: аренда потеряна, ошибка попытки отброшена`, ids(claim));
|
||||
return 'discarded';
|
||||
}
|
||||
trace.getActiveSpan()?.recordException({ name: (err as Error).name, message: 'Ошибка задания' });
|
||||
log(state === 'failed' ? 'error' : 'warn', state === 'failed' ? 'job.failed' : 'job.retry',
|
||||
`job попытка ${claim.attempts}: ${(err as Error).name} → ${state}${code ? ` ${code}` : `, повтор через ${Math.round(delayMs)} мс`}`,
|
||||
{ ...ids(claim), 'error.type': code ?? reason });
|
||||
if (state === 'failed' && claim.initial) {
|
||||
timeToReady.record(r.rows[0].age, { 'job.type': JOB_TYPE, outcome: 'failed', 'error.type': code ?? reason });
|
||||
}
|
||||
return state === 'failed' ? 'failed' : 'retry';
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e; // job останется processing: аренда истечёт и sweeper вернёт её
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function removeAll(s3: Storage, keys: string[]): Promise<void> {
|
||||
for (const key of keys) await s3.remove(key).catch(() => {}); // остаток уберёт reconciler
|
||||
}
|
||||
Reference in New Issue
Block a user