This commit is contained in:
2026-11-20 20:11:39 +03:00
parent 276dbdad8a
commit b4d667532f
116 changed files with 11777 additions and 40 deletions
+10
View File
@@ -0,0 +1,10 @@
# Test-only runner: Python + Docker CLI + curl for failure probes that control
# the Swarm stack while talking to its internal network.
FROM docker:27-cli AS cli
FROM python:3.11.9-slim-bookworm
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
COPY --from=cli /usr/local/bin/docker /usr/local/bin/docker
WORKDIR /repo
ENTRYPOINT ["python"]
+31
View File
@@ -0,0 +1,31 @@
# Собственные проверки лабораторной 5
Публичный клиент из `tests/` переиспользуется, поэтому проверки идут через
контракт и LB, а не через внутренние функции приложения.
```sh
make student-test BASE_URL=http://127.0.0.1:8080
make track2 BASE_URL=http://127.0.0.1:8080
python3 student-tests/worker_restart.py
python3 student-tests/outbox_gap.py
python3 student-tests/replay_dlq.py
python3 student-tests/staging_cleanup.py
```
| Файл | Что проверяет |
| --- | --- |
| `harness.py` | клиент публичного `tests/client.py`, сбор `X-Instance-Id`, история, ожидание готовности |
| `test_lab3.py` | lab3-инварианты: ≥2 реплики, конкурентная идемпотентность, 409 на другое тело |
| `test_lab5.py` | upload 202 queued, ready через polling, thumbnail 256×160, crop 128×128, optimized WebP, checksums, 413/415/400/404, чужие вложения, queued attachment в сообщении |
| `job_control.py` | Docker/admin-обвязка: scale, restart, `messenger.admin`, листинг S3, RabbitMQ queue stats |
| `worker_restart.py` | worker остановлен → 202 → content 409 → API restart → worker старт → ready; broker restart с volume |
| `outbox_gap.py` | relay остановлен: COMMIT+202 без publish; запуск relay завершает ту же job |
| `replay_dlq.py` | постоянная ошибка → failed + DLQ; явный replay создаёт новый job; replay ready отклоняется |
| `staging_cleanup.py` | staging существует до commit и удаляется после ready; final prefix содержит original + 3 варианта |
| `retry_probe.py` | 5 transient ошибок → backoff/jitter → failed/retry_exhausted + DLQ; replay → ready |
| `image_contract_probe.py` | EXIF orientation, alpha→white, удаление EXIF, реальные размеры JPEG/WebP |
| `idempotency_track.py` | трек 5.2: duplicate, reorder версий, crash до/после side effect, stale v1 после v2, lease/STOP worker; пишет `evidence/track2.json` |
Docker-пробы требуют запущенного Swarm-стенда и доступа к Docker socket.
Они меняют только сервисы `${STACK_NAME}_*` (по умолчанию `lab5`) и не удаляют
volumes. В конце track2 возвращает worker к 1 реплике. Токены не печатаются.
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+74
View File
@@ -0,0 +1,74 @@
"""Общая обвязка собственных проверок лабораторной 4.
Публичный клиент из tests/ переиспользуется, а не копируется: он уже проверяет
схему ответа, X-Request-Id, X-Instance-Id, конверт ошибки и challenge. Здесь
живут только помощники, специфичные для балансировки и идемпотентности.
"""
from __future__ import annotations
import os
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TESTS = ROOT / "tests"
HERE = Path(__file__).resolve().parent
for candidate in (str(TESTS), str(HERE)):
if candidate not in sys.path:
sys.path.insert(0, candidate)
from client import Client, Failure # noqa: E402
DEFAULT_BASE_URL = "http://127.0.0.1:8080"
DEFAULT_TIMEOUT = 10.0
def client(timeout: float = DEFAULT_TIMEOUT) -> Client:
return Client(os.environ.get("BASE_URL", DEFAULT_BASE_URL), None, timeout)
def instance_ids(api: Client, actor: dict, count: int = 40) -> set[str]:
"""Собирает X-Instance-Id разных ответов через LB, не доверяя одному запросу."""
seen: set[str] = set()
for _ in range(count):
seen.add(
api.call("GET", "/api/v1/users/me", actor=actor, schema="User")["headers"][
"X-Instance-Id"
]
)
return seen
def wait_ready(timeout: float = 120.0) -> None:
api = client(timeout=5)
deadline = time.monotonic() + timeout
last = "no attempts"
while time.monotonic() < deadline:
try:
api.call("GET", "/health/ready", schema="Health")
return
except (Failure, OSError) as exc:
last = str(exc)
time.sleep(0.5)
raise Failure("stand did not become ready within %.0fs: %s" % (timeout, last))
def history(api: Client, actor: dict, chat_id: str) -> list[dict]:
items: list[dict] = []
cursor = None
for _ in range(1000):
path = "/api/v1/chats/%s/messages?limit=100" % chat_id
if cursor is not None:
path += "&cursor=" + cursor
page = api.call("GET", path, actor=actor, schema="MessagePage")["json"]
items.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return items
raise Failure("history pagination exceeded safety bound")
def unique_key() -> str:
return uuid.uuid4().hex
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Печатает обезличенную сводку конкурентного повтора одного Idempotency-Key."""
from __future__ import annotations
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import harness
def main() -> int:
api = harness.client()
alice, bob, _, chat = api.bootstrap()
key = uuid4().hex
text = "probe-" + uuid4().hex
workers = 32
barrier = threading.Barrier(workers)
def worker(_: int) -> dict:
local = harness.client(10)
barrier.wait()
return local.message(alice, chat, text, key=key)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(worker, range(workers)))
elapsed = time.monotonic() - started
bodies = [r["json"] for r in responses]
instances = sorted({r["headers"]["X-Instance-Id"] for r in responses})
messages = [m for m in harness.history(api, bob, chat["id"]) if m["text"] == text]
summary = {
"concurrent_requests": workers,
"elapsed_seconds": round(elapsed, 3),
"statuses": sorted({r["status"] for r in responses}),
"distinct_instances": instances,
"distinct_message_ids": len({b["id"] for b in bodies}),
"history_matches": len(messages),
"all_responses_identical": all(b == bodies[0] for b in bodies),
}
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 0 if (
summary["statuses"] == [201]
and summary["distinct_message_ids"] == 1
and summary["history_matches"] == 1
and len(instances) >= 2
) else 1
if __name__ == "__main__":
raise SystemExit(main())
+330
View File
@@ -0,0 +1,330 @@
#!/usr/bin/env python3
"""Track 5.2: доказанная идемпотентность версионированного pipeline.
Гипотеза: at-least-once доставка + детерминированные ключи эффекта
(attachment_id, pipeline_version, variant) + lease-guarded commit дают
эффект «ровно один раз» для каждой принятой (202) задачи при дубле, reorder,
crash до/после side effect и устаревшей job после новой версии, хотя доставка
остаётся at-least-once (не exactly-once).
Сценарии выполняются автоматически на живом Swarm-стенде; результаты и
инварианты пишутся в evidence/track2.json. Скрипт не печатает токены.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
for candidate in (str(HERE), str(ROOT / "tests")):
if candidate not in sys.path:
sys.path.insert(0, candidate)
import job_control as jc # noqa: E402
from client import Client # noqa: E402
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
EXPECTED_VARIANTS = 3
EXPECTED_OBJECTS = 4
def now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
def job_for(report: dict, pipeline_version: int) -> dict | None:
for job in report.get("jobs", []):
if job["pipeline_version"] == pipeline_version:
return job
return None
def wait_all_terminal(attachment_id: str, timeout: float = 120.0) -> dict:
deadline = time.monotonic() + timeout
report = jc.admin_json("show", "--attachment", attachment_id)
while time.monotonic() < deadline:
report = jc.admin_json("show", "--attachment", attachment_id)
states = [job["state"] for job in report.get("jobs", [])]
attachment_state = (report.get("attachment") or {}).get("status")
if all(state in ("ready", "failed", "superseded") for state in states) and attachment_state in (
"ready",
"failed",
):
return report
time.sleep(0.25)
raise jc.ProbeError("jobs did not settle: %s" % report)
def accepted_upload(api: Client, actor: dict, chat: dict) -> tuple[dict, dict]:
attachment = jc.upload(api, actor, chat, PNG)
report = jc.wait_job(api, actor, attachment["id"], "queued", timeout=30)
job = report["jobs"][0]
return attachment, job
def final_objects(attachment_id: str) -> list[str]:
return jc.list_objects("final/%s/" % attachment_id)
def result_record(name: str, hypothesis: str, observed: dict, invariants: dict) -> dict:
return {
"scenario": name,
"hypothesis": hypothesis,
"observed": observed,
"invariants": invariants,
"passed": all(invariants.values()),
}
def scenario_duplicate(api: Client, actor: dict, chat: dict, started: str) -> dict:
jc.scale("worker", 0)
jc.wait_service("worker", 0)
attachment, job = accepted_upload(api, actor, chat)
# Original already published by relay; добавляем три копии того же сообщения.
time.sleep(1.0)
outbox_before = jc.admin_json("show", "--attachment", attachment["id"])
jc.admin_json("duplicate", "--job", job["id"], "--count", "3")
jc.scale("worker", 1)
jc.wait_service("worker", 1)
ready = jc.wait_attachment(api, actor, attachment["id"], "ready", timeout=120)
report = jc.admin_json("show", "--attachment", attachment["id"])
time.sleep(1.0)
events = [
event
for event in jc.service_logs("worker", since="10m")
if event.get("job_id") == job["id"] and event.get("ts", "") >= started
]
claimed = sum(1 for event in events if event.get("event") == "job_claimed")
noops = sum(1 for event in events if event.get("event") == "delivery_noop")
objects = final_objects(attachment["id"])
variants = report["attachment"]["variants"]
return result_record(
"duplicate_delivery",
"Повторная доставка не создаёт второй набор вариантов/объектов.",
{
"attachment_id": attachment["id"],
"job_id": job["id"],
"outbox_published_before_duplicate": [
row["published_at"] is not None for row in outbox_before["outbox"]
],
"worker_events": {"job_claimed": claimed, "delivery_noop": noops},
"job_attempts": report["jobs"][0]["attempts"],
"variant_rows": len(variants),
"objects_final_prefix": objects,
"status": ready["status"],
},
{
"one_effect": len(variants) == EXPECTED_VARIANTS and len(objects) == EXPECTED_OBJECTS,
"duplicates_were_delivered": claimed + noops >= 1,
"status_ready": ready["status"] == "ready" and ready["error_code"] is None,
},
)
def scenario_reorder(api: Client, actor: dict, chat: dict, started: str) -> dict:
jc.scale("worker", 0)
jc.wait_service("worker", 0)
attachment, v2_job = accepted_upload(api, actor, chat)
v1_job = jc.admin_json("enqueue", "--attachment", attachment["id"], "--pipeline-version", "1")
jc.scale("worker", 1)
jc.wait_service("worker", 1)
report = wait_all_terminal(attachment["id"], timeout=150)
objects = final_objects(attachment["id"])
variants = report["attachment"]["variants"]
v1_state = job_for(report, 1)["state"]
return result_record(
"reorder_versions",
"Порядок доставки версий не влияет на результат: побеждает более новая версия.",
{
"attachment_id": attachment["id"],
"jobs": report["jobs"],
"attachment_pipeline_version": report["attachment"]["pipeline_version"],
"variant_names": [item["name"] for item in variants],
"v1_state": v1_state,
"objects_final_prefix": objects,
},
{
"final_version_is_2": report["attachment"]["pipeline_version"] == 2,
"visible_variants_are_v2": len(variants) == EXPECTED_VARIANTS,
"v2_objects_present": any("/v2/" in key for key in objects),
"attachment_ready": report["attachment"]["status"] == "ready",
},
)
def scenario_crash(api: Client, actor: dict, chat: dict, kind: str, label: str) -> dict:
jc.scale("worker", 0)
jc.wait_service("worker", 0)
attachment, job = accepted_upload(api, actor, chat)
jc.admin_json("fault", "--kind", kind, "--count", "1")
jc.scale("worker", 1)
jc.wait_service("worker", 1)
ready = jc.wait_attachment(api, actor, attachment["id"], "ready", timeout=180)
report = jc.admin_json("show", "--attachment", attachment["id"])
variants = report["attachment"]["variants"]
objects = final_objects(attachment["id"])
events = [
event
for event in jc.service_logs("worker", since="20m")
if event.get("job_id") == job["id"] and event.get("event") == "job_claimed"
]
return result_record(
label,
"Crash в окне отказа не теряет принятую работу и не размножает эффект.",
{
"attachment_id": attachment["id"],
"job_id": job["id"],
"fault": kind,
"job_attempts": report["jobs"][0]["attempts"],
"claims_observed": len(events),
"job_state": report["jobs"][0]["state"],
"variant_rows": len(variants),
"objects_final_prefix": objects,
"status": ready["status"],
},
{
"recovered_to_ready": ready["status"] == "ready" and ready["error_code"] is None,
"retried": report["jobs"][0]["attempts"] == 2,
"one_effect": len(variants) == EXPECTED_VARIANTS and len(objects) == EXPECTED_OBJECTS,
},
)
def scenario_stale(api: Client, actor: dict, chat: dict, started: str) -> dict:
attachment = jc.upload(api, actor, chat, PNG)
ready = jc.wait_attachment(api, actor, attachment["id"], "ready", timeout=120)
before = jc.admin_json("show", "--attachment", attachment["id"])
before_variants = [(item["name"], item["sha256"]) for item in before["attachment"]["variants"]]
before_objects = final_objects(attachment["id"])
v1_job = jc.admin_json("enqueue", "--attachment", attachment["id"], "--pipeline-version", "1")
report = wait_all_terminal(attachment["id"], timeout=90)
after_variants = [(item["name"], item["sha256"]) for item in report["attachment"]["variants"]]
after_objects = final_objects(attachment["id"])
v1_state = job_for(report, 1)["state"]
return result_record(
"stale_after_newer",
"Устаревшая job не перезаписывает более новую опубликованную версию.",
{
"attachment_id": attachment["id"],
"stale_job_id": v1_job["job_id"],
"stale_job_state": v1_state,
"attachment_pipeline_version": report["attachment"]["pipeline_version"],
"variants_before": before_variants,
"variants_after": after_variants,
"objects_before": before_objects,
"objects_after": after_objects,
},
{
"stale_job_superseded": v1_state == "superseded",
"version_not_downgraded": report["attachment"]["pipeline_version"] == 2,
"variants_unchanged": before_variants == after_variants,
"objects_unchanged": before_objects == after_objects,
"still_ready": ready["status"] == "ready" and report["attachment"]["status"] == "ready",
},
)
def scenario_lease(api: Client, actor: dict, chat: dict, started: str) -> dict:
# Fault «зависший worker»: lease не продлевается на время сна. Второй
# worker дождётся истечения lease, заберёт job и завершит её; старый attempt
# проснётся и получит lease_lost при commit.
jc.scale("worker", 0)
jc.wait_service("worker", 0)
attachment = jc.upload(api, actor, chat, PNG)
job = jc.wait_job(api, actor, attachment["id"], "queued", timeout=30)["jobs"][0]
jc.admin_json("fault", "--kind", "stuck_before_commit", "--count", "1")
jc.scale("worker", 2)
jc.wait_service("worker", 2)
processing = jc.wait_job(api, actor, attachment["id"], "processing", timeout=30)
lease_seconds = 15.0
ready = jc.wait_attachment(api, actor, attachment["id"], "ready", timeout=180)
time.sleep(5.0)
final = jc.admin_json("show", "--attachment", attachment["id"])
variants = final["attachment"]["variants"]
objects = final_objects(attachment["id"])
events = [
event
for event in jc.service_logs("worker", since="15m")
if event.get("job_id") == job["id"] and event.get("ts", "") >= started
]
stale_commits = sum(
1 for event in events if event.get("event") == "job_complete_not_applied"
)
return result_record(
"stuck_worker_lease",
"Зависший worker не удерживает job навсегда: lease истекает, работу "
"завершает другой worker, старый commit отклоняется.",
{
"attachment_id": attachment["id"],
"job_id": job["id"],
"fault": "stuck_before_commit",
"lease_seconds": lease_seconds,
"observed_processing": bool(processing),
"job_attempts": final["jobs"][0]["attempts"],
"job_state": final["jobs"][0]["state"],
"variant_rows": len(variants),
"objects_final_prefix": objects,
"stale_commit_rejections_in_logs": stale_commits,
},
{
"recovered_to_ready": ready["status"] == "ready",
"one_effect": len(variants) == EXPECTED_VARIANTS and len(objects) == EXPECTED_OBJECTS,
"attempts_ge_2": final["jobs"][0]["attempts"] >= 2,
"stale_commit_was_rejected_or_not_observed": stale_commits <= 1,
},
)
def main() -> int:
api = jc.client(timeout=20)
api.call("GET", "/health/ready", schema="Health")
alice, bob, eve, chat = api.bootstrap()
started = now()
results = []
results.append(scenario_duplicate(api, alice, chat, started))
results.append(scenario_reorder(api, alice, chat, started))
results.append(scenario_crash(api, alice, chat, "crash_before_objects", "crash_before_side_effect"))
results.append(scenario_crash(api, alice, chat, "crash_after_objects", "crash_after_side_effect_before_ack"))
results.append(scenario_stale(api, alice, chat, started))
results.append(scenario_lease(api, alice, chat, started))
jc.scale("worker", 1)
jc.wait_service("worker", 1)
summary = {
"track": "5.2 proven idempotent pipeline",
"started_at": started,
"finished_at": now(),
"hypothesis": (
"At-least-once delivery plus deterministic effect keys and lease-guarded "
"versioned commits yields exactly-once effects for accepted jobs; it does "
"not yield exactly-once delivery."
),
"stand": {
"base_url": jc.BASE_URL,
"stack": jc.STACK,
"pipeline_version": 2,
"pipeline_v1": "original+thumbnail",
"pipeline_v2": "original+thumbnail+crop+optimized WebP",
},
"scenarios": results,
"all_passed": all(item["passed"] for item in results),
"not_exactly_once": (
"Broker redelivery and crash windows were observed; duplicates are normal. "
"Exactly-once delivery would require an atomic broker-ack + DB-commit "
"transaction, which is not available across RabbitMQ and PostgreSQL."
),
}
output = ROOT / "evidence" / "track2.json"
output.write_text(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True))
print("evidence:", output)
return 0 if summary["all_passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Контракт изображений: EXIF orientation, alpha→white, метаданные удалены."""
from __future__ import annotations
import io
import json
import sys
from pathlib import Path
from PIL import Image
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
for candidate in (str(HERE), str(ROOT / "tests")):
if candidate not in sys.path:
sys.path.insert(0, candidate)
from client import Client, arguments # noqa: E402
def png_rgba() -> bytes:
image = Image.new("RGBA", (100, 50), (255, 0, 0, 255))
for x in range(50, 100):
for y in range(50):
image.putpixel((x, y), (0, 0, 255, 0))
buffer = io.BytesIO()
image.save(buffer, format="PNG")
return buffer.getvalue()
def jpeg_with_exif() -> bytes:
image = Image.new("RGB", (320, 200), (10, 120, 220))
exif = Image.Exif()
exif[274] = 6 # Orientation: rotate 90 CW
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=90, exif=exif)
return buffer.getvalue()
def upload(api: Client, actor: dict, chat: dict, content: bytes, filename: str, content_type: str) -> dict:
from urllib.parse import quote
return api.call(
"POST",
"/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe="")),
202,
actor=actor,
raw=content,
headers={"Content-Type": content_type},
schema="Attachment",
)["json"]
def download(api: Client, actor: dict, attachment_id: str, variant: str) -> bytes:
return api.call(
"GET",
"/api/v1/attachments/" + attachment_id + "/content?variant=" + variant,
actor=actor,
)["bytes"]
def main() -> int:
args = arguments("Image contract probe")
api = Client(args.base_url, args.ca_file, 30)
alice, bob, eve, chat = api.bootstrap()
rgba = upload(api, alice, chat, png_rgba(), "alpha.png", "image/png")
rgba_ready = api.wait_ready(bob, rgba)
thumb = Image.open(io.BytesIO(download(api, bob, rgba["id"], "thumbnail"))).convert("RGB")
thumb_pixels = [thumb.getpixel((90, 10)), thumb.getpixel((90, 40))]
exif = upload(api, alice, chat, jpeg_with_exif(), "oriented.jpg", "image/jpeg")
exif_ready = api.wait_ready(bob, exif)
optimized = Image.open(io.BytesIO(download(api, bob, exif["id"], "optimized")))
thumbnail = Image.open(io.BytesIO(download(api, bob, exif["id"], "thumbnail")))
evidence = {
"scenario": "image_contract",
"alpha": {
"attachment_id": rgba["id"],
"status": rgba_ready["status"],
"thumbnail_size": thumb.size,
"alpha_region_rgb": thumb_pixels,
"alpha_composited_on_white": all(min(pixel) >= 245 for pixel in thumb_pixels),
},
"exif_orientation": {
"attachment_id": exif["id"],
"source_size": [320, 200],
"oriented_size": [200, 320],
"thumbnail_size": list(thumbnail.size),
"optimized_size": list(optimized.size),
"thumbnail_exif_entries": len(getattr(thumbnail, "getexif", lambda: {})()),
"optimized_exif_entries": len(getattr(optimized, "getexif", lambda: {})()),
"orientation_applied": thumbnail.size == (160, 256),
"metadata_removed": len(getattr(thumbnail, "getexif", lambda: {})()) == 0
and len(getattr(optimized, "getexif", lambda: {})()) == 0,
},
"variants": {
"thumbnail": "image/jpeg 160x256 for rotated 200x320",
"crop": "image/jpeg centered 128x128",
"optimized": "image/webp fit 1280x1280 without upscale",
},
}
evidence["passed"] = (
evidence["alpha"]["alpha_composited_on_white"]
and evidence["exif_orientation"]["orientation_applied"]
and evidence["exif_orientation"]["metadata_removed"]
)
output = ROOT / "evidence" / "image-contract.json"
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True))
return 0 if evidence["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())
+245
View File
@@ -0,0 +1,245 @@
"""Docker/admin helpers for lab5 failure probes (host-side, no secrets printed).
Requires the deployed Swarm stack and a Docker socket. All commands operate only
on services named ${STACK_NAME}_*; object listings use MinIO's own mc with the
read-only root credentials already mounted in the container, and never print them.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TESTS = ROOT / "tests"
for candidate in (str(TESTS), str(Path(__file__).resolve().parent)):
if candidate not in sys.path:
sys.path.insert(0, candidate)
from client import Client, Failure # noqa: E402
STACK = os.environ.get("STACK_NAME", "lab5")
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
class ProbeError(RuntimeError):
pass
def run(args: list[str], *, check: bool = True, timeout: float = 120.0) -> subprocess.CompletedProcess:
result = subprocess.run(args, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout)
if check and result.returncode != 0:
raise ProbeError("%s failed: %s" % (" ".join(args[:4]), (result.stderr or result.stdout).strip()[:500]))
return result
def docker(*args: str, check: bool = True, timeout: float = 120.0) -> str:
return run(["docker", *args], check=check, timeout=timeout).stdout.strip()
def api_container() -> str:
value = docker("ps", "-q", "-f", "name=%s_api" % STACK, "-f", "status=running")
containers = [line for line in value.splitlines() if line.strip()]
if not containers:
raise ProbeError("no running %s_api container" % STACK)
return containers[0]
def admin_json(*args: str) -> dict:
output = docker("exec", api_container(), "python", "-m", "messenger.admin", *args, timeout=120)
return json.loads(output)
def upload(api: Client, actor: dict, chat: dict, content: bytes, filename: str = "probe.png") -> dict:
from urllib.parse import quote
return api.call(
"POST",
"/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe="")),
202,
actor=actor,
raw=content,
headers={"Content-Type": "image/png"},
schema="Attachment",
)["json"]
def wait_attachment(api: Client, actor: dict, attachment_id: str, status: str, timeout: float = 90.0) -> dict:
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
last = api.call("GET", "/api/v1/attachments/" + attachment_id, actor=actor, schema="Attachment")["json"]
if last["status"] == status:
return last
if last["status"] == "failed" and status != "failed":
raise ProbeError("attachment failed with %s while waiting for %s" % (last["error_code"], status))
time.sleep(0.25)
raise ProbeError("attachment did not reach %s: %s" % (status, last))
def wait_job(api: Client, actor: dict, attachment_id: str, state: str, timeout: float = 90.0) -> dict:
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
report = admin_json("show", "--attachment", attachment_id)
states = [job["state"] for job in report.get("jobs", [])]
if state in states:
return report
last = states
time.sleep(0.25)
raise ProbeError("job did not reach %s: %s" % (state, last))
def scale(service: str, replicas: int) -> None:
docker("service", "scale", "%s_%s=%d" % (STACK, service, replicas), timeout=180)
def wait_service(service: str, replicas: int, timeout: float = 180.0) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
tasks = docker(
"service", "ps", "-q", "%s_%s" % (STACK, service), "--filter", "desired-state=running"
)
if len([line for line in tasks.splitlines() if line.strip()]) >= replicas:
return
time.sleep(1.0)
raise ProbeError("%s did not reach %d running tasks" % (service, replicas))
def restart(service: str, timeout: float = 240.0) -> None:
docker("service", "update", "--force", "%s_%s" % (STACK, service), timeout=timeout)
def minio_container() -> str:
value = docker("ps", "-q", "-f", "name=%s_minio" % STACK, "-f", "status=running")
containers = [line for line in value.splitlines() if line.strip()]
if not containers:
raise ProbeError("minio container not found")
return containers[0]
def rabbitmq_container() -> str:
value = docker("ps", "-q", "-f", "name=%s_rabbitmq" % STACK, "-f", "status=running")
containers = [line for line in value.splitlines() if line.strip()]
if not containers:
raise ProbeError("rabbitmq container not found")
return containers[0]
def list_objects(prefix: str) -> list[str]:
"""Ключи S3 через admin CLI внутри API (без печати credentials)."""
items = admin_json("objects", "--prefix", prefix)
return [item["key"] for item in items]
def wait_queue_messages(queue: str, minimum: int, timeout: float = 60.0) -> dict:
deadline = time.monotonic() + timeout
stats = {}
while time.monotonic() < deadline:
stats = queue_stats()
if stats.get(queue, {}).get("messages", 0) >= minimum:
return stats
time.sleep(0.5)
raise ProbeError("queue %s did not reach %d messages: %s" % (queue, minimum, stats))
def queue_stats() -> dict:
output = docker(
"exec", rabbitmq_container(), "rabbitmqctl", "list_queues", "name", "messages", "messages_ready", "messages_unacknowledged"
)
stats = {}
for line in output.splitlines():
parts = line.split()
if len(parts) >= 4 and parts[0] not in ("name", "Timeout:"):
try:
stats[parts[0]] = {
"messages": int(parts[1]),
"ready": int(parts[2]),
"unacknowledged": int(parts[3]),
}
except ValueError:
continue
return stats
def worker_container_for(hostname: str) -> str | None:
containers = [
line for line in docker("ps", "-q", "-f", "name=%s_worker" % STACK).splitlines() if line.strip()
]
for container in containers:
value = docker("inspect", "-f", "{{.Config.Hostname}}", container, check=False)
if value.strip() == hostname:
return container
return None
def pause_container(container: str) -> None:
run(["docker", "kill", "--signal=STOP", container], check=False)
def resume_container(container: str) -> None:
# Swarm мог заменить task, пока контейнер был остановлен; это не ошибка пробы.
run(["docker", "kill", "--signal=CONT", container], check=False)
def wait_ready(timeout: float = 180.0) -> None:
api = Client(BASE_URL, None, 5)
deadline = time.monotonic() + timeout
last = "not attempted"
while time.monotonic() < deadline:
try:
api.call("GET", "/health/ready", schema="Health")
return
except (Failure, OSError) as exc:
last = str(exc)
time.sleep(0.5)
raise ProbeError("stand did not become ready: %s" % last)
def wait_broker(timeout: float = 180.0) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run(
["docker", "exec", rabbitmq_container(), "rabbitmqctl", "status"],
check=False,
timeout=20,
)
if result.returncode == 0:
return
time.sleep(1.0)
raise ProbeError("rabbitmq did not become ready")
def service_logs(service: str, since: str = "20m") -> list[dict]:
"""JSON-логи всех task-контейнеров сервиса (включая завершившиеся crash-и)."""
containers = [
line
for line in docker(
"ps", "-a", "-q", "-f", "name=%s_%s" % (STACK, service), check=False
).splitlines()
if line.strip()
]
events = []
for container in containers:
output = run(
["docker", "logs", "--since", since, container],
check=False,
timeout=120,
)
for line in (output.stdout + "\n" + output.stderr).splitlines():
line = line.strip()
if not line.startswith("{"):
continue
try:
events.append(json.loads(line))
except ValueError:
continue
return events
def client(timeout: float = 15.0) -> Client:
return Client(BASE_URL, None, timeout)
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""COMMIT задания без publish: relay восстанавливает намерение из outbox."""
from __future__ import annotations
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
for candidate in (str(HERE), str(ROOT / "tests")):
if candidate not in sys.path:
sys.path.insert(0, candidate)
import job_control as jc # noqa: E402
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
def main() -> int:
api = jc.client(timeout=20)
api.call("GET", "/health/ready", schema="Health")
alice, bob, eve, chat = api.bootstrap()
jc.scale("relay", 0)
jc.wait_service("relay", 0)
attachment = jc.upload(api, alice, chat, PNG)
report = jc.wait_job(api, alice, attachment["id"], "queued", timeout=30)
time.sleep(2.0)
before = jc.admin_json("show", "--attachment", attachment["id"])
pending = [row for row in before["outbox"] if row["published_at"] is None]
jc.scale("relay", 1)
jc.wait_service("relay", 1)
ready = jc.wait_attachment(api, alice, attachment["id"], "ready", timeout=120)
after = jc.admin_json("show", "--attachment", attachment["id"])
evidence = {
"started_at": None,
"scenario": "crash_between_commit_and_publish",
"attachment_id": attachment["id"],
"job_id": report["jobs"][0]["id"],
"relay_replicas_during_accept": 0,
"outbox_pending_before_relay": pending,
"status_before_relay": "queued",
"status_after_relay": ready["status"],
"job_attempts": after["jobs"][0]["attempts"],
"variants": [item["name"] for item in after["attachment"]["variants"]],
"outbox_after": after["outbox"],
"passed": (
len(pending) == 1
and ready["status"] == "ready"
and len(after["attachment"]["variants"]) == 3
),
"note": (
"API committed attachment+job+outbox and returned 202 while relay was "
"stopped. Starting relay published the exact pending outbox row and the "
"same job id completed; no second upload was needed."
),
}
output = ROOT / "evidence" / "outbox-gap.json"
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True))
return 0 if evidence["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Постоянная ошибка → failed + DLQ; явный replay → новый job и ready."""
from __future__ import annotations
import json
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
for candidate in (str(HERE), str(ROOT / "tests")):
if candidate not in sys.path:
sys.path.insert(0, candidate)
import job_control as jc # noqa: E402
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
def main() -> int:
api = jc.client(timeout=20)
api.call("GET", "/health/ready", schema="Health")
alice, bob, eve, chat = api.bootstrap()
jc.scale("worker", 0)
jc.wait_service("worker", 0)
attachment = jc.upload(api, alice, chat, PNG)
report = jc.wait_job(api, alice, attachment["id"], "queued", timeout=30)
original_job = report["jobs"][0]["id"]
jc.admin_json("fault", "--kind", "permanent_once", "--count", "1")
jc.scale("worker", 1)
jc.wait_service("worker", 1)
failed = jc.wait_attachment(api, alice, attachment["id"], "failed", timeout=120)
failed_report = jc.admin_json("show", "--attachment", attachment["id"])
time.sleep(2.0)
queues = jc.queue_stats()
replay = jc.admin_json(
"replay",
"--job",
failed_report["jobs"][0]["id"],
"--operator",
"student",
"--reason",
"retry after transient storage fault was fixed",
)
# Replay может завершиться быстрее, чем клиент успевает увидеть queued;
# поэтому ждём терминальное ready, а не промежуточное состояние.
ready = jc.wait_attachment(api, bob, attachment["id"], "ready", timeout=120)
final = jc.admin_json("show", "--attachment", attachment["id"])
ready_job_id = replay["replay_job_id"]
refused = subprocess.run(
[
"docker",
"exec",
jc.api_container(),
"python",
"-m",
"messenger.admin",
"replay",
"--job",
ready_job_id,
"--operator",
"student",
"--reason",
"must be refused",
],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
evidence = {
"started_at": None,
"scenario": "permanent_failure_dlq_and_replay",
"attachment_id": attachment["id"],
"original_job_id": original_job,
"failed_attachment_status": failed["status"],
"failed_error_code": failed["error_code"],
"failed_job": failed_report["jobs"][0],
"queues_after_failure": queues,
"replay_job_id": replay["replay_job_id"],
"replay_job": next(
(job for job in final["jobs"] if job["id"] == replay["replay_job_id"]), None
),
"status_after_replay": ready["status"],
"final_variants": [item["name"] for item in final["attachment"]["variants"]],
"replay_of_ready_attempt": {
"return_code": refused.returncode,
"stderr": (refused.stderr or "").strip(),
"stdout": (refused.stdout or "").strip(),
},
"passed": (
failed["status"] == "failed"
and failed["error_code"] == "invalid_image"
and queues.get("attachment.dlq", {}).get("messages", 0) >= 1
and ready["status"] == "ready"
and len(final["attachment"]["variants"]) == 3
and refused.returncode != 0
),
"note": (
"The permanent fault produced failed+error_code and a DLQ message. "
"Explicit replay created a new job_id linked by replay_of; the effect "
"key stayed the same. Replaying an already ready job was refused."
),
}
output = ROOT / "evidence" / "replay-dlq.json"
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True))
return 0 if evidence["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Backoff/retry и исчерпание попыток: transient → retry, затем failed + DLQ, replay."""
from __future__ import annotations
import json
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
for candidate in (str(HERE), str(ROOT / "tests")):
if candidate not in sys.path:
sys.path.insert(0, candidate)
import job_control as jc # noqa: E402
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def main() -> int:
api = jc.client(timeout=20)
api.call("GET", "/health/ready", schema="Health")
alice, bob, eve, chat = api.bootstrap()
jc.scale("worker", 0)
jc.wait_service("worker", 0)
attachment = jc.upload(api, alice, chat, PNG)
job = jc.wait_job(api, alice, attachment["id"], "queued", timeout=30)["jobs"][0]
# Пять временных отказов: ровно столько попыток разрешено JOB_MAX_ATTEMPTS.
jc.admin_json("fault", "--kind", "transient_always", "--count", "5")
jc.scale("worker", 1)
jc.wait_service("worker", 1)
failed = jc.wait_attachment(api, alice, attachment["id"], "failed", timeout=180)
report = jc.admin_json("show", "--attachment", attachment["id"])
time.sleep(1.0)
queues = jc.queue_stats()
replay = jc.admin_json(
"replay",
"--job",
job["id"],
"--operator",
"student",
"--reason",
"bound retries demonstrated; transient fault cleared",
)
ready = jc.wait_attachment(api, bob, attachment["id"], "ready", timeout=120)
final = jc.admin_json("show", "--attachment", attachment["id"])
retries = [
event
for event in report["events"]
if event["to_state"] == "queued" and event["detail"] and "retry_in=" in (event["detail"] or "")
]
evidence = {
"scenario": "bounded_retry_then_failed_and_replay",
"attachment_id": attachment["id"],
"job_id": job["id"],
"max_attempts": report["jobs"][0]["max_attempts"],
"attempts": report["jobs"][0]["attempts"],
"failed_status": failed["status"],
"failed_error_code": failed["error_code"],
"job_state": report["jobs"][0]["state"],
"retry_events": retries,
"retry_delays_seconds": [
float(event["detail"].split("retry_in=")[1].rstrip("s")) for event in retries
],
"queues_after_failure": queues,
"replay_job_id": replay["replay_job_id"],
"status_after_replay": ready["status"],
"final_variants": [item["name"] for item in final["attachment"]["variants"]],
"passed": (
failed["status"] == "failed"
and failed["error_code"] == "retry_exhausted"
and report["jobs"][0]["attempts"] == 5
and len(retries) == 4
and queues.get("attachment.dlq", {}).get("messages", 0) >= 1
and ready["status"] == "ready"
and len(final["attachment"]["variants"]) == 3
),
"note": (
"Transient failures produced four backoff retries with jitter, then the "
"fifth attempt exhausted the configured limit and produced failed+DLQ. "
"An explicit replay after clearing the fault completed the same effect key."
),
}
output = ROOT / "evidence" / "retry.json"
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True))
return 0 if evidence["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Запуск собственных проверок лабораторной 5."""
from __future__ import annotations
import argparse
import os
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
def main() -> int:
parser = argparse.ArgumentParser(description="Собственные проверки лабораторной 5")
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
arguments = parser.parse_args()
os.environ["BASE_URL"] = arguments.base_url
if str(HERE) not in sys.path:
sys.path.insert(0, str(HERE))
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(line_buffering=True)
print("BASE_URL =", arguments.base_url, flush=True)
suite = unittest.defaultTestLoader.discover(
str(HERE), pattern="test_*.py", top_level_dir=str(HERE)
)
result = unittest.TextTestRunner(verbosity=2).run(suite)
return 0 if result.wasSuccessful() else 1
if __name__ == "__main__":
raise SystemExit(main())
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Staging удаляется только после успешной фиксации результата."""
from __future__ import annotations
import json
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
for candidate in (str(HERE), str(ROOT / "tests")):
if candidate not in sys.path:
sys.path.insert(0, candidate)
import job_control as jc # noqa: E402
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def main() -> int:
api = jc.client(timeout=20)
api.call("GET", "/health/ready", schema="Health")
alice, bob, eve, chat = api.bootstrap()
# Worker остановлен: видно staging-объект до публикации результата.
jc.scale("worker", 0)
jc.wait_service("worker", 0)
attachment = jc.upload(api, alice, chat, PNG)
staging_before = jc.list_objects("staging/%s" % attachment["id"])
final_before = jc.list_objects("final/%s/" % attachment["id"])
jc.scale("worker", 1)
jc.wait_service("worker", 1)
ready = jc.wait_attachment(api, alice, attachment["id"], "ready", timeout=120)
time.sleep(1.0)
staging_after = jc.list_objects("staging/%s" % attachment["id"])
final_after = jc.list_objects("final/%s/" % attachment["id"])
report = jc.admin_json("show", "--attachment", attachment["id"])
evidence = {
"scenario": "staging_cleanup_after_commit",
"attachment_id": attachment["id"],
"staging_before_ready": staging_before,
"final_before_ready": final_before,
"staging_after_ready": staging_after,
"final_after_ready": final_after,
"attachment_status": ready["status"],
"staging_key_in_db": report["attachment"]["staging_key"],
"original_key_in_db": report["attachment"]["object_key"],
"variants": [item["name"] for item in report["attachment"]["variants"]],
"passed": (
len(staging_before) == 1
and len(staging_after) == 0
and len(final_after) == 4
and ready["status"] == "ready"
),
"note": (
"The original was visible under the staging prefix before commit. "
"After the ready commit, worker deleted it; final prefix contains the "
"original plus exactly three variants."
),
}
output = ROOT / "evidence" / "staging-cleanup.json"
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True))
return 0 if evidence["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())
+108
View File
@@ -0,0 +1,108 @@
"""Собственные проверки лабораторной 3: реплики, LB и общая идемпотентность."""
from __future__ import annotations
import threading
import unittest
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import harness
from client import Client
class Lab3Tests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
harness.wait_ready()
cls.api = harness.client()
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
def test_01_at_least_two_instances_and_stable_header(self) -> None:
"""LB действительно распределяет один и тот же токен между разными процессами."""
observed = harness.instance_ids(self.api, self.alice, 40)
self.assertGreaterEqual(len(observed), 2, "less than two X-Instance-Id values through LB")
for _ in range(10):
me = self.api.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")["json"]
self.assertEqual(me["id"], self.alice["id"])
def test_02_concurrent_same_key_through_lb_creates_one_message(self) -> None:
"""Один ключ + одно тело одновременно через разные реплики = одно сообщение."""
key = uuid4().hex
text = "concurrent-idempotency-" + uuid4().hex
workers = 24
barrier = threading.Barrier(workers)
def worker(_: int) -> dict:
local = harness.client(10)
barrier.wait()
return local.message(self.alice, self.chat, text, key=key)
with ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(worker, range(workers)))
bodies = [response["json"] for response in responses]
instances = {response["headers"]["X-Instance-Id"] for response in responses}
self.assertGreaterEqual(len(instances), 2, "concurrent requests did not reach both replicas")
self.assertEqual(bodies, [bodies[0]] * workers, "replay returned a different Message")
messages = [m for m in harness.history(self.api, self.bob, self.chat["id"]) if m["text"] == text]
self.assertEqual(len(messages), 1, "idempotency key created %d messages" % len(messages))
self.assertEqual(messages[0], bodies[0])
def test_03_same_key_other_body_conflicts(self) -> None:
key = uuid4().hex
first = self.api.message(self.alice, self.chat, "first-" + uuid4().hex, key=key)["json"]
replay = self.api.message(self.alice, self.chat, first["text"], key=key)["json"]
self.assertEqual(replay, first)
self.api.call(
"POST",
"/api/v1/chats/" + self.chat["id"] + "/messages",
409,
actor=self.alice,
body={"text": "different body"},
headers={"Idempotency-Key": key},
)
def test_04_key_scope_user_and_chat(self) -> None:
key = uuid4().hex
text_alice = "scope-a-" + uuid4().hex
text_bob = "scope-b-" + uuid4().hex
alice_message = self.api.message(self.alice, self.chat, text_alice, key=key)["json"]
bob_message = self.api.message(self.bob, self.chat, text_bob, key=key)["json"]
self.assertNotEqual(alice_message["id"], bob_message["id"])
other_chat = self.api.call(
"POST",
"/api/v1/chats",
201,
actor=self.alice,
body={"title": "Другой чат", "member_ids": [self.alice["id"]]},
schema="Chat",
)["json"]
other = self.api.message(self.alice, other_chat, text_alice, key=key)["json"]
self.assertNotEqual(other["id"], alice_message["id"])
def test_05_key_validation(self) -> None:
path = "/api/v1/chats/" + self.chat["id"] + "/messages"
for bad in ("", "has space", "bad/slash", "x" * 129):
self.api.call(
"POST",
path,
400,
actor=self.alice,
body={"text": "bad-key"},
headers={"Idempotency-Key": bad},
)
self.api.call("POST", path, 400, actor=self.alice, body={"text": "no key"})
for good in ("a", "z" * 128):
self.api.message(self.alice, self.chat, "boundary-" + uuid4().hex, key=good)
def test_06_uncertain_retry_is_safe(self) -> None:
"""Повтор с тем же ключом после потери ответа не создаёт второй объект."""
key = uuid4().hex
text = "retry-after-conflict-" + uuid4().hex
first = self.api.message(self.alice, self.chat, text, key=key)["json"]
again = self.api.message(self.alice, self.chat, text, key=key)["json"]
self.assertEqual(first, again)
if __name__ == "__main__":
unittest.main(verbosity=2)
+235
View File
@@ -0,0 +1,235 @@
"""Собственные проверки лабораторной 5: асинхронный pipeline и варианты.
Проверки идут через публичный контракт и LB; Docker-сценарии (остановка worker,
брокера, fault injection) лежат в отдельных probes и в evidence.
"""
from __future__ import annotations
import hashlib
import struct
import unittest
import uuid
import zlib
from pathlib import Path
from urllib.parse import quote
import harness
from client import Client
from image_probe import jpeg_size
ROOT = Path(__file__).resolve().parents[1]
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
JPEG = (Path(__file__).resolve().parent / "fixtures" / "sample.jpg").read_bytes()
MAX_BYTES = 10_485_760
EXPECTED_VARIANTS = {"thumbnail", "crop", "optimized"}
def webp_size(data: bytes) -> tuple[int, int]:
"""Размеры WebP без внешних библиотек: VP8X, VP8L или lossy VP8."""
assert data[:4] == b"RIFF" and data[8:12] == b"WEBP", "not WebP"
offset = 12
while offset + 8 <= len(data):
fourcc = data[offset : offset + 4]
length = int.from_bytes(data[offset + 4 : offset + 8], "little")
payload = data[offset + 8 : offset + 8 + length]
if fourcc == b"VP8X" and len(payload) >= 10:
width = 1 + int.from_bytes(payload[4:7], "little")
height = 1 + int.from_bytes(payload[7:10], "little")
return width, height
if fourcc == b"VP8L" and len(payload) >= 5:
bits = int.from_bytes(payload[1:5], "little")
return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
if fourcc == b"VP8 " and len(payload) >= 10:
assert payload[3:6] == b"\x9d\x01\x2a", "not a VP8 keyframe"
width = int.from_bytes(payload[6:8], "little") & 0x3FFF
height = int.from_bytes(payload[8:10], "little") & 0x3FFF
return width, height
offset += 8 + length + (length & 1)
raise AssertionError("WebP dimensions not found")
def upload(
api: Client,
actor: dict,
chat: dict,
content: bytes,
*,
filename: str = "photo.png",
content_type: str = "image/png",
expected: int = 202,
):
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
return api.call(
"POST",
path,
expected,
actor=actor,
raw=content,
headers={"Content-Type": content_type},
schema="Attachment" if expected == 202 else None,
)
def png_with_dimensions(width: int, height: int) -> bytes:
"""Меняет IHDR у реального PNG и пересчитывает CRC: файл остаётся PNG."""
data = bytearray(PNG)
struct.pack_into(">I", data, 16, width)
struct.pack_into(">I", data, 20, height)
struct.pack_into(">I", data, 29, zlib.crc32(bytes(data[12:29])) & 0xFFFFFFFF)
return bytes(data)
class Lab5AttachmentTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
harness.wait_ready()
cls.api = harness.client()
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
cls.other_chat = cls.api.call(
"POST",
"/api/v1/chats",
201,
actor=cls.alice,
body={"title": "Другой чат lab5", "member_ids": [cls.alice["id"], cls.bob["id"]]},
schema="Chat",
)["json"]
def test_01_png_and_jpeg_pipeline(self) -> None:
for content, content_type, filename in (
(PNG, "image/png", "sample.png"),
(JPEG, "image/jpeg", "sample.jpg"),
):
queued = upload(
self.api, self.alice, self.chat, content, filename=filename, content_type=content_type
)["json"]
self.assertEqual(queued["status"], "queued")
self.assertEqual(queued["variants"], [])
self.assertIsNone(queued["error_code"])
self.assertEqual(queued["sha256"], hashlib.sha256(content).hexdigest())
self.assertEqual(queued["size_bytes"], len(content))
ready = self.api.wait_ready(self.bob, queued)
self.assertEqual(ready["status"], "ready")
self.assertIsNone(ready["error_code"])
names = {item["name"] for item in ready["variants"]}
self.assertEqual(names, EXPECTED_VARIANTS)
variants = {item["name"]: item for item in ready["variants"]}
self.assertEqual(
(variants["thumbnail"]["content_type"], variants["thumbnail"]["width"], variants["thumbnail"]["height"]),
("image/jpeg", 256, 160),
)
self.assertEqual(
(variants["crop"]["content_type"], variants["crop"]["width"], variants["crop"]["height"]),
("image/jpeg", 128, 128),
)
self.assertEqual(variants["optimized"]["content_type"], "image/webp")
self.assertLessEqual(max(variants["optimized"]["width"], variants["optimized"]["height"]), 1280)
original = self.api.call("GET", "/api/v1/attachments/" + queued["id"] + "/content", actor=self.bob)
self.assertEqual(original["bytes"], content)
self.assertEqual(original["headers"].get_content_type(), content_type)
self.assertEqual(original["headers"].get("Content-Length"), str(len(content)))
for name, expected_size in (("thumbnail", (256, 160)), ("crop", (128, 128))):
response = self.api.call(
"GET",
"/api/v1/attachments/" + queued["id"] + "/content?variant=" + name,
actor=self.bob,
)
self.assertEqual(response["headers"].get_content_type(), "image/jpeg")
self.assertEqual(hashlib.sha256(response["bytes"]).hexdigest(), variants[name]["sha256"])
self.assertEqual(len(response["bytes"]), variants[name]["size_bytes"])
self.assertEqual(jpeg_size(response["bytes"]), expected_size)
optimized = self.api.call(
"GET",
"/api/v1/attachments/" + queued["id"] + "/content?variant=optimized",
actor=self.bob,
)
self.assertEqual(optimized["headers"].get_content_type(), "image/webp")
self.assertEqual(hashlib.sha256(optimized["bytes"]).hexdigest(), variants["optimized"]["sha256"])
self.assertEqual(
webp_size(optimized["bytes"]),
(variants["optimized"]["width"], variants["optimized"]["height"]),
)
def test_02_stranger_and_nonmember(self) -> None:
attachment = upload(self.api, self.alice, self.chat, PNG)["json"]
for suffix in ("", "/content"):
self.api.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=self.eve)
upload(self.api, self.eve, self.chat, PNG, expected=404)
self.api.call(
"GET",
"/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail",
404,
actor=self.eve,
)
def test_03_attachment_from_another_chat_is_404(self) -> None:
foreign = upload(self.api, self.alice, self.other_chat, PNG)["json"]
self.api.call(
"POST",
"/api/v1/chats/" + self.chat["id"] + "/messages",
404,
actor=self.alice,
body={"text": "", "attachment_ids": [foreign["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
own = self.api.message(self.alice, self.other_chat, "", attachments=[foreign["id"]])["json"]
self.assertEqual(own["attachment_ids"], [foreign["id"]])
def test_04_queued_attachment_can_be_message_and_idempotency(self) -> None:
attachment = upload(self.api, self.alice, self.chat, PNG)["json"]
path = "/api/v1/chats/" + self.chat["id"] + "/messages"
self.api.call("POST", path, 400, actor=self.alice, body={"text": ""}, headers={"Idempotency-Key": uuid.uuid4().hex})
self.api.call(
"POST",
path,
400,
actor=self.alice,
body={"text": "too many", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
self.api.call(
"POST",
path,
400,
actor=self.alice,
body={"text": "duplicate", "attachment_ids": [attachment["id"], attachment["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
key = uuid.uuid4().hex
first = self.api.message(self.alice, self.chat, "", key=key, attachments=[attachment["id"]])["json"]
self.assertEqual(first["text"], "")
self.assertEqual(first["attachment_ids"], [attachment["id"]])
replay = self.api.message(self.alice, self.chat, "", key=key, attachments=[attachment["id"]])["json"]
self.assertEqual(replay, first)
self.api.call(
"POST",
path,
409,
actor=self.alice,
body={"text": "different", "attachment_ids": []},
headers={"Idempotency-Key": key},
)
def test_05_rejects_bad_images_and_filenames(self) -> None:
upload(self.api, self.alice, self.chat, b"\x00" * (MAX_BYTES + 1), expected=413)
upload(self.api, self.alice, self.chat, PNG[:100], expected=415)
upload(self.api, self.alice, self.chat, PNG, content_type="image/jpeg", expected=415)
upload(self.api, self.alice, self.chat, b"not an image", expected=415)
upload(self.api, self.alice, self.chat, b"", expected=415)
upload(self.api, self.alice, self.chat, png_with_dimensions(8000, 6000), expected=413)
upload(self.api, self.alice, self.chat, png_with_dimensions(10000, 10000), expected=413)
for bad in ("../secret.png", "a/b.png", "a\\b.png", "a\x00b.png", "a\nb.png", "x" * 256):
upload(self.api, self.alice, self.chat, PNG, filename=bad, expected=400)
def test_06_unknown_variant_is_400(self) -> None:
attachment = upload(self.api, self.alice, self.chat, PNG)["json"]
ready = self.api.wait_ready(self.bob, attachment)
self.api.call(
"GET",
"/api/v1/attachments/" + ready["id"] + "/content?variant=bogus",
400,
actor=self.bob,
)
if __name__ == "__main__":
unittest.main(verbosity=2)
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Демонстрация уровня 3: принятая работа переживает worker/API/broker restart.
Сценарии:
A. worker остановлен → upload 202 queued → content 409 → API restart →
тот же attachment остаётся queued → worker запущен → ready, варианты на месте.
B. worker остановлен → upload → durable сообщение в RabbitMQ → broker restart
с volume → worker запущен → ready.
"""
from __future__ import annotations
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
for candidate in (str(HERE), str(ROOT / "tests")):
if candidate not in sys.path:
sys.path.insert(0, candidate)
import job_control as jc # noqa: E402
from client import Client # noqa: E402
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
def wait_published(attachment_id: str, timeout: float = 60.0) -> dict:
deadline = time.monotonic() + timeout
report = jc.admin_json("show", "--attachment", attachment_id)
while time.monotonic() < deadline:
report = jc.admin_json("show", "--attachment", attachment_id)
if report.get("outbox") and all(row["published_at"] for row in report["outbox"]):
return report
time.sleep(0.25)
raise jc.ProbeError("outbox was not published: %s" % report)
def main() -> int:
api = jc.client(timeout=20)
api.call("GET", "/health/ready", schema="Health")
alice, bob, eve, chat = api.bootstrap()
started = now()
evidence: dict = {"started_at": started, "scenarios": []}
# A: worker остановлен; 202 и 409; API restart не теряет работу.
jc.scale("worker", 0)
jc.wait_service("worker", 0)
attachment = jc.upload(api, alice, chat, PNG)
queued = jc.wait_attachment(api, alice, attachment["id"], "queued", timeout=30)
api.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=bob)
content_status = 409
report_before = jc.admin_json("show", "--attachment", attachment["id"])
jc.restart("api")
jc.wait_ready(timeout=240)
api = jc.client(timeout=20)
after_restart = api.call(
"GET", "/api/v1/attachments/" + attachment["id"], actor=bob, schema="Attachment"
)["json"]
jc.scale("worker", 1)
jc.wait_service("worker", 1)
ready = jc.wait_attachment(api, bob, attachment["id"], "ready", timeout=120)
report_after = jc.admin_json("show", "--attachment", attachment["id"])
evidence["scenarios"].append(
{
"name": "worker_stopped_api_restart",
"attachment_id": attachment["id"],
"job_id": report_before["jobs"][0]["id"],
"upload_response_status": 202,
"status_before_restart": queued["status"],
"content_while_queued": content_status,
"outbox_after_upload": report_before["outbox"],
"status_after_api_restart": after_restart["status"],
"same_sha256": after_restart["sha256"] == attachment["sha256"],
"final_status": ready["status"],
"final_attempts": report_after["jobs"][0]["attempts"],
"final_variants": [item["name"] for item in report_after["attachment"]["variants"]],
"passed": (
queued["status"] == "queued"
and content_status == 409
and after_restart["status"] == "queued"
and ready["status"] == "ready"
and len(report_after["attachment"]["variants"]) == 3
),
}
)
# B: durable сообщение в broker; restart RabbitMQ с volume; затем worker.
jc.scale("worker", 0)
jc.wait_service("worker", 0)
time.sleep(5.0)
attachment_b = jc.upload(api, alice, chat, PNG)
published = wait_published(attachment_b["id"])
# Сообщение должно лежать именно в durable queue, а не быть уже забранным.
queue_before = jc.wait_queue_messages("attachment.jobs", 1, timeout=60)
jc.restart("rabbitmq")
jc.wait_broker(timeout=240)
queue_after = jc.queue_stats()
jc.scale("worker", 1)
jc.wait_service("worker", 1)
ready_b = jc.wait_attachment(api, bob, attachment_b["id"], "ready", timeout=150)
report_b = jc.admin_json("show", "--attachment", attachment_b["id"])
evidence["scenarios"].append(
{
"name": "broker_restart_with_volume",
"attachment_id": attachment_b["id"],
"job_id": published["jobs"][0]["id"],
"queue_before_restart": queue_before,
"queue_after_restart": queue_after,
"status_before_restart": "queued",
"final_status": ready_b["status"],
"final_attempts": report_b["jobs"][0]["attempts"],
"final_variants": [item["name"] for item in report_b["attachment"]["variants"]],
"passed": (
ready_b["status"] == "ready"
and len(report_b["attachment"]["variants"]) == 3
and any(
key == "attachment.jobs" and value["messages"] >= 1
for key, value in queue_before.items()
)
),
}
)
evidence["finished_at"] = now()
evidence["all_passed"] = all(item["passed"] for item in evidence["scenarios"])
evidence["note"] = (
"RabbitMQ quorum queue is durable; message was confirmed before restart. "
"Named volume lab5_rabbitmqdata was preserved. The same 202 attachment "
"and job id are used before and after restart."
)
output = ROOT / "evidence" / "worker-restart.json"
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True))
return 0 if evidence["all_passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())