forked from mtusi2026/mtusi2026lab3
lab3: путь записи сообщения одним оператором (C2)
Владелец ключа идемпотентности больше не оркестрируется в приложении: проверка членства, заявка ключа, вставка сообщения, инкремент версии чата (якорь инвалидации кэша) и сохранение тела ответа выполняются одним оператором SQL, атомарность которого обеспечивает сам оператор. - messages.repository: createOnce() одним запросом вместо трёх (проверка членства + INSERT + UPDATE version) и явной транзакции; тело ответа строится в SQL и служит источником истины и для первого ответа, и для повторов. - idempotency.repository: read() читает сохранённый ответ вместе с повторной проверкой доступа, delete/purge не изменились; claim/store внутри транзакции больше не нужны. - messages.service: без DatabaseClient и без предварительного chatsService. getForUser в пути записи; ключ обязателен, тело проверяется до обращения к БД, просроченный ключ освобождается и занимается заново. Итог: 1 round trip на запись вместо 8 и 2 вместо 3 на повтор; короче удержание блокировки строки chats, что и проверяется A/B на профиле горячего чата. Проверено: npm run build, tsc, unit-тесты, lint, публичный smoke и black-box набор приложения (включая конкурентный повтор с одним ключом) на стенде с образом mtusi-messenger:lab3-after.
This commit is contained in:
+94
-9
@@ -19,15 +19,16 @@ src/
|
||||
main.ts bootstrap: Fastify, ValidationPipe, shutdown hooks
|
||||
app.module.ts сборка модулей приложения
|
||||
config/ Zod-схема env + глобальный ConfigModule
|
||||
database/ pg.Pool, транзакции, миграции (001, 002)
|
||||
database/ pg.Pool, транзакции, миграции (001..004)
|
||||
redis/ клиент Redis (AOF-совместимый, без offline queue)
|
||||
auth/ Basic-вход, Redis-сессии, logout
|
||||
users/ регистрация (Argon2id), профиль
|
||||
chats/ создание чата в транзакции, список и чтение
|
||||
messages/ отправка сообщения, keyset-история
|
||||
cache/ версионированный кэш истории + lock на страницу
|
||||
idempotency/ журнал Idempotency-Key (claim/read/store/forget/GC)
|
||||
metrics/ /internal/metrics и /internal/metrics/reset
|
||||
health/ liveness/readiness с проверкой зависимостей
|
||||
health/ liveness/readiness с проверкой зависимостей + /internal/lb-check
|
||||
common/
|
||||
http/ cursor (формат+календарь), page (конверт {items,next_cursor}), request-id
|
||||
errors/ exception filter и тип тела ошибки ApiErrorBody
|
||||
@@ -44,7 +45,10 @@ scripts/
|
||||
восстановление из PostgreSQL; отказ зависимости даёт ограниченную ошибку
|
||||
(`503`), а не аварийное завершение процесса; длины строк проверяются в Unicode
|
||||
code points (свой декоратор `@CodePointLength`), как в JSON Schema, а не в
|
||||
UTF-16-единицах.
|
||||
UTF-16-единицах; состояние, от которого зависит корректность (сессии, журнал
|
||||
идемпотентности), живёт только в общих PostgreSQL/Redis — локальных сессий и
|
||||
файлов на диске реплики нет, поэтому `N` взаимозаменяемых реплик за одним LB
|
||||
дают один и тот же результат.
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
@@ -56,10 +60,17 @@ cp .env.example .env
|
||||
password=$(openssl rand -hex 32)
|
||||
sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$password/" .env
|
||||
sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:$password@postgres:5432/messenger|" .env
|
||||
docker compose --env-file .env up -d --build
|
||||
sed -i "s/^METRICS_TOKEN=.*/METRICS_TOKEN=$(openssl rand -hex 16)/" .env
|
||||
make stand-up # сборка + up -d --wait: migrate -> api x API_REPLICAS -> haproxy
|
||||
make wait-ready
|
||||
curl -fsS http://localhost:8080/health/ready
|
||||
for i in 1 2 3 4; do curl -sD- -o /dev/null localhost:8080/health/live | grep -i x-instance-id; done
|
||||
```
|
||||
|
||||
Публичной точкой входа служит HAProxy (`compose.yaml`): реплики API портов не
|
||||
публикуют. `API_REPLICAS` задаёт их число, `API_TOTAL_CPUS` / `API_TOTAL_MEMORY_MB`
|
||||
делятся между ними — это бюджет серии трека 1 (`../REPORT.md`).
|
||||
|
||||
Локальный запуск без Docker (нужны доступные PostgreSQL и Redis):
|
||||
|
||||
```sh
|
||||
@@ -96,7 +107,9 @@ npm run start:dev # или npm run start:prod после
|
||||
| `CACHE_LOCK_TTL_MS` | `1000` | TTL lock-а страницы |
|
||||
| `CACHE_MISS_DELAY_MS` | `0` | искусственная пауза на промахе; влияет только на `naive` |
|
||||
| `METRICS_TOKEN` | — (необязательна) | токен доступа к `/internal/metrics*`; без него endpoint закрыт |
|
||||
| `DRAIN_DELAY_MS` | `5000` | окно дрейна при получении сигнала завершения |
|
||||
| `DRAIN_DELAY_MS` | `5000` (в стенде `3000`) | окно дрейна при `SIGTERM`: реплика сразу перестаёт проходить пробу LB, ждёт этот интервал и только затем закрывает сервер и пулы |
|
||||
| `INSTANCE_ID` | hostname контейнера | значение `X-Instance-Id`; в Docker hostname = короткий ID контейнера, поэтому `scripts/stop-one.sh` находит реплику по нему |
|
||||
| `IDEMPOTENCY_TTL_SECONDS` | `86400` | срок хранения журнала Idempotency-Key (минимум 60) |
|
||||
|
||||
Поддерживаются также `DATABASE_URL_FILE` / `REDIS_URL_FILE`: если заданы, значение
|
||||
читается из файла (docker secrets / Swarm). Подробности и компромиссы —
|
||||
@@ -110,6 +123,7 @@ npm run start:dev # или npm run start:prod после
|
||||
|---|---|---|
|
||||
| `GET /health/live` | нет | процесс жив |
|
||||
| `GET /health/ready` | нет | готовность: PostgreSQL и Redis доступны, иначе `503` |
|
||||
| `GET /internal/lb-check` | нет | проба балансировщика: только флаг дрейна, без обращения к БД/Redis |
|
||||
| `POST /api/v1/users` | нет | регистрация с паролем (Argon2id) |
|
||||
| `POST /api/v1/auth/sessions` | `Basic` | вход, выдаёт opaque Bearer-токен |
|
||||
| `DELETE /api/v1/auth/sessions/current` | `Bearer` | отзыв текущей сессии, `204` |
|
||||
@@ -117,7 +131,7 @@ npm run start:dev # или npm run start:prod после
|
||||
| `POST /api/v1/chats` | `Bearer` | создание чата (транзакция) |
|
||||
| `GET /api/v1/chats` | `Bearer` | список доступных чатов |
|
||||
| `GET /api/v1/chats/:chatId` | `Bearer` | чат по id (чужой — `404`) |
|
||||
| `POST /api/v1/chats/:chatId/messages` | `Bearer` | отправка сообщения |
|
||||
| `POST /api/v1/chats/:chatId/messages` | `Bearer` + обязательный `Idempotency-Key` | отправка сообщения (см. ниже) |
|
||||
| `GET /api/v1/chats/:chatId/messages` | `Bearer` | история, keyset-пагинация `(created_at, id)` |
|
||||
| `GET /internal/metrics` | `Bearer METRICS_TOKEN` | счётчики и агрегаты латентности |
|
||||
| `POST /internal/metrics/reset` | `Bearer METRICS_TOKEN` | сброс счётчиков (`200`) |
|
||||
@@ -137,6 +151,7 @@ npm run start:dev # или npm run start:prod после
|
||||
| `npm test` / `npm run test:unit` | unit-тесты (vitest) |
|
||||
| `npm run test:e2e` | black-box набор против запущенного API (см. ниже) |
|
||||
| `npm run test:dependencies` | автоматическая проверка отказов Redis/PostgreSQL: останавливает и поднимает контейнеры Compose-стенда |
|
||||
| `npm run idempotency:gc` | ручной прогон удаления просроченных записей Idempotency-Key |
|
||||
| `npm run lint` | oxlint по `src/` и `test/` |
|
||||
| `npm run format` | prettier |
|
||||
| `npm run graph` | граф модулей и провайдеров через nestjs-spelunker (пишет `../docs/architecture/`) |
|
||||
@@ -183,15 +198,85 @@ make test-dependencies
|
||||
подтверждённое сообщение и новая запись. Каждый запрос к остановленной БД ждёт
|
||||
`DATABASE_CONNECTION_TIMEOUT_MS`, поэтому набор идёт около 40 секунд.
|
||||
|
||||
## Реплики, балансировка и остановка реплики
|
||||
|
||||
Все реплики запускаются из одного образа и одного `compose.yaml`; API портов не
|
||||
публикует, трафик идёт только через HAProxy. Состояние, от которого зависит
|
||||
корректность, лежит в общих PostgreSQL и Redis, поэтому клиент с одним
|
||||
Bearer-токеном обслуживается любой репликой:
|
||||
|
||||
```sh
|
||||
make test BASE_URL=http://localhost:8080 # сквозной сценарий через LB
|
||||
python3 scripts/lab3/lab3.py check spread # распределение X-Instance-Id
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh # отказ одной реплики
|
||||
scripts/start-replica.sh # вернуть остановленную реплику
|
||||
```
|
||||
|
||||
- `X-Instance-Id` = `INSTANCE_ID` или hostname процесса, стабилен для процесса;
|
||||
в Docker hostname контейнера — короткий ID, поэтому `scripts/stop-one.sh`
|
||||
останавливает ровно ту реплику, которую обслужил запрос теста. Тот же заголовок
|
||||
добавляется к ответам об ошибках, которые формируются фильтром до интерсептора.
|
||||
- **Остановка (`SIGTERM`)** идёт в порядке «сначала дрейн, потом разбор ресурсов»:
|
||||
реплика помечается not-ready (проба LB и `/health/ready` начинают отвечать
|
||||
`503`), `DRAIN_DELAY_MS` ждёт, пока LB её исключит (обнаружение ≈1 s), и лишь
|
||||
затем закрываются HTTP-сервер, пул PostgreSQL и соединение Redis. Если
|
||||
полагаться на стандартный порядок Nest (`onModuleDestroy` вызывает закрытие
|
||||
пулов раньше `beforeApplicationShutdown`), реплика какое-то время остаётся в
|
||||
ротации уже без ресурсов — это и было причиной явной последовательности в
|
||||
`src/main.ts`.
|
||||
- `/internal/lb-check` намеренно не проверяет БД и Redis: отказ общей
|
||||
зависимости нельзя исправить выводом реплик из ротации, иначе LB ответит
|
||||
клиенту своей HTML-страницей вместо ограниченного `503 unavailable`.
|
||||
`/health/ready` остаётся операторским сигналом и healthcheck'ом контейнера.
|
||||
|
||||
## Идемпотентность отправки сообщения
|
||||
|
||||
`POST /api/v1/chats/{chatId}/messages` требует заголовок `Idempotency-Key`
|
||||
(ASCII `[A-Za-z0-9._:-]{1,128}`). Область уникальности — пользователь + метод +
|
||||
путь чата + ключ, поэтому одинаковый ключ у разных пользователей или в разных
|
||||
чатах не конфликтует. Журнал — таблица `idempotency_keys` (миграция 003), то
|
||||
есть общая для всех реплик.
|
||||
|
||||
| Ситуация | Ответ |
|
||||
|---|---|
|
||||
| Заголовок отсутствует, пуст или не подходит под шаблон | `400 invalid_request` (до обращения к БД) |
|
||||
| Первый запрос с ключом | `201` и сообщение; заявка и тело ответа записываются одной транзакцией |
|
||||
| Повтор того же тела с тем же ключом | тот же `201` и тот же JSON (включая `id` и `created_at`), новое сообщение не создаётся |
|
||||
| Другое тело с тем же ключом | `409 conflict` |
|
||||
| Повтор после `404` (нет доступа к чату) | `404`, ключ не занят: заявка откатывается вместе с транзакцией |
|
||||
| Ключ старше `IDEMPOTENCY_TTL_SECONDS` | запись удаляется, ключ считается свободным |
|
||||
| Одновременные повторы через разные реплики | ровно одно сообщение: заявка берётся `INSERT ... ON CONFLICT DO NOTHING`, повтор читает сохранённый ответ |
|
||||
|
||||
Отпечаток тела считается по валидированному DTO с фиксированным порядком полей,
|
||||
поэтому порядок ключей в JSON не влияет на результат. Транзиентные сбои
|
||||
PostgreSQL (`57014`, `40001`, `40P01`) и обрывы соединения отдаются как
|
||||
`503 unavailable` и не фиксируются как окончательный результат: клиент может
|
||||
безопасно повторить запрос с тем же ключом. Просроченные записи удаляются
|
||||
фоновым проходом (`idempotency.purged` в метриках) под
|
||||
`pg_try_advisory_xact_lock`, а также вручную: `npm run idempotency:gc`.
|
||||
|
||||
## Харнесс экспериментов
|
||||
|
||||
Уровни 3/4 и трек 1 обслуживает `../scripts/lab3/lab3.py` (только stdlib) и
|
||||
профили k6 в `../scripts/load/`: `run`, `sweep`, `growth`, `failover`,
|
||||
`rolling-update`, `ab`, `analyze`, `watch`, `check`, `quiesce`, `track1`.
|
||||
Сырые результаты прогонов, манифесты условий измерения и графики складываются в
|
||||
`../evidence/track1/`. Подробности — в `../REPORT.md` и
|
||||
`../evidence/README.md`.
|
||||
|
||||
## Метрики
|
||||
|
||||
`GET /internal/metrics` возвращает `{counters, latency_ms}`: именованные SQL-метки,
|
||||
`GET /internal/metrics` возвращает `{counters, latency_ms, instance_id, build_id}`: именованные SQL-метки,
|
||||
операции Redis, `cache_hit`/`cache_miss`/`cache_lock_wait`, `session_get/set/del`,
|
||||
`request_count` и процентили латентности (буфер ограничен). Деградации
|
||||
наблюдаемы отдельными счётчиками: `cache_fallback`, `cache_write_error`,
|
||||
`cache_unlock_error`, `cache_lock_timeout`, `cache_corrupt_entry`,
|
||||
`database.pool_error`, `database.rollback_error`, `redis.error`.
|
||||
`database.pool_error`, `database.rollback_error`, `redis.error`, а также
|
||||
идемпотентность: `idempotency.claim`, `idempotency.replay`, `idempotency.conflict`,
|
||||
`idempotency.claim_lost`, `idempotency.released`, `idempotency.purged`,
|
||||
`idempotency.purge_error`, `messages.write`.
|
||||
|
||||
Счётчики локальны процессу: при нескольких репликах их нельзя суммировать как
|
||||
распределённый снимок, а рестарт API обнуляет их (данные PostgreSQL и Redis при
|
||||
этом не затрагиваются).
|
||||
этом не затрагиваются). `instance_id` и `build_id` позволяют сопоставить ответ
|
||||
конкретной реплике и сборке — этим пользуются rolling update и эксперименты.
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type pg from 'pg';
|
||||
import pg from 'pg';
|
||||
import { DatabaseClient } from '../../database/database.client.js';
|
||||
import type { Message } from '../message.js';
|
||||
|
||||
// A committed row always carries the response: the claim and the stored response
|
||||
// are written in the same transaction, so there is no poisoned intermediate
|
||||
// state to re-check at replay time.
|
||||
// are written by one statement, so there is no poisoned intermediate state to
|
||||
// re-check at replay time.
|
||||
export type IdempotencyRecord = {
|
||||
request_fingerprint: string;
|
||||
status_code: number;
|
||||
response_body: Message;
|
||||
created_at: Date | string;
|
||||
expired: boolean;
|
||||
is_member: boolean;
|
||||
};
|
||||
|
||||
const PURGE_BATCH_LIMIT = 1000;
|
||||
@@ -21,88 +22,48 @@ const PURGE_BATCHES = 10;
|
||||
export class IdempotencyRepository {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
/** True when this request created the claim, i.e. it owns the side effect. */
|
||||
async claim(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
fingerprint: string,
|
||||
): Promise<boolean> {
|
||||
const result = await client.query({
|
||||
text: `INSERT INTO idempotency_keys (user_id, method, path, key, request_fingerprint)
|
||||
VALUES ($1, 'POST', $2, $3, $4)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING created_at`,
|
||||
values: [userId, path, key, fingerprint],
|
||||
});
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the stored result and re-checks access in the same round trip: a
|
||||
* replay must still prove that the caller may read this chat.
|
||||
*/
|
||||
async read(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
chatId: string,
|
||||
ttlSeconds: number,
|
||||
): Promise<IdempotencyRecord | undefined> {
|
||||
const result = await client.query<IdempotencyRecord>({
|
||||
text: `SELECT request_fingerprint, status_code, response_body, created_at,
|
||||
created_at < now() - make_interval(secs => $4::double precision) AS expired
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
|
||||
values: [userId, path, key, ttlSeconds],
|
||||
});
|
||||
const result = await this.database.query<IdempotencyRecord>(
|
||||
'idempotency.read',
|
||||
`SELECT k.request_fingerprint, k.status_code, k.response_body, k.created_at,
|
||||
k.created_at < now() - make_interval(secs => $4::double precision) AS expired,
|
||||
EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $5 AND user_id = $1
|
||||
) AS is_member
|
||||
FROM idempotency_keys k
|
||||
WHERE k.user_id = $1 AND k.method = 'POST' AND k.path = $2 AND k.key = $3`,
|
||||
[userId, path, key, ttlSeconds, chatId],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async store(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
statusCode: number,
|
||||
message: Message,
|
||||
): Promise<void> {
|
||||
await client.query({
|
||||
text: `UPDATE idempotency_keys
|
||||
SET status_code = $4, response_body = $5::jsonb, message_id = $6
|
||||
async forget(userId: string, path: string, key: string): Promise<void> {
|
||||
await this.database.query(
|
||||
'idempotency.forget',
|
||||
`DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
|
||||
values: [
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
statusCode,
|
||||
JSON.stringify(message),
|
||||
message.id,
|
||||
],
|
||||
});
|
||||
[userId, path, key],
|
||||
);
|
||||
}
|
||||
|
||||
async forget(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
): Promise<void> {
|
||||
await client.query({
|
||||
text: `DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
|
||||
values: [userId, path, key],
|
||||
});
|
||||
}
|
||||
|
||||
async isMember(
|
||||
client: pg.PoolClient,
|
||||
chatId: string,
|
||||
userId: string,
|
||||
): Promise<boolean> {
|
||||
const result = await client.query<{ is_member: boolean }>({
|
||||
text: `SELECT EXISTS (
|
||||
async isMember(chatId: string, userId: string): Promise<boolean> {
|
||||
const result = await this.database.query<{ is_member: boolean }>(
|
||||
'messages.checkMembership',
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2
|
||||
) AS is_member`,
|
||||
values: [chatId, userId],
|
||||
});
|
||||
[chatId, userId],
|
||||
);
|
||||
return result.rows[0]?.is_member === true;
|
||||
}
|
||||
|
||||
@@ -113,7 +74,7 @@ export class IdempotencyRepository {
|
||||
* of deleted rows (0 when another replica is purging).
|
||||
*/
|
||||
async purgeExpired(ttlSeconds: number): Promise<number> {
|
||||
const client = await this.database.pool.connect();
|
||||
const client: pg.PoolClient = await this.database.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
try {
|
||||
@@ -126,15 +87,15 @@ export class IdempotencyRepository {
|
||||
}
|
||||
let purged = 0;
|
||||
for (let batch = 0; batch < PURGE_BATCHES; batch += 1) {
|
||||
const result = await client.query({
|
||||
text: `DELETE FROM idempotency_keys
|
||||
const result = await client.query(
|
||||
`DELETE FROM idempotency_keys
|
||||
WHERE ctid IN (
|
||||
SELECT ctid FROM idempotency_keys
|
||||
WHERE created_at < now() - make_interval(secs => $1::double precision)
|
||||
LIMIT ${PURGE_BATCH_LIMIT}
|
||||
)`,
|
||||
values: [ttlSeconds],
|
||||
});
|
||||
[ttlSeconds],
|
||||
);
|
||||
const deleted = result.rowCount ?? 0;
|
||||
purged += deleted;
|
||||
if (deleted < PURGE_BATCH_LIMIT) break;
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type pg from 'pg';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import type { Cursor } from '../common/http/cursor.js';
|
||||
import type { Message } from './message.js';
|
||||
@@ -16,6 +15,15 @@ type MessageRow = {
|
||||
created_at: Date | string;
|
||||
};
|
||||
|
||||
export type CreateOnceRequest = {
|
||||
userId: string;
|
||||
chatId: string;
|
||||
path: string;
|
||||
key: string;
|
||||
fingerprint: string;
|
||||
text: string;
|
||||
};
|
||||
|
||||
function toMessage(row: MessageRow): Message {
|
||||
return {
|
||||
id: row.id,
|
||||
@@ -26,36 +34,66 @@ function toMessage(row: MessageRow): Message {
|
||||
};
|
||||
}
|
||||
|
||||
// Один оператор делает всё, что нужно пути записи: проверяет членство, занимает
|
||||
// ключ идемпотентности, вставляет сообщение, увеличивает версию чата (якорь
|
||||
// инвалидации кэша истории) и сохраняет тело ответа. Атомарность даёт сам
|
||||
// оператор, поэтому явная транзакция и отдельные round trip'ы не нужны; тело
|
||||
// ответа строится в SQL и служит единственным источником истины и для первого
|
||||
// ответа, и для повторов.
|
||||
//
|
||||
// Зависимости CTE задают порядок выполнения: claim -> inserted -> bumped.
|
||||
const CREATE_ONCE_SQL = `
|
||||
WITH claim AS (
|
||||
INSERT INTO idempotency_keys (user_id, method, path, key, request_fingerprint,
|
||||
status_code, response_body, message_id)
|
||||
SELECT $1, 'POST', $2, $3, $4, 201,
|
||||
jsonb_build_object(
|
||||
'id', $5::uuid,
|
||||
'chat_id', $7::uuid,
|
||||
'sender_id', $1::uuid,
|
||||
'text', $6::text,
|
||||
'created_at', to_char(date_trunc('milliseconds', now()) AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')),
|
||||
$5::uuid
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $7::uuid AND user_id = $1
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING response_body
|
||||
), inserted AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $5::uuid, $7::uuid, $1::uuid, $6::text, date_trunc('milliseconds', now())
|
||||
FROM claim
|
||||
RETURNING id
|
||||
), bumped AS (
|
||||
UPDATE chats SET message_version = message_version + 1
|
||||
WHERE id = $7::uuid AND EXISTS (SELECT 1 FROM inserted)
|
||||
)
|
||||
SELECT response_body FROM claim`;
|
||||
|
||||
@Injectable()
|
||||
export class MessagesRepository {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
// The caller owns the transaction: the message insert, the chat version bump
|
||||
// and the idempotency claim must commit or roll back as one unit.
|
||||
async create(
|
||||
client: pg.PoolClient,
|
||||
chatId: string,
|
||||
senderId: string,
|
||||
text: string,
|
||||
): Promise<Message> {
|
||||
const id = randomUUID();
|
||||
const membership = await client.query({
|
||||
name: 'messages.checkMembership',
|
||||
text: 'SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2',
|
||||
values: [chatId, senderId],
|
||||
});
|
||||
if (!membership.rowCount) throw new NotFoundException();
|
||||
const result = await client.query<MessageRow>({
|
||||
name: 'messages.insert',
|
||||
text: 'INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at',
|
||||
values: [id, chatId, senderId, text],
|
||||
});
|
||||
await client.query({
|
||||
name: 'messages.incrementVersion',
|
||||
text: 'UPDATE chats SET message_version = message_version + 1 WHERE id = $1',
|
||||
values: [chatId],
|
||||
});
|
||||
return toMessage(result.rows[0]);
|
||||
/**
|
||||
* Returns the created message, or undefined when the key is already taken or
|
||||
* the caller is not a member of the chat (both leave no side effect).
|
||||
*/
|
||||
async createOnce(request: CreateOnceRequest): Promise<Message | undefined> {
|
||||
const result = await this.database.query<{ response_body: Message }>(
|
||||
'messages.createIdempotent',
|
||||
CREATE_ONCE_SQL,
|
||||
[
|
||||
request.userId,
|
||||
request.path,
|
||||
request.key,
|
||||
request.fingerprint,
|
||||
randomUUID(),
|
||||
request.text,
|
||||
request.chatId,
|
||||
],
|
||||
);
|
||||
return result.rows[0]?.response_body;
|
||||
}
|
||||
|
||||
async getVersion(chatId: string, userId: string): Promise<bigint> {
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type pg from 'pg';
|
||||
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
|
||||
import type { Page } from '../common/http/page.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import { ChatsService } from '../chats/chats.service.js';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import type { CreateMessageDto } from './dto/create-message.dto.js';
|
||||
import type { Message } from './message.js';
|
||||
@@ -27,16 +24,12 @@ import {
|
||||
} from './idempotency/idempotency.js';
|
||||
import { IdempotencyRepository } from './idempotency/idempotency.repository.js';
|
||||
|
||||
// A claim row can disappear between our failed insert attempt and the read
|
||||
// (the previous owner rolled back), so a bounded retry is part of the protocol.
|
||||
// Один повтор нужен только для просроченного ключа: запись удаляется, и тот же
|
||||
// оператор занимает ключ заново. Больше трёх кругов означает, что ключ
|
||||
// перехватывают параллельные запросы, и честнее вернуть 503, чем крутиться.
|
||||
const MAX_CLAIM_ATTEMPTS = 3;
|
||||
const PURGE_EVERY_REQUESTS = 512;
|
||||
|
||||
type CreateOutcome =
|
||||
| { kind: 'created'; message: Message }
|
||||
| { kind: 'replayed'; message: Message }
|
||||
| { kind: 'retry' };
|
||||
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
private readonly logger = new Logger(MessagesService.name);
|
||||
@@ -47,7 +40,6 @@ export class MessagesService {
|
||||
private readonly chatsService: ChatsService,
|
||||
private readonly cache: MessagesCacheService,
|
||||
private readonly idempotency: IdempotencyRepository,
|
||||
private readonly database: DatabaseClient,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
@@ -58,116 +50,78 @@ export class MessagesService {
|
||||
currentUser: User,
|
||||
rawKey: string | string[] | undefined,
|
||||
): Promise<Message> {
|
||||
// The key is validated before anything else: a missing, malformed or
|
||||
// duplicated header is a client error, never a stored result.
|
||||
// Ключ и тело проверяются до обращения к БД: клиентская ошибка не должна
|
||||
// создавать заявку и не должна зависеть от состояния хранилища.
|
||||
if (typeof rawKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(rawKey))
|
||||
throw new BadRequestException(
|
||||
'Idempotency-Key header is required',
|
||||
);
|
||||
if ([...input.text].every((character) => /\s/u.test(character)))
|
||||
throw new BadRequestException('Message text cannot be blank');
|
||||
await this.chatsService.getForUser(chatId, currentUser);
|
||||
|
||||
const path = messagesPath(chatId);
|
||||
const fingerprint = idempotencyFingerprint(input);
|
||||
const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS');
|
||||
for (let attempt = 1; attempt <= MAX_CLAIM_ATTEMPTS; attempt += 1) {
|
||||
const outcome = await this.database.withTransaction((client) =>
|
||||
this.attemptCreate(client, {
|
||||
chatId,
|
||||
path,
|
||||
key: rawKey,
|
||||
fingerprint,
|
||||
text: input.text,
|
||||
userId: currentUser.id,
|
||||
}),
|
||||
);
|
||||
if (outcome.kind !== 'retry') {
|
||||
const created = await this.messagesRepository.createOnce({
|
||||
userId: currentUser.id,
|
||||
chatId,
|
||||
path,
|
||||
key: rawKey,
|
||||
fingerprint,
|
||||
text: input.text,
|
||||
});
|
||||
if (created) {
|
||||
this.metrics.increment('idempotency.claim');
|
||||
this.metrics.increment('messages.write');
|
||||
this.scheduleExpiredPurge();
|
||||
return outcome.message;
|
||||
return created;
|
||||
}
|
||||
|
||||
const stored = await this.idempotency.read(
|
||||
currentUser.id,
|
||||
path,
|
||||
rawKey,
|
||||
chatId,
|
||||
ttl,
|
||||
);
|
||||
if (!stored) {
|
||||
// Заявки нет: либо запрос не имеет доступа к чату (404), либо
|
||||
// чужую заявку сняли между нашими двумя запросами (503).
|
||||
if (!(await this.idempotency.isMember(chatId, currentUser.id)))
|
||||
throw new NotFoundException();
|
||||
this.metrics.increment('idempotency.claim_lost');
|
||||
throw new ServiceUnavailableException(
|
||||
'Idempotency key could not be claimed',
|
||||
);
|
||||
}
|
||||
if (stored.request_fingerprint !== fingerprint) {
|
||||
this.metrics.increment('idempotency.conflict');
|
||||
throw new ConflictException(
|
||||
'Idempotency key reused with a different body',
|
||||
);
|
||||
}
|
||||
if (stored.expired) {
|
||||
this.metrics.increment('idempotency.released');
|
||||
await this.idempotency.forget(
|
||||
currentUser.id,
|
||||
path,
|
||||
rawKey,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!stored.is_member) throw new NotFoundException();
|
||||
this.metrics.increment('idempotency.replay');
|
||||
return stored.response_body;
|
||||
}
|
||||
throw new ServiceUnavailableException(
|
||||
'Idempotency key could not be claimed',
|
||||
);
|
||||
}
|
||||
|
||||
// One attempt = one transaction: the claim, the side effect and the stored
|
||||
// response commit together, so a retry can never duplicate a message and a
|
||||
// failure never leaves a half-finished claim behind.
|
||||
private async attemptCreate(
|
||||
client: pg.PoolClient,
|
||||
request: {
|
||||
chatId: string;
|
||||
path: string;
|
||||
key: string;
|
||||
fingerprint: string;
|
||||
text: string;
|
||||
userId: string;
|
||||
},
|
||||
): Promise<CreateOutcome> {
|
||||
const { chatId, path, key, fingerprint, text, userId } = request;
|
||||
const claimed = await this.idempotency.claim(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
fingerprint,
|
||||
);
|
||||
if (claimed) {
|
||||
this.metrics.increment('idempotency.claim');
|
||||
const message = await this.messagesRepository.create(
|
||||
client,
|
||||
chatId,
|
||||
userId,
|
||||
text,
|
||||
);
|
||||
await this.idempotency.store(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
HttpStatus.CREATED,
|
||||
message,
|
||||
);
|
||||
this.metrics.increment('messages.write');
|
||||
return { kind: 'created', message };
|
||||
}
|
||||
|
||||
const record = await this.idempotency.read(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS'),
|
||||
);
|
||||
if (!record) {
|
||||
// The previous owner aborted, so nothing was created and the key is
|
||||
// free again.
|
||||
this.metrics.increment('idempotency.claim_lost');
|
||||
return { kind: 'retry' };
|
||||
}
|
||||
if (record.request_fingerprint !== fingerprint) {
|
||||
this.metrics.increment('idempotency.conflict');
|
||||
throw new ConflictException(
|
||||
'Idempotency key reused with a different body',
|
||||
);
|
||||
}
|
||||
if (record.expired) {
|
||||
this.metrics.increment('idempotency.released');
|
||||
await this.idempotency.forget(client, userId, path, key);
|
||||
return { kind: 'retry' };
|
||||
}
|
||||
// A replay re-checks access, as the contract requires: the stored result
|
||||
// is only returned to a caller that may still read this chat.
|
||||
if (!(await this.idempotency.isMember(client, chatId, userId)))
|
||||
throw new NotFoundException();
|
||||
this.metrics.increment('idempotency.replay');
|
||||
return { kind: 'replayed', message: record.response_body };
|
||||
}
|
||||
|
||||
// Expired claims are storage hygiene, not part of the request: the pass runs
|
||||
// outside the request transaction, at most once per PURGE_EVERY_REQUESTS
|
||||
// successful writes, and its failure never changes the client's result.
|
||||
// outside the request path, at most once per PURGE_EVERY_REQUESTS successful
|
||||
// writes, and its failure never changes the client's result.
|
||||
private scheduleExpiredPurge(): void {
|
||||
this.requestsSincePurge += 1;
|
||||
if (this.requestsSincePurge < PURGE_EVERY_REQUESTS) return;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
|
||||
> app@0.0.1 test:e2e
|
||||
> vitest run --config ./vitest.config.e2e.ts -t idempotency
|
||||
|
||||
|
||||
RUN v4.1.11 /home/tomato/Projects/VP/mtusi2026lab3/app
|
||||
|
||||
|
||||
Test Files 1 passed | 1 skipped (2)
|
||||
Tests 4 passed | 12 skipped (16)
|
||||
Start at 22:48:21
|
||||
Duration 1.10s (transform 124ms, setup 0ms, import 262ms, tests 798ms, environment 0ms)
|
||||
|
||||
The plugin "vite-tsconfig-paths" is detected. Vite now supports tsconfig paths resolution natively via the resolve.tsconfigPaths option. You can remove the plugin and set resolve.tsconfigPaths: true in your Vite config instead.
|
||||
+327
-108
@@ -45,6 +45,7 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
ENV_FILE = ROOT / '.env'
|
||||
STAND_ENV = ROOT / '.env.stand'
|
||||
STAND_STATE = ROOT / '.env.stand.json'
|
||||
QUIESCE_STATE = ROOT / '.lab3-quiesce.json'
|
||||
RAW_DIR = ROOT / 'evidence/track1/raw'
|
||||
TRACK1_DIR = ROOT / 'evidence/track1'
|
||||
@@ -172,7 +173,7 @@ def render_stand_env(config: dict) -> str:
|
||||
|
||||
|
||||
def load_stand_config() -> dict:
|
||||
stored = read_json(STAND_ENV.with_suffix('.json'), None)
|
||||
stored = read_json(STAND_STATE, None)
|
||||
config = dict(DEFAULT_STAND)
|
||||
if STAND_ENV.exists():
|
||||
for line in STAND_ENV.read_text().splitlines():
|
||||
@@ -191,11 +192,20 @@ def numeric(value: str) -> float | int:
|
||||
|
||||
|
||||
def save_stand_config(config: dict) -> dict:
|
||||
STAND_ENV.write_text(render_stand_env(config))
|
||||
write_json(
|
||||
STAND_ENV.with_suffix('.json'),
|
||||
{key: str(value) for key, value in config.items()},
|
||||
)
|
||||
"""Пишет .env.stand и его машинно-читаемую копию.
|
||||
|
||||
Копия сохраняется уже с производными значениями (лимиты на реплику), иначе
|
||||
следующие запуски подхватили бы устаревшие лимиты, а манифесты прогонов
|
||||
показывали бы не те числа, что реально применены к контейнерам.
|
||||
"""
|
||||
rendered = render_stand_env(config)
|
||||
STAND_ENV.write_text(rendered)
|
||||
values = {
|
||||
line.split('=', 1)[0]: line.split('=', 1)[1]
|
||||
for line in rendered.splitlines()
|
||||
if '=' in line and not line.startswith('#')
|
||||
}
|
||||
write_json(STAND_STATE, values)
|
||||
return config
|
||||
|
||||
|
||||
@@ -229,12 +239,44 @@ def wait_for_lb(timeout: float = 120) -> None:
|
||||
raise SystemExit(f'stand did not become ready within {timeout}s: {last}')
|
||||
|
||||
|
||||
def container_ids(service: str = 'api') -> list[str]:
|
||||
def lb_backends_up() -> int:
|
||||
"""Число backend-слотов LB в состоянии UP (без строк FRONTEND/BACKEND)."""
|
||||
try:
|
||||
with urllib.request.urlopen(LB_STATS_URL, timeout=3) as response:
|
||||
text = response.read().decode('utf-8', 'replace')
|
||||
except OSError:
|
||||
return 0
|
||||
lines = text.splitlines()
|
||||
if lines and lines[0].startswith('#'):
|
||||
lines[0] = lines[0].lstrip('#').lstrip()
|
||||
return sum(
|
||||
1
|
||||
for row in csv.DictReader(lines)
|
||||
if row.get('pxname') == 'api'
|
||||
and re.match(r'^api\d+$', row.get('svname', ''))
|
||||
and row.get('status') == 'UP'
|
||||
)
|
||||
|
||||
|
||||
def wait_for_replicas(expected: int, timeout: float = 180) -> list[str]:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
mapping = replica_map()
|
||||
if len(mapping) >= expected and lb_backends_up() >= expected:
|
||||
return sorted(mapping)
|
||||
time.sleep(1)
|
||||
raise SystemExit(
|
||||
f'ожидалось {expected} реплик, видно {len(replica_map())} контейнеров и {lb_backends_up()} UP-слотов LB'
|
||||
)
|
||||
|
||||
|
||||
def container_ids(service: str = 'api', *, include_stopped: bool = False) -> list[str]:
|
||||
result = run_command(
|
||||
[
|
||||
'docker',
|
||||
'ps',
|
||||
'-q',
|
||||
*(['-a'] if include_stopped else []),
|
||||
'--filter',
|
||||
f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter',
|
||||
@@ -727,13 +769,18 @@ def k6_run(script: str, label: str, env: dict[str, str], timeout: float) -> dict
|
||||
|
||||
|
||||
def load_env(profile: str, mode: str, spread: str, label: str) -> dict[str, str]:
|
||||
return {
|
||||
env = {
|
||||
'BASE_URL': 'http://haproxy:8080',
|
||||
'PROFILE': spread,
|
||||
'MODE': mode,
|
||||
'CHATS': str(CHATS),
|
||||
'LABEL': label,
|
||||
}
|
||||
if os.environ.get('LAB3_MAX_VUS'):
|
||||
env['MAX_VUS'] = os.environ['LAB3_MAX_VUS']
|
||||
if os.environ.get('LAB3_PRE_VUS'):
|
||||
env['PRE_VUS'] = os.environ['LAB3_PRE_VUS']
|
||||
return env
|
||||
|
||||
|
||||
def run_measured(
|
||||
@@ -821,6 +868,12 @@ def write_raw(
|
||||
'dataset': dataset_size(),
|
||||
'versions': image_versions(),
|
||||
'host': {'cpus': bench_cpus(), 'background': host_background()},
|
||||
'generator': {
|
||||
'cpus': stand.get('LOADGEN_CPUS'),
|
||||
'memory': stand.get('LOADGEN_MEMORY'),
|
||||
'max_vus': os.environ.get('LAB3_MAX_VUS', '200'),
|
||||
'pre_vus': os.environ.get('LAB3_PRE_VUS', '60'),
|
||||
},
|
||||
'commit': run_command(['git', 'rev-parse', 'HEAD'], check=False).stdout.strip(),
|
||||
'quiesce': read_json(QUIESCE_STATE, None),
|
||||
'phases': phases,
|
||||
@@ -1111,10 +1164,13 @@ def cmd_check(args) -> None:
|
||||
print(json.dumps({'replicas': replica_map(), 'haproxy': haproxy_stats(Sampler()._haproxy() or [])}, ensure_ascii=False, indent=1))
|
||||
elif args.what == 'idempotency':
|
||||
LEVEL4_DIR.mkdir(parents=True, exist_ok=True)
|
||||
result = run_command(
|
||||
['npx', 'vitest', 'run', '--config', './vitest.config.e2e.ts', '-t', 'idempotency'],
|
||||
check=False,
|
||||
timeout=600,
|
||||
result = subprocess.run(
|
||||
['npm', 'run', 'test:e2e', '--', '-t', 'idempotency'],
|
||||
cwd=ROOT / 'app',
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=900,
|
||||
env={**os.environ, 'API_BASE_URL': BASE_URL},
|
||||
)
|
||||
output = result.stdout + result.stderr
|
||||
(LEVEL4_DIR / 'idempotency-concurrency.txt').write_text(output, encoding='utf-8')
|
||||
@@ -1131,6 +1187,14 @@ def cmd_run(args) -> None:
|
||||
overrides['API_REPLICAS'] = str(args.replicas)
|
||||
if args.pool:
|
||||
overrides['DATABASE_POOL_MAX'] = str(args.pool)
|
||||
if args.loadgen_cpus:
|
||||
overrides['LOADGEN_CPUS'] = str(args.loadgen_cpus)
|
||||
if args.lb_cpus:
|
||||
overrides['LB_CPUS'] = str(args.lb_cpus)
|
||||
if args.api_total_cpus:
|
||||
overrides['API_TOTAL_CPUS'] = str(args.api_total_cpus)
|
||||
if args.pg_cpus:
|
||||
overrides['PG_CPUS'] = str(args.pg_cpus)
|
||||
ensure_stand(overrides)
|
||||
profile = args.profile
|
||||
ladder = [int(value) for value in args.ladder.split(',')] if args.ladder else None
|
||||
@@ -1183,10 +1247,21 @@ def report_series(profile: str, prefix: str) -> None:
|
||||
write_markdown(TRACK1_DIR / f'summary-live-{profile}.md', f'Текущие агрегаты {profile}', lines)
|
||||
|
||||
|
||||
def configuration_key(label: str) -> str:
|
||||
"""Ключ конфигурации: метки вида <профиль>#<конфигурация>#rep<N>.
|
||||
|
||||
Без второго сегмента повторные прогоны разных конфигураций слились бы в одну
|
||||
таблицу (например, все N серии A), а A/B-стороны 'ab#A'/'ab#B' — в одну
|
||||
группу 'ab'.
|
||||
"""
|
||||
parts = label.split('#')
|
||||
return '#'.join(parts[:2]) if len(parts) > 1 else parts[0]
|
||||
|
||||
|
||||
def group_configurations(labels: list[str]) -> dict[str, list[str]]:
|
||||
groups: dict[str, list[str]] = {}
|
||||
for label in labels:
|
||||
groups.setdefault(label.split('#')[0], []).append(label)
|
||||
groups.setdefault(configuration_key(label), []).append(label)
|
||||
return {key: sorted(value) for key, value in sorted(groups.items())}
|
||||
|
||||
|
||||
@@ -1219,11 +1294,24 @@ def cmd_growth(args) -> None:
|
||||
],
|
||||
}
|
||||
log(f'серия роста {args.series} на темпе {rate} req/s (80% от колена {args.base_profile})')
|
||||
# Каждая точка отличается от базовой конфигурации ровно одним ресурсом:
|
||||
# остальные значения прибиты к базовым, иначе после точки «API x2» следующий
|
||||
# ресурс мерился бы уже с удвоенным бюджетом API.
|
||||
baseline = {
|
||||
'API_REPLICAS': '4',
|
||||
'API_TOTAL_CPUS': str(DEFAULT_STAND['API_TOTAL_CPUS']),
|
||||
'PG_CPUS': str(DEFAULT_STAND['PG_CPUS']),
|
||||
'DATABASE_POOL_MAX': str(DEFAULT_STAND['DATABASE_POOL_MAX']),
|
||||
'LB_CPUS': str(DEFAULT_STAND['LB_CPUS']),
|
||||
}
|
||||
for point in points[args.series]:
|
||||
overrides = {'API_REPLICAS': '4', **{key: value for key, value in point.items() if key != 'label'}}
|
||||
overrides = {
|
||||
**baseline,
|
||||
**{key: value for key, value in point.items() if key != 'label'},
|
||||
}
|
||||
ensure_stand(overrides)
|
||||
run_measured(
|
||||
f'growth#{point["label"]}',
|
||||
f'growth#{point["label"]}{args.suffix}',
|
||||
args.base_profile,
|
||||
rate=rate,
|
||||
duration=args.duration,
|
||||
@@ -1245,12 +1333,13 @@ class MessageProbe(threading.Thread):
|
||||
self.stop_event = threading.Event()
|
||||
self.samples: list[dict] = []
|
||||
self.confirmed: list[dict] = []
|
||||
self.started_monotonic = time.monotonic()
|
||||
|
||||
def run(self) -> None:
|
||||
import uuid
|
||||
|
||||
sequence = 0
|
||||
started = time.monotonic()
|
||||
started = self.started_monotonic
|
||||
while not self.stop_event.is_set():
|
||||
sequence += 1
|
||||
key = uuid.uuid4().hex
|
||||
@@ -1282,10 +1371,11 @@ def replica_ip(container: str) -> str:
|
||||
|
||||
|
||||
def cmd_failover(args) -> None:
|
||||
replicas = replica_map()
|
||||
targets = sorted(replicas) if args.replicas == 'all' else [args.replicas]
|
||||
config = load_stand_config()
|
||||
ensure_stand({'API_REPLICAS': str(len(replicas))})
|
||||
expected = int(config['API_REPLICAS'])
|
||||
ensure_stand({'API_REPLICAS': str(expected)})
|
||||
replicas = wait_for_replicas(expected)
|
||||
targets = replicas if args.replicas == 'all' else [args.replicas]
|
||||
results = []
|
||||
for target in targets:
|
||||
results.append(failover_once(target, args, config))
|
||||
@@ -1294,10 +1384,19 @@ def cmd_failover(args) -> None:
|
||||
|
||||
|
||||
def failover_once(target: str, args, config: dict) -> dict:
|
||||
if target not in replica_map():
|
||||
log(f'{target} не запущена: восстанавливаю реплику')
|
||||
"""Один цикл: нагрузка -> остановка реплики -> возврат -> проверка истории.
|
||||
|
||||
Проба идёт постоянно и повторяет неопределённый POST тем же ключом, поэтому
|
||||
«потерь» и «дублей» в истории быть не должно. Окно реального отсутствия
|
||||
реплики считается от выхода контейнера (docker stop возвращает управление
|
||||
уже после остановки), а не от вызова команды: дрейн длиной DRAIN_DELAY_MS
|
||||
специально переживает обнаружение отказа LB и не должен выглядеть отказом.
|
||||
"""
|
||||
if target not in replica_map() or lb_backends_up() < len(replica_map()):
|
||||
log(f'{target} не запущена или LB ещё не видит все реплики: восстанавливаю')
|
||||
run_command(['scripts/start-replica.sh'])
|
||||
wait_for_lb()
|
||||
wait_for_replicas(len(replica_map()) or int(config['API_REPLICAS']))
|
||||
if target not in replica_map():
|
||||
raise SystemExit(f'replica {target} did not come back')
|
||||
container = replica_map()[target]['container']
|
||||
@@ -1307,15 +1406,16 @@ def failover_once(target: str, args, config: dict) -> dict:
|
||||
alice = client.register(f'failover{target[:4]}')
|
||||
chat = client.create_chat(alice['token'], [alice['id']], f'failover {target}')
|
||||
|
||||
load_seconds = int(args.pre + args.hold + 30)
|
||||
label = f'failover#{target}'
|
||||
env = {
|
||||
**load_env('p-b', 'write', 'spread', label),
|
||||
'RATE': str(args.rate),
|
||||
'DURATION': str(args.duration),
|
||||
'DURATION': str(load_seconds),
|
||||
}
|
||||
sampler = Sampler().start()
|
||||
load = subprocess.Popen(
|
||||
[*COMPOSE, '--profile', 'load', 'run', '--rm', '--no-deps', *sum((['-e', f'{k}={v}'] for k, v in env.items()), []), 'loadgen', 'run', '/load/write-steady.js'],
|
||||
[*COMPOSE, '--profile', 'load', 'run', '--rm', '--no-deps', *sum((['-e', f'{key}={value}'] for key, value in env.items()), []), 'loadgen', 'run', '/load/write-steady.js'],
|
||||
cwd=ROOT,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
@@ -1326,45 +1426,41 @@ def failover_once(target: str, args, config: dict) -> dict:
|
||||
started = now_iso()
|
||||
|
||||
time.sleep(args.pre)
|
||||
stop_moment = time.monotonic()
|
||||
stop = run_command(
|
||||
['scripts/stop-one.sh'],
|
||||
check=False,
|
||||
env={'TARGET_INSTANCE_ID': target},
|
||||
timeout=30,
|
||||
)
|
||||
command_moment = time.monotonic()
|
||||
stop = run_command(['scripts/stop-one.sh'], check=False, env={'TARGET_INSTANCE_ID': target}, timeout=30)
|
||||
exit_moment = time.monotonic()
|
||||
stop_at = now_iso()
|
||||
first_success = None
|
||||
while time.monotonic() - stop_moment < args.duration - args.pre:
|
||||
successes = [sample for sample in list(probe.samples) if sample['t'] > 0 and sample.get('ok')]
|
||||
if any(sample['t'] > (stop_moment - probe_start(probe)) for sample in successes):
|
||||
first_success = round(time.monotonic() - stop_moment, 2)
|
||||
|
||||
first_success_after_exit = None
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
exit_offset = probe_offset(probe, exit_moment)
|
||||
if any(sample.get('ok') and sample['t'] >= exit_offset for sample in list(probe.samples)):
|
||||
first_success_after_exit = round(probe_offset(probe, time.monotonic()), 2)
|
||||
break
|
||||
time.sleep(0.1)
|
||||
time.sleep(max(0.0, args.hold))
|
||||
time.sleep(args.hold)
|
||||
restore_moment = time.monotonic()
|
||||
restore_at = now_iso()
|
||||
run_command(['scripts/start-replica.sh'])
|
||||
recovered = None
|
||||
deadline = time.monotonic() + 60
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
instances = set()
|
||||
for _ in range(6):
|
||||
response = client.call('GET', '/api/v1/users/me', token=alice['token'])
|
||||
instances.add(header(response['headers'], 'X-Instance-Id'))
|
||||
if len(instances) >= 2:
|
||||
recovered = round(time.monotonic() - stop_moment, 2)
|
||||
seen = {
|
||||
header(client.call('GET', '/api/v1/users/me', token=alice['token'])['headers'], 'X-Instance-Id')
|
||||
for _ in range(6)
|
||||
}
|
||||
if len(seen) >= 2:
|
||||
recovered = round(time.monotonic() - restore_moment, 2)
|
||||
break
|
||||
time.sleep(0.5)
|
||||
remaining = max(0.0, args.duration - (time.monotonic() - stop_moment) - args.pre)
|
||||
time.sleep(min(remaining, 15))
|
||||
probe.stop_event.set()
|
||||
probe.join(timeout=10)
|
||||
load.terminate()
|
||||
try:
|
||||
stdout, _ = load.communicate(timeout=120)
|
||||
stdout, _ = load.communicate(timeout=load_seconds + 90)
|
||||
except subprocess.TimeoutExpired:
|
||||
load.kill()
|
||||
stdout, _ = load.communicate()
|
||||
probe.stop_event.set()
|
||||
probe.join(timeout=15)
|
||||
samples = sampler.stop()
|
||||
finished = now_iso()
|
||||
|
||||
@@ -1378,53 +1474,86 @@ def failover_once(target: str, args, config: dict) -> dict:
|
||||
if 'steps' in candidate:
|
||||
summary = candidate
|
||||
break
|
||||
|
||||
history = client.history(alice['token'], chat)
|
||||
texts = [item['text'] for item in history]
|
||||
duplicates = sorted({text for text in texts if texts.count(text) > 1})
|
||||
missing = [item['text'] for item in probe.confirmed if item['text'] not in texts]
|
||||
lb = haproxy_stats(samples)
|
||||
detection = None
|
||||
for name, server in lb.items():
|
||||
if address in server['addresses']:
|
||||
for transition in server['transitions']:
|
||||
if transition['status'] != 'UP':
|
||||
detection = transition['t']
|
||||
break
|
||||
|
||||
command_offset = probe_offset(probe, command_moment)
|
||||
exit_offset = probe_offset(probe, exit_moment)
|
||||
outage_start = first_success_after_exit if first_success_after_exit is None else exit_offset
|
||||
last_offset = probe.samples[-1]['t'] if probe.samples else exit_offset
|
||||
phases = {
|
||||
'stop_at': stop_at,
|
||||
'stop_exit': stop.returncode,
|
||||
'first_success_after_stop_s': first_success,
|
||||
'stop_command_at': stop_at,
|
||||
'stop_exit_code': stop.returncode,
|
||||
'stop_command_took_s': round(exit_moment - command_moment, 2),
|
||||
'first_success_after_exit_s': (
|
||||
round(first_success_after_exit - exit_offset, 2) if first_success_after_exit is not None else None
|
||||
),
|
||||
'restore_at': restore_at,
|
||||
'second_replica_observed_s': recovered,
|
||||
'lb_down_at': detection,
|
||||
'replica_rejoined_s': recovered,
|
||||
'lb_down_at': lb_down_time(samples, address),
|
||||
'probe_offsets': {
|
||||
'stop_command': round(command_offset, 2),
|
||||
'container_exit': round(exit_offset, 2),
|
||||
'restore_command': round(probe_offset(probe, restore_moment), 2),
|
||||
'last_sample': round(last_offset, 2),
|
||||
},
|
||||
}
|
||||
if summary:
|
||||
write_raw(label, summary, samples, config, started, finished, phases, sampler.errors)
|
||||
failures = [sample for sample in probe.samples if not sample.get('ok')]
|
||||
result = {
|
||||
'instance': target,
|
||||
'container': container,
|
||||
'address': address,
|
||||
'rate': args.rate,
|
||||
'duration_s': args.duration,
|
||||
'phases': phases,
|
||||
'probe': {
|
||||
'attempts': len(probe.samples),
|
||||
'successes': sum(1 for sample in probe.samples if sample.get('ok')),
|
||||
'failures': sum(1 for sample in probe.samples if not sample.get('ok')),
|
||||
'rps_before': phase_rps(probe.samples, 0, probe_start(probe) + args.pre - probe_start(probe)),
|
||||
'failures': len(failures),
|
||||
'confirmed': len(probe.confirmed),
|
||||
'rps_before': phase_rps(probe.samples, 0.0, command_offset),
|
||||
'rps_while_stopped': phase_rps(probe.samples, exit_offset, outage_start),
|
||||
'rps_after': phase_rps(probe.samples, outage_start, last_offset),
|
||||
'errors_while_stopped': sum(
|
||||
1 for sample in failures if exit_offset <= sample['t'] <= outage_start
|
||||
),
|
||||
'timeline': [[sample['t'], 1 if sample.get('ok') else 0] for sample in probe.samples],
|
||||
},
|
||||
'duplicates': duplicates,
|
||||
'missing_confirmed': missing,
|
||||
'haproxy': lb,
|
||||
'k6': {'achieved_rps': summary['steps'][0]['achieved_rps'] if summary else None, 'failed': summary['steps'][0]['failed'] if summary else None},
|
||||
'haproxy': haproxy_stats(samples),
|
||||
'k6': {
|
||||
'achieved_rps': summary['steps'][0]['achieved_rps'] if summary else None,
|
||||
'failed': summary['steps'][0]['failed'] if summary else None,
|
||||
'dropped': summary.get('dropped_iterations') if summary else None,
|
||||
},
|
||||
}
|
||||
log(f'failover {target}: падение обнаружено, восстановление {recovered}s, дубли: {len(duplicates)}, потеряно: {len(missing)}')
|
||||
log(
|
||||
f'failover {target}: контейнер остановлен через {phases["stop_command_took_s"]}s, '
|
||||
f'первый успех после остановки через {phases["first_success_after_exit_s"]}s, '
|
||||
f'реплика вернулась через {recovered}s, дубли {len(duplicates)}, потеряно {len(missing)}'
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def probe_start(probe: MessageProbe) -> float:
|
||||
return probe.samples[0]['t'] if probe.samples else 0.0
|
||||
def probe_offset(probe: MessageProbe, moment: float) -> float:
|
||||
"""Переводит момент wall-clock в шкалу времени сэмплов пробы."""
|
||||
if not probe.samples:
|
||||
return 0.0
|
||||
return probe.samples[0]['t'] + (moment - probe.started_monotonic)
|
||||
|
||||
|
||||
def lb_down_time(samples: list[dict], address: str) -> str | None:
|
||||
for record in samples:
|
||||
if record.get('source') != 'haproxy' or record.get('server') in ('FRONTEND', 'BACKEND'):
|
||||
continue
|
||||
if address in (record.get('addr') or '') and record.get('status') not in ('UP',):
|
||||
return record['t']
|
||||
return None
|
||||
|
||||
|
||||
def phase_rps(samples: list[dict], start: float, end: float) -> float:
|
||||
@@ -1435,22 +1564,54 @@ def phase_rps(samples: list[dict], start: float, end: float) -> float:
|
||||
def write_failover_evidence(results: list[dict]) -> None:
|
||||
write_json(LEVEL4_DIR / 'failover-sweep.json', results)
|
||||
lines = table(
|
||||
['реплика', 'контейнер', 'попыток', 'успешных', 'ошибок', 'первый успех, s', 'вторая реплика, s', 'дубли', 'потери'],
|
||||
[
|
||||
'реплика',
|
||||
'контейнер',
|
||||
'попыток пробы',
|
||||
'успешных',
|
||||
'ошибок в отказе',
|
||||
'остановка контейнера, s',
|
||||
'первый успех после остановки, s',
|
||||
'реплика вернулась, s',
|
||||
'LB DOWN',
|
||||
'RPS до',
|
||||
'RPS в отказе',
|
||||
'RPS после',
|
||||
'k6 RPS',
|
||||
'k6 ошибок',
|
||||
'дубли',
|
||||
'потери',
|
||||
],
|
||||
[
|
||||
[
|
||||
result['instance'][:12],
|
||||
result['container'][:12],
|
||||
result['probe']['attempts'],
|
||||
result['probe']['successes'],
|
||||
result['probe']['failures'],
|
||||
result['phases']['first_success_after_stop_s'],
|
||||
result['phases']['second_replica_observed_s'],
|
||||
result['probe']['errors_while_stopped'],
|
||||
result['phases']['stop_command_took_s'],
|
||||
result['phases']['first_success_after_exit_s'],
|
||||
result['phases']['replica_rejoined_s'],
|
||||
(result['phases']['lb_down_at'] or '-')[11:19],
|
||||
result['probe']['rps_before'],
|
||||
result['probe']['rps_while_stopped'],
|
||||
result['probe']['rps_after'],
|
||||
result['k6']['achieved_rps'],
|
||||
result['k6']['failed'],
|
||||
len(result['duplicates']),
|
||||
len(result['missing_confirmed']),
|
||||
]
|
||||
for result in results
|
||||
],
|
||||
)
|
||||
lines += [
|
||||
'',
|
||||
'Проба: последовательные POST с интервалом 0.2 s, при неопределённом результате '
|
||||
'повтор с тем же Idempotency-Key (как у реального клиента). Окно отсутствия реплики '
|
||||
'считается от выхода контейнера до первого успешного ответа после него; дрейн перед '
|
||||
'остановкой специально переживает обнаружение отказа LB, поэтому клиент не обязан '
|
||||
'видеть ошибки. Потери и дубли проверяются по истории чата.',
|
||||
]
|
||||
write_markdown(LEVEL4_DIR / 'failover-sweep.md', 'Отказ каждой реплики под нагрузкой', lines)
|
||||
|
||||
|
||||
@@ -1459,7 +1620,7 @@ def cmd_rolling(args) -> None:
|
||||
replicas = int(config['API_REPLICAS'])
|
||||
build_id = args.build_id or datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
|
||||
before = replica_map()
|
||||
migrate_before = inspect(container_ids('migrate')[0], '{{.State.StartedAt}}') if container_ids('migrate') else None
|
||||
migrate_before = inspect(container_ids('migrate', include_stopped=True)[0], '{{.State.StartedAt}}')
|
||||
log(f'сборка образа {config["API_IMAGE"]} с BUILD_ID={build_id}')
|
||||
build = run_command(
|
||||
['docker', 'build', '--build-arg', f'BUILD_ID={build_id}', '-t', config['API_IMAGE'], '.'],
|
||||
@@ -1488,13 +1649,15 @@ def cmd_rolling(args) -> None:
|
||||
steps = []
|
||||
for step in range(replicas):
|
||||
current = replica_map()
|
||||
target = sorted(current)[step % len(current)]
|
||||
known = set(current)
|
||||
# Меняем самую «старую» реплику: только что созданная видна как самая молодая.
|
||||
target = sorted(current, key=lambda instance: current[instance]['started_at'])[0]
|
||||
container = current[target]['container']
|
||||
old_build = app_build_id(container)
|
||||
run_command(['docker', 'stop', '--time', '15', container], check=False, timeout=60)
|
||||
run_command(['docker', 'rm', container], check=False, timeout=60)
|
||||
compose('up', '-d', '--no-deps', '--no-recreate', '--scale', f'api={replicas}', 'api', timeout=600)
|
||||
new_instance, new_container = wait_for_replica_count(replicas, exclude=target)
|
||||
new_instance, new_container = wait_for_new_replica(replicas, known)
|
||||
new_build = app_build_id(new_container)
|
||||
steps.append(
|
||||
{
|
||||
@@ -1510,27 +1673,30 @@ def cmd_rolling(args) -> None:
|
||||
)
|
||||
log(f'rolling {step + 1}/{replicas}: {target[:12]} ({old_build}) -> {new_instance[:12]} ({new_build})')
|
||||
time.sleep(args.pause)
|
||||
summary = None
|
||||
if load is not None:
|
||||
try:
|
||||
stdout, _ = load.communicate(timeout=max(30, args.duration))
|
||||
except subprocess.TimeoutExpired:
|
||||
load.terminate()
|
||||
try:
|
||||
stdout, _ = load.communicate(timeout=60)
|
||||
except subprocess.TimeoutExpired:
|
||||
load.kill()
|
||||
stdout, _ = load.communicate()
|
||||
probe.stop_event.set()
|
||||
probe.join(timeout=10)
|
||||
samples = sampler.stop()
|
||||
summary = None
|
||||
if load is not None:
|
||||
load.terminate()
|
||||
try:
|
||||
stdout, _ = load.communicate(timeout=120)
|
||||
except subprocess.TimeoutExpired:
|
||||
load.kill()
|
||||
stdout, _ = load.communicate()
|
||||
for line in reversed((stdout or '').splitlines()):
|
||||
if line.strip().startswith('{'):
|
||||
try:
|
||||
candidate = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if 'steps' in candidate:
|
||||
summary = candidate
|
||||
break
|
||||
migrate_after = inspect(container_ids('migrate')[0], '{{.State.StartedAt}}') if container_ids('migrate') else None
|
||||
for line in reversed((stdout or '').splitlines()):
|
||||
if line.strip().startswith('{'):
|
||||
try:
|
||||
candidate = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if 'steps' in candidate:
|
||||
summary = candidate
|
||||
break
|
||||
migrate_after = inspect(container_ids('migrate', include_stopped=True)[0], '{{.State.StartedAt}}')
|
||||
failures = [sample for sample in probe.samples if not sample.get('ok')]
|
||||
server_failures = [sample for sample in failures if 500 <= int(sample.get('status') or 0) < 600]
|
||||
finished = now_iso()
|
||||
@@ -1575,16 +1741,22 @@ def app_build_id(container: str) -> str:
|
||||
return result.stdout.strip() or 'unknown'
|
||||
|
||||
|
||||
def wait_for_replica_count(replicas: int, exclude: str, timeout: float = 120) -> tuple[str, str]:
|
||||
def wait_for_new_replica(replicas: int, known: set[str], timeout: float = 180) -> tuple[str, str]:
|
||||
"""Ждёт появления НОВОЙ реплики (не из known) в состоянии healthy."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
mapping = replica_map()
|
||||
if len(mapping) >= replicas:
|
||||
for instance, info in sorted(mapping.items()):
|
||||
if instance != exclude:
|
||||
fresh = {instance: info for instance, info in mapping.items() if instance not in known}
|
||||
if len(mapping) >= replicas and fresh:
|
||||
for instance, info in sorted(fresh.items()):
|
||||
status = inspect(info['container'], '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}')
|
||||
if status == 'healthy':
|
||||
return instance, info['container']
|
||||
time.sleep(1)
|
||||
raise SystemExit(f'replica count did not reach {replicas} within {timeout}s')
|
||||
raise SystemExit(
|
||||
f'новая реплика не появилась healthy за {timeout}s (контейнеров {len(replica_map())}, '
|
||||
f'новых {len({i for i in replica_map() if i not in known})})'
|
||||
)
|
||||
|
||||
|
||||
def cmd_ab(args) -> None:
|
||||
@@ -1597,12 +1769,23 @@ def cmd_ab(args) -> None:
|
||||
report_ab(args)
|
||||
|
||||
|
||||
def report_ab(args) -> None:
|
||||
def report_ab(args=None) -> None:
|
||||
labels = [label for label in raw_labels() if label.startswith('ab#')]
|
||||
groups = group_configurations(labels)
|
||||
lines = []
|
||||
verdicts = []
|
||||
series_by_side = {side: summarise_series(groups.get(side, [])) for side in ('A', 'B')}
|
||||
series_by_side = {
|
||||
side: summarise_series(groups.get(f'ab#{side}', [])) for side in ('A', 'B')
|
||||
}
|
||||
images = {
|
||||
side: (getattr(args, side.lower(), None) if args else None) for side in ('A', 'B')
|
||||
}
|
||||
for side in ('A', 'B'):
|
||||
if not images[side] and groups.get(f'ab#{side}'):
|
||||
manifest = read_json(
|
||||
RAW_DIR / f'{groups[f"ab#{side}"][-1]}.manifest.json', {}
|
||||
)
|
||||
images[side] = (manifest.get('stand') or {}).get('API_IMAGE')
|
||||
for rate in sorted({row['rate'] for row in series_by_side['A']['rows']}):
|
||||
row_a = next((row for row in series_by_side['A']['rows'] if row['rate'] == rate), None)
|
||||
row_b = next((row for row in series_by_side['B']['rows'] if row['rate'] == rate), None)
|
||||
@@ -1648,7 +1831,14 @@ def report_ab(args) -> None:
|
||||
'',
|
||||
'Правило подтверждения: медиана меняется ≥5 % и диапазоны min/max повторов не перекрываются.',
|
||||
]
|
||||
write_json(TRACK1_DIR / 'ab-verdict.json', {'verdicts': verdicts, 'ceiling': {side: series_by_side[side]['ceiling_rps'] for side in ('A', 'B')}, 'images': {'A': args.before, 'B': args.after}})
|
||||
write_json(
|
||||
TRACK1_DIR / 'ab-verdict.json',
|
||||
{
|
||||
'verdicts': verdicts,
|
||||
'ceiling': {side: series_by_side[side]['ceiling_rps'] for side in ('A', 'B')},
|
||||
'images': images,
|
||||
},
|
||||
)
|
||||
write_markdown(TRACK1_DIR / 'summary-ab.md', 'A/B: подтверждённое улучшение', lines)
|
||||
|
||||
|
||||
@@ -1687,8 +1877,8 @@ def cmd_analyze(args) -> None:
|
||||
analyse_series_a(groups, labels)
|
||||
analyse_diagnostics(groups, labels)
|
||||
analyse_growth(groups, labels)
|
||||
if groups.get('A') or groups.get('B'):
|
||||
report_ab(None, None)
|
||||
if groups.get('ab#A') or groups.get('ab#B'):
|
||||
report_ab()
|
||||
make_graphs(groups, labels)
|
||||
log('analyze: таблицы и графики обновлены')
|
||||
|
||||
@@ -2082,10 +2272,10 @@ def make_graphs(groups: dict, labels: list[str]) -> None:
|
||||
figure.savefig(GRAPH_DIR / 'growth.png', dpi=120)
|
||||
plt.close(figure)
|
||||
|
||||
if groups.get('A') and groups.get('B'):
|
||||
if groups.get('ab#A') and groups.get('ab#B'):
|
||||
figure, axes = plt.subplots(figsize=(9, 5))
|
||||
series_a = summarise_series(groups['A'])
|
||||
series_b = summarise_series(groups['B'])
|
||||
series_a = summarise_series(groups['ab#A'])
|
||||
series_b = summarise_series(groups['ab#B'])
|
||||
rates = [row['rate'] for row in series_a['rows']]
|
||||
positions = list(range(len(rates)))
|
||||
axes.bar([p - 0.2 for p in positions], [row['achieved_rps'] for row in series_a['rows']], width=0.4, label='A (до)')
|
||||
@@ -2135,6 +2325,25 @@ def plot_container_cpu(plt, label: str) -> None:
|
||||
# ---------------------------------------------------------------- оркестрация трека
|
||||
|
||||
|
||||
def cmd_watch(args) -> None:
|
||||
"""Сэмплер без нагрузки: наблюдает стенд N секунд и пишет jsonl.gz.
|
||||
|
||||
Нужен там, где нагрузку создаёт внешний сценарий (публичный failover-тест,
|
||||
rolling update): переходы статусов LB получают отметки времени.
|
||||
"""
|
||||
sampler = Sampler().start()
|
||||
try:
|
||||
time.sleep(args.seconds)
|
||||
finally:
|
||||
samples = sampler.stop()
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
with gzip.open(out, 'wt', encoding='utf-8') as handle:
|
||||
for record in samples:
|
||||
handle.write(json.dumps(record, ensure_ascii=False) + '\n')
|
||||
print(json.dumps({'out': str(out), 'samples': len(samples), 'errors': sampler.errors}, ensure_ascii=False))
|
||||
|
||||
|
||||
def cmd_quiesce(args) -> None:
|
||||
result = run_command(['scripts/quiesce.sh', args.action], check=False, timeout=300)
|
||||
print(result.stdout + result.stderr)
|
||||
@@ -2210,6 +2419,10 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
run.add_argument('--duration', type=int, help='длительность полки, s')
|
||||
run.add_argument('--replicas', type=int)
|
||||
run.add_argument('--pool', type=int, help='DATABASE_POOL_MAX на реплику')
|
||||
run.add_argument('--loadgen-cpus', type=float, help='лимит CPU генератора (контингенция: k6 упёрся в квоту)')
|
||||
run.add_argument('--lb-cpus', type=float, help='лимит CPU HAProxy')
|
||||
run.add_argument('--api-total-cpus', type=float, help='суммарный бюджет CPU API (делится на реплики)')
|
||||
run.add_argument('--pg-cpus', type=float, help='лимит CPU PostgreSQL')
|
||||
run.add_argument('--mode', choices=['write', 'read'])
|
||||
run.add_argument('--spread', choices=['spread', 'hot'])
|
||||
run.add_argument('--no-warmup', action='store_true')
|
||||
@@ -2231,6 +2444,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
growth.add_argument('--duration', type=int, default=60)
|
||||
growth.add_argument('--base-profile', default='p-a')
|
||||
growth.add_argument('--no-warmup', action='store_true')
|
||||
growth.add_argument('--suffix', default='', help='суффикс метки: различает прогоны одной точки на разных темпах')
|
||||
growth.set_defaults(func=cmd_growth)
|
||||
|
||||
failover = sub.add_parser('failover', help='фазовый драйвер отказа реплики')
|
||||
@@ -2261,6 +2475,11 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
analyze = sub.add_parser('analyze', help='агрегаты и графики из raw')
|
||||
analyze.set_defaults(func=cmd_analyze)
|
||||
|
||||
watch = sub.add_parser('watch', help='сэмплер без нагрузки: наблюдение за стендом')
|
||||
watch.add_argument('--seconds', type=float, default=30)
|
||||
watch.add_argument('--out', required=True)
|
||||
watch.set_defaults(func=cmd_watch)
|
||||
|
||||
quiesce = sub.add_parser('quiesce', help='фон хоста: up/down/status')
|
||||
quiesce.add_argument('action', choices=['up', 'down', 'status'])
|
||||
quiesce.set_defaults(func=cmd_quiesce)
|
||||
|
||||
@@ -20,7 +20,13 @@ const LOAD_USERS = 3;
|
||||
// Бюджет VU: на 1100 req/s при p95 около 25 ms достаточно около 30 активных VU;
|
||||
// 60 предвыделенных и 200 максимальных оставляют запас, чтобы узкое место
|
||||
// оказалось на сервере, а не в генераторе.
|
||||
export const VUS = { preAllocated: 60, max: 200 };
|
||||
// Бюджет VU: на 1100 req/s при p95 около 25 ms достаточно около 30 активных VU.
|
||||
// Значения переопределяются извне (PRE_VUS/MAX_VUS): на пути чтения генератор
|
||||
// упирался в 200 VU раньше, чем в CPU, и потолок измерялся бы как потолок k6.
|
||||
export const VUS = {
|
||||
preAllocated: Number(__ENV.PRE_VUS || 60),
|
||||
max: Number(__ENV.MAX_VUS || 200),
|
||||
};
|
||||
|
||||
export function ratesFromEnv(fallback) {
|
||||
const raw = __ENV.LADDER;
|
||||
@@ -232,6 +238,7 @@ export function summaryJson(data, metrics, rates, kind, stepSeconds) {
|
||||
iterations: data.metrics.iterations?.values?.count ?? 0,
|
||||
dropped_iterations: data.metrics.dropped_iterations?.values?.count ?? 0,
|
||||
vus_max: data.metrics.vus_max?.values?.value ?? 0,
|
||||
vus_configured: VUS,
|
||||
http_req_duration_p95: round(global['p(95)'] ?? 0, 2),
|
||||
checks: {
|
||||
passes: data.metrics.checks?.values?.passes ?? 0,
|
||||
|
||||
Reference in New Issue
Block a user