Реализована лабораторная работа 4 на оценку 4

This commit is contained in:
MacBook
2026-10-20 21:16:52 +03:00
parent ec540a1a72
commit 6913a7ca1f
42 changed files with 3419 additions and 37 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Stop Redis and PostgreSQL separately and check bounded API failures."""
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
def compose(*args):
subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
check=True, stdout=subprocess.DEVNULL)
def wait_ready(client, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(0.5)
raise Failure("stack did not recover")
def main():
client = Client(timeout=5)
actor = client.user("dependency")
try:
compose("stop", "redis")
client.call("GET", "/health/ready", 503)
client.call("GET", "/api/v1/users/me", 503, actor=actor)
client.call("GET", "/api/v1/users/me", 401)
finally:
compose("start", "redis")
wait_ready(client)
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
try:
compose("stop", "postgres")
client.call("GET", "/health/ready", 503)
client.call("GET", "/api/v1/users/me", 503, actor=actor)
finally:
compose("start", "postgres")
wait_ready(client)
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
print("PASS: Redis/PostgreSQL failures returned 503; anonymous access stayed 401; state recovered")
if __name__ == "__main__":
try:
main()
except (Failure, OSError, subprocess.CalledProcessError) as exc:
print("FAIL:", exc)
raise SystemExit(1)
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Recreate the API with a two-second session TTL and prove expiry."""
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
def compose(env, *args):
subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
env=env, check=True, stdout=subprocess.DEVNULL)
def wait_ready(timeout=60):
client = Client(timeout=2)
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(0.5)
raise Failure("API did not become ready")
def main():
normal_env = dict(os.environ)
normal_env.pop("SESSION_TTL_SECONDS", None)
short_env = dict(normal_env)
short_env["SESSION_TTL_SECONDS"] = "2"
try:
compose(short_env, "up", "-d", "--force-recreate", "--no-deps", "--wait", "api1", "api2")
compose(short_env, "exec", "-T", "nginx", "nginx", "-s", "reload")
wait_ready()
client = Client()
actor = client.user("expiry")
time.sleep(3)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: two-second Redis session expired and was rejected")
finally:
compose(normal_env, "up", "-d", "--force-recreate", "--no-deps", "--wait", "api1", "api2")
compose(normal_env, "exec", "-T", "nginx", "nginx", "-s", "reload")
wait_ready()
if __name__ == "__main__":
try:
main()
except (Failure, OSError, subprocess.CalledProcessError) as exc:
print("FAIL:", exc)
raise SystemExit(1)
@@ -0,0 +1,55 @@
"""Prove that one idempotency key creates one message across both replicas."""
import concurrent.futures
import json
import sys
import threading
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run # noqa: E402
def main():
args = arguments("Concurrent cross-replica idempotency check")
base = Client(args.base_url, args.ca_file)
alice, _, _, chat = base.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/messages"
key = "parallel-" + uuid.uuid4().hex
body = {"text": "one logical concurrent message"}
workers = 12
barrier = threading.Barrier(workers)
def send(_):
client = Client(args.base_url, args.ca_file)
barrier.wait()
result = client.call("POST", path, 201, actor=alice, body=body,
headers={"Idempotency-Key": key}, schema="Message")
return result["json"], result["headers"]["X-Instance-Id"]
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(send, range(workers)))
messages = [item[0] for item in responses]
instances = sorted(set(item[1] for item in responses))
ids = sorted(set(item["id"] for item in messages))
check(len(ids) == 1, "one key created more than one message")
check(all(item == messages[0] for item in messages),
"idempotent responses differ")
check(len(instances) >= 2, "requests did not cross two API replicas")
base.call("POST", path, 409, actor=alice, body={"text": "different body"},
headers={"Idempotency-Key": key})
page = base.call("GET", path + "?limit=100", actor=alice,
schema="MessagePage")["json"]
check(sum(item["id"] == ids[0] for item in page["items"]) == 1,
"history contains a duplicate message")
result = {"parallel_requests": workers, "instances": instances,
"unique_message_ids": len(ids), "conflicting_reuse_status": 409}
print("PASS:", json.dumps(result, ensure_ascii=False))
if __name__ == "__main__":
run(main)
@@ -0,0 +1,71 @@
"""Check LB failover when api1 still runs but cannot reach its stores."""
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
def docker(*args):
return subprocess.run(["docker", *args], cwd=ROOT, check=True,
capture_output=True, text=True).stdout.strip()
def compose(*args):
return docker("compose", "--env-file", ".env", *args)
def details(container):
return json.loads(docker("inspect", container))[0]
def wait_health(container, expected, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if details(container)["State"]["Health"]["Status"] == expected:
return
time.sleep(1)
raise Failure("api1 did not become " + expected)
def main():
client = Client(timeout=8)
seen = set()
for _ in range(20):
seen.add(client.call("GET", "/health/ready", schema="Health")
["headers"]["X-Instance-Id"])
check(seen == {"api-1", "api-2"}, "both instances must be ready initially")
actor, _, _, chat = client.bootstrap()
container = compose("ps", "-q", "api1")
check(bool(container), "api1 container is missing")
network = next((name for name in details(container)["NetworkSettings"]["Networks"]
if name.endswith("_backend")), None)
check(network is not None, "api1 backend network is missing")
disconnected = False
try:
docker("network", "disconnect", network, container)
disconnected = True
wait_health(container, "unhealthy")
for _ in range(20):
for path, schema in (("/api/v1/users/me", "User"),
("/health/ready", "Health")):
response = client.call("GET", path, actor=actor, schema=schema)
check(response["headers"]["X-Instance-Id"] == "api-2",
path + " was not served by healthy api2")
for number in range(10):
response = client.message(actor, chat, "unready check " + str(number))
check(response["headers"]["X-Instance-Id"] == "api-2",
"message was not accepted by healthy api2")
print("PASS: api1 unhealthy with frontend connection; 40 GETs and 10 POSTs served by api2")
finally:
if disconnected:
docker("network", "connect", "--alias", "api1", network, container)
wait_health(container, "healthy")
if __name__ == "__main__":
run(main)
+79
View File
@@ -0,0 +1,79 @@
"""Ten simultaneous uploads with kernel cgroup peak-memory measurements."""
import concurrent.futures
import hashlib
import json
import math
import random
import struct
import threading
import time
from verify_attachments import ROOT, Client, check, compose, png_chunk, run, upload, wait_ready
def fixture():
# 9M pixels; random rows make a ~6.8 MiB valid PNG without another library.
rng = random.Random(2026)
import zlib
compressor = zlib.compressobj(1)
parts = []
for row in range(3000):
pixels = rng.randbytes(9000) if row % 4 == 0 else bytes(9000)
parts.append(compressor.compress(b"\x00" + pixels))
parts.append(compressor.flush())
return (b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", struct.pack(">IIBBBBB", 3000, 3000, 8, 2, 0, 0, 0))
+ png_chunk(b"IDAT", b"".join(parts)) + png_chunk(b"IEND", b""))
def memory():
return {service: json.loads(compose("exec", "-T", service, "/messenger", "memory"))
for service in ("api1", "api2")}
def main():
client = Client(timeout=60)
actor, _, _, chat = client.bootstrap()
# A new container cgroup resets memory.peak for this experiment.
compose("up", "-d", "--no-deps", "--force-recreate", "--wait", "api1", "api2")
compose("exec", "-T", "nginx", "nginx", "-s", "reload")
wait_ready(client)
raw = fixture()
digest = hashlib.sha256(raw).hexdigest()
before = memory()
barrier = threading.Barrier(11)
def send(number):
c = Client(timeout=60)
barrier.wait()
started = time.monotonic()
response = upload(c, actor, chat, raw, filename="load-%d.png" % number)
check(response["json"]["sha256"] == digest, "concurrent upload checksum mismatch")
return response, time.monotonic() - started
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
futures = [pool.submit(send, number) for number in range(10)]
started = time.monotonic()
barrier.wait()
responses = [future.result() for future in futures]
elapsed = time.monotonic() - started
after = memory()
for metrics in after.values():
check(metrics["memory.peak"] < metrics["memory.max"], "upload memory reached container limit")
for response, _ in responses:
downloaded = client.call("GET", "/api/v1/attachments/" + response["json"]["id"] + "/content", actor=actor)
check(downloaded["bytes"] == raw, "concurrent original changed")
times = sorted(duration * 1000 for _, duration in responses)
output = {"concurrent_uploads": 10, "file_size_bytes": len(raw), "pixels": 9000000,
"successful_uploads": 10, "failed_uploads": 0,
"elapsed_seconds": round(elapsed, 3), "successful_rps": round(10 / elapsed, 3),
"latency_ms": {"p50": round(times[4], 3), "p95": round(times[math.ceil(.95 * 10) - 1], 3), "p99": round(times[9], 3)},
"memory_before_bytes": before, "memory_after_bytes": after,
"peak_source": "Linux cgroup v2 memory.peak; fresh API containers including startup",
"decoder_slots_per_replica": 1,
"instances": sorted({response["headers"]["X-Instance-Id"] for response, _ in responses})}
(ROOT / "evidence/upload-memory.json").write_text(json.dumps(output, indent=2) + "\n")
print("PASS:", json.dumps(output))
if __name__ == "__main__":
run(main)
+169
View File
@@ -0,0 +1,169 @@
"""Grade 4: image validation, attachment ACLs and cross-replica persistence."""
import hashlib
import json
import struct
import subprocess
import sys
import time
import uuid
import zlib
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 # noqa: E402
def compose(*args, data=None):
result = subprocess.run(["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT, input=data, capture_output=True, text=True, check=True)
return result.stdout.strip()
def psql(sql):
return compose("exec", "-T", "postgres", "psql", "-X", "-q", "-A", "-t",
"-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger", data=sql)
def png_chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
def bomb_header(width=10000, height=10000):
# A valid PNG header must be rejected BEFORE decoding its huge bitmap.
return b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
def wide_png():
# Exactly 40M pixels, 16-bit RGBA, one very wide scanline. The compressed
# original is small but the decoder needs both bitmap and scanline buffers.
compressor = zlib.compressobj(1)
parts = [compressor.compress(b"\x00")]
remaining = 40000000 * 8
block = bytes(1024 * 1024)
while remaining:
n = min(len(block), remaining)
parts.append(compressor.compress(block[:n]))
remaining -= n
parts.append(compressor.flush())
return (b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", struct.pack(">IIBBBBB", 40000000, 1, 16, 6, 0, 0, 0))
+ png_chunk(b"IDAT", b"".join(parts)) + png_chunk(b"IEND", b""))
def upload(client, actor, chat, data, kind="image/png", filename="sample.png", expected=201):
return client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename, safe=""),
expected, actor=actor, raw=data, headers={"Content-Type": kind},
schema="Attachment" if expected == 201 else None)
def wait_ready(client, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(.5)
raise Failure("stack did not recover")
def main():
client = Client(timeout=30)
alice, bob, eve, chat = client.bootstrap()
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
jpeg = (ROOT / "student-tests/fixtures/sample.jpg").read_bytes()
att = upload(client, alice, chat, png)["json"]
jpg = upload(client, alice, chat, jpeg, "image/jpeg", "photo.jpg")["json"]
for item, raw in ((att, png), (jpg, jpeg)):
check(item["size_bytes"] == len(raw) and item["sha256"] == hashlib.sha256(raw).hexdigest(), "original metadata mismatch")
check(client.call("GET", "/api/v1/attachments/" + item["id"] + "/content", actor=bob)["bytes"] == raw, "original bytes changed")
# A private ancillary chunk before IEND creates valid exact-size PNGs.
for size in (6294458, 10485760):
sized = png[:-12] + png_chunk(b"vpAg", bytes(size - len(png) - 12)) + png[-12:]
large = upload(client, alice, chat, sized, filename="boundary.png")["json"]
check(large["size_bytes"] == size, "boundary upload size mismatch")
check(client.call("GET", "/api/v1/attachments/" + large["id"] + "/content", actor=bob)["bytes"] == sized,
"boundary original bytes changed")
upload(client, alice, chat, b"x" * (10485760 + 1), expected=413)
upload(client, alice, chat, png[:40], expected=415)
damaged = bytearray(png)
damaged[len(damaged) // 2] ^= 255
upload(client, alice, chat, bytes(damaged), expected=415)
upload(client, alice, chat, png[:-12], expected=415)
corrupt = png[:33] + png_chunk(b"IDAT", b"invalid compressed data") + png_chunk(b"IEND", b"")
upload(client, alice, chat, corrupt, expected=415)
upload(client, alice, chat, png, "image/jpeg", expected=415)
upload(client, alice, chat, b"not an image", expected=415)
upload(client, alice, chat, bomb_header(), expected=413)
upload(client, alice, chat, bomb_header(20000, 10000), expected=413)
upload(client, alice, chat, bomb_header(8001, 5000), expected=413)
wide = wide_png()
wide_response = upload(client, alice, chat, wide, filename="wide.png")
check(wide_response["json"]["sha256"] == hashlib.sha256(wide).hexdigest(), "wide PNG changed")
wide_metrics = {service: json.loads(compose("exec", "-T", service, "/messenger", "memory")) for service in ("api1", "api2")}
check(all(m["memory.peak"] < m["memory.max"] for m in wide_metrics.values()), "wide PNG exceeded memory limit")
for filename in ("../image.png", "a\\b.png", "bad\x00.png", "bad\n.png", " " , "x" * 256):
upload(client, alice, chat, png, filename=filename, expected=400)
for suffix in ("", "/content"):
client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 404, actor=eve)
upload(client, eve, chat, png, expected=404)
other = client.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Other", "member_ids": [alice["id"]]}, schema="Chat")["json"]
other_att = upload(client, alice, other, png)["json"]
path = "/api/v1/chats/" + chat["id"] + "/messages"
for ids in ([other_att["id"]], [str(uuid.uuid4())]):
client.call("POST", path, 404, actor=alice, body={"text": "", "attachment_ids": ids},
headers={"Idempotency-Key": uuid.uuid4().hex})
for body in ({"text": "x", "attachment_ids": [att["id"], att["id"]]},
{"text": "x", "attachment_ids": None}, {"text": None, "attachment_ids": [att["id"]]},
{"attachment_ids": [att["id"]]}, {"text": 42}, {"text": "x", "attachment_ids": {}},
{"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}):
client.call("POST", path, 400, actor=alice, body=body, headers={"Idempotency-Key": uuid.uuid4().hex})
key = uuid.uuid4().hex
first = client.message(bob, chat, "", key=key, attachments=[att["id"]])["json"]
check(client.message(bob, chat, "", key=key, attachments=[att["id"]])["json"] == first, "attachment replay changed")
client.call("POST", path, 409, actor=bob, body={"text": "", "attachment_ids": [jpg["id"]]}, headers={"Idempotency-Key": key})
text_key = uuid.uuid4().hex
text = client.message(alice, chat, "text", key=text_key)["json"]
replay = client.call("POST", path, 201, actor=alice, body={"attachment_ids": [], "text": "text"}, headers={"Idempotency-Key": text_key}, schema="Message")["json"]
check(text == replay, "omitted attachment_ids and [] are not equivalent")
object_key = psql("SELECT object_key FROM attachments WHERE id='" + att["id"] + "';")
audit = compose("exec", "-T", "api1", "/messenger", "s3-audit", object_key)
# Explicitly stop the replica that accepted this particular upload.
uploaded = upload(client, alice, chat, png)
service = {"api-1": "api1", "api-2": "api2"}[uploaded["headers"]["X-Instance-Id"]]
try:
compose("stop", "--timeout", "3", service)
wait_ready(client)
# One ready response can arrive before the monitor removes the stopped
# replica. Allow the documented ten-second failover budget, then check
# the download without retries so storage/content failures stay visible.
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
upstream = compose("exec", "-T", "nginx", "cat", "/run/nginx-upstream.conf")
if "server " + service + ":8080" not in upstream:
break
time.sleep(.2)
else:
raise Failure("stopped API was not excluded within ten seconds")
downloaded = client.call("GET", "/api/v1/attachments/" + uploaded["json"]["id"] + "/content", actor=bob)
check(downloaded["bytes"] == png, "other replica lost uploaded file")
check(downloaded["headers"]["X-Instance-Id"] != uploaded["headers"]["X-Instance-Id"], "upload replica was not stopped")
finally:
compose("start", service)
wait_ready(client)
result = {"png_jpeg": "PASS", "size_corruption_mime_pixels_filename": "PASS",
"exact_size_uploads_through_lb": [6294458, 10485760],
"corrupt_idat_and_missing_iend": "PASS", "pixel_limit_40005000_and_200000000": "PASS",
"cross_chat_and_outsider": "PASS", "message_idempotency": "PASS",
"wide_png_40000000_pixels": "PASS", "wide_memory_bytes": wide_metrics,
"private_bucket_and_limited_credentials": "PASS", "upload_replica_stopped_download_equal": True}
(ROOT / "evidence").mkdir(exist_ok=True)
(ROOT / "evidence/attachments-grade4.json").write_text(json.dumps(result, indent=2) + "\n")
print(audit)
print("PASS: attachment validation, authorization, idempotency and cross-replica download")
if __name__ == "__main__":
run(main)
+82
View File
@@ -0,0 +1,82 @@
"""Interrupt upload, fail S3 and metadata writes, then verify grace cleanup."""
import json
import socket
import time
import uuid
from urllib.parse import urlsplit
from verify_attachments import ROOT, Client, check, compose, psql, run, upload, wait_ready
def stat(key):
return json.loads(compose("exec", "-T", "api1", "/messenger", "s3-stat", key))
def cleanup():
return json.loads(compose("exec", "-T", "-e", "CLEANUP_GRACE_SECONDS=120", "cleanup", "/messenger", "cleanup"))
def main():
client = Client(timeout=30)
actor, _, _, chat = client.bootstrap()
raw = (ROOT / "tests/fixtures/sample.png").read_bytes()
good = upload(client, actor, chat, raw)["json"]
ready_key = psql("SELECT object_key FROM attachments WHERE id='" + good["id"] + "';")
count_before = psql("SELECT count(*) FROM attachments;")
# Abort a real HTTP upload with a body shorter than its Content-Length.
address = urlsplit(client.base)
with socket.create_connection((address.hostname, address.port or 80), timeout=5) as connection:
headers = ("POST /api/v1/chats/" + chat["id"] + "/attachments?filename=interrupted.png HTTP/1.1\r\n"
"Host: localhost\r\nAuthorization: Bearer " + actor["token"] + "\r\n"
"Content-Type: image/png\r\nContent-Length: " + str(len(raw) + 1000) + "\r\nConnection: close\r\n\r\n")
connection.sendall(headers.encode() + raw[:40])
time.sleep(1)
check(psql("SELECT count(*) FROM attachments;") == count_before, "interrupted upload left ready metadata")
try:
compose("stop", "s3")
client.call("GET", "/health/ready", 503)
upload(client, actor, chat, raw, expected=503)
client.call("GET", "/api/v1/users/me", 401)
finally:
compose("start", "s3")
wait_ready(client)
check(client.call("GET", "/api/v1/attachments/" + good["id"] + "/content", actor=actor)["bytes"] == raw,
"S3 restart lost original")
constraint = "injected_" + uuid.uuid4().hex
failed_keys = []
try:
psql("ALTER TABLE attachments ADD CONSTRAINT " + constraint + " CHECK (filename NOT LIKE 'failure-%') NOT VALID;")
for number in range(2):
before = set(psql("SELECT object_key FROM attachment_uploads;").splitlines())
upload(client, actor, chat, raw, filename="failure-%d.png" % number, expected=503)
after = set(psql("SELECT object_key FROM attachment_uploads;").splitlines())
new = after - before
check(len(new) == 1, "failed metadata write did not leave one durable intent")
key = new.pop()
check(stat(key)["exists"], "failure was not injected after successful S3 PUT")
failed_keys.append(key)
finally:
psql("ALTER TABLE attachments DROP CONSTRAINT IF EXISTS " + constraint + ";")
# Also cover an object whose intent is missing, as with late S3 completion.
psql("DELETE FROM attachment_uploads WHERE object_key='" + failed_keys[1] + "';")
fresh = cleanup()
check(all(stat(key)["exists"] for key in failed_keys), "fresh objects removed before safe grace")
print("Waiting 122 seconds for safe cleanup grace; fresh objects were preserved.", flush=True)
deadline = time.monotonic() + 122
while time.monotonic() < deadline:
time.sleep(max(0, min(1, deadline - time.monotonic())))
cleaned = cleanup()
check(all(not stat(key)["exists"] for key in failed_keys), "orphan objects survived cleanup")
check(stat(ready_key)["exists"], "cleanup deleted ready referenced data")
repeat = cleanup()
check(repeat["removed_objects"] == 0 and repeat["removed_intents"] == 0, "cleanup repeat is not idempotent")
result = {"partial_upload": "PASS", "s3_outage_503_and_recovery": "PASS",
"metadata_failure_after_put": "PASS", "orphan_without_intent": "PASS",
"grace_seconds": 120, "fresh_preserved": True, "ready_preserved": True,
"fresh_sweep": fresh, "cleanup": cleaned, "repeat": repeat}
(ROOT / "evidence/upload-recovery.json").write_text(json.dumps(result, indent=2) + "\n")
print("PASS:", json.dumps(result))
if __name__ == "__main__":
run(main)