forked from mtusi2026/mtusi2026lab5
lab5: брокер RabbitMQ, worker и асинхронная обработка
This commit is contained in:
@@ -0,0 +1,405 @@
|
||||
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { Channel, ConsumeMessage } from 'amqplib';
|
||||
import { createHash } from 'node:crypto';
|
||||
import os from 'node:os';
|
||||
import type { AttachmentRow } from '../attachments/attachment.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { ObjectStorage } from '../storage/object-storage.js';
|
||||
import { retryDelayMs } from '../jobs/backoff.js';
|
||||
import { BrokerClient } from '../jobs/broker.client.js';
|
||||
import {
|
||||
classifyError,
|
||||
JobTimeoutError,
|
||||
SourceMismatchError,
|
||||
SourceMissingError,
|
||||
type ErrorClass,
|
||||
} from '../jobs/errors.js';
|
||||
import { FaultInjector } from '../jobs/fault-injector.js';
|
||||
import { parseJobMessage } from '../jobs/job-message.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';
|
||||
|
||||
const SHUTDOWN_DRAIN_MS = 30_000;
|
||||
|
||||
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 = process.env.INSTANCE_ID ?? os.hostname();
|
||||
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,
|
||||
private readonly faults: FaultInjector,
|
||||
private readonly storage: ObjectStorage,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
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 {
|
||||
this.broker.consume(
|
||||
this.config.getOrThrow('WORKER_CONCURRENCY'),
|
||||
(message, channel) => this.handle(message, channel),
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private async handle(
|
||||
message: ConsumeMessage,
|
||||
channel: Channel,
|
||||
): Promise<void> {
|
||||
const parsed = parseJobMessage(message.content);
|
||||
if (!parsed) {
|
||||
this.metrics.increment('worker.messages.poison');
|
||||
this.safeNack(channel, message, false);
|
||||
return;
|
||||
}
|
||||
|
||||
let claim: ClaimResult;
|
||||
try {
|
||||
claim = await this.jobs.claim(
|
||||
parsed,
|
||||
this.workerId,
|
||||
this.leaseSeconds,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Claim failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
this.safeNack(channel, message, true);
|
||||
return;
|
||||
}
|
||||
if (claim.kind === 'skip') {
|
||||
if (claim.reason === 'mismatch') {
|
||||
this.safeNack(channel, message, false);
|
||||
return;
|
||||
}
|
||||
this.metrics.increment(`worker.jobs.skipped.${claim.reason}`);
|
||||
this.safeAck(channel, message);
|
||||
return;
|
||||
}
|
||||
|
||||
this.begin();
|
||||
try {
|
||||
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;
|
||||
},
|
||||
attachment: AttachmentRow,
|
||||
leaseToken: string,
|
||||
message: ConsumeMessage,
|
||||
channel: Channel,
|
||||
): Promise<void> {
|
||||
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;
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
throwIfAborted(controller.signal);
|
||||
for (const variant of variants) {
|
||||
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)),
|
||||
);
|
||||
committed = true;
|
||||
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);
|
||||
} 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;
|
||||
}
|
||||
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}`);
|
||||
this.safeAck(channel, message);
|
||||
} 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);
|
||||
}
|
||||
} 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 },
|
||||
variant: RenderedVariant,
|
||||
): string {
|
||||
return this.storage.variantKey(
|
||||
job.attachment_id,
|
||||
job.pipeline_version,
|
||||
variant.name,
|
||||
variant.ext,
|
||||
);
|
||||
}
|
||||
|
||||
private variantWrite(
|
||||
job: { attachment_id: string; pipeline_version: 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 cleanupStaging(attachment: AttachmentRow): Promise<void> {
|
||||
const key = attachment.staging_key;
|
||||
if (key === null) return;
|
||||
try {
|
||||
await this.storage.delete(key);
|
||||
await this.jobs.clearStaging(attachment.id, key);
|
||||
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 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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user