forked from mtusi2026/mtusi2026lab5
абораторная 5: брокер, worker, outbox, варианты изображений, тесты отказов (оценка 4)
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
|
||||
import json
|
||||
import platform
|
||||
import sys
|
||||
|
||||
from common import call, check, compose_output, docker, new_user, seen_instances
|
||||
|
||||
|
||||
def main():
|
||||
info = json.loads(docker("info", "--format", "{{json .}}"))
|
||||
print(f"host: {platform.system()} {platform.release()}, {platform.processor() or platform.machine()}; "
|
||||
f"client Python {platform.python_version()}")
|
||||
print(f"Docker {docker('version', '--format', '{{.Server.Version}}')}, "
|
||||
f"{compose_output('version').strip()}; Docker VM: {info.get('NCPU')} CPU, "
|
||||
f"{int(info.get('MemTotal', 0)) / 2**30:.1f} GiB RAM, {info.get('OperatingSystem')}")
|
||||
|
||||
print()
|
||||
print(compose_output("ps", "-a", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}\t{{.Ports}}").strip())
|
||||
for one_shot in ("migrate", "s3-init"):
|
||||
status = compose_output("ps", "-a", "--format", "{{.Status}}", one_shot).strip()
|
||||
check(status.startswith("Exited (0)"), f"{one_shot} service must finish with exit code 0")
|
||||
|
||||
config = json.loads(compose_output("config", "--format", "json"))
|
||||
services = config["services"]
|
||||
containers = compose_output("ps", "-q").split()
|
||||
rows = [json.loads(line) for line in docker("inspect", "--format", "{{json .}}", *containers).splitlines()]
|
||||
print()
|
||||
print("container image cpus memory host ports networks")
|
||||
api_count = 0
|
||||
for row in sorted(rows, key=lambda r: r["Name"]):
|
||||
labels = row["Config"]["Labels"]
|
||||
service = labels.get("com.docker.compose.service")
|
||||
limits = row["HostConfig"]
|
||||
cpus = limits.get("NanoCpus", 0) / 1e9
|
||||
memory = limits.get("Memory", 0) // 2**20
|
||||
ports = sorted({f"{b['HostIp']}:{b['HostPort']}" for bindings in (row["NetworkSettings"]["Ports"] or {}).values()
|
||||
for b in (bindings or [])})
|
||||
networks = sorted(name.split("_", 1)[-1] for name in row["NetworkSettings"]["Networks"])
|
||||
print(f"{row['Name'].lstrip('/'):<28} {row['Config']['Image']:<24} {cpus:>4.2f} {memory:>4} MiB "
|
||||
f"{','.join(ports) or '-':<23} {','.join(networks)}")
|
||||
check(cpus > 0 and memory > 0, f"{service}: no CPU/RAM limit")
|
||||
if service == "api":
|
||||
api_count += 1
|
||||
check(not ports, "api must not publish ports: everything goes through the balancer")
|
||||
if service == "lb":
|
||||
check(ports and all(p.startswith("127.0.0.1:") for p in ports), "lb must listen on 127.0.0.1 only")
|
||||
if service in ("postgres", "redis", "s3", "janitor", "rabbitmq", "worker", "dispatcher"):
|
||||
check(not ports and networks == ["data"], f"{service} must be only in the internal data network")
|
||||
check(api_count >= 2, "need at least 2 api replicas")
|
||||
running = {r["Config"]["Labels"].get("com.docker.compose.service") for r in rows if r["State"]["Running"]}
|
||||
check({"rabbitmq", "worker", "dispatcher"} <= running, "lab5: broker, worker and dispatcher must be running")
|
||||
check(any(v.get("target") == "/var/lib/rabbitmq" and v.get("type") == "volume"
|
||||
for v in services["rabbitmq"].get("volumes", [])), "rabbitmq needs a persistent volume")
|
||||
check(services["rabbitmq"].get("hostname") == "rabbitmq", "rabbitmq needs a fixed hostname (node data dir)")
|
||||
check(all("container_name" not in s for s in services.values()), "container_name prevents scaling")
|
||||
check(config["networks"]["data"].get("internal") is True, "data network must be internal")
|
||||
check("data" not in services["lb"]["networks"], "lb must not reach postgres/redis")
|
||||
|
||||
print()
|
||||
for name, service in sorted(services.items()):
|
||||
secrets = sorted(s["source"] for s in service.get("secrets", []))
|
||||
print(f"secrets of {name}: {secrets or '-'}")
|
||||
check(not services["lb"].get("secrets"), "lb gets no secrets")
|
||||
check(sorted(s["source"] for s in services["migrate"]["secrets"]) == ["database_url"], "migrate needs only database_url")
|
||||
for name in ("api", "janitor", "worker"):
|
||||
names = {s["source"] for s in services[name]["secrets"]}
|
||||
check(not names & {"s3_root_user", "s3_root_password", "s3_config"}, f"{name} must not get S3 admin keys")
|
||||
check({"s3_access_key_id", "s3_secret_access_key"} <= names, f"{name} needs the limited S3 key")
|
||||
broker_secrets = {"broker_url_dispatcher", "broker_url_worker", "rabbitmq_definitions"}
|
||||
for name in ("api", "janitor", "lb", "migrate"):
|
||||
names = {s["source"] for s in services[name].get("secrets", [])}
|
||||
check(not names & broker_secrets, f"{name} must not get broker credentials (API uses the outbox)")
|
||||
check({s["source"] for s in services["dispatcher"]["secrets"]} == {"database_url", "broker_url_dispatcher"},
|
||||
"dispatcher: only database_url and its own broker user")
|
||||
check(not {s["source"] for s in services["dispatcher"]["secrets"]} & {"s3_access_key_id", "s3_secret_access_key"},
|
||||
"dispatcher needs no S3 key")
|
||||
|
||||
user = new_user("stack")
|
||||
served = seen_instances(user["token"])
|
||||
print()
|
||||
print(f"through http://127.0.0.1:8080 one session is served by {len(served)} replicas: {sorted(served)}")
|
||||
check(len(served) >= 2, "requests are not balanced")
|
||||
health = call("GET", "/health/ready", 200)
|
||||
print(f"/health/ready -> {health.status} from {health.instance}")
|
||||
print(f"PASS: {api_count} api replicas behind one entry point, no direct API ports, limits on every "
|
||||
f"container, postgres/redis/s3/janitor/rabbitmq/worker/dispatcher only in the internal data network, "
|
||||
f"S3 admin keys only in s3 and s3-init, broker credentials only in dispatcher/worker")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,359 @@
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / os.environ.get("EVIDENCE_DIR", "evidence") # по умолчанию evidence/
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
PY = sys.executable
|
||||
|
||||
STEPS = [
|
||||
("check", "offline contract check (make check)", [PY, "scripts/check_contract.py"]),
|
||||
("stack", "stand layout: replicas, ports, limits, networks, secrets, S3", [PY, "student-tests/check_stack.py"]),
|
||||
("smoke", "public smoke via the balancer (make test), with attachment", [PY, "tests/smoke.py", "--base-url", BASE_URL]),
|
||||
("jobs-variants", "lab5: thumbnail/crop/optimized, EXIF orientation, alpha, no upscale, metadata stripped",
|
||||
[PY, "student-tests/test_jobs.py", "variants"]),
|
||||
("jobs-limits", "lab5: worker limits - bytes, pixels, memory (RLIMIT_AS), time (JOB_TIMEOUT_SECONDS)",
|
||||
[PY, "student-tests/test_jobs.py", "limits"]),
|
||||
("jobs-recovery", "lab5: worker down -> 202 -> restart api+broker -> ready; broker down -> outbox waits",
|
||||
[PY, "student-tests/test_jobs.py", "worker-down", "broker-down"]),
|
||||
("jobs-outbox", "lab5: dispatcher crash between COMMIT and publish / after confirm",
|
||||
[PY, "student-tests/test_jobs.py", "outbox-crash"]),
|
||||
("jobs-crash", "lab5: worker crash after S3 PUT / after COMMIT before ack, staging cleanup, frozen worker lease",
|
||||
[PY, "student-tests/test_jobs.py", "crash-after-put", "crash-after-commit", "staging", "lease"]),
|
||||
("jobs-retry", "lab5: backoff+jitter, retry_exhausted, replay, permanent errors, DLQ",
|
||||
[PY, "student-tests/test_jobs.py", "retry", "exhausted-replay", "permanent", "dlq"]),
|
||||
("jobs-concurrency", "lab5: WORKER_CONCURRENCY consumers, prefetch 1, bounded processing",
|
||||
[PY, "student-tests/test_jobs.py", "concurrency"]),
|
||||
("attachments", "lab4: files, limits, damaged images, MIME, filenames, access, attachment_ids",
|
||||
[PY, "student-tests/test_attachments.py"]),
|
||||
("s3-security", "lab4: private bucket outside API, limited API key, no console/ports, idempotent bootstrap",
|
||||
[PY, "student-tests/test_s3_security.py"]),
|
||||
("consistency", "lab4: aborted upload, crash between S3 and DB, janitor, orphans, S3 outage",
|
||||
[PY, "student-tests/test_consistency.py"]),
|
||||
("upload-memory", "lab4: >=10 concurrent uploads, peak memory of api replicas",
|
||||
[PY, "student-tests/upload_memory.py", "--output", "evidence/upload-memory.json"]),
|
||||
("balancing", "balancing, shared sessions/data/files, X-Instance-Id", [PY, "student-tests/test_balancing.py"]),
|
||||
("idempotency", "Idempotency-Key, parallel same key via replicas", [PY, "student-tests/test_idempotency.py"]),
|
||||
("student-tests", "lab1/lab2 API tests via the balancer", [PY, "student-tests/test_api.py"]),
|
||||
("race", "lab2 races via the balancer", [PY, "student-tests/test_race.py"]),
|
||||
("db", "PostgreSQL: rollback, FK, Argon2id, unique keys, migrations", [PY, "student-tests/test_db.py"]),
|
||||
("redis", "Redis as the session store", [PY, "student-tests/redis_info.py"]),
|
||||
("explain", "EXPLAIN of the history page (full plans: explain-history.txt)", [PY, "student-tests/explain.py"]),
|
||||
("failover", "public failover test for every replica, file downloaded via the other one (make test-failover)",
|
||||
[PY, "student-tests/run_failover.py"]),
|
||||
("load", "public load generator, 30 s, concurrency 4", [PY, "tests/load.py", "--base-url", BASE_URL,
|
||||
"--duration", "30", "--concurrency", "4",
|
||||
"--output", "evidence/load.json"]),
|
||||
("failures", "Redis and PostgreSQL outages via the balancer", [PY, "student-tests/test_failures.py"]),
|
||||
("persistence", "public persistence test incl. S3 + proof of real restarts (make test-persistence)",
|
||||
[PY, "student-tests/run_persistence.py"]),
|
||||
]
|
||||
|
||||
|
||||
def git(*args):
|
||||
try:
|
||||
return subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip()
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return ""
|
||||
|
||||
|
||||
def commit():
|
||||
head = git("rev-parse", "--short", "HEAD") or "unknown"
|
||||
changed = [line for line in git("status", "--porcelain").splitlines()
|
||||
if not line[3:].startswith(("evidence/", "REPORT.md"))]
|
||||
return head + (" + uncommitted changes" if changed else "")
|
||||
|
||||
|
||||
def run_step(name, description, command):
|
||||
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8", BASE_URL=BASE_URL)
|
||||
print(f"=== {name}: {description}", flush=True)
|
||||
started = time.monotonic()
|
||||
result = subprocess.run(command, cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
seconds = time.monotonic() - started
|
||||
output = result.stdout.decode("utf-8", "replace").replace("\r\n", "\n")
|
||||
shown = " ".join(Path(part).name if part == PY else part for part in command)
|
||||
header = (f"# {name}: {description}\n# date: {time.strftime('%Y-%m-%d %H:%M:%S')}, commit: {commit()}\n"
|
||||
f"# command: {shown}\n# exit code: {result.returncode}, {seconds:.1f} s\n\n")
|
||||
(EVIDENCE / f"{name}.txt").write_text(header + output, encoding="utf-8")
|
||||
tail = [line for line in output.splitlines() if line.strip()][-3:]
|
||||
for line in tail:
|
||||
print(" " + line)
|
||||
print(f" -> {'PASS' if result.returncode == 0 else 'FAIL'} ({seconds:.0f} s), evidence/{name}.txt", flush=True)
|
||||
return result.returncode == 0, seconds
|
||||
|
||||
|
||||
def load_json(name):
|
||||
path = EVIDENCE / name
|
||||
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else None
|
||||
|
||||
|
||||
def measurements():
|
||||
"""Markdown-таблицы замеров из evidence/*.json и evidence/*.txt (для REPORT.md и summary.md)."""
|
||||
lines = []
|
||||
try:
|
||||
info = json.loads(subprocess.run(["docker", "info", "--format", "{{json .}}"], capture_output=True,
|
||||
text=True, check=True).stdout)
|
||||
docker_vm = f"{info.get('NCPU')} CPU, {int(info.get('MemTotal', 0)) / 2**30:.1f} GiB RAM"
|
||||
except (OSError, ValueError, subprocess.CalledProcessError):
|
||||
docker_vm = "unknown"
|
||||
lines.append(f"Машина: {platform.system()} {platform.release()}, {platform.processor() or platform.machine()}; "
|
||||
f"Docker VM: {docker_vm}; клиент Python {platform.python_version()}; дата прогона "
|
||||
f"{time.strftime('%Y-%m-%d')}, commit {commit()}. Лимиты контейнеров: api 1 CPU / 512 MiB "
|
||||
f"каждая, postgres, s3 (SeaweedFS) и rabbitmq по 1 CPU / 512 MiB, redis и lb по 0,5 CPU / 128 MiB, "
|
||||
f"janitor 0,25 CPU / 192 MiB, dispatcher 0,25 CPU / 128 MiB, worker 2 CPU / 1536 MiB.")
|
||||
lines.append("")
|
||||
|
||||
failover = EVIDENCE / "failover.txt"
|
||||
results = []
|
||||
if failover.exists():
|
||||
text = failover.read_text(encoding="utf-8")
|
||||
stopped = re.findall(r"the hook stopped (\w+)", text)
|
||||
results = [json.loads(m) for m in re.findall(r"^(\{\"observed_instances_before\".*\})$", text, re.M)]
|
||||
if results:
|
||||
lines.append("Публичный тест отказа (`make test-failover`, 15 с записи во время остановки реплики):")
|
||||
lines.append("")
|
||||
lines.append("| Прогон | Остановлена реплика | Реплик до отказа | Успешных записей | Неудачных попыток "
|
||||
"(повторены с тем же ключом) | Первая запись после hook, с |")
|
||||
lines.append("| --- | --- | --- | --- | --- | --- |")
|
||||
for number, (result, container) in enumerate(zip(results, stopped), start=1):
|
||||
lines.append(f"| {number} | {container} | {result['observed_instances_before']} | "
|
||||
f"{result['successful_writes']} | {result['failed_attempts']} | "
|
||||
f"{result['first_recovery_seconds']} |")
|
||||
lines.append("")
|
||||
|
||||
memory = load_json("upload-memory.json")
|
||||
if memory:
|
||||
lines.append(f"Одновременные загрузки (`student-tests/upload_memory.py`, перед каждым сценарием реплики "
|
||||
f"перезапускаются, лимит api {memory['api_limit_mib']} MiB / {memory['api_limit_cpus']:g} CPU). "
|
||||
f"Пик RSS — VmHWM процесса API; cgroup — память контейнера, включая page cache временных файлов:")
|
||||
lines.append("")
|
||||
lines.append("| Сценарий | Одновременно | Объём, MiB | Время, с (p50 / max) | Реплика: загрузок | RSS до, MiB | "
|
||||
"Пик RSS, MiB | Рост, MiB | Пик cgroup, MiB |")
|
||||
lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- |")
|
||||
for run in memory["runs"]:
|
||||
for n, r in enumerate(run["replicas"]):
|
||||
head = (f"| {run['scenario']} | {run['concurrency']} | {run['total_mib']} | "
|
||||
f"{run['latency_s']['p50']} / {run['latency_s']['max']} |") if n == 0 else "| | | | |"
|
||||
cgroup = r["cgroup_peak_mib"] or r["cgroup_peak_sampled_mib"] or "-"
|
||||
lines.append(f"{head} {r['replica']}: {r['uploads_served']} | {r['rss_before_mib']} | "
|
||||
f"{r['rss_peak_mib']} | {r['rss_growth_mib']} | {cgroup} |")
|
||||
naive = memory["single_file_extra_rss_mib"]
|
||||
lines.append("")
|
||||
lines.append(f"Один PNG 8000x5000 RGB внутри контейнера api, дополнительный пик RSS: наивно (тело целиком в "
|
||||
f"памяти + полное декодирование Pillow) {naive['naive']} MiB, потоковая проверка "
|
||||
f"{naive['streaming']} MiB. 10 таких наивных загрузок одновременно не поместились бы в "
|
||||
f"{memory['api_limit_mib']} MiB.")
|
||||
lines.append("")
|
||||
|
||||
metrics = load_json("failover-metrics.json")
|
||||
if metrics:
|
||||
lines.append("Остановка каждой реплики под нагрузкой (`student-tests/failover_metrics.py`: 4 потока записи "
|
||||
"без пауз + 1 поток чтения, timeout клиента 2 с, 3 с до и 10 с после отказа):")
|
||||
lines.append("")
|
||||
lines.append("| Реплика | Как остановлена | Команда, с | HAProxy вывел из балансировки через, с | Ошибок "
|
||||
"(коды) | Ошибки прекратились через, с | Записей/с до | Записей/с после | p95 после, мс | "
|
||||
"Вернулась в балансировку после docker start, с |")
|
||||
lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |")
|
||||
for r in metrics["runs"]:
|
||||
how = "docker stop (SIGTERM)" if r["mode"] == "stop" else "docker kill (SIGKILL)"
|
||||
codes = ", ".join(f"{k}: {v}" for k, v in r["error_codes"].items()) or "-"
|
||||
lines.append(f"| {r['replica']} | {how} | {r['command_seconds']} | {r['lb_excluded_after_seconds']} | "
|
||||
f"{r['errors']} ({codes}) | {r['errors_stopped_after_seconds']} | {r['before']['write_rps']} | "
|
||||
f"{r['after']['write_rps']} | {r['after']['write_p95_ms']} | {r['rejoin_seconds']} |")
|
||||
lines.append("")
|
||||
lines.append("Во всех прогонах: потерянных подтверждённых сообщений 0, дублей 0, остановленная реплика "
|
||||
"после остановки не ответила ни разу.")
|
||||
lines.append("")
|
||||
|
||||
rolling = load_json("rolling-update.json")
|
||||
if rolling:
|
||||
during = rolling["during"]
|
||||
codes = ", ".join(f"{k}: {v}" for k, v in during["error_codes"].items()) or "-"
|
||||
lines.append(f"Rolling update (`student-tests/rolling_update.py`): версия {rolling['from_version']} -> "
|
||||
f"{rolling['to_version']}, {rolling['replicas']} реплики заменены по одной за "
|
||||
f"{rolling['update_seconds']} с под той же нагрузкой. Записей/с до: {rolling['before']['write_rps']}, "
|
||||
f"во время замены: {during['write_rps']}; ошибок: {during['errors']} ({codes}); "
|
||||
f"p95 {during['write_p95_ms']} мс, максимум {during['write_max_ms']} мс; подтверждено "
|
||||
f"{rolling['integrity']['confirmed_writes']} сообщений, потерь и дублей нет.")
|
||||
lines.append("")
|
||||
|
||||
load = load_json("load.json")
|
||||
if load:
|
||||
latency = load["successful_latency_ms"]
|
||||
lines.append(f"Публичный генератор нагрузки (`tests/load.py`, closed loop, concurrency {load['concurrency']}, "
|
||||
f"{load['requested_duration_seconds']:.0f} с, 2 реплики): {load['successful_rps']} успешных "
|
||||
f"POST/с, ошибок {load['failed_requests']} (доля {load['error_ratio']}), задержка успешных "
|
||||
f"p50 {latency['p50']} мс, p95 {latency['p95']} мс, p99 {latency['p99']} мс.")
|
||||
lines.append("")
|
||||
|
||||
persistence = EVIDENCE / "persistence.txt"
|
||||
restart_seconds = None
|
||||
if persistence.exists():
|
||||
found = re.search(r"took ([\d.]+) s", persistence.read_text(encoding="utf-8"))
|
||||
restart_seconds = found.group(1) if found else None
|
||||
|
||||
impacts = []
|
||||
if metrics:
|
||||
for mode, what, expected in (
|
||||
("stop", "`docker stop` реплики (SIGTERM) под нагрузкой",
|
||||
"ошибок нет: реплика сначала уходит из балансировки (readiness 503), потом закрывает приём"),
|
||||
("kill", "`docker kill` реплики (SIGKILL, авария) под нагрузкой",
|
||||
"единицы 502 на запросы, начатые на убитой реплике; клиент повторяет их с тем же ключом")):
|
||||
runs = [r for r in metrics["runs"] if r["mode"] == mode]
|
||||
if runs:
|
||||
impacts.append(
|
||||
f"| {what} | {expected} | ошибок: {', '.join(str(r['errors']) for r in runs)} (по репликам); "
|
||||
f"HAProxy вывел реплику через {', '.join(str(r['lb_excluded_after_seconds']) for r in runs)} с | "
|
||||
f"ошибки прекратились через {max(r['errors_stopped_after_seconds'] for r in runs)} с; "
|
||||
f"потерь 0, дублей 0; реплика вернулась через "
|
||||
f"{max(r['rejoin_seconds'] for r in runs)} с после `docker start` |")
|
||||
if failover.exists() and results:
|
||||
impacts.append(
|
||||
f"| публичный `make test-failover` для каждой реплики | запись продолжается не позже 10 с, "
|
||||
f"подтверждённые сообщения на месте, дублей нет | PASS {len(results)} раз(а), неудачных попыток: "
|
||||
f"{', '.join(str(r['failed_attempts']) for r in results)} | первая запись после hook через "
|
||||
f"{', '.join(str(r['first_recovery_seconds']) for r in results)} с (hook ждёт остановки ~4 с); потерь нет |")
|
||||
if rolling:
|
||||
impacts.append(
|
||||
f"| rolling update под нагрузкой | ошибок нет, реплик всё время не меньше {rolling['replicas']} | "
|
||||
f"ошибок: {rolling['during']['errors']}, замена заняла {rolling['update_seconds']} с | потерь 0, дублей 0 |")
|
||||
if restart_seconds:
|
||||
impacts.append(
|
||||
f"| перезапуск всего стенда (`restart` hook: postgres, redis, s3, api, janitor, lb) | данные, файл и "
|
||||
f"прежний токен живы | "
|
||||
f"PASS, те же контейнеры с новым временем старта | {restart_seconds} с до готовности; потерь нет |")
|
||||
consistency = EVIDENCE / "consistency.txt"
|
||||
if consistency.exists():
|
||||
text = consistency.read_text(encoding="utf-8")
|
||||
timings = re.findall(r"upload -> 503 unavailable in (\d+) ms", text)
|
||||
if len(timings) >= 2:
|
||||
impacts.append(f"| `docker compose stop s3` (SeaweedFS остановлен) | загрузка и скачивание -> 503, метаданные, "
|
||||
f"сообщения и /health/ready работают | upload 503 за {timings[0]} мс, download 503, остальное 200/201 | "
|
||||
f"после start файлы на месте; uploading-строку убрал janitor; потерь нет |")
|
||||
impacts.append(f"| `docker compose pause s3` (SeaweedFS завис) | то же, но через таймауты S3-клиента | upload 503 за "
|
||||
f"{timings[1]} мс (2 попытки x 5 с + откат 2 с) | после unpause файлы на месте; потерь нет |")
|
||||
if "PASS: S3 written but DB not committed" in text:
|
||||
impacts.append("| падение между PUT в S3 и COMMIT в БД (код API в контейнере, finish_upload падает) | "
|
||||
"вложение не видно, janitor не трогает его до конца grace period, потом удаляет объект и строку | "
|
||||
"GET/прикрепление -> 404; janitor: свежая строка сохранена, dry-run только отчёт, затем удалено | "
|
||||
"мусора не осталось; повторный проход ничего не делает |")
|
||||
if "PASS: an interrupted upload leaves no row" in text:
|
||||
impacts.append("| обрыв загрузки клиентом (9 МБ заявлено, отправлено 0,2 и 3 МБ) | ничего не сохраняется | "
|
||||
"строк и объектов не прибавилось, временных файлов 0 | мгновенно |")
|
||||
impacts += lab5_impacts()
|
||||
if impacts:
|
||||
lines.append("| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |")
|
||||
lines.append("| --- | --- | --- | --- |")
|
||||
lines.extend(impacts)
|
||||
lines.append("")
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
def lab5_line(name, pattern):
|
||||
"""Строка вывода test_jobs.py из evidence/<name>.txt, содержащая pattern (или None)."""
|
||||
path = EVIDENCE / f"{name}.txt"
|
||||
if not path.exists():
|
||||
return None
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
if pattern in line and not line.startswith(("#", "---")):
|
||||
return line.strip()
|
||||
return None
|
||||
|
||||
|
||||
def lab5_impacts():
|
||||
"""Строки таблицы отказов lab5: наблюдение — дословно строка вывода теста (числа из прогона)."""
|
||||
rows = [
|
||||
("jobs-recovery", "worker started", "worker остановлен, upload, рестарт rabbitmq и api с volumes, start worker",
|
||||
"202 queued, сообщение с вложением 201, content 409; после рестартов job в очереди; тот же job_id -> ready",
|
||||
"потерь нет; staging удалён после COMMIT"),
|
||||
("jobs-recovery", "rabbitmq started", "rabbitmq остановлен во время upload",
|
||||
"202 и /health/ready 200 без брокера; строка outbox ждёт; после start публикуется", "потерь нет"),
|
||||
("jobs-outbox", "killed between COMMIT and publish", "crash dispatcher между COMMIT задания и publish",
|
||||
"строка outbox не отмечена -> публикуется после рестарта процесса", "без ручного действия"),
|
||||
("jobs-outbox", "after publisher confirm", "crash dispatcher после confirm, до отметки outbox",
|
||||
"дубль сообщения, worker распознаёт по состоянию job", "один набор вариантов"),
|
||||
("jobs-crash", "killed after S3 PUT", "crash worker после PUT в S3, до COMMIT и ack",
|
||||
"повтор после истечения аренды перезаписывает те же ключи", "один набор, 4 объекта"),
|
||||
("jobs-crash", "after COMMIT, before ack", "crash worker после COMMIT, до ack",
|
||||
"redelivery ready-задачи -> no-op ack", "очередь пуста, дублей нет"),
|
||||
("jobs-crash", "frozen attempt", "worker завис (не продлевает аренду)",
|
||||
"dispatcher возвращает job, другой поток завершает; поздний результат отклонён fencing", "ready не откатан"),
|
||||
("jobs-limits", "imaging hang", "зависание обработки изображения",
|
||||
"процесс убит по JOB_TIMEOUT_SECONDS, временная ошибка, аренда продлевалась", "повтор -> ready"),
|
||||
("jobs-limits", "memory bomb", "нехватка памяти в процессе обработки (RLIMIT_AS)",
|
||||
"failed/resource_limit, worker жив", "постоянная ошибка, без повторов"),
|
||||
("jobs-retry", "storage_unavailable ->", "2 временные ошибки S3", "backoff с jitter, затем ready", "-"),
|
||||
("jobs-retry", "retry_exhausted (public", "5 временных ошибок подряд",
|
||||
"failed/retry_exhausted, реестр failed, content 409", "replay оператора"),
|
||||
("jobs-retry", "ops replay", "replay failed и повторный replay ready", "тот же job_id -> ready; повтор отклонён",
|
||||
"дубля нет"),
|
||||
("jobs-retry", "-> reject -> DLQ", "невалидное сообщение и неизвестный job_id", "reject -> DLQ, dlq-replay не исполняет",
|
||||
"сообщения сохранены"),
|
||||
("jobs-concurrency", "peak processing", "8 заданий в очереди, старт worker",
|
||||
"WORKER_CONCURRENCY=2, prefetch 1", "-"),
|
||||
]
|
||||
out = []
|
||||
for name, pattern, what, expected, recovery in rows:
|
||||
line = lab5_line(name, pattern)
|
||||
if line:
|
||||
out.append(f"| {what} | {expected} | {line.replace('|', '/')} | {recovery} |")
|
||||
return out
|
||||
|
||||
|
||||
def update_report(block):
|
||||
report = ROOT / "REPORT.md"
|
||||
text = report.read_text(encoding="utf-8")
|
||||
begin, end = "<!-- measurements:begin -->", "<!-- measurements:end -->"
|
||||
if begin not in text or end not in text:
|
||||
print("REPORT.md has no measurement markers, only evidence/summary.md was written")
|
||||
return
|
||||
head, rest = text.split(begin, 1)
|
||||
_, tail = rest.split(end, 1)
|
||||
report.write_text(f"{head}{begin}\n{block}\n{end}{tail}", encoding="utf-8")
|
||||
print("REPORT.md: measurement tables updated")
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
names = [name for name, _, _ in STEPS]
|
||||
if args[:1] == ["--from"]:
|
||||
if len(args) < 2 or args[1] not in names:
|
||||
raise SystemExit("usage: --from <step>; steps: " + ", ".join(names))
|
||||
selected = names[names.index(args[1]):]
|
||||
else:
|
||||
unknown = [a for a in args if a not in names]
|
||||
if unknown:
|
||||
raise SystemExit(f"unknown steps {unknown}; steps: " + ", ".join(names))
|
||||
selected = args or names
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
results = []
|
||||
for name, description, command in STEPS:
|
||||
if name not in selected:
|
||||
continue
|
||||
ok, seconds = run_step(name, description, command)
|
||||
results.append((name, description, ok, seconds))
|
||||
if not ok:
|
||||
print(f"\nSTOP: step '{name}' failed, see evidence/{name}.txt.")
|
||||
print(f"After fixing: python student-tests/collect_evidence.py --from {name}")
|
||||
break
|
||||
block = measurements()
|
||||
summary = ["# Сводка проверок", "", "| Шаг | Что проверяет | Результат | Время, с | Файл |",
|
||||
"| --- | --- | --- | --- | --- |"]
|
||||
summary += [f"| {n} | {d} | {'PASS' if ok else 'FAIL'} | {s:.0f} | evidence/{n}.txt |" for n, d, ok, s in results]
|
||||
(EVIDENCE / "summary.md").write_text("\n".join(summary) + "\n\n# Замеры\n\n" + block + "\n", encoding="utf-8")
|
||||
print("evidence/summary.md written")
|
||||
passed = all(ok for _, _, ok, _ in results)
|
||||
if passed:
|
||||
update_report(block) # таблицы строятся из всех файлов evidence/, в том числе от прошлых запусков
|
||||
raise SystemExit(0 if passed else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,347 @@
|
||||
|
||||
import base64
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
LB_STATS_URL = os.environ.get("LB_STATS_URL", "http://127.0.0.1:8404/stats;csv")
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, status, headers, data):
|
||||
self.status = status
|
||||
self.headers = {name.lower(): value for name, value in headers.items()}
|
||||
self.data = data
|
||||
try:
|
||||
self.json = json.loads(data.decode("utf-8")) if data else None
|
||||
except ValueError:
|
||||
self.json = None
|
||||
|
||||
@property
|
||||
def instance(self):
|
||||
"""X-Instance-Id: какая реплика API ответила (ID её контейнера)."""
|
||||
return self.headers.get("x-instance-id")
|
||||
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
def call(method, path, expected=200, *, body=None, raw=None, token=None, headers=None, timeout=30):
|
||||
"""HTTP-запрос к API. expected — код или кортеж кодов, иначе AssertionError.
|
||||
|
||||
Заодно проверяет то, что контракт требует от любого ответа:
|
||||
X-Request-Id, X-Instance-Id (с lab3), единый формат ошибки, WWW-Authenticate у 401.
|
||||
"""
|
||||
all_headers = dict(headers or {})
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
if data is not None:
|
||||
all_headers.setdefault("Content-Type", "application/json")
|
||||
if token is not None:
|
||||
all_headers["Authorization"] = "Bearer " + token
|
||||
|
||||
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as reply:
|
||||
response = Response(reply.status, reply.headers, reply.read())
|
||||
except urllib.error.HTTPError as error:
|
||||
response = Response(error.code, error.headers, error.read())
|
||||
|
||||
expected = expected if isinstance(expected, tuple) else (expected,)
|
||||
check(response.status in expected,
|
||||
f"{method} {path}: expected {expected}, got {response.status} {response.data[:200]!r}")
|
||||
request_id = response.headers.get("x-request-id")
|
||||
check(request_id, f"{method} {path}: no X-Request-Id header")
|
||||
check(response.instance, f"{method} {path}: no X-Instance-Id header")
|
||||
if response.status >= 400:
|
||||
error = (response.json or {}).get("error") or {}
|
||||
check(error.get("code") and error.get("message"), f"{method} {path}: wrong error format")
|
||||
check(error.get("request_id") == request_id, f"{method} {path}: request_id differs from header")
|
||||
if response.status == 401:
|
||||
check(response.headers.get("www-authenticate"), f"{method} {path}: 401 without WWW-Authenticate")
|
||||
return response
|
||||
|
||||
|
||||
def try_call(method, path, *, body=None, token=None, headers=None, timeout=2):
|
||||
"""Запрос без проверок и без исключений — для нагрузки во время отказа.
|
||||
|
||||
Возвращает Response или None, если соединение оборвалось / вышел timeout.
|
||||
"""
|
||||
all_headers = dict(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
all_headers["Content-Type"] = "application/json"
|
||||
if token is not None:
|
||||
all_headers["Authorization"] = "Bearer " + token
|
||||
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as reply:
|
||||
return Response(reply.status, reply.headers, reply.read())
|
||||
except urllib.error.HTTPError as error:
|
||||
try:
|
||||
return Response(error.code, error.headers, error.read())
|
||||
except OSError:
|
||||
return None
|
||||
except (urllib.error.URLError, OSError):
|
||||
return None
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
"""Значение заголовка Authorization: Basic base64(username:password), пароль в UTF-8."""
|
||||
return "Basic " + base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def login(username, password, expected=201):
|
||||
return call("POST", "/api/v1/auth/sessions", expected, headers={"Authorization": basic(username, password)})
|
||||
|
||||
|
||||
def new_user(prefix="user", password=PASSWORD):
|
||||
"""Регистрирует пользователя и входит. Возвращает dict: id, username, password, token."""
|
||||
username = f"{prefix}_{uuid.uuid4().hex[:10]}"
|
||||
user = call("POST", "/api/v1/users", 201,
|
||||
body={"username": username, "display_name": prefix.title(), "password": password}).json
|
||||
session = login(username, password).json
|
||||
return {**user, "password": password, "token": session["token"]}
|
||||
|
||||
|
||||
def new_chat(owner, *others, title="Test chat"):
|
||||
member_ids = [owner["id"]] + [user["id"] for user in others]
|
||||
return call("POST", "/api/v1/chats", 201, token=owner["token"],
|
||||
body={"title": title, "member_ids": member_ids}).json
|
||||
|
||||
|
||||
def new_key():
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def send(user, chat_id, text, expected=201, key=None):
|
||||
"""POST сообщения. С lab3 Idempotency-Key обязателен: если не задан, берём новый случайный."""
|
||||
return call("POST", f"/api/v1/chats/{chat_id}/messages", expected, token=user["token"],
|
||||
body={"text": text}, headers={"Idempotency-Key": key or new_key()})
|
||||
|
||||
|
||||
def post_message(user, chat_id, text="", attachment_ids=None, expected=201, key=None):
|
||||
"""POST сообщения с вложениями (lab4). attachment_ids=None — поле не передаётся."""
|
||||
body = {"text": text}
|
||||
if attachment_ids is not None:
|
||||
body["attachment_ids"] = attachment_ids
|
||||
return call("POST", f"/api/v1/chats/{chat_id}/messages", expected, token=user["token"],
|
||||
body=body, headers={"Idempotency-Key": key or new_key()})
|
||||
|
||||
|
||||
def upload(user, chat_id, data, content_type="image/png", filename="photo.png", expected=202, timeout=60,
|
||||
wait=True):
|
||||
"""POST /chats/{id}/attachments сырыми байтами. filename=None — без параметра.
|
||||
|
||||
Lab5: успешный приём — 202 со снимком queued (переход 201 -> 202 из COURSE.md). При wait=True
|
||||
ответ дополняется ожиданием готовности: .json — метаданные после GET в состоянии ready/failed,
|
||||
.accepted — исходный снимок 202. Так проверки lab4 («файл скачивается побайтно») сохраняются.
|
||||
"""
|
||||
query = "" if filename is None else "?filename=" + urllib.parse.quote(filename, safe="")
|
||||
headers = {"Content-Type": content_type} if content_type is not None else {}
|
||||
reply = call("POST", f"/api/v1/chats/{chat_id}/attachments{query}", expected, raw=data,
|
||||
token=user["token"] if user else None, headers=headers, timeout=timeout)
|
||||
if reply.status == 202:
|
||||
check(reply.json["status"] == "queued" and reply.json["variants"] == [], "202 must be a queued snapshot")
|
||||
reply.accepted = reply.json
|
||||
if wait:
|
||||
reply.json = wait_attachment(user, reply.json["id"])
|
||||
return reply
|
||||
|
||||
|
||||
def wait_attachment(user, attachment_id, statuses=("ready", "failed"), seconds=60):
|
||||
"""GET метаданных, пока вложение не перейдёт в одно из statuses (smoke ждёт ready до 60 с)."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
att = call("GET", f"/api/v1/attachments/{attachment_id}", 200, token=user["token"]).json
|
||||
if att["status"] in statuses:
|
||||
return att
|
||||
check(time.monotonic() < deadline, f"attachment {attachment_id} is {att['status']} after {seconds} s")
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def read_history(user, chat_id, limit=100):
|
||||
"""Вся история чата по страницам. Возвращает (сообщения, число_страниц)."""
|
||||
items, pages, cursor = [], 0, None
|
||||
while True:
|
||||
query = f"?limit={limit}" + (f"&cursor={urllib.parse.quote(cursor, safe='')}" if cursor else "")
|
||||
page = call("GET", f"/api/v1/chats/{chat_id}/messages{query}", 200, token=user["token"]).json
|
||||
items += page["items"]
|
||||
pages += 1
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items, pages
|
||||
|
||||
|
||||
def wait_ready(seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
with urllib.request.urlopen(BASE_URL + "/health/ready", timeout=3) as reply:
|
||||
if reply.status == 200:
|
||||
return
|
||||
except (urllib.error.URLError, OSError):
|
||||
pass
|
||||
check(time.monotonic() < deadline, f"API is not ready after {seconds} s")
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def compose(*args, env=None):
|
||||
"""docker compose <args> в корне репозитория. Вывод скрыт: в нём могут быть пути к секретам."""
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def compose_output(*args, env=None):
|
||||
"""docker compose <args> и его вывод (для logs, ps)."""
|
||||
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, check=True, env=env)
|
||||
return result.stdout.decode("utf-8", "replace") + result.stderr.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def docker(*args, check_exit=True):
|
||||
"""docker <args>, возвращает stdout."""
|
||||
result = subprocess.run(["docker", *args], cwd=ROOT, capture_output=True, check=check_exit)
|
||||
return result.stdout.decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def api_containers(include_stopped=False):
|
||||
"""Полные ID контейнеров сервиса api (по умолчанию только запущенные)."""
|
||||
args = ["ps", "-q", "-a", "api"] if include_stopped else ["ps", "-q", "api"]
|
||||
return sorted(compose_output(*args).split())
|
||||
|
||||
|
||||
def health(container):
|
||||
"""Статус Docker healthcheck контейнера: starting / healthy / unhealthy / ''."""
|
||||
return docker("inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{end}}", container,
|
||||
check_exit=False)
|
||||
|
||||
|
||||
def lb_servers():
|
||||
"""Состояние слотов backend api в HAProxy (страница статистики, CSV): {имя: статус}."""
|
||||
with urllib.request.urlopen(LB_STATS_URL, timeout=2) as reply:
|
||||
rows = list(csv.reader(io.StringIO(reply.read().decode("utf-8", "replace"))))
|
||||
header = [name.lstrip("# ") for name in rows[0]]
|
||||
servers = {}
|
||||
for row in rows[1:]:
|
||||
item = dict(zip(header, row))
|
||||
if item.get("pxname") == "api" and item.get("svname") not in ("FRONTEND", "BACKEND"):
|
||||
servers[item["svname"]] = item.get("status", "")
|
||||
return servers
|
||||
|
||||
|
||||
def lb_up_count():
|
||||
"""Сколько основных слотов (api1..api6, не аварийных) HAProxy считает готовыми (UP)."""
|
||||
return sum(1 for name, status in lb_servers().items() if name.startswith("api") and status.startswith("UP"))
|
||||
|
||||
|
||||
def seen_instances(token, requests=20):
|
||||
"""Какие реплики отвечают через балансировщик: X-Instance-Id у серии GET /users/me."""
|
||||
return {call("GET", "/api/v1/users/me", 200, token=token).instance for _ in range(requests)}
|
||||
|
||||
|
||||
def wait_balanced(replicas, seconds=60):
|
||||
"""Ждёт, пока все replicas контейнеров api healthy и HAProxy держит их в балансировке."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
running = api_containers()
|
||||
healthy = [container for container in running if health(container) == "healthy"]
|
||||
try:
|
||||
up = lb_up_count()
|
||||
except OSError:
|
||||
up = 0
|
||||
if len(healthy) >= replicas and up >= replicas:
|
||||
return running
|
||||
check(time.monotonic() < deadline,
|
||||
f"after {seconds} s: {len(healthy)} healthy api containers, {up} UP in HAProxy, need {replicas}")
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def redis_cli(*args):
|
||||
"""redis-cli внутри контейнера redis. Пароль читается там же из секрета и не попадает в вывод."""
|
||||
command = "REDISCLI_AUTH=\"$(sed -n 's/^requirepass //p' /run/secrets/redis_auth)\" redis-cli " + " ".join(args)
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "sh", "-c", command],
|
||||
cwd=ROOT, capture_output=True, check=True)
|
||||
return result.stdout.decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def session_key(token):
|
||||
"""Ключ сессии в Redis, как его считает auth.py: session:<SHA-256 токена>."""
|
||||
return "session:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Выполняет SQL в контейнере postgres. Возвращает (код выхода, вывод, текст ошибки).
|
||||
|
||||
Значения в SQL тестов — только сгенерированные самим тестом (uuid), не ввод пользователя.
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "postgres",
|
||||
"psql", "-U", "messenger", "-d", "messenger", "-X", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-c", sql],
|
||||
cwd=ROOT, capture_output=True, check=False,
|
||||
)
|
||||
output = result.stdout.decode("utf-8", "replace").strip()
|
||||
error = result.stderr.decode("utf-8", "replace").strip()
|
||||
return result.returncode, output, error
|
||||
|
||||
|
||||
def app_python(code, *args, service="api", env=None):
|
||||
"""Выполнить Python-скрипт внутри контейнера приложения (там есть модули API и S3-ключи API).
|
||||
|
||||
Скрипт передаётся через stdin, секреты остаются в контейнере. Возвращает stdout (последняя строка — JSON).
|
||||
"""
|
||||
command = ["docker", "compose", "exec", "-T"]
|
||||
for name, value in (env or {}).items():
|
||||
command += ["-e", f"{name}={value}"]
|
||||
command += [service, "python", "-", *map(str, args)]
|
||||
result = subprocess.run(command, cwd=ROOT, input=code.encode("utf-8"), capture_output=True, check=False)
|
||||
output = result.stdout.decode("utf-8", "replace").strip()
|
||||
check(result.returncode == 0, f"script in {service} failed: {result.stderr.decode('utf-8', 'replace')[-600:]}")
|
||||
return output
|
||||
|
||||
|
||||
def janitor(*args, env=None):
|
||||
"""Один проход janitor.py в контейнере janitor. Возвращает его JSON-отчёт."""
|
||||
command = ["docker", "compose", "exec", "-T"]
|
||||
for name, value in (env or {}).items():
|
||||
command += ["-e", f"{name}={value}"]
|
||||
command += ["janitor", "python", "janitor.py", "--once", *map(str, args)]
|
||||
result = subprocess.run(command, cwd=ROOT, capture_output=True, check=False)
|
||||
output = result.stdout.decode("utf-8", "replace").strip()
|
||||
check(result.returncode == 0, f"janitor failed: {result.stderr.decode('utf-8', 'replace')[-600:]}")
|
||||
return json.loads(output.splitlines()[-1])
|
||||
|
||||
|
||||
def sql_value(query):
|
||||
"""Одно значение из PostgreSQL (psql -A -t)."""
|
||||
code, output, error = psql(query)
|
||||
check(code == 0, f"psql failed: {error[-300:]}")
|
||||
return output
|
||||
|
||||
|
||||
def run_tests(tests):
|
||||
"""Запускает функции-тесты по очереди. Код выхода 1, если хоть один упал."""
|
||||
failed = 0
|
||||
for test in tests:
|
||||
try:
|
||||
test()
|
||||
except Exception as exc: # noqa: BLE001 — нужно напечатать любую ошибку теста
|
||||
failed += 1
|
||||
print(f"FAIL: {test.__name__}: {exc}")
|
||||
print(f"{len(tests) - failed} passed, {failed} failed")
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
from common import call, compose_output, new_user
|
||||
|
||||
|
||||
def main():
|
||||
user = new_user("demo")
|
||||
print(f"logged in once as {user['username']}; 8 requests with the same Bearer token:")
|
||||
for number in range(1, 9):
|
||||
reply = call("GET", "/api/v1/users/me", 200, token=user["token"])
|
||||
print(f" {number}. GET /api/v1/users/me -> {reply.status}, X-Instance-Id: {reply.instance}")
|
||||
print()
|
||||
print(compose_output("ps", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}", "api").strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,28 @@
|
||||
|
||||
import subprocess
|
||||
|
||||
from common import ROOT
|
||||
|
||||
OUTPUT = ROOT / "evidence" / "explain-history.txt"
|
||||
|
||||
|
||||
def main():
|
||||
sql = (ROOT / "student-tests" / "explain.sql").read_bytes()
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "postgres",
|
||||
"psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-v", "ON_ERROR_STOP=1"],
|
||||
cwd=ROOT, input=sql, capture_output=True, check=False,
|
||||
)
|
||||
OUTPUT.parent.mkdir(exist_ok=True)
|
||||
OUTPUT.write_bytes(result.stdout + result.stderr)
|
||||
if result.returncode != 0:
|
||||
print(result.stderr.decode("utf-8", "replace"))
|
||||
raise SystemExit("FAIL: psql returned an error, see output above")
|
||||
for line in result.stdout.decode("utf-8", "replace").splitlines():
|
||||
if line.startswith("===") or "Buffers" in line or "Execution Time" in line or " Scan " in line:
|
||||
print(line)
|
||||
print(f"PASS: full plans saved to {OUTPUT.relative_to(ROOT)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,76 @@
|
||||
|
||||
\pset footer off
|
||||
BEGIN;
|
||||
|
||||
CREATE TEMP TABLE seed_chats AS
|
||||
SELECT gen_random_uuid() AS id, n, CASE WHEN n = 0 THEN 15000 ELSE 100 END AS size
|
||||
FROM generate_series(0, 50) AS n;
|
||||
CREATE TEMP TABLE seed_user AS SELECT gen_random_uuid() AS id;
|
||||
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
SELECT id, 'explain_' || substr(md5(random()::text), 1, 10), convert_to('Explain', 'UTF8'), 'not-a-real-hash'
|
||||
FROM seed_user;
|
||||
INSERT INTO chats (id, title) SELECT id, convert_to('explain ' || n, 'UTF8') FROM seed_chats;
|
||||
INSERT INTO chat_members (chat_id, user_id) SELECT c.id, u.id FROM seed_chats c, seed_user u;
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), c.id, u.id, convert_to('message ' || g, 'UTF8'),
|
||||
timestamptz '2026-09-01 00:00:00+00' + g * interval '1 second'
|
||||
FROM seed_chats c, seed_user u, generate_series(1, c.size) AS g;
|
||||
ANALYZE messages;
|
||||
|
||||
SELECT id AS big_chat FROM seed_chats WHERE n = 0 \gset
|
||||
SELECT created_at AS cursor_time, id AS cursor_id FROM messages
|
||||
WHERE chat_id = :'big_chat' ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset
|
||||
|
||||
\echo '=== Data volume'
|
||||
SELECT count(*) AS messages_total,
|
||||
count(*) FILTER (WHERE chat_id = :'big_chat') AS messages_in_big_chat
|
||||
FROM messages;
|
||||
|
||||
\echo ''
|
||||
\echo '=== History index'
|
||||
SELECT indexdef FROM pg_indexes WHERE indexname = 'messages_history';
|
||||
|
||||
\echo ''
|
||||
\echo '=== 1. First page: limit=50, the app asks for 51 rows to know if there is a next page'
|
||||
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = :'big_chat'
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
\echo ''
|
||||
\echo '=== 2. Page after the 10000th message by keyset cursor (this is what the app does)'
|
||||
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
\echo ''
|
||||
\echo '=== 2b. The same page exactly as the app sends it since lab4: with attachment_ids of every message'
|
||||
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = :'big_chat' AND (m.created_at, m.id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
|
||||
ORDER BY m.created_at, m.id LIMIT 51;
|
||||
|
||||
\echo ''
|
||||
\echo '=== 3. The same page with OFFSET 10000 (the app does NOT do this)'
|
||||
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = :'big_chat'
|
||||
ORDER BY created_at, id OFFSET 10000 LIMIT 51;
|
||||
|
||||
\echo ''
|
||||
\echo '=== 4. Query 2 without the index (index is dropped only inside this transaction)'
|
||||
DROP INDEX messages_history;
|
||||
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
ROLLBACK;
|
||||
\echo ''
|
||||
\echo '=== ROLLBACK: test data removed, index is back'
|
||||
SELECT count(*) AS explain_users_left FROM users WHERE username LIKE 'explain\_%';
|
||||
@@ -0,0 +1,129 @@
|
||||
import json
|
||||
import platform
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from common import ROOT, api_containers, check, docker, lb_up_count, wait_balanced
|
||||
from loadgen import Load, summary
|
||||
|
||||
WARMUP_SECONDS = 3
|
||||
AFTER_SECONDS = 10
|
||||
OUTPUT = ROOT / "evidence" / "failover-metrics.json"
|
||||
|
||||
|
||||
class LbWatch:
|
||||
"""Раз в 0,1 с спрашивает у HAProxy, сколько реплик в балансировке (UP)."""
|
||||
|
||||
def __init__(self):
|
||||
self.points, self.stopping = [], threading.Event()
|
||||
self.thread = threading.Thread(target=self._run, daemon=True)
|
||||
|
||||
def _run(self):
|
||||
while not self.stopping.is_set():
|
||||
try:
|
||||
self.points.append((time.monotonic(), lb_up_count()))
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.stopping.set()
|
||||
self.thread.join(timeout=3)
|
||||
|
||||
def first_drop(self, after, replicas):
|
||||
return next((t for t, up in self.points if t >= after and up < replicas), None)
|
||||
|
||||
|
||||
def measure(container, mode, replicas):
|
||||
wait_balanced(replicas)
|
||||
load, watch = Load(), LbWatch()
|
||||
watch.start()
|
||||
load.start()
|
||||
time.sleep(WARMUP_SECONDS)
|
||||
t0 = time.monotonic()
|
||||
if mode == "stop":
|
||||
docker("stop", "--time", "8", container)
|
||||
else:
|
||||
docker("kill", container)
|
||||
command_seconds = time.monotonic() - t0
|
||||
time.sleep(max(0.0, AFTER_SECONDS - command_seconds))
|
||||
end = t0 + AFTER_SECONDS
|
||||
load.stop()
|
||||
watch.stop()
|
||||
|
||||
errors = [e for e in load.window(t0 - WARMUP_SECONDS, end) if not e[2]]
|
||||
errors_end = max((e[0] + e[5] for e in errors), default=None)
|
||||
drop = watch.first_drop(t0, replicas)
|
||||
served_after = [e[4] for e in load.window(t0 + command_seconds, end) if e[2]]
|
||||
target_hits = sum(1 for instance in served_after if instance and container.startswith(instance))
|
||||
integrity = load.verify()
|
||||
|
||||
started = time.monotonic()
|
||||
docker("start", container)
|
||||
wait_balanced(replicas)
|
||||
rejoin_seconds = time.monotonic() - started
|
||||
|
||||
return {
|
||||
"replica": container[:12],
|
||||
"mode": mode,
|
||||
"command_seconds": round(command_seconds, 2),
|
||||
"lb_excluded_after_seconds": round(drop - t0, 2) if drop else None,
|
||||
"errors": len(errors),
|
||||
"error_codes": summary(load, t0 - WARMUP_SECONDS, end)["error_codes"],
|
||||
"errors_stopped_after_seconds": round(errors_end - t0, 2) if errors_end else 0.0,
|
||||
"before": summary(load, t0 - WARMUP_SECONDS, t0),
|
||||
"after": summary(load, t0, end),
|
||||
"stopped_replica_answers_after_stop": target_hits,
|
||||
"integrity": integrity,
|
||||
"rejoin_seconds": round(rejoin_seconds, 2),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
modes = sys.argv[1:] or ["stop", "kill"]
|
||||
check(set(modes) <= {"stop", "kill"}, "usage: python student-tests/failover_metrics.py [stop] [kill]")
|
||||
containers = api_containers()
|
||||
replicas = len(containers)
|
||||
check(replicas >= 2, "need at least 2 running api replicas")
|
||||
print(f"api replicas: {[c[:12] for c in containers]}; load: 4 writers without pauses + 1 reader, "
|
||||
f"client timeout 2 s, retry with the same Idempotency-Key; {WARMUP_SECONDS} s before and "
|
||||
f"{AFTER_SECONDS} s after the failure")
|
||||
runs = []
|
||||
for container in containers:
|
||||
for mode in modes:
|
||||
print(f"--- {mode} {container[:12]} ...")
|
||||
run = measure(container, mode, replicas)
|
||||
runs.append(run)
|
||||
print(f" docker {mode}: {run['command_seconds']} s; HAProxy excluded it after "
|
||||
f"{run['lb_excluded_after_seconds']} s; errors: {run['errors']} {run['error_codes']}, "
|
||||
f"stopped after {run['errors_stopped_after_seconds']} s")
|
||||
print(f" write RPS before {run['before']['write_rps']} -> after {run['after']['write_rps']}; "
|
||||
f"p95 after {run['after']['write_p95_ms']} ms, max {run['after']['write_max_ms']} ms; "
|
||||
f"answers from the stopped replica after stop: {run['stopped_replica_answers_after_stop']}")
|
||||
print(f" confirmed {run['integrity']['confirmed_writes']}, in history "
|
||||
f"{run['integrity']['messages_in_history']}, lost 0, duplicates 0; "
|
||||
f"back in the balancer {run['rejoin_seconds']} s after docker start")
|
||||
check(run["stopped_replica_answers_after_stop"] == 0, "the stopped replica still answered")
|
||||
check(run["after"]["write_rps"] > 0, "no successful writes after the failure")
|
||||
print()
|
||||
print("replica mode cmd,s lb_out,s errors errors_end,s rps_before rps_after p95_after,ms rejoin,s")
|
||||
for r in runs:
|
||||
print(f"{r['replica']} {r['mode']:<4} {r['command_seconds']:>5} {str(r['lb_excluded_after_seconds']):>8} "
|
||||
f"{r['errors']:>6} {r['errors_stopped_after_seconds']:>12} {r['before']['write_rps']:>10} "
|
||||
f"{r['after']['write_rps']:>9} {str(r['after']['write_p95_ms']):>12} {r['rejoin_seconds']:>8}")
|
||||
OUTPUT.parent.mkdir(exist_ok=True)
|
||||
OUTPUT.write_text(json.dumps({
|
||||
"profile": {"writers": 4, "readers": 1, "client_timeout_seconds": 2, "warmup_seconds": WARMUP_SECONDS,
|
||||
"after_seconds": AFTER_SECONDS, "replicas": replicas, "client_python": platform.python_version()},
|
||||
"runs": runs,
|
||||
}, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"PASS: every replica was stopped ({', '.join(modes)}) and restored; no lost or duplicated messages; "
|
||||
f"saved {OUTPUT.relative_to(ROOT)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,93 @@
|
||||
"""Синтетические изображения для тестов вложений: только стандартная библиотека.
|
||||
|
||||
PNG собирается вручную (сигнатура, IHDR, IDAT, IEND), поэтому можно получить любой размер
|
||||
в пикселях и байтах, а также испортить конкретный байт. JPEG берётся из fixtures/.
|
||||
"""
|
||||
import os
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png(width, height, *, gray=False, noise=False, interlace=0, pad_to=None, idat=None) -> bytes:
|
||||
"""PNG width x height. noise=True — случайные пиксели (почти не сжимаются, файл большой).
|
||||
|
||||
pad_to — дополнить файл текстовым чанком tEXt после IDAT до точного размера в байтах.
|
||||
idat — готовые сжатые данные (для «бомбы»: заголовок обещает одно, данных другое).
|
||||
"""
|
||||
channels = 1 if gray else 3
|
||||
header = struct.pack(">IIBBBBB", width, height, 8, 0 if gray else 2, 0, 0, interlace)
|
||||
if idat is None:
|
||||
compressor = zlib.compressobj(6)
|
||||
parts = []
|
||||
# Adam7: 7 проходов, у каждого свои ширина и высота; без interlace — один проход.
|
||||
passes = [(width, height)] if not interlace else [
|
||||
((width - x + dx - 1) // dx, (height - y + dy - 1) // dy) for x, y, dx, dy in ADAM7]
|
||||
for pass_width, pass_height in passes:
|
||||
if pass_width <= 0 or pass_height <= 0:
|
||||
continue
|
||||
row = b"\x00" + bytes(pass_width * channels)
|
||||
for _ in range(pass_height):
|
||||
parts.append(compressor.compress(b"\x00" + os.urandom(pass_width * channels) if noise else row))
|
||||
parts.append(compressor.flush())
|
||||
idat = b"".join(parts)
|
||||
body = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", idat)
|
||||
if pad_to is not None:
|
||||
need = pad_to - len(body) - 12 - 12 - 8 # заголовок чанка-заполнителя, IEND, ключ "Comment\0"
|
||||
assert need >= 0, "image is already larger than pad_to"
|
||||
body += chunk(b"tEXt", b"Comment\x00" + b"a" * need)
|
||||
return body + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def noise_png(target_bytes: int) -> bytes:
|
||||
"""Почти несжимаемый PNG размером чуть меньше target_bytes (квадрат RGB со случайными пикселями)."""
|
||||
side = int(((target_bytes - 4096) / 3) ** 0.5)
|
||||
return png(side, side, noise=True)
|
||||
|
||||
|
||||
def sample_png() -> bytes:
|
||||
return (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def sample_jpeg() -> bytes:
|
||||
return (FIXTURES / "sample.jpg").read_bytes()
|
||||
|
||||
|
||||
def progressive_jpeg() -> bytes:
|
||||
return (FIXTURES / "progressive.jpg").read_bytes()
|
||||
|
||||
|
||||
def flip_byte(data: bytes, position: int) -> bytes:
|
||||
return data[:position] + bytes([data[position] ^ 0xFF]) + data[position + 1:]
|
||||
|
||||
|
||||
GIF = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"
|
||||
|
||||
|
||||
# --- сборка PNG из произвольных чанков (для проверок смысла чанков при верных CRC) ---
|
||||
|
||||
def ihdr(width, height, depth=8, color=2, interlace=0):
|
||||
return b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)
|
||||
|
||||
|
||||
def zero_idat(width, height, depth=8, channels=3):
|
||||
"""Сжатые пиксели: каждая строка = байт фильтра 0 + нули (индекс палитры 0 / чёрный)."""
|
||||
row_bytes = (width * depth * channels + 7) // 8
|
||||
return b"IDAT", zlib.compress((b"\x00" + bytes(row_bytes)) * height)
|
||||
|
||||
|
||||
def assemble(*chunks):
|
||||
"""PNG из чанков (kind, data) с ВЕРНЫМИ CRC; IEND добавляется, если не передан."""
|
||||
if not chunks or chunks[-1][0] != b"IEND":
|
||||
chunks = chunks + ((b"IEND", b""),)
|
||||
return b"\x89PNG\r\n\x1a\n" + b"".join(chunk(kind, data) for kind, data in chunks)
|
||||
@@ -0,0 +1,102 @@
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
|
||||
from common import check, new_chat, new_key, new_user, read_history, try_call
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, writers=4, timeout=2):
|
||||
self.alice, self.bob = new_user("load_a"), new_user("load_b")
|
||||
self.chat = new_chat(self.alice, self.bob, title="load")
|
||||
self.writers, self.timeout = writers, timeout
|
||||
self.events = [] # (время, "write"/"read", ok, код или "conn", реплика, задержка в с)
|
||||
self.confirmed = [] # сообщения, на которые пришёл 201
|
||||
self.lock = threading.Lock()
|
||||
self.stopping = threading.Event()
|
||||
self.threads = []
|
||||
|
||||
def _record(self, kind, started, reply, ok):
|
||||
code = reply.status if reply is not None else "conn"
|
||||
instance = reply.instance if reply is not None else None
|
||||
with self.lock:
|
||||
self.events.append((started, kind, ok, code, instance, time.monotonic() - started))
|
||||
|
||||
def _writer(self, number):
|
||||
path = f"/api/v1/chats/{self.chat['id']}/messages"
|
||||
sent = 0
|
||||
key, text = new_key(), f"load-{number}-{sent}"
|
||||
while not self.stopping.is_set():
|
||||
started = time.monotonic()
|
||||
reply = try_call("POST", path, body={"text": text}, token=self.alice["token"],
|
||||
headers={"Idempotency-Key": key}, timeout=self.timeout)
|
||||
ok = reply is not None and reply.status == 201
|
||||
self._record("write", started, reply, ok)
|
||||
if ok:
|
||||
with self.lock:
|
||||
self.confirmed.append(reply.json)
|
||||
sent += 1
|
||||
key, text = new_key(), f"load-{number}-{sent}"
|
||||
else:
|
||||
time.sleep(0.05) # и повторить тот же text с тем же ключом
|
||||
|
||||
def _reader(self):
|
||||
path = f"/api/v1/chats/{self.chat['id']}/messages?limit=20"
|
||||
while not self.stopping.is_set():
|
||||
started = time.monotonic()
|
||||
reply = try_call("GET", path, token=self.bob["token"], timeout=self.timeout)
|
||||
self._record("read", started, reply, reply is not None and reply.status == 200)
|
||||
time.sleep(0.05)
|
||||
|
||||
def start(self):
|
||||
self.threads = [threading.Thread(target=self._writer, args=(n,), daemon=True) for n in range(self.writers)]
|
||||
self.threads.append(threading.Thread(target=self._reader, daemon=True))
|
||||
for thread in self.threads:
|
||||
thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.stopping.set()
|
||||
for thread in self.threads:
|
||||
thread.join(timeout=self.timeout + 5)
|
||||
|
||||
def window(self, start, end, kind=None):
|
||||
with self.lock:
|
||||
return [e for e in self.events if start <= e[0] < end and (kind is None or e[1] == kind)]
|
||||
|
||||
def verify(self):
|
||||
"""Все подтверждённые сообщения есть в истории, id и тексты не повторяются."""
|
||||
history, _ = read_history(self.bob, self.chat["id"])
|
||||
ids = [message["id"] for message in history]
|
||||
texts = [message["text"] for message in history]
|
||||
by_id = {message["id"]: message for message in history}
|
||||
check(len(ids) == len(set(ids)), "duplicated message ids in history")
|
||||
check(len(texts) == len(set(texts)), "a retried request created a duplicate message")
|
||||
lost = [m for m in self.confirmed if by_id.get(m["id"]) != m]
|
||||
check(not lost, f"{len(lost)} confirmed messages are lost or changed")
|
||||
return {"confirmed_writes": len(self.confirmed), "messages_in_history": len(history), "duplicates": 0, "lost": 0}
|
||||
|
||||
|
||||
def summary(load, start, end):
|
||||
"""Успешные RPS, ошибки и задержки на отрезке [start, end)."""
|
||||
events = load.window(start, end)
|
||||
writes = [e for e in events if e[1] == "write"]
|
||||
ok_writes = sorted(e[5] for e in writes if e[2])
|
||||
errors = [e for e in events if not e[2]]
|
||||
seconds = max(end - start, 1e-6)
|
||||
|
||||
def percentile(p):
|
||||
return round(1000 * ok_writes[max(0, math.ceil(p * len(ok_writes)) - 1)], 1) if ok_writes else None
|
||||
|
||||
codes = {}
|
||||
for e in errors:
|
||||
codes[str(e[3])] = codes.get(str(e[3]), 0) + 1
|
||||
return {
|
||||
"seconds": round(seconds, 2),
|
||||
"write_rps": round(len(ok_writes) / seconds, 1),
|
||||
"reads": len([e for e in events if e[1] == "read"]),
|
||||
"errors": len(errors),
|
||||
"error_codes": codes,
|
||||
"write_p50_ms": percentile(0.50),
|
||||
"write_p95_ms": percentile(0.95),
|
||||
"write_max_ms": round(1000 * ok_writes[-1], 1) if ok_writes else None,
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import subprocess
|
||||
|
||||
from common import ROOT, login, new_user, redis_cli, session_key
|
||||
|
||||
|
||||
def without_password():
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "redis-cli", "get", "anything"],
|
||||
cwd=ROOT, capture_output=True, check=False)
|
||||
return (result.stdout + result.stderr).decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def main():
|
||||
user = new_user("info")
|
||||
token = login(user["username"], user["password"]).json["token"]
|
||||
key = session_key(token)
|
||||
print(f"session key: {key[:24]}...; value is the user id: {redis_cli('get', key) == user['id']}")
|
||||
print(f"TTL of the key, seconds: {redis_cli('ttl', key)}")
|
||||
keys = redis_cli("--scan", "--pattern", "'session:*'").splitlines()
|
||||
print(f"sessions in Redis: {len(keys)}")
|
||||
for name in ("appendonly", "appendfsync", "maxmemory-policy"):
|
||||
print("config", " = ".join(redis_cli("config", "get", name).split()))
|
||||
for line in redis_cli("info", "persistence").splitlines():
|
||||
if line.startswith(("aof_enabled", "aof_last_write_status")):
|
||||
print(line)
|
||||
print(f"without password: {without_password()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,88 @@
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from common import ROOT, api_containers, check, compose, compose_output, docker, health, lb_up_count, wait_balanced
|
||||
from loadgen import Load, summary
|
||||
|
||||
OUTPUT = ROOT / "evidence" / "rolling-update.json"
|
||||
|
||||
|
||||
def env_of(container):
|
||||
lines = docker("inspect", "-f", "{{range .Config.Env}}{{println .}}{{end}}", container).splitlines()
|
||||
return dict(line.split("=", 1) for line in lines if "=" in line)
|
||||
|
||||
|
||||
def wait_new_replica(container, up_needed, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while health(container) != "healthy" or lb_up_count() < up_needed:
|
||||
check(time.monotonic() < deadline, f"new replica {container[:12]} is not in the balancer after {seconds} s")
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def main():
|
||||
old = api_containers()
|
||||
replicas = len(old)
|
||||
check(replicas >= 2, "need at least 2 running api replicas")
|
||||
wait_balanced(replicas)
|
||||
old_version = env_of(old[0]).get("APP_VERSION")
|
||||
version = time.strftime("rolling-%Y%m%d-%H%M%S")
|
||||
env = dict(os.environ, APP_VERSION=version)
|
||||
|
||||
print(f"old replicas {[c[:12] for c in old]}, version {old_version}; building version {version}")
|
||||
started = time.monotonic()
|
||||
compose("build", "api", "migrate", env=env)
|
||||
print(f"image built in {time.monotonic() - started:.1f} s")
|
||||
migrate_log = compose_output("run", "--rm", "--no-deps", "-T", "migrate", env=env)
|
||||
print("migrations: " + [line for line in migrate_log.splitlines() if "Migrations applied" in line][-1]
|
||||
.split("messenger.db: ")[-1])
|
||||
|
||||
load = Load()
|
||||
load.start()
|
||||
time.sleep(3)
|
||||
t0 = time.monotonic()
|
||||
steps = []
|
||||
for container in old:
|
||||
step_start = time.monotonic()
|
||||
before = set(api_containers())
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={len(before) + 1}", "api", env=env)
|
||||
new = sorted(set(api_containers()) - before)
|
||||
check(len(new) == 1, f"expected one new container, got {len(new)}")
|
||||
wait_new_replica(new[0], replicas + 1)
|
||||
ready = time.monotonic() - step_start
|
||||
docker("stop", "--time", "15", container)
|
||||
docker("rm", container)
|
||||
steps.append({"old": container[:12], "new": new[0][:12], "new_ready_seconds": round(ready, 2),
|
||||
"step_seconds": round(time.monotonic() - step_start, 2)})
|
||||
print(f"replaced {container[:12]} -> {new[0][:12]}: new replica ready and in HAProxy after {ready:.1f} s, "
|
||||
f"step {steps[-1]['step_seconds']} s")
|
||||
t1 = time.monotonic()
|
||||
time.sleep(3)
|
||||
load.stop()
|
||||
|
||||
final = api_containers()
|
||||
versions = sorted({env_of(c).get("APP_VERSION") for c in final})
|
||||
integrity = load.verify()
|
||||
during = summary(load, t0, t1)
|
||||
before_stats = summary(load, t0 - 3, t0)
|
||||
print(f"now: replicas {[c[:12] for c in final]}, versions {versions}")
|
||||
print(f"under load: write RPS before {before_stats['write_rps']}, during the update {during['write_rps']}; "
|
||||
f"errors {during['errors']} {during['error_codes']}; p95 {during['write_p95_ms']} ms, "
|
||||
f"max {during['write_max_ms']} ms; update took {t1 - t0:.1f} s")
|
||||
print(f"confirmed {integrity['confirmed_writes']}, in history {integrity['messages_in_history']}, "
|
||||
f"lost 0, duplicates 0")
|
||||
check(len(final) == replicas and not set(final) & set(old), "old replicas are still running")
|
||||
check(versions == [version], "not every replica runs the new version")
|
||||
OUTPUT.parent.mkdir(exist_ok=True)
|
||||
OUTPUT.write_text(json.dumps({
|
||||
"from_version": old_version, "to_version": version, "replicas": replicas,
|
||||
"profile": {"writers": 4, "readers": 1, "client_timeout_seconds": 2},
|
||||
"steps": steps, "update_seconds": round(t1 - t0, 2),
|
||||
"before": before_stats, "during": during, "integrity": integrity,
|
||||
}, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"PASS: all {replicas} replicas replaced one by one under load, "
|
||||
f"{during['errors']} errors, no lost or duplicated messages; saved {OUTPUT.relative_to(ROOT)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,55 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from common import BASE_URL, ROOT, api_containers, call, check, compose_output, docker, wait_balanced
|
||||
|
||||
HOOK = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
|
||||
|
||||
|
||||
def ps():
|
||||
return compose_output("ps", "-a", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}", "api").strip()
|
||||
|
||||
|
||||
def aim(wanted):
|
||||
"""Для 2 реплик: последним перед тестом должна ответить реплика из wanted."""
|
||||
probe = call("GET", "/health/live", 200).instance
|
||||
if not any(container.startswith(probe) for container in wanted):
|
||||
call("GET", "/health/live", 200) # теперь последней ответила другая реплика
|
||||
|
||||
|
||||
def main():
|
||||
containers = api_containers()
|
||||
check(len(containers) >= 2, "need at least 2 running api replicas")
|
||||
print(f"hook: {HOOK.relative_to(ROOT)}; api replicas: {[c[:12] for c in containers]}")
|
||||
stopped_once = set()
|
||||
for attempt in range(1, 7):
|
||||
wait_balanced(len(containers))
|
||||
if len(containers) == 2:
|
||||
aim(set(containers) - stopped_once)
|
||||
print(f"=== run {attempt}: api containers before")
|
||||
print(ps())
|
||||
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
|
||||
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "failover",
|
||||
"--action-script", str(HOOK), "--base-url", BASE_URL],
|
||||
cwd=ROOT, capture_output=True, env=env)
|
||||
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
|
||||
check(result.returncode == 0, "public failover test failed")
|
||||
print("api containers after")
|
||||
print(ps())
|
||||
stopped = [container for container in containers if container not in api_containers()]
|
||||
check(len(stopped) == 1, f"expected exactly one stopped api container, got {len(stopped)}")
|
||||
print(f"the hook stopped {stopped[0][:12]} (X-Instance-Id of that replica = container ID); "
|
||||
f"other api containers kept running, postgres/redis/lb were not touched")
|
||||
stopped_once.add(stopped[0])
|
||||
docker("start", stopped[0])
|
||||
wait_balanced(len(containers))
|
||||
print(f"restored: docker start {stopped[0][:12]} -> healthy and back in HAProxy")
|
||||
if stopped_once == set(containers):
|
||||
break
|
||||
check(stopped_once == set(containers), "not every replica was stopped by the public test")
|
||||
print(f"PASS: public failover test passed {attempt} times; every api replica was stopped once and restored")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from common import BASE_URL, ROOT, check, compose_output, docker
|
||||
|
||||
HOOK = ROOT / "scripts" / ("restart.cmd" if os.name == "nt" else "restart.sh")
|
||||
|
||||
|
||||
def started():
|
||||
containers = compose_output("ps", "-q").split()
|
||||
lines = docker("inspect", "-f", "{{.Name}} {{.Id}} {{.State.StartedAt}}", *containers).splitlines()
|
||||
return {name.lstrip("/"): (cid, at) for name, cid, at in (line.split() for line in lines)}
|
||||
|
||||
|
||||
def main():
|
||||
before = started()
|
||||
print("before: container, ID, started at")
|
||||
for name, (cid, at) in sorted(before.items()):
|
||||
print(f" {name:<28} {cid[:12]} {at}")
|
||||
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
|
||||
begin = time.monotonic()
|
||||
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "persistence",
|
||||
"--action-script", str(HOOK), "--base-url", BASE_URL],
|
||||
cwd=ROOT, capture_output=True, env=env)
|
||||
seconds = time.monotonic() - begin
|
||||
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
|
||||
check(result.returncode == 0, "public persistence test failed")
|
||||
after = started()
|
||||
print(f"after (hook + waiting for readiness took {seconds:.1f} s): container, ID, started at, restarted?")
|
||||
restarted = []
|
||||
for name, (cid, at) in sorted(after.items()):
|
||||
same_id = before.get(name, ("", ""))[0] == cid
|
||||
new_start = before.get(name, ("", ""))[1] != at
|
||||
print(f" {name:<28} {cid[:12]} {at} same container: {same_id}, restarted: {new_start}")
|
||||
check(same_id, f"{name}: container was recreated, volumes/IDs must stay")
|
||||
if new_start:
|
||||
restarted.append(name.split("-")[-2])
|
||||
for service in ("postgres", "redis", "s3", "rabbitmq", "api", "janitor", "dispatcher", "worker", "lb"):
|
||||
check(service in restarted, f"{service} was not restarted by the hook")
|
||||
print("PASS: the hook restarted postgres, redis, s3 (SeaweedFS), rabbitmq, all api replicas, janitor, dispatcher, worker and lb (same containers, "
|
||||
"new start time); data, the attachment bytes and the old token survived")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,258 @@
|
||||
import base64
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from common import PASSWORD, basic, call, check, login, new_chat, new_key, new_user, read_history, run_tests, send
|
||||
|
||||
|
||||
def parse_time(value):
|
||||
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
|
||||
def test_duplicate_username():
|
||||
body = {"username": "dup_" + uuid.uuid4().hex[:10], "display_name": "First user", "password": PASSWORD}
|
||||
call("POST", "/api/v1/users", 201, body=body)
|
||||
call("POST", "/api/v1/users", 409, body=dict(body, display_name="Second user"))
|
||||
print("PASS: duplicate username returns 409")
|
||||
|
||||
|
||||
def test_invalid_json():
|
||||
alice = new_user("alice")
|
||||
chat = new_chat(alice)
|
||||
call("POST", "/api/v1/users", 400, raw=b'{"username":')
|
||||
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], raw=b"not json",
|
||||
headers={"Idempotency-Key": new_key()})
|
||||
print("PASS: invalid JSON returns 400")
|
||||
|
||||
|
||||
def test_wrong_fields():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
call("POST", "/api/v1/users", 400, body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
|
||||
call("POST", "/api/v1/users", 400,
|
||||
body={"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "x", "password": PASSWORD, "is_admin": True})
|
||||
# Отправителя нельзя подставить: он берётся из сессии.
|
||||
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"],
|
||||
body={"text": "hi", "sender_id": bob["id"]}, headers={"Idempotency-Key": new_key()})
|
||||
print("PASS: wrong and extra fields return 400")
|
||||
|
||||
|
||||
def test_foreign_chat():
|
||||
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
|
||||
chat = new_chat(alice, bob)
|
||||
call("GET", f"/api/v1/chats/{chat['id']}", 404, token=eve["token"])
|
||||
call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, token=eve["token"])
|
||||
send(eve, chat["id"], "not my chat", expected=404)
|
||||
# Несуществующий чат выглядит так же, как чужой.
|
||||
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, token=eve["token"])
|
||||
print("PASS: foreign chat returns 404")
|
||||
|
||||
|
||||
def test_empty_message():
|
||||
alice = new_user("alice")
|
||||
chat = new_chat(alice)
|
||||
for text in ("", " ", "\n\t"):
|
||||
send(alice, chat["id"], text, expected=400)
|
||||
send(alice, chat["id"], "я" * 4001, expected=400)
|
||||
send(alice, chat["id"], "я" * 4000)
|
||||
print("PASS: empty and too long messages return 400, 4000 chars is ok")
|
||||
|
||||
|
||||
def test_pagination():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
sent = [send(alice, chat["id"], f"Message {i}").json["id"] for i in range(7)]
|
||||
|
||||
history, pages = read_history(bob, chat["id"], limit=2)
|
||||
check(pages == 4, f"expected 4 pages, got {pages}")
|
||||
check([m["id"] for m in history] == sent, "pages overlap, lose or reorder messages")
|
||||
|
||||
other = new_chat(alice)
|
||||
for i in range(3):
|
||||
send(alice, other["id"], f"Other {i}")
|
||||
first = call("GET", f"/api/v1/chats/{other['id']}/messages?limit=1", token=alice["token"]).json
|
||||
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={first['next_cursor']}", 400, token=alice["token"])
|
||||
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor=broken", 400, token=alice["token"])
|
||||
print("PASS: pagination works across multiple pages, foreign cursor returns 400")
|
||||
|
||||
|
||||
def test_empty_cursor():
|
||||
alice = new_user("alice")
|
||||
chat = new_chat(alice)
|
||||
send(alice, chat["id"], "one message")
|
||||
for path in ("/api/v1/chats", f"/api/v1/chats/{chat['id']}/messages"):
|
||||
for query in ("?cursor=", "?cursor", "?limit=10&cursor="):
|
||||
call("GET", path + query, 400, token=alice["token"])
|
||||
call("GET", path, 200, token=alice["token"])
|
||||
print("PASS: empty cursor (?cursor= and ?cursor) returns 400, no cursor returns the first page")
|
||||
|
||||
|
||||
def test_chat_list_pagination():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
created = [new_chat(alice, bob, title=f"Chat {i}")["id"] for i in range(3)]
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
query = "?limit=1" + (f"&cursor={cursor}" if cursor else "")
|
||||
page = call("GET", "/api/v1/chats" + query, token=bob["token"]).json
|
||||
seen += [chat["id"] for chat in page["items"]]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
check(seen == created, "chat list pages are wrong")
|
||||
print("PASS: chat list pagination")
|
||||
|
||||
|
||||
def test_unicode():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob, title="Чат 👋")
|
||||
text = "Привет 👋 你好"
|
||||
check(send(alice, chat["id"], text).json["text"] == text, "text changed on write")
|
||||
history, _ = read_history(bob, chat["id"])
|
||||
check(history[-1]["text"] == text, "text changed on read")
|
||||
print("PASS: unicode text is stored as is")
|
||||
|
||||
|
||||
def test_nul_character_is_stored():
|
||||
name, title, text = "A\u0000B", "Chat\u0000title", "hello\u0000world"
|
||||
body = {"username": "nul_" + uuid.uuid4().hex[:10], "display_name": name, "password": "pass\u0000word-123"}
|
||||
user = call("POST", "/api/v1/users", 201, body=body).json
|
||||
check(user["display_name"] == name, "display_name with U+0000 changed")
|
||||
token = login(body["username"], body["password"]).json["token"]
|
||||
check(call("GET", "/api/v1/users/me", token=token).json["display_name"] == name, "display_name changed on read")
|
||||
chat = call("POST", "/api/v1/chats", 201, token=token, body={"title": title, "member_ids": [user["id"]]}).json
|
||||
check(chat["title"] == title, "title with U+0000 changed")
|
||||
check(call("GET", f"/api/v1/chats/{chat['id']}", token=token).json["title"] == title, "title changed on read")
|
||||
sent = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=token, body={"text": text},
|
||||
headers={"Idempotency-Key": new_key()}).json
|
||||
history = call("GET", f"/api/v1/chats/{chat['id']}/messages", token=token).json["items"]
|
||||
check(sent["text"] == text and history[-1]["text"] == text, "text with U+0000 changed")
|
||||
login("nul\u0000user", PASSWORD, expected=401)
|
||||
print("PASS: strings with U+0000 are stored and returned as is")
|
||||
|
||||
|
||||
|
||||
def test_user_has_no_password():
|
||||
body = {"username": "np_" + uuid.uuid4().hex[:10], "display_name": "No password", "password": PASSWORD}
|
||||
user = call("POST", "/api/v1/users", 201, body=body).json
|
||||
check(set(user) == {"id", "username", "display_name", "created_at"}, f"unexpected fields: {set(user)}")
|
||||
print("PASS: user response has no password or hash")
|
||||
|
||||
|
||||
def test_password_rules():
|
||||
def register(password, expected):
|
||||
body = {"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "Password", "password": password}
|
||||
call("POST", "/api/v1/users", expected, body=body)
|
||||
|
||||
register("x" * 11, 400)
|
||||
register("x" * 129, 400)
|
||||
register(" " * 12, 400)
|
||||
register("x" * 12, 201)
|
||||
register("я" * 128, 201)
|
||||
print("PASS: password length 12..128, blank password is rejected")
|
||||
|
||||
|
||||
def test_login_gives_token():
|
||||
username = "lg_" + uuid.uuid4().hex[:10]
|
||||
user = call("POST", "/api/v1/users", 201,
|
||||
body={"username": username, "display_name": "Login", "password": PASSWORD}).json
|
||||
reply = login(username, PASSWORD)
|
||||
session = reply.json
|
||||
check(session["token_type"] == "Bearer", "token_type must be Bearer")
|
||||
check(session["user"] == user, "session user differs from registered user")
|
||||
check(len(session["token"]) >= 43, "token is too short")
|
||||
check(username not in session["token"] and user["id"] not in session["token"], "token is not opaque")
|
||||
check(reply.headers.get("cache-control") == "no-store", "response with token must not be cached")
|
||||
left = (parse_time(session["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
check(290 < left <= 3600 + 5, f"unexpected session lifetime: {left:.0f} s")
|
||||
me = call("GET", "/api/v1/users/me", token=session["token"]).json
|
||||
check(me == user, "/users/me returned another user")
|
||||
print("PASS: Basic login returns opaque Bearer token with expiry")
|
||||
|
||||
|
||||
def test_wrong_password():
|
||||
user = new_user("wp")
|
||||
wrong = login(user["username"], "Wrong-password-000", expected=401)
|
||||
unknown = login("nobody_" + uuid.uuid4().hex[:8], PASSWORD, expected=401)
|
||||
check(wrong.headers["www-authenticate"].lower().startswith("basic"), "login 401 must ask for Basic")
|
||||
check(wrong.json["error"]["message"] == unknown.json["error"]["message"], "different answers leak usernames")
|
||||
print("PASS: wrong password and unknown user both return the same 401")
|
||||
|
||||
|
||||
def test_malformed_basic():
|
||||
no_colon = base64.b64encode(b"just_username").decode()
|
||||
for header in (None, "Basic", "Basic !!!", "Basic " + no_colon, "Bearer something"):
|
||||
headers = {} if header is None else {"Authorization": header}
|
||||
call("POST", "/api/v1/auth/sessions", 401, headers=headers)
|
||||
print("PASS: malformed Basic header returns 401")
|
||||
|
||||
|
||||
def test_password_with_colon_and_unicode():
|
||||
password = "пароль:с:двоеточием 👋"
|
||||
user = new_user("colon", password=password)
|
||||
call("GET", "/api/v1/users/me", token=user["token"])
|
||||
print("PASS: password with colon and unicode works")
|
||||
|
||||
|
||||
def test_bearer_required():
|
||||
user = new_user("br")
|
||||
for headers in ({}, {"Authorization": basic(user["username"], user["password"])},
|
||||
{"X-User-Id": user["id"]}, {"Authorization": "Bearer " + "A" * 43},
|
||||
{"Authorization": "Bearer"}, {"Authorization": "Token " + user["token"]}):
|
||||
reply = call("GET", "/api/v1/users/me", 401, headers=headers)
|
||||
check(reply.headers["www-authenticate"].lower().startswith("bearer"), "401 must ask for Bearer")
|
||||
call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + user["token"]})
|
||||
print("PASS: business endpoints need Bearer; Basic and X-User-Id give 401")
|
||||
|
||||
|
||||
def test_x_user_id_ignored():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
me = call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": bob["id"]}).json
|
||||
check(me["id"] == alice["id"], "X-User-Id changed the current user")
|
||||
print("PASS: X-User-Id does not change the current user")
|
||||
|
||||
|
||||
def test_auth_before_body():
|
||||
alice = new_user("alice")
|
||||
chat = new_chat(alice)
|
||||
call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, raw=b"not json")
|
||||
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
|
||||
print("PASS: 401 comes before 400 and 404")
|
||||
|
||||
|
||||
def test_logout():
|
||||
user = new_user("lo")
|
||||
second = login(user["username"], user["password"]).json["token"]
|
||||
call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
|
||||
call("GET", "/api/v1/users/me", 401, token=user["token"])
|
||||
call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"])
|
||||
call("GET", "/api/v1/users/me", 200, token=second) # другая сессия того же пользователя жива
|
||||
again = login(user["username"], user["password"]).json["token"]
|
||||
check(again != user["token"], "new login must give a new token")
|
||||
call("GET", "/api/v1/users/me", 200, token=again)
|
||||
print("PASS: logout revokes only the current session")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([
|
||||
test_duplicate_username,
|
||||
test_invalid_json,
|
||||
test_wrong_fields,
|
||||
test_foreign_chat,
|
||||
test_empty_message,
|
||||
test_pagination,
|
||||
test_empty_cursor,
|
||||
test_chat_list_pagination,
|
||||
test_unicode,
|
||||
test_nul_character_is_stored,
|
||||
test_user_has_no_password,
|
||||
test_password_rules,
|
||||
test_login_gives_token,
|
||||
test_wrong_password,
|
||||
test_malformed_basic,
|
||||
test_password_with_colon_and_unicode,
|
||||
test_bearer_required,
|
||||
test_x_user_id_ignored,
|
||||
test_auth_before_body,
|
||||
test_logout,
|
||||
])
|
||||
@@ -0,0 +1,338 @@
|
||||
"""Вложения через балансировщик: корректные файлы, лимиты, битые файлы, подмена MIME, доступ.
|
||||
|
||||
Только HTTP, Docker не нужен. Каждый негативный случай проверяет точный код ответа:
|
||||
пользовательская ошибка не должна становиться 500.
|
||||
"""
|
||||
import hashlib
|
||||
import http.client
|
||||
import socket
|
||||
import struct
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
import images
|
||||
from common import BASE_URL, call, check, new_chat, new_key, new_user, post_message, read_history, run_tests, upload
|
||||
|
||||
URL = urllib.parse.urlsplit(BASE_URL)
|
||||
|
||||
|
||||
def setup():
|
||||
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
|
||||
return alice, bob, eve, new_chat(alice, bob)
|
||||
|
||||
|
||||
def sha(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def check_error(reply, code):
|
||||
check(reply.json["error"]["code"] == code, f"expected error code {code}, got {reply.json['error']['code']}")
|
||||
|
||||
|
||||
def test_png_and_jpeg_roundtrip():
|
||||
alice, bob, _, chat = setup()
|
||||
for data, ctype, name in ((images.sample_png(), "image/png", "sample.png"),
|
||||
(images.sample_jpeg(), "image/jpeg", "sample.jpg"),
|
||||
(images.progressive_jpeg(), "image/jpeg", "progressive.jpg"),
|
||||
(images.png(33, 17, interlace=1), "image/png", "interlaced.png"),
|
||||
(images.png(1, 1, gray=True), "image/png", "1x1.png")):
|
||||
att = upload(alice, chat["id"], data, ctype, name).json
|
||||
check(att["status"] == "ready" and att["error_code"] is None, "not ready")
|
||||
check([v["name"] for v in att["variants"]] == ["thumbnail", "crop", "optimized"], "lab5 variants missing")
|
||||
check(att["sha256"] == sha(data) and att["size_bytes"] == len(data), "checksum/size differ")
|
||||
check(att["content_type"] == ctype and att["filename"] == name, "metadata differs")
|
||||
meta = call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"]).json
|
||||
check(meta == att, "GET metadata differs from POST response")
|
||||
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
|
||||
check(got.data == data, "downloaded bytes differ")
|
||||
check(got.headers["content-type"] == ctype, "wrong Content-Type on download")
|
||||
check(got.headers.get("content-length") == str(len(data)), "wrong Content-Length")
|
||||
check(got.headers.get("x-content-type-options") == "nosniff", "nosniff is missing")
|
||||
print(f"{name}: {len(data)} bytes, sha256 {att['sha256'][:12]}..., downloaded by the other member, same bytes")
|
||||
print("PASS: PNG, JPEG, progressive JPEG, interlaced PNG and 1x1 PNG are stored and returned byte for byte")
|
||||
|
||||
|
||||
def test_size_limit_exact_boundary():
|
||||
alice, _, _, chat = setup()
|
||||
exact = images.png(64, 64, pad_to=images.MAX_UPLOAD_BYTES)
|
||||
check(len(exact) == images.MAX_UPLOAD_BYTES, "fixture must be exactly 10 MiB")
|
||||
att = upload(alice, chat["id"], exact).json
|
||||
check(att["size_bytes"] == images.MAX_UPLOAD_BYTES and att["sha256"] == sha(exact), "10 MiB file changed")
|
||||
print(f"exactly {len(exact)} bytes (10 MiB) -> 202, then ready")
|
||||
over = images.png(64, 64, pad_to=images.MAX_UPLOAD_BYTES + 1)
|
||||
reply = upload(alice, chat["id"], over, expected=413)
|
||||
check_error(reply, "payload_too_large")
|
||||
print(f"{len(over)} bytes (10 MiB + 1) with Content-Length -> 413 before reading the body")
|
||||
print("PASS: the 10 MiB limit is exact")
|
||||
|
||||
|
||||
def chunked_upload(user, chat_id, total, piece=64 * 1024):
|
||||
"""Тело без Content-Length (Transfer-Encoding: chunked): сервер узнаёт размер только при чтении."""
|
||||
conn = http.client.HTTPConnection(URL.hostname, URL.port or 80, timeout=60)
|
||||
|
||||
def body():
|
||||
sent = 0
|
||||
head = images.sample_png()[:64]
|
||||
yield head
|
||||
sent += len(head)
|
||||
while sent < total:
|
||||
part = bytes(min(piece, total - sent))
|
||||
sent += len(part)
|
||||
yield part
|
||||
try:
|
||||
conn.request("POST", f"/api/v1/chats/{chat_id}/attachments?filename=big.png", body=body(),
|
||||
headers={"Content-Type": "image/png", "Authorization": "Bearer " + user["token"]},
|
||||
encode_chunked=True)
|
||||
reply = conn.getresponse()
|
||||
return reply.status, reply.read()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_size_limit_streaming():
|
||||
alice, _, _, chat = setup()
|
||||
status, data = chunked_upload(alice, chat["id"], 12 * 1024 * 1024)
|
||||
check(status == 413 and b"payload_too_large" in data, f"chunked 12 MiB: expected 413, got {status}")
|
||||
print("12 MiB without Content-Length (chunked) -> 413 as soon as the 10 MiB limit is passed")
|
||||
call("GET", "/health/ready", 200)
|
||||
print("PASS: oversized streamed body is cut off, the API keeps working")
|
||||
|
||||
|
||||
def test_pixel_limit():
|
||||
alice, _, _, chat = setup()
|
||||
at_limit = images.png(8000, 5000, gray=True) # ровно 40 000 000 пикселей
|
||||
att = upload(alice, chat["id"], at_limit, filename="40mpx.png").json
|
||||
print(f"8000x5000 = 40 000 000 pixels ({len(at_limit)} bytes compressed) -> 202, ready {att['id'][:8]}")
|
||||
over = images.png(8001, 5000, gray=True)
|
||||
check_error(upload(alice, chat["id"], over, filename="over.png", expected=413), "payload_too_large")
|
||||
print(f"8001x5000 = 40 005 000 pixels ({len(over)} bytes) -> 413")
|
||||
bomb = images.png(100_000, 100_000, idat=b"x\x9c\x03\x00\x00\x00\x00\x01")
|
||||
check_error(upload(alice, chat["id"], bomb, filename="bomb.png", expected=413), "payload_too_large")
|
||||
print(f"header claims 100000x100000 in {len(bomb)} bytes -> 413 from the header, nothing is decoded")
|
||||
print("PASS: pixel limit is checked before decompression")
|
||||
|
||||
|
||||
def test_damaged_images():
|
||||
alice, _, _, chat = setup()
|
||||
png, jpeg = images.sample_png(), images.sample_jpeg()
|
||||
cases = [
|
||||
("PNG cut in half", png[:len(png) // 2], "image/png"),
|
||||
("PNG without IEND", png[:-12], "image/png"),
|
||||
("PNG with a flipped byte in IDAT (CRC mismatch)", images.flip_byte(png, len(png) // 2), "image/png"),
|
||||
("PNG with garbage after IEND", png + b"garbage", "image/png"),
|
||||
("PNG signature only", png[:8], "image/png"),
|
||||
("PNG with less pixel data than the header says", images.png(10, 10, idat=zlib.compress(b"\x00" * 5)), "image/png"),
|
||||
("JPEG cut in half", jpeg[:len(jpeg) // 2], "image/jpeg"),
|
||||
("JPEG header only", jpeg[:20], "image/jpeg"),
|
||||
("random bytes", uuid.uuid4().bytes * 100, "image/png"),
|
||||
("plain text", "это не картинка".encode(), "image/jpeg"),
|
||||
]
|
||||
for name, data, ctype in cases:
|
||||
reply = upload(alice, chat["id"], data, ctype, "broken.bin", expected=415)
|
||||
check_error(reply, "unsupported_media_type")
|
||||
print(f"{name} ({len(data)} bytes, {ctype}) -> 415")
|
||||
check_error(upload(alice, chat["id"], b"", expected=400), "invalid_request")
|
||||
print("empty body -> 400")
|
||||
print("PASS: damaged and foreign files are rejected with 415, never 500")
|
||||
|
||||
|
||||
def test_png_chunk_semantics():
|
||||
"""CRC у всех чанков верные, но содержимое нарушает спецификацию PNG -> 415, а не 201.
|
||||
|
||||
Регрессия: PNG 1x1, глубина 8, палитровый, PLTE из 771 байта (257 записей) раньше получал 201 ready,
|
||||
хотя Pillow его отклоняет (invalid palette size).
|
||||
"""
|
||||
alice, bob, _, chat = setup()
|
||||
from images import assemble, ihdr, zero_idat
|
||||
pal = lambda entries: (b"PLTE", bytes(3 * entries))
|
||||
idat_p = zero_idat(1, 1, 8, 1)
|
||||
bad = [
|
||||
("PLTE 771 bytes = 257 entries (review case)",
|
||||
assemble(ihdr(1, 1, 8, 3), (b"PLTE", bytes(771)), (b"IDAT", zlib.compress(b"\0\0")))),
|
||||
("PLTE length not a multiple of 3", assemble(ihdr(1, 1, 8, 3), (b"PLTE", bytes(4)), idat_p)),
|
||||
("empty PLTE", assemble(ihdr(1, 1, 8, 3), (b"PLTE", b""), idat_p)),
|
||||
("palette larger than bit depth allows (depth 1, 3 entries)",
|
||||
assemble(ihdr(1, 1, 1, 3), pal(3), zero_idat(1, 1, 1, 1))),
|
||||
("palette image without PLTE", assemble(ihdr(1, 1, 8, 3), idat_p)),
|
||||
("PLTE in a grayscale image", assemble(ihdr(1, 1, 8, 0), pal(2), zero_idat(1, 1, 8, 1))),
|
||||
("PLTE after IDAT", assemble(ihdr(1, 1, 8, 3), idat_p, pal(2))),
|
||||
("two PLTE chunks", assemble(ihdr(1, 1, 8, 3), pal(2), pal(2), idat_p)),
|
||||
("tRNS longer than the palette", assemble(ihdr(1, 1, 8, 3), pal(2), (b"tRNS", bytes(3)), idat_p)),
|
||||
("tRNS before PLTE", assemble(ihdr(1, 1, 8, 3), (b"tRNS", bytes(1)), pal(2), idat_p)),
|
||||
("tRNS of wrong size for RGB (4 bytes instead of 6)",
|
||||
assemble(ihdr(1, 1, 8, 2), (b"tRNS", bytes(4)), zero_idat(1, 1, 8, 3))),
|
||||
("tRNS in an image with alpha channel",
|
||||
assemble(ihdr(1, 1, 8, 6), (b"tRNS", bytes(2)), zero_idat(1, 1, 8, 4))),
|
||||
("IEND with data", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"IEND", b"x"))),
|
||||
("unknown critical chunk", assemble(ihdr(1, 1, 8, 2), (b"ABCD", b""), zero_idat(1, 1, 8, 3))),
|
||||
("IDAT chunks not consecutive",
|
||||
assemble(ihdr(1, 2, 8, 2), (b"IDAT", zero_idat(1, 2, 8, 3)[1][:5]), (b"tEXt", b"k\0v"),
|
||||
(b"IDAT", zero_idat(1, 2, 8, 3)[1][5:]))),
|
||||
("gAMA after IDAT", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"gAMA", bytes(4)))),
|
||||
("gAMA of 2 bytes instead of 4", assemble(ihdr(1, 1, 8, 2), (b"gAMA", bytes(2)), zero_idat(1, 1, 8, 3))),
|
||||
("3 MiB metadata chunk before IDAT", assemble(ihdr(1, 1, 8, 2), (b"prVt", bytes(3 * 1024 * 1024)),
|
||||
zero_idat(1, 1, 8, 3))),
|
||||
("private chunk after IDAT", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"prVt", bytes(100)))),
|
||||
("animated PNG frame (fdAT)", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"fdAT", bytes(10)))),
|
||||
("tIME of 2 bytes instead of 7", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"tIME", bytes(2)))),
|
||||
("tEXt without keyword separator", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"tEXt", b"nokey"))),
|
||||
("zTXt with broken zlib after IDAT",
|
||||
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"k\0\0garbage"))),
|
||||
("zTXt text bomb: 50 MB of text in ~50 KB after IDAT",
|
||||
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"k\0\0" + zlib.compress(bytes(50_000_000))))),
|
||||
]
|
||||
for name, data in bad:
|
||||
check_error(upload(alice, chat["id"], data, filename="bad.png", expected=415), "unsupported_media_type")
|
||||
print(f"{name} ({len(data)} bytes, valid CRCs) -> 415")
|
||||
good = [
|
||||
("palette 256 entries + tRNS + tEXt and tIME after IDAT",
|
||||
assemble(ihdr(2, 2, 8, 3), pal(256), (b"tRNS", bytes(256)), zero_idat(2, 2, 8, 1),
|
||||
(b"tEXt", b"Comment\0ok"), (b"tIME", struct.pack(">HBBBBB", 2026, 10, 22, 12, 0, 0)))),
|
||||
("palette depth 2 with 4 entries", assemble(ihdr(3, 1, 2, 3), pal(4), zero_idat(3, 1, 2, 1))),
|
||||
("RGB with 6-byte tRNS and gAMA", assemble(ihdr(1, 1, 8, 2), (b"gAMA", struct.pack(">I", 45455)),
|
||||
(b"tRNS", bytes(6)), zero_idat(1, 1, 8, 3))),
|
||||
("compressed zTXt (100 KB of text) and iTXt after IDAT",
|
||||
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"Comment\0\0" + zlib.compress(b"a" * 100_000)),
|
||||
(b"iTXt", b"Title\0\1\0ru\0\0" + zlib.compress("Привет".encode())))),
|
||||
]
|
||||
for name, data in good:
|
||||
att = upload(alice, chat["id"], data, filename="good.png").json
|
||||
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
|
||||
check(got.data == data, "valid PNG changed")
|
||||
print(f"{name} -> 201, downloaded byte for byte")
|
||||
print("PASS: chunk contents are checked, not only CRCs; valid PNGs with metadata are still accepted")
|
||||
|
||||
|
||||
def test_mime_substitution():
|
||||
alice, _, _, chat = setup()
|
||||
cases = [
|
||||
("PNG bytes sent as image/jpeg", images.sample_png(), "image/jpeg"),
|
||||
("JPEG bytes sent as image/png", images.sample_jpeg(), "image/png"),
|
||||
("GIF bytes sent as image/png", images.GIF, "image/png"),
|
||||
("PNG sent as image/gif", images.sample_png(), "image/gif"),
|
||||
("PNG sent as text/html", images.sample_png(), "text/html"),
|
||||
("PNG sent as application/octet-stream", images.sample_png(), "application/octet-stream"),
|
||||
("PNG sent as multipart/form-data", images.sample_png(), "multipart/form-data; boundary=x"),
|
||||
]
|
||||
for name, data, ctype in cases:
|
||||
check_error(upload(alice, chat["id"], data, ctype, expected=415), "unsupported_media_type")
|
||||
print(f"{name} -> 415")
|
||||
att = upload(alice, chat["id"], images.sample_png(), "IMAGE/PNG; charset=binary").json
|
||||
check(att["content_type"] == "image/png", "content type must be normalised")
|
||||
print("PNG sent as 'IMAGE/PNG; charset=binary' -> 201, stored as image/png")
|
||||
print("PASS: the type is taken from the content; a declared type that does not match is refused")
|
||||
|
||||
|
||||
def test_filenames():
|
||||
alice, _, _, chat = setup()
|
||||
bad = ["../../etc/passwd", "a/b.png", "a\\b.png", "a\x00b.png", "line\nbreak.png", "tab\t.png",
|
||||
"bell\x07.png", "del\x7f.png", "", " ", ".", "..", "x" * 256]
|
||||
for name in bad:
|
||||
check_error(upload(alice, chat["id"], images.sample_png(), filename=name, expected=400), "invalid_request")
|
||||
print(f"{len(bad)} dangerous or invalid names (path, slashes, NUL, control characters, empty, 256 chars) -> 400")
|
||||
check_error(upload(alice, chat["id"], images.sample_png(), filename=None, expected=400), "invalid_request")
|
||||
print("no filename -> 400")
|
||||
for name in ("фото отпуска 😀.png", "x" * 255, "..hidden.png", "a b%20c?.png"):
|
||||
att = upload(alice, chat["id"], images.sample_png(), filename=name).json
|
||||
check(att["filename"] == name, "display name changed")
|
||||
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=alice["token"])
|
||||
check("filename*=UTF-8''" in got.headers.get("content-disposition", ""), "Content-Disposition is not encoded")
|
||||
print("Unicode, 255 chars, leading dots, %20 and ? are kept as display names only")
|
||||
print("PASS: filename never becomes a path; dangerous names are refused")
|
||||
|
||||
|
||||
def test_access_control():
|
||||
alice, bob, eve, chat = setup()
|
||||
att = upload(alice, chat["id"], images.sample_png()).json
|
||||
for suffix in ("", "/content"):
|
||||
reply = call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 404, token=eve["token"])
|
||||
check_error(reply, "not_found")
|
||||
call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 401)
|
||||
call("GET", f"/api/v1/attachments/{uuid.uuid4()}{suffix}", 404, token=alice["token"])
|
||||
call("GET", f"/api/v1/attachments/not-a-uuid{suffix}", 400, token=alice["token"])
|
||||
print("outsider -> 404 for metadata and bytes (same as a non-existent id); no token -> 401; bad UUID -> 400")
|
||||
check_error(upload(eve, chat["id"], images.sample_png(), expected=404), "not_found")
|
||||
check_error(upload(alice, str(uuid.uuid4()), images.sample_png(), expected=404), "not_found")
|
||||
upload(None, chat["id"], images.sample_png(), expected=401)
|
||||
print("upload into someone else's / unknown chat -> 404, without token -> 401")
|
||||
call("GET", f"/api/v1/attachments/{att['id']}/content?variant=preview", 400, token=bob["token"])
|
||||
for variant in ("original", "thumbnail", "crop", "optimized"):
|
||||
call("GET", f"/api/v1/attachments/{att['id']}/content?variant={variant}", 200, token=bob["token"])
|
||||
print("variant=preview -> 400 (not in the contract); original/thumbnail/crop/optimized -> 200 (lab5)")
|
||||
print("PASS: only chat members can see an attachment")
|
||||
|
||||
|
||||
def test_message_attachments():
|
||||
alice, bob, eve, chat = setup()
|
||||
first = upload(alice, chat["id"], images.sample_png()).json
|
||||
second = upload(bob, chat["id"], images.sample_jpeg(), "image/jpeg", "b.jpg").json
|
||||
msg = post_message(alice, chat["id"], "", [second["id"], first["id"]]).json
|
||||
check(msg["attachment_ids"] == [second["id"], first["id"]] and msg["text"] == "", "order or text changed")
|
||||
print("text='' with 2 attachments -> 201, order kept; any member may attach a file uploaded by another member")
|
||||
plain = post_message(bob, chat["id"], "без вложений").json
|
||||
check(plain["attachment_ids"] == [], "default attachment_ids must be []")
|
||||
reused = post_message(bob, chat["id"], "то же вложение ещё раз", [first["id"]]).json
|
||||
history, _ = read_history(bob, chat["id"])
|
||||
check(history == [msg, plain, reused], "history differs from the confirmed messages")
|
||||
print("history returns attachment_ids for every message, [] for a message without files; reuse is allowed")
|
||||
|
||||
other_chat = new_chat(alice, eve)
|
||||
foreign = upload(alice, other_chat["id"], images.sample_png()).json
|
||||
for ids, what in (([foreign["id"]], "attachment of another chat (author is a member of both)"),
|
||||
([first["id"], foreign["id"]], "own + foreign attachment"),
|
||||
([str(uuid.uuid4())], "unknown attachment_id")):
|
||||
check_error(post_message(alice, chat["id"], "x", ids, expected=404), "not_found")
|
||||
print(f"{what} -> 404")
|
||||
check_error(post_message(eve, chat["id"], "x", [first["id"]], expected=404), "not_found")
|
||||
print("outsider referencing an attachment of the chat -> 404")
|
||||
for ids, text, what in (([first["id"], first["id"]], "x", "duplicate ids"),
|
||||
([str(uuid.uuid4()) for _ in range(11)], "x", "11 ids"),
|
||||
(["not-a-uuid"], "x", "bad UUID"),
|
||||
([], "", "empty text without attachments"),
|
||||
([], " ", "whitespace text without attachments")):
|
||||
check_error(post_message(alice, chat["id"], text, ids, expected=400), "invalid_request")
|
||||
print(f"{what} -> 400")
|
||||
history_after, _ = read_history(bob, chat["id"])
|
||||
check(history_after == history, "a rejected message was stored")
|
||||
print("PASS: only attachments of the same chat can be linked; rejected requests change nothing")
|
||||
|
||||
|
||||
def test_idempotency_with_attachments():
|
||||
alice, bob, _, chat = setup()
|
||||
att = upload(alice, chat["id"], images.sample_png()).json
|
||||
other = upload(alice, chat["id"], images.sample_jpeg(), "image/jpeg").json
|
||||
key = new_key()
|
||||
first = post_message(alice, chat["id"], "фото", [att["id"]], key=key).json
|
||||
again = post_message(alice, chat["id"], "фото", [att["id"]], key=key).json
|
||||
check(again == first, "replay returned a different message")
|
||||
check_error(post_message(alice, chat["id"], "фото", [other["id"]], key=key, expected=409), "conflict")
|
||||
check_error(post_message(alice, chat["id"], "фото", [att["id"], other["id"]], key=key, expected=409), "conflict")
|
||||
key2 = new_key()
|
||||
plain = post_message(alice, chat["id"], "текст", None, key=key2).json
|
||||
check(post_message(alice, chat["id"], "текст", [], key=key2).json == plain, "[] must equal a missing field")
|
||||
history, _ = read_history(bob, chat["id"])
|
||||
check(len(history) == 2, "replays created extra messages")
|
||||
print("same key + same attachments -> same 201; other attachments -> 409; missing field == []")
|
||||
print("PASS: Idempotency-Key covers attachment_ids")
|
||||
|
||||
|
||||
def test_aborted_upload():
|
||||
alice, _, _, chat = setup()
|
||||
sock = socket.create_connection((URL.hostname, URL.port or 80), timeout=10)
|
||||
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=cut.png HTTP/1.1\r\nHost: {URL.hostname}\r\n"
|
||||
f"Authorization: Bearer {alice['token']}\r\nContent-Type: image/png\r\nContent-Length: 5000000\r\n\r\n")
|
||||
sock.sendall(head.encode() + images.sample_png() + bytes(1_000_000))
|
||||
sock.close() # клиент пропал на середине тела
|
||||
print("sent 1.1 MB of a declared 5 MB body and closed the connection")
|
||||
att = upload(alice, chat["id"], images.sample_png()).json
|
||||
call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=alice["token"])
|
||||
print("the API keeps serving uploads; nothing of the aborted request is visible "
|
||||
"(DB/S3 side is checked by test_consistency.py)")
|
||||
print("PASS: an interrupted upload is dropped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([test_png_and_jpeg_roundtrip, test_size_limit_exact_boundary, test_size_limit_streaming,
|
||||
test_pixel_limit, test_damaged_images, test_png_chunk_semantics, test_mime_substitution, test_filenames, test_access_control,
|
||||
test_message_attachments, test_idempotency_with_attachments, test_aborted_upload])
|
||||
@@ -0,0 +1,103 @@
|
||||
from collections import Counter
|
||||
|
||||
import images
|
||||
from common import api_containers, call, check, new_chat, new_key, new_user, run_tests, send, upload
|
||||
|
||||
|
||||
def test_requests_spread_over_replicas():
|
||||
alice = new_user("alice")
|
||||
replies = [call("GET", "/api/v1/users/me", 200, token=alice["token"]) for _ in range(20)]
|
||||
served = Counter(reply.instance for reply in replies)
|
||||
print(f"20 x GET /users/me with one token -> replicas: {dict(served)}")
|
||||
check(all(reply.json["id"] == alice["id"] for reply in replies), "another user returned")
|
||||
check(len(served) >= 2, "all requests went to one replica: balancing does not work")
|
||||
print("PASS: one session works on every replica, no second login (sessions are shared in Redis)")
|
||||
|
||||
|
||||
def test_write_on_one_read_on_other():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
sent = send(alice, chat["id"], "written on one replica")
|
||||
readers = set()
|
||||
for _ in range(6):
|
||||
reply = call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, token=bob["token"])
|
||||
check(sent.json in reply.json["items"], "confirmed message is not visible on another replica")
|
||||
readers.add(reply.instance)
|
||||
print(f"message written by {sent.instance}; read back by {sorted(readers)}")
|
||||
check(readers - {sent.instance}, "no read went to another replica")
|
||||
print("PASS: a message written via one replica is read right away via another (shared PostgreSQL)")
|
||||
|
||||
|
||||
def test_logout_seen_by_all_replicas():
|
||||
user = new_user("logout")
|
||||
out = call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
|
||||
after = [call("GET", "/api/v1/users/me", 401, token=user["token"]).instance for _ in range(10)]
|
||||
print(f"logout on {out.instance}; old token then rejected by {sorted(set(after))}")
|
||||
check(len(set(after)) >= 2, "only one replica answered")
|
||||
print("PASS: logout on one replica revokes the session on all of them")
|
||||
|
||||
|
||||
def test_idempotent_retry_on_other_replica():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
key = new_key()
|
||||
first = send(alice, chat["id"], "retry me", key=key)
|
||||
for _ in range(10): # round robin: следующий запрос уйдёт на другую реплику
|
||||
retry = send(alice, chat["id"], "retry me", key=key)
|
||||
if retry.instance != first.instance:
|
||||
break
|
||||
print(f"first POST on {first.instance} -> 201 {first.json['id']}; "
|
||||
f"same key on {retry.instance} -> {retry.status} {retry.json['id']}")
|
||||
check(retry.instance != first.instance, "retry never reached another replica")
|
||||
check(retry.json == first.json, "retry on another replica returned a different message")
|
||||
items = call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, token=bob["token"]).json["items"]
|
||||
check([m["text"] for m in items].count("retry me") == 1, "retry created a duplicate")
|
||||
print("PASS: Idempotency-Key is shared: a retry through another replica returns the same message")
|
||||
|
||||
|
||||
def test_attachment_on_other_replica():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
data = images.sample_png()
|
||||
sent = upload(alice, chat["id"], data)
|
||||
readers = set()
|
||||
for _ in range(6):
|
||||
reply = call("GET", f"/api/v1/attachments/{sent.json['id']}/content", 200, token=bob["token"])
|
||||
check(reply.data == data, "another replica returned different bytes")
|
||||
readers.add(reply.instance)
|
||||
print(f"file uploaded via {sent.instance}; downloaded byte for byte via {sorted(readers)}")
|
||||
check(readers - {sent.instance}, "no download went to another replica")
|
||||
print("PASS: a file uploaded through one replica is downloaded through another (shared S3, nothing local)")
|
||||
|
||||
|
||||
def test_instance_header_everywhere():
|
||||
containers = api_containers()
|
||||
alice, eve = new_user("alice"), new_user("eve")
|
||||
chat = new_chat(alice)
|
||||
replies = [
|
||||
call("GET", "/health/live", 200),
|
||||
call("GET", "/health/ready", 200),
|
||||
send(alice, chat["id"], "hello"),
|
||||
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], body={"text": "no key"}),
|
||||
call("GET", "/api/v1/users/me", 401),
|
||||
call("GET", f"/api/v1/chats/{chat['id']}", 404, token=eve["token"]),
|
||||
call("POST", "/api/v1/users", 409,
|
||||
body={"username": alice["username"], "display_name": "x", "password": alice["password"]}),
|
||||
]
|
||||
for reply in replies: # call() уже проверил, что заголовок есть; здесь — что это настоящий контейнер
|
||||
check(any(container.startswith(reply.instance) for container in containers),
|
||||
f"X-Instance-Id {reply.instance} is not a running api container")
|
||||
print(f"statuses {[r.status for r in replies]}: every answer has X-Instance-Id of a running container "
|
||||
f"{sorted({r.instance for r in replies})}; api containers: {[c[:12] for c in containers]}")
|
||||
print("PASS: X-Instance-Id is in every response and points to a real container")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([
|
||||
test_requests_spread_over_replicas,
|
||||
test_write_on_one_read_on_other,
|
||||
test_logout_seen_by_all_replicas,
|
||||
test_idempotent_retry_on_other_replica,
|
||||
test_attachment_on_other_replica,
|
||||
test_instance_header_everywhere,
|
||||
])
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Согласованность PostgreSQL и S3 при отказах; работа janitor (компенсация и очистка).
|
||||
|
||||
Нужен запущенный стенд из compose.yaml. Тест останавливает/замораживает S3 (`docker compose stop|pause s3`),
|
||||
выполняет код приложения внутри контейнера api (имитация падения между S3 PUT и COMMIT) и запускает
|
||||
janitor вручную. Данные синтетические, volumes не удаляются.
|
||||
|
||||
python student-tests/test_consistency.py [s3|crash|orphan|aborted|all]
|
||||
"""
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import images
|
||||
from common import (BASE_URL, app_python, call, check, compose, compose_output, docker, janitor, new_chat,
|
||||
new_user, post_message, run_tests, sql_value, upload, wait_ready)
|
||||
|
||||
URL = urllib.parse.urlsplit(BASE_URL)
|
||||
|
||||
# Выполняется внутри контейнера api: настоящие attachments.store / storage / db, но enqueue_upload
|
||||
# (lab5: UPDATE ... state='queued' + задание + outbox, COMMIT) падает — как если бы реплика умерла
|
||||
# сразу после PUT в staging, до фиксации задания.
|
||||
CRASH_AFTER_PUT = r'''
|
||||
import json, struct, sys, tempfile, zlib
|
||||
from uuid import UUID
|
||||
import attachments, db, storage, uploads
|
||||
chat_id, owner_id = UUID(sys.argv[1]), UUID(sys.argv[2])
|
||||
def chunk(k, d): return struct.pack(">I", len(d)) + k + d + struct.pack(">I", zlib.crc32(k + d))
|
||||
data = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 0, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(b"\x00\x80\x80\x80\x80" * 4)) + chunk(b"IEND", b""))
|
||||
f = tempfile.SpooledTemporaryFile(); f.write(data)
|
||||
import hashlib
|
||||
upload = uploads.Upload(f, len(data), hashlib.sha256(data).hexdigest())
|
||||
image = uploads.inspect(upload, "image/png")
|
||||
created = {}
|
||||
real_intent = db.create_upload_intent
|
||||
def remember(attachment_id, *args):
|
||||
created["id"], created["key"] = str(attachment_id), args[-1]
|
||||
return real_intent(attachment_id, *args)
|
||||
def crash(attachment_id, *args):
|
||||
raise RuntimeError("simulated crash between S3 PUT and DB COMMIT")
|
||||
db.create_upload_intent = remember
|
||||
db.enqueue_upload = crash
|
||||
db.pool.open()
|
||||
try:
|
||||
attachments.store(chat_id, owner_id, "crash.png", upload, image)
|
||||
outcome = "stored"
|
||||
except RuntimeError as exc:
|
||||
outcome = str(exc)
|
||||
print(json.dumps({"outcome": outcome, "attachment_id": created["id"], "object_key": created["key"],
|
||||
"object_exists": storage.exists(created["key"])}))
|
||||
'''
|
||||
|
||||
OBJECT_EXISTS = r'''
|
||||
import json, sys, storage
|
||||
print(json.dumps({"exists": storage.exists(sys.argv[1])}))
|
||||
'''
|
||||
|
||||
PUT_ORPHAN = r'''
|
||||
import hashlib, io, json, uuid, storage
|
||||
data = b"orphan object without a row in PostgreSQL"
|
||||
key = storage.new_key(uuid.uuid4().hex)
|
||||
storage.put(key, io.BytesIO(data), len(data), "image/png", hashlib.sha256(data).hexdigest())
|
||||
print(json.dumps({"key": key}))
|
||||
'''
|
||||
|
||||
DELETE_OBJECT = r'''
|
||||
import json, sys, storage
|
||||
storage.delete(sys.argv[1]); print(json.dumps({"deleted": sys.argv[1]}))
|
||||
'''
|
||||
|
||||
COUNT_OBJECTS = r'''
|
||||
import json, storage
|
||||
print(json.dumps({"objects": sum(1 for prefix in storage.ALL_PREFIXES for _ in storage.list_objects(prefix))}))
|
||||
'''
|
||||
|
||||
|
||||
def last_json(output):
|
||||
return json.loads(output.splitlines()[-1])
|
||||
|
||||
|
||||
def object_exists(key):
|
||||
return last_json(app_python(OBJECT_EXISTS, key))["exists"]
|
||||
|
||||
|
||||
def backdate(where):
|
||||
sql_value(f"UPDATE attachments SET created_at = created_at - interval '2 hours' WHERE {where}")
|
||||
|
||||
|
||||
def uploading_rows(chat_id):
|
||||
return int(sql_value(f"SELECT count(*) FROM attachments WHERE chat_id = '{chat_id}' AND state = 'uploading'"))
|
||||
|
||||
|
||||
def wait_download(user, att, seconds=60):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
reply = call("GET", f"/api/v1/attachments/{att['id']}/content", (200, 503), token=user["token"])
|
||||
if reply.status == 200:
|
||||
return reply
|
||||
check(time.monotonic() < deadline, "download did not recover after S3 start")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def s3_outage(stop_action, start_action, label):
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
data = images.sample_png()
|
||||
att = upload(alice, chat["id"], data).json
|
||||
before = uploading_rows(chat["id"])
|
||||
print(f"--- S3 {label}: docker compose {stop_action} s3")
|
||||
compose(stop_action, "s3")
|
||||
try:
|
||||
started = time.monotonic()
|
||||
reply = upload(alice, chat["id"], data, expected=503)
|
||||
ms = (time.monotonic() - started) * 1000
|
||||
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
|
||||
body = reply.data.decode().lower()
|
||||
check(not any(word in body for word in ("seaweed", "bucket", "s3:8333", "originals/", "traceback")),
|
||||
"error leaks storage details")
|
||||
print(f"upload -> 503 unavailable in {ms:.0f} ms, no storage details in the body")
|
||||
reply = call("GET", f"/api/v1/attachments/{att['id']}/content", 503, token=bob["token"])
|
||||
print("download of an existing file -> 503")
|
||||
meta = call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"]).json
|
||||
check(meta["sha256"] == att["sha256"], "metadata changed")
|
||||
post_message(alice, chat["id"], "текст без файла")
|
||||
post_message(alice, chat["id"], "", [att["id"]])
|
||||
call("GET", "/health/ready", 200)
|
||||
print("metadata, messages (also with an already stored attachment) and /health/ready keep working: "
|
||||
"S3 is needed only for file bytes")
|
||||
after = uploading_rows(chat["id"])
|
||||
print(f"uploading rows of this chat: before {before}, after the failed upload {after} "
|
||||
"(kept as a pointer for janitor if the rollback could not reach S3); not visible through the API")
|
||||
finally:
|
||||
print(f"docker compose {start_action} s3")
|
||||
compose(start_action, "s3")
|
||||
got = wait_download(bob, att)
|
||||
check(got.data == data, "file changed after S3 recovery")
|
||||
print("after S3 recovery the old file downloads byte for byte")
|
||||
upload(alice, chat["id"], data)
|
||||
print("new upload -> 201")
|
||||
leftover = uploading_rows(chat["id"])
|
||||
if leftover:
|
||||
backdate(f"chat_id = '{chat['id']}' AND state = 'uploading'")
|
||||
report = janitor()
|
||||
print(f"janitor after grace period: {json.dumps(report)}")
|
||||
check(uploading_rows(chat["id"]) == 0, "abandoned upload rows remain")
|
||||
print(f"PASS: S3 {label} -> 503 for file operations only, no visible half-uploads, everything cleaned up")
|
||||
|
||||
|
||||
def test_s3_stopped():
|
||||
s3_outage("stop", "start", "stopped (connection refused / name not resolved)")
|
||||
|
||||
|
||||
def test_s3_frozen():
|
||||
s3_outage("pause", "unpause", "frozen (no answer, timeouts)")
|
||||
|
||||
|
||||
def test_crash_between_s3_and_db():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
ready = upload(alice, chat["id"], images.sample_png()).json
|
||||
result = last_json(app_python(CRASH_AFTER_PUT, chat["id"], alice["id"]))
|
||||
check(result["outcome"].startswith("simulated crash"), f"unexpected outcome {result['outcome']}")
|
||||
att_id, key = result["attachment_id"], result["object_key"]
|
||||
state = sql_value(f"SELECT state FROM attachments WHERE id = '{att_id}'")
|
||||
check(state == "uploading" and result["object_exists"], "expected an uploading row and an object in S3")
|
||||
print(f"crash after S3 PUT: row {att_id[:8]} state={state}, object {key} exists in S3")
|
||||
call("GET", f"/api/v1/attachments/{att_id}", 404, token=alice["token"])
|
||||
call("GET", f"/api/v1/attachments/{att_id}/content", 404, token=alice["token"])
|
||||
post_message(alice, chat["id"], "x", [att_id], expected=404)
|
||||
print("the half-written attachment is invisible: GET -> 404, attach to a message -> 404")
|
||||
|
||||
report = janitor()
|
||||
check(sql_value(f"SELECT count(*) FROM attachments WHERE id = '{att_id}'") == "1" and object_exists(key),
|
||||
"fresh upload was deleted inside the grace period")
|
||||
print(f"janitor with default grace ({report['grace_seconds']} s) right away: {json.dumps(report)} -> "
|
||||
"fresh row and object are kept (the upload might still be running)")
|
||||
backdate(f"id = '{att_id}'")
|
||||
report = janitor("--dry-run")
|
||||
check(report["stale_uploads"] >= 1 and report["stale_uploads_deleted"] == 0, "dry run must only report")
|
||||
check(sql_value(f"SELECT count(*) FROM attachments WHERE id = '{att_id}'") == "1", "dry run deleted a row")
|
||||
print(f"row made 2 h old; janitor --dry-run: {json.dumps(report)} -> nothing deleted")
|
||||
report = janitor()
|
||||
check(report["stale_uploads_deleted"] >= 1, "janitor did not reclaim the abandoned upload")
|
||||
check(sql_value(f"SELECT count(*) FROM attachments WHERE id = '{att_id}'") == "0", "row still exists")
|
||||
check(not object_exists(key), "object still exists")
|
||||
print(f"janitor: {json.dumps(report)} -> row and object deleted")
|
||||
report = janitor()
|
||||
print(f"janitor again: {json.dumps(report)} -> idempotent")
|
||||
got = call("GET", f"/api/v1/attachments/{ready['id']}/content", 200, token=bob["token"])
|
||||
check(got.data == images.sample_png(), "ready attachment damaged by cleanup")
|
||||
print("the ready attachment of the same chat is untouched")
|
||||
print("PASS: S3 written but DB not committed -> invisible, reclaimed by janitor only after the grace period")
|
||||
|
||||
|
||||
def test_orphan_objects():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
ready = upload(alice, chat["id"], images.sample_png()).json
|
||||
key = last_json(app_python(PUT_ORPHAN))["key"]
|
||||
print(f"object {key} put into the bucket without a row in PostgreSQL")
|
||||
# Короткий grace только для теста: janitor требует grace >= 2 x UPLOAD_TIMEOUT_SECONDS, поэтому задаём 1 с.
|
||||
short = {"UPLOAD_TIMEOUT_SECONDS": "1"}
|
||||
report = janitor("--grace-seconds", "3", env=short)
|
||||
check(object_exists(key), "fresh orphan deleted inside grace period")
|
||||
print(f"janitor --grace-seconds 3 immediately: {json.dumps(report)} -> fresh object kept")
|
||||
time.sleep(4)
|
||||
report = janitor("--grace-seconds", "3", "--dry-run", env=short)
|
||||
check(report["orphan_objects"] >= 1 and report["orphan_objects_deleted"] == 0 and object_exists(key),
|
||||
"dry run must report and keep the orphan")
|
||||
print(f"after 4 s, --dry-run: {json.dumps(report)} -> reported, kept")
|
||||
report = janitor("--grace-seconds", "3", env=short)
|
||||
check(report["orphan_objects_deleted"] >= 1 and not object_exists(key), "orphan not deleted")
|
||||
print(f"janitor: {json.dumps(report)} -> orphan deleted")
|
||||
got = call("GET", f"/api/v1/attachments/{ready['id']}/content", 200, token=bob["token"])
|
||||
check(got.data == images.sample_png(), "ready attachment was deleted with orphans")
|
||||
print("ready attachments older than the grace period are untouched (they have rows)")
|
||||
|
||||
victim = upload(alice, chat["id"], images.sample_png(), filename="victim.png").json
|
||||
victim_key = sql_value(f"SELECT object_key FROM attachments WHERE id = '{victim['id']}'")
|
||||
app_python(DELETE_OBJECT, victim_key)
|
||||
report = janitor("--grace-seconds", "3", env=short)
|
||||
check(report["missing_objects"] >= 1, "missing object not reported")
|
||||
check(sql_value(f"SELECT state FROM attachments WHERE id = '{victim['id']}'") == "ready", "row was deleted")
|
||||
reply = call("GET", f"/api/v1/attachments/{victim['id']}/content", 503, token=bob["token"])
|
||||
print(f"object of a ready attachment deleted behind the API's back: janitor reports missing_objects="
|
||||
f"{report['missing_objects']} and keeps the row; download -> {reply.status} (not 500)")
|
||||
print("PASS: orphans are found and deleted only after the grace period; missing objects are reported")
|
||||
|
||||
|
||||
def api_tmp_files():
|
||||
counts = {}
|
||||
for container in compose_output("ps", "-q", "api").split():
|
||||
counts[container[:12]] = int(docker("exec", container, "sh", "-c", "ls -A /tmp/uploads | wc -l") or 0)
|
||||
return counts
|
||||
|
||||
|
||||
def test_aborted_upload_leaves_nothing():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
objects = last_json(app_python(COUNT_OBJECTS))["objects"]
|
||||
rows = int(sql_value("SELECT count(*) FROM attachments"))
|
||||
for sent in (100_000, 3_000_000):
|
||||
sock = socket.create_connection((URL.hostname, URL.port or 80), timeout=10)
|
||||
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=cut.png HTTP/1.1\r\nHost: x\r\n"
|
||||
f"Authorization: Bearer {alice['token']}\r\nContent-Type: image/png\r\n"
|
||||
f"Content-Length: 9000000\r\n\r\n")
|
||||
sock.sendall(head.encode() + images.sample_png() + bytes(sent))
|
||||
sock.close()
|
||||
print(f"declared 9 000 000 bytes, sent {sent + len(images.sample_png())}, closed the connection")
|
||||
time.sleep(2)
|
||||
check(int(sql_value("SELECT count(*) FROM attachments")) == rows, "an aborted upload left a row")
|
||||
check(last_json(app_python(COUNT_OBJECTS))["objects"] == objects, "an aborted upload left an S3 object")
|
||||
print(f"rows in attachments: {rows} -> {rows}; objects in bucket: {objects} -> {objects}")
|
||||
tmp = api_tmp_files()
|
||||
check(all(n == 0 for n in tmp.values()), f"temporary files left: {tmp}")
|
||||
print(f"temporary upload files in api containers: {tmp} (removed when the request ends)")
|
||||
for container in compose_output("ps", "-q", "api").split():
|
||||
mounts = docker("inspect", "-f", "{{json .Mounts}}", container)
|
||||
# файловые secrets compose монтируются read-only в /run/secrets — это не хранилище данных
|
||||
storage = [m for m in json.loads(mounts)
|
||||
if not (m.get("Destination", "").startswith("/run/secrets/") and m.get("RW") is False)]
|
||||
check(storage == [], f"api must not have volumes: originals live only in S3, got {storage}")
|
||||
print("api containers have no volumes: the original is never stored locally")
|
||||
print("PASS: an interrupted upload leaves no row, no object and no local file")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
target = sys.argv[1] if len(sys.argv) > 1 else "all"
|
||||
groups = {"s3": [test_s3_stopped, test_s3_frozen], "crash": [test_crash_between_s3_and_db],
|
||||
"orphan": [test_orphan_objects], "aborted": [test_aborted_upload_leaves_nothing]}
|
||||
groups["all"] = groups["aborted"] + groups["crash"] + groups["orphan"] + groups["s3"]
|
||||
check(target in groups, "usage: python student-tests/test_consistency.py [s3|crash|orphan|aborted|all]")
|
||||
wait_ready()
|
||||
run_tests(groups[target])
|
||||
@@ -0,0 +1,101 @@
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common import call, check, compose_output, new_user, psql, run_tests
|
||||
|
||||
|
||||
def sql_value(sql):
|
||||
code, output, error = psql(sql)
|
||||
check(code == 0, f"psql failed: {error}")
|
||||
return output
|
||||
|
||||
|
||||
def test_create_chat_rolls_back():
|
||||
alice = new_user("rollback")
|
||||
title = "rollback-" + uuid.uuid4().hex[:8]
|
||||
inserted_before = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
|
||||
|
||||
call("POST", "/api/v1/chats", 400, token=alice["token"],
|
||||
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
|
||||
|
||||
left = sql_value(f"SELECT count(*) FROM chats WHERE title = '{title}'")
|
||||
orphans = sql_value("SELECT count(*) FROM chats c WHERE NOT EXISTS "
|
||||
"(SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)")
|
||||
inserted_after = inserted_before
|
||||
deadline = time.monotonic() + 15
|
||||
while inserted_after == inserted_before and time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
inserted_after = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
|
||||
print(f"chat with unknown member -> 400; rows with this title: {left}; chats without members: {orphans}; "
|
||||
f"chats insert counter: {inserted_before} -> {inserted_after}")
|
||||
check(left == "0" and orphans == "0", "chat row survived the failed transaction")
|
||||
check(inserted_after > inserted_before, "the chat row was never inserted, rollback is not shown")
|
||||
print("PASS: chat row was inserted and then rolled back together with members")
|
||||
|
||||
|
||||
def test_message_needs_membership_in_db():
|
||||
code, _, error = psql("INSERT INTO messages (id, chat_id, sender_id, text) "
|
||||
f"VALUES ('{uuid.uuid4()}', '{uuid.uuid4()}', '{uuid.uuid4()}', convert_to('direct insert', 'UTF8'))")
|
||||
print(f"direct INSERT of a message from a non-member -> exit code {code}: {error.splitlines()[0] if error else ''}")
|
||||
check(code != 0 and "foreign key" in error, "database accepted a message from a non-member")
|
||||
print("PASS: the database itself rejects a message from a non-member")
|
||||
|
||||
|
||||
def test_password_is_argon2id():
|
||||
user = new_user("hash")
|
||||
stored = sql_value(f"SELECT password_hash FROM users WHERE username = '{user['username']}'")
|
||||
print(f"stored password: {stored[:31]}... (length {len(stored)})")
|
||||
check(stored.startswith("$argon2id$") and user["password"] not in stored, "password is not an Argon2id hash")
|
||||
print("PASS: password is stored as Argon2id hash")
|
||||
|
||||
|
||||
def test_unique_username_constraint():
|
||||
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
|
||||
"WHERE conrelid = 'users'::regclass AND contype = 'u'")
|
||||
print(f"unique constraint on users: {constraint}")
|
||||
check(constraint == "UNIQUE (username)", "no unique constraint on username")
|
||||
print("PASS: username is unique in the database")
|
||||
|
||||
|
||||
def test_migrations_are_not_repeated():
|
||||
versions = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
|
||||
print(f"applied migrations: {versions}; running the migrate service once more")
|
||||
output = compose_output("run", "--rm", "--no-deps", "-T", "migrate")
|
||||
again = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
|
||||
last_log = [line for line in output.splitlines() if "Migrations applied" in line][-1]
|
||||
print(f"after the second run: {again}; log: {last_log.split('messenger.db: ')[-1]}")
|
||||
check(again == versions and "none" in last_log, "migrations were applied again")
|
||||
print("PASS: migrations are applied once, a repeated run does nothing")
|
||||
|
||||
|
||||
def test_replicas_do_not_migrate():
|
||||
"""lab3: миграции применяет только сервис migrate, API-реплики лишь проверяют схему."""
|
||||
logs = compose_output("logs", "api").splitlines()
|
||||
checked = [line for line in logs if "Schema is up to date" in line]
|
||||
migrated = [line for line in logs if "Migrations applied" in line]
|
||||
migrate_exit = compose_output("ps", "-a", "--format", "{{.Status}}", "migrate").strip()
|
||||
print(f"api replicas that checked the schema at start: {len(checked)}; api log lines 'Migrations applied': "
|
||||
f"{len(migrated)}; migrate service: {migrate_exit}")
|
||||
check(checked and not migrated, "api replicas must not apply migrations")
|
||||
check(migrate_exit.startswith("Exited (0)"), "migrate service must finish with exit code 0")
|
||||
print("PASS: only the migrate service applies migrations, replicas wait for the schema")
|
||||
|
||||
|
||||
def test_idempotency_key_is_unique_in_db():
|
||||
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
|
||||
"WHERE conname = 'messages_idempotency_key'")
|
||||
print(f"unique constraint for Idempotency-Key: {constraint}")
|
||||
check(constraint == "UNIQUE (chat_id, sender_id, idempotency_key)", "no unique constraint for idempotency keys")
|
||||
print("PASS: one message per (chat, sender, Idempotency-Key) is enforced by the database")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([
|
||||
test_create_chat_rolls_back,
|
||||
test_message_needs_membership_in_db,
|
||||
test_password_is_argon2id,
|
||||
test_unique_username_constraint,
|
||||
test_migrations_are_not_repeated,
|
||||
test_replicas_do_not_migrate,
|
||||
test_idempotency_key_is_unique_in_db,
|
||||
])
|
||||
@@ -0,0 +1,57 @@
|
||||
import datetime as dt
|
||||
import os
|
||||
import time
|
||||
|
||||
from common import call, check, compose, login, new_user, redis_cli, run_tests, session_key, wait_ready
|
||||
|
||||
SHORT_TTL = 2
|
||||
|
||||
|
||||
def restart_api(ttl=None):
|
||||
env = dict(os.environ)
|
||||
if ttl is None:
|
||||
env.pop("SESSION_TTL_SECONDS", None) # значение снова из .env
|
||||
else:
|
||||
env["SESSION_TTL_SECONDS"] = str(ttl)
|
||||
compose("up", "-d", "--no-deps", "--wait", "api", env=env)
|
||||
wait_ready()
|
||||
|
||||
|
||||
def seconds_left(expires_at):
|
||||
moment = dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
|
||||
return (moment - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
|
||||
|
||||
def test_session_expires():
|
||||
print(f"recreating api with SESSION_TTL_SECONDS={SHORT_TTL}")
|
||||
restart_api(SHORT_TTL)
|
||||
try:
|
||||
user = new_user("ttl")
|
||||
session = login(user["username"], user["password"]).json
|
||||
token = session["token"]
|
||||
left = seconds_left(session["expires_at"])
|
||||
print(f"session issued, expires in {left:.2f} s; Redis TTL of the key: "
|
||||
f"{redis_cli('pttl', session_key(token))} ms")
|
||||
check(0 < left <= SHORT_TTL + 0.5, "short TTL instance must issue ~2 second sessions")
|
||||
|
||||
call("GET", "/api/v1/users/me", 200, token=token)
|
||||
print("before expiry: GET /users/me -> 200")
|
||||
|
||||
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 1.0)
|
||||
call("GET", "/api/v1/users/me", 401, token=token)
|
||||
exists = redis_cli("exists", session_key(token))
|
||||
print(f"after expiry: GET /users/me -> 401; key exists in Redis: {exists}")
|
||||
check(exists == "0", "Redis must delete the expired session key")
|
||||
finally:
|
||||
print("recreating api with SESSION_TTL_SECONDS from .env")
|
||||
restart_api()
|
||||
|
||||
user = new_user("ttl_back")
|
||||
left = seconds_left(login(user["username"], user["password"]).json["expires_at"])
|
||||
print(f"normal API again: new session expires in {left:.0f} s")
|
||||
check(left > 300, "normal TTL was not restored")
|
||||
print("PASS: session expires after SESSION_TTL_SECONDS and is rejected with 401")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([test_session_expires])
|
||||
@@ -0,0 +1,110 @@
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common import PASSWORD, basic, call, check, compose, new_chat, new_key, new_user, read_history, run_tests, send, wait_ready
|
||||
|
||||
FAKE_TOKEN = "A" * 43
|
||||
|
||||
|
||||
def timed(method, path, expected, **kwargs):
|
||||
started = time.monotonic()
|
||||
reply = call(method, path, expected, **kwargs)
|
||||
return reply, (time.monotonic() - started) * 1000
|
||||
|
||||
|
||||
def prepare():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
before = send(alice, chat["id"], "confirmed before outage").json
|
||||
return alice, bob, chat, before
|
||||
|
||||
|
||||
def recovered(alice, chat, before):
|
||||
wait_ready()
|
||||
history, _ = read_history(alice, chat["id"])
|
||||
check(before in history, "message confirmed before the outage is lost or changed")
|
||||
call("GET", "/api/v1/users/me", 200, token=alice["token"])
|
||||
print("after start: the old token works, confirmed messages are in place")
|
||||
|
||||
|
||||
def test_redis_down():
|
||||
alice, bob, chat, before = prepare()
|
||||
print("stopping redis")
|
||||
compose("stop", "redis")
|
||||
try:
|
||||
call("GET", "/health/live", 200)
|
||||
_, ms = timed("GET", "/health/ready", 503)
|
||||
print(f"/health/live -> 200, /health/ready -> 503 ({ms:.0f} ms)")
|
||||
reply, ms = timed("GET", "/api/v1/users/me", 503, token=alice["token"])
|
||||
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
|
||||
print(f"valid token: GET /users/me -> 503 unavailable ({ms:.0f} ms), session cannot be checked")
|
||||
call("GET", "/api/v1/chats", 503, token=FAKE_TOKEN)
|
||||
print("unknown token -> 503, not 200: nobody is trusted without a check")
|
||||
call("GET", "/api/v1/chats", 401)
|
||||
print("no token -> 401")
|
||||
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": basic(alice["username"], PASSWORD)})
|
||||
print("login -> 503: there is nowhere to store the session")
|
||||
call("POST", "/api/v1/users", 201,
|
||||
body={"username": "rd_" + uuid.uuid4().hex[:10], "display_name": "x", "password": PASSWORD})
|
||||
print("registration -> 201: it needs only PostgreSQL")
|
||||
finally:
|
||||
print("starting redis")
|
||||
compose("start", "redis")
|
||||
recovered(alice, chat, before)
|
||||
print("PASS: Redis outage gives 503 and does not let anyone in without a session check")
|
||||
|
||||
|
||||
def test_redis_crash():
|
||||
alice = new_user("crash")
|
||||
print("killing redis with SIGKILL (docker compose kill redis): no graceful shutdown")
|
||||
compose("kill", "redis")
|
||||
try:
|
||||
# Обычно 503; 200 возможен, если Docker уже успел поднять Redis по restart policy.
|
||||
status = call("GET", "/api/v1/users/me", (503, 200), token=alice["token"]).status
|
||||
print(f"right after the crash: GET /users/me -> {status}")
|
||||
finally:
|
||||
print("starting redis")
|
||||
compose("start", "redis")
|
||||
wait_ready()
|
||||
call("GET", "/api/v1/users/me", 200, token=alice["token"])
|
||||
print("after start: the session issued before the crash still works (AOF, appendfsync always)")
|
||||
print("PASS: sessions survive a Redis crash, not only a clean restart")
|
||||
|
||||
|
||||
def test_postgres_down():
|
||||
alice, bob, chat, before = prepare()
|
||||
print("stopping postgres")
|
||||
compose("stop", "postgres")
|
||||
try:
|
||||
call("GET", "/health/live", 200)
|
||||
_, ms = timed("GET", "/health/ready", 503)
|
||||
print(f"/health/live -> 200, /health/ready -> 503 ({ms:.0f} ms)")
|
||||
for method, path, body in (("GET", "/api/v1/users/me", None),
|
||||
("GET", "/api/v1/chats", None),
|
||||
("GET", f"/api/v1/chats/{chat['id']}/messages", None),
|
||||
("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "will not be saved"})):
|
||||
reply = call(method, path, 503, token=alice["token"], body=body, headers={"Idempotency-Key": new_key()})
|
||||
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
|
||||
check("postgres" not in reply.data.decode().lower(), "error must not show database details")
|
||||
print("valid token: users/me, chats, history, new message -> 503 unavailable, no details")
|
||||
call("GET", "/api/v1/chats", 401)
|
||||
call("GET", "/api/v1/chats", 401, token=FAKE_TOKEN)
|
||||
print("no token -> 401, unknown token -> 401: anonymous users are not let in")
|
||||
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": basic(alice["username"], PASSWORD)})
|
||||
call("POST", "/api/v1/users", 503,
|
||||
body={"username": "pd_" + uuid.uuid4().hex[:10], "display_name": "x", "password": PASSWORD})
|
||||
print("login -> 503, registration -> 503")
|
||||
finally:
|
||||
print("starting postgres")
|
||||
compose("start", "postgres")
|
||||
recovered(alice, chat, before)
|
||||
print("PASS: PostgreSQL outage gives limited 503 errors and keeps anonymous users out")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
target = sys.argv[1] if len(sys.argv) > 1 else "all"
|
||||
tests = {"redis": [test_redis_down, test_redis_crash], "postgres": [test_postgres_down],
|
||||
"all": [test_redis_down, test_redis_crash, test_postgres_down]}
|
||||
check(target in tests, "usage: python student-tests/test_failures.py [redis|postgres]")
|
||||
run_tests(tests[target])
|
||||
@@ -0,0 +1,174 @@
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import BASE_URL, call, check, new_chat, new_key, new_user, read_history, run_tests, send
|
||||
|
||||
PARALLEL = 20
|
||||
|
||||
|
||||
def post_raw(user, chat_id, raw, key):
|
||||
"""POST с телом «как есть» (bytes) — чтобы проверить другой порядок ключей и пробелы."""
|
||||
return call("POST", f"/api/v1/chats/{chat_id}/messages", (201, 409, 400), token=user["token"],
|
||||
raw=raw, headers={"Idempotency-Key": key})
|
||||
|
||||
|
||||
def texts_in(user, chat_id):
|
||||
history, _ = read_history(user, chat_id)
|
||||
return [message["text"] for message in history]
|
||||
|
||||
|
||||
def test_replay_returns_same_message():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
key = new_key()
|
||||
first = send(alice, chat["id"], "Привет 👋", key=key)
|
||||
# То же JSON-значение, записанное иначе: пробелы и \u-экранирование.
|
||||
same = post_raw(alice, chat["id"], b'{ "text" : "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442 \\ud83d\\udc4b" }', key)
|
||||
again = send(alice, chat["id"], "Привет 👋", key=key)
|
||||
print(f"first -> {first.status}; same JSON written differently -> {same.status}; plain retry -> {again.status}")
|
||||
check(same.status == 201 and same.json == first.json and again.json == first.json,
|
||||
"retry must return the original 201 and the same message")
|
||||
check(texts_in(bob, chat["id"]).count("Привет 👋") == 1, "retry created a duplicate")
|
||||
print("PASS: a retry with the same key returns the original 201 and message, no duplicate")
|
||||
|
||||
|
||||
def test_same_key_parallel_through_replicas():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
key = new_key()
|
||||
barrier = threading.Barrier(PARALLEL)
|
||||
|
||||
def post(_):
|
||||
barrier.wait() # все запросы стартуют одновременно
|
||||
return send(alice, chat["id"], "one message for 20 requests", key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
|
||||
replies = list(pool.map(post, range(PARALLEL)))
|
||||
bodies = {json.dumps(reply.json, sort_keys=True) for reply in replies}
|
||||
served = Counter(reply.instance for reply in replies)
|
||||
count = texts_in(bob, chat["id"]).count("one message for 20 requests")
|
||||
print(f"{PARALLEL} parallel POSTs with one key: statuses {dict(Counter(r.status for r in replies))}, "
|
||||
f"replicas {dict(served)}, different bodies in answers: {len(bodies)}, messages in history: {count}")
|
||||
check(len(served) >= 2, "requests did not go through different replicas")
|
||||
check(len(bodies) == 1 and count == 1, "parallel retries created more than one message")
|
||||
print("PASS: parallel requests with one key through different replicas create exactly one message")
|
||||
|
||||
|
||||
def test_same_key_different_bodies_parallel():
|
||||
alice = new_user("alice")
|
||||
chat = new_chat(alice)
|
||||
key = new_key()
|
||||
barrier = threading.Barrier(PARALLEL)
|
||||
|
||||
def post(index):
|
||||
text = "body A" if index % 2 == 0 else "body B"
|
||||
barrier.wait()
|
||||
reply = call("POST", f"/api/v1/chats/{chat['id']}/messages", (201, 409), token=alice["token"],
|
||||
body={"text": text}, headers={"Idempotency-Key": key})
|
||||
return text, reply
|
||||
|
||||
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
|
||||
results = list(pool.map(post, range(PARALLEL)))
|
||||
texts = texts_in(alice, chat["id"])
|
||||
winner = [t for t in texts if t in ("body A", "body B")]
|
||||
print(f"{PARALLEL} parallel POSTs, one key, two different bodies: "
|
||||
f"{dict(Counter((t, r.status) for t, r in results))}; saved: {winner}")
|
||||
check(len(winner) == 1, "exactly one message must be created")
|
||||
for text, reply in results:
|
||||
expected = 201 if text == winner[0] else 409
|
||||
check(reply.status == expected, f"{text}: expected {expected}, got {reply.status}")
|
||||
print("PASS: the first body wins, the same body gets 201, the other body gets 409")
|
||||
|
||||
|
||||
def test_key_scope():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
other = new_chat(alice, bob)
|
||||
key = new_key()
|
||||
a1 = send(alice, chat["id"], "scope", key=key).json
|
||||
b1 = send(bob, chat["id"], "scope", key=key).json
|
||||
a2 = send(alice, other["id"], "scope", key=key).json
|
||||
print(f"one key: alice in chat 1, bob in chat 1, alice in chat 2 -> {len({a1['id'], b1['id'], a2['id']})} messages")
|
||||
check(len({a1["id"], b1["id"], a2["id"]}) == 3, "a key must be scoped to user + chat")
|
||||
call("POST", f"/api/v1/chats/{chat['id']}/messages", 409, token=alice["token"],
|
||||
body={"text": "other text"}, headers={"Idempotency-Key": key})
|
||||
print("PASS: the key is scoped to the current user and chat; another body with a used key -> 409")
|
||||
|
||||
|
||||
def test_key_validation():
|
||||
alice = new_user("alice")
|
||||
chat = new_chat(alice)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
call("POST", path, 400, token=alice["token"], body={"text": "no key"})
|
||||
for bad in ("", "a" * 129, "has space", "slash/inside", "ключ", "quote\"", "a+b"):
|
||||
call("POST", path, 400, token=alice["token"], body={"text": "bad key"},
|
||||
headers={"Idempotency-Key": bad.encode("utf-8").decode("latin-1")}) # как есть, байтами UTF-8
|
||||
longest = ("Az09._:-" * 16)[:128]
|
||||
call("POST", path, 201, token=alice["token"], body={"text": "longest key"}, headers={"Idempotency-Key": longest})
|
||||
print("missing, empty, 129 chars, space, '/', non-ASCII, '\"', '+' -> 400; 128 chars of A-Z a-z 0-9 . _ : - -> 201")
|
||||
print("PASS: Idempotency-Key is required and checked: [A-Za-z0-9._:-]{1,128}")
|
||||
|
||||
|
||||
def test_failed_request_does_not_burn_key():
|
||||
alice, eve = new_user("alice"), new_user("eve")
|
||||
chat = new_chat(alice)
|
||||
key = new_key()
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
call("POST", path, 400, token=alice["token"], body={"text": " "}, headers={"Idempotency-Key": key})
|
||||
call("POST", path, 404, token=eve["token"], body={"text": "not my chat"}, headers={"Idempotency-Key": key})
|
||||
created = call("POST", path, 201, token=alice["token"], body={"text": "valid now"}, headers={"Idempotency-Key": key})
|
||||
print(f"key used by a 400 and by a 404 first, then valid request -> {created.status}")
|
||||
print("PASS: rejected requests (400, 404) do not store a result for the key")
|
||||
|
||||
|
||||
def test_replay_checks_session_and_access():
|
||||
alice, eve = new_user("alice"), new_user("eve")
|
||||
chat = new_chat(alice)
|
||||
key = new_key()
|
||||
send(alice, chat["id"], "private", key=key)
|
||||
stolen = call("POST", f"/api/v1/chats/{chat['id']}/messages", 404, token=eve["token"],
|
||||
body={"text": "private"}, headers={"Idempotency-Key": key})
|
||||
call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"])
|
||||
revoked = call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, token=alice["token"],
|
||||
body={"text": "private"}, headers={"Idempotency-Key": key})
|
||||
print(f"same key and body by an outsider -> {stolen.status}; by alice after logout -> {revoked.status}")
|
||||
print("PASS: a retry checks the session and chat access again, the saved answer is not leaked")
|
||||
|
||||
|
||||
def test_lost_response_then_retry():
|
||||
"""Клиент отправил POST и не дождался ответа (оборвал соединение). Повтор с тем же ключом безопасен."""
|
||||
alice = new_user("alice")
|
||||
chat = new_chat(alice)
|
||||
key = new_key()
|
||||
body = json.dumps({"text": "answer was lost"}).encode("utf-8")
|
||||
url = urllib.parse.urlsplit(BASE_URL)
|
||||
request = (f"POST /api/v1/chats/{chat['id']}/messages HTTP/1.1\r\nHost: {url.netloc}\r\n"
|
||||
f"Authorization: Bearer {alice['token']}\r\nIdempotency-Key: {key}\r\n"
|
||||
f"Content-Type: application/json\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode()
|
||||
with socket.create_connection((url.hostname, url.port or 80), timeout=5) as connection:
|
||||
connection.sendall(request + body) # и сразу закрываем, ответ не читаем
|
||||
time.sleep(1)
|
||||
retry = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=alice["token"],
|
||||
body={"text": "answer was lost"}, headers={"Idempotency-Key": key})
|
||||
count = texts_in(alice, chat["id"]).count("answer was lost")
|
||||
print(f"POST sent, connection closed without reading the answer; retry -> {retry.status}; messages: {count}")
|
||||
check(count == 1, "the retry after a lost answer created a duplicate")
|
||||
print("PASS: an unconfirmed POST can be safely retried with the same key")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([
|
||||
test_replay_returns_same_message,
|
||||
test_same_key_parallel_through_replicas,
|
||||
test_same_key_different_bodies_parallel,
|
||||
test_key_scope,
|
||||
test_key_validation,
|
||||
test_failed_request_does_not_burn_key,
|
||||
test_replay_checks_session_and_access,
|
||||
test_lost_response_then_retry,
|
||||
])
|
||||
@@ -0,0 +1,567 @@
|
||||
"""Lab5: асинхронная обработка вложений — варианты, сохранность, отказы, повторы, DLQ, replay.
|
||||
|
||||
Нужен запущенный стенд из compose.yaml с FAULT_INJECTION=1 (по умолчанию на учебном стенде).
|
||||
Тест управляет только своими синтетическими данными и сервисами через `docker compose stop|start|restart`,
|
||||
volumes не удаляет. Сбои внедряются файлами в volume faults (faults.py), SQL — только чтение.
|
||||
|
||||
python student-tests/test_jobs.py [сценарий ...] # без аргументов — все по порядку
|
||||
|
||||
Сценарии: variants limits worker-down broker-down outbox-crash crash-after-put crash-after-commit
|
||||
lease retry exhausted-replay permanent concurrency dlq
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
from common import (call, check, compose, compose_output, new_chat, new_user, post_message, psql, run_tests,
|
||||
send, sql_value, wait_ready)
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
PROBE = (HERE / "worker_probe.py").read_text(encoding="utf-8")
|
||||
FINAL_KEYS = ["v1/crop.jpg", "v1/optimized.webp", "v1/original", "v1/thumbnail.jpg"]
|
||||
LEASE = 15 # JOB_LEASE_SECONDS стенда
|
||||
TIMEOUT = 60 # JOB_TIMEOUT_SECONDS стенда
|
||||
MAX_ATTEMPTS = 5 # JOB_MAX_ATTEMPTS стенда
|
||||
|
||||
STATE = {}
|
||||
|
||||
|
||||
# ---------- инфраструктура ----------
|
||||
|
||||
def in_container(service, code, *args):
|
||||
"""python - <args> в контейнере service, код через stdin. Последняя строка stdout — JSON.
|
||||
Если service остановлен (сценарии с выключенным worker) — в одноразовом контейнере того же сервиса."""
|
||||
import subprocess
|
||||
from common import ROOT
|
||||
running = subprocess.run(["docker", "compose", "ps", "--status", "running", "-q", service], cwd=ROOT,
|
||||
capture_output=True, check=False).stdout.strip()
|
||||
launch = (["exec", "-T", service, "python"] if running
|
||||
else ["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", service])
|
||||
result = subprocess.run(["docker", "compose", *launch, "-", *map(str, args)], cwd=ROOT,
|
||||
input=code.encode("utf-8"), capture_output=True, check=False)
|
||||
check(result.returncode == 0, f"{service}: {result.stderr.decode('utf-8', 'replace')[-500:]}")
|
||||
return json.loads(result.stdout.decode("utf-8").strip().splitlines()[-1])
|
||||
|
||||
|
||||
def probe(*args):
|
||||
return in_container("worker", PROBE, *args)
|
||||
|
||||
|
||||
def ops(*args):
|
||||
import subprocess
|
||||
from common import ROOT
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "dispatcher", "python", "ops.py", *map(str, args)],
|
||||
cwd=ROOT, capture_output=True, check=False)
|
||||
check(result.returncode == 0, f"ops {args[0]}: {result.stderr.decode('utf-8', 'replace')[-400:]}")
|
||||
return json.loads(result.stdout.decode("utf-8"))
|
||||
|
||||
|
||||
def fault(point, times=1):
|
||||
"""Взвести точку сбоя: times файлов /faults/<point>.<n> (каждое срабатывание удаляет один файл)."""
|
||||
code = ("import pathlib, sys, time\n"
|
||||
"for n in range(int(sys.argv[2])):\n"
|
||||
" pathlib.Path('/faults', f'{sys.argv[1]}.{time.time_ns()}_{n}').touch()\n"
|
||||
"print('{}')\n")
|
||||
in_container("worker", code, point, times)
|
||||
|
||||
|
||||
def clear_faults():
|
||||
code = "import pathlib\nfor p in pathlib.Path('/faults').glob('*'):\n p.unlink()\nprint('{}')\n"
|
||||
in_container("worker", code)
|
||||
|
||||
|
||||
def image(kind):
|
||||
return base64.b64decode(probe("make", kind)["b64"])
|
||||
|
||||
|
||||
def user_and_chat():
|
||||
if "alice" not in STATE:
|
||||
STATE["alice"] = new_user("alice")
|
||||
STATE["bob"] = new_user("bob")
|
||||
STATE["chat"] = new_chat(STATE["alice"], STATE["bob"], title="Lab5 jobs")
|
||||
return STATE["alice"], STATE["bob"], STATE["chat"]
|
||||
|
||||
|
||||
def upload(data, content_type="image/png", filename="probe.png", expected=202):
|
||||
alice, _bob, chat = user_and_chat()
|
||||
query = "?filename=" + urllib.parse.quote(filename, safe="")
|
||||
att = call("POST", f"/api/v1/chats/{chat['id']}/attachments{query}", expected, raw=data, token=alice["token"],
|
||||
headers={"Content-Type": content_type}, timeout=60).json
|
||||
if expected == 202:
|
||||
check(att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None,
|
||||
f"202 must be a queued snapshot, got {att['status']}")
|
||||
return att
|
||||
|
||||
|
||||
def get(att_id, user=None):
|
||||
user = user or STATE["alice"]
|
||||
return call("GET", f"/api/v1/attachments/{att_id}", 200, token=user["token"]).json
|
||||
|
||||
|
||||
def wait_status(att_id, statuses, seconds=60):
|
||||
statuses = (statuses,) if isinstance(statuses, str) else statuses
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
att = get(att_id)
|
||||
if att["status"] in statuses:
|
||||
return att
|
||||
check(time.monotonic() < deadline, f"{att_id[:8]}: still {att['status']} after {seconds} s")
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def content(att_id, variant="original", expected=200):
|
||||
return call("GET", f"/api/v1/attachments/{att_id}/content?variant={variant}", expected,
|
||||
token=STATE["bob"]["token"])
|
||||
|
||||
|
||||
def job(att_id):
|
||||
rows = sql_value(f"SELECT job_id || '|' || status || '|' || attempt || '|' || coalesce(error_code, '-') "
|
||||
f"FROM attachment_jobs WHERE attachment_id = '{att_id}'")
|
||||
check(rows and "\n" not in rows, f"expected exactly one job for {att_id}")
|
||||
job_id, status, attempt, error = rows.split("|")
|
||||
return {"job_id": job_id, "status": status, "attempt": int(attempt), "error_code": error}
|
||||
|
||||
|
||||
def events(job_id):
|
||||
out = sql_value(f"SELECT attempt || ':' || event || ':' || coalesce(detail, '') FROM job_events "
|
||||
f"WHERE job_id = '{job_id}' ORDER BY id")
|
||||
return out.splitlines() if out else []
|
||||
|
||||
|
||||
def names(evs):
|
||||
return [e.split(":")[1] for e in evs]
|
||||
|
||||
|
||||
def assert_one_result(att_id, label=""):
|
||||
"""Инвариант идемпотентности: ровно один набор вариантов и ровно 4 объекта под конечным prefix."""
|
||||
info = probe("inspect", att_id)
|
||||
check(info["state"] == "ready", f"{label}: not ready in DB")
|
||||
check(info["variant_rows"] == 3, f"{label}: {info['variant_rows']} variant rows, expected 3")
|
||||
check(info["final_keys"] == FINAL_KEYS, f"{label}: final objects {info['final_keys']}")
|
||||
check(info["original_sha_ok"] and info["original_size_ok"], f"{label}: original differs from upload")
|
||||
check(all(v["sha_ok"] and v["meta_size_ok"] for v in info["variants"].values()), f"{label}: variant mismatch")
|
||||
return info
|
||||
|
||||
|
||||
def outbox_rows(job_id):
|
||||
out = sql_value(f"SELECT attempt || ':' || (published_at IS NOT NULL) FROM outbox WHERE job_id = '{job_id}' "
|
||||
f"ORDER BY id")
|
||||
return out.splitlines() if out else []
|
||||
|
||||
|
||||
def queue_depth():
|
||||
out = compose_output("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "list_queues", "-p", "messenger",
|
||||
"name", "messages", "messages_unacknowledged")
|
||||
depth = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) == 3 and parts[1].isdigit():
|
||||
depth[parts[0]] = (int(parts[1]), int(parts[2]))
|
||||
return depth
|
||||
|
||||
|
||||
def log(text):
|
||||
print(text, flush=True)
|
||||
|
||||
|
||||
# ---------- сценарии ----------
|
||||
|
||||
def test_variants():
|
||||
"""thumbnail/crop/optimized по контракту, EXIF orientation, alpha -> белый, без увеличения, без метаданных."""
|
||||
alice, bob, chat = user_and_chat()
|
||||
cases = {
|
||||
"thumb320": ("image/png", {"thumbnail": [256, 160], "crop": [128, 128], "optimized": [320, 200]}),
|
||||
"exif6": ("image/jpeg", {"thumbnail": [192, 256], "crop": [128, 128], "optimized": [300, 400]}),
|
||||
"alpha": ("image/png", {"thumbnail": [256, 170], "crop": [128, 128], "optimized": [300, 200]}),
|
||||
"tiny": ("image/png", {"thumbnail": [40, 30], "crop": [128, 128], "optimized": [40, 30]}),
|
||||
"large": ("image/jpeg", {"thumbnail": [256, 170], "crop": [128, 128], "optimized": [1280, 853]}),
|
||||
"strip": ("image/png", {"thumbnail": [256, 1], "crop": [128, 128], "optimized": [1280, 1]}),
|
||||
}
|
||||
for kind, (ctype, sizes) in cases.items():
|
||||
data = image(kind)
|
||||
att = upload(data, ctype, f"{kind}.{'jpg' if ctype == 'image/jpeg' else 'png'}")
|
||||
ready = wait_status(att["id"], "ready")
|
||||
meta = {v["name"]: v for v in ready["variants"]}
|
||||
check(set(meta) == {"thumbnail", "crop", "optimized"}, f"{kind}: variants {sorted(meta)}")
|
||||
for name, size in sizes.items():
|
||||
check([meta[name]["width"], meta[name]["height"]] == size,
|
||||
f"{kind}/{name}: {meta[name]['width']}x{meta[name]['height']}, expected {size}")
|
||||
check(meta["thumbnail"]["content_type"] == "image/jpeg" and meta["crop"]["content_type"] == "image/jpeg"
|
||||
and meta["optimized"]["content_type"] == "image/webp", f"{kind}: wrong variant content types")
|
||||
original = content(att["id"])
|
||||
check(original.data == data, f"{kind}: original is not byte-identical")
|
||||
for name in ("thumbnail", "crop", "optimized"):
|
||||
reply = content(att["id"], name)
|
||||
check(reply.headers["content-type"] == meta[name]["content_type"], f"{kind}/{name}: Content-Type")
|
||||
info = assert_one_result(att["id"], kind)
|
||||
for name, v in info["variants"].items():
|
||||
check(v["exif_tags"] == 0 and not v["has_xmp"], f"{kind}/{name}: metadata not stripped")
|
||||
if kind == "exif6":
|
||||
top = info["variants"]["thumbnail"]["pixel_top_center"]
|
||||
check(top[0] > 200 and top[1] < 60, f"exif6: orientation not applied, top pixel {top}")
|
||||
if kind == "alpha":
|
||||
left = info["variants"]["thumbnail"]["pixel_left_center"]
|
||||
right = info["variants"]["thumbnail"]["pixel_right_center"]
|
||||
check(left[:3] == [255, 255, 255] and right[2] > 200, f"alpha: not composited on white {left} {right}")
|
||||
check(info["variants"]["optimized"]["mode"] == "RGBA", "alpha: optimized WebP lost transparency")
|
||||
log(f"{kind}: " + ", ".join(f"{n} {s[0]}x{s[1]}" for n, s in sizes.items())
|
||||
+ f"; original byte-identical; EXIF/XMP in variants: 0; S3 keys {info['final_keys']}")
|
||||
# Отсутствующий вариант у ready -> 404 (нет такого имени в контракте -> 400), queued -> 409 проверяется ниже.
|
||||
content(att["id"], "unknown", expected=400)
|
||||
log("unknown variant name -> 400; variants carry their own size/sha256, original fields describe the upload")
|
||||
|
||||
|
||||
def test_limits():
|
||||
"""Лимиты: bytes и пиксели на API; память/пиксели/время процесса обработки на worker."""
|
||||
alice, _bob, chat = user_and_chat()
|
||||
big = b"\x89PNG\r\n\x1a\n" + b"\0" * (10 * 1024 * 1024)
|
||||
call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=big.png", 413, raw=big, token=alice["token"],
|
||||
headers={"Content-Type": "image/png"}, timeout=60)
|
||||
log("10 MiB + 8 bytes -> 413 before any job is created")
|
||||
report = probe("imaging-limits")
|
||||
at, over = report["at_limit_40mpx"], report["over_limit_max_10mpx"]
|
||||
check(at["exit_code"] == 0, f"40 Mpx PNG at the limit must be processed, exit {at['exit_code']}")
|
||||
check(over["exit_code"] == 4, f"worker-side pixel limit must reject (exit 4), got {over['exit_code']}")
|
||||
check(at["peak_rss_mib_max_children"] < report["memory_limit_mib"],
|
||||
f"peak RSS {at['peak_rss_mib_max_children']} MiB exceeds RLIMIT_AS {report['memory_limit_mib']} MiB")
|
||||
log(f"imaging.py on 8000x5000 PNG: exit 0, peak RSS {at['peak_rss_mib_max_children']} MiB "
|
||||
f"(RLIMIT_AS {report['memory_limit_mib']} MiB); same file with MAX_IMAGE_PIXELS=10M -> exit 4 (image_too_large)")
|
||||
# Память: процесс обработки упирается в RLIMIT_AS -> MemoryError -> постоянная ошибка resource_limit.
|
||||
fault("imaging_oom")
|
||||
att = upload(image("thumb320"), filename="oom.png")
|
||||
failed = wait_status(att["id"], ("failed", "ready"), 60)
|
||||
check(failed["status"] == "failed" and failed["error_code"] == "resource_limit",
|
||||
f"oom: expected failed/resource_limit, got {failed['status']}/{failed['error_code']}")
|
||||
j = job(att["id"])
|
||||
check(j["attempt"] == 1, "resource_limit is permanent: no retries expected")
|
||||
log(f"memory bomb in the imaging process -> failed/resource_limit after attempt 1; worker itself survived")
|
||||
STATE["oom_job"] = j["job_id"]
|
||||
# Время: зависший процесс обработки убивается по JOB_TIMEOUT_SECONDS -> временная ошибка -> retry -> ready.
|
||||
fault("imaging_hang")
|
||||
att = upload(image("thumb320"), filename="hang.png")
|
||||
started = time.monotonic()
|
||||
ready = wait_status(att["id"], "ready", TIMEOUT + 40)
|
||||
j = job(att["id"])
|
||||
evs = events(j["job_id"])
|
||||
check("lease_expired" not in names(evs), f"a long-running (alive) attempt must keep its lease: {evs}")
|
||||
check(any("processing_timeout" in e for e in evs) and j["attempt"] == 2, f"timeout not handled as retry: {evs}")
|
||||
log(f"imaging hang -> killed after {TIMEOUT} s (processing_timeout, temporary), lease renewed meanwhile "
|
||||
f"(no lease_expired), attempt 2 ready after {time.monotonic() - started:.0f} s")
|
||||
|
||||
|
||||
def test_worker_down():
|
||||
"""Защита п.2-3: worker остановлен -> 202 -> сообщение с вложением -> рестарт API+broker -> worker -> ready."""
|
||||
alice, bob, chat = user_and_chat()
|
||||
compose("stop", "worker")
|
||||
log("worker stopped")
|
||||
data = image("thumb320")
|
||||
att = upload(data, filename="offline.png")
|
||||
log(f"upload while worker is down -> 202 queued, attachment {att['id']}")
|
||||
j = job(att["id"])
|
||||
source_key = sql_value(f"SELECT source_key FROM attachments WHERE id = '{att['id']}'")
|
||||
check(source_key.startswith("staging/"), "source must be in the durable staging prefix")
|
||||
check(probe("exists", source_key)["exists"], "staging object must exist before 202")
|
||||
msg = post_message(alice, chat["id"], "photo while worker is down", [att["id"]]).json
|
||||
check(msg["attachment_ids"] == [att["id"]], "message must reference the queued attachment")
|
||||
content(att["id"], expected=409)
|
||||
content(att["id"], "thumbnail", expected=409)
|
||||
send(bob, chat["id"], "other messages keep working")
|
||||
deadline = time.monotonic() + 10
|
||||
while outbox_rows(j["job_id"]) != ["1:true"]:
|
||||
check(time.monotonic() < deadline, "dispatcher did not publish the job")
|
||||
time.sleep(0.2)
|
||||
deadline = time.monotonic() + 15 # счётчики quorum-очереди в rabbitmqctl обновляются раз в несколько секунд
|
||||
while (queue_depth().get("attachments.process.v1") or (0, 0))[0] < 1:
|
||||
check(time.monotonic() < deadline, "published message is not visible in the queue")
|
||||
time.sleep(0.5)
|
||||
depth = queue_depth().get("attachments.process.v1")
|
||||
log(f"message with attachment 201, content 409, other messages 201; job {j['job_id']} published, "
|
||||
f"queue messages/unacked = {depth}")
|
||||
compose("restart", "rabbitmq")
|
||||
compose("restart", "api")
|
||||
wait_ready()
|
||||
depth_after = queue_depth().get("attachments.process.v1")
|
||||
check(depth_after and depth_after[0] >= 1, f"message lost after broker restart: {depth_after}")
|
||||
check(get(att["id"])["status"] == "queued", "job must still be queued after restarts")
|
||||
log(f"rabbitmq and api restarted with volumes; queue still holds {depth_after[0]} message(s); status queued")
|
||||
compose("start", "worker")
|
||||
ready = wait_status(att["id"], "ready", 60)
|
||||
j2 = job(att["id"])
|
||||
check(j2["job_id"] == j["job_id"] and j2["status"] == "ready", "same job_id must finish")
|
||||
thumb = content(att["id"], "thumbnail")
|
||||
check(len(thumb.data) == {v["name"]: v for v in ready["variants"]}["thumbnail"]["size_bytes"], "thumbnail size")
|
||||
info = assert_one_result(att["id"], "worker-down")
|
||||
check(not info["staging_present"] and not probe("exists", source_key)["exists"],
|
||||
"staging must be cleaned after the safe commit")
|
||||
log(f"worker started -> same job {j['job_id']} ready, thumbnail downloadable; staging object deleted")
|
||||
|
||||
|
||||
def test_broker_down():
|
||||
"""Брокер недоступен: API принимает (outbox), dispatcher копит и публикует после восстановления."""
|
||||
compose("stop", "rabbitmq")
|
||||
log("rabbitmq stopped")
|
||||
att = upload(image("thumb320"), filename="no-broker.png")
|
||||
call("GET", "/health/ready", 200)
|
||||
j = job(att["id"])
|
||||
time.sleep(3)
|
||||
check(outbox_rows(j["job_id"]) == ["1:false"], "outbox row must wait while the broker is down")
|
||||
log(f"upload -> 202 and /health/ready 200 without broker; outbox row pending for job {j['job_id']}")
|
||||
compose("start", "rabbitmq")
|
||||
wait_status(att["id"], "ready", 90)
|
||||
check(outbox_rows(j["job_id"]) == ["1:true"], "outbox row must be published after recovery")
|
||||
assert_one_result(att["id"], "broker-down")
|
||||
log("rabbitmq started -> dispatcher published the pending row -> ready")
|
||||
|
||||
|
||||
def test_outbox_crash():
|
||||
"""Разрыв COMMIT/publish: dispatcher падает после COMMIT задания до publish и после confirm до отметки."""
|
||||
fault("dispatcher_crash_before_publish")
|
||||
att = upload(image("thumb320"), filename="crash-before-publish.png")
|
||||
ready = wait_status(att["id"], "ready", 60)
|
||||
j = job(att["id"])
|
||||
logs = compose_output("logs", "--tail", "400", "dispatcher")
|
||||
check("FAULT INJECTION: dispatcher_crash_before_publish" in logs, "fault did not fire")
|
||||
check(outbox_rows(j["job_id"]) == ["1:true"] and j["attempt"] == 1, "outbox must publish exactly the same job")
|
||||
assert_one_result(att["id"], "crash-before-publish")
|
||||
log(f"dispatcher killed between COMMIT and publish; restarted by policy, outbox re-published -> job "
|
||||
f"{j['job_id']} ready, attempt 1, no manual action")
|
||||
fault("dispatcher_crash_after_confirm")
|
||||
att = upload(image("thumb320"), filename="crash-after-confirm.png")
|
||||
wait_status(att["id"], "ready", 60)
|
||||
j = job(att["id"])
|
||||
deadline = time.monotonic() + 20
|
||||
while "duplicate_ignored" not in names(events(j["job_id"])):
|
||||
check(time.monotonic() < deadline, f"duplicate delivery not observed: {events(j['job_id'])}")
|
||||
time.sleep(0.3)
|
||||
assert_one_result(att["id"], "crash-after-confirm")
|
||||
log(f"dispatcher killed after publisher confirm, before marking outbox -> message published twice; "
|
||||
f"worker: {names(events(j['job_id']))} -> one result set")
|
||||
|
||||
|
||||
def test_crash_after_put():
|
||||
"""Worker падает после записи объектов в S3, до COMMIT/ack: повтор завершает тот же результат."""
|
||||
fault("worker_crash_after_put")
|
||||
att = upload(image("thumb320"), filename="crash-after-put.png")
|
||||
wait_status(att["id"], "ready", LEASE + 40)
|
||||
j = job(att["id"])
|
||||
evs = events(j["job_id"])
|
||||
check(names(evs).count("claimed") == 2 and "lease_expired" in names(evs), f"unexpected history {evs}")
|
||||
assert_one_result(att["id"], "crash-after-put")
|
||||
log(f"worker killed after S3 PUT (before COMMIT and ack): redelivery saw a live lease (no-op), lease expired "
|
||||
f"after {LEASE} s, attempt {j['attempt']} rewrote the same keys -> one set; events {names(evs)}")
|
||||
|
||||
|
||||
def test_crash_after_commit():
|
||||
"""Worker падает после COMMIT результата, до ack: повторная доставка ready-задачи — no-op с ack."""
|
||||
fault("worker_crash_after_commit")
|
||||
att = upload(image("thumb320"), filename="crash-after-commit.png")
|
||||
wait_status(att["id"], "ready", 30)
|
||||
j = job(att["id"])
|
||||
deadline = time.monotonic() + 30
|
||||
while "duplicate_ignored" not in names(events(j["job_id"])):
|
||||
check(time.monotonic() < deadline, f"redelivery not observed: {events(j['job_id'])}")
|
||||
time.sleep(0.3)
|
||||
evs = events(j["job_id"])
|
||||
check(names(evs).count("ready") == 1 and j["attempt"] == 1, f"ready must be recorded once: {evs}")
|
||||
assert_one_result(att["id"], "crash-after-commit")
|
||||
deadline = time.monotonic() + 20 # счётчики quorum-очереди обновляются с задержкой
|
||||
while queue_depth().get("attachments.process.v1") != (0, 0):
|
||||
check(time.monotonic() < deadline, f"message left in the queue: {queue_depth()}")
|
||||
time.sleep(0.5)
|
||||
log(f"worker killed after COMMIT, before ack: broker redelivered, worker acked as no-op ({evs[-1]}); "
|
||||
f"queue empty (0 ready, 0 unacked)")
|
||||
STATE["staging_check"] = att["id"]
|
||||
|
||||
|
||||
def test_lease():
|
||||
"""Зависший worker: аренда не продлевается -> dispatcher возвращает job -> другой поток завершает;
|
||||
результат зависшего отклоняется fencing-токеном, ready не откатывается."""
|
||||
fault("worker_freeze")
|
||||
att = upload(image("thumb320"), filename="frozen.png")
|
||||
started = time.monotonic()
|
||||
wait_status(att["id"], "ready", LEASE + 40)
|
||||
took = time.monotonic() - started
|
||||
j = job(att["id"])
|
||||
deadline = time.monotonic() + 3 * LEASE + 20
|
||||
while "stale_result_rejected" not in names(events(j["job_id"])):
|
||||
check(time.monotonic() < deadline, f"stale result of the frozen attempt not seen: {events(j['job_id'])}")
|
||||
time.sleep(0.5)
|
||||
evs = events(j["job_id"])
|
||||
check(get(att["id"])["status"] == "ready", "late result must not roll ready back")
|
||||
check(names(evs).count("ready") == 1, f"exactly one ready: {evs}")
|
||||
assert_one_result(att["id"], "lease")
|
||||
log(f"frozen attempt 1 stopped renewing; lease expired, recovered by dispatcher, attempt 2 ready after "
|
||||
f"{took:.0f} s; frozen attempt woke up -> stale_result_rejected; events {names(evs)}")
|
||||
|
||||
|
||||
def test_retry():
|
||||
"""Временные ошибки S3: backoff с jitter, затем ready; задержки видны в журнале."""
|
||||
fault("worker_s3_error", 2)
|
||||
att = upload(image("thumb320"), filename="retry.png")
|
||||
wait_status(att["id"], "ready", 60)
|
||||
j = job(att["id"])
|
||||
evs = [e for e in events(j["job_id"]) if ":retry_scheduled:" in e]
|
||||
check(len(evs) == 2 and j["attempt"] == 3, f"expected 2 retries, got {evs}")
|
||||
delays = [float(e.split("delay=")[1].rstrip("s")) for e in evs]
|
||||
check(1.0 <= delays[0] <= 2.0 and 2.0 <= delays[1] <= 4.0, f"backoff out of range: {delays}")
|
||||
assert_one_result(att["id"], "retry")
|
||||
log(f"2 x storage_unavailable -> retries after {delays[0]:.2f} s and {delays[1]:.2f} s (equal jitter: "
|
||||
f"1..2 s, 2..4 s), attempt 3 ready")
|
||||
|
||||
|
||||
def test_exhausted_replay():
|
||||
"""Исчерпание попыток -> failed/retry_exhausted, реестр failed, явный replay; replay ready — отказ."""
|
||||
alice, _bob, chat = user_and_chat()
|
||||
fault("worker_s3_error", MAX_ATTEMPTS)
|
||||
att = upload(image("thumb320"), filename="exhausted.png")
|
||||
failed = wait_status(att["id"], ("failed", "ready"), 120)
|
||||
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted",
|
||||
f"expected failed/retry_exhausted, got {failed['status']}/{failed['error_code']}")
|
||||
j = job(att["id"])
|
||||
check(j["attempt"] == MAX_ATTEMPTS, f"attempts {j['attempt']}")
|
||||
content(att["id"], expected=409)
|
||||
post_message(alice, chat["id"], "", [att["id"]], expected=409)
|
||||
registry = {row["job_id"]: row for row in ops("failed")}
|
||||
check(registry.get(j["job_id"], {}).get("replayable") is True, "failed job must be in the registry")
|
||||
log(f"{MAX_ATTEMPTS} temporary errors -> failed/retry_exhausted (public error_code), content 409, "
|
||||
f"attach 409, listed by ops.py failed (replayable)")
|
||||
replay = ops("replay", j["job_id"], "--reason", "s3 recovered")
|
||||
check("replayed" in replay, f"replay refused: {replay}")
|
||||
wait_status(att["id"], "ready", 60)
|
||||
assert_one_result(att["id"], "replay")
|
||||
j2 = job(att["id"])
|
||||
refused = ops("replay", j["job_id"])
|
||||
check("refused" in refused, "replay of a ready job must be refused")
|
||||
again = job(att["id"])
|
||||
check(again == j2, "refused replay must not change the job")
|
||||
check(names(events(j["job_id"])).count("replayed") == 1, "audit must contain the replay once")
|
||||
log(f"ops replay -> same job_id {j['job_id']} attempt {j2['attempt']} ready; second replay refused: "
|
||||
f"\"{refused['refused']}\"")
|
||||
|
||||
|
||||
def test_permanent():
|
||||
"""Постоянная ошибка (битое изображение в worker) -> failed сразу, без повторов."""
|
||||
fault("imaging_invalid")
|
||||
att = upload(image("thumb320"), filename="invalid.png")
|
||||
failed = wait_status(att["id"], ("failed", "ready"), 30)
|
||||
check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", f"got {failed}")
|
||||
j = job(att["id"])
|
||||
check(j["attempt"] == 1 and "retry_scheduled" not in names(events(j["job_id"])), "no retries for permanent")
|
||||
log("invalid image in the worker -> failed/invalid_image at attempt 1, no retry (permanent error)")
|
||||
|
||||
|
||||
def test_concurrency():
|
||||
"""Ограниченная конкуренция: WORKER_CONCURRENCY потребителей с prefetch=1; одновременно processing <= 2."""
|
||||
out = compose_output("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "list_consumers", "-p", "messenger",
|
||||
"queue_name", "prefetch_count", "ack_required")
|
||||
lines = [line.split() for line in out.splitlines() if line.strip()]
|
||||
header = lines[0] if lines and lines[0][0] == "queue_name" else ["queue_name", "prefetch_count", "ack_required"]
|
||||
consumers = [dict(zip(header, line)) for line in lines if line[0] == "attachments.process.v1"]
|
||||
check(len(consumers) == 2 and all(c["prefetch_count"] == "1" and c["ack_required"] == "true"
|
||||
for c in consumers), f"consumers {out}")
|
||||
# Копим очередь при остановленном worker, затем запускаем: работы больше, чем потоков.
|
||||
compose("stop", "worker")
|
||||
data = image("large")
|
||||
ids = [upload(data, "image/jpeg", f"burst{n}.jpg")["id"] for n in range(8)]
|
||||
id_list = ", ".join(f"'{i}'" for i in ids)
|
||||
compose("start", "worker")
|
||||
started = time.monotonic()
|
||||
peak, samples = 0, 0
|
||||
while True:
|
||||
busy, ready = map(int, sql_value(
|
||||
f"SELECT count(*) FILTER (WHERE status = 'processing') || '|' || count(*) FILTER (WHERE status = 'ready') "
|
||||
f"FROM attachment_jobs WHERE attachment_id IN ({id_list})").split("|"))
|
||||
peak, samples = max(peak, busy), samples + 1
|
||||
if ready == len(ids):
|
||||
break
|
||||
check(time.monotonic() - started < 120, "burst not processed in 120 s")
|
||||
time.sleep(0.05)
|
||||
took = time.monotonic() - started
|
||||
check(peak == 2, f"peak {peak} jobs in processing, expected exactly WORKER_CONCURRENCY=2")
|
||||
log(f"2 consumers, prefetch_count 1, manual ack; 8 queued 3000x2000 JPEG drained in {took:.1f} s after "
|
||||
f"worker start, peak processing {peak} of 8 ({samples} samples)")
|
||||
|
||||
|
||||
def test_dlq():
|
||||
"""Невалидные сообщения и сообщения о неизвестной job -> DLQ; dlq-replay их не исполняет."""
|
||||
publish = r'''
|
||||
import json, sys, uuid
|
||||
import broker, pipeline
|
||||
p = broker.Publisher()
|
||||
p.open().basic_publish(pipeline.EXCHANGE, pipeline.ROUTING_KEY, b'{"not":"a job"}', mandatory=True)
|
||||
p.publish(pipeline.build_message(uuid.uuid4(), uuid.uuid4(), 1, 1, None))
|
||||
p.close()
|
||||
print("{}")
|
||||
'''
|
||||
before = queue_depth().get("attachments.process.v1.dlq", (0, 0))[0]
|
||||
in_container("dispatcher", publish)
|
||||
deadline = time.monotonic() + 15
|
||||
while queue_depth().get("attachments.process.v1.dlq", (0, 0))[0] < before + 2:
|
||||
check(time.monotonic() < deadline, "messages did not reach the DLQ")
|
||||
time.sleep(0.3)
|
||||
peek = ops("dlq", "--limit", "50")
|
||||
reasons = {(m["invalid"] is not None, m["dead_letter_reason"]) for m in peek}
|
||||
check((True, "rejected") in reasons, f"invalid message not in DLQ: {peek}")
|
||||
replayed = ops("dlq-replay", "--limit", "50")
|
||||
kept = [m for m in replayed if m["action"] == "keep"]
|
||||
check(len(kept) >= 2, "invalid/unknown messages must be kept, not executed")
|
||||
after = queue_depth().get("attachments.process.v1.dlq", (0, 0))[0]
|
||||
check(after >= before + 2, "dlq-replay must not drop messages it cannot handle")
|
||||
log(f"schema-invalid message and unknown job_id -> reject -> DLQ ({after} message(s)); "
|
||||
f"dlq-replay kept them: {[m['note'] for m in kept][:2]}")
|
||||
|
||||
|
||||
def test_staging_cleanup():
|
||||
"""Janitor доделывает очистку staging, если worker упал до неё (после crash-after-commit)."""
|
||||
att_id = STATE.get("staging_check")
|
||||
if not att_id:
|
||||
log("skip: run crash-after-commit first")
|
||||
return
|
||||
key = sql_value(f"SELECT coalesce(source_key, '') FROM attachments WHERE id = '{att_id}'")
|
||||
if key:
|
||||
log(f"staging source still present after the crash (worker died before cleanup); waiting 60 s window")
|
||||
time.sleep(62)
|
||||
from common import janitor
|
||||
report = janitor()
|
||||
# фоновый janitor (проход раз в JANITOR_INTERVAL_SECONDS) мог успеть первым в окне 62 с — проверяем результат
|
||||
left = sql_value(f"SELECT coalesce(source_key, '') FROM attachments WHERE id = '{att_id}'")
|
||||
check(not left, f"staging source still referenced: {report}")
|
||||
check(not probe("exists", key)["exists"], "staging object must be gone")
|
||||
by = "this pass" if report["staging_ready_deleted"] else "the background janitor pass"
|
||||
log(f"janitor removed the staging source of the ready attachment ({by}); source_key NULL, object gone")
|
||||
else:
|
||||
log("staging already cleaned by the worker")
|
||||
|
||||
|
||||
SCENARIOS = {
|
||||
"variants": test_variants, "limits": test_limits, "worker-down": test_worker_down,
|
||||
"broker-down": test_broker_down, "outbox-crash": test_outbox_crash, "crash-after-put": test_crash_after_put,
|
||||
"crash-after-commit": test_crash_after_commit, "staging": test_staging_cleanup, "lease": test_lease,
|
||||
"retry": test_retry, "exhausted-replay": test_exhausted_replay, "permanent": test_permanent,
|
||||
"concurrency": test_concurrency, "dlq": test_dlq,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
chosen = sys.argv[1:] or list(SCENARIOS)
|
||||
wait_ready()
|
||||
clear_faults()
|
||||
tests = []
|
||||
for name in chosen:
|
||||
def run(name=name):
|
||||
log(f"--- {name}: {SCENARIOS[name].__doc__.splitlines()[0]}")
|
||||
try:
|
||||
SCENARIOS[name]()
|
||||
finally:
|
||||
compose("start", "worker") # идемпотентно: стенд остаётся рабочим даже после FAIL
|
||||
compose("start", "rabbitmq")
|
||||
run.__name__ = name
|
||||
tests.append(run)
|
||||
run_tests(tests)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import PASSWORD, call, check, new_chat, new_user, read_history, run_tests, send
|
||||
|
||||
CLIENTS = 10
|
||||
MESSAGES_PER_CLIENT = 10
|
||||
REGISTRATIONS = 20
|
||||
|
||||
|
||||
def test_concurrent_messages():
|
||||
users = [new_user(f"race{i}") for i in range(CLIENTS)]
|
||||
chat = new_chat(*users, title="race")
|
||||
barrier = threading.Barrier(CLIENTS) # все клиенты стартуют одновременно
|
||||
|
||||
def client(index):
|
||||
barrier.wait()
|
||||
for n in range(MESSAGES_PER_CLIENT):
|
||||
send(users[index], chat["id"], f"client-{index}-message-{n}")
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
||||
list(pool.map(client, range(CLIENTS))) # list() пробрасывает ошибки из потоков
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
history, pages = read_history(users[0], chat["id"], limit=30)
|
||||
ids = {message["id"] for message in history}
|
||||
expected = {f"client-{i}-message-{n}" for i in range(CLIENTS) for n in range(MESSAGES_PER_CLIENT)}
|
||||
print(f"sent {CLIENTS * MESSAGES_PER_CLIENT} messages from {CLIENTS} clients in {elapsed:.2f} s; "
|
||||
f"read {len(history)} in {pages} pages, unique ids: {len(ids)}")
|
||||
check(len(history) == CLIENTS * MESSAGES_PER_CLIENT, "wrong number of messages")
|
||||
check(len(ids) == len(history), "duplicate message ids")
|
||||
check({message["text"] for message in history} == expected, "lost or changed message texts")
|
||||
print("PASS: 100 concurrent messages from 10 clients, no losses and no duplicates")
|
||||
|
||||
|
||||
def test_concurrent_registration():
|
||||
username = "race_" + uuid.uuid4().hex[:10]
|
||||
barrier = threading.Barrier(REGISTRATIONS)
|
||||
|
||||
def register(index):
|
||||
barrier.wait()
|
||||
body = {"username": username, "display_name": f"Client {index}", "password": PASSWORD}
|
||||
return call("POST", "/api/v1/users", (201, 409), body=body).status
|
||||
|
||||
with ThreadPoolExecutor(max_workers=REGISTRATIONS) as pool:
|
||||
statuses = list(pool.map(register, range(REGISTRATIONS)))
|
||||
created, conflicts = statuses.count(201), statuses.count(409)
|
||||
print(f"{REGISTRATIONS} parallel registrations of one username: 201 x{created}, 409 x{conflicts}")
|
||||
check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win")
|
||||
print("PASS: concurrent registration created exactly one user")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([test_concurrent_messages, test_concurrent_registration])
|
||||
@@ -0,0 +1,146 @@
|
||||
"""S3 вне API: bucket приватный, ключ API ограничен, порты и веб-интерфейсы SeaweedFS не открыты, bootstrap идемпотентен.
|
||||
|
||||
Нужен запущенный стенд из compose.yaml.
|
||||
"""
|
||||
import json
|
||||
import socket
|
||||
|
||||
import images
|
||||
from common import app_python, call, check, compose_output, new_chat, new_user, run_tests, sql_value, upload
|
||||
|
||||
# Анонимные запросы прямо в S3 (SeaweedFS) из сети data (из контейнера api), без подписи и без API.
|
||||
ANONYMOUS = r'''
|
||||
import json, sys, urllib.request, urllib.error
|
||||
import settings
|
||||
base = settings.S3_ENDPOINT.rstrip("/") + "/" + settings.S3_BUCKET
|
||||
def status(method, url, data=None):
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url, data=data, method=method), timeout=5) as r:
|
||||
return r.status, r.read(300).decode("utf-8", "replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read(300).decode("utf-8", "replace")
|
||||
out = {}
|
||||
for name, method, url, data in (("get_object", "GET", base + "/" + sys.argv[1], None),
|
||||
("head_object", "HEAD", base + "/" + sys.argv[1], None),
|
||||
("list_bucket", "GET", base + "?list-type=2", None),
|
||||
("put_object", "PUT", base + "/originals/anonymous-test", b"x"),
|
||||
("get_bucket_policy", "GET", base + "?policy", None)):
|
||||
code, body = status(method, url, data)
|
||||
out[name] = {"status": code, "s3_code": body.split("<Code>")[1].split("</Code>")[0] if "<Code>" in body else ""}
|
||||
print(json.dumps(out))
|
||||
'''
|
||||
|
||||
# Что разрешено и запрещено ключу API (политика infra/s3-api-policy.json).
|
||||
API_KEY_RIGHTS = r'''
|
||||
import io, json, sys, uuid
|
||||
from botocore.exceptions import ClientError
|
||||
import settings, storage
|
||||
c, bucket = storage._client, settings.S3_BUCKET
|
||||
def attempt(name, fn):
|
||||
try:
|
||||
fn(); return "allowed"
|
||||
except ClientError as e:
|
||||
return "denied: " + e.response.get("Error", {}).get("Code", "?")
|
||||
public = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": {"AWS": ["*"]},
|
||||
"Action": ["s3:GetObject"], "Resource": [f"arn:aws:s3:::{bucket}/*"]}]})
|
||||
key = "originals/" + uuid.uuid4().hex
|
||||
result = {
|
||||
"get own object": attempt("get", lambda: c.get_object(Bucket=bucket, Key=sys.argv[1])["Body"].read()),
|
||||
"put object": attempt("put", lambda: c.put_object(Bucket=bucket, Key=key, Body=b"x")),
|
||||
"delete object": attempt("delete", lambda: c.delete_object(Bucket=bucket, Key=key)),
|
||||
"list bucket": attempt("list", lambda: c.list_objects_v2(Bucket=bucket, MaxKeys=1)),
|
||||
"create another bucket": attempt("create", lambda: c.create_bucket(Bucket="intruder-" + uuid.uuid4().hex[:8])),
|
||||
"make bucket public (put policy)": attempt("policy", lambda: c.put_bucket_policy(Bucket=bucket, Policy=public)),
|
||||
"read bucket policy": attempt("get_policy", lambda: c.get_bucket_policy(Bucket=bucket)),
|
||||
"delete bucket": attempt("delete_bucket", lambda: c.delete_bucket(Bucket=bucket)),
|
||||
"change versioning": attempt("versioning", lambda: c.put_bucket_versioning(
|
||||
Bucket=bucket, VersioningConfiguration={"Status": "Enabled"})),
|
||||
}
|
||||
try: # хранилище может не отказать в ListBuckets, а показать только доступные ключу bucket
|
||||
result["visible buckets"] = sorted(b["Name"] for b in c.list_buckets().get("Buckets", []))
|
||||
except ClientError as e:
|
||||
result["visible buckets"] = "denied: " + e.response.get("Error", {}).get("Code", "?")
|
||||
print(json.dumps(result))
|
||||
'''
|
||||
|
||||
|
||||
def last_json(output):
|
||||
return json.loads(output.splitlines()[-1])
|
||||
|
||||
|
||||
def prepare():
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
chat = new_chat(alice, bob)
|
||||
att = upload(alice, chat["id"], images.sample_png()).json
|
||||
key = sql_value(f"SELECT object_key FROM attachments WHERE id = '{att['id']}'")
|
||||
return alice, bob, att, key
|
||||
|
||||
|
||||
def test_bucket_is_private():
|
||||
alice, bob, att, key = prepare()
|
||||
result = last_json(app_python(ANONYMOUS, key))
|
||||
for name, reply in result.items():
|
||||
print(f"anonymous {name} directly to S3 (from the data network) -> {reply['status']} {reply['s3_code']}")
|
||||
check(reply["status"] in (401, 403), f"anonymous {name} must be refused, got {reply['status']}")
|
||||
call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
|
||||
print("the same file through the API for a chat member -> 200")
|
||||
print("PASS: the bucket is private: no anonymous read, list, write or policy read")
|
||||
|
||||
|
||||
def test_api_key_is_limited():
|
||||
alice, bob, att, key = prepare()
|
||||
result = last_json(app_python(API_KEY_RIGHTS, key))
|
||||
allowed = {"get own object", "put object", "delete object", "list bucket"}
|
||||
visible = result.pop("visible buckets")
|
||||
print(f"API key: {'list buckets':<32} -> {visible}")
|
||||
check(isinstance(visible, str) or len(visible) <= 1, "API key must not see other buckets")
|
||||
for name, outcome in result.items():
|
||||
print(f"API key: {name:<32} -> {outcome}")
|
||||
if name in allowed:
|
||||
check(outcome == "allowed", f"API key must be allowed to {name}")
|
||||
else:
|
||||
check(outcome.startswith("denied"), f"API key must NOT be allowed to {name}")
|
||||
print("PASS: the API key can only get/put/delete/list objects of its own bucket; "
|
||||
"bucket admin, policy and other buckets are denied")
|
||||
|
||||
|
||||
def test_no_open_ports_or_console():
|
||||
config = json.loads(compose_output("config", "--format", "json"))
|
||||
s3 = config["services"]["s3"]
|
||||
check(not s3.get("ports"), "s3 must not publish ports")
|
||||
check(sorted(s3["networks"]) == ["data"], "s3 must be only in the internal data network")
|
||||
check(config["networks"]["data"].get("internal") is True, "data network must be internal")
|
||||
print("compose: s3 has no published ports, only the internal network 'data' (S3 8333, master UI 9333, "
|
||||
"filer UI 8888 are reachable only inside the stand)")
|
||||
for port in (8333, 9333, 8888, 19333):
|
||||
sock = socket.socket()
|
||||
sock.settimeout(1)
|
||||
refused = sock.connect_ex(("127.0.0.1", port)) != 0
|
||||
sock.close()
|
||||
check(refused, f"127.0.0.1:{port} is reachable from the host")
|
||||
print(f"127.0.0.1:{port} from the host -> connection refused")
|
||||
secrets = {name: sorted(s["source"] for s in svc.get("secrets", [])) for name, svc in config["services"].items()}
|
||||
for name, items in sorted(secrets.items()):
|
||||
print(f"secrets of {name}: {items or '-'}")
|
||||
for name in ("api", "janitor"):
|
||||
check(not set(secrets[name]) & {"s3_root_user", "s3_root_password", "s3_config"},
|
||||
f"{name} must not get S3 admin keys or the key config")
|
||||
check(set(secrets["api"]) >= {"s3_access_key_id", "s3_secret_access_key"}, "api needs its own S3 key")
|
||||
print("PASS: S3 is reachable only inside the stand; admin keys are only in s3 and s3-init")
|
||||
|
||||
|
||||
def test_bootstrap_is_idempotent():
|
||||
alice, bob, att, key = prepare()
|
||||
output = compose_output("run", "--rm", "--no-deps", "s3-init")
|
||||
print("\n".join("s3-init: " + line for line in output.strip().splitlines() if line.strip()))
|
||||
check("bucket is private" in output, "bootstrap did not confirm a private bucket")
|
||||
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
|
||||
check(got.data == images.sample_png(), "file changed after repeated bootstrap")
|
||||
upload(alice, att["chat_id"], images.sample_png())
|
||||
print("after the repeated bootstrap: old file downloads, new upload works")
|
||||
print("PASS: bucket/user/policy bootstrap can be repeated safely")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([test_bucket_is_private, test_api_key_is_limited, test_no_open_ports_or_console,
|
||||
test_bootstrap_is_idempotent])
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Эксперимент: >= 10 одновременных загрузок и пик памяти API-реплик.
|
||||
|
||||
Гипотеза: память реплики почти не растёт от числа и размера одновременных загрузок, потому что
|
||||
тело пишется во временный файл (в RAM не больше 256 KiB на загрузку), PNG проверяется потоково
|
||||
(куски по 64 KiB), JPEG декодируется в масштабе 1/8, а одновременно проверяется не больше
|
||||
DECODE_CONCURRENCY файлов на реплику. Наивный вариант (тело целиком в память + полное декодирование)
|
||||
при тех же 10 загрузках не помещается в лимит 512 MiB.
|
||||
|
||||
Методика: перед каждым сценарием `docker compose restart api` (сбросить пик), прогрев, затем N потоков
|
||||
одновременно (barrier) загружают файл через балансировщик. Пик RSS процесса API — VmHWM из /proc/1/status
|
||||
(high-water mark ядра, не пропускает короткие всплески); дополнительно память cgroup контейнера
|
||||
(memory.peak, если ядро даёт; иначе максимум из опроса memory.current) и опрос VmRSS раз в ~0,1 с.
|
||||
|
||||
python student-tests/upload_memory.py [--concurrency 10] [--output evidence/upload-memory.json]
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import platform
|
||||
import statistics
|
||||
import threading
|
||||
import time
|
||||
|
||||
import images
|
||||
from common import (ROOT, app_python, call, check, compose, docker, new_chat, new_user, upload, wait_attachment,
|
||||
wait_balanced, wait_ready)
|
||||
|
||||
|
||||
def proc_status(container):
|
||||
"""VmRSS и VmHWM (КиБ) процесса API (PID 1) и память cgroup контейнера (байты)."""
|
||||
script = ("cat /proc/1/status | grep -E '^Vm(RSS|HWM)'; "
|
||||
"for f in /sys/fs/cgroup/memory.peak /sys/fs/cgroup/memory.current "
|
||||
"/sys/fs/cgroup/memory/memory.max_usage_in_bytes /sys/fs/cgroup/memory/memory.usage_in_bytes; "
|
||||
"do [ -r $f ] && echo \"$f $(cat $f)\"; done; true")
|
||||
out = docker("exec", container, "sh", "-c", script)
|
||||
values = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.replace(":", " ").split()
|
||||
if parts[0] in ("VmRSS", "VmHWM"):
|
||||
values[parts[0]] = int(parts[1])
|
||||
elif parts[0].endswith(("memory.peak", "max_usage_in_bytes")):
|
||||
values["cgroup_peak"] = int(parts[1])
|
||||
elif parts[0].endswith(("memory.current", "usage_in_bytes")):
|
||||
values["cgroup_current"] = int(parts[1])
|
||||
return values
|
||||
|
||||
|
||||
class Sampler(threading.Thread):
|
||||
def __init__(self, containers):
|
||||
super().__init__(daemon=True)
|
||||
self.containers = containers
|
||||
self.stop = threading.Event()
|
||||
self.rss = {c: 0 for c in containers}
|
||||
self.cgroup = {c: 0 for c in containers}
|
||||
self.samples = 0
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
for c in self.containers:
|
||||
try:
|
||||
v = proc_status(c)
|
||||
except Exception: # noqa: BLE001 — один пропущенный замер не важен
|
||||
continue
|
||||
self.rss[c] = max(self.rss[c], v.get("VmRSS", 0))
|
||||
self.cgroup[c] = max(self.cgroup[c], v.get("cgroup_current", 0))
|
||||
self.samples += 1
|
||||
|
||||
|
||||
def api_containers():
|
||||
from common import api_containers as running
|
||||
return running()
|
||||
|
||||
|
||||
def fresh_replicas():
|
||||
compose("restart", "api")
|
||||
containers = wait_balanced(2, seconds=90)
|
||||
wait_ready()
|
||||
return containers
|
||||
|
||||
|
||||
def warm_up(user, chat):
|
||||
"""По несколько загрузок на каждую реплику: в базовую линию входят импортированный Pillow, клиенты S3 и т.п."""
|
||||
for data, ctype in ((images.sample_png(), "image/png"), (images.sample_jpeg(), "image/jpeg")) * 4:
|
||||
upload(user, chat["id"], data, ctype)
|
||||
|
||||
|
||||
def scenario(name, payloads, concurrency):
|
||||
user = new_user("mem")
|
||||
chat = new_chat(user)
|
||||
containers = fresh_replicas()
|
||||
warm_up(user, chat)
|
||||
before = {c: proc_status(c) for c in containers}
|
||||
sampler = Sampler(containers)
|
||||
sampler.start()
|
||||
barrier = threading.Barrier(concurrency)
|
||||
results = [None] * concurrency
|
||||
|
||||
def worker(i):
|
||||
data, ctype = payloads[i % len(payloads)]
|
||||
barrier.wait()
|
||||
started = time.monotonic()
|
||||
try:
|
||||
# lab5: замеряем только приём (202 queued); обработку worker'ом ждём ниже, вне замера
|
||||
reply = upload(user, chat["id"], data, ctype, f"load-{i}.png", timeout=180, wait=False)
|
||||
results[i] = (reply.status, time.monotonic() - started, reply.instance, reply.json, data)
|
||||
except AssertionError as exc:
|
||||
results[i] = (str(exc)[:120], time.monotonic() - started, None, None, data)
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(concurrency)]
|
||||
wall = time.monotonic()
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
wall = time.monotonic() - wall
|
||||
time.sleep(0.5)
|
||||
sampler.stop.set()
|
||||
sampler.join()
|
||||
after = {c: proc_status(c) for c in containers}
|
||||
|
||||
ok = [r for r in results if r[0] == 202]
|
||||
check(len(ok) == concurrency, f"{name}: not all uploads succeeded: {[r[0] for r in results if r[0] != 202]}")
|
||||
for status, _, _, att, data in ok[:3]:
|
||||
att = wait_attachment(user, att["id"], seconds=120)
|
||||
check(att["status"] == "ready", f"{name}: attachment {att['id']} is {att['status']}, expected ready")
|
||||
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=user["token"])
|
||||
check(got.data == data and att["sha256"] == hashlib.sha256(data).hexdigest(), "stored file differs")
|
||||
latencies = sorted(r[1] for r in results)
|
||||
per_replica = []
|
||||
for c in containers:
|
||||
b, a = before[c], after[c]
|
||||
per_replica.append({
|
||||
"replica": c[:12],
|
||||
"uploads_served": sum(1 for r in ok if r[2] and c.startswith(r[2])),
|
||||
"rss_before_mib": round(b["VmRSS"] / 1024, 1),
|
||||
"rss_peak_mib": round(a["VmHWM"] / 1024, 1),
|
||||
"rss_growth_mib": round((a["VmHWM"] - b["VmRSS"]) / 1024, 1),
|
||||
"rss_peak_sampled_mib": round(sampler.rss[c] / 1024, 1),
|
||||
"cgroup_peak_mib": round(a["cgroup_peak"] / 2**20, 1) if "cgroup_peak" in a else None,
|
||||
"cgroup_peak_sampled_mib": round(sampler.cgroup[c] / 2**20, 1) if sampler.cgroup[c] else None,
|
||||
})
|
||||
sizes = sorted({len(d) for d, _ in payloads})
|
||||
summary = {
|
||||
"scenario": name,
|
||||
"concurrency": concurrency,
|
||||
"file_bytes": sizes,
|
||||
"total_mib": round(sum(len(r[4]) for r in results) / 2**20, 1),
|
||||
"all_202": True,
|
||||
"wall_seconds": round(wall, 2),
|
||||
"latency_s": {"p50": round(statistics.median(latencies), 2), "max": round(latencies[-1], 2)},
|
||||
"sampler_rounds": sampler.samples,
|
||||
"replicas": per_replica,
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
return summary
|
||||
|
||||
|
||||
# Для сравнения: то же внутри контейнера api, но «наивно» — тело целиком в памяти и полное декодирование.
|
||||
NAIVE_VS_STREAMING = r'''
|
||||
import json, os, subprocess, sys
|
||||
code = r"""
|
||||
import io, os, resource, struct, sys, zlib
|
||||
sys.path.insert(0, os.getcwd())
|
||||
os.environ.setdefault("S3_ACCESS_KEY_ID", "x")
|
||||
from PIL import Image
|
||||
import uploads # импорт до замера: сравниваем только саму проверку файла
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
def chunk(k, d): return struct.pack(">I", len(d)) + k + d + struct.pack(">I", zlib.crc32(k + d))
|
||||
w, h = 8000, 5000
|
||||
comp = zlib.compressobj(6); row = b"\x00" + bytes(w * 3)
|
||||
idat = b"".join(comp.compress(row) for _ in range(h)) + comp.flush()
|
||||
data = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", idat) + chunk(b"IEND", b"")
|
||||
del idat, comp, row
|
||||
base = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||||
if sys.argv[1] == "naive":
|
||||
body = bytes(data) + bytes(9 * 1024 * 1024) # тело запроса целиком в памяти (9 MiB)
|
||||
im = Image.open(io.BytesIO(data)); im.load()
|
||||
else:
|
||||
f = io.BytesIO(data); uploads.check_png(f)
|
||||
print((resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - base) // 1024)
|
||||
"""
|
||||
out = {}
|
||||
for mode in ("naive", "streaming"):
|
||||
r = subprocess.run([sys.executable, "-c", code, mode], capture_output=True, text=True, cwd=os.getcwd())
|
||||
out[mode] = int(r.stdout.strip().splitlines()[-1]) if r.returncode == 0 else r.stderr[-200:]
|
||||
print(json.dumps(out))
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--concurrency", type=int, default=10)
|
||||
parser.add_argument("--output", default="evidence/upload-memory.json")
|
||||
args = parser.parse_args()
|
||||
check(args.concurrency >= 10, "the experiment needs at least 10 concurrent uploads")
|
||||
|
||||
print(f"client: Python {platform.python_version()} on {platform.system()} {platform.release()}")
|
||||
print("preparing synthetic images (random-noise PNG ~9.5 MiB each, 40 Mpx PNG)...")
|
||||
large = [(images.noise_png(int(9.5 * 2**20)), "image/png") for _ in range(4)]
|
||||
pixels = [(images.png(8000, 5000), "image/png")]
|
||||
jpeg = [(images.sample_jpeg(), "image/jpeg")]
|
||||
print(f"large: {len(large[0][0])} bytes; 40 Mpx: {len(pixels[0][0])} bytes")
|
||||
|
||||
runs = [
|
||||
scenario("10 x ~9.5 MiB PNG (noise)", large, args.concurrency),
|
||||
scenario("10 x 40 Mpx PNG (8000x5000 RGB)", pixels, args.concurrency),
|
||||
scenario(f"{2 * args.concurrency} mixed: large + 40 Mpx + JPEG", large + pixels + jpeg, 2 * args.concurrency),
|
||||
]
|
||||
naive = json.loads(app_python(NAIVE_VS_STREAMING).splitlines()[-1])
|
||||
print(f"one 8000x5000 RGB PNG inside the api container, extra peak RSS: naive (body in RAM + full decode) "
|
||||
f"{naive['naive']} MiB, streaming check {naive['streaming']} MiB")
|
||||
limits = docker("inspect", "-f", "{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}", api_containers()[0]).split()
|
||||
result = {"date": time.strftime("%Y-%m-%d %H:%M"), "api_limit_mib": int(limits[0]) // 2**20,
|
||||
"api_limit_cpus": int(limits[1]) / 1e9, "runs": runs, "single_file_extra_rss_mib": naive}
|
||||
(ROOT / args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
worst = max(r["rss_growth_mib"] for run in runs for r in run["replicas"])
|
||||
print(f"PASS: all uploads succeeded; largest RSS growth of one replica: {worst} MiB "
|
||||
f"(limit {result['api_limit_mib']} MiB); results in {args.output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Пробник, который выполняется ВНУТРИ контейнера worker (там Pillow, модули приложения, доступ к БД и S3).
|
||||
|
||||
Тест передаёт этот файл через stdin: `docker compose exec -T worker python - <команда> [аргументы]`.
|
||||
Секреты остаются в контейнере; наружу выходит одна строка JSON (без ключей доступа, только факты).
|
||||
|
||||
make <kind> — тестовое изображение, base64 (kind: thumb320, exif6, alpha, tiny, large, strip, big40)
|
||||
inspect <attachment_id> — метаданные из БД + декодированные объекты из S3: размеры, формат, EXIF,
|
||||
цвета контрольных точек, SHA-256, список ключей под attachments/<id>/
|
||||
exists <key> — есть ли объект в bucket
|
||||
imaging-limits — imaging.py на 40-Мп PNG: пик RSS дочернего процесса и отказ по лимиту пикселей
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import resource
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from uuid import UUID
|
||||
|
||||
from PIL import Image
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
import settings
|
||||
import storage
|
||||
|
||||
|
||||
def make(kind: str) -> bytes:
|
||||
out = io.BytesIO()
|
||||
if kind == "thumb320": # 320x200 -> thumbnail 256x160 (контракт)
|
||||
img = Image.new("RGB", (320, 200), (200, 30, 30))
|
||||
img.paste((30, 30, 200), (0, 0, 160, 200))
|
||||
img.save(out, "PNG")
|
||||
elif kind == "exif6": # JPEG 400x300 с EXIF Orientation=6 и Make/Model/GPS
|
||||
img = Image.new("RGB", (400, 300), (0, 160, 0))
|
||||
img.paste((255, 0, 0), (0, 0, 100, 300)) # левая полоса красная: после поворота на 90° по часовой — сверху
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = 6
|
||||
exif[0x010F] = "ProbeCamera"
|
||||
exif[0x0110] = "Model-X"
|
||||
exif[0x8825] = {1: "N", 2: (55.0, 45.0, 0.0)}
|
||||
img.save(out, "JPEG", quality=95, exif=exif.tobytes())
|
||||
elif kind == "alpha": # RGBA 300x200: левая половина прозрачная
|
||||
img = Image.new("RGBA", (300, 200), (0, 0, 255, 255))
|
||||
img.paste((0, 0, 0, 0), (0, 0, 150, 200))
|
||||
img.save(out, "PNG")
|
||||
elif kind == "tiny": # 40x30: без увеличения для thumbnail/optimized
|
||||
Image.new("RGB", (40, 30), (10, 120, 220)).save(out, "PNG")
|
||||
elif kind == "large": # 3000x2000 JPEG: optimized 1280x853, thumbnail 256x170
|
||||
img = Image.radial_gradient("L").resize((3000, 2000)).convert("RGB")
|
||||
img.save(out, "JPEG", quality=90)
|
||||
elif kind == "strip": # 5000x2: thumbnail 256x1 (минимум 1 px)
|
||||
Image.new("RGB", (5000, 2), (90, 90, 90)).save(out, "PNG")
|
||||
elif kind == "big40": # 8000x5000 = 40 Мп ровно на лимите
|
||||
Image.new("RGB", (8000, 5000), (120, 60, 30)).save(out, "PNG")
|
||||
else:
|
||||
raise SystemExit("unknown kind")
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def connect():
|
||||
return psycopg.connect(settings.DATABASE_URL, autocommit=True, row_factory=dict_row)
|
||||
|
||||
|
||||
def read(key: str) -> bytes:
|
||||
stream = storage.open_read(key)
|
||||
try:
|
||||
return b"".join(storage.iter_chunks(stream))
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
|
||||
def inspect(attachment_id: str) -> dict:
|
||||
with connect() as conn:
|
||||
a = conn.execute("SELECT state, object_key, source_key, pipeline_version, sha256, size_bytes "
|
||||
"FROM attachments WHERE id = %s", (UUID(attachment_id),)).fetchone()
|
||||
variants = conn.execute("SELECT name, content_type, width, height, sha256, size_bytes, object_key "
|
||||
"FROM attachment_variants WHERE attachment_id = %s ORDER BY name",
|
||||
(UUID(attachment_id),)).fetchall()
|
||||
result = {"state": a["state"], "staging_present": a["source_key"] is not None and storage.exists(a["source_key"]),
|
||||
"variant_rows": len(variants), "variants": {}}
|
||||
if a["object_key"]:
|
||||
original = read(a["object_key"])
|
||||
result["original_sha_ok"] = hashlib.sha256(original).hexdigest() == a["sha256"]
|
||||
result["original_size_ok"] = len(original) == a["size_bytes"]
|
||||
for v in variants:
|
||||
data = read(v["object_key"])
|
||||
img = Image.open(io.BytesIO(data))
|
||||
info = {"format": img.format, "size": list(img.size), "mode": img.mode,
|
||||
"meta_size_ok": [v["width"], v["height"]] == list(img.size),
|
||||
"sha_ok": hashlib.sha256(data).hexdigest() == v["sha256"] and len(data) == v["size_bytes"],
|
||||
"exif_tags": len(img.getexif()), "has_xmp": "xmp" in img.info or b"http://ns.adobe.com/xap" in data,
|
||||
"quality_hint": None}
|
||||
rgb = img.convert("RGBA")
|
||||
w, h = rgb.size
|
||||
info["pixel_top_center"] = list(rgb.getpixel((w // 2, 0)))
|
||||
info["pixel_left_center"] = list(rgb.getpixel((0, h // 2)))
|
||||
info["pixel_right_center"] = list(rgb.getpixel((w - 1, h // 2)))
|
||||
result["variants"][v["name"]] = info
|
||||
prefix = f"attachments/{attachment_id}/"
|
||||
result["final_keys"] = sorted(key[len(prefix):] for key, _m, _s in storage.list_objects(prefix))
|
||||
return result
|
||||
|
||||
|
||||
def imaging_limits() -> dict:
|
||||
"""Пик памяти процесса обработки на худшем допустимом входе и отказ при превышении лимита пикселей."""
|
||||
here = os.path.dirname(os.path.abspath(storage.__file__))
|
||||
report = {}
|
||||
with tempfile.TemporaryDirectory(dir=settings.WORKER_TMP_DIR) as tmp:
|
||||
source = os.path.join(tmp, "big.png")
|
||||
with open(source, "wb") as f:
|
||||
f.write(make("big40"))
|
||||
env = {"PATH": os.environ.get("PATH", ""), "IMAGING_MEMORY_MB": str(settings.WORKER_MEMORY_LIMIT_MB),
|
||||
"IMAGING_CPU_SECONDS": str(settings.JOB_TIMEOUT_SECONDS)}
|
||||
for label, max_pixels in (("at_limit_40mpx", 40_000_000), ("over_limit_max_10mpx", 10_000_000)):
|
||||
out = os.path.join(tmp, label)
|
||||
os.mkdir(out)
|
||||
before = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss
|
||||
proc = subprocess.run([sys.executable, os.path.join(here, "imaging.py"), source, out, "image/png",
|
||||
str(max_pixels)], env=env, capture_output=True, timeout=120)
|
||||
peak = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss
|
||||
report[label] = {"exit_code": proc.returncode, "peak_rss_mib_max_children": round(peak / 1024, 1),
|
||||
"rss_grew": peak > before}
|
||||
report["memory_limit_mib"] = settings.WORKER_MEMORY_LIMIT_MB
|
||||
report["timeout_s"] = settings.JOB_TIMEOUT_SECONDS
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
command = sys.argv[1]
|
||||
if command == "make":
|
||||
print(json.dumps({"b64": base64.b64encode(make(sys.argv[2])).decode("ascii")}))
|
||||
elif command == "inspect":
|
||||
print(json.dumps(inspect(sys.argv[2])))
|
||||
elif command == "exists":
|
||||
print(json.dumps({"exists": storage.exists(sys.argv[2])}))
|
||||
elif command == "imaging-limits":
|
||||
print(json.dumps(imaging_limits()))
|
||||
else:
|
||||
raise SystemExit("unknown command")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user