154 lines
6.1 KiB
Python
154 lines
6.1 KiB
Python
"""Повторная доставка ready-задачи: no-op, не создаёт дубли.
|
|
|
|
Создаёт attachment, ждёт ready, публикует тот же job повторно,
|
|
проверяет, что variants не изменились и объекты в S3 не задублированы.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import io
|
|
import json
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
|
|
BASE = (
|
|
sys.argv[sys.argv.index("--base-url") + 1]
|
|
if "--base-url" in sys.argv
|
|
else "http://localhost:8080"
|
|
)
|
|
|
|
|
|
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, json.loads(payload) if payload else None
|
|
except urllib.error.HTTPError as e:
|
|
payload = e.read()
|
|
try:
|
|
return e.code, json.loads(payload) if payload else None
|
|
except Exception:
|
|
return e.code, None
|
|
|
|
|
|
def main():
|
|
# 1. Регистрация, логин, чат
|
|
username = "replay_" + uuid.uuid4().hex[:10]
|
|
password = "replay-pass-1234567890"
|
|
code, user = call("POST", "/api/v1/users", body={
|
|
"username": username, "display_name": "Replay", "password": password,
|
|
})
|
|
assert code == 201, f"register failed: {code} {user}"
|
|
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
code, session = call("POST", "/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + cred})
|
|
assert code == 201, f"login failed: {code}"
|
|
token = session["token"]
|
|
code, chat = call("POST", "/api/v1/chats",
|
|
headers={"Authorization": "Bearer " + token},
|
|
body={"title": "Replay", "member_ids": [user["id"]]})
|
|
assert code == 201, f"chat failed: {code}"
|
|
chat_id = chat["id"]
|
|
|
|
# 2. Upload
|
|
fixture = (Path(__file__).resolve().parent.parent / "tests/fixtures/sample.png").read_bytes()
|
|
code, att = 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 = att["id"]
|
|
print(f"upload: 202 queued ({att_id})")
|
|
|
|
# 3. Ждём ready
|
|
deadline = time.monotonic() + 60
|
|
while time.monotonic() < deadline:
|
|
code, att = call("GET", f"/api/v1/attachments/{att_id}",
|
|
headers={"Authorization": "Bearer " + token})
|
|
if code == 200 and att["status"] == "ready":
|
|
break
|
|
if code == 200 and att["status"] == "failed":
|
|
raise AssertionError(f"failed: {att.get('error_code')}")
|
|
time.sleep(0.5)
|
|
else:
|
|
raise AssertionError("not ready in 60s")
|
|
|
|
variants_before = att["variants"]
|
|
print(f"ready: {len(variants_before)} variants")
|
|
|
|
# 4. Повторная доставка: publish тот же job в broker
|
|
import subprocess
|
|
# job_id из БД
|
|
result = subprocess.run(
|
|
["docker", "compose", "--env-file", ".env", "exec", "-T", "postgres",
|
|
"psql", "-U", "messenger", "-d", "messenger", "-t", "-A",
|
|
"-c", f"SELECT job_id FROM jobs WHERE attachment_id = '{att_id}' LIMIT 1"],
|
|
capture_output=True, text=True, cwd="/home/user/projects/lab5/mtusi2026lab5",
|
|
)
|
|
job_id = result.stdout.strip()
|
|
assert job_id, f"job_id not found: {result.stderr}"
|
|
print(f"job_id: {job_id}")
|
|
|
|
# Опубликовать тот же job через worker (pika)
|
|
pub_result = subprocess.run(
|
|
["docker", "compose", "--env-file", ".env", "exec", "-T", "worker",
|
|
"python3", "-c", f"""
|
|
import os, json, pika
|
|
params = pika.URLParameters(os.environ['BROKER_URL'])
|
|
conn = pika.BlockingConnection(params)
|
|
ch = conn.channel()
|
|
ch.basic_publish('', 'attachment.process.v1', json.dumps({{
|
|
'schema_version': 1, 'job_id': '{job_id}', 'type': 'attachment.process.v1',
|
|
'attachment_id': '{att_id}', 'pipeline_version': 1, 'attempt': 1,
|
|
'created_at': '2026-01-01T00:00:00Z'
|
|
}}))
|
|
conn.close()
|
|
print('published')
|
|
"""],
|
|
capture_output=True, text=True, cwd="/home/user/projects/lab5/mtusi2026lab5",
|
|
)
|
|
print(f"replay publish: {pub_result.stdout.strip() or pub_result.stderr.strip()}")
|
|
|
|
# 5. Ждём 10 сек, проверяем variants
|
|
time.sleep(10)
|
|
code, att_after = call("GET", f"/api/v1/attachments/{att_id}",
|
|
headers={"Authorization": "Bearer " + token})
|
|
assert code == 200, f"get after failed: {code}"
|
|
variants_after = att_after["variants"]
|
|
assert variants_after == variants_before, \
|
|
f"variants changed: {len(variants_before)} -> {len(variants_after)}"
|
|
print(f"after replay: {len(variants_after)} variants (unchanged)")
|
|
|
|
# 6. Проверяем S3 — количество объектов не изменилось (root, mc ls)
|
|
for prefix, ext in (("originals", "png"), ("thumbnails", "jpg"),
|
|
("crops", "jpg"), ("optimized", "webp")):
|
|
result = subprocess.run(
|
|
["docker", "compose", "--env-file", ".env", "run", "--rm",
|
|
"--entrypoint", "sh", "s3-init", "-c",
|
|
f"mc alias set local http://s3:9000 $MINIO_ROOT_USER $MINIO_ROOT_PASSWORD >/dev/null && "
|
|
f"mc stat local/messenger-attachments/{prefix}/{att_id}.{ext} 2>&1 | head -1"],
|
|
capture_output=True, text=True, cwd="/home/user/projects/lab5/mtusi2026lab5",
|
|
)
|
|
out = (result.stdout + result.stderr).strip()
|
|
assert "Name" in out or "Size" in out, f"missing {prefix}: {out}"
|
|
print(f" {prefix}/{att_id}.{ext} exists")
|
|
|
|
print("PASS: idempotent replay — variants unchanged, no duplicates")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
from pathlib import Path
|
|
main() |