Files
mtusi2026lab3/bench/track1/k6/messages.js
T
Alexey BodanyukandClaude Opus 5.5 2033440cdb bench: трек 1 — оркестратор серий, k6 open-loop, py-spy sidecar
- bench/track1/run.py: на каждую конфигурацию x повтор — свежий стенд
  (отдельный compose-проект, пустые volumes), образ API из git-коммита
  (git archive), ступени constant-arrival-rate; CPU каждого контейнера,
  ожидание пула (STATS_LOG_SECONDS), pg_stat_database/pg_stat_statements,
  счётчики HAProxy; raw JSON + results.csv, без токенов.
- compose.bench.yaml: cpuset для k6 / LB+Valkey / PostgreSQL / API, чтобы
  генератор и LB не отнимали CPU у реплик.
- bench/track1/profile.py + pyspy/: py-spy с хешем пакета, профиль одной
  реплики под нагрузкой.
- API: STATS_LOG_SECONDS (по умолчанию выключено) — счётчики пула и CPU
  процесса в лог; API_IMAGE в compose для образа из коммита.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:51:37 +03:00

68 lines
3.1 KiB
JavaScript

// Track 1 workload: OPEN-LOOP arrival rate of "send message" requests through the LB.
// Every iteration = one POST /api/v1/chats/{id}/messages with a NEW Idempotency-Key into one
// of USERS chats (user i writes into chat i, shared with user i+1), so writers are spread over
// many chat rows and no single-row lock dominates. constant-arrival-rate starts iterations at
// RATE/s regardless of response time (no coordinated omission); iterations that cannot start
// because all VUs are busy are counted in dropped_iterations - they are failed demand.
// Phases: `warmup` (not reported) then `measure`. Only status 201 counts as success.
// Env: BASE_URL, RATE, WARMUP, DURATION, MAX_VUS, CHATS_FILE.
import http from 'k6/http';
import { check } from 'k6';
import exec from 'k6/execution';
import { Counter, Trend } from 'k6/metrics';
const BASE = __ENV.BASE_URL || 'http://lb:8080';
const RATE = parseInt(__ENV.RATE || '100', 10);
const WARMUP = __ENV.WARMUP || '10s';
const DURATION = __ENV.DURATION || '20s';
const MAX_VUS = parseInt(__ENV.MAX_VUS || '400', 10);
const ok = new Counter('ok_messages'); // 201 only
const okLatency = new Trend('ok_latency', true); // latency of 201 only
function phase(name, startTime, duration) {
return {
executor: 'constant-arrival-rate', rate: RATE, timeUnit: '1s', duration, startTime,
preAllocatedVUs: Math.min(MAX_VUS, Math.max(20, Math.ceil(RATE / 10))), maxVUs: MAX_VUS,
gracefulStop: '5s', exec: 'send', tags: { phase: name },
};
}
export const options = {
discardResponseBodies: true,
scenarios: { warmup: phase('warmup', '0s', WARMUP), measure: phase('measure', WARMUP, DURATION) },
summaryTrendStats: ['avg', 'p(50)', 'p(95)', 'p(99)', 'max'],
// Thresholds only create per-phase sub-metrics in the summary; they never fail the run.
thresholds: {
'http_reqs{phase:measure}': ['count>=0'],
'http_req_failed{phase:measure}': ['rate>=0'],
'http_req_duration{phase:measure}': ['max>=0'],
'ok_messages{phase:measure}': ['count>=0'],
'ok_latency{phase:measure}': ['max>=0'],
'dropped_iterations{scenario:measure}': ['count>=0'],
'iterations{scenario:measure}': ['count>=0'],
},
};
// Users, sessions and chats are created by bench/track1/run.py before k6 starts (so the timed
// phases start at once); the file with the synthetic tokens is mounted read-only and deleted after.
const chats = JSON.parse(open(__ENV.CHATS_FILE || '/data/chats.json'));
export function send() {
const n = exec.scenario.iterationInTest;
const c = chats[n % chats.length];
const res = http.post(`${BASE}/api/v1/chats/${c.chat}/messages`,
JSON.stringify({ text: `bench ${exec.vu.idInTest}-${n}` }),
{ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${c.token}`,
'Idempotency-Key': `${exec.scenario.name}-${exec.vu.idInTest}-${n}-${Date.now()}` },
tags: { name: 'post_message' }, timeout: '10s' });
if (check(res, { '201': (r) => r.status === 201 })) {
ok.add(1);
okLatency.add(res.timings.duration);
}
}
export function handleSummary(data) {
return { stdout: '\n@@SUMMARY@@' + JSON.stringify(data) + '\n' };
}