This commit is contained in:
2026-11-13 20:27:25 +03:00
parent ec540a1a72
commit 7b19d4691d
44 changed files with 2330 additions and 35 deletions
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Own lab3 checks: two replicas, shared idempotency and rolling replacement."""
import argparse
import subprocess
import sys
import time
import uuid
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
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--rolling-update", action="store_true")
args = parser.parse_args()
client = Client(args.base_url)
alice, bob, eve, chat = client.bootstrap()
instances = set()
for _ in range(40):
response = client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
instances.add(response["headers"].get("X-Instance-Id", ""))
if len(instances) >= 2:
break
check(len(instances) >= 2, "load balancer did not expose two API instances")
key = "parallel-" + uuid.uuid4().hex
text = "Одна запись при конкурентном повторе"
def send_once():
return client.message(alice, chat, text, key=key)["json"]
with ThreadPoolExecutor(max_workers=10) as pool:
messages = list(pool.map(lambda _: send_once(), range(10)))
check(len({message["id"] for message in messages}) == 1,
"concurrent idempotency created duplicate messages")
check(all(message == messages[0] for message in messages),
"idempotency replay returned different messages")
client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 409,
actor=alice, body={"text": "Другой текст"},
headers={"Idempotency-Key": key})
client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400,
actor=alice, body={"text": "Без ключа"})
print("PASS: two API instances, shared idempotency and conflict semantics")
if args.rolling_update:
output = ROOT / "evidence" / "rolling-load.json"
output.parent.mkdir(parents=True, exist_ok=True)
load = subprocess.Popen([
sys.executable, str(ROOT / "tests" / "load.py"),
"--base-url", args.base_url, "--duration", "20", "--concurrency", "4",
"--output", str(output),
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
time.sleep(2)
result = subprocess.run([str(ROOT / "scripts" / "rolling-update.sh")], check=False)
check(result.returncode == 0, "rolling-update.sh failed")
finally:
try:
load.wait(timeout=40)
except subprocess.TimeoutExpired:
load.kill()
load.wait()
raise Failure("rolling load exceeded its deadline")
check(load.returncode == 0, "load failed during rolling replacement")
print("PASS: rolling replacement completed while load was running")
if __name__ == "__main__":
try:
main()
except (Failure, AssertionError, OSError) as error:
print("FAIL:", error)
raise SystemExit(1)
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Lab4 grade-4 checks for upload validation and attachment authorization."""
import hashlib
import os
import sys
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
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
args = parser.parse_args()
client = Client(args.base_url)
alice, bob, eve, chat = client.bootstrap()
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
# Correct content succeeds and is byte-for-byte downloadable by another member.
uploaded = client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 201,
actor=alice, raw=fixture, headers={"Content-Type": "image/png"}, schema="Attachment")
attachment = uploaded["json"]
downloaded = client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)
check(downloaded["bytes"] == fixture, "downloaded object differs from upload")
check(hashlib.sha256(downloaded["bytes"]).hexdigest() == attachment["sha256"], "checksum mismatch")
# Too large, corrupt image, and mismatched MIME are controlled client errors.
client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=large.png", 413,
actor=alice, raw=b"\x89PNG\r\n\x1a\n" + b"x" * (10 * 1024 * 1024),
headers={"Content-Type": "image/png"})
client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=bad.png", 415,
actor=alice, raw=b"not-an-image", headers={"Content-Type": "image/png"})
client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=spoof.png", 415,
actor=alice, raw=fixture, headers={"Content-Type": "image/jpeg"})
# Outsider cannot read metadata or bytes; a random ID is also hidden as 404.
client.call("GET", f"/api/v1/attachments/{attachment['id']}", 404, actor=eve)
client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", 404, actor=eve)
client.call("GET", f"/api/v1/attachments/{uuid.uuid4()}", 404, actor=alice)
# An attachment from another chat cannot be referenced by a message.
other_chat = client.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Другой чат", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
client.call("POST", f"/api/v1/chats/{other_chat['id']}/messages", 404, actor=alice,
body={"text": "wrong chat", "attachment_ids": [attachment["id"]]},
headers={"Idempotency-Key": "wrong-chat-" + uuid.uuid4().hex})
print("PASS: attachment limits, MIME validation, authorization and chat binding")
if __name__ == "__main__":
try:
main()
except (Failure, AssertionError, OSError) as error:
print("FAIL:", error)
raise SystemExit(1)
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Ten concurrent uploads with Docker API memory sampling (local evidence only)."""
import argparse
import json
import re
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
def stats():
values = []
try:
output = subprocess.check_output(
["docker", "stats", "--no-stream", "--format", "{{.Name}}|{{.MemUsage}}"],
text=True, stderr=subprocess.DEVNULL)
for line in output.splitlines():
if "api-" not in line or " / " not in line:
continue
used = line.split("|", 1)[1].split(" / ", 1)[0].strip()
match = re.match(r"([0-9.]+)\s*(MiB|GiB|MB|GB)", used)
if match:
value = float(match.group(1)) * (1024 if match.group(2) in ("GiB", "GB") else 1)
values.append(value)
except (OSError, subprocess.CalledProcessError):
pass
return values
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--output", default="evidence/upload-memory.json")
args = parser.parse_args()
client = Client(args.base_url)
alice, _, _, chat = client.bootstrap()
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
peak = max(stats() or [0.0])
stop = threading.Event()
def sampler():
nonlocal peak
while not stop.is_set():
peak = max([peak] + stats())
time.sleep(0.1)
thread = threading.Thread(target=sampler, daemon=True)
thread.start()
started = time.monotonic()
with ThreadPoolExecutor(max_workers=10) as pool:
futures = [pool.submit(client.call, "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=parallel-{i}.png",
201, None, alice, {"Content-Type": "image/png"}, fixture, "Attachment") for i in range(10)]
results = [future.result() for future in futures]
stop.set()
thread.join(timeout=2)
report = {
"concurrency": 10,
"successful_uploads": len(results),
"fixture_bytes": len(fixture),
"elapsed_seconds": round(time.monotonic() - started, 3),
"api_peak_memory_mib": round(peak, 2),
"note": "Docker stats samples API containers every 100ms; local measurement, not a capacity benchmark."
}
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, ensure_ascii=False))
if __name__ == "__main__":
try:
main()
except (Failure, AssertionError, OSError) as error:
print("FAIL:", error)
raise SystemExit(1)