Files
mtusi2026lab7-safronov/bench/k6/telemetry.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

230 lines
7.7 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.
// Профиль цены телеметрии (design change track1-telemetry-cost, решение 8):
// одинаковая открытая нагрузка ниже насыщения через LB во всех вариантах.
// Классы — сценарии constant-arrival-rate с одним startTime на всю длину
// прогона (разогрев + чистое окно + окно отказов), timeUnit 10 с для дробной
// интенсивности; деление на окна — по времени отправки от t0 (setup пишет
// «t-t0,<мс>», часы ВМ). VU заранее и без прибавления, ответ не повторяется:
// недосланные итерации — dropped_iterations. Строка на запрос в файл консоли:
// «t,<класс>,<отправка мс>,<длительность мс>,<статус>,<X-Request-Id>,
// <X-Instance-Id>,<id вложения|->». Входы оркестратора: fixture.json
// (prepare.js), downloads.json (готовые вложения разогрева), broken.json (id
// вложения без объекта), тела s.jpg и bad.jpg (make_images.py).
// RATES — «класс:в секунду,…» (Profile.telemetry_rates)
// DURATION — секунды всех окон
// NAME — имя итога в raw/
// Регистрация: пароль — crypto.randomUUID() только в памяти итерации, в строки,
// итог и файлы не попадает; токен ответа не читается.
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,
summaryFiles,
syntheticText,
} from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const downloads = new SharedArray(
"downloads",
() => JSON.parse(open(`${WORK_DIR}/downloads.json`)),
);
const BROKEN = JSON.parse(open(`${WORK_DIR}/broken.json`));
const GOOD_BODY = open(`${WORK_DIR}/s.jpg`, "b");
const BAD_BODY = open(`${WORK_DIR}/bad.jpg`, "b");
const DURATION = Number(__ENV.DURATION);
const RATES = Object.fromEntries(
(__ENV.RATES || "")
.split(",")
.filter((item) => item !== "")
.map((item) => {
const [name, rate] = item.split(":");
return [name, Number(rate)];
}),
);
// больше timeout server LB (10 с, у загрузки 30 с): клиент видит ответ LB
const TIMEOUT = "40s";
const READER = authHeaders(fixture.tokens[fixture.readerId]);
const WRITE_URL = `${API}/chats/${fixture.writeChatId}/messages`;
const UPLOAD_URL = `${API}/chats/${fixture.readChatId}/attachments`;
// VU заранее: интенсивность × запас на медленные ответы (запись под
// блокировкой до 0,6 с, регистрация с Argon2id до 1 с) + постоянная часть
function vus(rate) {
return Math.max(4, Math.ceil(rate * 2) + 4);
}
function scenarios() {
const out = {};
for (const [name, rate] of Object.entries(RATES)) {
if (!(rate > 0)) {
continue;
}
out[name] = {
executor: "constant-arrival-rate",
exec: name,
rate: Math.max(1, Math.round(rate * 10)),
timeUnit: "10s",
startTime: "0s",
duration: `${DURATION}s`,
preAllocatedVUs: vus(rate),
maxVUs: vus(rate),
gracefulStop: "45s",
};
}
return out;
}
const iterationThresholds = Object.fromEntries(
Object.keys(RATES).map((name) => [
`iterations{scenario:${name}}`,
["count>=0"],
]),
);
export const options = {
scenarios: scenarios(),
summaryTrendStats: SUMMARY_TREND_STATS,
// пороги всегда выполняются: итерации по сценариям и недосланные попадают
// в итог, run.py сверяет с ними число строк
thresholds: {
...SUMMARY_THRESHOLDS,
...iterationThresholds,
iterations: ["count>=0"],
dropped_iterations: ["count>=0"],
},
};
export function setup() {
const t0 = Date.now();
console.log(`t-t0,${t0}`);
return { t0 };
}
// длительность — монотонные тайминги k6 с точностью 0,01 мс, без ответа —
// разность часов
function report(kind, start, res, 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) * 100) / 100,
);
const requestId = res.headers["X-Request-Id"] || "-";
const instance = res.headers["X-Instance-Id"] || "-";
console.log(
`t,${kind},${start},${duration},${res.status},${requestId},${instance},` +
`${id}`,
);
}
function get(kind, url, expected) {
const start = Date.now();
const res = http.get(url, {
headers: READER,
responseType: "none",
timeout: TIMEOUT,
responseCallback: http.expectedStatuses(expected),
});
report(kind, start, res);
}
export function read() {
get("read", `${WRITE_URL}?limit=${PAGE_LIMIT}`, 200);
}
export function me() {
get("me", `${API}/users/me`, 200);
}
export function card() {
get("card", `${API}/chats/${fixture.writeChatId}`, 200);
}
export function download() {
const id = downloads[exec.scenario.iterationInTest % downloads.length];
get("download", `${API}/attachments/${id}/content`, 200);
}
// вложение без объекта: 500 AttachmentContentMissing — ожидаемый ответ класса
export function broken() {
get("broken", `${API}/attachments/${BROKEN}/content`, 500);
}
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("tc", n) }),
{
headers: messageHeaders(fixture.tokens[sender]),
responseType: "none",
timeout: TIMEOUT,
responseCallback: http.expectedStatuses(201),
},
);
report("write", start, res);
}
function postUpload(kind, body) {
const start = Date.now();
const res = http.post(`${UPLOAD_URL}?filename=bench`, body, {
headers: {
Authorization: `Bearer ${fixture.tokens[fixture.readerId]}`,
"Content-Type": "image/jpeg",
},
timeout: TIMEOUT,
responseCallback: http.expectedStatuses(202),
});
let id = "-";
if (res.status === 202) {
id = res.json("id");
}
report(kind, start, res, id);
}
// имя сценария — имя класса и экспортируемой функции (exec)
export function upload() {
postUpload("upload", GOOD_BODY);
}
export function upload_bad() {
postUpload("upload_bad", BAD_BODY);
}
// регистрация — редкий медленный маршрут (Argon2id): имя из UUID без
// дефисов (шаблон контракта ^[a-z0-9_]{3,32}$), пароль сразу выбрасывается
export function register() {
const name = `t${crypto.randomUUID().split("-").join("").slice(0, 30)}`;
const start = Date.now();
const res = http.post(
`${API}/users`,
JSON.stringify({
username: name,
display_name: "Bench telemetry",
password: crypto.randomUUID(),
}),
{
headers: { "Content-Type": "application/json" },
responseType: "none",
timeout: TIMEOUT,
responseCallback: http.expectedStatuses(201),
},
);
report("register", start, res);
}
export function handleSummary(data) {
// t0 — в строке t-t0, итог без данных setup
delete data.setup_data;
return summaryFiles(data);
}