ЛР 5 — БПИ2302 — Щербацевич — на 4

This commit is contained in:
2026-11-20 19:54:38 +03:00
parent 276dbdad8a
commit 1844c21198
88 changed files with 7499 additions and 30 deletions
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Негативные проверки вложений для оценки 4: лимиты, MIME, ACL, чужой чат."""
import json
import os
import struct
import sys
import time
import uuid
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def png(width: int, height: int, extra: bytes = b"") -> bytes:
def chunk(tag: bytes, data: bytes) -> bytes:
crc = zlib.crc32(tag + data) & 0xFFFFFFFF
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc)
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + extra + chunk(b"IEND", b"")
def upload(client, actor, chat, filename, body, content_type, expected):
return client.call(
"POST",
"/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], filename),
expected,
actor=actor,
raw=body,
headers={"Content-Type": content_type},
schema="Attachment" if expected in (201, 202) else None,
)
def main():
client = Client(BASE, timeout=30)
alice, bob, eve, chat = client.bootstrap()
other = client.call(
"POST",
"/api/v1/chats",
201,
actor=eve,
body={"title": "Чужой", "member_ids": [eve["id"]]},
schema="Chat",
)["json"]
att, content = client.attachment(alice, chat)
att = client.wait_ready(alice, att)
check(content == SAMPLE, "fixture changed")
too_big = upload(client, alice, chat, "big.png", SAMPLE + b"x" * (10 * 1024 * 1024), "image/png", 413)
check(too_big["json"]["error"]["code"] == "payload_too_large", "oversize code")
spoof = upload(client, alice, chat, "spoof.png", SAMPLE, "image/jpeg", 415)
check(spoof["json"]["error"]["code"] == "unsupported_media_type", "spoofed MIME code")
broken = upload(client, alice, chat, "broken.png", b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", 415)
check(broken["json"]["error"]["code"] == "unsupported_media_type", "corrupt image code")
huge = upload(client, alice, chat, "huge.png", png(10001, 4000), "image/png", 413)
check(huge["json"]["error"]["code"] == "payload_too_large", "pixel limit code")
slash = upload(client, alice, chat, "a/b.png", SAMPLE, "image/png", 400)
check(slash["json"]["error"]["code"] == "invalid_request", "slash filename code")
missing = client.call(
"GET",
"/api/v1/attachments/%s" % uuid.uuid4(),
404,
actor=alice,
)
check(missing["json"]["error"]["code"] == "not_found", "unknown attachment")
stolen = client.call("GET", "/api/v1/attachments/%s" % att["id"], 404, actor=eve)
check(stolen["json"]["error"]["code"] == "not_found", "outsider metadata")
stolen_bytes = client.call("GET", "/api/v1/attachments/%s/content" % att["id"], 404, actor=eve)
check(stolen_bytes["json"]["error"]["code"] == "not_found", "outsider bytes")
foreign_file = upload(client, eve, other, "other.png", SAMPLE, "image/png", 202)["json"]
linked = client.call(
"POST",
"/api/v1/chats/%s/messages" % chat["id"],
404,
actor=alice,
body={"text": "", "attachment_ids": [foreign_file["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
check(linked["json"]["error"]["code"] == "not_found", "cross-chat attachment")
unknown_link = client.call(
"POST",
"/api/v1/chats/%s/messages" % chat["id"],
404,
actor=alice,
body={"text": "x", "attachment_ids": [str(uuid.uuid4())]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
check(unknown_link["json"]["error"]["code"] == "not_found", "unknown attachment_id")
ok = client.message(alice, chat, "", attachments=[att["id"]])["json"]
check(ok["attachment_ids"] == [att["id"]], "empty text with attachment")
download = client.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)
check(download["bytes"] == SAMPLE, "member download mismatch")
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "attachments.json").write_text(
json.dumps(
{
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"oversize": too_big["status"],
"spoofed_mime": spoof["status"],
"corrupt": broken["status"],
"pixels": huge["status"],
"foreign_chat": linked["status"],
"outsider": stolen["status"],
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
print("PASS: attachment validation and ACL")
if __name__ == "__main__":
run(main)
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Запуск публичного failover на Windows и POSIX с тем же scripts/stop-one.sh."""
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def script():
if os.name == "nt":
cmd = ROOT / "scripts" / "stop-one.cmd"
if cmd.is_file():
return str(cmd)
sh = ROOT / "scripts" / "stop-one.sh"
return str(sh)
def main():
env = os.environ.copy()
command = [
sys.executable,
str(ROOT / "tests" / "resilience.py"),
"--mode",
"failover",
"--action-script",
script(),
"--base-url",
env.get("BASE_URL", "http://127.0.0.1:8080"),
]
completed = subprocess.run(command, cwd=str(ROOT), env=env)
raise SystemExit(completed.returncode)
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Orphan object after S3 PUT without DB row is removed after the grace period."""
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
def compose(*args, timeout=120):
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("docker compose failed: " + (proc.stderr or proc.stdout)[-400:])
return proc.stdout
def main():
client = Client(BASE, timeout=20)
alice, _bob, _eve, chat = client.bootstrap()
att, _content = client.attachment(alice, chat)
orphan = "att/orphan-%s" % uuid.uuid4().hex
script = """
set -eu
ROOT_USER=$(cat /run/secrets/minio_root_user)
ROOT_PASS=$(cat /run/secrets/minio_root_password)
mc alias set local http://minio:9000 "$ROOT_USER" "$ROOT_PASS" >/dev/null
printf 'orphan' | mc pipe local/%s/%s
mc ls local/%s/%s >/dev/null
""" % (BUCKET, orphan, BUCKET, orphan)
compose("run", "--rm", "--no-deps", "--entrypoint", "/bin/sh", "minio-init", "-c", script)
time.sleep(2)
compose(
"run",
"--rm",
"--no-deps",
"-e",
"APP_ROLE=gc",
"-e",
"GC_ONCE=1",
"-e",
"ATTACHMENT_GC_GRACE_SECONDS=1",
"gc",
timeout=180,
)
missing = compose(
"run",
"--rm",
"--no-deps",
"--entrypoint",
"/bin/sh",
"minio-init",
"-c",
"""
set -eu
ROOT_USER=$(cat /run/secrets/minio_root_user)
ROOT_PASS=$(cat /run/secrets/minio_root_password)
mc alias set local http://minio:9000 "$ROOT_USER" "$ROOT_PASS" >/dev/null
if mc ls local/%s/%s >/dev/null 2>&1; then exit 7; fi
"""
% (BUCKET, orphan),
)
del missing
client.call("GET", "/api/v1/attachments/%s" % att["id"], actor=alice, schema="Attachment")
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "gc_orphans.json").write_text(
json.dumps(
{
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"orphan_removed": True,
"live_attachment_kept": att["id"],
"grace_seconds": 1,
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
print("PASS: orphan object removed, live attachment kept")
if __name__ == "__main__":
run(main)
+408
View File
@@ -0,0 +1,408 @@
#!/usr/bin/env python3
"""Сценарии оценки 4: варианты, остановка worker, outbox, crash до ack, lease, replay.
Стенд уже поднят. Скрипт останавливает worker, relay, rabbitmq и API и снова их запускает.
Токены и пароли не печатаются.
"""
import hashlib
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
from image_probe import jpeg_size
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
FAULTS = ROOT / "infra" / "faults.json"
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
SAFE = {
"inject_transient": False,
"crash_after_s3": False,
"relay_exit_before_publish": False,
"stall_seconds": 0,
"timeout_seconds": 0,
}
def compose(*args, timeout=180):
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("docker compose %s failed" % args[0])
return proc.stdout
def psql(sql):
proc = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
"-At",
"-c",
sql,
],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=60,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("database query failed")
return proc.stdout.strip()
def logs(service):
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", "logs", "--since", "3m", "--no-log-prefix", service],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=60,
encoding="utf-8",
errors="replace",
)
return proc.stdout
def write_faults(data):
payload = dict(SAFE)
payload.update(data)
temporary = FAULTS.with_suffix(".tmp")
temporary.write_text(json.dumps(payload), encoding="utf-8")
temporary.replace(FAULTS)
def job_id_for(attachment_id):
uuid.UUID(attachment_id)
return psql("SELECT job_id FROM attachment_jobs WHERE attachment_id = '%s'" % attachment_id)
def variant_counts(attachment_id):
uuid.UUID(attachment_id)
text = psql(
"SELECT name || ':' || count(*) FROM attachment_variants WHERE attachment_id = '%s' GROUP BY name ORDER BY name"
% attachment_id
)
counts = {}
if text:
for line in text.splitlines():
name, amount = line.split(":", 1)
counts[name] = int(amount)
return counts
def assert_single_variants(attachment_id):
counts = variant_counts(attachment_id)
check(counts == {"crop": 1, "optimized": 1, "thumbnail": 1}, "variant rows are not unique")
return counts
def wait_status(client, actor, attachment, status, seconds=90):
deadline = time.monotonic() + seconds
last = attachment
while time.monotonic() < deadline:
last = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=actor, schema="Attachment")["json"]
if last["status"] == status:
return last
if status != "failed" and last["status"] == "failed":
raise Failure("attachment failed while waiting for " + status)
time.sleep(0.4)
raise Failure("attachment stayed " + str(last.get("status")) + " while waiting for " + status)
def replay(job):
uuid.UUID(job)
proc = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"worker",
"-m",
"app.replay",
job,
],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=90,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("replay command failed")
line = [item for item in proc.stdout.splitlines() if item.startswith("{")]
check(line, "replay did not print a result")
return json.loads(line[-1])
def check_ready_image(client, actor, ready, content):
variants = {item["name"]: item for item in ready["variants"]}
check(set(variants) == {"thumbnail", "crop", "optimized"}, "ready variants mismatch")
thumb = variants["thumbnail"]
crop = variants["crop"]
optimized = variants["optimized"]
check((thumb["width"], thumb["height"]) == (256, 160), "thumbnail metadata mismatch")
check(thumb["content_type"] == "image/jpeg", "thumbnail type mismatch")
check((crop["width"], crop["height"]) == (128, 128), "crop metadata mismatch")
check(crop["content_type"] == "image/jpeg", "crop type mismatch")
check((optimized["width"], optimized["height"]) == (320, 200), "optimized metadata mismatch")
check(optimized["content_type"] == "image/webp", "optimized type mismatch")
original = client.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=actor)
check(original["bytes"] == content, "original bytes changed")
for name, meta, magic in (
("thumbnail", thumb, b"\xff\xd8"),
("crop", crop, b"\xff\xd8"),
("optimized", optimized, b"RIFF"),
):
body = client.call(
"GET",
"/api/v1/attachments/" + ready["id"] + "/content?variant=" + name,
actor=actor,
)
check(body["headers"].get_content_type() == meta["content_type"], name + " content type mismatch")
check(len(body["bytes"]) == meta["size_bytes"], name + " size mismatch")
check(hashlib.sha256(body["bytes"]).hexdigest() == meta["sha256"], name + " checksum mismatch")
check(body["bytes"][:4] == magic or body["bytes"][:2] == magic, name + " magic mismatch")
if name != "optimized":
check(jpeg_size(body["bytes"]) == (meta["width"], meta["height"]), name + " jpeg size mismatch")
check(optimized and body["bytes"][8:12] == b"WEBP", "optimized is not webp")
def main():
write_faults({})
evidence = {"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
client = Client(BASE, timeout=30)
alice, bob, _eve, chat = client.bootstrap()
try:
att, content = client.attachment(alice, chat)
check(att["status"] == "queued" and att["variants"] == [], "upload snapshot is not queued")
ready = client.wait_ready(bob, att, wait_seconds=90)
check_ready_image(client, bob, ready, content)
assert_single_variants(att["id"])
evidence["happy_path"] = {"attachment_id": att["id"], "job_id": job_id_for(att["id"]), "status": "ready"}
print("PASS: thumbnail, crop and optimized")
compose("stop", "worker")
queued, queued_bytes = client.attachment(alice, chat)
blocked = client.call("GET", "/api/v1/attachments/" + queued["id"] + "/content", 409, actor=bob)
check(blocked["json"]["error"]["code"] == "conflict", "content of a queued file is not 409")
linked = client.message(alice, chat, "", attachments=[queued["id"]])["json"]
check(linked["attachment_ids"] == [queued["id"]], "queued attachment was rejected")
client.message(bob, chat, "сообщение без вложения")
compose("restart", "api")
compose("restart", "rabbitmq")
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
break
except Failure:
time.sleep(1)
else:
raise Failure("api did not recover after restart")
still = client.call("GET", "/api/v1/attachments/" + queued["id"], actor=alice, schema="Attachment")["json"]
check(still["status"] in {"queued", "processing", "ready"}, "accepted job disappeared")
compose("start", "worker")
recovered = wait_status(client, bob, queued, "ready", 90)
downloaded = client.call("GET", "/api/v1/attachments/" + queued["id"] + "/content", actor=bob)
check(downloaded["bytes"] == queued_bytes, "recovered original changed")
assert_single_variants(queued["id"])
evidence["worker_stopped"] = {
"attachment_id": queued["id"],
"job_id": job_id_for(queued["id"]),
"content_before_worker": 409,
"status_after_recovery": recovered["status"],
"rabbit_restarted": True,
"api_restarted": True,
}
print("PASS: stopped worker, broker restart, same job reached ready")
compose("stop", "relay")
held, _held_bytes = client.attachment(alice, chat)
held_job = job_id_for(held["id"])
unpublished = psql(
"SELECT count(*) FROM job_outbox WHERE job_id = '%s' AND published_at IS NULL" % held_job
)
check(unpublished == "1", "outbox row was published while relay was stopped")
compose("start", "relay")
held_ready = wait_status(client, alice, held, "ready", 90)
evidence["outbox_gap"] = {
"attachment_id": held["id"],
"job_id": held_job,
"unpublished_before_restart": int(unpublished),
"status": held_ready["status"],
}
print("PASS: commit without publish recovered from the outbox")
write_faults({"relay_exit_before_publish": True})
time.sleep(0.8)
crashed, _bytes = client.attachment(alice, chat)
crash_job = job_id_for(crashed["id"])
seen = False
deadline = time.monotonic() + 40
while time.monotonic() < deadline:
if "injected exit after outbox commit before broker publish" in logs("relay"):
seen = True
break
time.sleep(0.5)
check(seen, "relay did not exit between commit and publish")
crash_ready = wait_status(client, alice, crashed, "ready", 90)
gap = psql("SELECT gap_injected FROM job_outbox WHERE job_id = '%s' ORDER BY created_at LIMIT 1" % crash_job)
check(gap == "t", "gap latch was not stored")
jobs = psql("SELECT count(*) FROM attachment_jobs WHERE attachment_id = '%s'" % crashed["id"])
check(jobs == "1", "crash recovery created another job")
evidence["relay_crash"] = {
"attachment_id": crashed["id"],
"job_id": crash_job,
"gap_injected": True,
"log_seen": True,
"status": crash_ready["status"],
}
write_faults({})
print("PASS: relay crash before publish recovered the same job")
write_faults({"crash_after_s3": True})
time.sleep(0.8)
side, side_bytes = client.attachment(alice, chat)
side_job = job_id_for(side["id"])
seen = False
deadline = time.monotonic() + 40
while time.monotonic() < deadline:
if "injected crash after object write before ack job_id=%s" % side_job in logs("worker"):
seen = True
break
time.sleep(0.5)
check(seen, "worker did not exit after the object write")
side_ready = wait_status(client, bob, side, "ready", 90)
side_download = client.call("GET", "/api/v1/attachments/" + side["id"] + "/content", actor=bob)
check(side_download["bytes"] == side_bytes, "redelivery changed the original")
assert_single_variants(side["id"])
evidence["crash_before_ack"] = {
"attachment_id": side["id"],
"job_id": side_job,
"log_seen": True,
"status": side_ready["status"],
"variant_rows": assert_single_variants(side["id"]),
}
write_faults({})
print("PASS: crash after object write redelivered the same result")
compose("stop", "worker", "relay")
leased, _leased_bytes = client.attachment(alice, chat)
leased_job = job_id_for(leased["id"])
psql(
"UPDATE attachment_jobs SET status = 'processing', attempt = 1, lease_owner = 'dead', "
"lease_until = now() - interval '2 minutes' WHERE job_id = '%s'" % leased_job
)
psql("UPDATE job_outbox SET published_at = now() WHERE job_id = '%s' AND published_at IS NULL" % leased_job)
psql("UPDATE attachments SET status = 'processing', error_code = NULL WHERE id = '%s'" % leased["id"])
compose("start", "relay", "worker")
lease_ready = wait_status(client, alice, leased, "ready", 90)
evidence["expired_lease"] = {
"attachment_id": leased["id"],
"job_id": leased_job,
"status": lease_ready["status"],
}
print("PASS: expired processing lease was recovered")
write_faults({"inject_transient": True})
time.sleep(0.8)
failed, _failed_bytes = client.attachment(alice, chat)
failed_job = job_id_for(failed["id"])
failed_meta = wait_status(client, alice, failed, "failed", 90)
check(failed_meta["error_code"] == "retry_exhausted", "exhausted job has no safe error code")
denied = client.call("GET", "/api/v1/attachments/" + failed["id"] + "/content", 409, actor=alice)
check(denied["json"]["error"]["code"] == "conflict", "failed content is not 409")
registry = psql("SELECT count(*) FROM job_failures WHERE job_id = '%s'" % failed_job)
check(int(registry) >= 1, "failure registry is empty")
dlq = compose("exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", "name", "messages")
check("attachment.jobs.dlq" in dlq, "dlq is missing")
write_faults({})
time.sleep(0.5)
first = replay(failed_job)
check(first["outcome"] == "enqueued", "failed job was not replayed")
replayed = wait_status(client, alice, failed, "ready", 90)
second = replay(failed_job)
check(second["outcome"] == "already_ready", "replay of a ready job was not a no-op")
assert_single_variants(failed["id"])
evidence["retry_and_replay"] = {
"attachment_id": failed["id"],
"job_id": failed_job,
"error_code": failed_meta["error_code"],
"failure_rows": int(registry),
"first_replay": first["outcome"],
"second_replay": second["outcome"],
"status": replayed["status"],
}
print("PASS: backoff exhausted to failed, replay is safe")
write_faults({"stall_seconds": 5, "timeout_seconds": 1})
time.sleep(0.8)
stalled, _stalled_bytes = client.attachment(alice, chat)
client.message(alice, chat, "API отвечает, пока worker ограничен по времени")
client.call("GET", "/health/ready", schema="Health")
stalled_meta = wait_status(client, alice, stalled, "failed", 90)
check(stalled_meta["error_code"] == "retry_exhausted", "timed out job was not exhausted")
write_faults({})
time.sleep(0.5)
stalled_job = job_id_for(stalled["id"])
outcome = replay(stalled_job)
check(outcome["outcome"] == "enqueued", "timed out job was not replayed")
stalled_ready = wait_status(client, alice, stalled, "ready", 90)
evidence["timeout"] = {
"attachment_id": stalled["id"],
"job_id": stalled_job,
"error_code": stalled_meta["error_code"],
"status": stalled_ready["status"],
"api_ready_during_stall": True,
}
print("PASS: worker time limit does not block the API")
finally:
write_faults({})
try:
compose("start", "worker", "relay", "api", "rabbitmq")
except Failure:
pass
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "grade4.json").write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: grade 4 failure scenarios")
if __name__ == "__main__":
run(main)
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Проверки lab3: разные реплики, идемпотентность через LB, гонка одного ключа."""
import json
import os
import sys
import threading
import time
import uuid
from collections import Counter
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
def history(client, actor, chat):
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
result = []
seen = set()
for _ in range(1000):
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
result.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return result
check(cursor not in seen, "cursor cycle")
seen.add(cursor)
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(cursor, safe="")
raise Failure("history pagination exceeded safety bound")
def test_instances(client, actor):
seen = []
for _ in range(40):
seen.append(client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["headers"]["X-Instance-Id"])
unique = sorted(set(seen))
check(len(unique) >= 2, "less than two API instances observed: %s" % unique)
return {"unique_instance_ids": unique, "samples": len(seen), "counts": dict(Counter(seen))}
def test_idempotency(client, alice, bob, chat):
key = uuid.uuid4().hex
first = client.message(alice, chat, "Один ключ", key=key)
replay = client.message(alice, chat, "Один ключ", key=key)
check(first["json"] == replay["json"], "idempotent replay differs")
check(first["json"]["id"] == replay["json"]["id"], "idempotent replay allocated a new id")
conflict = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
409,
actor=alice,
body={"text": "другой body"},
headers={"Idempotency-Key": key},
)
check(conflict["json"]["error"]["code"] == "conflict", "wrong body code")
missing = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
400,
actor=alice,
body={"text": "без ключа"},
)
check(missing["json"]["error"]["code"] == "invalid_request", "missing key code")
other_user = client.message(bob, chat, "Один ключ", key=key)
check(other_user["json"]["id"] != first["json"]["id"], "key leaked across users")
return first["json"]["id"]
def test_concurrent_key(client, alice, chat):
key = uuid.uuid4().hex
text = "Гонка ключа " + key
barrier = threading.Barrier(12)
results = []
errors = []
lock = threading.Lock()
def worker():
local = Client(BASE, timeout=20)
try:
barrier.wait(20)
response = local.message(alice, chat, text, key=key)
with lock:
results.append((response["status"], response["json"]["id"], response["headers"]["X-Instance-Id"]))
except Exception as exc:
with lock:
errors.append("%s: %s" % (type(exc).__name__, exc))
threads = [threading.Thread(target=worker) for _ in range(12)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
check(not errors, "concurrent idempotent POST failed: " + "; ".join(errors[:5]))
check(len(results) == 12, "expected 12 successes, got %s" % len(results))
ids = {item[1] for item in results}
instances = sorted({item[2] for item in results})
check(len(ids) == 1, "concurrent key created %s messages" % len(ids))
listed = history(client, alice, chat)
matches = [item for item in listed if item["text"] == text]
check(len(matches) == 1, "history contains %s copies of the concurrent key" % len(matches))
return {"message_id": next(iter(ids)), "instances": instances, "successes": len(results)}
def main():
client = Client(BASE, timeout=10)
alice, bob, _eve, chat = client.bootstrap()
instances = test_instances(client, alice)
message_id = test_idempotency(client, alice, bob, chat)
race = test_concurrent_key(client, alice, chat)
EVIDENCE.mkdir(exist_ok=True)
report = {
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"base_url": BASE,
"instances": instances,
"idempotent_message_id_present": bool(message_id),
"concurrent_key": race,
}
(EVIDENCE / "level3.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: level 3 replica routing and shared idempotency")
if __name__ == "__main__":
run(main)
+642
View File
@@ -0,0 +1,642 @@
#!/usr/bin/env python3
"""Проверки уровня 4: гонка, откат, EXPLAIN, TTL, logout и отказ Redis/PostgreSQL.
Стенд уже должен быть поднят: scripts/bootstrap и docker compose up.
Скрипт останавливает redis и postgres и снова их запускает.
Токены и пароли не печатаются и не пишутся в evidence.
"""
import asyncio
import base64
import json
import os
import socket
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
sys.path.insert(0, str(ROOT / "src"))
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
class Failure(AssertionError):
pass
def check(condition, message):
if not condition:
raise Failure(message)
def host_secret(name):
path = ROOT / "secrets" / name
if not path.is_file():
raise Failure("missing secrets/%s; run scripts/bootstrap first" % name)
value = path.read_text(encoding="utf-8").strip()
if not value:
raise Failure("empty secrets/%s" % name)
return value
def call(method, path, expected, body=None, token=None, authorization=None, user_id=None, timeout=15, headers=None):
extra = headers or {}
headers = {"Accept": "application/json"}
headers.update(extra)
data = None
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = "application/json"
if authorization:
headers["Authorization"] = authorization
elif token:
headers["Authorization"] = "Bearer " + token
if user_id:
headers["X-User-Id"] = user_id
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
try:
response = urllib.request.urlopen(request, timeout=timeout)
except urllib.error.HTTPError as error:
response = error
except (urllib.error.URLError, TimeoutError, OSError) as exc:
raise Failure(method + " " + path.split("?")[0] + " failed: " + type(exc).__name__) from None
with response:
status = response.status
payload = response.read()
header_id = response.headers.get("X-Request-Id")
challenge = response.headers.get("WWW-Authenticate", "")
allowed = [expected] if isinstance(expected, int) else list(expected)
check(status in allowed, "%s %s: expected %s, got %s" % (method, path.split("?")[0], allowed, status))
check(header_id and header_id.strip(), "missing X-Request-Id")
parsed = None
if payload:
try:
parsed = json.loads(payload)
except json.JSONDecodeError as exc:
raise Failure("response is not JSON") from exc
if status >= 400:
check(isinstance(parsed, dict) and set(parsed) == {"error"}, "error envelope")
error = parsed["error"]
check(set(error) == {"code", "message", "request_id"}, "error fields")
check(error["request_id"] == header_id, "request_id differs from header")
lowered = error["message"].lower()
for leaked in ("traceback", "select ", "password", "syntax", "asyncpg", "sqlalchemy"):
check(leaked not in lowered, "error message leaked internals")
if status == 204:
check(not payload, "204 must not contain a body")
return {"status": status, "json": parsed, "www": challenge}
def basic(username, password):
raw = base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode("ascii")
return "Basic " + raw
def register(label, password=None):
username = ("u_%s_%s" % (label, uuid.uuid4().hex[:10])).lower()
password = password or ("T3st-" + uuid.uuid4().hex)
created = call(
"POST",
"/api/v1/users",
201,
body={"username": username, "display_name": "Студент " + label, "password": password},
)["json"]
check("password" not in created, "password leaked")
session = call("POST", "/api/v1/auth/sessions", 201, authorization=basic(username, password))["json"]
check(session["token_type"] == "Bearer" and session["user"]["id"] == created["id"], "session shape")
check(len(session["token"]) >= 32, "token is too short")
return {"id": created["id"], "username": username, "password": password, "token": session["token"]}
def compose(*args, timeout=120):
proc = subprocess.run(
["docker", "compose", *args],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("docker compose %s failed with code %s" % (args[0], proc.returncode))
return proc.stdout
def psql(sql, timeout=60):
proc = subprocess.run(
[
"docker",
"compose",
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
"-At",
"-c",
sql,
],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("psql failed")
return proc.stdout.strip()
def redis_cli(*args):
proc = subprocess.run(
["docker", "compose", "exec", "-T", "redis", "redis-cli", *args],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=20,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("redis-cli failed")
return proc.stdout.strip()
def sql_quote(value):
text = str(value)
if "'" in text or ";" in text or "\n" in text:
raise Failure("refusing unsafe SQL literal")
return "'" + text + "'"
def free_port():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def wait_ready(timeout=90):
deadline = time.monotonic() + timeout
last = ""
while time.monotonic() < deadline:
try:
call("GET", "/health/ready", 200, timeout=5)
return
except Failure as exc:
last = str(exc)
time.sleep(0.5)
raise Failure("API did not become ready: " + last)
def test_credentials():
user = register("cred")
wrong = call(
"POST",
"/api/v1/auth/sessions",
401,
authorization=basic(user["username"], "wrong-password-value"),
)
missing = call(
"POST",
"/api/v1/auth/sessions",
401,
authorization=basic("no_such_user_zz", "wrong-password-value"),
)
check(wrong["json"]["error"]["code"] == "unauthorized", "wrong password code")
check(wrong["json"]["error"]["message"] == missing["json"]["error"]["message"], "credential errors differ")
check(wrong["www"].lower().startswith("basic "), "basic challenge")
bare = call("GET", "/api/v1/users/me", 401)
check(bare["www"].lower().startswith("bearer "), "bearer challenge")
only_header = call("GET", "/api/v1/users/me", 401, user_id=user["id"])
check(only_header["json"]["error"]["code"] == "unauthorized", "X-User-Id alone was accepted")
other = register("other")
me = call("GET", "/api/v1/users/me", 200, token=user["token"], user_id=other["id"])["json"]
check(me["id"] == user["id"], "X-User-Id overrode bearer")
basic_on_api = call("GET", "/api/v1/users/me", 401, authorization=basic(user["username"], user["password"]))
check(basic_on_api["www"].lower().startswith("bearer "), "basic accepted on business API")
print("PASS: credentials, same 401, X-User-Id ignored")
def test_unicode_password():
password = "Пароль:пример-12"
check(12 <= len(password) <= 128 and ":" in password, "fixture password")
user = register("uni", password=password)
again = call("POST", "/api/v1/auth/sessions", 201, authorization=basic(user["username"], password))["json"]
check(again["user"]["id"] == user["id"], "unicode password login failed")
print("PASS: unicode password with colon")
def test_logout():
user = register("bye")
call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
rejected = call("GET", "/api/v1/users/me", 401, token=user["token"])
check(rejected["www"].lower().startswith("bearer "), "revoked token challenge")
again = call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"])
check(again["json"]["error"]["code"] == "unauthorized", "second logout")
print("PASS: logout revokes the session")
def test_injection_and_rollback():
user = register("sql")
chat = call(
"POST",
"/api/v1/chats",
201,
token=user["token"],
body={"title": "SQL", "member_ids": [user["id"]]},
)["json"]
payload = "'; DROP TABLE messages; --"
sent = call(
"POST",
"/api/v1/chats/%s/messages" % chat["id"],
201,
token=user["token"],
body={"text": payload},
headers={"Idempotency-Key": uuid.uuid4().hex},
)["json"]
check(sent["text"] == payload, "text was rewritten")
check(psql("SELECT to_regclass('public.messages')") == "messages", "messages table disappeared")
listed = call("GET", "/api/v1/chats/%s/messages?limit=10" % chat["id"], 200, token=user["token"])["json"]
check(listed["items"][0]["text"] == payload, "stored text differs")
before = int(psql("SELECT count(*) FROM chats"))
title = "partial-" + uuid.uuid4().hex
rejected = call(
"POST",
"/api/v1/chats",
400,
token=user["token"],
body={"title": title, "member_ids": [user["id"], str(uuid.uuid4())]},
)
check(rejected["json"]["error"]["code"] == "invalid_request", "unknown member code")
after = int(psql("SELECT count(*) FROM chats"))
check(before == after, "unknown member committed a chat")
check(psql("SELECT count(*) FROM chats WHERE title = %s" % sql_quote(title)) == "0", "partial chat row exists")
print("PASS: parameterized text and unknown-member chat is not stored")
return user, chat
async def failpoint(owner_id, other_id, title):
os.environ["DATABASE_URL"] = host_secret("host_database_url")
os.environ["REDIS_URL"] = host_secret("host_cache_url")
from app.config import load_settings
from app.crud.chats import create_chat
from app.db import build_engine, build_session_factory
from app.runtime import configure
from app.sessions import build_redis
settings = load_settings()
engine = build_engine(settings)
redis = build_redis(settings)
configure(build_session_factory(engine), redis, settings)
try:
try:
await create_chat(
uuid.UUID(owner_id),
title,
(uuid.UUID(owner_id), uuid.UUID(other_id)),
fail_after_insert=True,
)
except RuntimeError as exc:
check(str(exc) == "rollback-check", "failpoint raised a different error")
else:
raise Failure("failpoint committed a chat")
finally:
await redis.aclose()
await engine.dispose()
def test_failpoint(owner_id, other_id):
title = "rollback-" + uuid.uuid4().hex
before = int(psql("SELECT count(*) FROM chats"))
try:
asyncio.run(failpoint(owner_id, other_id, title))
except Failure:
raise
except Exception as exc:
raise Failure("rollback check failed: " + type(exc).__name__) from None
after = int(psql("SELECT count(*) FROM chats"))
left = psql("SELECT count(*) FROM chats WHERE title = %s" % sql_quote(title))
check(before == after and left == "0", "chat insert survived the rollback")
print("PASS: composite chat insert rolls back before commit")
return {"chats_before": before, "chats_after": after, "title_rows": int(left)}
def test_race():
username = "race_" + uuid.uuid4().hex[:8]
password = "Race-password-" + uuid.uuid4().hex[:8]
body = {"username": username, "display_name": "Гонка", "password": password}
barrier = threading.Barrier(16)
statuses = []
lock = threading.Lock()
def worker():
try:
barrier.wait(20)
result = call("POST", "/api/v1/users", [201, 409], body=body, timeout=30)
with lock:
statuses.append(result["status"])
except Exception as exc:
with lock:
statuses.append(str(exc)[:120])
threads = [threading.Thread(target=worker) for _ in range(16)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
created = statuses.count(201)
conflict = statuses.count(409)
check(created == 1 and conflict == 15 and len(statuses) == 16, "race statuses %s" % statuses)
print("PASS: 16 parallel registrations, one 201 and fifteen 409")
return {"created": created, "conflict": conflict}
def assert_plan(name, plan):
check("ix_messages_history" in plan, name + " plan ignores ix_messages_history")
check("Seq Scan" not in plan, name + " plan seq-scans messages")
check("Index Scan" in plan or "Index Only Scan" in plan, name + " plan is not an index scan")
check("Buffers:" in plan, name + " plan has no buffer stats")
def test_explain(user):
chat = call(
"POST",
"/api/v1/chats",
201,
token=user["token"],
body={"title": "План", "member_ids": [user["id"]]},
)["json"]
chat_sql = sql_quote(chat["id"])
user_sql = sql_quote(user["id"])
psql(
"INSERT INTO messages (id, chat_id, sender_id, body, created_at) "
"SELECT gen_random_uuid(), %s, %s, 'row-' || g, "
"TIMESTAMPTZ '2026-01-01 00:00:00+00' + (g || ' microseconds')::interval "
"FROM generate_series(1, 10000) AS g" % (chat_sql, user_sql),
timeout=60,
)
count = int(psql("SELECT count(*) FROM messages WHERE chat_id = %s" % chat_sql))
check(count >= 10000, "expected at least 10000 messages, got %s" % count)
psql("ANALYZE messages")
midpoint = psql(
"SELECT to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS.US'), id::text "
"FROM messages WHERE chat_id = %s ORDER BY created_at, id OFFSET 5000 LIMIT 1" % chat_sql
)
created_at, message_id = midpoint.split("|")
late = psql(
"EXPLAIN (ANALYZE, BUFFERS) SELECT id, body FROM messages "
"WHERE chat_id = %s AND (created_at, id) > (%s::timestamptz, %s::uuid) "
"ORDER BY created_at, id LIMIT 50"
% (chat_sql, sql_quote(created_at + "+00"), sql_quote(message_id)),
timeout=60,
)
first = psql(
"EXPLAIN (ANALYZE, BUFFERS) SELECT id, body FROM messages "
"WHERE chat_id = %s ORDER BY created_at, id LIMIT 50" % chat_sql,
timeout=60,
)
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "explain_messages.txt").write_text(
"messages=%s\n\n-- first page\n%s\n\n-- page after row 5000\n%s\n" % (count, first, late),
encoding="utf-8",
)
assert_plan("first", first)
assert_plan("late", late)
print("PASS: EXPLAIN uses ix_messages_history on %s messages" % count)
return {"messages": count, "chat_id": chat["id"]}
def test_expiry_and_migrations():
from app.timeutil import parse_time
users_before = int(psql("SELECT count(*) FROM users"))
port = free_port()
env = os.environ.copy()
env["PYTHONPATH"] = str(ROOT / "src")
env["PYTHONUNBUFFERED"] = "1"
env["APP_HOST"] = "127.0.0.1"
env["APP_PORT"] = str(port)
env["APP_ENV"] = "lab"
env["DATABASE_URL"] = host_secret("host_database_url")
env["REDIS_URL"] = host_secret("host_cache_url")
env["S3_ENDPOINT"] = host_secret("host_s3_endpoint")
env["S3_ACCESS_KEY_ID"] = host_secret("s3_access_key_id")
env["S3_SECRET_ACCESS_KEY"] = host_secret("s3_secret_access_key")
env["S3_BUCKET"] = "messenger-attachments"
env["SESSION_TTL_SECONDS"] = "2"
env.pop("DATABASE_URL_FILE", None)
env.pop("CACHE_URL_FILE", None)
proc = subprocess.Popen(
[sys.executable, "-m", "app"],
cwd=str(ROOT),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
)
logs = []
def read_logs():
if proc.stdout is None:
return
for line in proc.stdout:
if "://" not in line and "password" not in line.lower():
logs.append(line)
reader = threading.Thread(target=read_logs, daemon=True)
reader.start()
base = "http://127.0.0.1:%s" % port
try:
deadline = time.monotonic() + 40
ready = False
while time.monotonic() < deadline:
if proc.poll() is not None:
raise Failure("short-ttl server exited: " + "".join(logs[-8:]))
try:
urllib.request.urlopen(base + "/health/ready", timeout=2).read()
ready = True
break
except (urllib.error.URLError, TimeoutError, OSError):
time.sleep(0.2)
check(ready, "short-ttl server did not become ready: " + "".join(logs[-8:]))
username = "ttl_" + uuid.uuid4().hex[:8]
password = "Ttl-password-" + uuid.uuid4().hex[:8]
body = json.dumps(
{"username": username, "display_name": "TTL", "password": password},
ensure_ascii=False,
).encode("utf-8")
request = urllib.request.Request(
base + "/api/v1/users",
data=body,
headers={"Content-Type": "application/json", "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=20) as response:
created = json.loads(response.read())
login = urllib.request.Request(
base + "/api/v1/auth/sessions",
data=b"",
headers={"Authorization": basic(username, password), "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(login, timeout=20) as response:
session = json.loads(response.read())
expires = parse_time(session["expires_at"])
delta = (expires - datetime.now(timezone.utc)).total_seconds()
check(0 < delta <= 3, "SESSION_TTL_SECONDS=2 was not applied")
time.sleep(delta + 1.0)
probe = urllib.request.Request(
base + "/api/v1/users/me",
headers={"Authorization": "Bearer " + session["token"], "Accept": "application/json"},
)
try:
with urllib.request.urlopen(probe, timeout=10) as response:
status = response.status
except urllib.error.HTTPError as error:
status = error.status
check(status == 401, "expired session status %s" % status)
finally:
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=8)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
reader.join(timeout=2)
users_after = int(psql("SELECT count(*) FROM users"))
versions = psql("SELECT count(*) FROM schema_migrations")
version_name = psql("SELECT version FROM schema_migrations ORDER BY version")
check(users_after == users_before + 1, "migrations duplicated or dropped users")
names = psql("SELECT version FROM schema_migrations ORDER BY version")
check(versions == "3", "expected three applied migrations, got %s" % versions)
check(
"001_initial.sql" in names and "002_idempotency.sql" in names and "003_attachments.sql" in names,
"migration set changed: %s" % names,
)
print("PASS: short TTL expires and migrations stay idempotent")
return {"users_before": users_before, "users_after": users_after, "migration": version_name}
def test_redis_persistence(user):
from app.sessions import session_key
before = int(redis_cli("PTTL", session_key(user["token"])))
check(before > 300000, "session ttl is unexpectedly short")
compose("restart", "redis")
wait_ready()
after = int(redis_cli("PTTL", session_key(user["token"])))
check(after > 0, "session disappeared after redis restart")
check(after <= before + 1000, "redis restart extended the session ttl")
me = call("GET", "/api/v1/users/me", 200, token=user["token"])["json"]
check(me["id"] == user["id"], "token did not survive redis restart")
print("PASS: Redis AOF kept the session and did not refresh TTL")
return {"pttl_before_ms": before, "pttl_after_ms": after}
def test_dependency_loss(user, chat_id):
observed = {}
compose("stop", "redis")
try:
live = call("GET", "/health/live", 200)
ready = call("GET", "/health/ready", 503)
anonymous = call("GET", "/api/v1/users/me", 401)
trusted = call("GET", "/api/v1/users/me", 503, token=user["token"])
check(live["json"]["status"] == "ok", "live failed while redis is down")
check(ready["json"]["error"]["code"] == "unavailable", "ready code")
check(anonymous["json"]["error"]["code"] == "unauthorized", "anonymous became trusted")
check(trusted["json"]["error"]["code"] == "unavailable", "unverified token was accepted")
observed["redis_down"] = {
"live": live["status"],
"ready": ready["status"],
"anonymous": anonymous["status"],
"bearer": trusted["status"],
}
finally:
compose("start", "redis")
wait_ready()
me = call("GET", "/api/v1/users/me", 200, token=user["token"])["json"]
check(me["id"] == user["id"], "token lost after redis came back")
compose("stop", "postgres")
try:
live = call("GET", "/health/live", 200)
ready = call("GET", "/health/ready", 503, timeout=20)
anonymous = call("GET", "/api/v1/users/me", 401, timeout=20)
denied = call("GET", "/api/v1/chats/" + chat_id, 503, token=user["token"], timeout=20)
check(live["json"]["status"] == "ok", "live depends on postgres")
check(ready["json"]["error"]["code"] == "unavailable", "ready while postgres is down")
check(anonymous["json"]["error"]["code"] == "unauthorized", "anonymous trusted without postgres")
check(denied["json"]["error"]["code"] == "unavailable", "request served without postgres")
observed["postgres_down"] = {
"live": live["status"],
"ready": ready["status"],
"anonymous": anonymous["status"],
"bearer": denied["status"],
}
finally:
compose("start", "postgres")
wait_ready(timeout=90)
history = call("GET", "/api/v1/chats/%s/messages?limit=5" % chat_id, 200, token=user["token"])["json"]
check(history["items"], "messages lost after postgres restart")
print("PASS: redis and postgres outages return 503 and do not trust anonymous clients")
return observed
def main():
os.environ["DATABASE_URL"] = host_secret("host_database_url")
os.environ["REDIS_URL"] = host_secret("host_cache_url")
wait_ready(timeout=60)
test_credentials()
test_unicode_password()
test_logout()
user, chat = test_injection_and_rollback()
other = register("pair")
rollback = test_failpoint(user["id"], other["id"])
race = test_race()
explain = test_explain(user)
expiry = test_expiry_and_migrations()
pttl = test_redis_persistence(user)
faults = test_dependency_loss(user, chat["id"])
remaining = int(psql("SELECT count(*) FROM messages WHERE chat_id = %s" % sql_quote(explain["chat_id"])))
check(remaining == explain["messages"], "bulk history lost after postgres restart")
EVIDENCE.mkdir(exist_ok=True)
report = {
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"base_url": BASE,
"race": race,
"rollback": rollback,
"explain": {"messages": explain["messages"]},
"expiry_and_migrations": expiry,
"redis_restart": pttl,
"dependency_loss": faults,
"messages_after_postgres_restart": remaining,
}
(EVIDENCE / "level4.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: level 4 checks")
if __name__ == "__main__":
try:
main()
except Failure as exc:
print("FAIL:", exc)
sys.exit(1)
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Тот же сценарий, что tests/resilience.py, но hook запускается так, как умеет ОС.
Linux выполняет scripts/restart.sh напрямую.
Windows не умеет CreateProcess для shell-скрипта, поэтому здесь используется Git Bash.
Скрипт тот же: перезапуск api, postgres и redis без удаления томов.
"""
import os
import subprocess
import sys
import time
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
def hook_command():
script = ROOT / "scripts" / "restart.sh"
if os.name != "nt":
return [str(script)]
bash = Path(os.environ.get("BASH", r"C:\Program Files\Git\bin\bash.exe"))
check(bash.is_file(), "Git Bash is required to launch scripts/restart.sh on Windows")
return [str(bash), "-c", "sh scripts/restart.sh"]
def history(client, actor, chat):
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
result = []
seen = set()
for _ in range(1000):
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
result.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return result
check(cursor not in seen, "cursor cycle")
seen.add(cursor)
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(cursor, safe="")
raise Failure("history pagination exceeded safety bound")
def main():
client = Client("http://127.0.0.1:8080", timeout=5)
alice, bob, _eve, chat = client.bootstrap()
original = client.message(alice, chat, "Сохранить при отказе")["json"]
print("Executing scripts/restart.sh")
completed = subprocess.run(hook_command(), cwd=str(ROOT))
check(completed.returncode == 0, "restart hook failed")
deadline = time.monotonic() + 90
while True:
try:
client.call("GET", "/health/ready", schema="Health")
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
break
except Failure:
check(time.monotonic() < deadline, "stack/session did not recover within 90 seconds")
time.sleep(0.5)
messages = history(client, bob, chat)
check(any(item == original for item in messages), "confirmed message lost or altered")
print("PASS: persistence preserved confirmed data and existing session")
if __name__ == "__main__":
run(main)
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Публичный persistence-сценарий с restart.cmd на Windows и restart.sh на POSIX."""
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def script():
if os.name == "nt":
cmd = ROOT / "scripts" / "restart.cmd"
if cmd.is_file():
return str(cmd)
return str(ROOT / "scripts" / "restart.sh")
def main():
env = os.environ.copy()
command = [
sys.executable,
str(ROOT / "tests" / "resilience.py"),
"--mode",
"persistence",
"--action-script",
script(),
"--base-url",
env.get("BASE_URL", "http://127.0.0.1:8080"),
]
completed = subprocess.run(command, cwd=str(ROOT), env=env)
raise SystemExit(completed.returncode)
if __name__ == "__main__":
main()
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Поочерёдная замена API-реплик под нагрузкой POST сообщений."""
import json
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
def compose(*args, timeout=180):
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("docker compose %s failed" % args[0])
return proc.stdout
def api_ids():
return [line.strip() for line in compose("ps", "-q", "api").splitlines() if line.strip()]
def inspect_health(container_id):
proc = subprocess.run(
["docker", "inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}", container_id],
capture_output=True,
text=True,
timeout=20,
encoding="utf-8",
errors="replace",
)
return proc.stdout.strip()
def wait_healthy(container_id, timeout=90):
deadline = time.monotonic() + timeout
last = ""
while time.monotonic() < deadline:
last = inspect_health(container_id)
if last == "healthy":
return
time.sleep(0.5)
raise Failure("replica %s did not become healthy: %s" % (container_id[:12], last))
def wait_ready(timeout=90):
client = Client(BASE, timeout=3)
deadline = time.monotonic() + timeout
last = ""
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure as exc:
last = str(exc)
time.sleep(0.4)
raise Failure("LB ready wait failed: " + last)
def main():
client = Client(BASE, timeout=8)
alice, _bob, _eve, chat = client.bootstrap()
halt = threading.Event()
latencies = []
errors = []
lock = threading.Lock()
def worker(index):
local = Client(BASE, timeout=5)
n = 0
while not halt.is_set():
started = time.monotonic()
try:
local.message(alice, chat, "rolling-%s-%s" % (index, n))
with lock:
latencies.append(time.monotonic() - started)
except Failure:
with lock:
errors.append(time.monotonic())
n += 1
threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(4)]
for thread in threads:
thread.start()
time.sleep(5)
before = api_ids()
check(len(before) >= 2, "rolling update needs >=2 replicas")
compose("build", "api")
replaced = []
for old in list(before):
current = api_ids()
compose("up", "-d", "--no-deps", "--scale", "api=%d" % (len(current) + 1), "--no-recreate", "api")
deadline = time.monotonic() + 60
new_ids = api_ids()
while len(new_ids) <= len(current) and time.monotonic() < deadline:
time.sleep(0.5)
new_ids = api_ids()
added = [item for item in new_ids if item not in current]
check(added, "new replica was not created")
wait_healthy(added[-1])
wait_ready()
subprocess.run(["docker", "stop", "-t", "5", old], capture_output=True)
subprocess.run(["docker", "rm", "-f", old], capture_output=True)
remaining = api_ids()
check(old not in remaining, "old replica %s still in service" % old[:12])
compose("up", "-d", "--no-deps", "--scale", "api=%d" % len(before), "api")
wait_ready()
replaced.append(old[:12])
time.sleep(5)
halt.set()
for thread in threads:
thread.join(timeout=10)
after = api_ids()
check(len(after) >= 2, "lost replicas after rolling update")
check(len(latencies) > 0, "no successful writes during rolling update")
report = {
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"replaced": replaced,
"replicas_before": [item[:12] for item in before],
"replicas_after": [item[:12] for item in after],
"successful_writes": len(latencies),
"failed_writes": len(errors),
"error_ratio": round(len(errors) / max(1, len(latencies) + len(errors)), 6),
}
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "rolling.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: rolling update under load")
print(json.dumps(report, ensure_ascii=False))
if __name__ == "__main__":
run(main)
+509
View File
@@ -0,0 +1,509 @@
#!/usr/bin/env python3
import base64
import json
import os
import socket
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
SECRET = "SECRET_MESSAGE_DO_NOT_LOG_7f3a"
CLIENTS = 10
PER_CLIENT = 10
class Failure(AssertionError):
pass
def check(condition, message):
if not condition:
raise Failure(message)
def free_port():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
class Server:
def __init__(self, port):
self.base = "http://127.0.0.1:%d" % port
env = os.environ.copy()
env["PYTHONPATH"] = str(ROOT / "src")
env["PYTHONUNBUFFERED"] = "1"
env["APP_HOST"] = "127.0.0.1"
env["APP_PORT"] = str(port)
env["APP_ENV"] = "lab"
env["DATABASE_URL"] = host_secret("host_database_url")
env["REDIS_URL"] = host_secret("host_cache_url")
env["S3_ENDPOINT"] = host_secret("host_s3_endpoint")
env["S3_ACCESS_KEY_ID"] = host_secret("s3_access_key_id")
env["S3_SECRET_ACCESS_KEY"] = host_secret("s3_secret_access_key")
env["S3_BUCKET"] = "messenger-attachments"
env["SESSION_TTL_SECONDS"] = "3600"
env.pop("DATABASE_URL_FILE", None)
env.pop("CACHE_URL_FILE", None)
self.logs = []
self.proc = subprocess.Popen(
[sys.executable, "-m", "app"],
cwd=str(ROOT),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
)
self._reader = threading.Thread(target=self._read, daemon=True)
self._reader.start()
def _read(self):
assert self.proc.stdout is not None
for line in self.proc.stdout:
self.logs.append(line)
def wait_ready(self):
deadline = time.monotonic() + 40
last = ""
while time.monotonic() < deadline:
if self.proc.poll() is not None:
raise Failure("server exited early:\n" + "".join(self.logs[-40:]))
try:
call(self.base, "GET", "/health/ready", 200)
return
except Failure as exc:
last = str(exc)
except (urllib.error.URLError, TimeoutError, OSError) as exc:
last = type(exc).__name__
time.sleep(0.1)
raise Failure("server did not become ready: " + last + "\n" + "".join(self.logs[-40:]))
def stop(self):
if self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=8)
except subprocess.TimeoutExpired:
self.proc.kill()
self.proc.wait(timeout=5)
self._reader.join(timeout=2)
def output(self):
return "".join(self.logs)
def host_secret(name):
path = ROOT / "secrets" / name
if not path.is_file():
raise Failure("missing secrets/%s; run scripts/bootstrap.ps1 or scripts/bootstrap.sh" % name)
value = path.read_text(encoding="utf-8").strip()
if not value:
raise Failure("empty secrets/%s" % name)
return value
def call(
base,
method,
path,
expected,
body=None,
token=None,
user_id=None,
authorization=None,
raw=None,
content_type="application/json",
timeout=20,
headers=None,
):
extra_headers = headers or {}
headers = {"Accept": "application/json"}
headers.update(extra_headers)
data = None
if raw is not None:
data = raw
headers["Content-Type"] = content_type
elif body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = content_type
if authorization:
headers["Authorization"] = authorization
elif token:
headers["Authorization"] = "Bearer " + token
if user_id:
headers["X-User-Id"] = user_id
request = urllib.request.Request(base + path, data=data, headers=headers, method=method)
try:
response = urllib.request.urlopen(request, timeout=timeout)
except urllib.error.HTTPError as error:
response = error
except (urllib.error.URLError, TimeoutError, OSError) as exc:
raise Failure(method + " " + path.split("?")[0] + " failed: " + type(exc).__name__) from None
with response:
status = response.status
payload = response.read()
header_id = response.headers.get("X-Request-Id")
instance_id = response.headers.get("X-Instance-Id")
content_type_value = response.headers.get_content_type()
allowed = [expected] if isinstance(expected, int) else list(expected)
check(status in allowed, "%s %s: expected %s, got %s" % (method, path.split("?")[0], allowed, status))
check(header_id and header_id.strip() and "," not in header_id, "missing or duplicated X-Request-Id")
check(instance_id and instance_id.strip() and "," not in instance_id, "missing or duplicated X-Instance-Id")
parsed = None
if payload:
check(content_type_value == "application/json", "expected application/json")
try:
parsed = json.loads(payload)
except json.JSONDecodeError as exc:
raise Failure("response is not JSON") from exc
if status >= 400:
check(isinstance(parsed, dict) and set(parsed) == {"error"}, "error envelope")
error = parsed["error"]
check(set(error) == {"code", "message", "request_id"}, "error fields")
check(error["request_id"] == header_id, "request_id differs from header")
check(error["message"] and "Traceback" not in error["message"], "error message leaked internals")
return {"status": status, "json": parsed, "request_id": header_id, "instance_id": instance_id}
def send_message(base, chat_id, token, text, expected=201, key=None):
headers = {"Idempotency-Key": key or uuid.uuid4().hex}
return call(
base,
"POST",
"/api/v1/chats/%s/messages" % chat_id,
expected,
token=token,
body={"text": text},
headers=headers,
)
def create_user(base, label):
username = ("u_%s_%s" % (label, uuid.uuid4().hex[:10])).lower()
password = "T3st-" + uuid.uuid4().hex
body = {"username": username, "display_name": "Студент " + label, "password": password}
created = call(base, "POST", "/api/v1/users", 201, body=body)["json"]
check(created["username"] == username, "username changed")
check("password" not in created, "password leaked in user response")
raw = base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode("ascii")
session = call(base, "POST", "/api/v1/auth/sessions", 201, authorization="Basic " + raw)["json"]
check(session["token_type"] == "Bearer", "token type")
check(session["user"]["id"] == created["id"], "session user")
check("password" not in session["user"], "password leaked in session")
created["token"] = session["token"]
created["instance_id"] = session.get("instance_id")
return created
def replace_cursor(token, fields):
padding = "=" * (-len(token) % 4)
data = json.loads(base64.urlsafe_b64decode(token + padding))
data.update(fields)
raw = json.dumps(data, separators=(",", ":"), sort_keys=True).encode("ascii")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def test_invalid_json(base):
broken = call(base, "POST", "/api/v1/users", 400, raw=b"{")
check(broken["json"]["error"]["code"] == "invalid_request", "malformed JSON code")
extra = call(
base,
"POST",
"/api/v1/users",
400,
body={"username": "abc_user", "display_name": "Имя", "extra": True},
)
check(extra["json"]["error"]["code"] == "invalid_request", "extra field code")
bad_utf = call(base, "POST", "/api/v1/users", 400, raw=b"\xff")
check(bad_utf["json"]["error"]["code"] == "invalid_request", "invalid utf-8 code")
alice = create_user(base, "utf")
chat = call(
base,
"POST",
"/api/v1/chats",
201,
token=alice["token"],
body={"title": "UTF", "member_ids": [alice["id"]]},
)["json"]
bad_message = call(
base,
"POST",
"/api/v1/chats/%s/messages" % chat["id"],
400,
token=alice["token"],
raw=b"\xff",
headers={"Idempotency-Key": uuid.uuid4().hex},
)
check(bad_message["json"]["error"]["code"] == "invalid_request", "invalid utf-8 message code")
print("PASS: invalid JSON")
def test_duplicate_username(base):
first = create_user(base, "dup")
again = call(
base,
"POST",
"/api/v1/users",
409,
body={
"username": first["username"],
"display_name": "Другой",
"password": "T3st-" + uuid.uuid4().hex,
},
)
check(again["json"]["error"]["code"] == "conflict", "duplicate username code")
me = call(base, "GET", "/api/v1/users/me", 200, token=first["token"])["json"]
check(me["id"] == first["id"], "first user disappeared after duplicate")
print("PASS: duplicate username")
def test_empty_and_foreign(base):
alice = create_user(base, "alice")
bob = create_user(base, "bob")
chat = call(
base,
"POST",
"/api/v1/chats",
201,
token=alice["token"],
body={"title": "Только Алиса", "member_ids": [alice["id"]]},
)["json"]
path = "/api/v1/chats/" + chat["id"]
for text in ("", " ", "\n\t"):
denied = call(
base,
"POST",
path + "/messages",
400,
token=alice["token"],
body={"text": text},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
check(denied["json"]["error"]["code"] == "invalid_request", "empty message code")
for method, target, payload in (
("GET", path, None),
("GET", path + "/messages", None),
("POST", path + "/messages", {"text": "чужое"}),
):
extra = {"Idempotency-Key": uuid.uuid4().hex} if method == "POST" else None
hidden = call(base, method, target, 404, token=bob["token"], body=payload, headers=extra)
check(hidden["json"]["error"]["code"] == "not_found", "foreign chat code")
check(chat["title"] not in hidden["json"]["error"]["message"], "foreign chat leaked title")
listed = call(base, "GET", "/api/v1/chats?limit=100", 200, token=bob["token"])["json"]
check(all(item["id"] != chat["id"] for item in listed["items"]), "foreign chat listed")
missing = call(base, "GET", "/api/v1/chats/" + str(uuid.uuid4()), 404, token=bob["token"])
check(missing["json"]["error"]["code"] == "not_found", "missing chat code")
bad_limit = call(base, "GET", path + "/messages?limit=0", 400, token=alice["token"])
check(bad_limit["json"]["error"]["code"] == "invalid_request", "limit=0 code")
print("PASS: empty message and foreign chat")
def test_pagination(base):
alice = create_user(base, "page")
other = create_user(base, "other")
chat = call(
base,
"POST",
"/api/v1/chats",
201,
token=alice["token"],
body={"title": "Страницы", "member_ids": [alice["id"]]},
)["json"]
other_chat = call(
base,
"POST",
"/api/v1/chats",
201,
token=other["token"],
body={"title": "Другой", "member_ids": [other["id"]]},
)["json"]
texts = ["p0", "Привет, мир 👋", "p2", "p3", "p4"]
created = []
for text in texts:
created.append(send_message(base, chat["id"], alice["token"], text)["json"])
send_message(base, other_chat["id"], other["token"], "x")
send_message(base, other_chat["id"], other["token"], "y")
collected = []
cursor = None
pages = 0
while True:
target = "/api/v1/chats/%s/messages?limit=2" % chat["id"]
if cursor:
target += "&cursor=" + quote(cursor, safe="")
page = call(base, "GET", target, 200, token=alice["token"])["json"]
pages += 1
collected.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
check(pages < 10, "pagination did not finish")
check(pages == 3, "expected 3 pages, got %d" % pages)
check(collected == created, "pagination lost, duplicated or reordered messages")
stolen = call(
base,
"GET",
"/api/v1/chats/%s/messages?limit=1" % other_chat["id"],
200,
token=other["token"],
)["json"]
check(stolen["next_cursor"], "foreign page should expose a cursor")
rejected = call(
base,
"GET",
"/api/v1/chats/%s/messages?limit=2&cursor=%s" % (chat["id"], quote(stolen["next_cursor"], safe="")),
400,
token=alice["token"],
)
check(rejected["json"]["error"]["code"] == "invalid_request", "foreign cursor code")
first_page = call(
base,
"GET",
"/api/v1/chats/%s/messages?limit=1" % chat["id"],
200,
token=alice["token"],
)["json"]
for fields in ({"t": None}, {"t": 123}, {"i": 123}):
broken = call(
base,
"GET",
"/api/v1/chats/%s/messages?limit=1&cursor=%s"
% (chat["id"], quote(replace_cursor(first_page["next_cursor"], fields), safe="")),
400,
token=alice["token"],
)
check(broken["json"]["error"]["code"] == "invalid_request", "tampered cursor code")
print("PASS: pagination")
def test_concurrency(base):
users = [create_user(base, "c%d" % index) for index in range(CLIENTS)]
chat = call(
base,
"POST",
"/api/v1/chats",
201,
token=users[0]["token"],
body={"title": "Гонка", "member_ids": [user["id"] for user in users]},
)["json"]
barrier = threading.Barrier(CLIENTS)
found = []
errors = []
lock = threading.Lock()
def worker(user):
try:
barrier.wait(10)
local = []
for index in range(PER_CLIENT):
message = send_message(
base,
chat["id"],
user["token"],
"m-%s-%d" % (user["id"][:8], index),
)["json"]
local.append(message["id"])
with lock:
found.extend(local)
except Exception as exc:
with lock:
errors.append("%s: %s" % (type(exc).__name__, exc))
threads = [threading.Thread(target=worker, args=(user,)) for user in users]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
check(not errors, "concurrent sends failed: " + "; ".join(errors[:5]))
check(len(found) == CLIENTS * PER_CLIENT, "submitted count")
check(len(set(found)) == CLIENTS * PER_CLIENT, "duplicate message ids")
listed = []
cursor = None
while True:
target = "/api/v1/chats/%s/messages?limit=40" % chat["id"]
if cursor:
target += "&cursor=" + quote(cursor, safe="")
page = call(base, "GET", target, 200, token=users[0]["token"])["json"]
listed.extend(item["id"] for item in page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
check(len(listed) == 100 and len(set(listed)) == 100, "history does not contain 100 unique messages")
check(set(listed) == set(found), "history ids differ from accepted sends")
EVIDENCE.mkdir(exist_ok=True)
report = {
"date": "2026-10-25",
"command": "python student-tests/run.py",
"clients": CLIENTS,
"messages_per_client": PER_CLIENT,
"submitted": len(found),
"unique_ids": len(set(found)),
"listed": len(listed),
"failed_requests": len(errors),
"pass": True,
}
(EVIDENCE / "concurrency.json").write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print("PASS: concurrency 100 unique messages from 10 clients")
def test_logs(server):
alice = create_user(server.base, "logs")
chat = call(
server.base,
"POST",
"/api/v1/chats",
201,
token=alice["token"],
body={"title": "Логи", "member_ids": [alice["id"]]},
)["json"]
send_message(server.base, chat["id"], alice["token"], SECRET)
time.sleep(0.2)
output = server.output()
check("duration_ms=" in output and "method=POST" in output, "request log line missing")
check(SECRET not in output, "message text leaked into logs")
check(alice["token"] not in output, "session token leaked into logs")
check("lab-only-password" not in output and "postgresql+asyncpg://" not in output, "database url leaked into logs")
print("PASS: logs omit message text")
def main():
port = free_port()
server = Server(port)
try:
server.wait_ready()
call(server.base, "GET", "/health/live", 200)
call(server.base, "GET", "/api/v1/users/me", 401)
header_only = create_user(server.base, "header")
rejected = call(server.base, "GET", "/api/v1/users/me", 401, user_id=header_only["id"])
check(rejected["json"]["error"]["code"] == "unauthorized", "X-User-Id was accepted")
test_invalid_json(server.base)
test_duplicate_username(server.base)
test_empty_and_foreign(server.base)
test_pagination(server.base)
test_concurrency(server.base)
test_logs(server)
finally:
server.stop()
print("PASS: student tests")
if __name__ == "__main__":
try:
main()
except Failure as exc:
print("FAIL:", exc)
sys.exit(1)
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Прямой анонимный доступ к bucket должен быть закрыт."""
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
S3 = os.environ.get("S3_PUBLIC_URL", "http://127.0.0.1:9000").rstrip("/")
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
def anonymous(path: str) -> int:
request = urllib.request.Request(S3 + path, method="GET")
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status
except urllib.error.HTTPError as exc:
return exc.status
except (urllib.error.URLError, TimeoutError, OSError) as exc:
raise Failure("direct s3 probe failed: " + type(exc).__name__) from None
def main():
client = Client(BASE, timeout=20)
alice, _bob, _eve, chat = client.bootstrap()
att, content = client.attachment(alice, chat)
att = client.wait_ready(alice, att)
listed = anonymous("/" + BUCKET)
obj = anonymous("/" + BUCKET + "/att/" + att["id"])
check(listed in {403, 404}, "anonymous list status %s" % listed)
check(obj in {403, 404}, "anonymous object status %s" % obj)
download = client.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=alice)
check(download["bytes"] == content, "authorized download after anonymous probe")
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "s3_private.json").write_text(
json.dumps(
{
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"anonymous_list": listed,
"anonymous_object": obj,
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
print("PASS: private bucket rejects anonymous GET")
if __name__ == "__main__":
run(main)
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Трек 5.1: цена масштабирования API при фиксированном и растущем бюджете CPU/RAM."""
import json
import math
import os
import subprocess
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
DURATION = float(os.environ.get("TRACK1_DURATION", "30"))
CONCURRENCY = int(os.environ.get("TRACK1_CONCURRENCY", "8"))
WARMUP = float(os.environ.get("TRACK1_WARMUP", "8"))
def compose(*args, timeout=180):
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=timeout,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
raise Failure("docker compose %s failed: %s" % (args[0], proc.stderr[-400:]))
return proc.stdout
def api_ids():
return [line.strip() for line in compose("ps", "-q", "api").splitlines() if line.strip()]
def wait_ready(timeout=90):
client = Client(BASE, timeout=3)
deadline = time.monotonic() + timeout
last = ""
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure as exc:
last = str(exc)
time.sleep(0.4)
raise Failure("ready wait failed: " + last)
def scale_api(n):
compose("up", "-d", "--no-deps", "--scale", "api=%d" % n, "api")
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
if len(api_ids()) >= n:
wait_ready()
return
time.sleep(0.5)
raise Failure("failed to scale api to %s" % n)
def apply_limits(cpus_each, memory_mb_each):
for container_id in api_ids():
args = ["docker", "update", "--cpus", "%.3f" % cpus_each, "--memory", "%dm" % memory_mb_each, container_id]
proc = subprocess.run(args, capture_output=True, text=True, timeout=30)
if proc.returncode != 0:
raise Failure("docker update failed")
def docker_stats():
proc = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"],
capture_output=True,
text=True,
timeout=30,
encoding="utf-8",
errors="replace",
)
rows = []
for line in proc.stdout.splitlines():
parts = line.split("\t")
if len(parts) == 3:
rows.append({"name": parts[0], "cpu": parts[1], "mem": parts[2]})
return rows
def run_load(duration, concurrency, warmup):
client = Client(BASE, timeout=8)
alice, _bob, _eve, chat = client.bootstrap()
if warmup > 0:
deadline = time.monotonic() + warmup
index = 0
while time.monotonic() < deadline:
client.message(alice, chat, "warmup-%s" % index)
index += 1
barrier = threading.Barrier(concurrency)
def worker(worker_id):
local = Client(BASE, timeout=5)
barrier.wait()
end = time.monotonic() + duration
latencies, errors = [], 0
index = 0
while time.monotonic() < end:
started = time.monotonic()
try:
local.message(alice, chat, "track1-%s-%s" % (worker_id, index))
latencies.append(time.monotonic() - started)
except Failure:
errors += 1
index += 1
return latencies, errors
started = time.monotonic()
with ThreadPoolExecutor(max_workers=concurrency) as pool:
results = list(pool.map(worker, range(concurrency)))
elapsed = time.monotonic() - started
latencies = sorted(item for values, _ in results for item in values)
errors = sum(n for _, n in results)
total = len(latencies) + errors
def percentile(p):
if not latencies:
return None
return round(1000 * latencies[max(0, math.ceil(p * len(latencies)) - 1)], 3)
return {
"elapsed_seconds": round(elapsed, 3),
"concurrency": concurrency,
"successful_requests": len(latencies),
"failed_requests": errors,
"error_ratio": round(errors / total, 6) if total else None,
"successful_rps": round(len(latencies) / elapsed, 3) if elapsed else None,
"successful_latency_ms": {"p50": percentile(0.50), "p95": percentile(0.95), "p99": percentile(0.99)},
"docker_stats": docker_stats(),
}
def measure(label, replicas, cpus_each, memory_mb_each):
scale_api(replicas)
apply_limits(cpus_each, memory_mb_each)
wait_ready()
time.sleep(2)
result = run_load(DURATION, CONCURRENCY, WARMUP)
result.update(
{
"label": label,
"replicas": replicas,
"cpus_each": cpus_each,
"memory_mb_each": memory_mb_each,
"total_cpu": round(replicas * cpus_each, 3),
"total_memory_mb": replicas * memory_mb_each,
}
)
print(json.dumps({k: result[k] for k in ("label", "replicas", "total_cpu", "successful_rps", "error_ratio")}, ensure_ascii=False))
return result
def main():
wait_ready()
fixed_budget = [
measure("fixed-1", 1, 1.00, 512),
measure("fixed-2", 2, 0.50, 256),
measure("fixed-4", 4, 0.25, 128),
]
growing = [
measure("grow-2x0.25", 2, 0.25, 128),
measure("grow-2x0.50", 2, 0.50, 256),
measure("grow-2x1.00", 2, 1.00, 512),
]
scale_api(2)
apply_limits(0.50, 256)
report = {
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"hypothesis": "При фиксированном суммарном CPU/RAM добавление реплик перестаёт помогать, когда узким местом становится PostgreSQL/HAProxy, а не CPU процесса API.",
"profile": {
"duration_seconds": DURATION,
"concurrency": CONCURRENCY,
"warmup_seconds": WARMUP,
"workload": "closed-loop POST /messages through HAProxy",
},
"fixed_total_budget": fixed_budget,
"growing_resources": growing,
}
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "track1.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
check(all(item["successful_requests"] > 0 for item in fixed_budget + growing), "a track1 series had no successes")
print("PASS: track1 series written to evidence/track1.json")
if __name__ == "__main__":
run(main)
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""10 параллельных загрузок и пик RSS API-реплик по docker stats."""
import json
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
WORKERS = 10
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def api_mem_mib() -> float:
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", "ps", "-q", "api"],
cwd=str(ROOT),
capture_output=True,
text=True,
timeout=20,
)
ids = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
if not ids:
raise Failure("no api containers")
stats = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", *ids],
capture_output=True,
text=True,
timeout=20,
)
if stats.returncode != 0:
raise Failure("docker stats failed")
peak = 0.0
for line in stats.stdout.splitlines():
used = line.split("/", 1)[0].strip()
if used.endswith("GiB"):
peak = max(peak, float(used[:-3].strip()) * 1024)
elif used.endswith("MiB"):
peak = max(peak, float(used[:-3].strip()))
elif used.endswith("KiB"):
peak = max(peak, float(used[:-3].strip()) / 1024)
return peak
def main():
client = Client(BASE, timeout=30)
alice, _bob, _eve, chat = client.bootstrap()
before = api_mem_mib()
barrier = threading.Barrier(WORKERS)
errors = []
lock = threading.Lock()
def worker(index: int) -> None:
local = Client(BASE, timeout=30)
try:
barrier.wait(20)
local.call(
"POST",
"/api/v1/chats/%s/attachments?filename=p%d.png" % (chat["id"], index),
202,
actor=alice,
raw=SAMPLE,
headers={"Content-Type": "image/png"},
schema="Attachment",
)
except Exception as exc:
with lock:
errors.append("%s: %s" % (type(exc).__name__, exc))
threads = [threading.Thread(target=worker, args=(i,)) for i in range(WORKERS)]
for thread in threads:
thread.start()
peak = before
deadline = time.monotonic() + 30
while any(thread.is_alive() for thread in threads) and time.monotonic() < deadline:
peak = max(peak, api_mem_mib())
time.sleep(0.4)
for thread in threads:
thread.join()
peak = max(peak, api_mem_mib())
check(not errors, "concurrent uploads failed: " + "; ".join(errors[:3]))
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "upload_mem.json").write_text(
json.dumps(
{
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"workers": WORKERS,
"rss_before_mib": round(before, 2),
"rss_peak_mib": round(peak, 2),
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
print("PASS: %s concurrent uploads, peak RSS %.1f MiB" % (WORKERS, peak))
if __name__ == "__main__":
run(main)