lab6: observability — OTel Collector, Prometheus, Loki, Tempo, Grafana

This commit is contained in:
2026-11-13 13:20:46 +03:00
parent 470d9d6f1e
commit 5945e035e0
63 changed files with 6436 additions and 19 deletions
+171
View File
@@ -0,0 +1,171 @@
"""Проверка crop 128×128 и optimized WebP 1280×1280 (lab5 grade 4).
Запуск:
python3 student_tests/test_variants.py --base-url http://localhost:8080
"""
from __future__ import annotations
import base64
import json
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
BASE = (
sys.argv[sys.argv.index("--base-url") + 1]
if "--base-url" in sys.argv
else "http://localhost:8080"
)
ROOT = Path(__file__).resolve().parent.parent
def call(method, path, headers=None, body=None, raw=None, timeout=30):
data = None
h = dict(headers or {})
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
elif raw is not None:
data = raw
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
resp = urllib.request.urlopen(req, timeout=timeout)
payload = resp.read()
return resp.status, payload, dict(resp.headers)
except urllib.error.HTTPError as e:
payload = e.read()
return e.code, payload, dict(e.headers)
def jpeg_size(data: bytes) -> tuple[int, int]:
assert data[:2] == b"\xff\xd8", "not a JPEG"
i = 2
sof = {0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf}
while i < len(data):
while i < len(data) and data[i] == 0xff:
i += 1
marker = data[i]
i += 1
if marker in {0xd9, 0xda}:
break
if marker in {0x01, 0xd8} or 0xd0 <= marker <= 0xd7:
continue
length = int.from_bytes(data[i:i+2], "big")
if marker in sof:
return (int.from_bytes(data[i+5:i+7], "big"),
int.from_bytes(data[i+3:i+5], "big"))
i += length
raise AssertionError("JPEG SOF not found")
def webp_size(data: bytes) -> tuple[int, int]:
assert data[:4] == b"RIFF" and data[8:12] == b"WEBP", "not a WebP"
# VP8L (lossless) или VP8 (lossy)
chunk = data[12:16]
if chunk == b"VP8 ":
i = data.index(b"\x9d\x01\x2a", 20)
w = int.from_bytes(data[i+3:i+5], "little") & 0x3fff
h = int.from_bytes(data[i+5:i+7], "little") & 0x3fff
return w, h
if chunk == b"VP8L":
b = data[21:25]
bits = int.from_bytes(b, "little")
w = (bits & 0x3FFF) + 1
h = ((bits >> 14) & 0x3FFF) + 1
return w, h
raise AssertionError("unknown WebP chunk")
def main():
username = "variants_" + uuid.uuid4().hex[:10]
password = "variants-pass-1234567890"
code, _, _ = call("POST", "/api/v1/users", body={
"username": username, "display_name": "Variants", "password": password,
})
assert code == 201, f"register failed: {code}"
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
code, payload, _ = call("POST", "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + cred})
assert code == 201, f"login failed: {code}"
session = json.loads(payload)
token = session["token"]
user_id = session["user"]["id"]
code, payload, _ = call("POST", "/api/v1/chats",
headers={"Authorization": "Bearer " + token},
body={"title": "Variants", "member_ids": [user_id]})
assert code == 201, f"chat failed: {code}"
chat_id = json.loads(payload)["id"]
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
code, payload, _ = call(
"POST",
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"},
raw=fixture,
)
assert code == 202, f"upload failed: {code}"
att_id = json.loads(payload)["id"]
print(f"upload: 202 queued ({att_id})")
# Ждём ready
deadline = time.monotonic() + 60
att = None
while time.monotonic() < deadline:
code, payload, _ = call("GET", f"/api/v1/attachments/{att_id}",
headers={"Authorization": "Bearer " + token})
if code == 200:
att = json.loads(payload)
if att["status"] == "ready":
break
time.sleep(0.5)
assert att and att["status"] == "ready", f"not ready: {att}"
variants = {v["name"]: v for v in att["variants"]}
print(f"variants: {list(variants.keys())}")
# --- thumbnail ---
assert "thumbnail" in variants, "missing thumbnail"
code, thumb_bytes, headers = call(
"GET", f"/api/v1/attachments/{att_id}/content?variant=thumbnail",
headers={"Authorization": "Bearer " + token},
)
assert code == 200, f"thumbnail download: {code}"
assert headers.get("content-type", "").startswith("image/jpeg")
w, h = jpeg_size(thumb_bytes)
assert (w, h) == (256, 160), f"thumbnail {w}x{h}, expected 256x160"
print(f"PASS: thumbnail 256x160 ({len(thumb_bytes)} bytes)")
# --- crop ---
assert "crop" in variants, "missing crop"
code, crop_bytes, headers = call(
"GET", f"/api/v1/attachments/{att_id}/content?variant=crop",
headers={"Authorization": "Bearer " + token},
)
assert code == 200, f"crop download: {code}"
assert headers.get("content-type", "").startswith("image/jpeg")
w, h = jpeg_size(crop_bytes)
assert (w, h) == (128, 128), f"crop {w}x{h}, expected 128x128"
print(f"PASS: crop 128x128 ({len(crop_bytes)} bytes)")
# --- optimized ---
assert "optimized" in variants, "missing optimized"
code, opt_bytes, headers = call(
"GET", f"/api/v1/attachments/{att_id}/content?variant=optimized",
headers={"Authorization": "Bearer " + token},
)
assert code == 200, f"optimized download: {code}"
assert headers.get("content-type", "").startswith("image/webp")
w, h = webp_size(opt_bytes)
# fixture 320x200 → вписан в 1280×1280 без увеличения → 320×200
assert (w, h) == (320, 200), f"optimized {w}x{h}, expected 320x200 (no upscale)"
print(f"PASS: optimized WebP {w}x{h} ({len(opt_bytes)} bytes)")
print("\nPASS: all variants — thumbnail, crop, optimized")
if __name__ == "__main__":
main()