forked from mtusi2026/mtusi2026lab5
fix: close cleanup and replay races, integer thumbnail sizing, sharp deadline, contract tests
This commit is contained in:
@@ -55,6 +55,7 @@ export async function reconcile(
|
||||
s3,
|
||||
(options.now ?? new Date()).getTime() - options.stagingRetentionMs,
|
||||
options.apply,
|
||||
options.prefix,
|
||||
);
|
||||
}
|
||||
for (const prefix of options.prefix ? [options.prefix] : DEFAULT_PREFIXES) {
|
||||
@@ -69,10 +70,11 @@ async function expireFailedStaging(
|
||||
s3: S3Service,
|
||||
before: number,
|
||||
apply: boolean,
|
||||
prefix?: string,
|
||||
): Promise<number> {
|
||||
const rows = await prisma.attachment.findMany({
|
||||
where: {
|
||||
stagingKey: { not: null },
|
||||
stagingKey: { not: null, startsWith: prefix },
|
||||
OR: [{ status: 'ready' }, { status: 'failed', updatedAt: { lt: new Date(before) } }],
|
||||
},
|
||||
select: { id: true, stagingKey: true },
|
||||
@@ -83,20 +85,30 @@ async function expireFailedStaging(
|
||||
}
|
||||
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 {
|
||||
const released = await prisma.attachment.updateMany({
|
||||
where: {
|
||||
id: row.id,
|
||||
stagingKey: row.stagingKey,
|
||||
OR: [{ status: 'ready' }, { status: 'failed', updatedAt: { lt: new Date(before) } }],
|
||||
},
|
||||
data: { stagingKey: null },
|
||||
});
|
||||
if (released.count === 0) {
|
||||
continue;
|
||||
}
|
||||
await s3.delete(row.stagingKey!).then(
|
||||
() => expired++,
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
return expired;
|
||||
}
|
||||
|
||||
function attachmentIdOf(key: string): string | null {
|
||||
const match = /^attachments\/([0-9a-f-]{36})(\/|$)/.exec(key);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
async function reconcilePrefix(
|
||||
prisma: ReconcilePrisma,
|
||||
s3: S3Service,
|
||||
@@ -121,12 +133,18 @@ async function reconcilePrefix(
|
||||
where: { objectKey: { in: keys } },
|
||||
select: { objectKey: true },
|
||||
});
|
||||
const ids = [...new Set(keys.map(attachmentIdOf).filter((id): id is string => id !== null))];
|
||||
const owners = ids.length
|
||||
? await prisma.attachment.findMany({ where: { id: { in: ids } }, select: { id: true } })
|
||||
: [];
|
||||
const owned = new Set(owners.map((row) => row.id));
|
||||
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)) {
|
||||
const owner = attachmentIdOf(key);
|
||||
if (known.has(key) || (owner !== null && owned.has(owner))) {
|
||||
report.referenced++;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ const INVALID_CHAT_ID = example(
|
||||
);
|
||||
|
||||
export const GUIDE = `
|
||||
Учебный мессенджер, лабораторная 3: PostgreSQL, сессии, Redis-кэш сессий.
|
||||
Учебный мессенджер, лабораторная 5: PostgreSQL, сессии, Redis-кэш сессий, вложения в S3 и их фоновая обработка.
|
||||
Документ — обязательный контракт \`contracts/openapi.json\`, дополненный примерами запросов и ответов.
|
||||
|
||||
**Как пройти сценарий в Swagger UI**
|
||||
@@ -90,8 +90,9 @@ export const GUIDE = `
|
||||
4. \`GET /api/v1/users/me\` — свой id; id второго участника — из ответа его регистрации.
|
||||
5. \`POST /api/v1/chats\` с \`member_ids\` = [свой id, id собеседника] → \`chat_id\`.
|
||||
6. \`POST /api/v1/chats/{chat_id}/messages\` с заголовком \`Idempotency-Key\` (любая строка из \`A-Za-z0-9._:-\`, до 128 символов). Повтор с тем же ключом и телом вернёт то же сообщение, с другим телом — 409. Затем \`GET …/messages?limit=1\` и следующая страница с \`cursor\` = \`next_cursor\`.
|
||||
7. Чтобы действовать от другого пользователя: Logout в Authorize, вход им и новый token.
|
||||
8. \`DELETE /api/v1/auth/sessions/current\` — logout; тот же token дальше даёт 401.
|
||||
7. \`POST /api/v1/chats/{chat_id}/attachments?filename=photo.png\` с телом PNG/JPEG → 202 \`queued\`. \`GET /api/v1/attachments/{id}\` повторять, пока \`status\` не станет \`ready\` (до этого \`/content\` отвечает 409), затем \`/content?variant=thumbnail\`, \`crop\` или \`optimized\`.
|
||||
8. Чтобы действовать от другого пользователя: Logout в Authorize, вход им и новый token.
|
||||
9. \`DELETE /api/v1/auth/sessions/current\` — logout; тот же token дальше даёт 401.
|
||||
|
||||
Сессия живёт \`SESSION_TTL_SECONDS\` (по умолчанию 3600 с). Пароль — 12–128 символов Unicode, двоеточие допустимо.
|
||||
`;
|
||||
|
||||
+17
-6
@@ -187,7 +187,12 @@ export async function republishStale(
|
||||
return stale.length;
|
||||
}
|
||||
|
||||
export type ReplayResult = 'replayed' | 'already_ready' | 'not_failed' | 'not_found';
|
||||
export type ReplayResult =
|
||||
| 'replayed'
|
||||
| 'already_ready'
|
||||
| 'not_failed'
|
||||
| 'source_missing'
|
||||
| 'not_found';
|
||||
|
||||
export async function replayJob(
|
||||
prisma: PrismaClient,
|
||||
@@ -203,6 +208,16 @@ export async function replayJob(
|
||||
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: {
|
||||
@@ -214,12 +229,8 @@ export async function replayJob(
|
||||
},
|
||||
});
|
||||
if (taken.count === 0) {
|
||||
return 'not_failed';
|
||||
throw new Error('job changed during replay');
|
||||
}
|
||||
await tx.attachment.update({
|
||||
where: { id: job.attachmentId },
|
||||
data: { status: 'queued', errorCode: null },
|
||||
});
|
||||
await tx.jobEvent.create({
|
||||
data: {
|
||||
jobId,
|
||||
|
||||
+12
-3
@@ -8,7 +8,12 @@ import {
|
||||
} from '../storage/s3.service';
|
||||
import { JobMessage, PIPELINE_VERSION } from './job-message';
|
||||
import { markFailed, retryOrFail } from './job-store';
|
||||
import { InvalidImageError, RenderedVariant, renderVariants } from './variants';
|
||||
import {
|
||||
InvalidImageError,
|
||||
RenderedVariant,
|
||||
RenderTimeoutError,
|
||||
renderVariants,
|
||||
} from './variants';
|
||||
|
||||
export type Outcome = 'ready' | 'retry' | 'failed' | 'skipped';
|
||||
|
||||
@@ -136,7 +141,11 @@ export class JobProcessor {
|
||||
}
|
||||
let variants: RenderedVariant[];
|
||||
try {
|
||||
variants = await renderVariants(original, this.options.maxPixels);
|
||||
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');
|
||||
@@ -213,7 +222,7 @@ export class JobProcessor {
|
||||
const reason =
|
||||
error instanceof PermanentError
|
||||
? error.message
|
||||
: error instanceof TimeoutError
|
||||
: 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}`);
|
||||
|
||||
+21
-6
@@ -25,24 +25,36 @@ export class InvalidImageError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
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 } {
|
||||
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)),
|
||||
};
|
||||
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 }).rotate();
|
||||
sharp(original, { failOn: 'error', limitInputPixels: maxPixels })
|
||||
.timeout({ seconds: timeoutSeconds })
|
||||
.rotate();
|
||||
try {
|
||||
const meta = await sharp(original, { limitInputPixels: maxPixels }).metadata();
|
||||
if (!meta.width || !meta.height) {
|
||||
@@ -73,6 +85,9 @@ export async function renderVariants(
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user