Files
mtusi2026lab5-fork/student-tests/pipeline.py
T

344 lines
17 KiB
Python

"""Pipeline checks against an isolated Compose project with synthetic data."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
import subprocess
import sys
import time
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
from image_probe import jpeg_size
def run_compose(*args):
return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True,
text=True, encoding="utf-8", timeout=110)
def compose(*args):
result = run_compose(*args)
if result.returncode:
raise RuntimeError(result.stderr)
return result.stdout.strip()
def sql(statement):
return compose("exec", "-T", "db", "psql", "-XAt", "-v", "ON_ERROR_STOP=1",
"-U", "messenger", "-d", "messenger", "-c", statement)
def admin(*args):
return compose("exec", "-T", "broker", "sh", "-ec",
'export RABBITMQADMIN_PASSWORD="$(cat /run/secrets/broker_password)" '
'RABBITMQADMIN_USERNAME=messenger; exec rabbitmqadmin --timeout 5 "$@"', "admin", *args)
def wait_for(read, expected, timeout=60):
deadline = time.monotonic() + timeout
value = None
while time.monotonic() < deadline:
try:
value = read()
except (Failure, RuntimeError) as exc:
value = str(exc)
if value == expected:
return value
time.sleep(0.5)
raise AssertionError(f"expected {expected!r}, last observed {value!r}")
def queue_size():
out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages_ready")
for line in out.splitlines():
fields = line.split()
if len(fields) == 2 and fields[0] == "attachments.v1":
return int(fields[1])
return 0
def started_at(service):
ids = compose("ps", "-q", service).splitlines()
result = subprocess.run(["docker", "inspect", "--format", "{{.State.StartedAt}}", *ids],
cwd=ROOT, capture_output=True, text=True, check=True, timeout=15)
return result.stdout.splitlines()
def minimum(client):
started = time.monotonic()
alice, bob, _, chat = client.bootstrap()
wait_for(queue_size, 0)
compose("stop", "worker")
try:
attachment, content = client.attachment(alice, chat)
aid = attachment["id"]
route = "/api/v1/attachments/" + aid
client.call("GET", route + "/content", 409, actor=alice)
sent = client.message(alice, chat, "", attachments=[aid])["json"]
check(sent["attachment_ids"] == [aid], "queued attachment missing from message")
text = "Сообщение во время остановки worker"
check(client.message(bob, chat, text)["json"]["text"] == text, "ordinary message was blocked")
wait_for(lambda: sql(f"SELECT published_at IS NOT NULL FROM attachment_jobs WHERE attachment_id='{aid}'"), "t")
before_restart = queue_size()
check(before_restart == 1, "expected one published delivery in the isolated queue")
api_before = started_at("api")
broker_before = started_at("broker")
compose("restart", "api", "broker")
after_restart = wait_for(queue_size, before_restart)
api_after = started_at("api")
check(len(api_before) >= 2 and len(api_after) == len(api_before) and all(t not in api_before for t in api_after),
"expected both API replicas to restart")
check(started_at("broker") != broker_before, "broker was not restarted")
admin("get", "messages", "--queue", "attachments.v1", "--ack-mode", "reject_requeue_true")
job_id = sql(f"SELECT id FROM attachment_jobs WHERE attachment_id='{aid}'")
finally:
compose("start", "worker")
ready = client.wait_ready(bob, attachment)
thumb = client.call("GET", route + "/content?variant=thumbnail", actor=bob)["bytes"]
check(jpeg_size(thumb) == (256, 160), "invalid JPEG size")
check(client.call("GET", route + "/content", actor=bob)["bytes"] == content, "original changed")
wait_for(lambda: f"Ack job {job_id} attempt 1 redelivered True" in compose("logs", "worker"), True)
check(len(ready["variants"]) >= 1, "thumbnail missing from metadata")
check(sql(f"SELECT count(*) FROM attachment_variants WHERE attachment_id='{aid}' AND name='thumbnail'") == "1",
"duplicate thumbnails")
print(json.dumps({"scenario": "restart_and_redelivery", "attachment": aid, "job": job_id,
"api_replicas": len(api_before), "queue_before": before_restart,
"queue_after": after_restart, "thumbnail": list(jpeg_size(thumb)),
"original_sha256": hashlib.sha256(content).hexdigest(), "seconds": round(time.monotonic() - started, 2),
"redelivered": True, "result": "PASS"}))
def job(aid, version=1):
return json.loads(sql(f"""
SELECT json_build_object('id', id, 'attempt', attempt, 'published', published_at IS NOT NULL,
'lease', lease_until IS NOT NULL, 'created_at', created_at)
FROM attachment_jobs WHERE attachment_id='{aid}' AND pipeline_version={version}
"""))
def state(aid):
return sql(f"SELECT status FROM attachments WHERE id='{aid}'")
def variant_counts(aid):
return sql(f"""
SELECT pipeline_version, count(*) FROM attachment_variants
WHERE attachment_id='{aid}' GROUP BY pipeline_version ORDER BY pipeline_version
""")
def inject(service, fault, aid, attempt=None):
target = f"{fault}:{aid}" if attempt is None else f"{fault}:{aid}:{attempt}"
result = run_compose("run", "--rm", "--no-deps", "-e", f"LAB5_TEST_FAULT={target}",
"-e", "JOB_TIMEOUT_SECONDS=10", service)
check(result.returncode == 71 and f"Injected fault {fault}" in result.stderr,
f"{fault} did not terminate at the expected point (exit {result.returncode})")
def verify_outputs(client, actor, attachment, original):
ready = client.wait_ready(actor, attachment)
expected = {"thumbnail": ("image/jpeg", (256, 160)), "crop": ("image/jpeg", (128, 128)),
"optimized": ("image/webp", (320, 200))}
route = "/api/v1/attachments/" + ready["id"]
check(client.call("GET", route + "/content", actor=actor)["bytes"] == original, "original changed")
check({v["name"] for v in ready["variants"]} == expected.keys(), "variant set differs")
for variant in ready["variants"]:
name = variant["name"]
mime, dimensions = expected[name]
response = client.call("GET", route + "/content?variant=" + name, actor=actor)
data = response["bytes"]
check(variant["content_type"] == response["headers"].get_content_type() == mime, "incorrect MIME")
check((variant["width"], variant["height"]) == dimensions, "incorrect variant dimensions")
if mime == "image/jpeg":
check(jpeg_size(data) == dimensions, "incorrect JPEG dimensions")
else:
check(webp_size(data) == dimensions, "incorrect WebP dimensions")
check(hashlib.sha256(data).hexdigest() == variant["sha256"], "checksum mismatch")
return ready
def webp_size(data):
check(data[:4] == b"RIFF" and data[8:12] == b"WEBP", "invalid WebP")
kind = data[12:16]
if kind == b"VP8X":
return tuple(1 + int.from_bytes(data[i:i + 3], "little") for i in (24, 27))
if kind == b"VP8L":
packed = int.from_bytes(data[21:25], "little")
return (1 + (packed & 0x3fff), 1 + (packed >> 14 & 0x3fff))
check(kind == b"VP8 " and data[23:26] == b"\x9d\x01\x2a", "invalid VP8 frame")
return tuple(int.from_bytes(data[i:i + 2], "little") & 0x3fff for i in (26, 28))
def failures(client):
started = time.monotonic()
alice, _, _, chat = client.bootstrap()
compose("stop", "dispatcher", "worker")
try:
attachment, original = client.attachment(alice, chat)
aid = attachment["id"]
accepted = job(aid)
check(not accepted["published"] and state(aid) == "queued", "outbox did not persist first")
inject("dispatcher", "before-publish", aid)
check(job(aid) == accepted, "crash changed unpublished job")
compose("start", "dispatcher")
wait_for(lambda: job(aid)["published"], True)
inject("worker", "before-write", aid)
check(state(aid) == "processing" and job(aid)["lease"] and variant_counts(aid) == "", "invalid pre-write state")
route = "/api/v1/attachments/" + aid
processing = client.call("GET", route, actor=alice, schema="Attachment")["json"]
check(processing["status"] == "processing", "API did not expose processing")
client.call("GET", route + "/content", 409, actor=alice)
wait_for(lambda: job(aid)["attempt"], 2, 85)
wait_for(lambda: job(aid)["published"], True)
inject("worker", "after-write", aid)
check(state(aid) == "processing" and variant_counts(aid) == "", "uncommitted results became visible")
wait_for(lambda: job(aid)["attempt"], 3, 85)
wait_for(lambda: job(aid)["published"], True)
inject("worker", "before-ack", aid, attempt=3)
check(state(aid) == "ready" and variant_counts(aid) == "1|3", "result not committed before ack")
saved = verify_outputs(client, alice, attachment, original)
finally:
compose("start", "dispatcher", "worker")
wait_for(lambda: f'Ack job {accepted["id"]} attempt 3 redelivered True' in compose("logs", "worker"), True)
check(verify_outputs(client, alice, attachment, original) == saved, "redelivery changed ready result")
check(variant_counts(aid) == "1|3", "redelivery duplicated variants")
print(json.dumps({"scenario": "crash_windows", "attachment": aid, "job": accepted["id"],
"attempt": job(aid)["attempt"], "committed_variants": variant_counts(aid),
"seconds": round(time.monotonic() - started, 2), "result": "PASS"}))
def publish(aid, version, entry, attempt=None):
body = json.dumps({"schema_version": 1, "type": "attachment.process.v1", "job_id": entry["id"],
"attachment_id": aid, "pipeline_version": version,
"attempt": entry["attempt"] if attempt is None else attempt, "created_at": entry["created_at"]},
separators=(",", ":"))
admin("publish", "message", "--routing-key", "attachments.v1", "--payload", body)
def versions(client):
started = time.monotonic()
alice, _, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
aid = attachment["id"]
version_one = verify_outputs(client, alice, attachment, original)
first = job(aid)
compose("stop", "dispatcher", "worker")
try:
compose("exec", "-T", "api", "dotnet", "Messenger.Api.dll", "--upgrade-attachment", aid)
second = job(aid, 2)
# Сначала фиктивная будущая попытка v2 и устаревшая v1, затем действительная v2.
publish(aid, 2, second, attempt=2)
publish(aid, 1, first)
compose("start", "dispatcher")
wait_for(lambda: job(aid, 2)["published"], True)
publish(aid, 2, second)
compose("start", "worker")
version_two = verify_outputs(client, alice, attachment, original)
wait_for(lambda: compose("logs", "worker").count(f'Ack job {second["id"]}'), 3)
check(version_one["variants"] != version_two["variants"], "v2 did not produce a distinguishable result")
previous_acks = compose("logs", "worker").count(f'Ack job {first["id"]}')
publish(aid, 1, first)
wait_for(lambda: compose("logs", "worker").count(f'Ack job {first["id"]}'), previous_acks + 1)
check(verify_outputs(client, alice, attachment, original) == version_two, "v1 overwrote v2")
check(variant_counts(aid).splitlines() == ["1|3", "2|3"], "versioned effect keys are not unique")
finally:
compose("start", "dispatcher", "worker")
print(json.dumps({"scenario": "duplicate_reorder_old_version", "attachment": aid,
"v1": first["id"], "v2": second["id"], "committed_variants": variant_counts(aid),
"v1_sha256": next(v["sha256"] for v in version_one["variants"] if v["name"] == "thumbnail"),
"v2_sha256": next(v["sha256"] for v in version_two["variants"] if v["name"] == "thumbnail"),
"seconds": round(time.monotonic() - started, 2), "result": "PASS"}))
def retry_and_replay(client):
started = time.monotonic()
alice, _, _, chat = client.bootstrap()
compose("stop", "worker")
name = "lab5-test-retry"
try:
attachment, original = client.attachment(alice, chat)
aid = attachment["id"]
queued_message = client.message(alice, chat, "", key="retry-demo", attachments=[aid])["json"]
compose("run", "-d", "--rm", "--no-deps", "--name", name, "-e", f"LAB5_TEST_FAULT=transient:{aid}",
"-e", "JOB_MAX_ATTEMPTS=2", "worker")
wait_for(lambda: state(aid), "failed")
route = "/api/v1/attachments/" + aid
failed = client.call("GET", route, actor=alice, schema="Attachment")["json"]
check(failed["error_code"] == "retry_exhausted" and job(aid)["attempt"] == 2, "retry limit not enforced")
client.call("GET", route + "/content", 409, actor=alice)
client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 409, actor=alice,
body={"text": "", "attachment_ids": [aid]}, headers={"Idempotency-Key": "failed-new"})
jid = job(aid)["id"]
check(jid in compose("exec", "-T", "api", "dotnet", "Messenger.Api.dll", "--failed-jobs"), "job missing from registry")
check(client.message(alice, chat, "", key="retry-demo", attachments=[aid])["json"] == queued_message,
"existing message replay lost its result")
finally:
subprocess.run(["docker", "stop", name], cwd=ROOT, capture_output=True, timeout=20)
compose("start", "worker")
compose("exec", "-T", "api", "dotnet", "Messenger.Api.dll", "--replay-job", jid)
verify_outputs(client, alice, attachment, original)
wait_for(lambda: sql(f"SELECT count(*) FROM upload_intents WHERE id='{aid}'"), "0")
rejected = run_compose("exec", "-T", "api", "dotnet", "Messenger.Api.dll", "--replay-job", jid)
check(rejected.returncode == 2, "ready job can be replayed")
print(json.dumps({"scenario": "bounded_retry_replay", "attachment": aid, "job": jid,
"failed_attempt": 2, "recovery_attempt": job(aid)["attempt"],
"seconds": round(time.monotonic() - started, 2), "result": "PASS"}))
def synthetic_png(width, height, scanline):
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
header = struct.pack(">2I5B", width, height, 8, 2, 0, 0, 0)
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header)
+ chunk(b"IDAT", zlib.compress(scanline)) + chunk(b"IEND", b""))
def image_limits(client):
alice, _, _, chat = client.bootstrap()
upload = f'/api/v1/chats/{chat["id"]}/attachments?filename=boundary.png'
headers = {"Content-Type": "image/png"}
results = {}
for name, body, expected in (
("bytes", b"0" * 10485761, 413),
("pixels", synthetic_png(8000, 6000, b"\0"), 413),
("wrong_signature", b"not a PNG file", 415)):
results[name] = client.call("POST", upload, expected, actor=alice, headers=headers, raw=body)["status"]
# У файла корректны структура, CRC и zlib, но фильтр строки вне диапазона PNG.
upload_response = client.call("POST", upload, 202, actor=alice, headers=headers, schema="Attachment",
raw=synthetic_png(1, 1, b"\x05\x00\x00\x00"))
aid = upload_response["json"]["id"]
route = "/api/v1/attachments/" + aid
wait_for(lambda: client.call("GET", route, actor=alice, schema="Attachment")["json"]["status"], "failed")
failed = client.call("GET", route, actor=alice, schema="Attachment")["json"]
entry = job(aid)
check(failed["error_code"] == "invalid_image" and entry["attempt"] == 1 and not entry["lease"],
"permanent decoder failure should terminate on the first attempt")
check(not failed["variants"] and variant_counts(aid) == "", "invalid image produced variants")
client.call("GET", route + "/content", 409, actor=alice)
print(json.dumps({"scenario": "image_limits_and_permanent_failure", "attachment": aid, **results,
"error_code": failed["error_code"], "attempt": entry["attempt"], "result": "PASS"}))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default=None)
scenarios = {"minimum": minimum, "failures": failures, "versions": versions,
"retry": retry_and_replay, "limits": image_limits}
parser.add_argument("--scenario", choices=[*scenarios, "all"], default="all")
args = parser.parse_args()
client = Client(args.base_url)
for name, test in scenarios.items():
if args.scenario in (name, "all"):
wait_for(lambda: client.call("GET", "/health/ready", schema="Health")["json"]["status"], "ok")
test(client)
if __name__ == "__main__":
main()