forked from mtusi2026/mtusi2026lab2
Compare commits
2
Commits
c25f19aa81
...
b6c3aa1e64
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6c3aa1e64 | ||
|
|
02dfeccb42 |
@@ -4,7 +4,7 @@ PostgreSQL, серверные сессии и Valkey
|
|||||||
|
|
||||||
- Автор, группа: Максимова Мария, БВТ2303
|
- Автор, группа: Максимова Мария, БВТ2303
|
||||||
- Целевая оценка: 4
|
- Целевая оценка: 4
|
||||||
- Commit / PR: `TODO` — подставить `git rev-parse --short HEAD` после финального коммита
|
- Commit / PR: 02dfecc
|
||||||
- Использованные средства: Python 3.12.7 (в Docker), FastAPI, SQLAlchemy 2 (async) + asyncpg, argon2-cffi, redis-py 5 (клиент Valkey), PostgreSQL 16.4, Valkey 8.0.1, Docker Desktop + WSL2.
|
- Использованные средства: Python 3.12.7 (в Docker), FastAPI, SQLAlchemy 2 (async) + asyncpg, argon2-cffi, redis-py 5 (клиент Valkey), PostgreSQL 16.4, Valkey 8.0.1, Docker Desktop + WSL2.
|
||||||
- Источники: документация PostgreSQL (EXPLAIN, сравнение строк/row comparison, транзакции, WAL), документация Valkey (persistence, `SET NX`, `EX`), RFC 7617 (HTTP Basic), документация FastAPI и SQLAlchemy.
|
- Источники: документация PostgreSQL (EXPLAIN, сравнение строк/row comparison, транзакции, WAL), документация Valkey (persistence, `SET NX`, `EX`), RFC 7617 (HTTP Basic), документация FastAPI и SQLAlchemy.
|
||||||
- Помощь ИИ: Claude Code и Perplexity использовались для части реализации кэша, тестов уровня 4, диагностики окружения и оформления отчёта. Все команды, тесты и измерения я запускала локально сама, результаты сохранены в `evidence/`.
|
- Помощь ИИ: Claude Code и Perplexity использовались для части реализации кэша, тестов уровня 4, диагностики окружения и оформления отчёта. Все команды, тесты и измерения я запускала локально сама, результаты сохранены в `evidence/`.
|
||||||
@@ -471,7 +471,7 @@ LIMIT 51; -- limit + 1, чтобы понять, есть ли сле
|
|||||||
## 12. Secrets и Git
|
## 12. Secrets и Git
|
||||||
|
|
||||||
- Реальные secrets генерирует `scripts/init-secrets.sh` в `infra/secrets/*.txt`. В контейнеры они передаются как Docker secrets (`*_FILE`), а не через переменные окружения или `compose.yaml`.
|
- Реальные secrets генерирует `scripts/init-secrets.sh` в `infra/secrets/*.txt`. В контейнеры они передаются как Docker secrets (`*_FILE`), а не через переменные окружения или `compose.yaml`.
|
||||||
- В Git лежат только шаблоны `infra/secrets/*.example.txt` и `.env.example`.
|
- В Git нет ни одного файла с secrets: их создаёт `scripts/init-secrets.sh` на каждой машине, в репозитории лежит только `.env.example` без значений.
|
||||||
- `.gitignore` исключает `infra/secrets/*.txt`, `.env`, `.venv/`, `.venv-wsl/`, `__pycache__/`. `.dockerignore` дополнительно исключает `infra/secrets` и `.git` из build context.
|
- `.gitignore` исключает `infra/secrets/*.txt`, `.env`, `.venv/`, `.venv-wsl/`, `__pycache__/`. `.dockerignore` дополнительно исключает `infra/secrets` и `.git` из build context.
|
||||||
- Volume `postgres_data` — объект Docker, он не лежит в дереве репозитория и в Git попасть не может.
|
- Volume `postgres_data` — объект Docker, он не лежит в дереве репозитория и в Git попасть не может.
|
||||||
- В `evidence/` нет токенов, паролей, `DATABASE_URL`, заголовков `Authorization` и реальных сообщений. Официальные тесты не печатают credentials, а restart-hook запускается с подавленным выводом.
|
- В `evidence/` нет токенов, паролей, `DATABASE_URL`, заголовков `Authorization` и реальных сообщений. Официальные тесты не печатают credentials, а restart-hook запускается с подавленным выводом.
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
|||||||
+30
-30
@@ -5,64 +5,64 @@ PASS: chat row was rolled back together with members
|
|||||||
PASS: no chats without members exist in the database
|
PASS: no chats without members exist in the database
|
||||||
|
|
||||||
== EXPLAIN for message history pagination
|
== EXPLAIN for message history pagination
|
||||||
messages total: 50003; in explained chat: 10000
|
messages total: 61133; in explained chat: 10000
|
||||||
PASS: explained chat has >= 10 000 messages
|
PASS: explained chat has >= 10 000 messages
|
||||||
|
|
||||||
-- first page
|
-- first page
|
||||||
Limit (actual time=0.010..0.016 rows=51 loops=1)
|
Limit (actual time=0.042..0.048 rows=51 loops=1)
|
||||||
Buffers: shared hit=4
|
Buffers: shared hit=4
|
||||||
-> Index Scan using messages_keyset_idx on messages (actual time=0.010..0.013 rows=51 loops=1)
|
-> Index Scan using messages_keyset_idx on messages (actual time=0.042..0.045 rows=51 loops=1)
|
||||||
Index Cond: (chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid)
|
Index Cond: (chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid)
|
||||||
Buffers: shared hit=4
|
Buffers: shared hit=4
|
||||||
Planning:
|
Planning:
|
||||||
Buffers: shared hit=6
|
Buffers: shared hit=6
|
||||||
Planning Time: 0.131 ms
|
Planning Time: 0.084 ms
|
||||||
Execution Time: 0.035 ms
|
Execution Time: 0.067 ms
|
||||||
|
|
||||||
-- keyset page after position 9000
|
-- keyset page after position 9000
|
||||||
Limit (actual time=0.012..0.021 rows=51 loops=1)
|
Limit (actual time=0.010..0.019 rows=51 loops=1)
|
||||||
Buffers: shared hit=5
|
Buffers: shared hit=5
|
||||||
-> Index Scan using messages_keyset_idx on messages (actual time=0.011..0.018 rows=51 loops=1)
|
-> Index Scan using messages_keyset_idx on messages (actual time=0.010..0.016 rows=51 loops=1)
|
||||||
Index Cond: ((chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid) AND (ROW(created_at, id) > ROW('2026-10-01 07:31:21.6187+00'::timestamp with time zone, '6cbb1e03-f1e2-4113-8a7b-612c90c9761f'::uuid)))
|
Index Cond: ((chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid) AND (ROW(created_at, id) > ROW('2026-10-01 07:31:21.6187+00'::timestamp with time zone, '6cbb1e03-f1e2-4113-8a7b-612c90c9761f'::uuid)))
|
||||||
Buffers: shared hit=5
|
Buffers: shared hit=5
|
||||||
Planning Time: 0.043 ms
|
Planning Time: 0.063 ms
|
||||||
Execution Time: 0.104 ms
|
Execution Time: 0.069 ms
|
||||||
|
|
||||||
-- OFFSET 9000 (not used by the API)
|
-- OFFSET 9000 (not used by the API)
|
||||||
Limit (actual time=3.723..3.729 rows=51 loops=1)
|
Limit (actual time=3.412..3.417 rows=51 loops=1)
|
||||||
Buffers: shared hit=207
|
Buffers: shared hit=208
|
||||||
-> Sort (actual time=3.127..3.460 rows=9051 loops=1)
|
-> Sort (actual time=2.955..3.217 rows=9051 loops=1)
|
||||||
Sort Key: created_at, id
|
Sort Key: created_at, id
|
||||||
Sort Method: quicksort Memory: 1713kB
|
Sort Method: quicksort Memory: 1713kB
|
||||||
Buffers: shared hit=207
|
Buffers: shared hit=208
|
||||||
-> Bitmap Heap Scan on messages (actual time=0.321..0.920 rows=10000 loops=1)
|
-> Bitmap Heap Scan on messages (actual time=0.240..0.883 rows=10000 loops=1)
|
||||||
Recheck Cond: (chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid)
|
Recheck Cond: (chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid)
|
||||||
Heap Blocks: exact=134
|
Heap Blocks: exact=134
|
||||||
Buffers: shared hit=207
|
Buffers: shared hit=208
|
||||||
-> Bitmap Index Scan on messages_keyset_idx (actual time=0.307..0.308 rows=10000 loops=1)
|
-> Bitmap Index Scan on messages_keyset_idx (actual time=0.224..0.224 rows=10000 loops=1)
|
||||||
Index Cond: (chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid)
|
Index Cond: (chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid)
|
||||||
Buffers: shared hit=73
|
Buffers: shared hit=74
|
||||||
Planning Time: 0.040 ms
|
Planning Time: 0.110 ms
|
||||||
Execution Time: 3.848 ms
|
Execution Time: 3.597 ms
|
||||||
|
|
||||||
-- keyset page WITHOUT messages_keyset_idx (rolled back)
|
-- keyset page WITHOUT messages_keyset_idx (rolled back)
|
||||||
Limit (actual time=1.882..1.886 rows=51 loops=1)
|
Limit (actual time=2.273..2.278 rows=51 loops=1)
|
||||||
Buffers: shared hit=667
|
Buffers: shared hit=817
|
||||||
-> Sort (actual time=1.880..1.882 rows=51 loops=1)
|
-> Sort (actual time=2.271..2.273 rows=51 loops=1)
|
||||||
Sort Key: created_at, id
|
Sort Key: created_at, id
|
||||||
Sort Method: top-N heapsort Memory: 31kB
|
Sort Method: top-N heapsort Memory: 31kB
|
||||||
Buffers: shared hit=667
|
Buffers: shared hit=817
|
||||||
-> Seq Scan on messages (actual time=0.386..1.804 rows=999 loops=1)
|
-> Seq Scan on messages (actual time=0.366..2.188 rows=999 loops=1)
|
||||||
Filter: ((chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid) AND (ROW(created_at, id) > ROW('2026-10-01 07:31:21.6187+00'::timestamp with time zone, '6cbb1e03-f1e2-4113-8a7b-612c90c9761f'::uuid)))
|
Filter: ((chat_id = '7c57b8e9-42a1-4cf8-904b-08545328a890'::uuid) AND (ROW(created_at, id) > ROW('2026-10-01 07:31:21.6187+00'::timestamp with time zone, '6cbb1e03-f1e2-4113-8a7b-612c90c9761f'::uuid)))
|
||||||
Rows Removed by Filter: 49004
|
Rows Removed by Filter: 60134
|
||||||
Buffers: shared hit=667
|
Buffers: shared hit=817
|
||||||
Planning:
|
Planning:
|
||||||
Buffers: shared hit=4
|
Buffers: shared hit=4
|
||||||
Planning Time: 0.088 ms
|
Planning Time: 0.166 ms
|
||||||
Execution Time: 1.920 ms
|
Execution Time: 2.308 ms
|
||||||
PASS: first page reads the index in order, no Sort
|
PASS: first page reads the index in order, no Sort
|
||||||
PASS: keyset cursor is an Index Cond, not a filter over the history
|
PASS: keyset cursor is an Index Cond, not a filter over the history
|
||||||
PASS: keyset deep page touches fewer buffers than OFFSET (5 < 207)
|
PASS: keyset deep page touches fewer buffers than OFFSET (5 < 208)
|
||||||
PASS: index reduces buffers for the deep page (5 < 667)
|
PASS: index reduces buffers for the deep page (5 < 817)
|
||||||
|
|
||||||
PASS: db checks
|
PASS: db checks
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ PASS: forged token still 401 without Valkey
|
|||||||
PASS: anonymous still 401 without Valkey
|
PASS: anonymous still 401 without Valkey
|
||||||
PASS: logout works without Valkey
|
PASS: logout works without Valkey
|
||||||
PASS: token revoked during outage -> 401
|
PASS: token revoked during outage -> 401
|
||||||
PASS: bounded latency during outage (max 0.27s)
|
PASS: bounded latency during outage (max 0.26s)
|
||||||
PASS: token revoked during outage stays 401 after Valkey returns (stale cache flushed)
|
PASS: token revoked during outage stays 401 after Valkey returns (stale cache flushed)
|
||||||
PASS: live session works after recovery
|
PASS: live session works after recovery
|
||||||
|
|
||||||
|
|||||||
+6
-6
@@ -2,16 +2,16 @@
|
|||||||
"lab": 2,
|
"lab": 2,
|
||||||
"workload": "closed-loop POST messages; no automatic retries",
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
"requested_duration_seconds": 15.0,
|
"requested_duration_seconds": 15.0,
|
||||||
"elapsed_seconds": 15.026,
|
"elapsed_seconds": 15.017,
|
||||||
"concurrency": 4,
|
"concurrency": 4,
|
||||||
"successful_requests": 3324,
|
"successful_requests": 4452,
|
||||||
"failed_requests": 0,
|
"failed_requests": 0,
|
||||||
"error_ratio": 0.0,
|
"error_ratio": 0.0,
|
||||||
"successful_rps": 221.222,
|
"successful_rps": 296.457,
|
||||||
"successful_latency_ms": {
|
"successful_latency_ms": {
|
||||||
"p50": 15.779,
|
"p50": 12.336,
|
||||||
"p95": 30.073,
|
"p95": 19.091,
|
||||||
"p99": 59.585
|
"p99": 32.117
|
||||||
},
|
},
|
||||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -2,16 +2,16 @@
|
|||||||
"lab": 2,
|
"lab": 2,
|
||||||
"workload": "closed-loop POST messages; no automatic retries",
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
"requested_duration_seconds": 15.0,
|
"requested_duration_seconds": 15.0,
|
||||||
"elapsed_seconds": 15.026,
|
"elapsed_seconds": 15.017,
|
||||||
"concurrency": 4,
|
"concurrency": 4,
|
||||||
"successful_requests": 3324,
|
"successful_requests": 4452,
|
||||||
"failed_requests": 0,
|
"failed_requests": 0,
|
||||||
"error_ratio": 0.0,
|
"error_ratio": 0.0,
|
||||||
"successful_rps": 221.222,
|
"successful_rps": 296.457,
|
||||||
"successful_latency_ms": {
|
"successful_latency_ms": {
|
||||||
"p50": 15.779,
|
"p50": 12.336,
|
||||||
"p95": 30.073,
|
"p95": 19.091,
|
||||||
"p99": 59.585
|
"p99": 32.117
|
||||||
},
|
},
|
||||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-10
@@ -1,14 +1,14 @@
|
|||||||
## containers before restart hook
|
## containers before restart hook
|
||||||
api running Up 49 seconds 2026-10-02 09:47:54 +0300 MSK
|
api running Up 42 seconds 2026-10-02 09:54:27 +0300 MSK
|
||||||
api_short_ttl running Up 49 seconds 2026-10-02 09:47:54 +0300 MSK
|
api_short_ttl running Up 42 seconds 2026-10-02 09:54:27 +0300 MSK
|
||||||
db running Up 2 minutes (healthy) 2026-10-02 09:39:03 +0300 MSK
|
db running Up 49 seconds (healthy) 2026-10-02 09:39:03 +0300 MSK
|
||||||
migrate exited Exited (0) 53 seconds ago 2026-10-02 09:47:53 +0300 MSK
|
migrate exited Exited (0) 42 seconds ago 2026-10-02 09:54:26 +0300 MSK
|
||||||
valkey running Up 55 seconds (healthy) 2026-10-02 09:47:53 +0300 MSK
|
valkey running Up 49 seconds (healthy) 2026-10-02 09:47:53 +0300 MSK
|
||||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
## containers after restart hook (Status shows new uptime)
|
## containers after restart hook (Status shows new uptime)
|
||||||
api running Up 2 seconds 2026-10-02 09:47:54 +0300 MSK
|
api running Up 1 second 2026-10-02 09:54:27 +0300 MSK
|
||||||
api_short_ttl running Up 54 seconds 2026-10-02 09:47:54 +0300 MSK
|
api_short_ttl running Up 46 seconds 2026-10-02 09:54:27 +0300 MSK
|
||||||
db running Up 3 seconds (health: starting) 2026-10-02 09:39:03 +0300 MSK
|
db running Up 2 seconds (health: starting) 2026-10-02 09:39:03 +0300 MSK
|
||||||
migrate exited Exited (0) 58 seconds ago 2026-10-02 09:47:53 +0300 MSK
|
migrate exited Exited (0) 47 seconds ago 2026-10-02 09:54:26 +0300 MSK
|
||||||
valkey running Up 3 seconds (health: starting) 2026-10-02 09:47:53 +0300 MSK
|
valkey running Up 2 seconds (health: starting) 2026-10-02 09:47:53 +0300 MSK
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id UUID PRIMARY KEY,
|
|
||||||
username VARCHAR(32) NOT NULL UNIQUE,
|
|
||||||
display_name VARCHAR(100) NOT NULL,
|
|
||||||
password_hash TEXT NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
|
|
||||||
CONSTRAINT users_username_format_check
|
|
||||||
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
|
||||||
|
|
||||||
CONSTRAINT users_display_name_nonblank_check
|
|
||||||
CHECK (char_length(btrim(display_name)) >= 1)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS chats (
|
|
||||||
id UUID PRIMARY KEY,
|
|
||||||
title VARCHAR(255) NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
|
|
||||||
CONSTRAINT chats_title_nonblank_check
|
|
||||||
CHECK (char_length(btrim(title)) >= 1)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_members (
|
|
||||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
|
||||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
|
||||||
PRIMARY KEY (chat_id, user_id)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS messages (
|
|
||||||
id UUID PRIMARY KEY,
|
|
||||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
|
||||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
|
||||||
text VARCHAR(4000) NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
|
|
||||||
CONSTRAINT messages_text_nonblank_check
|
|
||||||
CHECK (char_length(btrim(text)) >= 1)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS messages_keyset_idx
|
|
||||||
ON messages (chat_id, created_at ASC, id ASC);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS chat_members_list_idx
|
|
||||||
ON chat_members (user_id, chat_id);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS sessions (
|
|
||||||
id UUID PRIMARY KEY,
|
|
||||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
token_hash CHAR(64) NOT NULL UNIQUE,
|
|
||||||
expires_at TIMESTAMPTZ NOT NULL,
|
|
||||||
revoked_at TIMESTAMPTZ,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS active_sessions_by_token_idx
|
|
||||||
ON sessions (token_hash, expires_at)
|
|
||||||
WHERE revoked_at IS NULL;
|
|
||||||
@@ -1,337 +0,0 @@
|
|||||||
import argparse
|
|
||||||
import json
|
|
||||||
import math
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
import uuid
|
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
|
|
||||||
def percentile(values: list[float], percent: float) -> float:
|
|
||||||
if not values:
|
|
||||||
return 0.0
|
|
||||||
ordered = sorted(values)
|
|
||||||
index = math.ceil(len(ordered) * percent / 100) - 1
|
|
||||||
index = max(0, min(index, len(ordered) - 1))
|
|
||||||
return round(ordered[index], 3)
|
|
||||||
|
|
||||||
|
|
||||||
def require_json(response: httpx.Response, expected_status: int) -> dict:
|
|
||||||
if response.status_code != expected_status:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"{response.request.method} {response.request.url} returned "
|
|
||||||
f"{response.status_code}, expected {expected_status}: {response.text}"
|
|
||||||
)
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
|
|
||||||
def create_fixture(
|
|
||||||
base_url: str,
|
|
||||||
history_size: int,
|
|
||||||
) -> tuple[str, str]:
|
|
||||||
suffix = uuid.uuid4().hex[:12]
|
|
||||||
|
|
||||||
with httpx.Client(base_url=base_url, timeout=30.0) as client:
|
|
||||||
user = require_json(
|
|
||||||
client.post(
|
|
||||||
"/api/v1/users",
|
|
||||||
json={
|
|
||||||
"username": f"bench_{suffix}",
|
|
||||||
"display_name": "Benchmark User",
|
|
||||||
},
|
|
||||||
),
|
|
||||||
201,
|
|
||||||
)
|
|
||||||
user_id = user["id"]
|
|
||||||
|
|
||||||
chat = require_json(
|
|
||||||
client.post(
|
|
||||||
"/api/v1/chats",
|
|
||||||
headers={"X-User-Id": user_id},
|
|
||||||
json={
|
|
||||||
"title": "Benchmark chat",
|
|
||||||
"member_ids": [user_id],
|
|
||||||
},
|
|
||||||
),
|
|
||||||
201,
|
|
||||||
)
|
|
||||||
chat_id = chat["id"]
|
|
||||||
|
|
||||||
headers = {"X-User-Id": user_id, "Connection": "close"}
|
|
||||||
|
|
||||||
for number in range(history_size):
|
|
||||||
last_error = None
|
|
||||||
|
|
||||||
for attempt in range(3):
|
|
||||||
try:
|
|
||||||
with httpx.Client(base_url=base_url, timeout=30.0) as client:
|
|
||||||
response = client.post(
|
|
||||||
f"/api/v1/chats/{chat_id}/messages",
|
|
||||||
headers=headers,
|
|
||||||
json={"text": f"synthetic-{number:06d}"},
|
|
||||||
)
|
|
||||||
|
|
||||||
if response.status_code == 201:
|
|
||||||
break
|
|
||||||
|
|
||||||
last_error = RuntimeError(
|
|
||||||
f"message {number}: got {response.status_code}: {response.text}"
|
|
||||||
)
|
|
||||||
|
|
||||||
except httpx.HTTPError as error:
|
|
||||||
last_error = error
|
|
||||||
|
|
||||||
time.sleep(0.05 * (attempt + 1))
|
|
||||||
else:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"fixture failed at message {number} after 3 attempts: {last_error}"
|
|
||||||
)
|
|
||||||
|
|
||||||
if (number + 1) % 1000 == 0 or number + 1 == history_size:
|
|
||||||
print(f"fixture progress: {number + 1}/{history_size}")
|
|
||||||
|
|
||||||
return user_id, chat_id
|
|
||||||
|
|
||||||
def get_metrics(base_url: str) -> dict:
|
|
||||||
with httpx.Client(base_url=base_url, timeout=10.0) as client:
|
|
||||||
return require_json(client.get("/internal/metrics"), 200)
|
|
||||||
|
|
||||||
|
|
||||||
def prepare_deep_cursor(
|
|
||||||
base_url: str,
|
|
||||||
user_id: str,
|
|
||||||
chat_id: str,
|
|
||||||
history_size: int,
|
|
||||||
page_limit: int,
|
|
||||||
depth_fraction: float,
|
|
||||||
) -> str:
|
|
||||||
pages_before_cursor = max(
|
|
||||||
1,
|
|
||||||
int(history_size * depth_fraction) // page_limit,
|
|
||||||
)
|
|
||||||
|
|
||||||
cursor = None
|
|
||||||
headers = {"X-User-Id": user_id}
|
|
||||||
|
|
||||||
with httpx.Client(base_url=base_url, timeout=30.0) as client:
|
|
||||||
for _ in range(pages_before_cursor):
|
|
||||||
params = {"limit": page_limit}
|
|
||||||
if cursor is not None:
|
|
||||||
params["cursor"] = cursor
|
|
||||||
|
|
||||||
body = require_json(
|
|
||||||
client.get(
|
|
||||||
f"/api/v1/chats/{chat_id}/messages",
|
|
||||||
headers=headers,
|
|
||||||
params=params,
|
|
||||||
),
|
|
||||||
200,
|
|
||||||
)
|
|
||||||
cursor = body["next_cursor"]
|
|
||||||
|
|
||||||
if cursor is None:
|
|
||||||
raise RuntimeError(
|
|
||||||
"history ended before requested cursor depth; "
|
|
||||||
"start with a fresh container"
|
|
||||||
)
|
|
||||||
|
|
||||||
return cursor
|
|
||||||
|
|
||||||
|
|
||||||
def run_requests(
|
|
||||||
base_url: str,
|
|
||||||
user_id: str,
|
|
||||||
chat_id: str,
|
|
||||||
cursor: str,
|
|
||||||
page_limit: int,
|
|
||||||
concurrency: int,
|
|
||||||
seconds: int,
|
|
||||||
record_latencies: bool,
|
|
||||||
) -> tuple[int, int, list[float], dict[str, int]]:
|
|
||||||
deadline = time.perf_counter() + seconds
|
|
||||||
lock = threading.Lock()
|
|
||||||
|
|
||||||
successes = 0
|
|
||||||
failures = 0
|
|
||||||
latencies: list[float] = []
|
|
||||||
status_counts: dict[str, int] = {}
|
|
||||||
|
|
||||||
def worker() -> None:
|
|
||||||
nonlocal successes, failures
|
|
||||||
|
|
||||||
headers = {"X-User-Id": user_id}
|
|
||||||
with httpx.Client(base_url=base_url, timeout=10.0) as client:
|
|
||||||
while time.perf_counter() < deadline:
|
|
||||||
started = time.perf_counter()
|
|
||||||
try:
|
|
||||||
response = client.get(
|
|
||||||
f"/api/v1/chats/{chat_id}/messages",
|
|
||||||
headers=headers,
|
|
||||||
params={"limit": page_limit, "cursor": cursor},
|
|
||||||
)
|
|
||||||
elapsed_ms = (time.perf_counter() - started) * 1000
|
|
||||||
|
|
||||||
with lock:
|
|
||||||
key = str(response.status_code)
|
|
||||||
status_counts[key] = status_counts.get(key, 0) + 1
|
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
successes += 1
|
|
||||||
if record_latencies:
|
|
||||||
latencies.append(elapsed_ms)
|
|
||||||
else:
|
|
||||||
failures += 1
|
|
||||||
|
|
||||||
except httpx.HTTPError:
|
|
||||||
with lock:
|
|
||||||
failures += 1
|
|
||||||
status_counts["transport_error"] = (
|
|
||||||
status_counts.get("transport_error", 0) + 1
|
|
||||||
)
|
|
||||||
|
|
||||||
with ThreadPoolExecutor(max_workers=concurrency) as executor:
|
|
||||||
futures = [executor.submit(worker) for _ in range(concurrency)]
|
|
||||||
for future in futures:
|
|
||||||
future.result()
|
|
||||||
|
|
||||||
return successes, failures, latencies, status_counts
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description="Track 1: deep cursor benchmark for in-memory message history."
|
|
||||||
)
|
|
||||||
parser.add_argument("--base-url", required=True)
|
|
||||||
parser.add_argument("--history-size", type=int, required=True)
|
|
||||||
parser.add_argument("--concurrency", type=int, required=True)
|
|
||||||
parser.add_argument("--warmup-seconds", type=int, default=5)
|
|
||||||
parser.add_argument("--duration-seconds", type=int, default=15)
|
|
||||||
parser.add_argument("--page-limit", type=int, default=100)
|
|
||||||
parser.add_argument("--depth-fraction", type=float, default=0.8)
|
|
||||||
parser.add_argument("--implementation", required=True)
|
|
||||||
parser.add_argument("--git-commit", required=True)
|
|
||||||
parser.add_argument("--output", required=True)
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
if args.history_size < args.page_limit * 2:
|
|
||||||
raise SystemExit("history-size must contain at least two pages")
|
|
||||||
if args.concurrency < 1:
|
|
||||||
raise SystemExit("concurrency must be >= 1")
|
|
||||||
if not 0.1 <= args.depth_fraction < 1.0:
|
|
||||||
raise SystemExit("depth-fraction must be in [0.1, 1.0)")
|
|
||||||
|
|
||||||
print(
|
|
||||||
f"fixture: history={args.history_size}, "
|
|
||||||
f"concurrency={args.concurrency}, "
|
|
||||||
f"deep cursor={args.depth_fraction:.0%}"
|
|
||||||
)
|
|
||||||
|
|
||||||
user_id, chat_id = create_fixture(args.base_url, args.history_size)
|
|
||||||
|
|
||||||
metrics_before = get_metrics(args.base_url)
|
|
||||||
if metrics_before["messages"] != args.history_size:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"expected exactly {args.history_size} messages, got "
|
|
||||||
f"{metrics_before['messages']}. "
|
|
||||||
"Run each scenario in a fresh container."
|
|
||||||
)
|
|
||||||
|
|
||||||
cursor = prepare_deep_cursor(
|
|
||||||
args.base_url,
|
|
||||||
user_id,
|
|
||||||
chat_id,
|
|
||||||
args.history_size,
|
|
||||||
args.page_limit,
|
|
||||||
args.depth_fraction,
|
|
||||||
)
|
|
||||||
|
|
||||||
print(f"warmup: {args.warmup_seconds}s")
|
|
||||||
run_requests(
|
|
||||||
args.base_url,
|
|
||||||
user_id,
|
|
||||||
chat_id,
|
|
||||||
cursor,
|
|
||||||
args.page_limit,
|
|
||||||
args.concurrency,
|
|
||||||
args.warmup_seconds,
|
|
||||||
record_latencies=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
print(f"measurement: {args.duration_seconds}s")
|
|
||||||
started_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
||||||
successes, failures, latencies, status_counts = run_requests(
|
|
||||||
args.base_url,
|
|
||||||
user_id,
|
|
||||||
chat_id,
|
|
||||||
cursor,
|
|
||||||
args.page_limit,
|
|
||||||
args.concurrency,
|
|
||||||
args.duration_seconds,
|
|
||||||
record_latencies=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
metrics_after = get_metrics(args.base_url)
|
|
||||||
attempted = successes + failures
|
|
||||||
|
|
||||||
result = {
|
|
||||||
"experiment": "track1-inmemory-deep-cursor",
|
|
||||||
"timestamp_utc": started_at,
|
|
||||||
"implementation": args.implementation,
|
|
||||||
"git_commit": args.git_commit,
|
|
||||||
"container_limits": {
|
|
||||||
"cpus": 2,
|
|
||||||
"memory": "512m",
|
|
||||||
},
|
|
||||||
"workload": {
|
|
||||||
"endpoint": "GET /api/v1/chats/{chat_id}/messages",
|
|
||||||
"history_size": args.history_size,
|
|
||||||
"page_limit": args.page_limit,
|
|
||||||
"cursor_depth_fraction": args.depth_fraction,
|
|
||||||
"concurrency": args.concurrency,
|
|
||||||
"warmup_seconds": args.warmup_seconds,
|
|
||||||
"duration_seconds": args.duration_seconds,
|
|
||||||
"writes_during_measurement": False,
|
|
||||||
"client": "httpx synchronous client; one instance per worker",
|
|
||||||
},
|
|
||||||
"results": {
|
|
||||||
"attempted_requests": attempted,
|
|
||||||
"successful_requests": successes,
|
|
||||||
"failed_requests": failures,
|
|
||||||
"error_rate_percent": round(
|
|
||||||
(failures / attempted * 100) if attempted else 0.0,
|
|
||||||
4,
|
|
||||||
),
|
|
||||||
"successful_rps": round(successes / args.duration_seconds, 3),
|
|
||||||
"latency_ms": {
|
|
||||||
"p50": percentile(latencies, 50),
|
|
||||||
"p95": percentile(latencies, 95),
|
|
||||||
"p99": percentile(latencies, 99),
|
|
||||||
},
|
|
||||||
"status_counts": status_counts,
|
|
||||||
"rss_before_bytes": metrics_before["rss_bytes"],
|
|
||||||
"rss_after_bytes": metrics_after["rss_bytes"],
|
|
||||||
"rss_after_mib": round(
|
|
||||||
metrics_after["rss_bytes"] / (1024 * 1024),
|
|
||||||
3,
|
|
||||||
),
|
|
||||||
"messages_after": metrics_after["messages"],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
output = Path(args.output)
|
|
||||||
output.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
output.write_text(
|
|
||||||
json.dumps(result, ensure_ascii=False, indent=2),
|
|
||||||
encoding="utf-8",
|
|
||||||
)
|
|
||||||
|
|
||||||
print(json.dumps(result["results"], ensure_ascii=False, indent=2))
|
|
||||||
print(f"saved: {output}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,227 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
import urllib.error
|
|
||||||
import urllib.parse
|
|
||||||
import urllib.request
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
|
|
||||||
def request(
|
|
||||||
base_url: str,
|
|
||||||
method: str,
|
|
||||||
path: str,
|
|
||||||
body: bytes | None = None,
|
|
||||||
headers: dict[str, str] | None = None,
|
|
||||||
) -> tuple[int, dict, dict[str, str]]:
|
|
||||||
request_headers = {"Accept": "application/json"}
|
|
||||||
if headers:
|
|
||||||
request_headers.update(headers)
|
|
||||||
|
|
||||||
req = urllib.request.Request(
|
|
||||||
f"{base_url.rstrip('/')}{path}",
|
|
||||||
data=body,
|
|
||||||
headers=request_headers,
|
|
||||||
method=method,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(req, timeout=10) as response:
|
|
||||||
raw = response.read().decode("utf-8")
|
|
||||||
return response.status, json.loads(raw) if raw else {}, dict(response.headers.items())
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
raw = exc.read().decode("utf-8")
|
|
||||||
return exc.code, json.loads(raw) if raw else {}, dict(exc.headers.items())
|
|
||||||
|
|
||||||
|
|
||||||
def json_request(
|
|
||||||
base_url: str,
|
|
||||||
method: str,
|
|
||||||
path: str,
|
|
||||||
payload: dict,
|
|
||||||
user_id: str | None = None,
|
|
||||||
) -> tuple[int, dict, dict[str, str]]:
|
|
||||||
headers = {"Content-Type": "application/json"}
|
|
||||||
if user_id:
|
|
||||||
headers["X-User-Id"] = user_id
|
|
||||||
return request(
|
|
||||||
base_url,
|
|
||||||
method,
|
|
||||||
path,
|
|
||||||
json.dumps(payload).encode("utf-8"),
|
|
||||||
headers,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def expect_error(status: int, body: dict, expected_status: int, expected_code: str) -> None:
|
|
||||||
assert status == expected_status, f"expected HTTP {expected_status}, got {status}: {body}"
|
|
||||||
assert body.get("error", {}).get("code") == expected_code, (
|
|
||||||
f"expected error.code={expected_code!r}, got {body}"
|
|
||||||
)
|
|
||||||
assert body.get("error", {}).get("request_id"), f"missing error request_id: {body}"
|
|
||||||
|
|
||||||
def create_user(base_url: str, suffix: str) -> dict:
|
|
||||||
status, body, _ = json_request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/users",
|
|
||||||
{
|
|
||||||
"username": f"u_{suffix}",
|
|
||||||
"display_name": f"User {suffix}",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
assert status == 201, f"create user failed: {status}, {body}"
|
|
||||||
return body
|
|
||||||
|
|
||||||
def create_chat(base_url: str, owner_id: str, member_ids: list[str], suffix: str) -> dict:
|
|
||||||
status, body, _ = json_request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/chats",
|
|
||||||
{
|
|
||||||
"title": f"Extra tests {suffix}",
|
|
||||||
"member_ids": member_ids,
|
|
||||||
},
|
|
||||||
owner_id,
|
|
||||||
)
|
|
||||||
assert status == 201, f"create chat failed: {status}, {body}"
|
|
||||||
return body
|
|
||||||
|
|
||||||
|
|
||||||
def test_malformed_json(base_url: str) -> None:
|
|
||||||
status, body, _ = request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/users",
|
|
||||||
b'{"username": "bad_json",',
|
|
||||||
{"Content-Type": "application/json"},
|
|
||||||
)
|
|
||||||
expect_error(status, body, 400, "invalid_request")
|
|
||||||
|
|
||||||
|
|
||||||
def test_foreign_chat(base_url: str, owner: dict, outsider: dict, suffix: str) -> None:
|
|
||||||
chat = create_chat(base_url, owner["id"], [owner["id"]], suffix)
|
|
||||||
status, body, _ = request(
|
|
||||||
base_url,
|
|
||||||
"GET",
|
|
||||||
f"/api/v1/chats/{chat['id']}/messages",
|
|
||||||
headers={"X-User-Id": outsider["id"]},
|
|
||||||
)
|
|
||||||
expect_error(status, body, 404, "not_found")
|
|
||||||
|
|
||||||
|
|
||||||
def test_empty_message(base_url: str, owner: dict, suffix: str) -> None:
|
|
||||||
chat = create_chat(base_url, owner["id"], [owner["id"]], suffix)
|
|
||||||
status, body, _ = json_request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
f"/api/v1/chats/{chat['id']}/messages",
|
|
||||||
{"text": " "},
|
|
||||||
owner["id"],
|
|
||||||
)
|
|
||||||
expect_error(status, body, 400, "invalid_request")
|
|
||||||
|
|
||||||
|
|
||||||
def test_duplicate_username(base_url: str, suffix: str) -> None:
|
|
||||||
username = f"dup_{suffix}"
|
|
||||||
|
|
||||||
status, body, _ = json_request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/users",
|
|
||||||
{"username": username, "display_name": "Original"},
|
|
||||||
)
|
|
||||||
assert status == 201, f"first user creation failed: {status}, {body}"
|
|
||||||
|
|
||||||
status, body, _ = json_request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/users",
|
|
||||||
{"username": username, "display_name": "Duplicate"},
|
|
||||||
)
|
|
||||||
expect_error(status, body, 409, "conflict")
|
|
||||||
|
|
||||||
|
|
||||||
def test_message_pagination(base_url: str, owner: dict, suffix: str) -> None:
|
|
||||||
chat = create_chat(base_url, owner["id"], [owner["id"]], suffix)
|
|
||||||
expected_texts = [f"page_{suffix}_{index}" for index in range(7)]
|
|
||||||
|
|
||||||
for text in expected_texts:
|
|
||||||
status, body, _ = json_request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
f"/api/v1/chats/{chat['id']}/messages",
|
|
||||||
{"text": text},
|
|
||||||
owner["id"],
|
|
||||||
)
|
|
||||||
assert status == 201, f"message creation failed: {status}, {body}"
|
|
||||||
|
|
||||||
received = []
|
|
||||||
cursor = None
|
|
||||||
|
|
||||||
while True:
|
|
||||||
query = {"limit": "3"}
|
|
||||||
if cursor:
|
|
||||||
query["cursor"] = cursor
|
|
||||||
|
|
||||||
status, body, _ = request(
|
|
||||||
base_url,
|
|
||||||
"GET",
|
|
||||||
f"/api/v1/chats/{chat['id']}/messages?{urllib.parse.urlencode(query)}",
|
|
||||||
headers={"X-User-Id": owner["id"]},
|
|
||||||
)
|
|
||||||
assert status == 200, f"history request failed: {status}, {body}"
|
|
||||||
|
|
||||||
received.extend(body["items"])
|
|
||||||
cursor = body["next_cursor"]
|
|
||||||
if cursor is None:
|
|
||||||
break
|
|
||||||
|
|
||||||
received_ids = [message["id"] for message in received]
|
|
||||||
received_texts = [message["text"] for message in received]
|
|
||||||
|
|
||||||
assert len(received) == len(expected_texts), (
|
|
||||||
f"expected {len(expected_texts)} messages, got {len(received)}"
|
|
||||||
)
|
|
||||||
assert len(set(received_ids)) == len(expected_texts), "pagination returned duplicate message IDs"
|
|
||||||
assert received_texts == expected_texts, (
|
|
||||||
f"unexpected message order/content: {received_texts}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
parser = argparse.ArgumentParser()
|
|
||||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
suffix = uuid.uuid4().hex[:12]
|
|
||||||
owner = create_user(args.base_url, f"owner_{suffix}")
|
|
||||||
outsider = create_user(args.base_url, f"outsider_{suffix}")
|
|
||||||
|
|
||||||
tests = [
|
|
||||||
("malformed JSON -> 400 invalid_request", lambda: test_malformed_json(args.base_url)),
|
|
||||||
("foreign chat -> 404 not_found", lambda: test_foreign_chat(args.base_url, owner, outsider, suffix)),
|
|
||||||
("empty message -> 400 invalid_request", lambda: test_empty_message(args.base_url, owner, suffix)),
|
|
||||||
("duplicate username -> 409 conflict", lambda: test_duplicate_username(args.base_url, suffix)),
|
|
||||||
("message pagination across pages", lambda: test_message_pagination(args.base_url, owner, suffix)),
|
|
||||||
]
|
|
||||||
|
|
||||||
for name, test in tests:
|
|
||||||
test()
|
|
||||||
print(f"PASS: {name}")
|
|
||||||
|
|
||||||
print("PASS: extra lab1 scenarios (5/5)")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
raise SystemExit(main())
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAIL: {exc}", file=sys.stderr)
|
|
||||||
raise SystemExit(1)
|
|
||||||
except Exception as exc:
|
|
||||||
print(f"FAIL: unexpected error: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
||||||
raise SystemExit(1)
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
|
|
||||||
CONTROL_TEXT = "CONTROL_SECRET_MESSAGE_MUST_NOT_BE_IN_LOGS"
|
|
||||||
|
|
||||||
|
|
||||||
def request(
|
|
||||||
base_url: str,
|
|
||||||
method: str,
|
|
||||||
path: str,
|
|
||||||
payload: dict | None = None,
|
|
||||||
user_id: str | None = None,
|
|
||||||
) -> tuple[int, dict]:
|
|
||||||
headers = {"Accept": "application/json"}
|
|
||||||
data = None
|
|
||||||
|
|
||||||
if payload is not None:
|
|
||||||
data = json.dumps(payload).encode("utf-8")
|
|
||||||
headers["Content-Type"] = "application/json"
|
|
||||||
|
|
||||||
if user_id is not None:
|
|
||||||
headers["X-User-Id"] = user_id
|
|
||||||
|
|
||||||
req = urllib.request.Request(
|
|
||||||
f"{base_url.rstrip('/')}{path}",
|
|
||||||
data=data,
|
|
||||||
headers=headers,
|
|
||||||
method=method,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(req, timeout=10) as response:
|
|
||||||
raw = response.read().decode("utf-8")
|
|
||||||
return response.status, json.loads(raw) if raw else {}
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
raw = exc.read().decode("utf-8")
|
|
||||||
return exc.code, json.loads(raw) if raw else {}
|
|
||||||
|
|
||||||
|
|
||||||
def require(status: int, body: dict, expected: int, action: str) -> None:
|
|
||||||
assert status == expected, f"{action}: expected HTTP {expected}, got {status}: {body}"
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
parser = argparse.ArgumentParser()
|
|
||||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
suffix = uuid.uuid4().hex[:12]
|
|
||||||
|
|
||||||
status, user = request(
|
|
||||||
args.base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/users",
|
|
||||||
{
|
|
||||||
"username": f"log_{suffix}",
|
|
||||||
"display_name": "Log safety test",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
require(status, user, 201, "create user")
|
|
||||||
|
|
||||||
status, chat = request(
|
|
||||||
args.base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/chats",
|
|
||||||
{
|
|
||||||
"title": "Log safety test",
|
|
||||||
"member_ids": [user["id"]],
|
|
||||||
},
|
|
||||||
user["id"],
|
|
||||||
)
|
|
||||||
require(status, chat, 201, "create chat")
|
|
||||||
|
|
||||||
status, message = request(
|
|
||||||
args.base_url,
|
|
||||||
"POST",
|
|
||||||
f"/api/v1/chats/{chat['id']}/messages",
|
|
||||||
{"text": CONTROL_TEXT},
|
|
||||||
user["id"],
|
|
||||||
)
|
|
||||||
require(status, message, 201, "create control message")
|
|
||||||
|
|
||||||
print("PASS: control message accepted with HTTP 201")
|
|
||||||
print(f"CONTROL_TEXT={CONTROL_TEXT}")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
raise SystemExit(main())
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAIL: {exc}", file=sys.stderr)
|
|
||||||
raise SystemExit(1)
|
|
||||||
except Exception as exc:
|
|
||||||
print(f"FAIL: unexpected error: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
||||||
raise SystemExit(1)
|
|
||||||
@@ -1,212 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import concurrent.futures
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
import urllib.error
|
|
||||||
import urllib.parse
|
|
||||||
import urllib.request
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
|
|
||||||
TOTAL_CLIENTS = 10
|
|
||||||
MESSAGES_PER_CLIENT = 10
|
|
||||||
EXPECTED_MESSAGES = TOTAL_CLIENTS * MESSAGES_PER_CLIENT
|
|
||||||
|
|
||||||
|
|
||||||
def request(
|
|
||||||
base_url: str,
|
|
||||||
method: str,
|
|
||||||
path: str,
|
|
||||||
payload: dict | None = None,
|
|
||||||
user_id: str | None = None,
|
|
||||||
) -> tuple[int, dict]:
|
|
||||||
headers = {"Accept": "application/json"}
|
|
||||||
|
|
||||||
data = None
|
|
||||||
if payload is not None:
|
|
||||||
data = json.dumps(payload).encode("utf-8")
|
|
||||||
headers["Content-Type"] = "application/json"
|
|
||||||
|
|
||||||
if user_id is not None:
|
|
||||||
headers["X-User-Id"] = user_id
|
|
||||||
|
|
||||||
req = urllib.request.Request(
|
|
||||||
f"{base_url.rstrip('/')}{path}",
|
|
||||||
data=data,
|
|
||||||
headers=headers,
|
|
||||||
method=method,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(req, timeout=15) as response:
|
|
||||||
raw = response.read().decode("utf-8")
|
|
||||||
return response.status, json.loads(raw) if raw else {}
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
raw = exc.read().decode("utf-8")
|
|
||||||
return exc.code, json.loads(raw) if raw else {}
|
|
||||||
|
|
||||||
|
|
||||||
def require_status(status: int, body: dict, expected: int, action: str) -> None:
|
|
||||||
assert status == expected, f"{action}: expected HTTP {expected}, got {status}: {body}"
|
|
||||||
|
|
||||||
|
|
||||||
def create_user(base_url: str, suffix: str, index: int) -> dict:
|
|
||||||
status, body = request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/users",
|
|
||||||
{
|
|
||||||
"username": f"race_{suffix}_{index}",
|
|
||||||
"display_name": f"Race client {index}",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
require_status(status, body, 201, f"create user {index}")
|
|
||||||
return body
|
|
||||||
|
|
||||||
|
|
||||||
def create_chat(base_url: str, owner_id: str, member_ids: list[str], suffix: str) -> dict:
|
|
||||||
status, body = request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
"/api/v1/chats",
|
|
||||||
{
|
|
||||||
"title": f"Race test {suffix}",
|
|
||||||
"member_ids": member_ids,
|
|
||||||
},
|
|
||||||
owner_id,
|
|
||||||
)
|
|
||||||
require_status(status, body, 201, "create chat")
|
|
||||||
return body
|
|
||||||
|
|
||||||
|
|
||||||
def send_message(
|
|
||||||
base_url: str,
|
|
||||||
chat_id: str,
|
|
||||||
user_id: str,
|
|
||||||
client_index: int,
|
|
||||||
message_index: int,
|
|
||||||
suffix: str,
|
|
||||||
) -> dict:
|
|
||||||
text = f"race_{suffix}_client_{client_index}_message_{message_index}"
|
|
||||||
status, body = request(
|
|
||||||
base_url,
|
|
||||||
"POST",
|
|
||||||
f"/api/v1/chats/{chat_id}/messages",
|
|
||||||
{"text": text},
|
|
||||||
user_id,
|
|
||||||
)
|
|
||||||
require_status(
|
|
||||||
status,
|
|
||||||
body,
|
|
||||||
201,
|
|
||||||
f"send client={client_index}, message={message_index}",
|
|
||||||
)
|
|
||||||
return body
|
|
||||||
|
|
||||||
|
|
||||||
def read_all_messages(base_url: str, chat_id: str, user_id: str) -> list[dict]:
|
|
||||||
items: list[dict] = []
|
|
||||||
cursor: str | None = None
|
|
||||||
|
|
||||||
while True:
|
|
||||||
query = {"limit": "100"}
|
|
||||||
if cursor is not None:
|
|
||||||
query["cursor"] = cursor
|
|
||||||
|
|
||||||
status, body = request(
|
|
||||||
base_url,
|
|
||||||
"GET",
|
|
||||||
f"/api/v1/chats/{chat_id}/messages?{urllib.parse.urlencode(query)}",
|
|
||||||
user_id=user_id,
|
|
||||||
)
|
|
||||||
require_status(status, body, 200, "read messages")
|
|
||||||
|
|
||||||
items.extend(body["items"])
|
|
||||||
cursor = body["next_cursor"]
|
|
||||||
if cursor is None:
|
|
||||||
return items
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description="Race test: 10 clients × 10 messages, then verify 100 unique messages."
|
|
||||||
)
|
|
||||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
suffix = uuid.uuid4().hex[:12]
|
|
||||||
|
|
||||||
users = [
|
|
||||||
create_user(args.base_url, suffix, index)
|
|
||||||
for index in range(TOTAL_CLIENTS)
|
|
||||||
]
|
|
||||||
chat = create_chat(
|
|
||||||
args.base_url,
|
|
||||||
users[0]["id"],
|
|
||||||
[user["id"] for user in users],
|
|
||||||
suffix,
|
|
||||||
)
|
|
||||||
|
|
||||||
jobs = [
|
|
||||||
(
|
|
||||||
args.base_url,
|
|
||||||
chat["id"],
|
|
||||||
users[client_index]["id"],
|
|
||||||
client_index,
|
|
||||||
message_index,
|
|
||||||
suffix,
|
|
||||||
)
|
|
||||||
for client_index in range(TOTAL_CLIENTS)
|
|
||||||
for message_index in range(MESSAGES_PER_CLIENT)
|
|
||||||
]
|
|
||||||
|
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=TOTAL_CLIENTS) as executor:
|
|
||||||
created = list(executor.map(lambda job: send_message(*job), jobs))
|
|
||||||
|
|
||||||
created_ids = [message["id"] for message in created]
|
|
||||||
assert len(created) == EXPECTED_MESSAGES, (
|
|
||||||
f"POST result count: expected {EXPECTED_MESSAGES}, got {len(created)}"
|
|
||||||
)
|
|
||||||
assert len(set(created_ids)) == EXPECTED_MESSAGES, (
|
|
||||||
f"POST returned duplicate IDs: {len(set(created_ids))}/{EXPECTED_MESSAGES} unique"
|
|
||||||
)
|
|
||||||
|
|
||||||
messages = read_all_messages(args.base_url, chat["id"], users[0]["id"])
|
|
||||||
ids = [message["id"] for message in messages]
|
|
||||||
texts = [message["text"] for message in messages]
|
|
||||||
|
|
||||||
expected_texts = {
|
|
||||||
f"race_{suffix}_client_{client_index}_message_{message_index}"
|
|
||||||
for client_index in range(TOTAL_CLIENTS)
|
|
||||||
for message_index in range(MESSAGES_PER_CLIENT)
|
|
||||||
}
|
|
||||||
|
|
||||||
assert len(messages) == EXPECTED_MESSAGES, (
|
|
||||||
f"history count: expected {EXPECTED_MESSAGES}, got {len(messages)}"
|
|
||||||
)
|
|
||||||
assert len(set(ids)) == EXPECTED_MESSAGES, (
|
|
||||||
f"history contains duplicate IDs: {len(set(ids))}/{EXPECTED_MESSAGES} unique"
|
|
||||||
)
|
|
||||||
assert set(texts) == expected_texts, (
|
|
||||||
"history is missing or contains unexpected messages"
|
|
||||||
)
|
|
||||||
|
|
||||||
print(f"PASS: parallel POST requests: {len(created)}/{EXPECTED_MESSAGES}")
|
|
||||||
print(f"PASS: unique IDs returned by POST: {len(set(created_ids))}/{EXPECTED_MESSAGES}")
|
|
||||||
print(f"PASS: history items after writes: {len(messages)}/{EXPECTED_MESSAGES}")
|
|
||||||
print(f"PASS: unique IDs in history: {len(set(ids))}/{EXPECTED_MESSAGES}")
|
|
||||||
print("PASS: race test (10 clients x 10 messages = 100 unique messages)")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
raise SystemExit(main())
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAIL: {exc}", file=sys.stderr)
|
|
||||||
raise SystemExit(1)
|
|
||||||
except Exception as exc:
|
|
||||||
print(f"FAIL: unexpected error: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
||||||
raise SystemExit(1)
|
|
||||||
Reference in New Issue
Block a user