forked from mtusi2026/mtusi2026lab5
feat: accept uploads into staging with jobs, outbox and job processor
This commit is contained in:
@@ -26,7 +26,7 @@ export class AttachmentsController {
|
||||
constructor(private readonly attachments: AttachmentsService) {}
|
||||
|
||||
@Post('api/v1/chats/:chatId/attachments')
|
||||
@HttpCode(201)
|
||||
@HttpCode(202)
|
||||
async upload(
|
||||
@Param('chatId') chatId: string,
|
||||
@Query('filename') filename: unknown,
|
||||
@@ -61,19 +61,19 @@ export class AttachmentsController {
|
||||
@CurrentUser() user: User,
|
||||
@Res() reply: FastifyReply,
|
||||
): Promise<void> {
|
||||
const { attachment, content } = await this.attachments.openContent(
|
||||
const download = await this.attachments.openContent(
|
||||
attachmentId,
|
||||
user.id,
|
||||
variant,
|
||||
);
|
||||
await reply
|
||||
.header('content-type', attachment.contentType)
|
||||
.header('content-length', attachment.sizeBytes)
|
||||
.header('content-type', download.contentType)
|
||||
.header('content-length', download.sizeBytes)
|
||||
.header('x-content-type-options', 'nosniff')
|
||||
.header(
|
||||
'content-disposition',
|
||||
`inline; filename*=UTF-8''${encodeURIComponent(attachment.filename)}`,
|
||||
`inline; filename*=UTF-8''${encodeURIComponent(download.filename)}`,
|
||||
)
|
||||
.send(content);
|
||||
.send(download.content);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { Attachment, Prisma } from '@prisma/client';
|
||||
import { Attachment, AttachmentVariant, Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { mkdtemp, readdir, rm, stat } from 'fs/promises';
|
||||
import { tmpdir } from 'os';
|
||||
@@ -10,6 +10,8 @@ import { codePointLength } from '../common/dto/code-point-length.validator';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { validate as isUuid } from '../common/uuid';
|
||||
import { isDatabaseUnavailable, PrismaService } from '../db/prisma.service';
|
||||
import { PIPELINE_VERSION } from '../jobs/job-message';
|
||||
import { enqueueJob } from '../jobs/job-store';
|
||||
import { S3Service } from '../storage/s3.service';
|
||||
import { assertValidImage, isSupportedContentType } from './image-validation';
|
||||
import { receiveBody } from './upload-body';
|
||||
@@ -18,7 +20,16 @@ const TEMP_PREFIX = 'messenger-upload-';
|
||||
const STALE_TEMP_MS = 60 * 60 * 1000;
|
||||
const MAX_FILENAME_CODE_POINTS = 255;
|
||||
const FORBIDDEN_FILENAME = /[/\\\p{Cc}\p{Zl}\p{Zp}]/u;
|
||||
const KNOWN_VARIANTS = new Set(['thumbnail', 'crop', 'optimized']);
|
||||
const KNOWN_VARIANTS = new Set(['original', 'thumbnail', 'crop', 'optimized']);
|
||||
|
||||
export type AttachmentWithVariants = Attachment & { variants: AttachmentVariant[] };
|
||||
|
||||
export interface DownloadableContent {
|
||||
filename: string;
|
||||
contentType: string;
|
||||
sizeBytes: number;
|
||||
content: Readable;
|
||||
}
|
||||
|
||||
export interface UploadInput {
|
||||
chatId: string;
|
||||
@@ -36,6 +47,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
private readonly maxPixels = Number(process.env.MAX_IMAGE_PIXELS ?? 40000000);
|
||||
private readonly maxConcurrent = Number(process.env.MAX_CONCURRENT_UPLOADS ?? 16);
|
||||
private readonly bodyTimeoutMs = Number(process.env.UPLOAD_BODY_TIMEOUT_MS ?? 60000);
|
||||
private readonly tempRoot = process.env.UPLOAD_TMP_DIR ?? tmpdir();
|
||||
private activeUploads = 0;
|
||||
|
||||
constructor(
|
||||
@@ -47,7 +59,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
await this.removeStaleTempDirs();
|
||||
}
|
||||
|
||||
async upload(input: UploadInput): Promise<Attachment> {
|
||||
async upload(input: UploadInput): Promise<AttachmentWithVariants> {
|
||||
await assertChatMember(this.prisma, input.chatId, input.ownerId);
|
||||
const filename = parseFilename(input.filename);
|
||||
const contentType = parseContentType(input.contentType);
|
||||
@@ -58,7 +70,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
throw new ApiError('unavailable', 'too many concurrent uploads');
|
||||
}
|
||||
this.activeUploads++;
|
||||
const dir = await mkdtemp(join(tmpdir(), TEMP_PREFIX));
|
||||
const dir = await mkdtemp(join(this.tempRoot, TEMP_PREFIX));
|
||||
try {
|
||||
return await this.store(input, filename, contentType, join(dir, 'body'));
|
||||
} finally {
|
||||
@@ -67,7 +79,10 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
}
|
||||
|
||||
async getVisible(attachmentId: string, userId: string): Promise<Attachment> {
|
||||
async getVisible(
|
||||
attachmentId: string,
|
||||
userId: string,
|
||||
): Promise<AttachmentWithVariants> {
|
||||
if (!isUuid(attachmentId)) {
|
||||
throw new ApiError('invalid_request', 'attachmentId must be a valid UUID');
|
||||
}
|
||||
@@ -76,6 +91,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
id: attachmentId,
|
||||
chat: { members: { some: { userId } } },
|
||||
},
|
||||
include: { variants: { where: { pipelineVersion: PIPELINE_VERSION } } },
|
||||
});
|
||||
if (!row) {
|
||||
throw new ApiError('not_found', 'attachment not found');
|
||||
@@ -87,10 +103,30 @@ export class AttachmentsService implements OnModuleInit {
|
||||
attachmentId: string,
|
||||
userId: string,
|
||||
variant: unknown,
|
||||
): Promise<{ attachment: Attachment; content: Readable }> {
|
||||
): Promise<DownloadableContent> {
|
||||
const attachment = await this.getVisible(attachmentId, userId);
|
||||
assertOriginalVariant(variant);
|
||||
return { attachment, content: await this.s3.getStream(attachment.objectKey) };
|
||||
const name = parseVariant(variant);
|
||||
if (attachment.status !== 'ready') {
|
||||
throw new ApiError('conflict', `attachment is ${attachment.status}`);
|
||||
}
|
||||
if (name === 'original') {
|
||||
return {
|
||||
filename: attachment.filename,
|
||||
contentType: attachment.contentType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
content: await this.s3.getStream(attachment.objectKey),
|
||||
};
|
||||
}
|
||||
const stored = attachment.variants.find((v) => v.name === name);
|
||||
if (!stored) {
|
||||
throw new ApiError('not_found', 'attachment variant not found');
|
||||
}
|
||||
return {
|
||||
filename: attachment.filename,
|
||||
contentType: stored.contentType,
|
||||
sizeBytes: stored.sizeBytes,
|
||||
content: await this.s3.getStream(stored.objectKey),
|
||||
};
|
||||
}
|
||||
|
||||
private async store(
|
||||
@@ -98,7 +134,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
filename: string,
|
||||
contentType: string,
|
||||
path: string,
|
||||
): Promise<Attachment> {
|
||||
): Promise<AttachmentWithVariants> {
|
||||
if (!input.body) {
|
||||
throw new ApiError('invalid_request', 'request body must not be empty');
|
||||
}
|
||||
@@ -113,32 +149,38 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
await assertValidImage(path, size, contentType, this.maxPixels);
|
||||
const id = randomUUID();
|
||||
const objectKey = `attachments/${id}`;
|
||||
await this.s3.putFile({ key: objectKey, path, size, contentType, sha256 });
|
||||
const stagingKey = `staging/${id}`;
|
||||
await this.s3.putFile({ key: stagingKey, path, size, contentType, sha256 });
|
||||
const now = new Date();
|
||||
try {
|
||||
return await this.prisma.attachment.create({
|
||||
data: {
|
||||
id,
|
||||
chatId: input.chatId,
|
||||
ownerId: input.ownerId,
|
||||
filename,
|
||||
contentType,
|
||||
sizeBytes: size,
|
||||
sha256,
|
||||
objectKey,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
const attachment = await tx.attachment.create({
|
||||
data: {
|
||||
id,
|
||||
chatId: input.chatId,
|
||||
ownerId: input.ownerId,
|
||||
filename,
|
||||
contentType,
|
||||
sizeBytes: size,
|
||||
sha256,
|
||||
objectKey: `attachments/${id}/original`,
|
||||
stagingKey,
|
||||
status: 'queued',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
await enqueueJob(tx, id, now);
|
||||
return { ...attachment, variants: [] };
|
||||
});
|
||||
} catch (error) {
|
||||
if (isDefiniteRejection(error)) {
|
||||
await this.s3.delete(objectKey).catch(() => {
|
||||
this.logger.warn(`compensation failed for ${objectKey}`);
|
||||
await this.s3.delete(stagingKey).catch(() => {
|
||||
this.logger.warn(`compensation failed for ${stagingKey}`);
|
||||
});
|
||||
}
|
||||
if (error instanceof Prisma.PrismaClientUnknownRequestError) {
|
||||
this.logger.error(`metadata insert failed for ${objectKey}`);
|
||||
this.logger.error(`metadata insert failed for ${stagingKey}`);
|
||||
throw new ApiError('unavailable', 'database unavailable');
|
||||
}
|
||||
throw error;
|
||||
@@ -146,7 +188,7 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
|
||||
private async removeStaleTempDirs(): Promise<void> {
|
||||
const root = tmpdir();
|
||||
const root = this.tempRoot;
|
||||
const names = await readdir(root);
|
||||
for (const name of names.filter((n) => n.startsWith(TEMP_PREFIX))) {
|
||||
const path = join(root, name);
|
||||
@@ -158,12 +200,12 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
}
|
||||
|
||||
function assertOriginalVariant(raw: unknown): void {
|
||||
if (raw === undefined || raw === 'original') {
|
||||
return;
|
||||
function parseVariant(raw: unknown): string {
|
||||
if (raw === undefined) {
|
||||
return 'original';
|
||||
}
|
||||
if (typeof raw === 'string' && KNOWN_VARIANTS.has(raw)) {
|
||||
throw new ApiError('not_found', 'attachment variant not found');
|
||||
return raw;
|
||||
}
|
||||
throw new ApiError('invalid_request', 'unknown attachment variant');
|
||||
}
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
import { Attachment } from '@prisma/client';
|
||||
import { Attachment, AttachmentVariant } from '@prisma/client';
|
||||
|
||||
const VARIANT_ORDER = ['thumbnail', 'crop', 'optimized'];
|
||||
|
||||
export interface VariantResponse {
|
||||
name: string;
|
||||
content_type: string;
|
||||
size_bytes: number;
|
||||
width: number;
|
||||
height: number;
|
||||
sha256: string;
|
||||
}
|
||||
|
||||
export interface AttachmentResponse {
|
||||
id: string;
|
||||
@@ -8,14 +19,18 @@ export interface AttachmentResponse {
|
||||
content_type: string;
|
||||
size_bytes: number;
|
||||
sha256: string;
|
||||
status: 'ready';
|
||||
variants: never[];
|
||||
error_code: null;
|
||||
status: string;
|
||||
variants: VariantResponse[];
|
||||
error_code: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export function toAttachmentResponse(row: Attachment): AttachmentResponse {
|
||||
export function toAttachmentResponse(
|
||||
row: Attachment & { variants: AttachmentVariant[] },
|
||||
): AttachmentResponse {
|
||||
const variants = row.status === 'ready' ? [...row.variants] : [];
|
||||
variants.sort((a, b) => VARIANT_ORDER.indexOf(a.name) - VARIANT_ORDER.indexOf(b.name));
|
||||
return {
|
||||
id: row.id,
|
||||
chat_id: row.chatId,
|
||||
@@ -24,9 +39,16 @@ export function toAttachmentResponse(row: Attachment): AttachmentResponse {
|
||||
content_type: row.contentType,
|
||||
size_bytes: row.sizeBytes,
|
||||
sha256: row.sha256,
|
||||
status: 'ready',
|
||||
variants: [],
|
||||
error_code: null,
|
||||
status: row.status,
|
||||
variants: variants.map((variant) => ({
|
||||
name: variant.name,
|
||||
content_type: variant.contentType,
|
||||
size_bytes: variant.sizeBytes,
|
||||
width: variant.width,
|
||||
height: variant.height,
|
||||
sha256: variant.sha256,
|
||||
})),
|
||||
error_code: row.errorCode,
|
||||
created_at: row.createdAt.toISOString(),
|
||||
updated_at: row.updatedAt.toISOString(),
|
||||
};
|
||||
|
||||
@@ -2,10 +2,14 @@ import { PrismaClient } from '@prisma/client';
|
||||
import { S3Service } from '../storage/s3.service';
|
||||
|
||||
const MAX_REPORTED_KEYS = 20;
|
||||
const DEFAULT_PREFIXES = ['attachments/', 'staging/'];
|
||||
|
||||
type ReconcilePrisma = Pick<PrismaClient, 'attachment' | 'attachmentVariant'>;
|
||||
|
||||
export interface ReconcileOptions {
|
||||
apply: boolean;
|
||||
graceMs: number;
|
||||
stagingRetentionMs?: number;
|
||||
prefix?: string;
|
||||
now?: Date;
|
||||
pageSize?: number;
|
||||
@@ -14,6 +18,7 @@ export interface ReconcileOptions {
|
||||
export interface ReconcileReport {
|
||||
mode: 'apply' | 'dry-run';
|
||||
grace_seconds: number;
|
||||
staging_expired: number;
|
||||
scanned: number;
|
||||
fresh_skipped: number;
|
||||
referenced: number;
|
||||
@@ -25,7 +30,7 @@ export interface ReconcileReport {
|
||||
}
|
||||
|
||||
export async function reconcile(
|
||||
prisma: Pick<PrismaClient, 'attachment'>,
|
||||
prisma: ReconcilePrisma,
|
||||
s3: S3Service,
|
||||
options: ReconcileOptions,
|
||||
): Promise<ReconcileReport> {
|
||||
@@ -34,6 +39,7 @@ export async function reconcile(
|
||||
const report: ReconcileReport = {
|
||||
mode: options.apply ? 'apply' : 'dry-run',
|
||||
grace_seconds: options.graceMs / 1000,
|
||||
staging_expired: 0,
|
||||
scanned: 0,
|
||||
fresh_skipped: 0,
|
||||
referenced: 0,
|
||||
@@ -43,22 +49,83 @@ export async function reconcile(
|
||||
orphan_keys: [],
|
||||
duration_ms: 0,
|
||||
};
|
||||
if (options.stagingRetentionMs !== undefined) {
|
||||
report.staging_expired = await expireFailedStaging(
|
||||
prisma,
|
||||
s3,
|
||||
(options.now ?? new Date()).getTime() - options.stagingRetentionMs,
|
||||
options.apply,
|
||||
);
|
||||
}
|
||||
for (const prefix of options.prefix ? [options.prefix] : DEFAULT_PREFIXES) {
|
||||
await reconcilePrefix(prisma, s3, prefix, cutoff, options, report);
|
||||
}
|
||||
report.duration_ms = Date.now() - started;
|
||||
return report;
|
||||
}
|
||||
|
||||
async function expireFailedStaging(
|
||||
prisma: ReconcilePrisma,
|
||||
s3: S3Service,
|
||||
before: number,
|
||||
apply: boolean,
|
||||
): Promise<number> {
|
||||
const rows = await prisma.attachment.findMany({
|
||||
where: {
|
||||
status: 'failed',
|
||||
stagingKey: { not: null },
|
||||
updatedAt: { lt: new Date(before) },
|
||||
},
|
||||
select: { id: true, stagingKey: true },
|
||||
take: 500,
|
||||
});
|
||||
if (!apply) {
|
||||
return rows.length;
|
||||
}
|
||||
let expired = 0;
|
||||
for (const row of rows) {
|
||||
try {
|
||||
await s3.delete(row.stagingKey!);
|
||||
await prisma.attachment.update({
|
||||
where: { id: row.id },
|
||||
data: { stagingKey: null },
|
||||
});
|
||||
expired++;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return expired;
|
||||
}
|
||||
|
||||
async function reconcilePrefix(
|
||||
prisma: ReconcilePrisma,
|
||||
s3: S3Service,
|
||||
prefix: string,
|
||||
cutoff: number,
|
||||
options: ReconcileOptions,
|
||||
report: ReconcileReport,
|
||||
): Promise<void> {
|
||||
let token: string | undefined;
|
||||
do {
|
||||
const page = await s3.listObjects(
|
||||
options.prefix ?? 'attachments/',
|
||||
options.pageSize ?? 500,
|
||||
token,
|
||||
);
|
||||
const page = await s3.listObjects(prefix, options.pageSize ?? 500, token);
|
||||
token = page.nextToken;
|
||||
report.scanned += page.objects.length;
|
||||
const old = page.objects.filter((object) => object.lastModified.getTime() < cutoff);
|
||||
report.fresh_skipped += page.objects.length - old.length;
|
||||
const keys = old.map((object) => object.key);
|
||||
const rows = await prisma.attachment.findMany({
|
||||
where: { objectKey: { in: old.map((object) => object.key) } },
|
||||
where: { OR: [{ objectKey: { in: keys } }, { stagingKey: { in: keys } }] },
|
||||
select: { objectKey: true, stagingKey: true },
|
||||
});
|
||||
const variants = await prisma.attachmentVariant.findMany({
|
||||
where: { objectKey: { in: keys } },
|
||||
select: { objectKey: true },
|
||||
});
|
||||
const known = new Set(rows.map((row) => row.objectKey));
|
||||
const known = new Set([
|
||||
...rows.flatMap((row) => [row.objectKey, row.stagingKey]),
|
||||
...variants.map((row) => row.objectKey),
|
||||
]);
|
||||
for (const { key } of old) {
|
||||
if (known.has(key)) {
|
||||
report.referenced++;
|
||||
@@ -76,6 +143,4 @@ export async function reconcile(
|
||||
}
|
||||
}
|
||||
} while (token);
|
||||
report.duration_ms = Date.now() - started;
|
||||
return report;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
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 type ReplayResult = 'replayed' | 'already_ready' | 'not_failed' | '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';
|
||||
}
|
||||
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) {
|
||||
return 'not_failed';
|
||||
}
|
||||
await tx.attachment.update({
|
||||
where: { id: job.attachmentId },
|
||||
data: { status: 'queued', errorCode: null },
|
||||
});
|
||||
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(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
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, 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),
|
||||
};
|
||||
}
|
||||
|
||||
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: { afterStore?: () => Promise<void> } = {},
|
||||
) {}
|
||||
|
||||
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) {
|
||||
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);
|
||||
} 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.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
|
||||
? '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}`;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
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 function fitInside(
|
||||
width: number,
|
||||
height: number,
|
||||
box: number,
|
||||
): { width: number; height: number } {
|
||||
const scale = Math.min(box / width, box / height, 1);
|
||||
return {
|
||||
width: Math.max(1, Math.floor(width * scale)),
|
||||
height: Math.max(1, Math.floor(height * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
export async function renderVariants(
|
||||
original: Buffer,
|
||||
maxPixels: number,
|
||||
): Promise<RenderedVariant[]> {
|
||||
const open = (): Sharp =>
|
||||
sharp(original, { failOn: 'error', limitInputPixels: maxPixels }).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;
|
||||
}
|
||||
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'),
|
||||
};
|
||||
}
|
||||
@@ -166,12 +166,16 @@ export class MessagesService {
|
||||
if (attachmentIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const found = await this.prisma.attachment.count({
|
||||
const found = await this.prisma.attachment.findMany({
|
||||
where: { id: { in: attachmentIds }, chatId },
|
||||
select: { status: true },
|
||||
});
|
||||
if (found !== attachmentIds.length) {
|
||||
if (found.length !== attachmentIds.length) {
|
||||
throw new ApiError('not_found', 'attachment not found');
|
||||
}
|
||||
if (found.some((row) => row.status === 'failed')) {
|
||||
throw new ApiError('conflict', 'failed attachment cannot be attached');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { S3Service } from './storage/s3.service';
|
||||
|
||||
const DEFAULT_GRACE_SECONDS = 3600;
|
||||
const DEFAULT_INTERVAL_SECONDS = 300;
|
||||
const DEFAULT_STAGING_RETENTION_SECONDS = 86400;
|
||||
|
||||
function option(name: string, fallback: number): number {
|
||||
const prefix = `--${name}=`;
|
||||
@@ -23,6 +24,10 @@ async function main(): Promise<void> {
|
||||
const loop = process.argv.includes('--loop');
|
||||
const graceSeconds = option('grace-seconds', DEFAULT_GRACE_SECONDS);
|
||||
const intervalSeconds = option('interval-seconds', DEFAULT_INTERVAL_SECONDS);
|
||||
const stagingRetentionSeconds = option(
|
||||
'staging-retention-seconds',
|
||||
Number(process.env.STAGING_RETENTION_SECONDS ?? DEFAULT_STAGING_RETENTION_SECONDS),
|
||||
);
|
||||
const prisma = new PrismaService();
|
||||
const s3 = new S3Service();
|
||||
do {
|
||||
@@ -30,6 +35,7 @@ async function main(): Promise<void> {
|
||||
const report = await reconcile(prisma, s3, {
|
||||
apply,
|
||||
graceMs: graceSeconds * 1000,
|
||||
stagingRetentionMs: stagingRetentionSeconds * 1000,
|
||||
});
|
||||
process.stdout.write(`${JSON.stringify(report)}\n`);
|
||||
} catch (error) {
|
||||
|
||||
@@ -76,6 +76,69 @@ export class S3Service implements OnModuleDestroy {
|
||||
);
|
||||
}
|
||||
|
||||
async putBuffer(
|
||||
key: string,
|
||||
body: Buffer,
|
||||
contentType: string,
|
||||
sha256: string,
|
||||
): Promise<void> {
|
||||
await this.guard(`put ${key}`, () =>
|
||||
this.client.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: this.bucket,
|
||||
Key: key,
|
||||
Body: body,
|
||||
ContentLength: body.length,
|
||||
ContentType: contentType,
|
||||
ChecksumSHA256: Buffer.from(sha256, 'hex').toString('base64'),
|
||||
}),
|
||||
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async getBuffer(key: string, maxBytes: number): Promise<Buffer> {
|
||||
let body: Readable;
|
||||
try {
|
||||
const response = await this.client.send(
|
||||
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
|
||||
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
|
||||
);
|
||||
if ((response.ContentLength ?? 0) > maxBytes) {
|
||||
throw new ObjectTooLargeError(key);
|
||||
}
|
||||
body = response.Body as Readable;
|
||||
} catch (error) {
|
||||
if (error instanceof ObjectTooLargeError) {
|
||||
throw error;
|
||||
}
|
||||
const name = error instanceof Error ? error.name : 'unknown error';
|
||||
this.logger.error(`get ${key} failed: ${name}`);
|
||||
if (name === 'NoSuchKey') {
|
||||
throw new ObjectMissingError(key);
|
||||
}
|
||||
throw new ApiError('unavailable', 'object storage unavailable');
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
try {
|
||||
for await (const chunk of body) {
|
||||
size += chunk.length;
|
||||
if (size > maxBytes) {
|
||||
body.destroy();
|
||||
throw new ObjectTooLargeError(key);
|
||||
}
|
||||
chunks.push(chunk);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ObjectTooLargeError) {
|
||||
throw error;
|
||||
}
|
||||
throw new ApiError('unavailable', 'object storage unavailable');
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
async getStream(key: string): Promise<Readable> {
|
||||
const deadline = new AbortController();
|
||||
const timer = setTimeout(() => deadline.abort(), IDLE_TIMEOUT_MS);
|
||||
@@ -158,6 +221,20 @@ export class S3Service implements OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
export class ObjectMissingError extends Error {
|
||||
constructor(key: string) {
|
||||
super(`object ${key} is missing from storage`);
|
||||
this.name = 'ObjectMissingError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ObjectTooLargeError extends Error {
|
||||
constructor(key: string) {
|
||||
super(`object ${key} exceeds size limit`);
|
||||
this.name = 'ObjectTooLargeError';
|
||||
}
|
||||
}
|
||||
|
||||
function readSecret(name: string): string {
|
||||
const file = process.env[`${name}_FILE`];
|
||||
const value = file ? readFileSync(file, 'utf8').trim() : process.env[name];
|
||||
|
||||
Reference in New Issue
Block a user