4
This commit is contained in:
@@ -16,3 +16,9 @@ The course-provided black-box suite remains in `tests/`; Spring tests remain in
|
||||
unknown attachment, foreign user and cross-chat binding; every user error is 4xx.
|
||||
- `concurrent_upload_memory.py` — 12 simultaneous ~6.5 MiB valid PNG uploads and
|
||||
aggregate API container memory sampling through `docker stats`.
|
||||
- `lab5_worker_recovery.py` — durable worker stop/restart, all three variants and
|
||||
idempotent duplicate delivery.
|
||||
- `lab5_fault_injection.py` — crashes after outbox commit and after result commit
|
||||
but before consumer acknowledgement.
|
||||
- `lab5_dlq_replay_lease.py` — permanent failure DLQ routing, guarded audited
|
||||
replay, and expired processing-lease recovery.
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise DLQ routing, guarded replay and expired processing leases."""
|
||||
|
||||
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
|
||||
|
||||
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 queue_ready(queue):
|
||||
listing = command(
|
||||
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
|
||||
"name", "messages_ready", capture=True)
|
||||
for line in listing.splitlines():
|
||||
columns = line.split("\t")
|
||||
if len(columns) == 2 and columns[0] == queue:
|
||||
return int(columns[1])
|
||||
raise Failure("queue not found: " + queue)
|
||||
|
||||
|
||||
def wait_ready(client, actor, attachment, seconds=120):
|
||||
return client.wait_ready(actor, attachment, wait_seconds=seconds)
|
||||
|
||||
|
||||
def replay(job_id):
|
||||
subprocess.run(
|
||||
["powershell", "-NoProfile", "-File", str(ROOT / "scripts" / "replay-failed.ps1"),
|
||||
"-JobId", job_id, "-RequestedBy", "integration-test",
|
||||
"-EnvFile", ".env.example"],
|
||||
cwd=ROOT, check=True, text=True)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("http://localhost:8080")
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
|
||||
# A permanently malformed delivery is rejected and dead-lettered.
|
||||
before_dlq = queue_ready(env_value("ATTACHMENT_DLQ_QUEUE"))
|
||||
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={}",
|
||||
'properties={"delivery_mode":2,"content_type":"application/json"}')
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline and queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) <= before_dlq:
|
||||
time.sleep(0.5)
|
||||
check(queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) == before_dlq + 1,
|
||||
"malformed permanent failure was not dead-lettered exactly once")
|
||||
|
||||
# Replay is allowed only from failed and creates one audit record.
|
||||
command("stop", "worker")
|
||||
failed, _ = client.attachment(alice, chat)
|
||||
job_id = database_scalar(
|
||||
"SELECT id FROM attachment_jobs WHERE attachment_id = '" + failed["id"] + "';")
|
||||
database_scalar(
|
||||
"UPDATE attachment_jobs SET status='failed', published=true, "
|
||||
"last_error_code='retry_exhausted', lease_token=NULL, lease_until=NULL "
|
||||
"WHERE id='" + job_id + "'; "
|
||||
"UPDATE attachments SET status='failed', error_code='retry_exhausted' "
|
||||
"WHERE id='" + failed["id"] + "'; SELECT 1;")
|
||||
replay(job_id)
|
||||
replay(job_id)
|
||||
audit_count = database_scalar(
|
||||
"SELECT count(*) FROM attachment_job_replays WHERE job_id='" + job_id + "';")
|
||||
check(audit_count == "1", "replay was not guarded or was audited more than once")
|
||||
command("start", "worker")
|
||||
ready = wait_ready(client, bob, failed)
|
||||
check(ready["status"] == "ready", "replayed failed job did not become ready")
|
||||
replay(job_id)
|
||||
check(database_scalar(
|
||||
"SELECT count(*) FROM attachment_job_replays WHERE job_id='" + job_id + "';") == "1",
|
||||
"replay changed an already successful job")
|
||||
check(database_scalar(
|
||||
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" + failed["id"] + "';") == "3",
|
||||
"replay did not preserve exactly one variant set")
|
||||
|
||||
# The API reaper returns an expired processing lease to the durable outbox.
|
||||
command("stop", "worker")
|
||||
leased, _ = client.attachment(alice, chat)
|
||||
lease_job = database_scalar(
|
||||
"SELECT id FROM attachment_jobs WHERE attachment_id='" + leased["id"] + "';")
|
||||
database_scalar(
|
||||
"UPDATE attachment_jobs SET status='processing', attempt=1, published=true, "
|
||||
"lease_token=gen_random_uuid(), lease_until=clock_timestamp()-interval '1 second' "
|
||||
"WHERE id='" + lease_job + "'; "
|
||||
"UPDATE attachments SET status='processing' WHERE id='" + leased["id"] + "'; SELECT 1;")
|
||||
command("start", "worker")
|
||||
lease_ready = wait_ready(client, bob, leased)
|
||||
check(lease_ready["status"] == "ready", "expired processing lease was not recovered")
|
||||
check(int(database_scalar(
|
||||
"SELECT attempt FROM attachment_jobs WHERE id='" + lease_job + "';")) >= 2,
|
||||
"expired lease did not consume a bounded retry attempt")
|
||||
print("PASS: DLQ, guarded replay and expired lease recovery")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove recovery across DB-commit/publish and result-commit/ack crashes."""
|
||||
|
||||
import os
|
||||
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
|
||||
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env.example"]
|
||||
|
||||
|
||||
def command(*args, capture=False, environment=None):
|
||||
result = subprocess.run(
|
||||
[*COMPOSE, *args], cwd=ROOT, check=True, text=True,
|
||||
capture_output=capture, env=environment)
|
||||
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 recreate(service, fault_name=None):
|
||||
environment = os.environ.copy()
|
||||
environment["FAULT_CRASH_AFTER_OUTBOX_COMMIT"] = "false"
|
||||
environment["FAULT_CRASH_AFTER_RESULT_COMMIT"] = "false"
|
||||
if fault_name:
|
||||
environment[fault_name] = "true"
|
||||
command("up", "-d", "--no-deps", "--force-recreate", service,
|
||||
environment=environment)
|
||||
|
||||
|
||||
def wait_http(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")
|
||||
|
||||
|
||||
def wait_job(attachment_id, expected="ready", seconds=120):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
status = database_scalar(
|
||||
"SELECT status FROM attachment_jobs WHERE attachment_id = '"
|
||||
+ attachment_id + "';")
|
||||
if status == expected:
|
||||
return
|
||||
if status == "failed":
|
||||
raise Failure("fault-injected job reached failed")
|
||||
time.sleep(1)
|
||||
raise Failure("fault-injected job did not reach " + expected)
|
||||
|
||||
|
||||
def latest_attachment(chat_id, fault_column):
|
||||
row = database_scalar(
|
||||
"SELECT a.id FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
|
||||
"WHERE a.chat_id = '" + chat_id + "' AND j." + fault_column
|
||||
+ " = true ORDER BY a.created_at DESC LIMIT 1;")
|
||||
check(bool(row), "fault marker was not persisted")
|
||||
return row
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("http://localhost:8080")
|
||||
wait_http(client)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
original = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
# Crash exactly after attachment + outbox COMMIT, before the request thread publishes.
|
||||
recreate("api", "FAULT_CRASH_AFTER_OUTBOX_COMMIT")
|
||||
wait_http(client)
|
||||
try:
|
||||
client.call(
|
||||
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=outbox.png",
|
||||
202, actor=alice, raw=original, headers={"Content-Type": "image/png"},
|
||||
schema="Attachment")
|
||||
raise Failure("outbox fault did not terminate the API request")
|
||||
except Failure as error:
|
||||
if "outbox fault did not" in str(error):
|
||||
raise
|
||||
|
||||
outbox_attachment = latest_attachment(chat["id"], "publish_fault_injected")
|
||||
wait_job(outbox_attachment)
|
||||
recreate("api")
|
||||
wait_http(client)
|
||||
recovered = client.call(
|
||||
"GET", "/api/v1/attachments/" + outbox_attachment,
|
||||
actor=bob, schema="Attachment")["json"]
|
||||
check(recovered["status"] == "ready", "outbox recovery did not publish the job")
|
||||
check(len(recovered["variants"]) == 3, "outbox recovery did not finish all variants")
|
||||
|
||||
# Crash after S3 effects + result COMMIT, before RabbitMQ consumer ack.
|
||||
recreate("worker", "FAULT_CRASH_AFTER_RESULT_COMMIT")
|
||||
queued = client.call(
|
||||
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=ack-window.png",
|
||||
202, actor=alice, raw=original, headers={"Content-Type": "image/png"},
|
||||
schema="Attachment")["json"]
|
||||
wait_job(queued["id"])
|
||||
ready = client.wait_ready(bob, queued, wait_seconds=120)
|
||||
check(len(ready["variants"]) == 3, "result crash lost variants")
|
||||
result_marker = database_scalar(
|
||||
"SELECT result_fault_injected FROM attachment_jobs WHERE attachment_id = '"
|
||||
+ queued["id"] + "';")
|
||||
check(result_marker == "t", "result commit fault marker was not persisted")
|
||||
recreate("worker")
|
||||
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
queues = command(
|
||||
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
|
||||
"name", "messages_ready", "messages_unacknowledged", capture=True)
|
||||
if "attachments.process.level4.v1\t0\t0" in queues:
|
||||
break
|
||||
time.sleep(1)
|
||||
variant_count = database_scalar(
|
||||
"SELECT count(*) FROM attachment_variants WHERE attachment_id = '"
|
||||
+ queued["id"] + "';")
|
||||
check(variant_count == "3", "redelivery duplicated committed variants")
|
||||
print("PASS: outbox commit/publish crash and result commit/ack crash recovered")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -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