Files
mtusi2026lab4/app/src/attachments/attachments.service.spec.ts
T

114 lines
3.4 KiB
TypeScript

import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
import { fileURLToPath } from 'node:url';
import { describe, expect, it, vi } from 'vitest';
import type { AttachmentRow } from './attachment.js';
import { AttachmentsService } from './attachments.service.js';
const here = dirname(fileURLToPath(import.meta.url));
const png = readFileSync(join(here, '../../../tests/fixtures/sample.png'));
const lostReply = () =>
Object.assign(new Error('Connection terminated unexpectedly'), {});
const settings: Record<string, number> = {
MAX_UPLOAD_BYTES: 10_485_760,
MAX_IMAGE_PIXELS: 40_000_000,
UPLOAD_TIMEOUT_MS: 10_000,
};
function setup(repository: Record<string, unknown>) {
const storage = {
objectKey: (id: string) => `attachments/${id}/original`,
putStream: vi.fn(async (_key: string, body: Readable) => {
for await (const _chunk of body) {
// drain like S3 does
}
}),
delete: vi.fn().mockResolvedValue(undefined),
};
const service = new AttachmentsService(
{ getOrThrow: (key: string) => settings[key] } as never,
{
insertPending: vi.fn(),
deleteClaimed: vi.fn(),
...repository,
} as never,
storage as never,
{ getForUser: vi.fn() } as never,
{ increment: vi.fn(), add: vi.fn() } as never,
{ verify: vi.fn() } as never,
{ run: (work: () => Promise<unknown>) => work() } as never,
);
const upload = () =>
service.uploadProxy(
'chat',
{ id: 'user' } as never,
'a.png',
'image/png',
String(png.length),
Readable.from([png]),
);
return { storage, upload };
}
const readyRow = (id: string): AttachmentRow => ({
id,
chat_id: 'chat',
owner_id: 'user',
filename: 'a.png',
content_type: 'image/png',
upload_mode: 'proxy',
status: 'ready',
object_key: `attachments/${id}/original`,
size_bytes: png.length,
sha256: 'a'.repeat(64),
width: 320,
height: 200,
expires_at: null,
created_at: new Date(),
updated_at: new Date(),
});
describe('AttachmentsService compensation', () => {
it('keeps the object and answers 201 when ready was committed but its reply was lost', async () => {
const { storage, upload } = setup({
markReady: vi.fn().mockRejectedValue(lostReply()),
claimForCompensation: vi.fn().mockResolvedValue(false),
findById: vi.fn((id: string) => Promise.resolve(readyRow(id))),
});
const attachment = await upload();
expect(attachment.status).toBe('ready');
expect(storage.delete).not.toHaveBeenCalled();
});
it('deletes nothing while PostgreSQL is unreachable', async () => {
const { storage, upload } = setup({
markReady: vi.fn().mockRejectedValue(lostReply()),
claimForCompensation: vi.fn().mockRejectedValue(lostReply()),
findById: vi.fn().mockRejectedValue(lostReply()),
});
await expect(upload()).rejects.toThrow();
expect(storage.delete).not.toHaveBeenCalled();
});
it('deletes the object only after claiming the pending row', async () => {
const order: string[] = [];
const { storage, upload } = setup({
markReady: vi.fn().mockRejectedValue(lostReply()),
claimForCompensation: vi.fn(async () => {
order.push('claim');
return true;
}),
deleteClaimed: vi.fn(async () => {
order.push('delete-row');
}),
});
storage.delete.mockImplementation(async () => {
order.push('delete-object');
});
await expect(upload()).rejects.toThrow();
expect(order).toEqual(['claim', 'delete-object', 'delete-row']);
});
});