ЛР 5: реализация мессенджера и сценарии проверки

This commit is contained in:
Russiankryt
2026-12-03 17:20:51 +03:00
parent 276dbdad8a
commit 02e9d457f1
30 changed files with 1932 additions and 37 deletions
+100
View File
@@ -0,0 +1,100 @@
"""Inject worker termination around effects and verify a stale version is a no-op."""
import collections
import json
from unittest.mock import patch
from uuid import UUID
from attachments import Objects
from db import Store
from pipeline import GROUP, STREAM, claim, connect_broker, process, relay_once, try_publish
from replay import replay
class InjectedCrash(BaseException):
pass
def expire_lease(store, message):
with store.pool.connection() as db:
db.execute("""
UPDATE image_jobs SET leased_until=clock_timestamp()-interval '1 second'
WHERE id=%s
""", (UUID(message["job_id"]),))
def state(store, row):
with store.pool.connection() as db:
return db.execute("SELECT * FROM attachments WHERE id=%s", (row,)).fetchone()
def event(broker, job_id):
for _, fields in reversed(broker.xrange(STREAM)):
message = json.loads(fields["job"])
if message["job_id"] == str(job_id):
return message
raise AssertionError("durable job was not relayed")
def main():
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("attachment", type=UUID, help="One newly queued image in the isolated test stack")
args = parser.parse_args()
store, broker, objects = Store(), connect_broker(), Objects()
attachment = args.attachment
try:
assert state(store, attachment)["status"] == "queued"
with store.pool.connection() as db:
original = db.execute("SELECT id FROM image_jobs WHERE attachment_id=%s", (attachment,)).fetchone()["id"]
assert relay_once(store, broker)
message = event(broker, original)
job = claim(store, message)
assert job
# The first worker dies after taking a lease, before any object is written.
expire_lease(store, message)
job = claim(store, message)
calls = collections.Counter()
put = objects.put
def crash_after_object(key, *pos, **named):
result = put(key, *pos, **named)
calls[key] += 1
raise InjectedCrash()
try:
with patch.object(objects, "put", side_effect=crash_after_object):
try_publish(store, objects, job)
except InjectedCrash:
pass
else:
raise AssertionError("fault did not fire after an object was written")
assert state(store, attachment)["status"] == "processing"
expire_lease(store, message)
assert process(store, objects, message) == "ready"
first = state(store, attachment)
assert process(store, objects, message) == "ignored"
assert state(store, attachment) == first
second_id = replay(store, attachment, new_version=True)
assert relay_once(store, broker)
second_message = event(broker, second_id)
assert process(store, objects, second_message) == "ready"
second = state(store, attachment)
assert second["pipeline_version"] == first["pipeline_version"] + 1
assert process(store, objects, message) == "ignored"
assert state(store, attachment) == second
assert len(calls) == 1 and len(second["variants"]) == 3
print(json.dumps({"before_effect": True, "after_effect_before_commit": True,
"duplicate_after_commit": True, "old_delivery_after_v2": True,
"ready_variants": len(second["variants"])}, indent=2))
finally:
broker.close()
store.pool.close()
if __name__ == "__main__":
main()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Reproduce the worker-offline trajectory on a running test stack."""
import argparse
import hashlib
import json
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, check
from image_probe import jpeg_size
def compose(*args):
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, timeout=90)
def wait_api(client):
end = time.monotonic() + 45
while time.monotonic() < end:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(0.5)
raise Failure("API did not recover")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--pause", type=int, default=0, help="Extra seconds with worker stopped")
parser.add_argument("--no-restart", action="store_true", help="Keep API up during telemetry demo")
args = parser.parse_args()
client = Client(args.base_url)
actor, peer, _, chat = client.bootstrap()
compose("stop", "worker")
try:
upload, original = client.attachment(actor, chat)
message = client.message(actor, chat, "", attachments=[upload["id"]])["json"]
check(message["attachment_ids"] == [upload["id"]], "message lost queued attachment")
meta = "/api/v1/attachments/" + upload["id"]
client.call("GET", meta + "/content", 409, actor=peer)
print("202 queued, привязка к сообщению 201, скачивание 409.", flush=True)
if args.pause:
time.sleep(args.pause)
if not args.no_restart:
compose("restart", "broker", "api")
wait_api(client)
queued = client.call("GET", meta, actor=peer, schema="Attachment")["json"]
check(queued["status"] == "queued", "restart lost the pending job")
print("После рестарта без worker задача осталась queued.", flush=True)
finally:
compose("start", "worker")
ready = client.wait_ready(peer, upload)
variants = {item["name"]: item for item in ready["variants"]}
check({"thumbnail", "crop", "optimized"} <= variants.keys(), "missing generated variants")
downloaded = client.call("GET", meta + "/content", actor=peer)["bytes"]
thumb = client.call("GET", meta + "/content?variant=thumbnail", actor=peer)["bytes"]
check(downloaded == original, "original changed")
check(jpeg_size(thumb) == (256, 160), "thumbnail dimensions changed")
check(variants["thumbnail"]["sha256"] == hashlib.sha256(thumb).hexdigest(), "thumbnail hash changed")
print(json.dumps({"status": ready["status"], "thumbnail": "256x160",
"variants": sorted(variants), "original_matches": True}, indent=2))
if __name__ == "__main__":
main()