Files
mtusi2026lab4/bench/k6/failover.js
T
ricoromaandClaude Opus 5.5 5d5d8f9d2a chore: carry lab 3 over
- carry the lab 3 solution over from mtusi2026lab3-safronov
  (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests,
  bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts,
  Dockerfile, compose, pyproject and uv lock
- merge Makefile, .gitignore and .dockerignore (the lab 3 versions only
  add lines to the skeleton, which is the same in lab 4) and
  .env.example (lab 4 skeleton names listed in the header)
- rename the compose project to mtusi-lab4 and the image to :lab4 so
  the stand does not reuse the lab 3 containers and volumes
- update AGENTS.md for lab 4: current lab, origin commit, contract and
  test files of the new skeleton

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:32:33 +03:00

131 lines
4.9 KiB
JavaScript
Raw 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);
}