Implement durable image processing pipeline with outbox and recovery

This commit is contained in:
Polusikkkk
2026-11-17 18:48:50 +03:00
parent 276dbdad8a
commit be223efc8b
84 changed files with 8982 additions and 18 deletions
+266
View File
@@ -0,0 +1,266 @@
from __future__ import annotations
import base64
import hashlib
import json
import secrets
import time
from uuid import UUID, uuid4
from queued_restart import ROOT, api, dc, http, wait_ready
from outbox_gap import snapshot
from before_ack import sql, object_keys
EVIDENCE = ROOT / "evidence" / "after_objects.json"
def intermediate_state(job_id):
return json.loads(sql(f"""
SELECT json_build_object(
'job_id', j.id,
'status', j.status,
'attempt', j.attempt,
'lease_remaining_seconds',
extract(epoch FROM (j.lease_until - clock_timestamp())),
'fault_consumed', f.consumed_at IS NOT NULL,
'variant_rows', (
SELECT count(*)
FROM attachment_variants v
WHERE v.attachment_id = j.attachment_id
)
)
FROM attachment_jobs j
JOIN pipeline_fault_injections f ON f.job_id = j.id
WHERE j.id = '{job_id}'::uuid
AND f.stage = 'after_objects';
"""))
def main():
evidence = {
"scenario": "worker crash after S3 writes, before result COMMIT",
}
job_id = None
restore = False
try:
wait_ready()
for service in ("publisher", "worker"):
if not dc("ps", "--status", "running", "-q", service):
raise AssertionError(f"Start {service} before this test")
username = "obj_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "After objects test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
token = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "After objects",
"member_ids": [user["id"]],
},
)
restore = True
dc("stop", "worker")
if dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Worker is still running")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = str(UUID(attachment["id"]))
path = f"/api/v1/attachments/{attachment_id}"
initial = snapshot(attachment_id)
job_id = str(UUID(initial["job_id"]))
sql(f"""
INSERT INTO pipeline_fault_injections (job_id, stage)
VALUES ('{job_id}'::uuid, 'after_objects');
""")
evidence["attachment_id"] = attachment_id
evidence["initial_job"] = initial
print(f"Armed one-shot after_objects fault for job {job_id}")
dc("start", "worker")
started = time.monotonic()
deadline = started + 45
while time.monotonic() < deadline:
middle = intermediate_state(job_id)
if middle["fault_consumed"]:
break
time.sleep(0.5)
else:
raise AssertionError("after_objects fault was not consumed")
assert middle["status"] == "processing"
assert middle["attempt"] == 1
assert middle["lease_remaining_seconds"] > 0
assert middle["variant_rows"] == 0
evidence["after_crash"] = middle
current = api("GET", path, 200, token=token)
assert current["status"] == "processing"
assert current["variants"] == []
api("GET", path + "/content", 409, token=token)
expected_keys = sorted([
f"originals/{attachment_id}",
f"variants/{attachment_id}/v1/thumbnail",
f"variants/{attachment_id}/v1/crop",
f"variants/{attachment_id}/v1/optimized",
])
# Во время автоматического рестарта docker exec может быть недоступен.
deadline = time.monotonic() + 25
while time.monotonic() < deadline:
try:
keys_before_recovery = object_keys(attachment_id)
break
except RuntimeError:
time.sleep(1)
else:
raise AssertionError("Could not inspect S3 after worker restart")
assert keys_before_recovery == expected_keys
# Подтверждаем, что осмотр S3 всё ещё был до восстановления lease.
confirmed_middle = intermediate_state(job_id)
assert confirmed_middle["status"] == "processing"
assert confirmed_middle["attempt"] == 1
assert confirmed_middle["lease_remaining_seconds"] > 0
assert confirmed_middle["variant_rows"] == 0
evidence["objects_before_recovery"] = keys_before_recovery
evidence["confirmed_intermediate_state"] = confirmed_middle
print(
"Fault consumed: processing, attempt=1, active lease, "
"S3 objects=4, variant rows=0, content=409"
)
print("Waiting for automatic lease recovery...")
deadline = started + 240
while time.monotonic() < deadline:
current = api("GET", path, 200, token=token)
if current["status"] == "ready":
break
if current["status"] == "failed":
raise AssertionError(
"Attachment failed: " + str(current["error_code"])
)
time.sleep(1)
else:
raise AssertionError("Lease recovery did not reach ready")
final = snapshot(attachment_id)
assert final["job_id"] == job_id
assert final["status"] == "ready"
assert final["attempt"] == 2
assert final["outbox_count"] == 2
assert current["error_code"] is None
status, body = http("GET", path + "/content", token=token)
assert status == 200 and body == original
variants = {item["name"]: item for item in current["variants"]}
assert len(current["variants"]) == 3
assert set(variants) == {"thumbnail", "crop", "optimized"}
for name, metadata in variants.items():
status, body = http(
"GET", path + "/content?variant=" + name,
token=token,
)
assert status == 200
assert len(body) == metadata["size_bytes"]
assert hashlib.sha256(body).hexdigest() == metadata["sha256"]
count = int(sql(f"""
SELECT count(*)
FROM attachment_variants
WHERE attachment_id = '{attachment_id}'::uuid;
"""))
assert count == 3
keys_after_recovery = object_keys(attachment_id)
assert keys_after_recovery == keys_before_recovery
logs = dc("logs", "--no-color", "--tail=400", "worker")
events = [
line for line in logs.splitlines()
if job_id in line
]
assert any(
"child_fault" in line and "stage=after_objects" in line
for line in events
)
assert any(
"status=queued" in line and "reason=lease_expired" in line
for line in events
)
evidence["final_job"] = final
evidence["variant_rows"] = count
evidence["objects_after_recovery"] = keys_after_recovery
evidence["worker_events"] = events
evidence["elapsed_s"] = round(time.monotonic() - started, 3)
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
if job_id is not None:
sql(f"""
UPDATE pipeline_fault_injections
SET consumed_at = clock_timestamp()
WHERE job_id = '{job_id}'::uuid
AND stage = 'after_objects'
AND consumed_at IS NULL;
""")
finally:
try:
if restore:
dc("start", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print(
"PASS: crash after S3 writes recovered via expired lease; "
"same job, attempt=2, variants=3, objects=4"
)
if __name__ == "__main__":
main()
+262
View File
@@ -0,0 +1,262 @@
from __future__ import annotations
import base64
import hashlib
import json
import secrets
import subprocess
import time
from uuid import UUID, uuid4
from queued_restart import ROOT, api, dc, http, wait_ready
from outbox_gap import snapshot
EVIDENCE = ROOT / "evidence" / "before_ack.json"
def sql(query):
return dc(
"exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger",
"-X", "-A", "-t", "-v", "ON_ERROR_STOP=1",
"-c", query,
)
def worker_state():
ids = dc("ps", "-a", "-q", "worker").split()
if len(ids) != 1:
raise AssertionError("This test expects exactly one worker container")
template = (
'{"started_at":{{json .State.StartedAt}},'
'"restart_count":{{.RestartCount}}}'
)
result = subprocess.run(
["docker", "inspect", "--format", template, ids[0]],
capture_output=True,
text=True,
check=True,
)
return json.loads(result.stdout)
def object_keys(attachment_id):
code = """
import json
import sys
from uuid import UUID
from app.storage import bucket_name, get_client
attachment_id = str(UUID(sys.argv[1]))
client = get_client()
keys = []
for prefix in (
f"originals/{attachment_id}",
f"variants/{attachment_id}/",
):
for page in client.get_paginator("list_objects_v2").paginate(
Bucket=bucket_name(), Prefix=prefix,
):
keys.extend(item["Key"] for item in page.get("Contents", []))
print(json.dumps(sorted(keys)))
"""
return json.loads(
dc("exec", "-T", "worker", "python", "-c", code, attachment_id)
)
def main():
evidence = {"scenario": "worker crash after ready commit, before ack"}
job_id = None
restore = False
try:
wait_ready()
if not dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Start worker before this test")
username = "ack_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "Before ack test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
token = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "Before ack",
"member_ids": [user["id"]],
},
)
restore = True
dc("stop", "worker")
if dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Worker is still running")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = str(UUID(attachment["id"]))
path = f"/api/v1/attachments/{attachment_id}"
before = snapshot(attachment_id)
job_id = str(UUID(before["job_id"]))
sql(f"""
INSERT INTO pipeline_fault_injections (job_id, stage)
VALUES ('{job_id}'::uuid, 'before_ack');
""")
evidence["attachment_id"] = attachment_id
evidence["job_id"] = job_id
evidence["initial_job"] = before
print(f"Armed one-shot before_ack fault for job {job_id}")
dc("start", "worker")
started_state = worker_state()
evidence["worker_before_fault"] = started_state
fault_line = f"fault_injection job_id={job_id} stage=before_ack"
redelivery_line = f"delivery job_id={job_id} redelivered=True"
ack_line = f"ack job_id={job_id}"
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
logs = dc("logs", "--no-color", "--tail=300", "worker")
fault_at = logs.find(fault_line)
redelivery_at = logs.find(redelivery_line)
ack_at = logs.find(ack_line)
if 0 <= fault_at < redelivery_at < ack_at:
break
time.sleep(1)
else:
raise AssertionError(
"Expected fault -> redelivered=True -> ack was not observed"
)
evidence["delivery_events"] = [
line for line in logs.splitlines()
if job_id in line
]
print("Observed: before_ack crash -> redelivered=True -> ack")
after_state = worker_state()
assert (
after_state["started_at"] != started_state["started_at"]
or after_state["restart_count"] > started_state["restart_count"]
)
evidence["worker_after_fault"] = after_state
consumed = json.loads(sql(f"""
SELECT json_build_object(
'consumed', consumed_at IS NOT NULL
)
FROM pipeline_fault_injections
WHERE job_id = '{job_id}'::uuid
AND stage = 'before_ack';
"""))
assert consumed["consumed"] is True
final = snapshot(attachment_id)
assert final["job_id"] == job_id
assert final["status"] == "ready"
assert final["attempt"] == 1
assert final["outbox_count"] == 1
current = api("GET", path, 200, token=token)
assert current["status"] == "ready"
assert current["error_code"] is None
variants = {item["name"]: item for item in current["variants"]}
assert len(current["variants"]) == 3
assert set(variants) == {"thumbnail", "crop", "optimized"}
status, body = http("GET", path + "/content", token=token)
assert status == 200 and body == original
for name, metadata in variants.items():
status, body = http(
"GET", path + "/content?variant=" + name,
token=token,
)
assert status == 200
assert len(body) == metadata["size_bytes"]
assert hashlib.sha256(body).hexdigest() == metadata["sha256"]
variant_count = int(sql(f"""
SELECT count(*)
FROM attachment_variants
WHERE attachment_id = '{attachment_id}'::uuid;
"""))
assert variant_count == 3
keys = object_keys(attachment_id)
expected_keys = sorted([
f"originals/{attachment_id}",
f"variants/{attachment_id}/v1/thumbnail",
f"variants/{attachment_id}/v1/crop",
f"variants/{attachment_id}/v1/optimized",
])
assert keys == expected_keys
evidence["final_job"] = final
evidence["fault"] = consumed
evidence["variant_rows"] = variant_count
evidence["final_object_keys"] = keys
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
if job_id is not None:
sql(f"""
UPDATE pipeline_fault_injections
SET consumed_at = clock_timestamp()
WHERE job_id = '{job_id}'::uuid
AND stage = 'before_ack'
AND consumed_at IS NULL;
""")
finally:
try:
if restore:
dc("start", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print(
"PASS: crash before ack caused broker redelivery; "
"ready result preserved, attempt=1, variants=3, objects=4"
)
if __name__ == "__main__":
main()
+308
View File
@@ -0,0 +1,308 @@
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
from resilience import history
WORKERS = 12
ROUNDS = 3
def main():
args = arguments("Concurrent cross-replica idempotency")
control = Client(
args.base_url,
args.ca_file,
timeout=10,
)
alice, bob, eve, chat = control.bootstrap()
path = f"/api/v1/chats/{chat['id']}/messages"
check(
history(control, alice, chat) == [],
"fresh test chat is not empty",
)
clients = [
Client(args.base_url, args.ca_file, timeout=10)
for _ in range(WORKERS)
]
saved_messages = []
round_results = []
first_key = None
for round_number in range(1, ROUNDS + 1):
key = uuid.uuid4().hex
text = f"Один ключ — одно сообщение: {round_number} {key}"
if first_key is None:
first_key = key
barrier = threading.Barrier(WORKERS)
def send(index):
if index % 3 == 0:
body = {"text": text}
elif index % 3 == 1:
body = {
"attachment_ids": [],
"text": text,
}
else:
body = {
"text": text,
"attachment_ids": [],
}
raw = json.dumps(
body,
ensure_ascii=False,
indent=2 if index % 2 else None,
).encode("utf-8")
barrier.wait(timeout=15)
return clients[index].call(
"POST",
path,
expected=201,
actor=alice,
raw=raw,
headers={
"Content-Type": "application/json",
"Idempotency-Key": key,
},
schema="Message",
)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=WORKERS) as executor:
responses = list(executor.map(send, range(WORKERS)))
elapsed = time.monotonic() - started
original = responses[0]["json"]
check(
all(
response["json"] == original
for response in responses
),
"same key returned different Message objects",
)
instances = Counter(
response["headers"]["X-Instance-Id"]
for response in responses
)
check(
len(instances) >= 2,
"concurrent requests did not reach two replicas",
)
messages = history(control, bob, chat)
same_text = [
message
for message in messages
if message["text"] == text
]
check(
same_text == [original],
"concurrent repeats created zero or multiple messages",
)
check(
len(messages) == round_number,
"unexpected message count after concurrent round",
)
saved_messages.append(original)
result = {
"round": round_number,
"requests": WORKERS,
"responses_201": len(responses),
"observed_instances": len(instances),
"responses_by_instance": dict(instances),
"unique_message_ids": len(
{
response["json"]["id"]
for response in responses
}
),
"matching_history_messages": len(same_text),
"duration_seconds": round(elapsed, 3),
}
round_results.append(result)
print(json.dumps(result, ensure_ascii=False))
conflict = control.call(
"POST",
path,
expected=409,
actor=alice,
body={"text": "Другой текст с прежним ключом"},
headers={"Idempotency-Key": first_key},
)
check(
conflict["json"]["error"]["code"] == "conflict",
"wrong error code for body conflict",
)
control.call(
"POST",
path,
expected=400,
actor=alice,
body={"text": "Без ключа"},
)
for invalid_key in ("bad key", "x" * 129):
control.call(
"POST",
path,
expected=400,
actor=alice,
body={"text": "Некорректный ключ"},
headers={"Idempotency-Key": invalid_key},
)
control.call(
"POST",
path,
expected=404,
actor=eve,
body={"text": saved_messages[0]["text"]},
headers={"Idempotency-Key": first_key},
)
bob_message = control.message(
bob,
chat,
"Тот же ключ другого пользователя",
key=first_key,
)["json"]
check(
bob_message["sender_id"] == bob["id"],
"wrong sender for another user's scope",
)
check(
bob_message["id"] != saved_messages[0]["id"],
"key incorrectly shared between users",
)
second_chat = control.call(
"POST",
"/api/v1/chats",
expected=201,
actor=alice,
body={
"title": "Другой чат для области ключа",
"member_ids": [alice["id"], bob["id"]],
},
schema="Chat",
)["json"]
other_chat_message = control.message(
alice,
second_chat,
"Тот же ключ в другом чате",
key=first_key,
)["json"]
check(
other_chat_message["chat_id"] == second_chat["id"],
"wrong chat in scoped result",
)
check(
other_chat_message["id"] != saved_messages[0]["id"],
"key incorrectly shared between chats",
)
replay = control.message(
alice,
chat,
saved_messages[0]["text"],
key=first_key,
)["json"]
check(
replay == saved_messages[0],
"original result changed after scope tests",
)
messages = history(control, bob, chat)
expected = saved_messages + [bob_message]
check(
len(messages) == len(expected),
"unexpected final message count",
)
check(
{message["id"] for message in messages}
== {message["id"] for message in expected},
"missing or extra messages in first chat",
)
check(
history(control, bob, second_chat) == [other_chat_message],
"unexpected history in second chat",
)
control.call(
"DELETE",
"/api/v1/auth/sessions/current",
expected=204,
actor=alice,
)
control.call(
"POST",
path,
expected=401,
actor=alice,
body={"text": saved_messages[0]["text"]},
headers={"Idempotency-Key": first_key},
)
print(
json.dumps(
{
"rounds": ROUNDS,
"concurrent_requests_per_round": WORKERS,
"concurrent_requests_total": WORKERS * ROUNDS,
"body_conflict_409": True,
"missing_and_invalid_key_400": True,
"foreign_user_404": True,
"user_scope_independent": True,
"chat_scope_independent": True,
"replay_preserved": True,
"revoked_session_401": True,
"unexpected_messages": 0,
},
ensure_ascii=False,
)
)
print(
"PASS: concurrent cross-replica idempotency, "
"scope, validation and authorization checks."
)
if __name__ == "__main__":
run(main)
+294
View File
@@ -0,0 +1,294 @@
from __future__ import annotations
import base64
import hashlib
import json
import secrets
import subprocess
import time
from uuid import UUID, uuid4
from queued_restart import ROOT, DC, api, dc, http, wait_ready
from outbox_gap import snapshot
from before_ack import sql, object_keys
EVIDENCE = ROOT / "evidence" / "failed_replay.json"
def staging_write(attachment_id, *, original=None):
code = """
import sys
from uuid import UUID
from app.job_db import connect_db
from app.storage import _put
attachment_id = UUID(sys.argv[1])
mode = sys.argv[2]
with connect_db() as db:
row = db.execute(
'''
SELECT staging_key, content_type
FROM attachments
WHERE id = %s
''',
(attachment_id,),
).fetchone()
if row is None or not row["staging_key"]:
raise SystemExit(2)
data = (
b"deliberate synthetic staging corruption"
if mode == "corrupt"
else sys.stdin.buffer.read()
)
_put(row["staging_key"], data, row["content_type"])
"""
mode = "corrupt" if original is None else "restore"
result = subprocess.run(
[
DC, "exec", "-T", "api",
"python", "-c", code, attachment_id, mode,
],
cwd=ROOT,
input=b"" if original is None else original,
capture_output=True,
timeout=90,
)
if result.returncode:
raise RuntimeError(f"Staging operation failed: {mode}")
def replay_command(job_id, *, apply=False):
args = [
DC, "exec", "-T", "worker",
"python", "-m", "app.replay",
"--job-id", job_id,
"--actor", "student-test",
"--reason", "Synthetic staging integrity fault repaired",
]
if apply:
args.append("--apply")
result = subprocess.run(
args,
cwd=ROOT,
capture_output=True,
text=True,
timeout=90,
)
return result.returncode, json.loads(result.stdout)
def audit_count(job_id):
return int(sql(f"""
SELECT count(*)
FROM attachment_job_replays
WHERE job_id = '{job_id}'::uuid;
"""))
def wait_status(path, token, expected, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
current = api("GET", path, 200, token=token)
if current["status"] == expected:
return current
if expected == "ready" and current["status"] == "failed":
raise AssertionError(
"Replay failed: " + str(current["error_code"])
)
time.sleep(0.5)
raise AssertionError(f"Timeout waiting for {expected}")
def main():
evidence = {"scenario": "failed staging integrity and audited replay"}
restore_worker = False
corrupted = False
attachment_id = None
original = None
try:
assert sql(
"SELECT to_regclass('attachment_job_replays') IS NOT NULL;"
) == "t", "Apply migration 007 first"
wait_ready()
if not dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Start worker before this test")
username = "rep_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "Failed replay test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
token = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "Failed replay",
"member_ids": [user["id"]],
},
)
restore_worker = True
dc("stop", "worker")
if dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Worker is still running")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = str(UUID(attachment["id"]))
path = f"/api/v1/attachments/{attachment_id}"
job_id = str(UUID(snapshot(attachment_id)["job_id"]))
evidence["attachment_id"] = attachment_id
evidence["job_id"] = job_id
# Отмечаем до вызова, чтобы finally попытался восстановить
# исходник даже при неопределённом результате S3-записи.
corrupted = True
staging_write(attachment_id)
dc("start", "worker")
failed = wait_status(path, token, "failed")
assert failed["error_code"] == "invalid_image"
assert failed["variants"] == []
failed_job = snapshot(attachment_id)
assert failed_job["status"] == "failed"
assert failed_job["attempt"] == 1
assert failed_job["outbox_count"] == 1
assert audit_count(job_id) == 0
registry = json.loads(
dc("exec", "-T", "worker", "python", "-m", "app.replay", "--list")
)
assert any(item["job_id"] == job_id for item in registry)
api("GET", path + "/content", 409, token=token)
api(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
409,
token=token,
payload={"text": "", "attachment_ids": [attachment_id]},
headers={"Idempotency-Key": str(uuid4())},
)
evidence["failed_job"] = failed_job
print("Corrupted staging produced failed/invalid_image; API returns 409")
code, rejected = replay_command(job_id, apply=True)
assert code != 0
assert rejected["result"] == "error"
assert snapshot(attachment_id) == failed_job
assert audit_count(job_id) == 0
evidence["rejected_replay"] = rejected
print("Replay rejected corrupted staging without state changes or audit")
staging_write(attachment_id, original=original)
corrupted = False
code, dry_run = replay_command(job_id)
assert code == 0 and dry_run["result"] == "dry_run"
assert snapshot(attachment_id) == failed_job
assert audit_count(job_id) == 0
evidence["dry_run"] = dry_run
print("Original restored; dry-run left job unchanged")
code, applied = replay_command(job_id, apply=True)
assert code == 0 and applied["result"] == "replayed"
assert applied["new_attempt"] == 2
ready = wait_status(path, token, "ready")
final = snapshot(attachment_id)
assert final["job_id"] == job_id
assert final["status"] == "ready"
assert final["attempt"] == 2
assert final["outbox_count"] == 2
assert audit_count(job_id) == 1
status, body = http("GET", path + "/content", token=token)
assert status == 200 and body == original
variants = {item["name"]: item for item in ready["variants"]}
assert len(ready["variants"]) == 3
assert set(variants) == {"thumbnail", "crop", "optimized"}
for name, metadata in variants.items():
status, body = http(
"GET", path + "/content?variant=" + name,
token=token,
)
assert status == 200
assert len(body) == metadata["size_bytes"]
assert hashlib.sha256(body).hexdigest() == metadata["sha256"]
keys_before_noop = object_keys(attachment_id)
assert len(keys_before_noop) == 4
code, noop = replay_command(job_id, apply=True)
assert code == 0
assert noop["result"] == "noop"
assert noop["status"] == "ready"
assert snapshot(attachment_id) == final
assert audit_count(job_id) == 1
assert object_keys(attachment_id) == keys_before_noop
evidence["applied_replay"] = applied
evidence["final_job"] = final
evidence["ready_replay"] = noop
evidence["audit_rows"] = 1
evidence["object_count"] = len(keys_before_noop)
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
if corrupted and attachment_id is not None:
staging_write(attachment_id, original=original)
finally:
try:
if restore_worker:
dc("start", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print(
"PASS: failed registry, integrity guard, dry-run, audited replay "
"and ready noop verified; same job, attempt=2"
)
if __name__ == "__main__":
main()
+228
View File
@@ -0,0 +1,228 @@
from __future__ import annotations
import base64
import hashlib
import io
import json
import secrets
import time
from uuid import UUID, uuid4
from PIL import Image
from queued_restart import ROOT, api, dc, http, wait_ready
EVIDENCE = ROOT / "evidence" / "outbox_gap.json"
def snapshot(attachment_id):
attachment_id = str(UUID(attachment_id))
query = f"""
SELECT json_build_object(
'job_id', j.id,
'status', j.status,
'attempt', j.attempt,
'outbox_count', (
SELECT count(*)
FROM attachment_outbox o
WHERE o.job_id = j.id
),
'published', EXISTS (
SELECT 1
FROM attachment_outbox o
WHERE o.job_id = j.id
AND o.published_at IS NOT NULL
)
)
FROM attachment_jobs j
WHERE j.attachment_id = '{attachment_id}'::uuid
AND j.pipeline_version = 1;
"""
result = dc(
"exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger",
"-X", "-A", "-t", "-v", "ON_ERROR_STOP=1",
"-c", query,
)
if not result:
raise AssertionError("Job is missing")
return json.loads(result)
def main():
evidence = {
"scenario": "API crash after COMMIT while publisher is stopped",
}
restore = False
try:
wait_ready()
for service in ("publisher", "worker"):
if not dc("ps", "--status", "running", "-q", service):
raise AssertionError(f"Start {service} before this test")
username = "gap_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "Outbox gap test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
session = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)
token = session["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "Outbox gap",
"member_ids": [user["id"]],
},
)
restore = True
dc("stop", "publisher", "worker")
for service in ("publisher", "worker"):
if dc("ps", "--status", "running", "-q", service):
raise AssertionError(f"{service} is still running")
print("Publisher and worker stopped")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = attachment["id"]
path = f"/api/v1/attachments/{attachment_id}"
assert attachment["status"] == "queued"
before = snapshot(attachment_id)
assert before["status"] == "queued"
assert before["attempt"] == 1
assert before["outbox_count"] == 1
assert before["published"] is False
evidence["attachment_id"] = attachment_id
evidence["before_crash"] = before
print("Upload 202; job committed; outbox is not published")
dc("kill", "--signal", "SIGKILL", "api")
after_crash = snapshot(attachment_id)
assert after_crash == before
evidence["after_api_kill"] = after_crash
print("API killed with SIGKILL; committed job remains in PostgreSQL")
dc("up", "-d", "--no-deps", "api")
wait_ready()
# Прежняя сессия и то же вложение должны сохраниться.
current = api("GET", path, 200, token=token)
assert current["status"] == "queued"
api("GET", path + "/content", 409, token=token)
dc("start", "publisher")
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
published = snapshot(attachment_id)
if published["published"]:
break
time.sleep(1)
else:
raise AssertionError("Pending outbox was not published")
assert published["job_id"] == before["job_id"]
assert published["attempt"] == 1
assert published["outbox_count"] == 1
evidence["after_publisher_start"] = published
print("Publisher recovered the existing outbox without a new job")
dc("start", "worker")
started = time.monotonic()
deadline = started + 90
while time.monotonic() < deadline:
current = api("GET", path, 200, token=token)
if current["status"] == "ready":
break
if current["status"] == "failed":
raise AssertionError(
"Processing failed: " + str(current["error_code"])
)
time.sleep(0.5)
else:
raise AssertionError("Ready timeout")
status, body = http("GET", path + "/content", token=token)
assert status == 200
assert body == original
variants = {item["name"]: item for item in current["variants"]}
assert set(variants) == {"thumbnail", "crop", "optimized"}
for name, expected_format in (
("thumbnail", "JPEG"),
("crop", "JPEG"),
("optimized", "WEBP"),
):
status, body = http(
"GET", path + "/content?variant=" + name,
token=token,
)
metadata = variants[name]
assert status == 200
assert len(body) == metadata["size_bytes"]
assert hashlib.sha256(body).hexdigest() == metadata["sha256"]
with Image.open(io.BytesIO(body)) as image:
image.load()
assert image.format == expected_format
assert image.size == (
metadata["width"], metadata["height"]
)
final = snapshot(attachment_id)
assert final["job_id"] == before["job_id"]
assert final["status"] == "ready"
assert final["attempt"] == 1
assert final["outbox_count"] == 1
evidence["final"] = final
evidence["ready_after_worker_start_s"] = round(
time.monotonic() - started, 3
)
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
if restore:
dc("up", "-d", "--no-deps", "api")
dc("start", "publisher", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print("PASS: committed outbox survived API crash and reached ready without a new job")
if __name__ == "__main__":
main()
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
from __future__ import annotations
import concurrent.futures
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tests"))
from client import Client
BASE_URL = "http://127.0.0.1:18082"
MAX_RESPONSE_SECONDS = 6.0
WATCHDOG_SECONDS = 8.0
COMPOSE = [
"docker", "compose",
"-f", "compose.yaml",
"-f", "compose.s3.yaml",
"--env-file", ".env",
]
def docker(*args):
return subprocess.check_output(
["docker", *args],
cwd=ROOT,
text=True,
timeout=20,
stderr=subprocess.PIPE,
).strip()
def main():
pg_id = subprocess.check_output(
[*COMPOSE, "ps", "-q", "postgres"],
cwd=ROOT,
text=True,
timeout=20,
).strip()
assert pg_id, "PostgreSQL container not found"
assert docker(
"inspect", "-f", "{{.State.Paused}}", pg_id
) == "false", "PostgreSQL is already paused"
c = Client(BASE_URL, None)
alice, _, _, chat = c.bootstrap()
message = c.message(alice, chat, "postgres-pause regression")["json"]
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
baseline_instances = set()
for _ in range(6):
response = c.call(
"GET", path, actor=alice, schema="MessagePage"
)
assert any(
item["id"] == message["id"]
for item in response["json"]["items"]
), "Baseline message is missing"
instance = response["headers"].get("X-Instance-Id")
assert instance, "Baseline response has no X-Instance-Id"
baseline_instances.add(instance)
assert len(baseline_instances) >= 2, (
"Baseline did not reach both API replicas"
)
print("Baseline: history is available through both replicas", flush=True)
def probe():
started = time.monotonic()
try:
client = Client(BASE_URL, None)
response = client.call("GET", path, 503, actor=alice)
elapsed = time.monotonic() - started
instance = response["headers"].get("X-Instance-Id")
code = response["json"]["error"]["code"]
return {
"ok": bool(instance) and code == "unavailable",
"status": 503,
"code": code,
"instance": instance,
"elapsed_s": round(elapsed, 4),
}
except Exception as exc:
return {
"ok": False,
"error_type": type(exc).__name__,
"elapsed_s": round(time.monotonic() - started, 4),
}
executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)
paused_by_test = False
try:
paused_by_test = True
docker("pause", pg_id)
assert docker(
"inspect", "-f", "{{.State.Paused}}", pg_id
) == "true"
print("PostgreSQL paused; requesting history", flush=True)
futures = [executor.submit(probe) for _ in range(4)]
_, pending = concurrent.futures.wait(
futures, timeout=WATCHDOG_SECONDS
)
assert not pending, "History requests exceeded the test watchdog"
results = [future.result() for future in futures]
print(json.dumps(results, indent=2), flush=True)
assert all(item["ok"] for item in results), (
"Expected API JSON 503 unavailable with X-Instance-Id"
)
assert all(
item["elapsed_s"] < MAX_RESPONSE_SECONDS
for item in results
), "API response exceeded the declared deadline"
failed_instances = {item["instance"] for item in results}
assert baseline_instances.issubset(failed_instances), (
"Paused-DB requests did not exercise both baseline replicas"
)
finally:
try:
if paused_by_test:
state = docker(
"inspect", "-f", "{{.State.Paused}}", pg_id
)
if state == "true":
docker("unpause", pg_id)
print("PostgreSQL unpaused", flush=True)
finally:
executor.shutdown(wait=False, cancel_futures=True)
recovery_started = time.monotonic()
recovery_deadline = recovery_started + 60
while True:
try:
response = c.call(
"GET", path, actor=alice, schema="MessagePage"
)
assert any(
item["id"] == message["id"]
for item in response["json"]["items"]
), "Confirmed message disappeared"
break
except Exception:
if time.monotonic() >= recovery_deadline:
raise AssertionError("History did not recover") from None
time.sleep(1)
report = {
"scenario": "postgres_pause_history",
"passed": True,
"max_response_seconds": MAX_RESPONSE_SECONDS,
"baseline_instances": sorted(baseline_instances),
"paused_requests": results,
"recovery_observed_after_s": round(
time.monotonic() - recovery_started, 4
),
"confirmed_message_preserved": True,
}
target = ROOT / "evidence" / "postgres_pause.json"
target.parent.mkdir(exist_ok=True)
target.write_text(json.dumps(report, indent=2) + "\n")
print("PASS: bounded API 503 on both replicas; history recovered", flush=True)
if __name__ == "__main__":
main()
+345
View File
@@ -0,0 +1,345 @@
from __future__ import annotations
import base64
import hashlib
import io
import json
from pathlib import Path
import secrets
import subprocess
import time
import urllib.error
import urllib.request
from uuid import uuid4
from PIL import Image
ROOT = Path(__file__).resolve().parent.parent
BASE = "http://127.0.0.1:18085"
DC = str(ROOT / "scripts/dc")
EVIDENCE = ROOT / "evidence" / "queued_restart.json"
def dc(*args, timeout=150):
result = subprocess.run(
[DC, *args],
cwd=ROOT,
capture_output=True,
text=True,
timeout=timeout,
)
if result.returncode:
details = "\n".join(
part.strip()
for part in (result.stdout, result.stderr)
if part.strip()
)
raise RuntimeError(
"Compose command failed: "
+ " ".join(args)
+ f" (exit={result.returncode})"
+ "\n"
+ details[-6000:]
)
return result.stdout.strip()
def http(method, path, *, token=None, payload=None, data=None, headers=None):
request_headers = dict(headers or {})
if token:
request_headers["Authorization"] = "Bearer " + token
if payload is not None:
data = json.dumps(payload).encode()
request_headers["Content-Type"] = "application/json"
request = urllib.request.Request(
BASE + path,
data=data,
headers=request_headers,
method=method,
)
try:
response = urllib.request.urlopen(request, timeout=15)
except urllib.error.HTTPError as exc:
response = exc
with response:
return response.status, response.read()
def api(method, path, expected, **kwargs):
status, body = http(method, path, **kwargs)
if status != expected:
raise AssertionError(
f"{method} {path}: expected {expected}, got {status}"
)
return json.loads(body) if body else None
def wait_ready(timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
if http("GET", "/health/ready")[0] == 200:
return
except (OSError, TimeoutError):
pass
time.sleep(1)
raise AssertionError("API readiness timeout")
def container_starts():
result = {}
for service in ("api", "broker"):
ids = dc("ps", "-q", service).split()
if not ids:
raise AssertionError(f"No running containers for {service}")
for container_id in ids:
inspected = subprocess.run(
[
"docker", "inspect",
"--format", "{{.State.StartedAt}}",
container_id,
],
check=True,
capture_output=True,
text=True,
)
result[container_id] = inspected.stdout.strip()
return result
def job_snapshot(attachment_id):
code = """
import json
import sys
from uuid import UUID
from app.job_db import connect_db
with connect_db() as db:
row = db.execute(
'''
SELECT j.status, j.attempt,
EXISTS (
SELECT 1 FROM attachment_outbox o
WHERE o.job_id = j.id
AND o.attempt = j.attempt
AND o.published_at IS NOT NULL
) AS published
FROM attachment_jobs j
WHERE j.attachment_id = %s
AND j.pipeline_version = 1
''',
(UUID(sys.argv[1]),),
).fetchone()
print(json.dumps(row))
"""
return json.loads(
dc("exec", "-T", "publisher", "python", "-c", code, attachment_id)
)
def queue_snapshot(timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
output = dc(
"exec", "-T", "broker",
"rabbitmqctl", "-q", "list_queues",
"name", "durable", "messages_ready",
timeout=20,
)
for line in output.splitlines():
fields = line.split()
if len(fields) == 3 and fields[0] == "attachment.process.v1":
return {
"name": fields[0],
"durable": fields[1].lower() == "true",
"messages_ready": int(fields[2]),
}
except (RuntimeError, subprocess.TimeoutExpired):
pass
time.sleep(2)
raise AssertionError("Queue inspection timeout")
def main():
evidence = {"scenario": "queued upload survives API and broker restart"}
stopped = False
try:
wait_ready()
if not dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Start worker before running this test")
username = "lab5_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "Queue restart test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
session = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)
token = session["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "Queued restart",
"member_ids": [user["id"]],
},
)
dc("stop", "worker")
stopped = True
if dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Worker is still running")
print("Worker stopped")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = attachment["id"]
path = f"/api/v1/attachments/{attachment_id}"
assert attachment["status"] == "queued"
evidence["attachment_id"] = attachment_id
print(f"Upload accepted: {attachment_id}, status=queued")
api("GET", path + "/content", 409, token=token)
message = api(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
201,
token=token,
payload={"text": "", "attachment_ids": [attachment_id]},
headers={"Idempotency-Key": str(uuid4())},
)
evidence["message_id"] = message["id"]
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
snapshot = job_snapshot(attachment_id)
if snapshot and snapshot["published"]:
break
time.sleep(1)
else:
raise AssertionError("Outbox was not confirmed as published")
evidence["job_before_restart"] = snapshot
before_queue = queue_snapshot()
assert before_queue["durable"]
assert before_queue["messages_ready"] >= 1
evidence["queue_before_restart"] = before_queue
before = container_starts()
dc("restart", "api", "broker")
wait_ready()
after_queue = queue_snapshot()
after = container_starts()
assert set(before) == set(after)
assert all(before[key] != after[key] for key in before)
assert after_queue["durable"]
assert after_queue["messages_ready"] >= 1
evidence["container_starts_before"] = before
evidence["container_starts_after"] = after
evidence["queue_after_restart"] = after_queue
print("API and broker restarted; queued message remains in broker")
current = api("GET", path, 200, token=token)
assert current["status"] == "queued"
api("GET", path + "/content", 409, token=token)
history = api(
"GET",
f"/api/v1/chats/{chat['id']}/messages?limit=100",
200,
token=token,
)
assert any(item["id"] == message["id"] for item in history["items"])
dc("start", "worker")
started = time.monotonic()
deadline = started + 90
while time.monotonic() < deadline:
current = api("GET", path, 200, token=token)
if current["status"] == "ready":
break
if current["status"] == "failed":
raise AssertionError(
"Attachment failed: " + str(current["error_code"])
)
time.sleep(0.5)
else:
raise AssertionError("Attachment did not become ready")
status, downloaded = http("GET", path + "/content", token=token)
assert status == 200 and downloaded == original
variants = {item["name"]: item for item in current["variants"]}
assert set(variants) == {"thumbnail", "crop", "optimized"}
for name, fmt in (
("thumbnail", "JPEG"),
("crop", "JPEG"),
("optimized", "WEBP"),
):
status, body = http(
"GET", path + "/content?variant=" + name, token=token,
)
assert status == 200
metadata = variants[name]
assert len(body) == metadata["size_bytes"]
assert hashlib.sha256(body).hexdigest() == metadata["sha256"]
with Image.open(io.BytesIO(body)) as image:
image.load()
assert image.format == fmt
assert image.size == (metadata["width"], metadata["height"])
evidence["ready_after_worker_start_s"] = round(
time.monotonic() - started, 3
)
evidence["original_sha256"] = hashlib.sha256(original).hexdigest()
evidence["variants"] = list(variants)
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
if stopped:
dc("start", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print("PASS: queued task survived API/broker restart; original and variants verified")
if __name__ == "__main__":
main()
+226
View File
@@ -0,0 +1,226 @@
from __future__ import annotations
import base64
import json
import secrets
import time
from uuid import UUID, uuid4
from queued_restart import ROOT, api, dc, wait_ready
from before_ack import sql
from failed_replay import staging_write
EVIDENCE = ROOT / "evidence" / "retry_exhaustion.json"
def job_details(attachment_id):
return json.loads(sql(f"""
SELECT json_build_object(
'job_id', j.id,
'status', j.status,
'attempt', j.attempt,
'max_attempts', j.max_attempts,
'error_code', j.error_code,
'lease_cleared',
j.lease_token IS NULL AND j.lease_until IS NULL,
'outbox', (
SELECT json_agg(
json_build_object(
'attempt', o.attempt,
'published', o.published_at IS NOT NULL,
'delay_seconds',
extract(epoch FROM (o.available_at - o.created_at))
)
ORDER BY o.attempt
)
FROM attachment_outbox o
WHERE o.job_id = j.id
)
)
FROM attachment_jobs j
WHERE j.attachment_id = '{attachment_id}'::uuid
AND j.pipeline_version = 1;
"""))
def remove_staging(attachment_id):
code = """
import sys
from uuid import UUID
from app.job_db import connect_db
from app.storage import bucket_name, get_client
with connect_db() as db:
row = db.execute(
"SELECT staging_key FROM attachments WHERE id = %s",
(UUID(sys.argv[1]),),
).fetchone()
if row is None or not row["staging_key"]:
raise RuntimeError("Expected staging reference")
get_client().delete_object(
Bucket=bucket_name(),
Key=row["staging_key"],
)
"""
dc("exec", "-T", "api", "python", "-c", code, attachment_id)
def main():
evidence = {"scenario": "temporary S3 read failure exhausts bounded retries"}
restore_worker = False
restore_staging = False
attachment_id = None
original = None
try:
wait_ready()
for service in ("publisher", "worker"):
if not dc("ps", "--status", "running", "-q", service):
raise AssertionError(f"Start {service} before this test")
username = "rty_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "Retry exhaustion test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
token = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "Retry exhaustion",
"member_ids": [user["id"]],
},
)
restore_worker = True
dc("stop", "worker")
assert not dc("ps", "--status", "running", "-q", "worker")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = str(UUID(attachment["id"]))
path = f"/api/v1/attachments/{attachment_id}"
initial = job_details(attachment_id)
assert initial["attempt"] == 1
assert initial["max_attempts"] == 5
evidence["attachment_id"] = attachment_id
evidence["initial_job"] = initial
restore_staging = True
remove_staging(attachment_id)
print("Test staging object removed; configured attempt limit=5")
dc("start", "worker")
started = time.monotonic()
deadline = started + 180
observed_attempts = []
previous_attempt = None
while time.monotonic() < deadline:
current = job_details(attachment_id)
if current["attempt"] != previous_attempt:
previous_attempt = current["attempt"]
observed_attempts.append(previous_attempt)
print(
f"Observed attempt={previous_attempt}, "
f"status={current['status']}",
flush=True,
)
if current["status"] == "failed":
break
if current["status"] == "ready":
raise AssertionError("Missing staging unexpectedly reached ready")
time.sleep(0.5)
else:
raise AssertionError("Retry exhaustion timeout")
assert current["job_id"] == initial["job_id"]
assert current["attempt"] == current["max_attempts"] == 5
assert current["error_code"] == "retry_exhausted"
assert current["lease_cleared"] is True
outbox = current["outbox"]
assert [row["attempt"] for row in outbox] == [1, 2, 3, 4, 5]
assert all(row["published"] for row in outbox)
for row in outbox:
if row["attempt"] == 1:
continue
previous = row["attempt"] - 1
upper = min(30.0, 2.0 ** min(previous, 5))
assert 0.49 <= row["delay_seconds"] <= upper + 0.1
failed = api("GET", path, 200, token=token)
assert failed["status"] == "failed"
assert failed["error_code"] == "retry_exhausted"
assert failed["variants"] == []
api("GET", path + "/content", 409, token=token)
count = int(sql(f"""
SELECT count(*) FROM attachment_variants
WHERE attachment_id = '{attachment_id}'::uuid;
"""))
assert count == 0
# Короткое дополнительное наблюдение терминального состояния.
time.sleep(5)
assert job_details(attachment_id) == current
evidence["observed_attempts"] = observed_attempts
evidence["final_job"] = current
evidence["terminal_observation_seconds"] = 5
evidence["elapsed_s"] = round(time.monotonic() - started, 3)
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
# Возвращаем принятые bytes, но failed автоматически не повторяем.
if restore_staging and attachment_id is not None:
staging_write(attachment_id, original=original)
finally:
try:
if restore_worker:
dc("start", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print(
"PASS: five published attempts exhausted retries; "
"backoff bounds verified; terminal failed/retry_exhausted, no variants"
)
if __name__ == "__main__":
main()
+284
View File
@@ -0,0 +1,284 @@
import json
from pathlib import Path
import subprocess
import sys
import time
from datetime import datetime, timezone
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run
PROJECT = "mtusi2026lab3"
def timestamp():
return datetime.now(timezone.utc).isoformat()
def command(*args):
return subprocess.check_output(
list(args),
cwd=ROOT,
text=True,
timeout=45,
).strip()
def compose(*args):
return command(
"docker",
"compose",
"-p",
PROJECT,
*args,
)
def inspect(container, template):
return command(
"docker",
"inspect",
"--format",
template,
container,
)
def api_ids():
ids = compose("ps", "-q", "api").split()
return {
inspect(container, "{{.Id}}")
for container in ids
}
def healthy(container):
return inspect(
container,
"{{.State.Running}} {{.State.Health.Status}}",
) == "true healthy"
def instance_id(container):
code = (
"import urllib.request; "
"r=urllib.request.urlopen("
"'http://127.0.0.1:8080/health/live', timeout=2); "
"print(r.headers.get('X-Instance-Id', '')); "
"r.close()"
)
return command(
"docker",
"exec",
container,
"python",
"-c",
code,
)
def main():
args = arguments("Sequential API container replacement")
client = Client(
args.base_url,
args.ca_file,
timeout=2,
)
alice, bob, eve, chat = client.bootstrap()
import uuid
key = uuid.uuid4().hex
text = "Сохранить при замене " + key
original_message = client.message(
alice,
chat,
text,
key=key,
)["json"]
original_ids = sorted(api_ids())
check(len(original_ids) == 2, "expected exactly two API containers")
for container in original_ids:
check(healthy(container), "both API containers must be healthy")
print(
json.dumps(
{
"event": "replacement_started",
"utc": timestamp(),
"original_container_ids": original_ids,
},
ensure_ascii=False,
),
flush=True,
)
replacements = []
for old in original_ids:
current = api_ids()
check(len(current) == 2, "expected two APIs before replacement")
check(old in current, "original target container is missing")
other = next(container for container in current if container != old)
check(healthy(other), "remaining API is not healthy")
other_started = inspect(other, "{{.State.StartedAt}}")
old_instance = instance_id(old)
step_started = time.monotonic()
print(
json.dumps(
{
"event": "replacing",
"utc": timestamp(),
"old_container_id": old,
"old_instance": old_instance,
"remaining_container_id": other,
},
ensure_ascii=False,
),
flush=True,
)
command("docker", "stop", "--time", "10", old)
command("docker", "rm", old)
compose(
"up",
"-d",
"--no-deps",
"--no-recreate",
"--no-build",
"--scale",
"api=2",
"api",
)
deadline = time.monotonic() + 30
replacement = None
while time.monotonic() < deadline:
current = api_ids()
candidates = current - {other}
if (
len(current) == 2
and len(candidates) == 1
and other in current
):
candidate = next(iter(candidates))
if candidate != old and healthy(candidate):
replacement = candidate
break
time.sleep(0.5)
check(replacement is not None, "replacement did not become healthy")
new_instance = instance_id(replacement)
check(new_instance != old_instance, "instance did not change")
seen_through_lb = False
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
try:
response = client.call(
"GET",
"/api/v1/users/me",
actor=alice,
schema="User",
)
except Failure:
time.sleep(0.2)
continue
if response["headers"]["X-Instance-Id"] == new_instance:
seen_through_lb = True
break
time.sleep(0.2)
check(
seen_through_lb,
"new API was not observed through LB with existing session",
)
check(healthy(other), "remaining API became unhealthy")
check(
inspect(other, "{{.State.StartedAt}}") == other_started,
"the other API was restarted unexpectedly",
)
replay = client.message(
alice,
chat,
text,
key=key,
)["json"]
check(
replay == original_message,
"confirmed message or idempotency result changed",
)
result = {
"event": "replacement_ready",
"utc": timestamp(),
"old_container_id": old,
"new_container_id": replacement,
"old_instance": old_instance,
"new_instance": new_instance,
"step_seconds": round(
time.monotonic() - step_started, 3
),
"other_api_not_restarted": True,
"existing_session_works": True,
"replay_preserved": True,
}
replacements.append(result)
print(json.dumps(result, ensure_ascii=False), flush=True)
time.sleep(3)
final_ids = api_ids()
check(len(final_ids) == 2, "expected two APIs after replacement")
check(
not final_ids.intersection(original_ids),
"some original API containers were not replaced",
)
for container in final_ids:
check(healthy(container), "final API is not healthy")
print(
json.dumps(
{
"event": "replacement_finished",
"utc": timestamp(),
"replacements": len(replacements),
"final_container_ids": sorted(final_ids),
},
ensure_ascii=False,
),
flush=True,
)
print(
"PASS: both API containers replaced sequentially; "
"existing session and confirmed message preserved.",
flush=True,
)
if __name__ == "__main__":
run(main)
+274
View File
@@ -0,0 +1,274 @@
from __future__ import annotations
import base64
import json
import secrets
import time
from uuid import UUID, uuid4
from queued_restart import ROOT, api, dc, http, wait_ready
EVIDENCE = ROOT / "evidence" / "staging_cleanup.json"
def storage_action(attachment_id, action):
code = """
import json
import sys
from uuid import UUID
from app.job_db import connect_db
from app.storage import _get, _put, bucket_name, get_client
attachment_id = UUID(sys.argv[1])
action = sys.argv[2]
prefix = f"staging/{attachment_id}/"
extra = prefix + "v99"
client = get_client()
bucket = bucket_name()
if action == "add_orphan":
_put(extra, b"synthetic unreferenced staging object", "image/png")
elif action == "remove_orphan":
client.delete_object(Bucket=bucket, Key=extra)
elif action == "add_ready_leftover":
with connect_db() as db:
with db.transaction():
row = db.execute(
'''
SELECT object_key, content_type, status
FROM attachments
WHERE id = %s
FOR UPDATE
''',
(attachment_id,),
).fetchone()
if row is None or row["status"] != "ready":
raise RuntimeError("Expected a genuinely ready attachment")
data = _get(row["object_key"])
staging_key = prefix + "v1"
_put(staging_key, data, row["content_type"])
db.execute(
"UPDATE attachments SET staging_key = %s WHERE id = %s",
(staging_key, attachment_id),
)
elif action != "inspect":
raise ValueError("Unknown action")
keys = []
for page in client.get_paginator("list_objects_v2").paginate(
Bucket=bucket, Prefix=prefix,
):
keys.extend(item["Key"] for item in page.get("Contents", []))
with connect_db() as db:
row = db.execute(
'''
SELECT status, staging_key IS NOT NULL AS staging_reference
FROM attachments WHERE id = %s
''',
(attachment_id,),
).fetchone()
print(json.dumps({"keys": sorted(keys), **row}))
"""
return json.loads(
dc(
"exec", "-T", "api",
"python", "-c", code, attachment_id, action,
)
)
def cleanup(attachment_id, *, apply=False):
args = [
"exec", "-T", "worker",
"python", "-m", "app.cleanup_staging",
"--attachment-id", attachment_id,
"--grace-seconds", "0",
"--allow-short-grace",
]
if apply:
args.append("--apply")
return json.loads(dc(*args))
def main():
evidence = {"scenario": "scoped staging cleanup safety"}
attachment_id = None
restore = False
try:
wait_ready()
if not dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Start worker before this test")
username = "cln_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "Staging cleanup test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
token = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "Staging cleanup",
"member_ids": [user["id"]],
},
)
restore = True
dc("stop", "worker")
assert not dc("ps", "--status", "running", "-q", "worker")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = str(UUID(attachment["id"]))
path = f"/api/v1/attachments/{attachment_id}"
active_key = f"staging/{attachment_id}/v1"
orphan_key = f"staging/{attachment_id}/v99"
state = storage_action(attachment_id, "add_orphan")
assert state["status"] == "queued"
assert state["keys"] == sorted([active_key, orphan_key])
# worker остановлен, поэтому уборщик запускаем в API-контейнере.
# Модуль и настройки хранилищ у него те же.
def scoped_cleanup(apply):
args = [
"exec", "-T", "api",
"python", "-m", "app.cleanup_staging",
"--attachment-id", attachment_id,
"--grace-seconds", "0",
"--allow-short-grace",
]
if apply:
args.append("--apply")
return json.loads(dc(*args))
dry = scoped_cleanup(False)
assert dry["active"] == 1
assert dry["candidates"] == 1
assert dry["deleted"] == 0
assert storage_action(attachment_id, "inspect")["keys"] == state["keys"]
applied = scoped_cleanup(True)
assert applied["active"] == 1
assert applied["deleted"] == 1
state = storage_action(attachment_id, "inspect")
assert state["keys"] == [active_key]
assert state["staging_reference"] is True
assert api("GET", path, 200, token=token)["status"] == "queued"
evidence["queued_dry_run"] = dry
evidence["queued_apply"] = applied
print("Dry-run preserved both objects; apply removed only the orphan")
dc("start", "worker")
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
ready = api("GET", path, 200, token=token)
if ready["status"] == "ready":
break
if ready["status"] == "failed":
raise AssertionError("Active staging was not processed")
time.sleep(0.5)
else:
raise AssertionError("Ready timeout")
# Дожидаемся завершения штатной уборки в job_runner.
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
state = storage_action(attachment_id, "inspect")
if not state["keys"] and not state["staging_reference"]:
break
time.sleep(0.5)
else:
raise AssertionError("Normal staging cleanup did not finish")
# Имитируем остаток после сбоя удаления, не подделывая ready:
# оригинал и варианты уже созданы настоящим worker.
storage_action(attachment_id, "add_ready_leftover")
ready_dry = cleanup(attachment_id)
assert ready_dry["candidates"] == 1
assert ready_dry["deleted"] == 0
ready_apply = cleanup(attachment_id, apply=True)
assert ready_apply["deleted"] == 1
state = storage_action(attachment_id, "inspect")
assert state["status"] == "ready"
assert state["keys"] == []
assert state["staging_reference"] is False
assert api("GET", path, 200, token=token) == ready
status, body = http("GET", path + "/content", token=token)
assert status == 200 and body == original
for variant in ready["variants"]:
status, body = http(
"GET", path + "/content?variant=" + variant["name"],
token=token,
)
assert status == 200
assert len(body) == variant["size_bytes"]
evidence["attachment_id"] = attachment_id
evidence["ready_dry_run"] = ready_dry
evidence["ready_apply"] = ready_apply
evidence["final_storage_state"] = state
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
if attachment_id is not None:
storage_action(attachment_id, "remove_orphan")
finally:
try:
if restore:
dc("start", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print(
"PASS: dry-run is non-destructive; queued staging preserved; "
"orphan and ready leftover removed; ready content intact"
)
if __name__ == "__main__":
main()
+318
View File
@@ -0,0 +1,318 @@
#!/usr/bin/env python3
"""Targeted API failure test. Uses synthetic data; leaves target stopped."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run
from resilience import history
PROJECT = "mtusi2026lab3"
def docker_output(*args):
return subprocess.check_output(
["docker", *args],
cwd=ROOT,
text=True,
).strip()
def target_instance(container):
labels = json.loads(
docker_output(
"inspect",
"--format",
"{{json .Config.Labels}}",
container,
)
)
check(
labels.get("com.docker.compose.project") == PROJECT,
"target belongs to another Compose project",
)
check(
labels.get("com.docker.compose.service") == "api",
"target is not an API container",
)
check(
docker_output(
"inspect",
"--format",
"{{.State.Running}}",
container,
) == "true",
"target container is not running",
)
code = (
"import urllib.request; "
"r=urllib.request.urlopen("
"'http://127.0.0.1:8080/health/live', timeout=2); "
"print(r.headers.get('X-Instance-Id', '')); "
"r.close()"
)
instance = docker_output(
"exec", container, "python", "-c", code
)
check(bool(instance), "target has no X-Instance-Id")
return instance
def main():
def configure(parser):
parser.add_argument(
"--target-container",
required=True,
)
args = arguments(
"Targeted API failover through the load balancer",
configure,
)
script = ROOT / "scripts" / "stop-one.sh"
check(
script.is_file() and os.access(script, os.X_OK),
"stop-one.sh must exist and be executable",
)
target = target_instance(args.target_container)
client = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, eve, chat = client.bootstrap()
original_key = uuid.uuid4().hex
original_text = "Подтверждено до отказа " + original_key
original = client.message(
alice,
chat,
original_text,
key=original_key,
)["json"]
observed = set()
for _ in range(40):
response = client.call(
"GET",
"/api/v1/users/me",
actor=alice,
schema="User",
)
observed.add(response["headers"]["X-Instance-Id"])
check(len(observed) >= 2, "less than two API instances")
check(target in observed, "target is not observed through LB")
env = dict(os.environ)
env["TARGET_INSTANCE_ID"] = target
print(
"Target container:",
args.target_container,
"| instance:",
target,
flush=True,
)
started = time.monotonic()
proc = subprocess.Popen(
[str(script)],
cwd=ROOT,
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
successes = []
write_failures = 0
read_successes = 0
read_failures = 0
after_instances = []
first_recovery = None
attempts = 0
key = uuid.uuid4().hex
text = "Во время отказа " + key
try:
while time.monotonic() - started < 15:
code = proc.poll()
elapsed = time.monotonic() - started
check(
code is None or code == 0,
"stop-one hook failed",
)
check(
code is not None or elapsed < 10,
"stop-one hook exceeded 10 seconds",
)
attempts += 1
try:
response = client.message(
alice,
chat,
text,
key=key,
)
except Failure:
write_failures += 1
# Keep the same key and text after uncertain POST.
else:
successes.append(response["json"])
if proc.poll() == 0:
if first_recovery is None:
first_recovery = time.monotonic() - started
after_instances.append(
response["headers"]["X-Instance-Id"]
)
key = uuid.uuid4().hex
text = "Во время отказа " + key
if attempts % 5 == 0:
try:
page = client.call(
"GET",
(
"/api/v1/chats/"
+ chat["id"]
+ "/messages?limit=100"
),
actor=bob,
schema="MessagePage",
)["json"]
except Failure:
read_failures += 1
else:
check(
any(
message == original
for message in page["items"]
),
"confirmed message absent during read",
)
read_successes += 1
time.sleep(0.1)
elapsed = time.monotonic() - started
check(proc.poll() == 0, "stop-one hook did not finish")
check(
first_recovery is not None and first_recovery <= 10,
"writes did not recover within 10 seconds",
)
check(
len(after_instances) >= 5,
"too few writes after stop",
)
check(
target not in after_instances[-5:],
"stopped instance still serves requests",
)
check(read_successes > 0, "no successful history reads")
check(
docker_output(
"inspect",
"--format",
"{{.State.Running}}",
args.target_container,
) == "false",
"target container is still running",
)
replay = client.message(
alice,
chat,
original_text,
key=original_key,
)["json"]
check(
replay == original,
"replay after failure returned another message",
)
messages = history(client, bob, chat)
by_id = {message["id"]: message for message in messages}
check(
len(by_id) == len(messages),
"duplicate message IDs",
)
check(
by_id.get(original["id"]) == original,
"pre-failure message lost or altered",
)
for message in successes:
check(
by_id.get(message["id"]) == message,
"confirmed in-flight message lost or altered",
)
texts = [message["text"] for message in messages]
check(
len(texts) == len(set(texts)),
"retry created duplicate message text",
)
print(
json.dumps(
{
"target_container": args.target_container,
"target_instance": target,
"observed_instances_before": len(observed),
"duration_seconds": round(elapsed, 3),
"successful_writes": len(successes),
"failed_write_attempts": write_failures,
"successful_reads": read_successes,
"failed_read_attempts": read_failures,
"successful_write_rps": round(
len(successes) / elapsed, 3
),
"first_recovery_seconds": round(
first_recovery, 3
),
"replay_preserved": True,
"target_stopped": True,
},
ensure_ascii=False,
)
)
print(
"PASS: targeted failover; session, messages "
"and replay preserved. Target remains stopped."
)
finally:
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
if __name__ == "__main__":
run(main)
+147
View File
@@ -0,0 +1,147 @@
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import unittest
from unittest.mock import MagicMock, patch
from uuid import UUID
from app.cleanup_staging import sweep
ATTACHMENT_ID = UUID("11111111-1111-4111-8111-111111111111")
KEY = f"staging/{ATTACHMENT_ID}/v1"
class CleanupStagingTests(unittest.TestCase):
def run_sweep(
self,
*,
status=None,
locked=True,
recent_failure=False,
recent_object=False,
apply=True,
):
now = datetime.now(timezone.utc)
old = now - timedelta(days=2)
modified = now + timedelta(seconds=1) if recent_object else old
row = None
if status is not None:
row = {
"id": ATTACHMENT_ID,
"status": status,
"updated_at": (
now + timedelta(seconds=1)
if recent_failure else old
),
}
db = MagicMock()
db.__enter__.return_value = db
def execute(query, params=None):
cursor = MagicMock()
if "pg_try_advisory_xact_lock" in query:
cursor.fetchone.return_value = {"locked": locked}
elif "SELECT id, status, updated_at" in query:
cursor.fetchone.return_value = row
return cursor
db.execute.side_effect = execute
client = MagicMock()
client.get_paginator.return_value.paginate.return_value = [
{"Contents": [{"Key": KEY, "LastModified": modified}]}
]
client.head_object.return_value = {"LastModified": modified}
with (
patch("app.cleanup_staging.connect_db", return_value=db),
patch("app.cleanup_staging.get_client", return_value=client),
patch("app.cleanup_staging.bucket_name", return_value="test-bucket"),
):
result = sweep(
apply=apply,
grace_seconds=86400,
attachment_id=ATTACHMENT_ID,
)
return result, db, client
def assert_no_delete(self, client):
client.delete_object.assert_not_called()
def test_queued_is_preserved_even_when_old(self):
result, _, client = self.run_sweep(status="queued")
self.assertEqual(result["active"], 1)
self.assertEqual(result["deleted"], 0)
self.assert_no_delete(client)
def test_processing_is_preserved_even_when_old(self):
result, _, client = self.run_sweep(status="processing")
self.assertEqual(result["active"], 1)
self.assertEqual(result["deleted"], 0)
self.assert_no_delete(client)
def test_busy_upload_lock_prevents_deletion(self):
result, _, client = self.run_sweep(locked=False)
self.assertEqual(result["busy"], 1)
self.assert_no_delete(client)
client.head_object.assert_not_called()
def test_recent_failed_state_preserves_old_object(self):
result, _, client = self.run_sweep(
status="failed",
recent_failure=True,
)
self.assertEqual(result["fresh"], 1)
self.assert_no_delete(client)
def test_recent_object_is_preserved(self):
result, _, client = self.run_sweep(
status="failed",
recent_object=True,
)
self.assertEqual(result["fresh"], 1)
self.assert_no_delete(client)
def test_expired_failed_staging_is_deleted_and_reference_cleared(self):
result, db, client = self.run_sweep(status="failed")
self.assertEqual(result["deleted"], 1)
client.delete_object.assert_called_once_with(
Bucket="test-bucket",
Key=KEY,
)
updates = [
call for call in db.execute.call_args_list
if "SET staging_key = NULL" in call.args[0]
]
self.assertEqual(len(updates), 1)
self.assertEqual(updates[0].args[1], (ATTACHMENT_ID, KEY))
def test_expired_failed_dry_run_is_non_destructive(self):
result, db, client = self.run_sweep(
status="failed",
apply=False,
)
self.assertEqual(result["candidates"], 1)
self.assertEqual(result["deleted"], 0)
self.assert_no_delete(client)
self.assertFalse(any(
"SET staging_key = NULL" in call.args[0]
for call in db.execute.call_args_list
))
def test_old_orphan_is_deleted_without_attachment_update(self):
result, db, client = self.run_sweep()
self.assertEqual(result["deleted"], 1)
client.delete_object.assert_called_once()
self.assertFalse(any(
"SET staging_key = NULL" in call.args[0]
for call in db.execute.call_args_list
))
if __name__ == "__main__":
unittest.main(verbosity=2)
+94
View File
@@ -0,0 +1,94 @@
from __future__ import annotations
import hashlib
import io
import unittest
from PIL import Image
from app.image_pipeline import InvalidImage, render_variants
def make_image(size, *, mode="RGB", color="red", orientation=None):
with Image.new(mode, size, color) as image:
output = io.BytesIO()
if orientation is None:
image.save(output, format="PNG")
else:
exif = Image.Exif()
exif[274] = orientation
image.save(output, format="JPEG", exif=exif)
return output.getvalue()
def variants_by_name(data):
return {
variant["name"]: variant
for variant in render_variants(data)
}
class ImagePipelineTests(unittest.TestCase):
def assert_variant(self, variant, fmt, size):
data = variant["data"]
self.assertEqual(variant["size_bytes"], len(data))
self.assertEqual(
variant["sha256"],
hashlib.sha256(data).hexdigest(),
)
self.assertEqual(
(variant["width"], variant["height"]),
size,
)
with Image.open(io.BytesIO(data)) as image:
image.load()
self.assertEqual(image.format, fmt)
self.assertEqual(image.size, size)
self.assertFalse(dict(image.getexif()))
self.assertFalse(image.info.get("icc_profile"))
self.assertFalse(image.info.get("xmp"))
def test_contract_dimensions_and_original(self):
data = make_image((320, 200))
before = hashlib.sha256(data).hexdigest()
variants = variants_by_name(data)
self.assertEqual(set(variants), {"thumbnail", "crop", "optimized"})
self.assert_variant(variants["thumbnail"], "JPEG", (256, 160))
self.assert_variant(variants["crop"], "JPEG", (128, 128))
self.assert_variant(variants["optimized"], "WEBP", (320, 200))
self.assertEqual(hashlib.sha256(data).hexdigest(), before)
def test_rounding_down(self):
variants = variants_by_name(make_image((321, 200)))
self.assert_variant(variants["thumbnail"], "JPEG", (256, 159))
def test_small_image_not_upscaled_except_crop(self):
variants = variants_by_name(make_image((64, 32)))
self.assert_variant(variants["thumbnail"], "JPEG", (64, 32))
self.assert_variant(variants["optimized"], "WEBP", (64, 32))
self.assert_variant(variants["crop"], "JPEG", (128, 128))
def test_transparency_becomes_white(self):
data = make_image((64, 32), mode="RGBA", color=(255, 0, 0, 0))
variants = variants_by_name(data)
for variant in variants.values():
with Image.open(io.BytesIO(variant["data"])) as image:
pixel = image.convert("RGB").getpixel((0, 0))
self.assertTrue(all(channel >= 245 for channel in pixel))
def test_exif_orientation(self):
data = make_image((320, 200), orientation=6)
variants = variants_by_name(data)
self.assert_variant(variants["thumbnail"], "JPEG", (160, 256))
self.assert_variant(variants["optimized"], "WEBP", (200, 320))
def test_invalid_input(self):
for data in (b"", b"not an image"):
with self.subTest(data=data):
with self.assertRaises(InvalidImage):
render_variants(data)
if __name__ == "__main__":
unittest.main()