chore: port lab5 solution as lab6 base

This commit is contained in:
2026-11-18 18:40:47 +03:00
parent 470d9d6f1e
commit 98d5787545
105 changed files with 21898 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
import { validate as isUuid } from '../common/uuid';
export const PIPELINE_VERSION = 1;
export const JOB_TYPE = 'attachment.process.v1';
export interface JobMessage {
schema_version: 1;
job_id: string;
type: typeof JOB_TYPE;
attachment_id: string;
pipeline_version: number;
attempt: number;
created_at: string;
}
const FIELDS = [
'schema_version',
'job_id',
'type',
'attachment_id',
'pipeline_version',
'attempt',
'created_at',
];
export function jobMessage(
job: { id: string; attachmentId: string; pipelineVersion: number; attempt: number },
createdAt: Date,
): JobMessage {
return {
schema_version: 1,
job_id: job.id,
type: JOB_TYPE,
attachment_id: job.attachmentId,
pipeline_version: job.pipelineVersion,
attempt: job.attempt,
created_at: createdAt.toISOString(),
};
}
export function parseJobMessage(raw: Buffer): JobMessage | null {
let value: any;
try {
value = JSON.parse(raw.toString('utf8'));
} catch {
return null;
}
if (
typeof value !== 'object' ||
value === null ||
Array.isArray(value) ||
Object.keys(value).some((key) => !FIELDS.includes(key)) ||
value.schema_version !== 1 ||
value.type !== JOB_TYPE ||
typeof value.job_id !== 'string' ||
!isUuid(value.job_id) ||
typeof value.attachment_id !== 'string' ||
!isUuid(value.attachment_id) ||
!Number.isInteger(value.pipeline_version) ||
value.pipeline_version < 1 ||
!Number.isInteger(value.attempt) ||
value.attempt < 1 ||
typeof value.created_at !== 'string' ||
Number.isNaN(Date.parse(value.created_at))
) {
return null;
}
return value as JobMessage;
}
+257
View File
@@ -0,0 +1,257 @@
import { AttachmentJob, Prisma, PrismaClient } from '@prisma/client';
import { randomUUID } from 'crypto';
import { jobMessage, PIPELINE_VERSION } from './job-message';
type Tx = Prisma.TransactionClient;
export const RETRY_EXHAUSTED = 'retry_exhausted';
export function maxAttempts(): number {
return Number(process.env.JOB_MAX_ATTEMPTS ?? 5);
}
export function backoffMs(attempt: number, random = Math.random): number {
const base = Number(process.env.JOB_RETRY_BASE_MS ?? 1000);
const cap = Number(process.env.JOB_RETRY_MAX_MS ?? 30000);
const delay = Math.min(cap, base * 2 ** (attempt - 1));
return Math.round(delay / 2 + random() * (delay / 2));
}
export async function enqueueJob(
tx: Tx,
attachmentId: string,
now: Date,
): Promise<AttachmentJob> {
const job = await tx.attachmentJob.create({
data: {
id: randomUUID(),
attachmentId,
pipelineVersion: PIPELINE_VERSION,
status: 'queued',
attempt: 1,
maxAttempts: maxAttempts(),
nextAttemptAt: now,
createdAt: now,
updatedAt: now,
},
});
await tx.jobEvent.create({
data: { jobId: job.id, attempt: 1, event: 'enqueued', createdAt: now },
});
await publishLater(tx, job, now);
return job;
}
export async function scheduleRetry(
tx: Tx,
job: AttachmentJob,
reason: string,
now: Date,
event = 'retry_scheduled',
): Promise<AttachmentJob> {
const delay = backoffMs(job.attempt);
const next = await tx.attachmentJob.update({
where: { id: job.id },
data: {
status: 'queued',
attempt: job.attempt + 1,
nextAttemptAt: new Date(now.getTime() + delay),
leaseOwner: null,
leaseUntil: null,
lastError: reason,
},
});
await tx.attachment.update({
where: { id: job.attachmentId },
data: { status: 'queued' },
});
await tx.jobEvent.create({
data: {
jobId: job.id,
attempt: job.attempt,
event,
detail: `${reason}; next attempt ${next.attempt} in ${delay} ms`,
createdAt: now,
},
});
await publishLater(tx, next, next.nextAttemptAt);
return next;
}
export async function markFailed(
tx: Tx,
job: AttachmentJob,
errorCode: string,
reason: string,
now: Date,
): Promise<void> {
await tx.attachmentJob.update({
where: { id: job.id },
data: {
status: 'failed',
errorCode,
lastError: reason,
leaseOwner: null,
leaseUntil: null,
finishedAt: now,
},
});
await tx.attachment.update({
where: { id: job.attachmentId },
data: { status: 'failed', errorCode },
});
await tx.jobEvent.create({
data: {
jobId: job.id,
attempt: job.attempt,
event: 'failed',
detail: `${errorCode}: ${reason}`,
createdAt: now,
},
});
}
export async function retryOrFail(
tx: Tx,
job: AttachmentJob,
reason: string,
now: Date,
event?: string,
): Promise<'retry' | 'failed'> {
if (job.attempt >= job.maxAttempts) {
await markFailed(tx, job, RETRY_EXHAUSTED, reason, now);
return 'failed';
}
await scheduleRetry(tx, job, reason, now, event);
return 'retry';
}
export async function recoverExpiredLeases(
prisma: PrismaClient,
now = new Date(),
limit = 100,
): Promise<number> {
const expired = await prisma.attachmentJob.findMany({
where: { status: 'processing', leaseUntil: { lt: now } },
orderBy: { leaseUntil: 'asc' },
take: limit,
});
let recovered = 0;
for (const candidate of expired) {
await prisma.$transaction(async (tx) => {
const taken = await tx.attachmentJob.updateMany({
where: {
id: candidate.id,
status: 'processing',
leaseOwner: candidate.leaseOwner,
leaseUntil: { lt: now },
},
data: { leaseOwner: null, leaseUntil: null, status: 'queued' },
});
if (taken.count === 0) {
return;
}
await retryOrFail(tx, candidate, 'lease expired', now, 'lease_expired');
recovered++;
});
}
return recovered;
}
export async function republishStale(
prisma: PrismaClient,
staleMs: number,
now = new Date(),
limit = 100,
): Promise<number> {
const cutoff = new Date(now.getTime() - staleMs);
const stale = await prisma.$queryRaw<AttachmentJob[]>`
SELECT j.id, j.attachment_id AS "attachmentId", j.pipeline_version AS "pipelineVersion", j.attempt
FROM attachment_jobs j
WHERE j.status = 'queued'
AND j.next_attempt_at < ${cutoff}
AND NOT EXISTS (
SELECT 1 FROM outbox o
WHERE o.job_id = j.id AND (o.published_at IS NULL OR o.published_at > ${cutoff})
)
ORDER BY j.next_attempt_at
LIMIT ${limit}`;
for (const job of stale) {
await prisma.$transaction(async (tx) => {
await tx.jobEvent.create({
data: { jobId: job.id, attempt: job.attempt, event: 'republished', createdAt: now },
});
await publishLater(tx, job, now);
});
}
return stale.length;
}
export type ReplayResult =
| 'replayed'
| 'already_ready'
| 'not_failed'
| 'source_missing'
| 'not_found';
export async function replayJob(
prisma: PrismaClient,
jobId: string,
actor: string,
now = new Date(),
): Promise<ReplayResult> {
return prisma.$transaction(async (tx) => {
const job = await tx.attachmentJob.findUnique({ where: { id: jobId } });
if (!job) {
return 'not_found';
}
if (job.status === 'ready') {
return 'already_ready';
}
if (job.status !== 'failed') {
return 'not_failed';
}
const source = await tx.attachment.updateMany({
where: { id: job.attachmentId, status: 'failed', stagingKey: { not: null } },
data: { status: 'queued', errorCode: null },
});
if (source.count === 0) {
return 'source_missing';
}
const taken = await tx.attachmentJob.updateMany({
where: { id: jobId, status: 'failed' },
data: {
status: 'queued',
attempt: 1,
errorCode: null,
nextAttemptAt: now,
finishedAt: null,
},
});
if (taken.count === 0) {
throw new Error('job changed during replay');
}
await tx.jobEvent.create({
data: {
jobId,
attempt: 1,
event: 'replayed',
detail: `by ${actor}; previous ${job.errorCode} after attempt ${job.attempt}`,
createdAt: now,
},
});
await publishLater(tx, { ...job, attempt: 1 }, now);
return 'replayed';
});
}
async function publishLater(tx: Tx, job: AttachmentJob, availableAt: Date): Promise<void> {
await tx.outboxEntry.create({
data: {
jobId: job.id,
payload: jobMessage(job, availableAt) as unknown as Prisma.InputJsonObject,
availableAt,
createdAt: new Date(),
},
});
}
+273
View File
@@ -0,0 +1,273 @@
import { Logger } from '@nestjs/common';
import { Attachment, AttachmentJob, PrismaClient } from '@prisma/client';
import { createHash, randomUUID } from 'crypto';
import {
ObjectMissingError,
ObjectTooLargeError,
S3Service,
} from '../storage/s3.service';
import { JobMessage, PIPELINE_VERSION } from './job-message';
import { markFailed, retryOrFail } from './job-store';
import {
InvalidImageError,
RenderedVariant,
RenderTimeoutError,
renderVariants,
} from './variants';
export type Outcome = 'ready' | 'retry' | 'failed' | 'skipped';
export interface ProcessorOptions {
timeoutMs: number;
leaseMs: number;
maxBytes: number;
maxPixels: number;
}
export function processorOptions(): ProcessorOptions {
const timeoutMs = Number(process.env.JOB_TIMEOUT_SECONDS ?? 60) * 1000;
return {
timeoutMs,
leaseMs: Number(process.env.JOB_LEASE_SECONDS ?? timeoutMs / 1000 + 30) * 1000,
maxBytes: Number(process.env.MAX_UPLOAD_BYTES ?? 10485760),
maxPixels: Number(process.env.MAX_IMAGE_PIXELS ?? 40000000),
};
}
export interface ProcessorHooks {
afterStore?: () => Promise<void>;
afterCommit?: () => Promise<void>;
}
class PermanentError extends Error {
constructor(
readonly code: string,
reason: string,
) {
super(reason);
}
}
class TimeoutError extends Error {}
export class JobProcessor {
private readonly logger = new Logger('JobProcessor');
constructor(
private readonly prisma: PrismaClient,
private readonly s3: S3Service,
private readonly options: ProcessorOptions = processorOptions(),
private readonly hooks: ProcessorHooks = {},
) {}
async handle(message: JobMessage): Promise<Outcome> {
const job = await this.prisma.attachmentJob.findUnique({
where: { id: message.job_id },
include: { attachment: true },
});
if (
!job ||
job.attachmentId !== message.attachment_id ||
job.pipelineVersion !== message.pipeline_version ||
job.pipelineVersion !== PIPELINE_VERSION
) {
this.logger.warn(`job ${message.job_id}: unknown or mismatched, dropped`);
return 'skipped';
}
const lease = await this.claim(job);
if (!lease) {
if (job.status === 'ready') {
await this.removeStaging(job.attachment);
}
this.logger.log(`job ${job.id}: ${job.status}, not due or leased elsewhere, skipped`);
return 'skipped';
}
let variants: RenderedVariant[];
try {
variants = await this.withTimeout(this.produce(job.attachment));
} catch (error) {
return this.recordFailure(lease, error);
}
await this.hooks.afterStore?.();
return this.commit(lease, job.attachment, variants);
}
private async claim(job: AttachmentJob): Promise<AttachmentJob | null> {
const now = new Date();
const owner = randomUUID();
return this.prisma.$transaction(async (tx) => {
const taken = await tx.attachmentJob.updateMany({
where: { id: job.id, status: 'queued', nextAttemptAt: { lte: now } },
data: {
status: 'processing',
leaseOwner: owner,
leaseUntil: new Date(now.getTime() + this.options.leaseMs),
},
});
if (taken.count === 0) {
return null;
}
await tx.attachment.update({
where: { id: job.attachmentId },
data: { status: 'processing' },
});
const leased = await tx.attachmentJob.findUniqueOrThrow({ where: { id: job.id } });
await tx.jobEvent.create({
data: { jobId: job.id, attempt: leased.attempt, event: 'processing', createdAt: now },
});
return leased;
});
}
private async produce(attachment: Attachment): Promise<RenderedVariant[]> {
if (!attachment.stagingKey) {
throw new PermanentError('staging_missing', 'staging object was already removed');
}
let original: Buffer;
try {
original = await this.s3.getBuffer(attachment.stagingKey, this.options.maxBytes);
} catch (error) {
if (error instanceof ObjectMissingError) {
throw new PermanentError('staging_missing', 'staging object not found');
}
if (error instanceof ObjectTooLargeError) {
throw new PermanentError('invalid_image', 'staging object exceeds size limit');
}
throw error;
}
const sha256 = createHash('sha256').update(original).digest('hex');
if (original.length !== attachment.sizeBytes || sha256 !== attachment.sha256) {
throw new PermanentError('checksum_mismatch', 'staging object differs from accepted upload');
}
let variants: RenderedVariant[];
try {
variants = await renderVariants(
original,
this.options.maxPixels,
Math.ceil(this.options.timeoutMs / 1000),
);
} catch (error) {
if (error instanceof InvalidImageError) {
throw new PermanentError('invalid_image', 'image cannot be decoded');
}
throw error;
}
await this.s3.putBuffer(attachment.objectKey, original, attachment.contentType, sha256);
for (const variant of variants) {
await this.s3.putBuffer(
variantKey(attachment.id, variant),
variant.body,
variant.contentType,
variant.sha256,
);
}
return variants;
}
private async commit(
lease: AttachmentJob,
attachment: Attachment,
variants: RenderedVariant[],
): Promise<Outcome> {
const now = new Date();
const committed = await this.prisma.$transaction(async (tx) => {
const owned = await tx.attachmentJob.updateMany({
where: { id: lease.id, status: 'processing', leaseOwner: lease.leaseOwner },
data: {
status: 'ready',
leaseOwner: null,
leaseUntil: null,
lastError: null,
finishedAt: now,
},
});
if (owned.count === 0) {
return false;
}
await tx.attachmentVariant.createMany({
data: variants.map((variant) => ({
attachmentId: attachment.id,
pipelineVersion: PIPELINE_VERSION,
name: variant.name,
contentType: variant.contentType,
objectKey: variantKey(attachment.id, variant),
sizeBytes: variant.body.length,
width: variant.width,
height: variant.height,
sha256: variant.sha256,
createdAt: now,
})),
skipDuplicates: true,
});
await tx.attachment.update({
where: { id: attachment.id },
data: { status: 'ready', errorCode: null },
});
await tx.jobEvent.create({
data: { jobId: lease.id, attempt: lease.attempt, event: 'ready', createdAt: now },
});
return true;
});
if (!committed) {
this.logger.warn(`job ${lease.id}: lease lost before commit, result left to owner`);
return 'skipped';
}
await this.hooks.afterCommit?.();
await this.removeStaging(attachment);
return 'ready';
}
private async recordFailure(lease: AttachmentJob, error: unknown): Promise<Outcome> {
const now = new Date();
const reason =
error instanceof PermanentError
? error.message
: error instanceof TimeoutError || error instanceof RenderTimeoutError
? 'processing timed out'
: `temporary failure: ${error instanceof Error ? error.name : 'unknown'}`;
this.logger.warn(`job ${lease.id} attempt ${lease.attempt}: ${reason}`);
return this.prisma.$transaction(async (tx) => {
const owned = await tx.attachmentJob.count({
where: { id: lease.id, status: 'processing', leaseOwner: lease.leaseOwner },
});
if (owned === 0) {
return 'skipped' as const;
}
if (error instanceof PermanentError) {
await markFailed(tx, lease, error.code, reason, now);
return 'failed' as const;
}
return retryOrFail(tx, lease, reason, now);
});
}
private async removeStaging(attachment: Attachment): Promise<void> {
if (!attachment.stagingKey) {
return;
}
try {
await this.s3.delete(attachment.stagingKey);
await this.prisma.attachment.update({
where: { id: attachment.id },
data: { stagingKey: null },
});
} catch {
this.logger.warn(`staging cleanup postponed for ${attachment.id}`);
}
}
private withTimeout<T>(work: Promise<T>): Promise<T> {
let timer: NodeJS.Timeout;
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new TimeoutError()), this.options.timeoutMs);
});
return Promise.race([work, deadline]).finally(() => clearTimeout(timer));
}
}
export function variantKey(
attachmentId: string,
variant: Pick<RenderedVariant, 'name' | 'extension'>,
): string {
return `attachments/${attachmentId}/v${PIPELINE_VERSION}/${variant.name}.${variant.extension}`;
}
+111
View File
@@ -0,0 +1,111 @@
import { createHash } from 'crypto';
import sharp, { Sharp } from 'sharp';
sharp.cache(false);
sharp.concurrency(1);
const WHITE = { r: 255, g: 255, b: 255 };
const JPEG_QUALITY = 82;
const WEBP_QUALITY = 80;
export interface RenderedVariant {
name: 'thumbnail' | 'crop' | 'optimized';
contentType: string;
extension: string;
body: Buffer;
width: number;
height: number;
sha256: string;
}
export class InvalidImageError extends Error {
constructor(reason: string) {
super(reason);
this.name = 'InvalidImageError';
}
}
export class RenderTimeoutError extends Error {
constructor() {
super('image processing exceeded its time limit');
this.name = 'RenderTimeoutError';
}
}
export function fitInside(
width: number,
height: number,
box: number,
): { width: number; height: number } {
if (width <= box && height <= box) {
return { width, height };
}
if (width >= height) {
return { width: box, height: Math.max(1, Math.floor((height * box) / width)) };
}
return { width: Math.max(1, Math.floor((width * box) / height)), height: box };
}
export async function renderVariants(
original: Buffer,
maxPixels: number,
timeoutSeconds = 0,
): Promise<RenderedVariant[]> {
const open = (): Sharp =>
sharp(original, { failOn: 'error', limitInputPixels: maxPixels })
.timeout({ seconds: timeoutSeconds })
.rotate();
try {
const meta = await sharp(original, { limitInputPixels: maxPixels }).metadata();
if (!meta.width || !meta.height) {
throw new InvalidImageError('image has no dimensions');
}
const swapped = (meta.orientation ?? 1) >= 5;
const width = swapped ? meta.height : meta.width;
const height = swapped ? meta.width : meta.height;
const thumb = fitInside(width, height, 256);
const large = fitInside(width, height, 1280);
const thumbnail = open()
.resize(thumb.width, thumb.height, { fit: 'fill' })
.flatten({ background: WHITE })
.jpeg({ quality: JPEG_QUALITY });
const crop = open()
.resize(128, 128, { fit: 'cover', position: 'centre' })
.flatten({ background: WHITE })
.jpeg({ quality: JPEG_QUALITY });
const optimized = open()
.resize(large.width, large.height, { fit: 'fill' })
.webp({ quality: WEBP_QUALITY, effort: 4 });
return [
await finish('thumbnail', 'image/jpeg', 'jpg', thumbnail),
await finish('crop', 'image/jpeg', 'jpg', crop),
await finish('optimized', 'image/webp', 'webp', optimized),
];
} catch (error) {
if (error instanceof InvalidImageError) {
throw error;
}
if (error instanceof Error && /timeout/i.test(error.message)) {
throw new RenderTimeoutError();
}
throw new InvalidImageError(error instanceof Error ? error.message : 'decode failed');
}
}
async function finish(
name: RenderedVariant['name'],
contentType: string,
extension: string,
pipeline: Sharp,
): Promise<RenderedVariant> {
const { data, info } = await pipeline.toBuffer({ resolveWithObject: true });
return {
name,
contentType,
extension,
body: data,
width: info.width,
height: info.height,
sha256: createHash('sha256').update(data).digest('hex'),
};
}