Files
mtusi2026lab4/bench/k6/lib.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

123 lines
5.2 KiB
JavaScript

// Общие хелперы сценариев стенда: адрес, идентификация, текст, генератор
// случайных чисел, запись итога. Не Node.js: только встроенные модули k6.
import encoding from "k6/encoding";
import http from "k6/http";
import { check, fail } from "k6";
// через балансировщик стенда: имя сервиса haproxy — алиас в сети
// mtusi-bench, за ним Profile.replicas реплик (решение 6 design change
// graceful-failover)
export const BASE_URL = __ENV.BASE_URL || "http://haproxy:8080";
export const API = `${BASE_URL}/api/v1`;
// каталог метки (сырые итоги) и рабочий каталог (фикстура, курсоры)
export const OUT_DIR = __ENV.OUT_DIR || "/out";
export const WORK_DIR = __ENV.WORK_DIR || "/work";
export const TEXT_LENGTH = Number(__ENV.TEXT_LENGTH || 64);
export const PAGE_LIMIT = Number(__ENV.PAGE_LIMIT || 50);
// перцентили в итоге; подметрика expected_response:true — только успехи
export const SUMMARY_TREND_STATS = [
"avg", "min", "med", "p(50)", "p(95)", "p(99)", "max",
];
export const SUCCESS_DURATION = "http_req_duration{expected_response:true}";
// порог всегда выполняется: он нужен, чтобы подметрика попала в итог
export const SUMMARY_THRESHOLDS = { [SUCCESS_DURATION]: ["max>=0"] };
// идентификация, как Actor.headers() в student-tests: Bearer-токен сессии
export function authHeaders(token) {
return {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
}
// заголовки отправки сообщения: с лабы 3 обязателен Idempotency-Key. Новый
// ключ на каждую отправку (UUID v4 WebCrypto — допустимый алфавит
// контракта); стенд отправку не повторяет. Профиль отказа задаёт ключ сам:
// повтор неподтверждённой записи строит тот же ключ по номеру
export function messageHeaders(token, key = crypto.randomUUID()) {
return {
...authHeaders(token),
"Idempotency-Key": key,
};
}
// синтетический пароль из двух UUID v4 WebCrypto (73 символа, контракт —
// 12–128): только в памяти prepare.js, в фикстуру и результаты не попадает
function syntheticPassword() {
return `${crypto.randomUUID()}-${crypto.randomUUID()}`;
}
// синтетический текст ровно TEXT_LENGTH ASCII-символов
export function syntheticText(tag, n) {
const prefix = `${tag}-${n}-`;
return prefix + "x".repeat(Math.max(0, TEXT_LENGTH - prefix.length));
}
// mulberry32: воспроизводимая последовательность из 32-битного зерна
export function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// регистрация с паролем и вход по Basic: { id, token } пользователя
export function register(username, displayName) {
const password = syntheticPassword();
const res = http.post(
`${API}/users`,
JSON.stringify({ username, display_name: displayName, password }),
{ headers: { "Content-Type": "application/json" } },
);
if (!check(res, { "register 201": (r) => r.status === 201 })) {
fail(`register ${username}: ${res.status} ${res.body}`);
}
const basic = encoding.b64encode(`${username}:${password}`);
const login = http.post(`${API}/auth/sessions`, null, {
headers: { Authorization: `Basic ${basic}` },
});
if (!check(login, { "login 201": (r) => r.status === 201 })) {
fail(`login ${username}: ${login.status} ${login.body}`);
}
return { id: res.json("id"), token: login.json("token") };
}
export function createChat(ownerToken, title, memberIds) {
const res = http.post(
`${API}/chats`,
JSON.stringify({ title, member_ids: memberIds }),
{ headers: authHeaders(ownerToken) },
);
if (!check(res, { "chat 201": (r) => r.status === 201 })) {
fail(`create chat ${title}: ${res.status} ${res.body}`);
}
return res.json("id");
}
export function sendMessage(chatId, senderToken, text, key = undefined) {
const res = http.post(
`${API}/chats/${chatId}/messages`,
JSON.stringify({ text }),
{
headers: messageHeaders(senderToken, key),
responseCallback: http.expectedStatuses(201),
},
);
check(res, { "message 201": (r) => r.status === 201 });
return res;
}
// итог прогона: в файл NAME.json каталога метки; без NAME — в рабочий
// каталог (прогрев), чтобы оркестратор посчитал подтверждённые записи
export function summaryFiles(data) {
const name = __ENV.NAME;
const path = name ? `${OUT_DIR}/raw/${name}.json` : `${WORK_DIR}/last.json`;
return { [path]: JSON.stringify(data) };
}