Исправить заголовок 413 и дополнить проверку отказов и масштабирования lab3

This commit is contained in:
Vladislav Agapov
2026-10-29 15:25:37 +03:00
parent 7b7e23fd02
commit f4ec74b78b
294 changed files with 29530 additions and 57 deletions
+61
View File
@@ -0,0 +1,61 @@
import http from 'k6/http';
import encoding from 'k6/encoding';
import { sleep } from 'k6';
export const options = { vus: 1, iterations: 1, setupTimeout: '120s' };
const base = __ENV.BASE_URL;
const target = __ENV.TARGET_INSTANCE_ID;
export function setup() {
const username = 'fail_' + Date.now();
const password = 'synthetic-failover-password';
const user = http.post(base + '/api/v1/users', JSON.stringify({username, password, display_name:'Failover'}), {headers:{'Content-Type':'application/json'}});
if (user.status !== 201) throw new Error('registration ' + user.status);
const session = http.post(base + '/api/v1/auth/sessions', null, {headers:{Authorization:'Basic ' + encoding.b64encode(username + ':' + password)}});
if (session.status !== 201) throw new Error('login ' + session.status);
const headers = {Authorization:'Bearer ' + session.json().token, 'Content-Type':'application/json'};
const chat = http.post(base + '/api/v1/chats', JSON.stringify({title:'Failover',member_ids:[user.json().id]}), {headers});
if (chat.status !== 201) throw new Error('chat ' + chat.status);
const seen = new Set();
for (let i=0; i<20; i++) {
const response = http.get(base + '/api/v1/users/me', {headers, timeout:'2s'});
if (response.status !== 200) throw new Error('initial read ' + response.status);
seen.add(response.headers['X-Instance-Id']);
}
if (seen.size < 2 || !seen.has(target)) throw new Error('target not observed through LB');
const path = base + '/api/v1/chats/' + chat.json().id + '/messages';
const original = http.post(path, JSON.stringify({text:'before failure'}), {headers:{...headers,'Idempotency-Key':'before'}});
if (original.status !== 201) throw new Error('initial message ' + original.status);
return {headers,path,original:original.json()};
}
export default function(data) {
console.log('READY_TO_STOP ' + target);
const started = Date.now();
const confirmed = new Set([data.original.id]);
let errors = 0, reads = 0, sequence = 0;
const events = [];
const lastInstances = [];
while (Date.now() - started < 25000) {
const response = http.post(data.path, JSON.stringify({text:'during-' + sequence}), {headers:{...data.headers,'Idempotency-Key':'during-' + sequence},timeout:'2s'});
if (response.status === 201) {
confirmed.add(response.json().id); sequence++;
events.push({seconds:(Date.now()-started)/1000,instance:response.headers['X-Instance-Id']});
lastInstances.push(response.headers['X-Instance-Id']);
} else errors++;
const read = http.get(data.path + '?limit=100', {headers:data.headers,timeout:'2s'});
if (read.status === 200) reads++; else errors++;
sleep(0.1);
}
const items = [];
let path = data.path + '?limit=100';
while (path) {
const response = http.get(path, {headers:data.headers,timeout:'5s'});
if (response.status !== 200) throw new Error('final history ' + response.status);
items.push(...response.json().items);
const cursor = response.json().next_cursor;
path = cursor ? data.path + '?limit=100&cursor=' + encodeURIComponent(cursor) : null;
}
const ids = new Set(items.map(item=>item.id));
if ([...confirmed].some(id=>!ids.has(id))) throw new Error('confirmed message lost');
if (new Set(items.map(item=>item.text)).size !== items.length) throw new Error('uncertain retry duplicated');
if (lastInstances.length < 5 || lastInstances.slice(-5).includes(target)) throw new Error('target still serves or insufficient writes');
console.log(JSON.stringify({target,started_epoch_ms:started,confirmed:confirmed.size,reads,errors,events,pass:true}));
}
+26 -11
View File
@@ -1,7 +1,7 @@
import http from 'k6/http';
import encoding from 'k6/encoding';
import execution from 'k6/execution';
import { check } from 'k6';
import { check, sleep } from 'k6';
import { Counter, Trend } from 'k6/metrics';
const base = __ENV.BASE_URL || 'https://hl.agapov.space';
@@ -10,13 +10,16 @@ const users = Number(__ENV.USERS || 16);
const writes = new Counter('confirmed_messages');
const attempts = new Counter('attempted_messages');
const failures = new Counter('application_errors');
const operations = new Counter('measured_operations');
const failedWrites = new Counter('failed_writes');
const latency = new Trend('message_latency_ms', true);
export const options = {
scenarios: {
warmup: { executor: 'constant-vus', vus: 4, duration: '5s' },
measured: { executor: 'constant-vus', vus: Number(__ENV.VUS || 32), duration: `${seconds}s`, startTime: '5s' },
warmup: { executor: 'constant-vus', vus: 4, duration: '5s', gracefulStop: '0s' },
measured: { executor: 'constant-vus', vus: Number(__ENV.VUS || 32), duration: `${seconds}s`, startTime: '10s', gracefulStop: '0s' },
},
setupTimeout: '120s',
setupTimeout: '180s',
thresholds: { 'application_errors{status:429}': ['count>=0'], 'application_errors{status:503}': ['count>=0'], 'application_errors{status:0}': ['count>=0'] },
summaryTrendStats: ['avg', 'p(50)', 'p(95)', 'p(99)', 'max'],
};
@@ -24,17 +27,27 @@ export function setup() {
const actors = [];
const prefix = `bench_${Date.now()}`;
for (let i = 0; i < users; i++) {
const username = `${prefix}_${i}`;
let prepared = false;
for (let attempt = 0; attempt < 5; attempt++) {
for (let ready = 0; ready < 30; ready++) {
if (http.get(base + '/health/ready', {timeout:'3s', tags:{phase:'setup'}}).status === 200) break;
sleep(1);
}
const username = `${prefix}_${i}_${attempt}`;
const password = 'synthetic-benchmark-password';
let response = http.post(`${base}/api/v1/users`, JSON.stringify({ username, display_name: 'Synthetic', password }), { headers: { 'Content-Type': 'application/json' }, tags: { phase: 'setup' } });
if (response.status !== 201) throw new Error(`registration: ${response.status}`);
if (response.status !== 201) { console.warn(`setup registration: ${response.status}; abandoning synthetic actor`); sleep(1); continue; }
const user = response.json();
response = http.post(`${base}/api/v1/auth/sessions`, null, { headers: { Authorization: `Basic ${encoding.b64encode(`${username}:${password}`)}` }, tags: { phase: 'setup' } });
if (response.status !== 201) throw new Error(`login: ${response.status}`);
if (response.status !== 201) { console.warn(`setup login: ${response.status}; abandoning synthetic actor`); sleep(1); continue; }
const token = response.json().token;
response = http.post(`${base}/api/v1/chats`, JSON.stringify({ title: 'Synthetic benchmark', member_ids: [user.id] }), { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, tags: { phase: 'setup' } });
if (response.status !== 201) throw new Error(`chat: ${response.status}`);
if (response.status !== 201) { console.warn(`setup chat: ${response.status}; abandoning synthetic actor`); sleep(1); continue; }
actors.push({ token, chat: response.json().id });
prepared = true;
break;
}
if (!prepared) throw new Error("synthetic actor setup exhausted retries");
}
return actors;
}
@@ -46,17 +59,19 @@ export default function (actors) {
const path = `${base}/api/v1/chats/${actor.chat}/messages`;
const payload = JSON.stringify({ text: `synthetic message ${__VU}:${__ITER}` });
const response = http.post(path, payload, { headers, tags: { phase: 'load' } });
if (measured) { latency.add(response.timings.duration); attempts.add(1); }
if (measured) { latency.add(response.timings.duration); attempts.add(1); operations.add(1); }
if (check(response, { 'message confirmed': r => r.status === 201 })) { if (measured) writes.add(1); }
else if (measured) failures.add(1, { status: String(response.status) });
else if (measured) { failures.add(1, { status: String(response.status) }); failedWrites.add(1); }
if (response.status === 201 && __ITER % 10 === 0) {
if (measured) operations.add(1);
const repeated = http.post(path, payload, { headers, tags: { phase: 'load' } });
if (!check(repeated, { 'retry returns original': r => r.status === 201 && r.json().id === response.json().id })) { if (measured) failures.add(1, { status: String(repeated.status) }); }
}
if (measured) operations.add(1);
const read = http.get(`${path}?limit=10`, { headers, tags: { phase: 'load' } });
if (!check(read, { 'history readable': r => r.status === 200 })) { if (measured) failures.add(1, { status: String(read.status) }); }
}
export function handleSummary(data) {
return { stdout: JSON.stringify({ profile: { vus: Number(__ENV.VUS || 32), seconds, warmup_seconds: 5, users }, summary: data }) + '\n' };
return { stdout: JSON.stringify({ profile: { vus: Number(__ENV.VUS || 32), seconds, warmup_seconds: 5, drain_seconds: 5, users }, summary: data }) + '\n' };
}