Files
mtusi2026lab3/bench/k6/failover.js
T
ricoromaandClaude Opus 5.5 459f84c75c feat: coordinate timeout chain and add failover load profile
HAProxy checks get fastinter 500ms and timeout check 2.5s (hung replica
detected within 6.5 s), http-reuse never with uvicorn keep-alive 60 s so
the LB closes idle replica connections, and app connections set
idle_in_transaction_session_timeout so a frozen replica releases its
idempotency key. The bench stand runs behind HAProxy with N replicas and
gains the failover profile (make bench_failover / bench_failover_quick):
constant-rate writes with a key and reads while each replica is stopped,
killed or paused, with per-second timeline, detection and recovery time
and write reconciliation. Driver commands idle-conns and hang-key check
the keep-alive and hung-transaction decisions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 23:21:12 +03:00

129 lines
4.8 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). Каждый запрос —
// строка «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);
}