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>
This commit is contained in:
2026-09-30 22:11:46 +03:00
co-authored by Claude Opus 5.5
parent 65003b6119
commit 7b775a29a9
174 changed files with 19023 additions and 11 deletions
+61
View File
@@ -0,0 +1,61 @@
// Пул курсоров сценария read: проход истории читаемого чата страницами по
// WALK_LIMIT и равномерная выборка до POOL_SIZE курсоров. В пул идут
// только позиции, после которых есть ещё PAGE_LIMIT сообщений, чтобы
// каждая страница read была полной.
import http from "k6/http";
import { fail } from "k6";
import { API, PAGE_LIMIT, WORK_DIR, authHeaders } from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const WALK_LIMIT = Number(__ENV.WALK_LIMIT || 100);
const POOL_SIZE = Number(__ENV.POOL_SIZE || 1000);
export const options = {
vus: 1,
iterations: 1,
setupTimeout: "30m",
};
export function setup() {
const url = `${API}/chats/${fixture.readChatId}/messages`;
const params = { headers: authHeaders(fixture.readerId) };
const positions = [];
let cursor = null;
let walked = 0;
for (;;) {
const query = cursor === null
? `?limit=${WALK_LIMIT}`
: `?limit=${WALK_LIMIT}&cursor=${encodeURIComponent(cursor)}`;
const res = http.get(url + query, params);
if (res.status !== 200) {
fail(`history page after ${walked}: ${res.status} ${res.body}`);
}
const body = res.json();
walked += body.items.length;
if (body.next_cursor === null) {
break;
}
positions.push({ after: walked, cursor: body.next_cursor });
cursor = body.next_cursor;
}
const eligible = positions.filter((p) => walked - p.after >= PAGE_LIMIT);
const step = Math.max(1, eligible.length / POOL_SIZE);
const pool = [];
for (let i = 0; i < eligible.length && pool.length < POOL_SIZE; i += step) {
pool.push(eligible[Math.floor(i)]);
}
return {
walked,
eligible: eligible.length,
first_after: pool.length ? pool[0].after : null,
last_after: pool.length ? pool[pool.length - 1].after : null,
cursors: pool.map((p) => p.cursor),
};
}
export default function () {}
export function handleSummary(data) {
return { [`${WORK_DIR}/cursors.json`]: JSON.stringify(data.setup_data) };
}
+89
View File
@@ -0,0 +1,89 @@
// Общие хелперы сценариев стенда: адрес, идентификация, текст, генератор
// случайных чисел, запись итога. Не 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) };
}
+39
View File
@@ -0,0 +1,39 @@
// Одна порция наполнения читаемого чата: COUNT сообщений от участников по
// кругу. OFFSET — сколько сообщений уже отправлено, для номеров в тексте.
import exec from "k6/execution";
import {
SUMMARY_THRESHOLDS,
SUMMARY_TREND_STATS,
WORK_DIR,
sendMessage,
summaryFiles,
syntheticText,
} from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const OFFSET = Number(__ENV.OFFSET || 0);
export const options = {
scenarios: {
prefill: {
executor: "shared-iterations",
vus: Number(__ENV.VUS || 32),
iterations: Number(__ENV.COUNT),
maxDuration: "30m",
},
},
discardResponseBodies: true,
summaryTrendStats: SUMMARY_TREND_STATS,
thresholds: SUMMARY_THRESHOLDS,
};
export default function () {
const n = OFFSET + exec.scenario.iterationInTest;
const sender = fixture.memberIds[n % fixture.memberIds.length];
sendMessage(fixture.readChatId, sender, syntheticText("p", n));
}
export function handleSummary(data) {
return summaryFiles(data);
}
+34
View File
@@ -0,0 +1,34 @@
// Пользователи и два чата стенда: читаемый (сценарий read) и чат записи
// (сценарий write). Итог — fixture.json в рабочем каталоге.
import { WORK_DIR, createChat, register } from "./lib.js";
const MEMBERS = Number(__ENV.MEMBERS || 10);
export const options = {
vus: 1,
iterations: 1,
setupTimeout: "60s",
};
export function setup() {
// размер начинается с пустого процесса, поэтому имени хватает времени
const stamp = Date.now().toString(36);
const readerId = register(`b${stamp}_reader`, "Bench reader");
const memberIds = [];
for (let i = 0; i < MEMBERS; i++) {
memberIds.push(register(`b${stamp}_m${i}`, `Bench member ${i}`));
}
const everyone = [readerId, ...memberIds];
return {
readerId,
memberIds,
readChatId: createChat(readerId, "bench read", everyone),
writeChatId: createChat(readerId, "bench write", everyone),
};
}
export default function () {}
export function handleSummary(data) {
return { [`${WORK_DIR}/fixture.json`]: JSON.stringify(data.setup_data) };
}
+69
View File
@@ -0,0 +1,69 @@
// Сценарий read: страница истории читаемого чата с курсором, случайно
// выбранным из пула. У каждого VU свой генератор с зерном SEED + номер VU:
// последовательность одинакова в разных метках и различна у клиентов.
import exec from "k6/execution";
import http from "k6/http";
import { check } from "k6";
import { SharedArray } from "k6/data";
import {
API,
PAGE_LIMIT,
SUMMARY_THRESHOLDS,
SUMMARY_TREND_STATS,
WORK_DIR,
authHeaders,
mulberry32,
summaryFiles,
} 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,
);
const SEED = Number(__ENV.SEED || 0);
// отладка стенда: напечатать первые TRACE выборов каждого VU
const TRACE = Number(__ENV.TRACE || 0);
const URL = `${API}/chats/${fixture.readChatId}/messages`;
const PARAMS = {
headers: authHeaders(fixture.readerId),
responseCallback: http.expectedStatuses(200),
};
export const options = {
scenarios: {
read: {
executor: "constant-vus",
vus: Number(__ENV.VUS),
duration: __ENV.DURATION,
gracefulStop: "5s",
},
},
summaryTrendStats: SUMMARY_TREND_STATS,
thresholds: SUMMARY_THRESHOLDS,
};
let random = null;
let picks = 0;
export default function () {
if (random === null) {
random = mulberry32(SEED + exec.vu.idInTest);
}
const index = Math.floor(random() * cursors.length);
if (picks < TRACE) {
console.log(`trace vu=${exec.vu.idInTest} pick=${picks} index=${index}`);
}
picks += 1;
const cursor = encodeURIComponent(cursors[index]);
const res = http.get(`${URL}?limit=${PAGE_LIMIT}&cursor=${cursor}`, PARAMS);
check(res, {
"status 200": (r) => r.status === 200,
"full page": (r) => r.status === 200 && r.json("items.#") === PAGE_LIMIT,
});
}
export function handleSummary(data) {
return summaryFiles(data);
}
+48
View File
@@ -0,0 +1,48 @@
// Проверка после блока read: читаемый чат не изменился. Дочитывает
// историю от последнего курсора пула до конца и считает сообщения. Новое
// сообщение встало бы в конец, поэтому хвоста достаточно.
import http from "k6/http";
import { fail } from "k6";
import { API, WORK_DIR, authHeaders } from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const pool = JSON.parse(open(`${WORK_DIR}/cursors.json`));
const WALK_LIMIT = Number(__ENV.WALK_LIMIT || 100);
export const options = {
vus: 1,
iterations: 1,
setupTimeout: "30m",
};
export function setup() {
const url = `${API}/chats/${fixture.readChatId}/messages`;
const params = { headers: authHeaders(fixture.readerId) };
// пустой пул (история короче страницы обхода) — читаем с начала
const hasPool = pool.cursors.length > 0;
let cursor = hasPool ? pool.cursors[pool.cursors.length - 1] : null;
let tail = 0;
for (;;) {
const query = cursor === null
? `?limit=${WALK_LIMIT}`
: `?limit=${WALK_LIMIT}&cursor=${encodeURIComponent(cursor)}`;
const res = http.get(url + query, params);
if (res.status !== 200) {
fail(`history tail after ${tail}: ${res.status} ${res.body}`);
}
const body = res.json();
tail += body.items.length;
if (body.next_cursor === null) {
break;
}
cursor = body.next_cursor;
}
return { from_after: hasPool ? pool.last_after : 0, tail };
}
export default function () {}
export function handleSummary(data) {
return { [`${WORK_DIR}/tail.json`]: JSON.stringify(data.setup_data) };
}
+39
View File
@@ -0,0 +1,39 @@
// Сценарий write: ровно COUNT сообщений в чат записи от участников по
// кругу, VUS клиентов одновременно. Читаемый чат не меняется.
import exec from "k6/execution";
import {
SUMMARY_THRESHOLDS,
SUMMARY_TREND_STATS,
WORK_DIR,
sendMessage,
summaryFiles,
syntheticText,
} from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const OFFSET = Number(__ENV.OFFSET || 0);
export const options = {
scenarios: {
write: {
executor: "shared-iterations",
vus: Number(__ENV.VUS),
iterations: Number(__ENV.COUNT),
maxDuration: "10m",
},
},
discardResponseBodies: true,
summaryTrendStats: SUMMARY_TREND_STATS,
thresholds: SUMMARY_THRESHOLDS,
};
export default function () {
const n = OFFSET + exec.scenario.iterationInTest;
const sender = fixture.memberIds[n % fixture.memberIds.length];
sendMessage(fixture.writeChatId, sender, syntheticText("w", n));
}
export function handleSummary(data) {
return summaryFiles(data);
}