ЛР 4: реализация мессенджера и сценарии проверки

This commit is contained in:
Russiankryt
2026-12-03 17:20:50 +03:00
parent ec540a1a72
commit c87c84df1f
26 changed files with 1549 additions and 37 deletions
+71
View File
@@ -0,0 +1,71 @@
"""Inject missing metadata and missing bytes in an isolated test repository."""
import hashlib
import io
import json
import time
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from attachments import Objects
from db import Store
from reconcile import scan
def main():
store, objects = Store(), Objects()
user, chat, missing, used, orphan, fresh = [uuid4() for _ in range(6)]
raw = b"synthetic reconciler fixture"
digest = hashlib.sha256(raw).hexdigest()
all_keys = [objects.key(item) for item in (missing, used, orphan, fresh)]
def put(item):
objects.put(objects.key(item), io.BytesIO(raw), "image/png", len(raw))
try:
with store.pool.connection() as db:
db.execute("INSERT INTO users (id,username,display_name,password_hash) VALUES(%s,%s,'test','inactive')",
(user, "reconcile_" + user.hex[:12]))
db.execute("INSERT INTO chats(id,title) VALUES(%s,'reconciler fixture')", (chat,))
db.execute("INSERT INTO chat_members VALUES(%s,%s,1)", (chat, user))
for item in (missing, used):
db.execute("""
INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at)
VALUES(%s,%s,%s,'fixture.png','image/png',%s,%s,clock_timestamp()-interval '20 seconds')
""", (item, chat, user, len(raw), digest))
db.execute("""
INSERT INTO messages(id,chat_id,sender_id,text,attachment_ids)
VALUES(%s,%s,%s,'uses a real object',ARRAY[%s]::uuid[])
""", (uuid4(), chat, user, used))
put(used)
put(orphan)
time.sleep(2.5)
put(fresh)
cutoff = datetime.now(timezone.utc) - timedelta(seconds=1.5)
dry = scan(store, objects, cutoff)
assert str(orphan) in dry["orphan"] and str(missing) in dry["missing"]
assert str(fresh) not in dry["orphan"] and objects.has(objects.key(orphan))
fixed = scan(store, objects, cutoff, apply=True)
assert str(orphan) in fixed["orphan"] and str(missing) in fixed["missing"]
assert not objects.has(objects.key(orphan)) and objects.has(objects.key(used))
assert objects.has(objects.key(fresh))
again = scan(store, objects, cutoff, apply=True)
assert str(orphan) not in again["orphan"] and str(missing) not in again["missing"]
put(missing)
recovery = scan(store, objects, cutoff, apply=True)
assert str(missing) in recovery["restored"]
print(json.dumps({"dry_run": dry, "apply": fixed, "repeat": again, "recover": recovery}, indent=2))
finally:
for key in all_keys:
objects.delete(key)
with store.pool.connection() as db:
db.execute("DELETE FROM messages WHERE chat_id=%s", (chat,))
db.execute("DELETE FROM attachments WHERE chat_id=%s", (chat,))
db.execute("DELETE FROM chat_members WHERE chat_id=%s", (chat,))
db.execute("DELETE FROM chats WHERE id=%s", (chat,))
db.execute("DELETE FROM users WHERE id=%s", (user,))
store.pool.close()
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
"""Negative binary-upload scenarios and concurrent-upload measurement."""
import argparse
import json
import os
import subprocess
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
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, check # noqa: E402
def stats(stop, snapshots):
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, text=True).split()
while not stop.is_set():
raw = subprocess.check_output(["docker", "stats", "--no-stream", "--format",
"{{.Name}} {{.MemUsage}}", *ids], cwd=ROOT, text=True, timeout=12)
snapshots.append(raw.splitlines())
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--docker-stats", action="store_true")
parser.add_argument("--output", type=Path, default=ROOT / "evidence/uploads.json")
args = parser.parse_args()
client = Client(args.base_url, timeout=25)
actor, peer, outsider, chat = client.bootstrap()
image = (ROOT / "tests/fixtures/sample.png").read_bytes()
endpoint = f"/api/v1/chats/{chat['id']}/attachments?filename="
png = {"Content-Type": "image/png"}
client.call("POST", endpoint + "bad.png", 415, actor=actor, raw=b"not png", headers=png)
client.call("POST", endpoint + "wrong.jpg", 415, actor=actor, raw=image,
headers={"Content-Type": "image/jpeg"})
client.call("POST", endpoint + quote("../bad.png", safe=""), 400, actor=actor, raw=image, headers=png)
client.call("POST", endpoint + "too-big.png", 413, actor=actor,
raw=b"x" * (10 * 1024 * 1024 + 1), headers=png)
original, _ = client.attachment(actor, chat)
other = client.call("POST", "/api/v1/chats", 201, actor=outsider,
body={"title": "Private", "member_ids": [outsider["id"]]}, schema="Chat")["json"]
path = f"/api/v1/chats/{other['id']}/messages"
client.call("POST", path, 404, actor=outsider, headers={"Idempotency-Key": "foreign-file"},
body={"text": "", "attachment_ids": [original["id"]]})
client.call("GET", f"/api/v1/attachments/{original['id']}", 404, actor=outsider)
snapshots = []
stop = threading.Event()
polling = threading.Thread(target=stats, args=(stop, snapshots)) if args.docker_stats else None
if polling:
polling.start()
barrier = threading.Barrier(10)
def send(index):
local = Client(args.base_url, timeout=25)
barrier.wait()
return local.call("POST", endpoint + f"concurrent-{index}.png", 201, actor=actor,
raw=image, headers=png, schema="Attachment")["elapsed"]
started = time.monotonic()
try:
with ThreadPoolExecutor(10) as pool:
observations = list(pool.map(send, range(10)))
finally:
stop.set()
if polling:
polling.join(timeout=15)
result = {"uploads": 10, "source_bytes": len(image), "elapsed_s": time.monotonic() - started,
"request_seconds": observations, "container_memory_samples": snapshots}
if args.docker_stats:
check(bool(snapshots), "docker stats did not return any data")
args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print("PASS: upload validation, foreign attachment denied, ten concurrent uploads")
if __name__ == "__main__":
main()