Files
mtusi2026lab7/app/src/worker/job-processor.service.ts
T

685 lines
19 KiB
TypeScript

import {
Inject,
Injectable,
Logger,
OnApplicationBootstrap,
Optional,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { Channel, ConsumeMessage } from 'amqplib';
import {
ROOT_CONTEXT,
SpanKind,
SpanStatusCode,
trace,
type Span,
} from '@opentelemetry/api';
import { createHash } from 'node:crypto';
import type { AttachmentRow } from '../attachments/attachment.js';
import type { AppConfig } from '../config/app-config.schema.js';
import { resolveInstanceId } from '../config/instance-id.js';
import { ObjectStorage } from '../storage/object-storage.js';
import { retryDelayMs } from '../jobs/backoff.js';
import { BrokerClient } from '../jobs/broker.client.js';
import { JOB_QUEUE } from '../jobs/broker.topology.js';
import {
classifyError,
JobTimeoutError,
SourceMismatchError,
SourceMissingError,
type ErrorClass,
} from '../jobs/errors.js';
import { FaultInjector } from '../jobs/fault-injector.js';
import {
JOB_TYPE,
parseJobMessage,
type JobMessage,
} from '../jobs/job-message.js';
import { OutboxRelay } from '../jobs/outbox-relay.service.js';
import {
JobsRepository,
type ClaimResult,
type VariantWrite,
} from '../jobs/jobs.repository.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { renderVariants, type RenderedVariant } from './pipelines.js';
import { instruments, meter } from '../telemetry/instruments.js';
import { appLogger } from '../telemetry/logger.js';
import {
contextFromTraceFields,
errorType,
markSpanError,
traceFieldsFromHeaders,
tracer,
} from '../telemetry/tracing.js';
const SHUTDOWN_DRAIN_MS = 30_000;
const VARIANT_EXTENSIONS = [
['thumbnail', 'jpg'],
['crop', 'jpg'],
['optimized', 'webp'],
] as const;
/** Bounded outcome set: the `outcome` label of messenger.jobs.processed. */
type JobOutcome =
| 'succeeded'
| 'superseded'
| 'lease_lost'
| 'retry'
| 'failed'
| 'commit_failed'
| 'poison'
| 'claim_failed'
| 'skipped'
| 'mismatch'
| 'crashed';
// Outcomes where the delivery did not do its job: WARN log, ERROR span status.
const PROBLEM_OUTCOMES: ReadonlySet<JobOutcome> = new Set<JobOutcome>([
'retry',
'failed',
'commit_failed',
'poison',
'claim_failed',
'mismatch',
'crashed',
]);
function throwIfAborted(signal: AbortSignal): void {
if (!signal.aborted) return;
throw signal.reason instanceof Error ? signal.reason : new Error('Aborted');
}
function sha256(data: Buffer): string {
return createHash('sha256').update(data).digest('hex');
}
@Injectable()
export class JobProcessor implements OnApplicationBootstrap {
private readonly logger = new Logger(JobProcessor.name);
private readonly workerId: string;
private readonly maxPixels: number;
private readonly timeoutSeconds: number;
private readonly leaseSeconds: number;
private readonly retryBaseMs: number;
private readonly retryMaxMs: number;
private readonly maxUploadBytes: number;
private active = 0;
private readonly idleWaiters: (() => void)[] = [];
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly broker: BrokerClient,
private readonly jobs: JobsRepository,
@Optional() @Inject(OutboxRelay) private readonly relay: OutboxRelay | undefined,
private readonly faults: FaultInjector,
private readonly storage: ObjectStorage,
private readonly metrics: MetricsService,
) {
this.workerId = resolveInstanceId(config, 'wrk');
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
this.timeoutSeconds = config.getOrThrow('JOB_TIMEOUT_SECONDS');
this.leaseSeconds = config.getOrThrow('JOB_LEASE_SECONDS');
this.retryBaseMs = config.getOrThrow('JOB_RETRY_BASE_MS');
this.retryMaxMs = config.getOrThrow('JOB_RETRY_MAX_MS');
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
}
onApplicationBootstrap(): void {
const concurrency = this.config.getOrThrow('WORKER_CONCURRENCY');
this.observeSaturation(concurrency);
this.broker.consume(concurrency, (message, channel) =>
this.handle(message, channel),
);
}
/**
* Saturation of this worker: jobs in flight against WORKER_CONCURRENCY
* (= prefetch). Together with messenger.jobs.queue.* it separates «the
* worker is slow» from «the worker is full» from «the worker is gone».
*/
private observeSaturation(concurrency: number): void {
const m = meter();
const active = m.createObservableUpDownCounter(
'messenger.worker.jobs.active',
{ unit: '{job}', description: 'Jobs this worker is processing now' },
);
const capacity = m.createObservableUpDownCounter(
'messenger.worker.jobs.capacity',
{
unit: '{job}',
description:
'Jobs this worker may process at once (WORKER_CONCURRENCY)',
},
);
m.addBatchObservableCallback(
(result) => {
result.observe(active, this.active);
result.observe(capacity, concurrency);
},
[active, capacity],
);
}
async drain(timeoutMs = SHUTDOWN_DRAIN_MS): Promise<void> {
if (this.active === 0) return;
const { promise, resolve } = Promise.withResolvers<void>();
this.idleWaiters.push(resolve);
const timer = setTimeout(resolve, timeoutMs);
await promise;
clearTimeout(timer);
}
/**
* One CONSUMER span per delivery. Its parent is the PRODUCER span from the
* AMQP headers; messages without trace headers (published before lab6 or
* replayed raw) fall back to the trace context stored in the body.
*/
private async handle(
message: ConsumeMessage,
channel: Channel,
): Promise<void> {
const parsed = parseJobMessage(message.content);
const fromHeaders = traceFieldsFromHeaders(
message.properties.headers as Record<string, unknown> | undefined,
);
const parent = fromHeaders.traceparent
? contextFromTraceFields(fromHeaders)
: contextFromTraceFields(parsed, ROOT_CONTEXT);
const started = process.hrtime.bigint();
await tracer().startActiveSpan(
`process ${JOB_QUEUE}`,
{
kind: SpanKind.CONSUMER,
attributes: {
'messaging.system': 'rabbitmq',
'messaging.operation.type': 'process',
'messaging.destination.name': JOB_QUEUE,
'messaging.rabbitmq.message.redelivered':
message.fields.redelivered,
...(parsed
? {
'messaging.message.id': parsed.job_id,
'messenger.job.id': parsed.job_id,
'messenger.attachment.id': parsed.attachment_id,
'messenger.job.attempt': parsed.attempt,
'messenger.pipeline.version': parsed.pipeline_version,
}
: {}),
},
},
parent,
async (span: Span) => {
let outcome: JobOutcome = 'crashed';
try {
outcome = await this.dispatch(parsed, message, channel);
} catch (error) {
markSpanError(span, error);
throw error;
} finally {
this.record(span, parsed, outcome, started);
}
},
);
}
private record(
span: Span,
parsed: JobMessage | undefined,
outcome: JobOutcome,
started: bigint,
): void {
const seconds = Number(process.hrtime.bigint() - started) / 1e9;
const labels = { 'job.type': JOB_TYPE, outcome };
instruments().jobsProcessed.add(1, labels);
instruments().jobDuration.record(seconds, labels);
// time-to-ready is recorded at the ready commit in process().
span.setAttribute('messenger.job.outcome', outcome);
const problem = PROBLEM_OUTCOMES.has(outcome);
if (problem && outcome !== 'crashed')
span.setStatus({ code: SpanStatusCode.ERROR, message: outcome });
appLogger.event(
problem ? 'WARN' : 'INFO',
'job.processed',
`job ${outcome}`,
{
'messenger.job.id': parsed?.job_id,
'messenger.attachment.id': parsed?.attachment_id,
'messenger.job.attempt': parsed?.attempt,
'messenger.job.outcome': outcome,
duration_ms: Math.round(seconds * 1000),
},
);
span.end();
}
private async dispatch(
parsed: JobMessage | undefined,
message: ConsumeMessage,
channel: Channel,
): Promise<JobOutcome> {
if (!parsed) {
this.metrics.increment('worker.messages.poison');
this.safeNack(channel, message, false);
return 'poison';
}
const claim = await this.claimWithRetry(parsed);
if (!claim) {
this.metrics.increment('worker.jobs.claim_failed');
// Do not burn the delivery limit in a tight nack loop while the
// database is briefly unavailable.
this.safeNackAfter(channel, message, true, 5000);
return 'claim_failed';
}
if (claim.kind === 'skip') {
if (claim.reason === 'mismatch') {
this.safeNack(channel, message, false);
return 'mismatch';
}
this.metrics.increment(`worker.jobs.skipped.${claim.reason}`);
trace
.getActiveSpan()
?.setAttribute('messenger.job.skip_reason', claim.reason);
this.safeAck(channel, message);
return 'skipped';
}
this.begin();
try {
return await this.process(
claim.job,
claim.attachment,
claim.leaseToken,
message,
channel,
);
} finally {
this.end();
}
}
private async process(
job: {
job_id: string;
attachment_id: string;
pipeline_version: number;
attempt: number;
created_at: Date;
},
attachment: AttachmentRow,
leaseToken: string,
message: ConsumeMessage,
channel: Channel,
): Promise<JobOutcome> {
this.metrics.increment('worker.jobs.claimed');
const controller = new AbortController();
const target = {
attachmentId: job.attachment_id,
pipelineVersion: job.pipeline_version,
};
const timeout = setTimeout(
() => controller.abort(new JobTimeoutError(this.timeoutSeconds)),
this.timeoutSeconds * 1000,
);
const heartbeat = setInterval(
() => {
this.jobs
.extendLease(job.job_id, leaseToken, this.leaseSeconds)
.then((extended) => {
if (!extended && !controller.signal.aborted)
controller.abort(new Error('Lease lost'));
})
.catch((error: unknown) => {
this.logger.warn(
`Lease heartbeat failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
});
},
Math.max(1000, (this.leaseSeconds * 1000) / 3),
);
let committed = false;
let committedOutcome: JobOutcome = 'succeeded';
try {
await this.faults.point(
'worker.before_side_effect',
target,
controller.signal,
);
throwIfAborted(controller.signal);
const source = await this.ensureFinalOriginal(
attachment,
controller.signal,
);
throwIfAborted(controller.signal);
const variants = await renderVariants(
source,
job.pipeline_version,
{
maxPixels: this.maxPixels,
timeoutSeconds: this.timeoutSeconds,
signal: controller.signal,
},
);
throwIfAborted(controller.signal);
for (const variant of variants) {
if (
!(await this.jobs.extendLease(
job.job_id,
leaseToken,
this.leaseSeconds,
))
)
throw new Error('Lease lost');
await this.storage.putBuffer(
this.variantKey(job, variant),
variant.data,
variant.contentType,
controller.signal,
);
}
await this.faults.point(
'worker.after_side_effect',
target,
controller.signal,
);
throwIfAborted(controller.signal);
const result = await this.jobs.commitSuccess(
job.job_id,
leaseToken,
variants.map((variant) => this.variantWrite(job, variant)),
);
const readyCommittedAt = Date.now();
committed = true;
committedOutcome = result;
if (result === 'succeeded') {
// Durable acceptance (job.created_at, set in the acceptance
// transaction) to the ready commit; before post-commit fault/ACK.
const ready = (readyCommittedAt - job.created_at.getTime()) / 1000;
if (Number.isFinite(ready) && ready >= 0)
instruments().timeToReady.record(ready, { 'job.type': JOB_TYPE });
}
this.metrics.increment(`worker.jobs.${result}`);
await this.faults.point(
'worker.after_commit_before_ack',
target,
controller.signal,
);
this.safeAck(channel, message);
if (result === 'succeeded') {
await this.cleanupStaging(attachment);
await this.cleanupAttemptObjects(job, job.attempt);
} else if (result === 'superseded') {
await this.cleanupAttemptObjects(job, null);
}
return result;
} catch (error) {
if (committed) {
// The durable effect is already committed; a failure at the ack
// fault point or a lost reply must not turn into a retry.
this.safeAck(channel, message);
return committedOutcome;
}
// Only the error type/code reaches the span: driver messages may
// carry request values.
trace.getActiveSpan()?.setAttribute('error.type', errorType(error));
const failure = this.classify(error, controller.signal);
const delay = retryDelayMs(
job.attempt,
this.retryBaseMs,
this.retryMaxMs,
);
try {
const outcome = await this.jobs.commitFailure(
job.job_id,
leaseToken,
failure,
delay,
);
this.metrics.increment(`worker.jobs.${outcome}`);
if (outcome === 'retry') this.relay?.kick();
this.safeAck(channel, message);
if (outcome === 'retry' || outcome === 'failed')
await this.cleanupAttemptObjects(job, null);
return outcome;
} catch (commitError) {
this.metrics.increment('worker.jobs.commit_failed');
this.logger.warn(
`Failure commit failed: ${commitError instanceof Error ? commitError.message : 'unknown error'}`,
);
setTimeout(() => this.safeNack(channel, message, true), 1000);
return 'commit_failed';
}
} finally {
clearTimeout(timeout);
clearInterval(heartbeat);
}
}
private classify(error: unknown, signal: AbortSignal): ErrorClass {
if (signal.aborted && signal.reason instanceof JobTimeoutError)
return classifyError(signal.reason);
return classifyError(error);
}
private async ensureFinalOriginal(
attachment: AttachmentRow,
signal: AbortSignal,
): Promise<Buffer> {
const expectedSize = Number(attachment.size_bytes);
const head = await this.storage.head(attachment.object_key);
if (head !== null && head.size === expectedSize) {
const data = await this.readObject(attachment.object_key, signal);
this.verifySource(attachment, data);
return data;
}
const stagingKey = attachment.staging_key;
if (stagingKey === null) throw new SourceMissingError();
const data = await this.readObject(stagingKey, signal);
this.verifySource(attachment, data);
await this.storage.putBuffer(
attachment.object_key,
data,
attachment.content_type,
signal,
);
this.metrics.increment('worker.original.published');
return data;
}
private async readObject(
key: string,
signal: AbortSignal,
): Promise<Buffer> {
const stream = await this.storage.getStream(key, signal);
if (stream === null) throw new SourceMissingError();
const chunks: Buffer[] = [];
let total = 0;
const destroy = (): void => {
stream.destroy(
signal.reason instanceof Error
? signal.reason
: new Error('Aborted'),
);
};
signal.addEventListener('abort', destroy, { once: true });
try {
for await (const chunk of stream as AsyncIterable<Buffer>) {
total += chunk.length;
if (total > this.maxUploadBytes)
throw new SourceMismatchError(
'Source exceeds MAX_UPLOAD_BYTES',
);
chunks.push(chunk);
}
} catch (error) {
if (signal.aborted)
throw signal.reason instanceof Error ? signal.reason : error;
throw error;
} finally {
signal.removeEventListener('abort', destroy);
stream.destroy();
}
return Buffer.concat(chunks, total);
}
private verifySource(attachment: AttachmentRow, data: Buffer): void {
if (
data.length !== Number(attachment.size_bytes) ||
sha256(data) !== attachment.sha256
)
throw new SourceMismatchError();
}
private variantKey(
job: {
attachment_id: string;
pipeline_version: number;
attempt: number;
},
variant: RenderedVariant,
): string {
return this.storage.variantKey(
job.attachment_id,
job.pipeline_version,
variant.name,
variant.ext,
job.attempt,
);
}
private variantWrite(
job: {
attachment_id: string;
pipeline_version: number;
attempt: number;
},
variant: RenderedVariant,
): VariantWrite {
return {
name: variant.name,
objectKey: this.variantKey(job, variant),
contentType: variant.contentType,
sizeBytes: variant.data.length,
width: variant.width,
height: variant.height,
sha256: variant.sha256,
};
}
private async cleanupAttemptObjects(
job: { attachment_id: string; pipeline_version: number; attempt: number },
keepAttempt: number | null,
): Promise<void> {
for (let attempt = 1; attempt <= job.attempt; attempt += 1) {
if (attempt === keepAttempt) continue;
for (const [name, extension] of VARIANT_EXTENSIONS) {
try {
await this.storage.delete(
this.storage.variantKey(
job.attachment_id,
job.pipeline_version,
name,
extension,
attempt,
),
);
} catch (error) {
this.logger.warn(
`Variant cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
}
}
}
}
private async cleanupStaging(attachment: AttachmentRow): Promise<void> {
const key = attachment.staging_key;
if (key === null) return;
try {
const cleared = await this.jobs.clearStaging(
attachment.id,
key,
(stagingKey) => this.storage.delete(stagingKey),
);
if (cleared) this.metrics.increment('worker.staging.deleted');
} catch (error) {
this.metrics.increment('worker.staging.error');
this.logger.warn(
`Staging cleanup for ${attachment.id} deferred: ${error instanceof Error ? error.message : 'unknown error'}`,
);
}
}
private async claimWithRetry(
message: JobMessage,
): Promise<ClaimResult | undefined> {
for (let attempt = 1; attempt <= 3; attempt += 1) {
try {
return await this.jobs.claim(
message,
this.workerId,
this.leaseSeconds,
);
} catch (error) {
if (attempt === 3) {
this.logger.warn(
`Claim failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
return undefined;
}
await this.sleep(300 * attempt);
}
}
return undefined;
}
private sleep(milliseconds: number): Promise<void> {
const { promise, resolve } = Promise.withResolvers<void>();
setTimeout(resolve, milliseconds);
return promise;
}
private safeNackAfter(
channel: Channel,
message: ConsumeMessage,
requeue: boolean,
delayMs: number,
): void {
setTimeout(() => this.safeNack(channel, message, requeue), delayMs);
}
private safeAck(channel: Channel, message: ConsumeMessage): void {
try {
channel.ack(message);
} catch {
// A closed channel redelivers; the DB fence makes the duplicate a no-op.
}
}
private safeNack(
channel: Channel,
message: ConsumeMessage,
requeue: boolean,
): void {
try {
channel.nack(message, false, requeue);
} catch {
// The broker redelivers after the delivery limit or lease recovery.
}
}
private begin(): void {
this.active += 1;
}
private end(): void {
this.active -= 1;
if (this.active !== 0) return;
for (const resolve of this.idleWaiters.splice(0)) resolve();
}
}