Files
mtusi2026lab2/bench/k6/lib.js
T
ricoromaandClaude Opus 5.5 7b775a29a9 chore: carry over lab 1 solution into lab 2 skeleton
Copy the committed lab 1 sources as-is: src/, student-tests/, bench/,
Dockerfile, docker-compose.yml, pyproject.toml, uv.lock,
.python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/,
openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays
in the lab 1 repository.

Merge the new skeleton files with own sections: Makefile (lab 2
targets plus own run, docker, bench and common targets), .gitignore,
.dockerignore and .env.example. Rename the image to
mtusi-messenger:lab2 and point AGENTS.md at lab 2.

The application is still the in-memory lab 1 implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:11:46 +03:00

90 lines
3.5 KiB
JavaScript

// Общие хелперы сценариев стенда: адрес, идентификация, текст, генератор
// случайных чисел, запись итога. Не Node.js: только встроенные модули k6.
import http from "k6/http";
import { check, fail } from "k6";
export const BASE_URL = __ENV.BASE_URL || "http://mtusi-bench-api: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"] };
// идентификация лабы 1; с лабы 2 здесь Bearer, как Actor.headers()
export function authHeaders(userId) {
return { "X-User-Id": userId, "Content-Type": "application/json" };
}
// синтетический текст ровно 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;
};
}
export function register(username, displayName) {
const res = http.post(
`${API}/users`,
JSON.stringify({ username, display_name: displayName }),
{ headers: { "Content-Type": "application/json" } },
);
if (!check(res, { "register 201": (r) => r.status === 201 })) {
fail(`register ${username}: ${res.status} ${res.body}`);
}
return res.json("id");
}
export function createChat(ownerId, title, memberIds) {
const res = http.post(
`${API}/chats`,
JSON.stringify({ title, member_ids: memberIds }),
{ headers: authHeaders(ownerId) },
);
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, senderId, text) {
const res = http.post(
`${API}/chats/${chatId}/messages`,
JSON.stringify({ text }),
{
headers: authHeaders(senderId),
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) };
}