forked from mtusi2026/mtusi2026lab4
lab4: компенсация без потери объекта при потере ответа COMMIT, полный декод изображений (sharp) в proxy и direct complete
This commit is contained in:
@@ -30,6 +30,8 @@ import {
|
||||
ImageRejectedError,
|
||||
} from './image/image-inspector.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
import { ImageDecoder } from './image/image-decoder.js';
|
||||
import { UploadSlots } from './upload-slots.js';
|
||||
|
||||
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
|
||||
|
||||
@@ -49,11 +51,9 @@ class UploadInterruptedError extends Error {}
|
||||
@Injectable()
|
||||
export class AttachmentsService {
|
||||
private readonly logger = new Logger(AttachmentsService.name);
|
||||
private inFlight = 0;
|
||||
private readonly maxUploadBytes: number;
|
||||
private readonly maxPixels: number;
|
||||
private readonly uploadTimeoutMs: number;
|
||||
private readonly maxInFlight: number;
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
@@ -61,11 +61,12 @@ export class AttachmentsService {
|
||||
private readonly storage: ObjectStorage,
|
||||
private readonly chats: ChatsService,
|
||||
private readonly metrics: MetricsService,
|
||||
private readonly decoder: ImageDecoder,
|
||||
private readonly slots: UploadSlots,
|
||||
) {
|
||||
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
|
||||
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
|
||||
this.uploadTimeoutMs = config.getOrThrow('UPLOAD_TIMEOUT_MS');
|
||||
this.maxInFlight = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT');
|
||||
}
|
||||
|
||||
async uploadProxy(
|
||||
@@ -93,15 +94,9 @@ export class AttachmentsService {
|
||||
if (contentLength > this.maxUploadBytes)
|
||||
throw new PayloadTooLargeException('Image is too large');
|
||||
|
||||
if (this.inFlight >= this.maxInFlight)
|
||||
throw new HttpException(
|
||||
{ message: 'Too many concurrent uploads', retryAfter: 1 },
|
||||
429,
|
||||
);
|
||||
this.inFlight += 1;
|
||||
try {
|
||||
return this.slots.run(async () => {
|
||||
await this.chats.getForUser(chatId, user);
|
||||
return await this.receive(
|
||||
return this.receive(
|
||||
chatId,
|
||||
user,
|
||||
filename,
|
||||
@@ -109,9 +104,7 @@ export class AttachmentsService {
|
||||
contentLength,
|
||||
body,
|
||||
);
|
||||
} finally {
|
||||
this.inFlight -= 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async receive(
|
||||
@@ -193,8 +186,12 @@ export class AttachmentsService {
|
||||
});
|
||||
|
||||
const sha256 = createHash('sha256');
|
||||
const decoder = this.decoder;
|
||||
// Copy for the full decode check; bounded by MAX_UPLOAD_BYTES and
|
||||
// UPLOAD_MAX_IN_FLIGHT, released as soon as the decode starts.
|
||||
const copy: Buffer[] = [];
|
||||
let total = 0;
|
||||
const account = (chunk: Buffer, inspect: boolean): void => {
|
||||
const account = (chunk: Buffer, inspect: boolean): boolean => {
|
||||
total += chunk.length;
|
||||
if (total > contentLength)
|
||||
throw new UploadInterruptedError(
|
||||
@@ -203,19 +200,26 @@ export class AttachmentsService {
|
||||
if (inspect) inspector.push(chunk);
|
||||
sha256.update(chunk);
|
||||
this.metrics.add('attachments.proxy.bytes_in', chunk.length);
|
||||
// Validate before the last bytes reach S3: it cannot commit an
|
||||
// object whose body is incomplete.
|
||||
if (total === contentLength) inspector.finish();
|
||||
copy.push(chunk);
|
||||
return total === contentLength;
|
||||
};
|
||||
// Validate before the last bytes reach S3: it cannot commit an object
|
||||
// whose body is incomplete, so an invalid image never becomes an object.
|
||||
const finalize = async (): Promise<void> => {
|
||||
inspector.finish();
|
||||
const data = Buffer.concat(copy, total);
|
||||
copy.length = 0;
|
||||
await decoder.verify(data);
|
||||
};
|
||||
async function* generate(): AsyncGenerator<Buffer> {
|
||||
for (const chunk of head) {
|
||||
account(chunk, false);
|
||||
if (account(chunk, false)) await finalize();
|
||||
yield chunk;
|
||||
}
|
||||
for (;;) {
|
||||
const step = await next();
|
||||
if (step.done) break;
|
||||
account(step.value, true);
|
||||
if (account(step.value, true)) await finalize();
|
||||
yield step.value;
|
||||
}
|
||||
if (total < contentLength)
|
||||
@@ -238,6 +242,7 @@ export class AttachmentsService {
|
||||
// `rejection`; the listener also keeps a late error from crashing us.
|
||||
readable.on('error', () => controller.abort());
|
||||
let claimed = false;
|
||||
let stored = false;
|
||||
try {
|
||||
await this.storage.putStream(
|
||||
key,
|
||||
@@ -250,6 +255,7 @@ export class AttachmentsService {
|
||||
'attachments.proxy.bytes_to_s3',
|
||||
contentLength,
|
||||
);
|
||||
stored = true;
|
||||
const row = await this.repository.markReady(id, {
|
||||
sizeBytes: total,
|
||||
sha256: sha256.digest('hex'),
|
||||
@@ -264,7 +270,23 @@ export class AttachmentsService {
|
||||
return toAttachment(row);
|
||||
} catch (error) {
|
||||
readable.destroy();
|
||||
if (!claimed) await this.compensate(id, key);
|
||||
if (!claimed) {
|
||||
const outcome = await this.compensate(id, key);
|
||||
// markReady failed on our side, but the row is no longer
|
||||
// pending: the commit may have succeeded with its reply lost.
|
||||
// If so, the upload is complete and 201 is the truth.
|
||||
if (outcome === 'not_pending' && stored) {
|
||||
const row = await this.repository
|
||||
.findById(id)
|
||||
.catch(() => undefined);
|
||||
if (row?.status === 'ready') {
|
||||
this.metrics.increment(
|
||||
'attachments.upload.recovered',
|
||||
);
|
||||
return toAttachment(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw this.mapUploadError(rejection ?? error, timedOut);
|
||||
}
|
||||
} finally {
|
||||
@@ -279,16 +301,33 @@ export class AttachmentsService {
|
||||
return error;
|
||||
}
|
||||
|
||||
async compensate(id: string, key: string): Promise<void> {
|
||||
/**
|
||||
* Undoes an upload that did not reach `ready`. The row is claimed first
|
||||
* (pending -> deleting) and the object is deleted only after a successful
|
||||
* claim: if PostgreSQL committed `ready` but the reply was lost, the claim
|
||||
* matches nothing and the object stays. If PostgreSQL is unreachable,
|
||||
* nothing is deleted; the sweeper finishes the job after expiry + grace
|
||||
* (a row stuck in `deleting` is re-claimed after a minute).
|
||||
*/
|
||||
async compensate(
|
||||
id: string,
|
||||
key: string,
|
||||
): Promise<'compensated' | 'not_pending' | 'deferred'> {
|
||||
try {
|
||||
if (!(await this.repository.claimForCompensation(id))) {
|
||||
this.metrics.increment('attachments.compensation_skipped');
|
||||
return 'not_pending';
|
||||
}
|
||||
await this.storage.delete(key);
|
||||
await this.repository.deletePending(id);
|
||||
await this.repository.deleteClaimed(id);
|
||||
this.metrics.increment('attachments.compensated');
|
||||
return 'compensated';
|
||||
} catch (error) {
|
||||
this.metrics.increment('attachments.compensation_deferred');
|
||||
this.logger.warn(
|
||||
`Compensation of attachment ${id} deferred: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
return 'deferred';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user