forked from mtusi2026/mtusi2026lab4
lab4: e2e вложений, отказы S3/PG, исправления потока загрузки
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
@@ -10,6 +12,7 @@ import type { ApiErrorBody } from '../src/common/errors/api-error.js';
|
||||
import type { Page } from '../src/common/http/page.js';
|
||||
import type { Message } from '../src/messages/message.js';
|
||||
import type { User } from '../src/users/user.js';
|
||||
import { noisePng } from './support/png.js';
|
||||
|
||||
// Automated counterpart of the manual Redis/PostgreSQL outage checks. Four
|
||||
// topologies, because the load balancer probes /health/ready (the same route as
|
||||
@@ -41,6 +44,8 @@ const composeEnvFile = process.env.E2E_COMPOSE_ENV_FILE ?? '.env';
|
||||
const redisService = process.env.E2E_REDIS_SERVICE ?? 'redis';
|
||||
const postgresService = process.env.E2E_POSTGRES_SERVICE ?? 'postgres';
|
||||
const apiService = process.env.E2E_API_SERVICE ?? 'api';
|
||||
const s3Service = process.env.E2E_S3_SERVICE ?? 's3';
|
||||
const s3Bucket = process.env.E2E_S3_BUCKET ?? 'messenger-attachments';
|
||||
const lbStatsUrl =
|
||||
process.env.E2E_LB_STATS_URL ?? 'http://127.0.0.1:8404/stats;csv';
|
||||
// PostgreSQL superuser of the stand (compose.yaml, .env); psql runs over the
|
||||
@@ -440,6 +445,106 @@ async function restoreDatabaseAccess(): Promise<void> {
|
||||
await psql('select pg_reload_conf()');
|
||||
}
|
||||
|
||||
const samplePng = readFileSync(
|
||||
new URL('../../tests/fixtures/sample.png', import.meta.url),
|
||||
);
|
||||
|
||||
function secretFile(name: string): string {
|
||||
return readFileSync(`${composeDir}/secrets/${name}`, 'utf8').trim();
|
||||
}
|
||||
|
||||
// Root credentials stay inside the local process and the container's exec
|
||||
// environment; they are never printed.
|
||||
async function objectExists(key: string): Promise<boolean> {
|
||||
const host = `http://${secretFile('minio_root_user')}:${secretFile('minio_root_password')}@127.0.0.1:9000`;
|
||||
try {
|
||||
await dockerExecService(
|
||||
s3Service,
|
||||
'env',
|
||||
`MC_HOST_stand=${host}`,
|
||||
'mc',
|
||||
'stat',
|
||||
`stand/${s3Bucket}/${key}`,
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForS3Healthy(): Promise<void> {
|
||||
const container = (await compose('ps', '-q', s3Service)).split('\n')[0];
|
||||
await waitFor(
|
||||
async () =>
|
||||
(await docker(
|
||||
'inspect',
|
||||
'-f',
|
||||
'{{.State.Health.Status}}',
|
||||
container,
|
||||
).catch(() => '')) === 'healthy',
|
||||
async () => 's3 is not healthy',
|
||||
60_000,
|
||||
);
|
||||
}
|
||||
|
||||
function uploadPath(chatId: string, filename: string): string {
|
||||
return `/api/v1/chats/${chatId}/attachments?filename=${encodeURIComponent(filename)}`;
|
||||
}
|
||||
|
||||
async function sweepNow(): Promise<void> {
|
||||
await compose(
|
||||
'exec',
|
||||
'-T',
|
||||
'-e',
|
||||
'ATTACHMENT_SWEEP_GRACE_SECONDS=0',
|
||||
apiService,
|
||||
'node',
|
||||
'dist/attachments/attachments-sweep.cli.js',
|
||||
);
|
||||
}
|
||||
|
||||
async function waitUntilExpired(filter: string): Promise<void> {
|
||||
await waitFor(
|
||||
async () =>
|
||||
Number(
|
||||
await psql(
|
||||
`select count(*) from attachments where ${filter} and expires_at < now()`,
|
||||
),
|
||||
) > 0,
|
||||
async () => 'pending row did not expire',
|
||||
60_000,
|
||||
);
|
||||
}
|
||||
|
||||
async function rawUpload(
|
||||
data: Buffer,
|
||||
chatId: string,
|
||||
filename: string,
|
||||
token: string,
|
||||
splitAt: number,
|
||||
between: () => Promise<void>,
|
||||
): Promise<string> {
|
||||
const url = new URL(baseUrl);
|
||||
const socket = net.connect(Number(url.port || 80), url.hostname);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once('connect', resolve);
|
||||
socket.once('error', reject);
|
||||
});
|
||||
const chunks: Buffer[] = [];
|
||||
socket.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
const closed = new Promise<void>((resolve) => socket.on('close', resolve));
|
||||
socket.write(
|
||||
`POST ${uploadPath(chatId, filename)} HTTP/1.1\r\nHost: ${url.host}\r\n` +
|
||||
`Authorization: Bearer ${token}\r\nContent-Type: image/png\r\n` +
|
||||
`Content-Length: ${data.length}\r\nConnection: close\r\n\r\n`,
|
||||
);
|
||||
socket.write(data.subarray(0, splitAt));
|
||||
await between();
|
||||
socket.write(data.subarray(splitAt));
|
||||
await closed;
|
||||
return Buffer.concat(chunks).toString('latin1');
|
||||
}
|
||||
|
||||
describe.skipIf(!enabled)('dependency outages', () => {
|
||||
let user: User;
|
||||
let token: string;
|
||||
@@ -496,6 +601,7 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
// then the temporary per-replica rule, then rotation.
|
||||
await compose('start', redisService);
|
||||
await compose('start', postgresService);
|
||||
await compose('start', s3Service);
|
||||
await waitForReadiness(200);
|
||||
await restoreDatabaseAccess();
|
||||
const expected = (await apiContainers()).length;
|
||||
@@ -519,7 +625,8 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
let sampling = true;
|
||||
const sampler = (async () => {
|
||||
while (sampling) {
|
||||
for (const slot of await lbSlots()) statuses.add(slot.status);
|
||||
for (const slot of await lbSlots())
|
||||
statuses.add(slot.status);
|
||||
await sleep(200);
|
||||
}
|
||||
})();
|
||||
@@ -796,4 +903,128 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
},
|
||||
outagedRequestBudgetMs,
|
||||
);
|
||||
|
||||
it(
|
||||
'degrades attachments while S3 is down and sweeps the failed upload afterwards',
|
||||
async () => {
|
||||
const upload = (data: Buffer, name: string) =>
|
||||
request<ApiErrorBody & { id: string }>(
|
||||
uploadPath(chat.id, name),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...bearer(token),
|
||||
'content-type': 'image/png',
|
||||
},
|
||||
body: data as unknown as BodyInit,
|
||||
},
|
||||
);
|
||||
const before = await upload(samplePng, `s3before-${runId}.png`);
|
||||
expect(before.response.status).toBe(201);
|
||||
|
||||
await compose('stop', s3Service);
|
||||
try {
|
||||
const failed = await upload(samplePng, `s3down-${runId}.png`);
|
||||
expectBoundedOutage(failed);
|
||||
const metadata = await request(
|
||||
`/api/v1/attachments/${before.body.id}`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
expect(metadata.response.status).toBe(200);
|
||||
const content = await request<ApiErrorBody>(
|
||||
`/api/v1/attachments/${before.body.id}/content`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
expectBoundedOutage(content);
|
||||
const text = await request<Message>(
|
||||
`/api/v1/chats/${chat.id}/messages`,
|
||||
json({ text: 'S3 down' }, messageHeaders(token)),
|
||||
);
|
||||
expect(text.response.status).toBe(201);
|
||||
expect((await request('/health/ready')).response.status).toBe(
|
||||
200,
|
||||
);
|
||||
// Compensation could not reach S3, so the row stays for the sweeper.
|
||||
expect(
|
||||
await psql(
|
||||
`select count(*) from attachments where chat_id = '${chat.id}' and status = 'pending' and filename = 's3down-${runId}.png'`,
|
||||
),
|
||||
).toBe('1');
|
||||
} finally {
|
||||
await compose('start', s3Service);
|
||||
}
|
||||
await waitForS3Healthy();
|
||||
|
||||
const bytes = await fetch(
|
||||
`${baseUrl}/api/v1/attachments/${before.body.id}/content`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
expect(bytes.status).toBe(200);
|
||||
expect(
|
||||
Buffer.from(await bytes.arrayBuffer()).equals(samplePng),
|
||||
).toBe(true);
|
||||
const after = await upload(samplePng, `s3after-${runId}.png`);
|
||||
expect(after.response.status).toBe(201);
|
||||
|
||||
const filter = `chat_id = '${chat.id}' and status = 'pending' and filename = 's3down-${runId}.png'`;
|
||||
await waitUntilExpired(filter);
|
||||
await sweepNow();
|
||||
expect(
|
||||
await psql(`select count(*) from attachments where ${filter}`),
|
||||
).toBe('0');
|
||||
},
|
||||
outagedRequestBudgetMs,
|
||||
);
|
||||
|
||||
it(
|
||||
'compensates the S3 write when PostgreSQL fails before ready',
|
||||
async () => {
|
||||
const data = noisePng(1024 * 1024);
|
||||
const filename = `pgfault-${runId}.png`;
|
||||
const filter = `chat_id = '${chat.id}' and status = 'pending' and filename = '${filename}'`;
|
||||
let restarted = false;
|
||||
let reply = '';
|
||||
try {
|
||||
reply = await rawUpload(
|
||||
data,
|
||||
chat.id,
|
||||
filename,
|
||||
token,
|
||||
64 * 1024,
|
||||
async () => {
|
||||
await waitFor(
|
||||
async () =>
|
||||
Number(
|
||||
await psql(
|
||||
`select count(*) from attachments where ${filter}`,
|
||||
),
|
||||
) === 1,
|
||||
async () => 'pending row did not appear',
|
||||
10_000,
|
||||
);
|
||||
await compose('stop', postgresService);
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
await compose('start', postgresService);
|
||||
restarted = true;
|
||||
}
|
||||
expect(restarted).toBe(true);
|
||||
expect(reply.startsWith('HTTP/1.1 503')).toBe(true);
|
||||
await waitForReadiness(200);
|
||||
|
||||
const key = await psql(
|
||||
`select object_key from attachments where ${filter}`,
|
||||
);
|
||||
expect(key).toMatch(/^attachments\/[0-9a-f-]{36}\/original$/u);
|
||||
expect(await objectExists(key)).toBe(false);
|
||||
|
||||
await waitUntilExpired(filter);
|
||||
await sweepNow();
|
||||
expect(
|
||||
await psql(`select count(*) from attachments where ${filter}`),
|
||||
).toBe('0');
|
||||
},
|
||||
outagedRequestBudgetMs,
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user