lab4: стенд MinIO, секреты, bootstrap, хуки; перенос приложения lab3

This commit is contained in:
2026-10-22 22:24:06 +03:00
parent ec540a1a72
commit 4107ee27a3
92 changed files with 13388 additions and 11 deletions
+674
View File
@@ -0,0 +1,674 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import { Pool } from 'pg';
import { createClient } from 'redis';
import type { SessionResponse } from '../src/auth/auth.service.js';
import type { Chat } from '../src/chats/chat.js';
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';
// The suite is black-box: run it against the compiled application process.
// Vitest sets process.env.BASE_URL itself (Vite base), so the API URL uses its own name.
const baseUrl = (process.env.API_BASE_URL ?? 'http://localhost:8080').replace(
/\/+$/u,
'',
);
const basicChallenge = 'Basic realm="messenger", charset="UTF-8"';
const bearerChallenge = 'Bearer realm="messenger"';
const password = 'integration:пароль🔐';
const runId = randomUUID().replaceAll('-', '').slice(0, 12);
const usernames: string[] = [];
const tokens: string[] = [];
let sequence = 0;
let database: Pool;
let redis: ReturnType<typeof createClient>;
type Actor = { user: User; password: string; token: string };
type HttpResult<T> = { body: T; response: Response };
async function http<T = unknown>(
path: string,
init: RequestInit = {},
): Promise<HttpResult<T>> {
const response = await fetch(`${baseUrl}${path}`, init);
const text = await response.text();
let body: unknown = undefined;
if (text) {
try {
body = JSON.parse(text);
} catch {
body = text;
}
}
return { body: body as T, response };
}
function json(
body: unknown,
headers: Record<string, string> = {},
): RequestInit {
return {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(body),
};
}
function basic(username: string, secret: string): string {
return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`;
}
function bearer(token: string): Record<string, string> {
return { authorization: `Bearer ${token}` };
}
function idempotencyKey(): Record<string, string> {
return { 'idempotency-key': randomUUID().replaceAll('-', '') };
}
function messageHeaders(token: string): Record<string, string> {
return { ...bearer(token), ...idempotencyKey() };
}
async function register(
displayName = 'Интеграционный пользователь',
secret = password,
): Promise<User> {
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
usernames.push(username);
const result = await http<User>(
'/api/v1/users',
json({ username, display_name: displayName, password: secret }),
);
expect(result.response.status).toBe(201);
return result.body;
}
async function login(user: User, secret = password): Promise<SessionResponse> {
const result = await http<SessionResponse>('/api/v1/auth/sessions', {
method: 'POST',
headers: { authorization: basic(user.username, secret) },
});
expect(result.response.status).toBe(201);
tokens.push(result.body.token);
return result.body;
}
async function actor(displayName?: string): Promise<Actor> {
const user = await register(displayName);
const session = await login(user);
return { user, password, token: session.token };
}
function expectError(
result: HttpResult<ApiErrorBody>,
status: number,
code: string,
): void {
expect(result.response.status).toBe(status);
expect(result.body.error.code).toBe(code);
expect(result.body.error.request_id).toBe(
result.response.headers.get('x-request-id'),
);
}
describe('HTTP integration contract', () => {
beforeAll(async () => {
database = new Pool({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: 5000,
});
redis = createClient({
url: process.env.REDIS_URL,
socket: { reconnectStrategy: false },
});
redis.on('error', () => {});
await redis.connect();
});
afterAll(async () => {
if (usernames.length) {
await database.query('BEGIN');
try {
await database.query(
`DELETE FROM messages WHERE sender_id IN (SELECT id FROM users WHERE username = ANY($1::text[]))`,
[usernames],
);
await database.query(
`DELETE FROM chats WHERE id IN (SELECT chat_id FROM chat_members WHERE user_id IN (SELECT id FROM users WHERE username = ANY($1::text[])))`,
[usernames],
);
await database.query(
'DELETE FROM users WHERE username = ANY($1::text[])',
[usernames],
);
await database.query('COMMIT');
} catch (error) {
await database.query('ROLLBACK');
throw error;
}
}
if (redis.isOpen) redis.destroy();
await database.end();
});
it('serves liveness and requires real session authentication', async () => {
const live = await http<{ status: string }>('/health/live');
expect(live.response.status).toBe(200);
expect(live.body).toEqual({ status: 'ok' });
const denied = await http<ApiErrorBody>('/api/v1/users/me');
expectError(denied, 401, 'unauthorized');
expect(denied.response.headers.get('www-authenticate')).toBe(
bearerChallenge,
);
});
it('measures string lengths in Unicode code points', async () => {
const emoji = '🔐';
const username = (suffix: string) =>
`e2e_${runId}_${suffix}`.slice(0, 32);
const rejected = await http<ApiErrorBody>(
'/api/v1/users',
json({
username: username('cp_short'),
display_name: 'Code points',
password: emoji.repeat(11),
}),
);
expectError(rejected, 400, 'invalid_request');
const tooLongPassword = await http<ApiErrorBody>(
'/api/v1/users',
json({
username: username('cp_long'),
display_name: 'Code points',
password: emoji.repeat(129),
}),
);
expectError(tooLongPassword, 400, 'invalid_request');
const tooLongName = await http<ApiErrorBody>(
'/api/v1/users',
json({
username: username('cp_name'),
display_name: emoji.repeat(101),
password,
}),
);
expectError(tooLongName, 400, 'invalid_request');
const shortUsername = username('cp_ok');
usernames.push(shortUsername);
const boundaryPassword = emoji.repeat(12);
const created = await http<User>(
'/api/v1/users',
json({
username: shortUsername,
display_name: emoji.repeat(100),
password: boundaryPassword,
}),
);
expect(created.response.status).toBe(201);
expect([...created.body.display_name].length).toBe(100);
// The stored password keeps all 12 code points: authentication works.
const session = await http<SessionResponse>('/api/v1/auth/sessions', {
method: 'POST',
headers: {
authorization: basic(shortUsername, boundaryPassword),
},
});
expect(session.response.status).toBe(201);
tokens.push(session.body.token);
const longTitleRejected = await http<ApiErrorBody>(
'/api/v1/chats',
json(
{ title: emoji.repeat(101), member_ids: [created.body.id] },
bearer(session.body.token),
),
);
expectError(longTitleRejected, 400, 'invalid_request');
const longTitle = await http<Chat>(
'/api/v1/chats',
json(
{ title: emoji.repeat(100), member_ids: [created.body.id] },
bearer(session.body.token),
),
);
expect(longTitle.response.status).toBe(201);
const tooLongText = await http<ApiErrorBody>(
`/api/v1/chats/${longTitle.body.id}/messages`,
json({ text: emoji.repeat(4001) }, messageHeaders(session.body.token)),
);
expectError(tooLongText, 400, 'invalid_request');
const boundaryText = await http<Message>(
`/api/v1/chats/${longTitle.body.id}/messages`,
json({ text: emoji.repeat(4000) }, messageHeaders(session.body.token)),
);
expect(boundaryText.response.status).toBe(201);
expect([...boundaryText.body.text].length).toBe(4000);
});
it('rejects whitespace-only and too-short credentials', async () => {
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
usernames.push(username);
const cases = [
{ password: ' '.repeat(12), display_name: 'Пользователь' },
{ password: '\t'.repeat(16), display_name: 'Пользователь' },
{ password: 'short-pass', display_name: 'Пользователь' },
{ password, display_name: ' ' },
];
for (const body of cases) {
const result = await http<ApiErrorBody>(
'/api/v1/users',
json({ username, ...body }),
);
expectError(result, 400, 'invalid_request');
}
const accepted = await http<User>(
'/api/v1/users',
json({ username, display_name: 'Пользователь', password }),
);
expect(accepted.response.status).toBe(201);
});
it('registers, logs in with Unicode/colon password, and challenges malformed Basic', async () => {
const user = await register();
const session = await login(user);
expect(session.user.id).toBe(user.id);
expect(session.token_type).toBe('Bearer');
const me = await http<User>('/api/v1/users/me', {
headers: bearer(session.token),
});
expect(me.response.status).toBe(200);
expect(me.body.id).toBe(user.id);
for (const authorization of [
'Basic !!!',
'Basic YWJj',
'Bearer nope',
]) {
const result = await http<ApiErrorBody>('/api/v1/auth/sessions', {
method: 'POST',
headers: { authorization },
});
expectError(result, 401, 'unauthorized');
expect(result.response.headers.get('www-authenticate')).toBe(
basicChallenge,
);
}
const bodyResult = await http<ApiErrorBody>('/api/v1/auth/sessions', {
...json({ unexpected: true }),
headers: { authorization: basic(user.username, password) },
});
expectError(bodyResult, 400, 'invalid_request');
});
it('returns conflict for concurrent duplicate registration', async () => {
const username = `e2e_${runId}_race`.slice(0, 32);
usernames.push(username);
const results = await Promise.all([
http<User>(
'/api/v1/users',
json({ username, display_name: 'Race A', password }),
),
http<User>(
'/api/v1/users',
json({ username, display_name: 'Race B', password }),
),
]);
expect(
results.filter((item) => item.response.status === 201),
'duplicate registration must create exactly one user',
).toHaveLength(1);
expect(
results.filter((item) => item.response.status === 409),
'loser of the race must receive 409, not 500',
).toHaveLength(1);
// The database unique index is the race-proof guard, so verify its effect.
const persisted = await database.query<{ count: string }>(
'SELECT count(*)::text AS count FROM users WHERE username = $1',
[username],
);
expect(persisted.rows[0]?.count).toBe('1');
});
it('uses Bearer only, ignores X-User-Id spoofing, and prevents logout replay', async () => {
const alice = await actor('Алиса');
const bob = await actor('Боб');
const spoof = await http<ApiErrorBody>('/api/v1/users/me', {
headers: { ...bearer(alice.token), 'x-user-id': bob.user.id },
});
expect(spoof.response.status).toBe(200);
expect((spoof.body as unknown as User).id).toBe(alice.user.id);
const basicBusiness = await http<ApiErrorBody>('/api/v1/users/me', {
headers: { authorization: basic(alice.user.username, password) },
});
expectError(basicBusiness, 401, 'unauthorized');
expect(basicBusiness.response.headers.get('www-authenticate')).toBe(
bearerChallenge,
);
const logout = await http('/api/v1/auth/sessions/current', {
method: 'DELETE',
headers: bearer(alice.token),
});
expect(logout.response.status).toBe(204);
const replay = await http<ApiErrorBody>('/api/v1/users/me', {
headers: bearer(alice.token),
});
expectError(replay, 401, 'unauthorized');
});
it('rejects unknown and duplicate chat members and hides chats from outsiders', async () => {
const alice = await actor();
const bob = await actor();
const outsider = await actor();
const unknown = await http<ApiErrorBody>(
'/api/v1/chats',
json(
{ title: 'unknown', member_ids: [alice.user.id, randomUUID()] },
bearer(alice.token),
),
);
expectError(unknown, 400, 'invalid_request');
const leaked = await http<ApiErrorBody>(`/api/v1/chats?limit=100`, {
headers: bearer(alice.token),
});
expect(leaked.response.status).toBe(200);
expect(
(leaked.body as unknown as Page<Chat>).items.some(
(item) => item.title === 'unknown',
),
).toBe(false);
const duplicate = await http<ApiErrorBody>(
'/api/v1/chats',
json(
{
title: 'duplicate',
member_ids: [alice.user.id, alice.user.id],
},
bearer(alice.token),
),
);
expectError(duplicate, 400, 'invalid_request');
const created = await http<Chat>(
'/api/v1/chats',
json(
{
title: `chat-${runId}`,
member_ids: [alice.user.id, bob.user.id],
},
bearer(alice.token),
),
);
expect(created.response.status).toBe(201);
const hidden = await http<ApiErrorBody>(
`/api/v1/chats/${created.body.id}`,
{ headers: bearer(outsider.token) },
);
expectError(hidden, 404, 'not_found');
});
it('keeps sender server-owned and makes writes visible to a second session', async () => {
const alice = await actor();
const secondSession = (await login(alice.user)).token;
const chat = await http<Chat>(
'/api/v1/chats',
json(
{ title: `messages-${runId}`, member_ids: [alice.user.id] },
bearer(alice.token),
),
);
expect(chat.response.status).toBe(201);
const blank = await http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages`,
json(
{ text: ' \n\t', sender_id: randomUUID() },
messageHeaders(alice.token),
),
);
expectError(blank, 400, 'invalid_request');
const spoof = await http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages`,
json(
{ text: 'hello', sender_id: randomUUID() },
messageHeaders(alice.token),
),
);
expectError(spoof, 400, 'invalid_request');
await http(`/api/v1/chats/${chat.body.id}/messages?limit=50`, {
headers: bearer(secondSession),
});
const sent = await http<Message>(
`/api/v1/chats/${chat.body.id}/messages`,
json({ text: 'hello' }, messageHeaders(alice.token)),
);
expect(sent.response.status).toBe(201);
expect(sent.body.sender_id).toBe(alice.user.id);
const page = await http<Page<Message>>(
`/api/v1/chats/${chat.body.id}/messages?limit=50`,
{ headers: bearer(secondSession) },
);
expect(page.response.status).toBe(200);
expect(page.body.items.map((item) => item.id)).toContain(sent.body.id);
});
it('validates cursor, limits, malformed JSON, and paginates without repeats', async () => {
const alice = await actor();
const chat = await http<Chat>(
'/api/v1/chats',
json(
{ title: `pages-${runId}`, member_ids: [alice.user.id] },
bearer(alice.token),
),
);
for (const text of ['one', 'two', 'three']) {
const sent = await http(
`/api/v1/chats/${chat.body.id}/messages`,
json({ text }, messageHeaders(alice.token)),
);
expect(sent.response.status).toBe(201);
}
const invalidLimit = await http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages?limit=101`,
{ headers: bearer(alice.token) },
);
expectError(invalidLimit, 400, 'invalid_request');
const invalidCursor = await http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages?cursor=not-a-cursor`,
{ headers: bearer(alice.token) },
);
expectError(invalidCursor, 400, 'invalid_request');
const rolledOver = http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages?cursor=${encodeURIComponent(
Buffer.from(
JSON.stringify({
scope: `messages:${chat.body.id}`,
created_at: '2026-02-31T00:00:00.000Z',
id: randomUUID(),
}),
'utf8',
).toString('base64url'),
)}`,
{ headers: bearer(alice.token) },
);
expectError(await rolledOver, 400, 'invalid_request');
const malformed = await http<ApiErrorBody>('/api/v1/users', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{',
});
expectError(malformed, 400, 'invalid_request');
const first = await http<Page<Message>>(
`/api/v1/chats/${chat.body.id}/messages?limit=2`,
{ headers: bearer(alice.token) },
);
expect(first.body.items).toHaveLength(2);
const second = await http<Page<Message>>(
`/api/v1/chats/${chat.body.id}/messages?limit=2&cursor=${encodeURIComponent(first.body.next_cursor!)}`,
{ headers: bearer(alice.token) },
);
expect(second.body.items).toHaveLength(1);
expect(
new Set(
[...first.body.items, ...second.body.items].map(
(item) => item.id,
),
).size,
).toBe(3);
});
it.skipIf(process.env.SESSION_TTL_SECONDS !== '2')(
'expires sessions with TTL=2',
async () => {
const user = await register();
const session = await login(user);
await sleep(2300);
const expired = await http<ApiErrorBody>('/api/v1/users/me', {
headers: bearer(session.token),
});
expectError(expired, 401, 'unauthorized');
},
);
});
// lab3: the Idempotency-Key contract of POST /chats/{id}/messages. The suite is
// black-box, so these assertions hold for one replica and for a load-balanced
// fleet alike.
describe('message idempotency', () => {
async function chatFor(token: string, memberIds: string[]): Promise<string> {
const created = await http<Chat>(
'/api/v1/chats',
json({ title: `idempotency-${runId}`, member_ids: memberIds }, bearer(token)),
);
expect(created.response.status).toBe(201);
return created.body.id;
}
async function textsIn(chatId: string, token: string): Promise<string[]> {
const page = await http<Page<Message>>(
`/api/v1/chats/${chatId}/messages?limit=100`,
{ headers: bearer(token) },
);
expect(page.response.status).toBe(200);
return page.body.items.map((item) => item.text);
}
it('requires a well-formed Idempotency-Key', async () => {
const alice = await actor();
const chatId = await chatFor(alice.token, [alice.user.id]);
const path = `/api/v1/chats/${chatId}/messages`;
const missing = await http<ApiErrorBody>(
path,
json({ text: 'без ключа' }, bearer(alice.token)),
);
expectError(missing, 400, 'invalid_request');
for (const key of ['has space', 'comma,separated', 'x'.repeat(129)]) {
const malformed = await http<ApiErrorBody>(
path,
json({ text: 'плохой ключ' }, { ...bearer(alice.token), 'idempotency-key': key }),
);
expectError(malformed, 400, 'invalid_request');
}
});
it('replays the stored response and conflicts on a different body', async () => {
const alice = await actor();
const chatId = await chatFor(alice.token, [alice.user.id]);
const path = `/api/v1/chats/${chatId}/messages`;
const key = randomUUID().replaceAll('-', '');
const headers = { ...bearer(alice.token), 'idempotency-key': key };
const text = `повтор ${runId}`;
const first = await http<Message>(path, json({ text }, headers));
expect(first.response.status).toBe(201);
const replayed = await http<Message>(path, json({ text }, headers));
expect(replayed.response.status).toBe(201);
expect(replayed.body).toEqual(first.body);
const conflict = await http<ApiErrorBody>(
path,
json({ text: 'другой body' }, headers),
);
expectError(conflict, 409, 'conflict');
expect(await textsIn(chatId, alice.token)).toEqual([text]);
});
it('creates exactly one message for concurrent requests with one key', async () => {
const alice = await actor();
const chatId = await chatFor(alice.token, [alice.user.id]);
const path = `/api/v1/chats/${chatId}/messages`;
const headers = { ...bearer(alice.token), ...idempotencyKey() };
const text = `конкурентный повтор ${runId}`;
const results = await Promise.all(
Array.from({ length: 8 }, () => http<Message>(path, json({ text }, headers))),
);
for (const result of results) expect(result.response.status).toBe(201);
const ids = new Set(results.map((result) => result.body.id));
expect(
ids.size,
'one key must resolve to exactly one message across replicas',
).toBe(1);
expect(await textsIn(chatId, alice.token)).toEqual([text]);
});
it('replays a key created by another replica', async () => {
// lab3: повтор с тем же ключом может прийти на любую реплику, поэтому
// проверяем не только сам повтор, но и то, что его обслужила другая реплика
// (иначе тест не отличал бы общий журнал от локального состояния процесса).
const alice = await actor();
const chatId = await chatFor(alice.token, [alice.user.id]);
const path = `/api/v1/chats/${chatId}/messages`;
const key = randomUUID().replaceAll('-', '');
const headers = { ...bearer(alice.token), 'idempotency-key': key };
const first = await http<Message>(path, json({ text: 'переключение реплики' }, headers));
expect(first.response.status).toBe(201);
const firstInstance = first.response.headers.get('x-instance-id');
expect(firstInstance).toBeTruthy();
let replay = first;
let replayInstance = firstInstance;
for (let attempt = 0; attempt < 12 && replayInstance === firstInstance; attempt += 1) {
replay = await http<Message>(path, json({ text: 'переключение реплики' }, headers));
expect(replay.response.status).toBe(201);
replayInstance = replay.response.headers.get('x-instance-id');
}
expect(
replayInstance,
'повтор должен был прийти на другую реплику (round-robin за LB)',
).not.toBe(firstInstance);
expect(replay.body).toEqual(first.body);
expect(await textsIn(chatId, alice.token)).toEqual(['переключение реплики']);
});
it('scopes the key per user and per chat path', async () => {
const alice = await actor();
const bob = await actor();
const outsider = await actor();
const chatId = await chatFor(alice.token, [alice.user.id, bob.user.id]);
const path = `/api/v1/chats/${chatId}/messages`;
const key = randomUUID().replaceAll('-', '');
const foreignChatId = await chatFor(outsider.token, [outsider.user.id]);
const denied = await http<ApiErrorBody>(
`/api/v1/chats/${foreignChatId}/messages`,
json({ text: 'чужое' }, { ...bearer(alice.token), 'idempotency-key': key }),
);
expectError(denied, 404, 'not_found');
const mine = await http<Message>(
path,
json({ text: 'своё' }, { ...bearer(alice.token), 'idempotency-key': key }),
);
expect(mine.response.status).toBe(201);
const other = await http<Message>(
path,
json({ text: 'своё' }, { ...bearer(bob.token), 'idempotency-key': key }),
);
expect(other.response.status).toBe(201);
expect(other.body.id).not.toBe(mine.body.id);
});
});
+799
View File
@@ -0,0 +1,799 @@
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import type { SessionResponse } from '../src/auth/auth.service.js';
import type { Chat } from '../src/chats/chat.js';
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';
// Automated counterpart of the manual Redis/PostgreSQL outage checks. Four
// topologies, because the load balancer probes /health/ready (the same route as
// the container healthcheck):
// 1. Redis outage — shared dependency: every replica turns not-ready, HAProxy
// removes all backends and answers 503 itself, while the replica's own
// readiness stays a bounded API 503 with request_id.
// 2. PostgreSQL outage — same shared-dependency topology, confirmed data and
// the session survive the restart.
// 3. Per-replica PostgreSQL fault — only the selected replica loses its own
// path to the database (temporary pg_hba reject entry for its address plus
// connection termination): that slot leaves rotation, the healthy replica
// keeps serving, and the fault is always undone.
// 4. Pool saturation — a busy shared pool is overload, not a lost dependency:
// the replicas stay in rotation because the probe uses its own connection.
//
// It is opt-in because it needs control over the Docker Compose project:
// make test-dependencies
// cd app && E2E_DEPENDENCY_FAULTS=1 npm run test:dependencies
const enabled = process.env.E2E_DEPENDENCY_FAULTS === '1';
const baseUrl = (process.env.API_BASE_URL ?? 'http://localhost:8080').replace(
/\/+$/u,
'',
);
const composeDir =
process.env.E2E_COMPOSE_DIR ??
fileURLToPath(new URL('../..', import.meta.url));
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 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
// container's local socket, so no password is needed here.
const postgresUser = process.env.E2E_POSTGRES_USER ?? 'messenger';
const postgresDatabase = process.env.E2E_POSTGRES_DB ?? 'messenger';
const pgHbaPath =
process.env.E2E_PG_HBA_PATH ?? '/var/lib/postgresql/data/pg_hba.conf';
const pgHbaBackup = `${pgHbaPath}.lab3-partial-fault.bak`;
const password = 'outage-check:пароль🔐';
const runId = randomUUID().replaceAll('-', '').slice(0, 12);
// A request that reaches a stopped database waits for the pool connection
// timeout, so every outage step costs up to DATABASE_CONNECTION_TIMEOUT_MS.
const outagedRequestBudgetMs = 180_000;
const slotBudgetMs = 20_000;
const readyReads = 16;
const saturatingWrites = 60; // больше, чем replicas × DATABASE_POOL_MAX (2 × 10)
const execFileAsync = promisify(execFile);
type Result<T> = { body: T; text: string; response: Response };
type ReplicaProbe = {
instanceId: string | null;
requestId: string | null;
status: number;
text: string;
};
type LbSlot = { addr: string; check: string; name: string; status: string };
async function compose(...args: string[]): Promise<string> {
const result = await execFileAsync(
'docker',
['compose', '--env-file', composeEnvFile, ...args],
{ cwd: composeDir, timeout: 120_000 },
);
return result.stdout.trim();
}
async function docker(...args: string[]): Promise<string> {
const result = await execFileAsync('docker', args, {
cwd: composeDir,
timeout: 60_000,
});
return result.stdout.trim();
}
async function request<T = unknown>(
path: string,
init: RequestInit = {},
): Promise<Result<T>> {
const response = await fetch(`${baseUrl}${path}`, init);
const text = await response.text();
// With every backend out of rotation the answer is the LB's own HTML 503,
// so a body is not guaranteed to be JSON (it always is for API answers).
let body: T | undefined;
try {
body = text ? (JSON.parse(text) as T) : undefined;
} catch {
body = undefined;
}
return { body: body as T, text, response };
}
function json(
body: unknown,
headers: Record<string, string> = {},
): RequestInit {
return {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(body),
};
}
function bearer(token: string): Record<string, string> {
return { authorization: `Bearer ${token}` };
}
// POST messages needs a unique Idempotency-Key in lab3+; outage checks only
// need the write path, not replay semantics.
function messageHeaders(token: string): Record<string, string> {
return {
...bearer(token),
'idempotency-key': randomUUID().replaceAll('-', ''),
};
}
function basic(username: string, secret: string): string {
return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`;
}
// The dependencies recover asynchronously, so readiness is polled instead of
// asserted right after docker compose returns.
async function waitForReadiness(
expected: number,
timeoutMs = 90_000,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
let last: number | string = 'no response';
for (;;) {
try {
const probe = await request('/health/ready');
last = probe.response.status;
if (probe.response.status === expected) return;
} catch (error) {
last = error instanceof Error ? error.message : 'request failed';
}
if (Date.now() > deadline)
throw new Error(
`readiness never became ${expected} within ${timeoutMs}ms (last: ${String(last)})`,
);
await sleep(250);
}
}
async function waitFor(
condition: () => Promise<boolean>,
describe: () => Promise<string>,
timeoutMs: number,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (await condition()) return;
if (Date.now() > deadline)
throw new Error(
`condition not reached within ${timeoutMs}ms: ${await describe()}`,
);
await sleep(250);
}
}
function expectBoundedError(
status: number,
text: string,
requestId: string | null,
): void {
expect(status).toBe(503);
const body = JSON.parse(text) as ApiErrorBody;
expect(body.error.code).toBe('unavailable');
expect(body.error.message).toBe('Service unavailable');
expect(body.error.request_id).toBe(requestId);
// A bounded error must not leak driver details, SQL text or a stack trace.
expect(text).not.toMatch(
/ECONNREFUSED|ECONNRESET|Connection terminated|pg\.|node_modules|at .*\(.+:\d+:\d+\)/u,
);
}
function expectBoundedOutage(result: Result<ApiErrorBody>): void {
expectBoundedError(
result.response.status,
result.text,
result.response.headers.get('x-request-id'),
);
}
// With every backend out of rotation the last hop is the load balancer itself:
// it answers with its own 503 page, so there is no API error body and no
// X-Instance-Id — the request never reached a replica.
function expectLbOutage(result: Result<unknown>): void {
expect(result.response.status).toBe(503);
expect(result.response.headers.get('x-instance-id')).toBeNull();
}
// What a client sees while a shared dependency is down: either the bounded 503
// of a replica that is still in rotation (identified by X-Instance-Id), or the
// LB's own 503 once every replica has left rotation. Never a success.
function expectUnavailableThroughLb(result: Result<ApiErrorBody>): void {
expect(result.response.status).toBe(503);
if (result.response.headers.get('x-instance-id') === null) return;
expectBoundedOutage(result);
}
async function historyOf(
chatId: string,
token: string,
): Promise<Result<Page<Message>>> {
return request<Page<Message>>(
`/api/v1/chats/${chatId}/messages?limit=100`,
{
headers: bearer(token),
},
);
}
async function apiContainers(): Promise<string[]> {
const stdout = await compose('ps', '-q', apiService);
return stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0)
.sort();
}
async function containerIp(container: string): Promise<string> {
return docker(
'inspect',
'-f',
'{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}',
container,
);
}
// The replicas publish no ports, so a single replica is probed from inside its
// own network namespace (loopback).
const probeScript = `
const params = JSON.parse(process.env.LAB3_PROBE);
const port = process.env.APP_PORT || 8080;
const response = await fetch('http://127.0.0.1:' + port + params.path, {
method: params.method || 'GET',
headers: params.headers || {},
body: params.body,
});
const text = await response.text();
console.log(JSON.stringify({
status: response.status,
text,
instanceId: response.headers.get('x-instance-id'),
requestId: response.headers.get('x-request-id'),
}));
`;
type ProbeInit = {
body?: string;
headers?: Record<string, string>;
method?: string;
};
async function probeReplica(
container: string,
path: string,
init: ProbeInit = {},
): Promise<ReplicaProbe> {
const stdout = await docker(
'exec',
'-e',
`LAB3_PROBE=${JSON.stringify({ path, ...init })}`,
container,
'node',
'--input-type=module',
'-e',
probeScript,
);
return JSON.parse(stdout) as ReplicaProbe;
}
async function waitForReplicaReadiness(
container: string,
expected: number,
timeoutMs: number,
): Promise<void> {
let last = 'no probe';
await waitFor(
async () => {
try {
const probe = await probeReplica(container, '/health/ready');
last = `${probe.status} ${probe.text}`;
return probe.status === expected;
} catch (error) {
last = error instanceof Error ? error.message : 'probe failed';
return false;
}
},
async () => last,
timeoutMs,
);
}
function parseCsvLine(line: string): string[] {
const values: string[] = [];
let current = '';
let quoted = false;
for (const character of line) {
if (character === '"') quoted = !quoted;
else if (character === ',' && !quoted) {
values.push(current);
current = '';
} else current += character;
}
values.push(current.replace(/\r$/u, ''));
return values;
}
// Resolved backend slots of the api backend: the unused slots of the
// server-template have no address and are ignored.
async function lbSlots(): Promise<LbSlot[]> {
const response = await fetch(lbStatsUrl);
const lines = (await response.text()).trim().split('\n');
const header = parseCsvLine(lines[0].replace(/^#\s*/u, '')).map((name) =>
name.trim(),
);
const column = (name: string): number => header.indexOf(name);
return lines
.slice(1)
.map(parseCsvLine)
.filter(
(columns) =>
columns[column('pxname')] === 'api' &&
/^api\d+$/u.test(columns[column('svname')] ?? '') &&
(columns[column('addr')] ?? '').length > 0,
)
.map((columns) => ({
addr: columns[column('addr')],
check: columns[column('check_status')],
name: columns[column('svname')],
status: columns[column('status')],
}));
}
async function waitForSlot(
predicate: (slots: LbSlot[]) => boolean,
describe: string,
timeoutMs = slotBudgetMs,
): Promise<LbSlot[]> {
let last = 'no stats';
await waitFor(
async () => {
try {
const slots = await lbSlots();
last = slots
.map(
(slot) =>
`${slot.name}@${slot.addr} ${slot.status}/${slot.check}`,
)
.join(', ');
return slots.length > 0 && predicate(slots);
} catch (error) {
last = error instanceof Error ? error.message : 'stats failed';
return false;
}
},
async () => `${describe} (last: ${last})`,
timeoutMs,
);
return lbSlots();
}
function upSlots(slots: LbSlot[]): LbSlot[] {
return slots.filter((slot) => slot.status === 'UP');
}
async function psql(query: string): Promise<string> {
return dockerExecService(
postgresService,
'psql',
'-U',
postgresUser,
'-d',
postgresDatabase,
'-tA',
'-c',
query,
);
}
// docker exec needs a container, while the suite is configured with Compose
// service names, so the container of the service is resolved first.
async function dockerExecService(
service: string,
...args: string[]
): Promise<string> {
const container = (await compose('ps', '-q', service))
.split('\n')[0]
?.trim();
if (!container) throw new Error(`no container for service ${service}`);
return docker('exec', container, ...args);
}
// Takes away the replica's own path to PostgreSQL without touching the shared
// database: a reject entry for the replica's address becomes the first matching
// line of pg_hba.conf, so its new connections fail while the server stays up
// for everyone else. The file is rewritten through the existing inode (`cat >
// file`) to preserve the owner and mode the server needs to reload it.
async function applyReplicaDatabaseReject(address: string): Promise<void> {
const script = [
`test -f ${pgHbaBackup} || cat ${pgHbaPath} > ${pgHbaBackup}`,
`printf 'host all all ${address}/32 reject\\n' > /tmp/lab3-pg-hba`,
`cat ${pgHbaPath} >> /tmp/lab3-pg-hba`,
`cat /tmp/lab3-pg-hba > ${pgHbaPath}`,
'rm -f /tmp/lab3-pg-hba',
].join('; ');
await dockerExecService(postgresService, 'sh', '-c', script);
await psql('select pg_reload_conf()');
await psql(
`select count(pg_terminate_backend(pid)) from pg_stat_activity where client_addr = '${address}'`,
);
}
// Idempotent restore: also runs from afterAll, so an assertion that failed
// mid-fault cannot leave the stand rejecting one replica.
async function restoreDatabaseAccess(): Promise<void> {
await dockerExecService(
postgresService,
'sh',
'-c',
`if [ -f ${pgHbaBackup} ]; then cat ${pgHbaBackup} > ${pgHbaPath}; rm -f ${pgHbaBackup}; fi`,
);
await psql('select pg_reload_conf()');
}
describe.skipIf(!enabled)('dependency outages', () => {
let user: User;
let token: string;
let chat: Chat;
let message: Message;
let replicas: string[];
beforeAll(async () => {
await compose('up', '-d');
await waitForReadiness(200);
const username = `outage_${runId}`;
const registered = await request<User>(
'/api/v1/users',
json({ username, display_name: 'Отказ зависимости', password }),
);
expect(registered.response.status).toBe(201);
user = registered.body;
const session = await request<SessionResponse>(
'/api/v1/auth/sessions',
{
method: 'POST',
headers: { authorization: basic(username, password) },
},
);
expect(session.response.status).toBe(201);
token = session.body.token;
const created = await request<Chat>(
'/api/v1/chats',
json(
{ title: `outage-${runId}`, member_ids: [user.id] },
bearer(token),
),
);
expect(created.response.status).toBe(201);
chat = created.body;
const sent = await request<Message>(
`/api/v1/chats/${chat.id}/messages`,
json({ text: 'Сообщение до отказа' }, messageHeaders(token)),
);
expect(sent.response.status).toBe(201);
message = sent.body;
replicas = await apiContainers();
expect(replicas.length).toBeGreaterThanOrEqual(2);
await waitForSlot(
(slots) => upSlots(slots).length === replicas.length,
'not every replica is UP',
30_000,
);
}, outagedRequestBudgetMs);
afterAll(async () => {
// Always restore the stand, even when an assertion failed mid-outage:
// first the services (pg_hba is only reachable in a running container),
// then the temporary per-replica rule, then rotation.
await compose('start', redisService);
await compose('start', postgresService);
await waitForReadiness(200);
await restoreDatabaseAccess();
const expected = (await apiContainers()).length;
await waitForSlot(
(slots) => upSlots(slots).length === expected,
'backends did not return to rotation',
30_000,
);
}, outagedRequestBudgetMs);
it(
'keeps every replica in rotation while the database pool is saturated',
async () => {
// A row lock on the chat parks every write in the shared pool; the
// readiness probe uses its own connection and must keep answering.
const lock = psql(
`begin; select id from chats where id = '${chat.id}' for update; select pg_sleep(4); commit;`,
);
await sleep(300);
const statuses = new Set<string>();
let sampling = true;
const sampler = (async () => {
while (sampling) {
for (const slot of await lbSlots()) statuses.add(slot.status);
await sleep(200);
}
})();
const writes = await Promise.all(
Array.from({ length: saturatingWrites }, () =>
request(
`/api/v1/chats/${chat.id}/messages`,
json({ text: 'saturation' }, messageHeaders(token)),
),
),
);
await lock;
await sleep(1000);
sampling = false;
await sampler;
expect([...statuses]).toEqual(['UP']);
expect(
writes
.map((write) => write.response.status)
.filter((status) => status !== 201),
).toEqual([]);
},
outagedRequestBudgetMs,
);
it(
'serves bounded 503 for the Redis outage and recovers the session',
async () => {
await compose('stop', redisService);
const replica = replicas[0];
expect((await probeReplica(replica, '/health/live')).status).toBe(
200,
);
await waitForReplicaReadiness(replica, 503, 30_000);
const readiness = await probeReplica(replica, '/health/ready');
expectBoundedError(
readiness.status,
readiness.text,
readiness.requestId,
);
const me = await probeReplica(replica, '/api/v1/users/me', {
headers: bearer(token),
});
expectBoundedError(me.status, me.text, me.requestId);
// A request without a session must stay unauthorized during an outage:
// the outage may not turn an anonymous caller into a trusted one.
const anonymous = await probeReplica(replica, '/api/v1/chats', {
headers: { 'x-user-id': user.id },
});
expect(anonymous.status).toBe(401);
expect(
(JSON.parse(anonymous.text) as ApiErrorBody).error.code,
).toBe('unauthorized');
expectUnavailableThroughLb(
await request<ApiErrorBody>('/api/v1/users/me', {
headers: bearer(token),
}),
);
await waitForSlot(
// 'UP 1/2' is still in rotation: wait for DOWN itself.
(slots) => slots.every((slot) => slot.status === 'DOWN'),
'not every slot left rotation',
);
expectLbOutage(
await request('/api/v1/users/me', { headers: bearer(token) }),
);
await compose('start', redisService);
await waitForReadiness(200);
await waitForSlot(
(slots) => upSlots(slots).length === replicas.length,
'backends did not return to rotation',
30_000,
);
// Sessions live in Redis with persistence, so the old token still works.
const recovered = await request<User>('/api/v1/users/me', {
headers: bearer(token),
});
expect(recovered.response.status).toBe(200);
expect(recovered.body.id).toBe(user.id);
const history = await historyOf(chat.id, token);
expect(history.response.status).toBe(200);
expect(history.body.items.map((item) => item.id)).toContain(
message.id,
);
},
outagedRequestBudgetMs,
);
it(
'serves bounded 503 for the PostgreSQL outage and keeps confirmed data',
async () => {
await compose('stop', postgresService);
const replica = replicas[0];
expect((await probeReplica(replica, '/health/live')).status).toBe(
200,
);
await waitForReplicaReadiness(replica, 503, 30_000);
const readiness = await probeReplica(replica, '/health/ready');
expectBoundedError(
readiness.status,
readiness.text,
readiness.requestId,
);
// Redis still answers, so these requests reach the database layer and
// must fail with the bounded 503, not an unhandled 500.
const me = await probeReplica(replica, '/api/v1/users/me', {
headers: bearer(token),
});
expectBoundedError(me.status, me.text, me.requestId);
const chats = await probeReplica(replica, '/api/v1/chats', {
headers: bearer(token),
});
expectBoundedError(chats.status, chats.text, chats.requestId);
const history = await probeReplica(
replica,
`/api/v1/chats/${chat.id}/messages?limit=100`,
{ headers: bearer(token) },
);
expectBoundedError(history.status, history.text, history.requestId);
const registration = await probeReplica(replica, '/api/v1/users', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
username: `outage_${runId}_late`,
display_name: 'Отказ зависимости',
password,
}),
});
expectBoundedError(
registration.status,
registration.text,
registration.requestId,
);
expectUnavailableThroughLb(
await request<ApiErrorBody>('/api/v1/users/me', {
headers: bearer(token),
}),
);
await waitForSlot(
// 'UP 1/2' is still in rotation: wait for DOWN itself.
(slots) => slots.every((slot) => slot.status === 'DOWN'),
'not every slot left rotation',
);
expectLbOutage(
await request('/api/v1/users/me', { headers: bearer(token) }),
);
await compose('start', postgresService);
await waitForReadiness(200);
await waitForSlot(
(slots) => upSlots(slots).length === replicas.length,
'backends did not return to rotation',
30_000,
);
const recovered = await request<User>('/api/v1/users/me', {
headers: bearer(token),
});
expect(recovered.response.status).toBe(200);
expect(recovered.body.id).toBe(user.id);
const after = await historyOf(chat.id, token);
expect(after.response.status).toBe(200);
expect(after.body.items.map((item) => item.id)).toContain(
message.id,
);
const sent = await request<Message>(
`/api/v1/chats/${chat.id}/messages`,
json({ text: 'Сообщение после отказа' }, messageHeaders(token)),
);
expect(sent.response.status).toBe(201);
},
outagedRequestBudgetMs,
);
it(
'excludes only the replica that lost its own database path',
async () => {
const selected = replicas[0];
const healthy = replicas[1];
const selectedIp = await containerIp(selected);
const selectedAddress = `${selectedIp}:8080`;
const selectedInstance = (
await probeReplica(selected, '/health/live')
).instanceId;
expect(selectedInstance).not.toBeNull();
const healthyInstance = (
await probeReplica(healthy, '/health/live')
).instanceId;
try {
await applyReplicaDatabaseReject(selectedIp);
const faultAt = Date.now();
await waitForReplicaReadiness(selected, 503, 30_000);
expect(
(await probeReplica(healthy, '/health/ready')).status,
).toBe(200);
// Only the affected slot leaves rotation. While `fall 2` counts the
// failed checks the slot passes through "UP 1/2 (L7STS)", so the
// wait is for DOWN itself, not for "no longer plain UP".
const slots = await waitForSlot(
(candidates) =>
upSlots(candidates).length === replicas.length - 1 &&
candidates.some(
(slot) =>
slot.addr === selectedAddress &&
slot.status === 'DOWN',
),
`selected slot ${selectedAddress} did not go down`,
30_000,
);
// inter 500 ms × fall 2 + timeout check 500 ms + polling step 250 ms.
expect(Date.now() - faultAt).toBeLessThan(3_000);
expect(
slots.find((slot) => slot.addr === selectedAddress)?.status,
).toBe('DOWN');
const served = new Set<string>();
for (let index = 0; index < readyReads; index += 1) {
const read = await historyOf(chat.id, token);
expect(read.response.status).toBe(200);
served.add(
read.response.headers.get('x-instance-id') ?? 'unknown',
);
}
expect(served.has(selectedInstance as string)).toBe(false);
expect(served.has(healthyInstance as string)).toBe(true);
} finally {
await restoreDatabaseAccess();
}
await waitForReplicaReadiness(selected, 200, 30_000);
await waitForSlot(
(slots) =>
upSlots(slots).length === replicas.length &&
slots.some(
(slot) =>
slot.addr === selectedAddress &&
slot.status === 'UP',
),
'restored replica did not return to rotation',
30_000,
);
let servedAgain = false;
for (
let index = 0;
index < readyReads * 2 && !servedAgain;
index += 1
) {
const read = await historyOf(chat.id, token);
expect(read.response.status).toBe(200);
servedAgain =
read.response.headers.get('x-instance-id') ===
selectedInstance;
}
expect(servedAgain).toBe(true);
},
outagedRequestBudgetMs,
);
});