Implement durable image processing pipeline with outbox and recovery
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user