158 lines
6.3 KiB
Python
158 lines
6.3 KiB
Python
#!/usr/bin/env python3
|
||
"""Сценарий согласованности: pending-строка + объект после отказа S3/БД.
|
||
|
||
Поднимает одноразовый API-контейнер с ATTACHMENT_FAULT_MODE=after_s3_put,
|
||
заставляет его загрузить файл (S3 PUT прошёл, COMMIT в PostgreSQL — нет),
|
||
затем запускает reconciler в dry-run и apply. Проверяет, что:
|
||
* свежий pending-мусор не удаляется при большом grace;
|
||
* после grace удаляются и объект, и pending-строка;
|
||
* готовое (используемое) вложение не удаляется;
|
||
* повторный apply идемпотентен.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
import uuid
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
sys.path.insert(0, str(ROOT / "tests"))
|
||
from client import Client, Failure # noqa: E402
|
||
|
||
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||
STACK = os.environ.get("STACK_NAME", "lab4")
|
||
IMAGE = os.environ.get("API_IMAGE", "mtusi-messenger-lab4:4.0.0")
|
||
NETWORK = STACK + "_backend"
|
||
FAULT_API = "lab4-reconcile-fault"
|
||
FAULT_PORT = 18099
|
||
|
||
|
||
def docker(*args: str, check: bool = True) -> subprocess.CompletedProcess:
|
||
return subprocess.run(["docker", *args], check=check, capture_output=True, text=True)
|
||
|
||
|
||
def common_args() -> list[str]:
|
||
secrets = str(ROOT / "secrets")
|
||
return [
|
||
"--user", "0",
|
||
"--network", NETWORK,
|
||
"-v", secrets + ":/run/secrets:ro",
|
||
"-e", "APP_ENV=lab",
|
||
"-e", "APP_PORT=8080",
|
||
"-e", "SESSION_TTL_SECONDS=3600",
|
||
"-e", "DATABASE_URL_FILE=/run/secrets/database_url",
|
||
"-e", "CACHE_URL_FILE=/run/secrets/cache_url",
|
||
"-e", "CURSOR_SECRET_FILE=/run/secrets/cursor_secret",
|
||
"-e", "S3_ENDPOINT=http://minio:9000",
|
||
"-e", "S3_REGION=us-east-1",
|
||
"-e", "S3_BUCKET=messenger-attachments",
|
||
"-e", "S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id",
|
||
"-e", "S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key",
|
||
]
|
||
|
||
|
||
def wait_http(url: str, deadline_seconds: float = 60.0) -> None:
|
||
deadline = time.monotonic() + deadline_seconds
|
||
last = "no attempt"
|
||
while time.monotonic() < deadline:
|
||
try:
|
||
with urllib.request.urlopen(url, timeout=3) as response:
|
||
if response.status == 200:
|
||
return
|
||
except Exception as exc: # noqa: BLE001 - diagnostics only
|
||
last = type(exc).__name__
|
||
time.sleep(0.5)
|
||
raise SystemExit("fault API did not become ready: " + last)
|
||
|
||
|
||
def reconcile(*mode: str) -> dict:
|
||
name = "lab4-reconcile-" + uuid.uuid4().hex[:10]
|
||
try:
|
||
docker("run", "-d", "--name", name, *common_args(), IMAGE, "python", "-m", "messenger.reconcile", *mode)
|
||
code = int(docker("wait", name).stdout.strip() or "1")
|
||
logs = docker("logs", name).stdout
|
||
finally:
|
||
docker("rm", "-f", name, check=False)
|
||
start, end = logs.find("{"), logs.rfind("}")
|
||
if start < 0 or end < start:
|
||
raise SystemExit("reconcile did not print JSON: " + logs[-500:])
|
||
report = json.loads(logs[start:end + 1])
|
||
report["exit_code"] = code
|
||
return report
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description="Проверка reconciler")
|
||
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
|
||
parser.add_argument("--output", default="evidence/reconcile.json")
|
||
args = parser.parse_args()
|
||
|
||
api = Client(args.base_url, None, timeout=10)
|
||
alice, bob, _eve, chat = api.bootstrap()
|
||
used, used_content = api.attachment(alice, chat)
|
||
report: dict = {"used_attachment": used["id"]}
|
||
|
||
docker("run", "-d", "--name", FAULT_API, "-p", "18099:8080", *common_args(),
|
||
"-e", "ATTACHMENT_FAULT_MODE=after_s3_put", IMAGE, "python", "-m", "messenger")
|
||
try:
|
||
wait_http("http://127.0.0.1:18099/health/ready")
|
||
fault_client = Client("http://127.0.0.1:18099", None, timeout=20)
|
||
pending = fault_client.call(
|
||
"POST",
|
||
"/api/v1/chats/%s/attachments?filename=pending.png" % chat["id"],
|
||
503,
|
||
actor=alice,
|
||
raw=PNG,
|
||
headers={"Content-Type": "image/png"},
|
||
)
|
||
report["fault_upload"] = {
|
||
"status": pending["status"],
|
||
"error": pending["json"]["error"]["code"],
|
||
"instance": pending["headers"].get("X-Instance-Id"),
|
||
}
|
||
finally:
|
||
docker("rm", "-f", FAULT_API, check=False)
|
||
|
||
# Свежий pending-мусор должен пережить большой grace.
|
||
dry = reconcile("--dry-run", "--grace-seconds", "3600")
|
||
report["dry_run_fresh"] = {
|
||
"would_delete_objects": dry.get("would_delete_objects"),
|
||
"would_delete_rows": dry.get("would_delete_rows"),
|
||
"fresh_kept": any(item.get("action") == "keep_fresh" for item in dry.get("plan", [])),
|
||
}
|
||
time.sleep(2.0)
|
||
applied = reconcile("--apply", "--grace-seconds", "1")
|
||
report["apply"] = {
|
||
"deleted_objects": applied.get("deleted_objects"),
|
||
"deleted_rows": applied.get("deleted_rows"),
|
||
"missing_ready": len(applied.get("missing_ready", [])),
|
||
}
|
||
again = reconcile("--apply", "--grace-seconds", "1")
|
||
report["apply_again"] = {
|
||
"deleted_objects": again.get("deleted_objects"),
|
||
"deleted_rows": again.get("deleted_rows"),
|
||
}
|
||
# Готовое вложение не тронуто и скачивается байт-в-байт.
|
||
try:
|
||
downloaded = api.call("GET", "/api/v1/attachments/" + used["id"] + "/content", actor=bob)["bytes"]
|
||
report["used_download_matches"] = downloaded == used_content
|
||
except Failure as exc:
|
||
report["used_download_matches"] = False
|
||
report["used_download_error"] = str(exc)
|
||
output = Path(args.output)
|
||
output.parent.mkdir(parents=True, exist_ok=True)
|
||
output.write_text(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
|
||
print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
|
||
return 0 if report.get("used_download_matches") and report["apply"]["deleted_rows"] >= 1 else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|