Files
mtusi2026lab3/infra/k6/messages.js
T
ArtyomandClaude Opus 5.5 711c9c98dc Add the k6 load profile and the load and detect probe modes
The k6 profile from the prepared kit runs an open model against the
balancer from the edge network: constant arrival rate, 80 % keyed
message posts and 20 % history reads over 20 synthetic users and 10
chats, metrics only for the measure phase, and no setup data (tokens)
in summary.json. scripts/k6.sh runs it with the host uid so the
summary is writable on Linux too.

scripts/probe.py gains three things. check --rounds repeats the
same-key race with a new key per round and counts rounds with
identical bodies, one stored copy and 409 on another body. load runs
an action under k6 while a probe posts every 0.1 s and resends the
same key after a failure and a poller reads the number of UP servers;
it writes the action log, the probe and LB traces, the delta of the
backend retry, redispatch and error counters, and a verdict: dip for
a replica that leaves and returns, replace for a rolling update that
must keep capacity and end on new replicas only. detect runs the
action in the background and polls the balancer at the same time, so
a drain that ends after the exclusion is visible, and checks the
declared maximum, the LB answer after detection and the time to
restore.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 19:51:59 +03:00

107 lines
4.1 KiB
JavaScript

import http from 'k6/http';
import { check } from 'k6';
import encoding from 'k6/encoding';
import exec from 'k6/execution';
const BASE = __ENV.BASE_URL || 'http://lb:8080';
const RATE = Number(__ENV.RATE || 50);
const WARMUP = Number(__ENV.WARMUP || 10);
const DURATION = Number(__ENV.DURATION || 60);
const USERS = Math.max(2, Number(__ENV.USERS || 20));
const READ_RATIO = Number(__ENV.READ_RATIO || 0.2);
const VUS = Number(__ENV.VUS || Math.max(10, Math.ceil(RATE / 10)));
const MAX_VUS = Number(__ENV.MAX_VUS || Math.max(VUS, Math.min(VUS * 4, 1000)));
const RUN = __ENV.RUN_ID || Date.now().toString(36);
const SUMMARY = __ENV.SUMMARY || '/out/summary.json';
const JSON_HEADERS = { 'Content-Type': 'application/json' };
const phase = (startTime, duration) => ({
executor: 'constant-arrival-rate',
rate: RATE,
timeUnit: '1s',
startTime: `${startTime}s`,
duration: `${duration}s`,
preAllocatedVUs: VUS,
maxVUs: MAX_VUS,
gracefulStop: '5s',
});
const measured = ['http_reqs', 'http_req_failed', 'http_req_duration', 'dropped_iterations', 'iterations'];
export const options = {
setupTimeout: '180s',
summaryTrendStats: ['avg', 'min', 'med', 'p(90)', 'p(95)', 'p(99)', 'max'],
scenarios: Object.assign(WARMUP > 0 ? { warmup: phase(0, WARMUP) } : {}, { measure: phase(WARMUP, DURATION) }),
thresholds: Object.fromEntries([
...measured.map((metric) => [`${metric}{scenario:measure}`, []]),
['http_req_duration{scenario:measure,name:post_message}', []],
['http_req_duration{scenario:measure,name:get_history}', []],
]),
};
function created(response, what) {
if (response.status !== 201) {
throw new Error(`${what}: HTTP ${response.status}`);
}
return response.json();
}
const bearer = (token, extra) => Object.assign({ Authorization: `Bearer ${token}` }, extra || {});
export function setup() {
const actors = [];
for (let i = 0; i < USERS; i++) {
const username = `k6_${RUN}_${i}`.slice(0, 32);
const password = `K6-${RUN}-${i}-synthetic`;
const user = created(
http.post(`${BASE}/api/v1/users`, JSON.stringify({ username, display_name: `k6 ${i}`, password }), { headers: JSON_HEADERS }),
'register',
);
const basic = encoding.b64encode(`${username}:${password}`);
const session = created(
http.post(`${BASE}/api/v1/auth/sessions`, null, { headers: { Authorization: `Basic ${basic}` } }),
'login',
);
actors.push({ id: user.id, token: session.token });
}
const chats = [];
for (let i = 0; i < USERS; i += 2) {
const [a, b] = [actors[i], actors[(i + 1) % USERS]];
const body = JSON.stringify({ title: `k6 ${RUN} ${i}`, member_ids: [a.id, b.id] });
const chat = created(http.post(`${BASE}/api/v1/chats`, body, { headers: bearer(a.token, JSON_HEADERS) }), 'chat');
chats.push({ id: chat.id, tokens: [a.token, b.token] });
}
console.log('LOAD-START');
return { chats };
}
export default function (data) {
const n = exec.scenario.iterationInTest;
const chat = data.chats[n % data.chats.length];
const token = chat.tokens[Math.floor(n / data.chats.length) % 2];
if (Math.random() < READ_RATIO) {
const response = http.get(`${BASE}/api/v1/chats/${chat.id}/messages?limit=50`, {
headers: bearer(token),
tags: { name: 'get_history' },
timeout: '10s',
});
check(response, { 'history 200': (r) => r.status === 200 });
return;
}
const key = `${RUN}-${exec.scenario.name}-${n}`;
const response = http.post(`${BASE}/api/v1/chats/${chat.id}/messages`, JSON.stringify({ text: `k6 ${key}` }), {
headers: bearer(token, Object.assign({ 'Idempotency-Key': key }, JSON_HEADERS)),
tags: { name: 'post_message' },
timeout: '10s',
});
check(response, { 'message 201': (r) => r.status === 201 });
}
export function handleSummary(data) {
delete data.setup_data;
const reqs = data.metrics['http_reqs{scenario:measure}'];
const failed = data.metrics['http_req_failed{scenario:measure}'];
const line = `measure: ${reqs ? reqs.values.count : 0} requests, failed ratio ${failed ? failed.values.rate : 'n/a'}\n`;
return { [SUMMARY]: JSON.stringify(data, null, 1), stdout: line };
}