forked from mtusi2026/mtusi2026lab4
- S3: SeaweedFS 4.51 (MinIO-образы недоступны), приватный bucket, отдельные ограниченные ключи API, служебные порты закрыты; идемпотентный s3-init с проверкой приватности и прогревом записи - вложения: потоковая загрузка PNG/JPEG, лимиты 10 MiB / 40 Мпикс, тип по содержимому, проверка filename, скачивание только участникам - согласованность PG/S3: pending -> PUT -> ready, компенсация, sweeper с grace и dry-run; attachment_ids в сообщениях, FK по чату - back-pressure на S3 PUT после найденного OOM SeaweedFS - тесты student-tests, evidence, REPORT.md, DEMO.md
62 lines
2.4 KiB
Python
62 lines
2.4 KiB
Python
"""Helpers for student tests: synthetic images (stdlib only) and read-only inspection of the compose stack."""
|
|
import os
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
|
|
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
|
SAMPLE_PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
|
SAMPLE_JPG = (FIXTURES / "sample.jpg").read_bytes()
|
|
|
|
|
|
def _chunk(kind, data):
|
|
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
|
|
|
|
|
def png(width, height, color_type=2, row=None):
|
|
"""PNG writer: color_type 0 = gray (1 byte/px), 2 = RGB (3 bytes/px). row(y) returns raw row bytes."""
|
|
bpp = {0: 1, 2: 3}[color_type]
|
|
blank = bytes(width * bpp)
|
|
comp = zlib.compressobj(6)
|
|
parts = []
|
|
for y in range(height):
|
|
parts.append(comp.compress(b"\x00" + (row(y) if row else blank)))
|
|
parts.append(comp.flush())
|
|
ihdr = struct.pack(">IIBBBBB", width, height, 8, color_type, 0, 0, 0)
|
|
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", b"".join(parts)) + _chunk(b"IEND", b"")
|
|
|
|
|
|
def png_header_only(width, height):
|
|
"""Valid signature + IHDR claiming width x height, tiny IDAT: the pixel limit must fire before decoding."""
|
|
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
|
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", zlib.compress(bytes(1000))) + _chunk(b"IEND", b"")
|
|
|
|
|
|
def noise_png(width, height):
|
|
return png(width, height, 2, row=lambda y: os.urandom(width * 3))
|
|
|
|
|
|
def dc(*args, check=True, timeout=120):
|
|
out = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
|
if check and out.returncode != 0:
|
|
raise RuntimeError("docker compose %s failed: %s" % (args[0], out.stderr.strip()[-300:]))
|
|
return out
|
|
|
|
|
|
def psql(sql):
|
|
return dc("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAX", "-c", sql).stdout.strip()
|
|
|
|
|
|
def api_python(code, service="api"):
|
|
"""Run Python inside an API container: it has the API's own (restricted) S3 credentials as secrets."""
|
|
return dc("exec", "-T", service, "python", "-c", code).stdout.strip()
|
|
|
|
|
|
def count_objects():
|
|
return int(api_python("from app.objects import ObjectStore; print(sum(1 for _ in ObjectStore().list_originals()))"))
|