Files
mtusi2026lab7-safronov/bench/k6/failover.js
ricoromaandClaude Opus 5.5 089d78609d chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:59:04 +03:00

131 lines
4.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Профили отказа и замены реплик: постоянная интенсивность записи с ключом
// и чтения страницы истории через LB, пока оркестратор останавливает и
// возвращает реплику (решение 7 design change graceful-failover) или
// заменяет реплики scripts/rolling-update.sh (решение 8 design change
// rolling-update). Каждый запрос —
// строка «fo,<w|r>,<n>,<отправка мс>,<длительность мс>,<статус>,
// <X-Instance-Id>,<успех>» в вывод k6: из них run.py строит посекундную
// шкалу. Время — Date.now() часов ВМ Docker, те же часы, что у журнала LB и
// событий Docker.
import exec from "k6/execution";
import http from "k6/http";
import { SharedArray } from "k6/data";
import {
API,
PAGE_LIMIT,
SUMMARY_THRESHOLDS,
SUMMARY_TREND_STATS,
WORK_DIR,
authHeaders,
messageHeaders,
mulberry32,
summaryFiles,
syntheticText,
} from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const cursors = new SharedArray(
"cursors",
() => JSON.parse(open(`${WORK_DIR}/cursors.json`)).cursors,
);
// ключ записи — <RUN>.<PHASE>.<n>: повтор (retry.js) строит тот же
const RUN = __ENV.RUN;
const PHASE = Number(__ENV.PHASE);
const SEED = Number(__ENV.SEED || 0);
// VU сценария: заранее созданные и предел (Profile.failover_pre_vus,
// failover_max_vus). Создание VU на ходу пропускает итерации
const PRE_VUS = Number(__ENV.PRE_VUS || 600);
const MAX_VUS = Number(__ENV.MAX_VUS || 1500);
// больше timeout server LB (10 с): клиент видит ответ LB, а не свой таймаут
const TIMEOUT = __ENV.TIMEOUT || "15s";
const WRITE_URL = `${API}/chats/${fixture.writeChatId}/messages`;
const READ_URL = `${API}/chats/${fixture.readChatId}/messages`;
const READ_HEADERS = authHeaders(fixture.tokens[fixture.readerId]);
function scenario(fn, rate) {
return {
executor: "constant-arrival-rate",
exec: fn,
rate,
timeUnit: "1s",
duration: __ENV.DURATION,
// зависшая реплика держит запрос до timeout server: VU с запасом
preAllocatedVUs: PRE_VUS,
maxVUs: MAX_VUS,
gracefulStop: "20s",
};
}
export const options = {
scenarios: {
write: scenario("write", Number(__ENV.WRITE_RATE)),
read: scenario("read", Number(__ENV.READ_RATE)),
},
summaryTrendStats: SUMMARY_TREND_STATS,
// пороги всегда выполняются: подметрики итераций по сценариям попадают
// в итог, и run.py сверяет с ними число строк о запросах
thresholds: {
...SUMMARY_THRESHOLDS,
"iterations{scenario:write}": ["count>=0"],
"iterations{scenario:read}": ["count>=0"],
},
};
// длительность — по монотонным таймингам k6, а не разность Date.now():
// часы ВМ подводятся, и при шаге назад разность выходила отрицательной.
// Ответа нет (status 0) — тайминги пусты, тогда разность часов
function report(kind, n, start, res, ok) {
const instance = res.headers["X-Instance-Id"] || "-";
const t = res.timings;
const measured = t.blocked + t.connecting + t.tls_handshaking + t.duration;
const duration = Math.max(
0,
Math.round(res.status === 0 ? Date.now() - start : measured),
);
console.log(
`fo,${kind},${n},${start},${duration},${res.status},${instance},${ok ? 1 : 0}`,
);
}
export function write() {
const n = exec.scenario.iterationInTest;
const sender = fixture.memberIds[n % fixture.memberIds.length];
const start = Date.now();
const res = http.post(
WRITE_URL,
JSON.stringify({ text: syntheticText(`f${PHASE}`, n) }),
{
headers: messageHeaders(fixture.tokens[sender], `${RUN}.${PHASE}.${n}`),
responseType: "none",
timeout: TIMEOUT,
responseCallback: http.expectedStatuses(201),
},
);
report("w", n, start, res, res.status === 201);
}
let random = null;
export function read() {
if (random === null) {
random = mulberry32(SEED + exec.vu.idInTest);
}
const n = exec.scenario.iterationInTest;
const cursor = encodeURIComponent(
cursors[Math.floor(random() * cursors.length)],
);
const start = Date.now();
const res = http.get(`${READ_URL}?limit=${PAGE_LIMIT}&cursor=${cursor}`, {
headers: READ_HEADERS,
timeout: TIMEOUT,
responseCallback: http.expectedStatuses(200),
});
const full = res.status === 200 && res.json("items.#") === PAGE_LIMIT;
report("r", n, start, res, full);
}
export function handleSummary(data) {
return summaryFiles(data);
}