forked from mtusi2026/mtusi2026lab5
93 lines
3.1 KiB
TypeScript
93 lines
3.1 KiB
TypeScript
import { request } from 'node:http';
|
|
import type { AddressInfo } from 'node:net';
|
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
import { DrainingFastifyAdapter } from './fastify-adapter';
|
|
|
|
describe('upload body deadline over real HTTP', () => {
|
|
it('returns 408 for a client that keeps sending and never invokes the handler', async () => {
|
|
const adapter = new DrainingFastifyAdapter(0, 1000);
|
|
const server = adapter.getInstance();
|
|
let calls = 0;
|
|
server.post('/api/v1/chats/:chat_id/attachments', () => {
|
|
calls++;
|
|
return {};
|
|
});
|
|
await server.listen({ host: '127.0.0.1', port: 0 });
|
|
let timer: ReturnType<typeof setInterval> | undefined;
|
|
let watchdog: ReturnType<typeof setTimeout> | undefined;
|
|
try {
|
|
const port = (server.server.address() as AddressInfo).port;
|
|
const result = await new Promise<{
|
|
status?: number;
|
|
body: string;
|
|
id?: string;
|
|
}>((resolve, reject) => {
|
|
const client = request(
|
|
{
|
|
host: '127.0.0.1',
|
|
port,
|
|
method: 'POST',
|
|
path: '/api/v1/chats/test/attachments',
|
|
headers: { 'content-type': 'image/png', 'content-length': '10000' },
|
|
},
|
|
(response) => {
|
|
clearInterval(timer);
|
|
clearTimeout(watchdog);
|
|
let body = '';
|
|
response.on('data', (part: Buffer) => {
|
|
body += part.toString();
|
|
});
|
|
response.on('end', () => {
|
|
client.destroy();
|
|
resolve({
|
|
status: response.statusCode,
|
|
body,
|
|
id: response.headers['x-request-id'] as string,
|
|
});
|
|
});
|
|
response.on('error', reject);
|
|
},
|
|
);
|
|
client.on('error', reject);
|
|
watchdog = setTimeout(
|
|
() => client.destroy(new Error('deadline did not fire')),
|
|
7000,
|
|
);
|
|
client.write('partial');
|
|
timer = setInterval(() => client.write('x'), 100);
|
|
});
|
|
expect(result.status).toBe(408);
|
|
expect(result.id).toBeTruthy();
|
|
expect(JSON.parse(result.body)).toMatchObject({
|
|
error: { code: 'invalid_request', request_id: result.id },
|
|
});
|
|
expect(calls).toBe(0);
|
|
} finally {
|
|
clearInterval(timer);
|
|
clearTimeout(watchdog);
|
|
await server.close();
|
|
}
|
|
}, 15000);
|
|
|
|
it('clears the reception deadline before a completed body is processed', async () => {
|
|
const adapter = new DrainingFastifyAdapter(0, 1000);
|
|
const server = adapter.getInstance();
|
|
server.post('/api/v1/chats/:chat_id/attachments', async () => {
|
|
await delay(1200);
|
|
return { stored: true };
|
|
});
|
|
try {
|
|
const response = await server.inject({
|
|
method: 'POST',
|
|
url: '/api/v1/chats/test/attachments',
|
|
headers: { 'content-type': 'image/png' },
|
|
payload: Buffer.from('complete'),
|
|
});
|
|
expect(response.statusCode).toBe(200);
|
|
expect(response.json()).toEqual({ stored: true });
|
|
} finally {
|
|
await server.close();
|
|
}
|
|
});
|
|
});
|