ЛР 3 — БПИ2304 — Кирюпина — на 3

This commit is contained in:
SashaKirupina
2026-11-12 18:27:32 +03:00
parent 0ab3a341aa
commit 4b8abdf073
36 changed files with 1782 additions and 28 deletions
+110
View File
@@ -0,0 +1,110 @@
'use strict';
const assert = require('node:assert/strict');
const { randomUUID } = require('node:crypto');
const { execFileSync } = require('node:child_process');
const base = process.env.BASE_URL || 'http://localhost:8080';
async function call(method, path, expected = 200, actor, body, headers = {}) {
const response = await fetch(base + path, { method, headers: {
...(actor ? { Authorization: 'Bearer ' + actor.token } : {}),
...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...headers },
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(5000) });
assert.equal(response.status, expected, `${method} ${path}: unexpected status`);
assert.ok(response.headers.get('x-request-id'));
assert.ok(response.headers.get('x-instance-id'));
const data = response.status === 204 ? null : await response.json();
if (expected >= 400) assert.equal(data.error.request_id, response.headers.get('x-request-id'));
return { data, instance: response.headers.get('x-instance-id') };
}
async function user() {
const username = 'u_' + randomUUID().replaceAll('-', '').slice(0, 16);
const password = 'Password-' + randomUUID();
const created = await call('POST', '/api/v1/users', 201, null, { username, password, display_name: 'Студент 😀' });
const login = await call('POST', '/api/v1/auth/sessions', 201, null, undefined,
{ Authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64') });
return { id: created.data.id, token: login.data.token };
}
async function main() {
const a = await user(), b = await user(), outsider = await user();
const instances = new Set();
for (let i = 0; i < 12; i++) {
const result = await call('GET', '/api/v1/users/me', 200, a);
assert.equal(result.data.id, a.id);
instances.add(result.instance);
}
assert.equal(instances.size, 2, 'One session must work through both replicas');
const chat = (await call('POST', '/api/v1/chats', 201, a, { title: 'Идемпотентность', member_ids: [a.id, b.id] })).data;
const path = '/api/v1/chats/' + chat.id + '/messages';
const key = randomUUID();
const results = await Promise.all(Array.from({ length: 16 }, () => call('POST', path, 201, a,
{ text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key })));
assert.equal(new Set(results.map(r => r.instance)).size, 2);
for (const result of results) assert.deepEqual(result.data, results[0].data);
let history = (await call('GET', path, 200, b)).data;
assert.equal(history.items.length, 1);
await call('POST', path, 409, a, { text: 'Другой текст' }, { 'Idempotency-Key': key });
await call('POST', path, 400, a, { text: 'Без ключа' });
await call('POST', path, 400, a, { text: 'Неверный ключ' }, { 'Idempotency-Key': 'bad key' });
await call('POST', path, 404, outsider, { text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key });
await call('POST', path, 201, b, { text: 'Другой пользователь' }, { 'Idempotency-Key': key });
const otherChat = (await call('POST', '/api/v1/chats', 201, a, { title: 'Другой чат', member_ids: [a.id] })).data;
await call('POST', '/api/v1/chats/' + otherChat.id + '/messages', 201, a, { text: 'Другой чат' }, { 'Idempotency-Key': key });
const retryKey = randomUUID();
await call('POST', path, 400, a, { text: '\u0085' }, { 'Idempotency-Key': retryKey });
await call('POST', path, 201, a, { text: 'После ошибки можно повторить' }, { 'Idempotency-Key': retryKey });
const raceKey = randomUUID();
const race = await Promise.all(['Первый', 'Второй'].map(text => fetch(base + path, { method: 'POST',
headers: { Authorization: 'Bearer ' + a.token, 'Content-Type': 'application/json', 'Idempotency-Key': raceKey }, body: JSON.stringify({ text }) }).then(r => r.status)));
assert.deepEqual(race.sort(), [201, 409]);
history = (await call('GET', path, 200, b)).data;
assert.equal(history.items.length, 4);
console.log('PASS: one session on 2 replicas; 16 concurrent same-key requests across both yield 1 message; changed payload=409; user/chat scope isolated; invalid request does not consume key.');
if (process.argv.includes('--lifecycle')) {
const python = process.env.LAB_PYTHON || (process.platform === 'win32' ? 'py' : 'python3');
const control = action => execFileSync(python, ['scripts/control.py', action], { stdio: ['ignore', 'pipe', 'pipe'] });
// Also prove that an idempotency result and cursor survive a full stack restart.
const firstPage = (await call('GET', path + '?limit=1', 200, a)).data;
control('restart');
await waitForReady(a);
const replay = await call('POST', path, 201, a, { text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key });
assert.deepEqual(replay.data, results[0].data);
const secondPage = (await call('GET', path + '?limit=100&cursor=' + encodeURIComponent(firstPage.next_cursor), 200, a)).data;
assert.equal(firstPage.items.length + secondPage.items.length, 4);
console.log('PASS: full restart preserves session, signed cursor and idempotency response.');
for (const service of ['api1', 'api2']) {
const code = "fetch('http://127.0.0.1:8080/health/live').then(r=>console.log(r.headers.get('x-instance-id')))";
const target = execFileSync('docker', ['compose', 'exec', '-T', service, 'node', '-e', code], { encoding: 'utf8' }).trim();
process.env.TARGET_INSTANCE_ID = target;
const started = Date.now();
control('stop-one');
let recovered = false, failures = 0;
const writeKey = randomUUID();
while (Date.now() - started < 10000) {
try {
const result = await call('POST', path, 201, a, { text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key });
assert.deepEqual(result.data, results[0].data);
assert.notEqual(result.instance, target);
await call('POST', path, 201, b, { text: 'После отказа ' + service }, { 'Idempotency-Key': writeKey });
const read = await call('GET', path, 200, b);
assert.ok(read.data.items.some(m => m.id === results[0].data.id));
recovered = true;
console.log(JSON.stringify({ stopped: service, recovery_ms: Date.now() - started, transient_failures: failures, confirmed_messages_preserved: true }));
break;
} catch { failures++; await new Promise(r => setTimeout(r, 100)); }
}
try { assert.ok(recovered, service + ' did not recover within 10 seconds'); }
finally { control('restore'); await waitForReady(a); }
}
console.log('PASS: either replica can stop; surviving replica reads, writes and replays without duplicates. Both replicas restored.');
}
await call('DELETE', '/api/v1/auth/sessions/current', 204, a);
await call('POST', path, 401, a, { text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key });
console.log('PASS: replay after logout cannot bypass authentication.');
}
async function waitForReady(actor) {
for (let i = 0; i < 40; i++) {
try { await call('GET', '/api/v1/users/me', 200, actor); return; }
catch { await new Promise(r => setTimeout(r, 250)); }
}
throw new Error('LB did not become ready');
}
main().catch(error => { console.error('FAIL: ' + error.message); process.exitCode = 1; });
+43
View File
@@ -0,0 +1,43 @@
'use strict';
const assert = require('node:assert/strict');
const { randomUUID } = require('node:crypto');
const { pool, transaction } = require('./src/db');
const { migrate } = require('./src/migrate');
const { sendMessage } = require('./src/messages');
async function counts() {
const result = {};
for (const table of ['users', 'chats', 'chat_members', 'messages', 'sessions', 'message_requests'])
result[table] = (await pool.query(`SELECT count(*) AS n FROM ${table}`)).rows[0].n;
return result;
}
async function main() {
const before = await counts();
await migrate(); await migrate();
assert.deepEqual(await counts(), before);
assert.equal((await pool.query('SELECT count(*)::int AS n FROM schema_migrations')).rows[0].n, 2);
const user = randomUUID(), chat = randomUUID(), key = randomUUID();
await transaction(async client => {
await client.query('INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)',
[user, 'ttl_' + user.replaceAll('-', '').slice(0, 16), 'Synthetic TTL test', 'unusable-test-hash']);
await client.query('INSERT INTO chats(id,title) VALUES($1,$2)', [chat, 'Retention test']);
await client.query('INSERT INTO chat_members VALUES($1,$2)', [chat, user]);
});
const first = await sendMessage(user, chat, key, 'Original');
await assert.rejects(sendMessage(user, chat, key, 'Changed'), e => e.status === 409);
assert.equal((await pool.query('SELECT count(*)::int AS n FROM messages WHERE chat_id=$1', [chat])).rows[0].n, 1);
const hours = (await pool.query(`SELECT extract(epoch FROM (expires_at-clock_timestamp()))/3600 AS hours
FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3`, [user, chat, key])).rows[0].hours;
assert.ok(Number(hours) > 23.9);
// Simulate expiry only for the synthetic record, without waiting 24 hours.
await pool.query(`UPDATE message_requests SET expires_at=clock_timestamp()-interval '1 second'
WHERE user_id=$1 AND chat_id=$2 AND key=$3`, [user, chat, key]);
const second = await sendMessage(user, chat, key, 'After expiry');
assert.notEqual(first.id, second.id);
assert.equal((await pool.query('SELECT count(*)::int AS n FROM messages WHERE chat_id=$1', [chat])).rows[0].n, 2);
assert.equal((await pool.query('SELECT count(*)::int AS n FROM message_requests WHERE chat_id=$1', [chat])).rows[0].n, 1);
const missingChat = randomUUID();
await assert.rejects(sendMessage(user, missingChat, randomUUID(), 'Must rollback'), e => e.code === '23503');
assert.equal((await pool.query('SELECT count(*)::int AS n FROM message_requests WHERE chat_id=$1', [missingChat])).rows[0].n, 0);
console.log('PASS: migrations repeat without data changes; 24-hour retention; conflict inserts no duplicate; expired key may be reused without deleting old message; FK failure leaves no idempotency result.');
}
main().catch(error => { console.error('FAIL: storage check (' + (error.code || error.name) + ')'); process.exitCode = 1; }).finally(() => pool.end());