Убрать устаревшие файлы lab1 и неиспользуемый init.sql
Тесты lab1 в student-tests работали через X-User-Id и для lab2 неактуальны. infra/postgres/init.sql дублировал миграции и нигде не подключался. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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 запускается с подавленным выводом.
|
||||||
|
|||||||
@@ -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