4
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise durable queued upload, component restarts and duplicate delivery.
|
||||
|
||||
Run from the repository root against the local compose.yaml:
|
||||
python student_tests/lab5_worker_recovery.py
|
||||
The script preserves volumes and leaves the complete stack running.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, Failure, check, run # noqa: E402
|
||||
from image_probe import jpeg_size # noqa: E402
|
||||
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env.example"]
|
||||
|
||||
|
||||
def command(*args, capture=False):
|
||||
result = subprocess.run(
|
||||
[*COMPOSE, *args], cwd=ROOT, check=True,
|
||||
text=True, capture_output=capture)
|
||||
return result.stdout.strip() if capture else ""
|
||||
|
||||
|
||||
def database_scalar(sql):
|
||||
return command(
|
||||
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-At", "-c", sql, capture=True)
|
||||
|
||||
|
||||
def env_value(name):
|
||||
for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines():
|
||||
if line.startswith(name + "="):
|
||||
return line.split("=", 1)[1]
|
||||
raise Failure("missing " + name + " in .env.example")
|
||||
|
||||
|
||||
def wait_http_ready(client, seconds=120):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure("API did not become ready after restart")
|
||||
|
||||
|
||||
def wait_rabbit(seconds=120):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
result = subprocess.run(
|
||||
[*COMPOSE, "exec", "-T", "rabbitmq", "rabbitmq-diagnostics", "-q", "ping"],
|
||||
cwd=ROOT, text=True, capture_output=True)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
time.sleep(2)
|
||||
raise Failure("RabbitMQ did not become ready after restart")
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("http://localhost:8080")
|
||||
command("stop", "worker")
|
||||
try:
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
check(attachment["status"] == "queued", "upload did not remain queued")
|
||||
client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
409, actor=bob)
|
||||
linked = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
check(linked["attachment_ids"] == [attachment["id"]],
|
||||
"queued attachment could not be linked")
|
||||
|
||||
command("restart", "api")
|
||||
command("restart", "rabbitmq")
|
||||
wait_rabbit()
|
||||
wait_http_ready(client)
|
||||
command("start", "worker")
|
||||
|
||||
ready = client.wait_ready(bob, attachment, wait_seconds=120)
|
||||
check(ready["status"] == "ready", "attachment did not become ready")
|
||||
downloaded = client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob)
|
||||
check(downloaded["bytes"] == original, "original bytes changed")
|
||||
variants = {item["name"]: item for item in ready["variants"]}
|
||||
check(set(variants) == {"thumbnail", "crop", "optimized"},
|
||||
"expected thumbnail, crop and optimized variants")
|
||||
check((variants["thumbnail"]["width"], variants["thumbnail"]["height"]) == (256, 160),
|
||||
"thumbnail dimensions differ from contract")
|
||||
check((variants["crop"]["width"], variants["crop"]["height"]) == (128, 128),
|
||||
"crop dimensions differ from contract")
|
||||
crop = client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=crop",
|
||||
actor=bob)
|
||||
check(crop["headers"].get_content_type() == "image/jpeg", "crop is not JPEG")
|
||||
check(jpeg_size(crop["bytes"]) == (128, 128), "crop JPEG has wrong dimensions")
|
||||
optimized = client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=optimized",
|
||||
actor=bob)
|
||||
check(optimized["headers"].get_content_type() == "image/webp", "optimized is not WebP")
|
||||
check(optimized["bytes"][:4] == b"RIFF" and optimized["bytes"][8:12] == b"WEBP",
|
||||
"optimized payload has no WebP signature")
|
||||
|
||||
job_row = database_scalar(
|
||||
"SELECT id || '|' || pipeline_version || '|' || attempt || '|' || "
|
||||
"to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') "
|
||||
"FROM attachment_jobs WHERE attachment_id = '" + attachment["id"] + "';")
|
||||
job_id, pipeline_version, attempt, created_at = job_row.split("|")
|
||||
payload = json.dumps({
|
||||
"schema_version": 1,
|
||||
"job_id": job_id,
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": attachment["id"],
|
||||
"pipeline_version": int(pipeline_version),
|
||||
"attempt": int(attempt),
|
||||
"created_at": created_at,
|
||||
}, separators=(",", ":"))
|
||||
command(
|
||||
"exec", "-T", "rabbitmq", "rabbitmqadmin",
|
||||
"-u", env_value("RABBITMQ_USER"),
|
||||
"-p", env_value("RABBITMQ_PASSWORD"),
|
||||
"publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"),
|
||||
"routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"),
|
||||
"payload=" + payload,
|
||||
'properties={"delivery_mode":2,"content_type":"application/json"}')
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
queued = command(
|
||||
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
|
||||
"name", "messages_ready", "messages_unacknowledged", capture=True)
|
||||
if env_value("ATTACHMENT_JOB_QUEUE") + "\t0\t0" in queued:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
variant_count = database_scalar(
|
||||
"SELECT count(*) FROM attachment_variants WHERE attachment_id = '"
|
||||
+ attachment["id"] + "';")
|
||||
status = database_scalar(
|
||||
"SELECT status FROM attachments WHERE id = '" + attachment["id"] + "';")
|
||||
check(variant_count == "3", "duplicate delivery changed the three variant rows")
|
||||
check(status == "ready", "duplicate delivery changed terminal ready state")
|
||||
check(hashlib.sha256(downloaded["bytes"]).hexdigest() == attachment["sha256"],
|
||||
"original checksum changed")
|
||||
print("PASS: stopped worker, durable restart recovery and duplicate delivery")
|
||||
finally:
|
||||
command("start", "worker")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user