'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; });