feat: Accept durable queued uploads and publish outbox jobs (U2)

Carry forward the lab4 API and storage baseline, stage verified originals in
MinIO, and atomically commit attachment, job, and outbox records before 202.
Publish identifier-only jobs with broker confirms and reclaimable outbox leases.
Clean abandoned and completed staging objects after database checks.
This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 14:35:35 +03:00
parent af7213900b
commit b23ecc111f
34 changed files with 2017 additions and 4 deletions
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Keep broker messages within the public job schema and free of file data."""
import json
import sys
import unittest
from datetime import datetime, timezone
from pathlib import Path
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tests"))
from client import validate # noqa: E402
from src.pipeline_jobs import job_payload # noqa: E402
class OutboxPayloadTest(unittest.TestCase):
def test_job_message_has_only_contract_fields(self):
schema = json.loads((ROOT / "contracts/jobs.schema.json").read_text(encoding="utf-8"))
row = {
"job_id": uuid4(), "attachment_id": uuid4(), "pipeline_version": 2,
"attempt": 3, "created_at": datetime.now(timezone.utc),
"object_key": "staging/must-not-leak", "bytes": b"must-not-leak",
}
message = job_payload(row)
validate(message, schema)
self.assertEqual(set(message), set(schema["required"]))
self.assertNotIn("staging", json.dumps(message))
self.assertNotIn("bytes", json.dumps(message))
if __name__ == "__main__":
unittest.main()
+46
View File
@@ -0,0 +1,46 @@
"""Run inside the cleanup image against an isolated pair of staging keys."""
import time
import sys
from io import BytesIO
from pathlib import Path
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.db import pool
from src.pipeline_jobs import reserve_upload
from src.staging_cleanup import BUCKET, clean_once, storage
client = storage()
orphan_id, active_id = uuid4(), uuid4()
orphan_key, active_key = f"staging/{orphan_id}", f"staging/{active_id}"
def exists(key):
return any(obj.object_name == key for obj in client.list_objects(BUCKET, prefix=key))
try:
for key in (orphan_key, active_key):
client.put_object(BUCKET, key, BytesIO(b"test"), 4, content_type="image/png")
with pool().connection() as conn:
reserve_upload(conn, active_id, active_key, lease_seconds=60)
time.sleep(2)
clean_once(client, grace_seconds=1)
assert not exists(orphan_key), "old orphan was not removed"
assert exists(active_key), "active upload was removed"
with pool().connection() as conn:
conn.execute(
"UPDATE attachment_uploads SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=%s",
(active_id,),
)
clean_once(client, grace_seconds=1)
assert not exists(active_key), "expired orphan was not removed"
print("PASS: cleanup removes old orphans and preserves active uploads")
finally:
for key in (orphan_key, active_key):
client.remove_object(BUCKET, key)
with pool().connection() as conn:
conn.execute("DELETE FROM attachment_uploads WHERE id=%s", (active_id,))
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Exercise 202 handoff while RabbitMQ and worker are unavailable."""
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run # noqa: E402
def compose(*args):
subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT, check=True, stdout=subprocess.DEVNULL,
)
def ready_after_restart(client):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(1)
raise Failure("API did not recover after restart")
def main():
args = arguments("Lab5 durable upload handoff with stopped broker and worker")
client = Client(args.base_url, args.ca_file)
compose("stop", "worker", "publisher", "broker")
try:
alice, bob, _eve, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", 409, actor=bob)
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
check(message["attachment_ids"] == [attachment["id"]], "queued attachment cannot be linked")
compose("up", "-d", "broker")
compose("restart", "api")
ready_after_restart(client)
check(
client.call("GET", f"/api/v1/attachments/{attachment['id']}", actor=bob, schema="Attachment")["json"]["status"] == "queued",
"accepted job disappeared before publisher restart",
)
compose("up", "-d", "publisher", "worker")
client.wait_ready(bob, attachment)
result = client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)
check(result["bytes"] == original, "accepted original changed after recovery")
finally:
compose("up", "-d", "broker", "publisher", "worker")
print("PASS: accepted upload survived broker/API outage and reached ready")
if __name__ == "__main__":
run(main)
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
"""Public U2 check while publisher and worker are stopped."""
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run # noqa: E402
def main():
args = arguments("Lab5 durable queued upload")
client = Client(args.base_url, args.ca_file)
alice, bob, _eve, chat = client.bootstrap()
attachment, _content = client.attachment(alice, chat)
check(attachment["status"] == "queued", "upload did not enter queued state")
client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", 409, actor=bob)
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
check(message["attachment_ids"] == [attachment["id"]], "queued attachment cannot be linked")
print("PASS: 202 queued upload is readable and linkable; content is pending")
if __name__ == "__main__":
run(main)