лаба на 5

This commit is contained in:
2026-11-12 15:32:10 +03:00
parent 910252c277
commit 0edfe46482
13 changed files with 1378 additions and 31 deletions
+2 -1
View File
@@ -17,7 +17,8 @@ async def dispatch(channel):
UPDATE attachment_jobs
SET status = 'queued',
published_at = NULL,
started_at = NULL
started_at = NULL,
execution_id = NULL
WHERE status = 'processing'
AND started_at < now() - interval '90 seconds'
""")
+16
View File
@@ -69,3 +69,19 @@ async def ping_storage() -> bool:
return True
except Exception:
return False
async def object_exists(key: str) -> bool:
from botocore.exceptions import ClientError
try:
await asyncio.to_thread(
s3_client.head_object,
Bucket=S3_BUCKET,
Key=key,
)
return True
except ClientError as exc:
if exc.response["Error"]["Code"] in {"404", "NoSuchKey", "NotFound"}:
return False
raise
+59 -6
View File
@@ -6,7 +6,7 @@ import json
import logging
import time
import random
from uuid import UUID
from uuid import UUID, uuid4
from PIL import Image, ImageOps, UnidentifiedImageError
from sqlalchemy import text
@@ -96,10 +96,31 @@ def make_optimized(body: bytes):
return output.getvalue(), image.width, image.height
def fault_injection(point: str):
if os.getenv("FAULT_INJECTION_ENABLED") != "1":
return
if os.getenv("FAULT_INJECTION_POINT") != point:
return
marker = f"/tmp/lab5_fault_{point}"
try:
fd = os.open(marker, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
except FileExistsError:
return
os.close(fd)
logging.error("FAULT INJECTION: %s", point)
os._exit(77)
async def process(payload: dict):
job_id = UUID(payload["job_id"])
attachment_id = UUID(payload["attachment_id"])
generation = payload.get("generation", 1)
execution_id = uuid4()
async with SessionFactory() as session:
async with session.begin():
@@ -133,10 +154,12 @@ async def process(payload: dict):
await session.execute(
text("""
UPDATE attachment_jobs
SET status = 'processing', started_at = now()
SET status = 'processing',
started_at = now(),
execution_id = :execution_id
WHERE id = :id
"""),
{"id": job_id},
{"id": job_id, "execution_id": execution_id},
)
await session.execute(
@@ -170,6 +193,8 @@ async def process(payload: dict):
f"variants/{row.chat_id}/{attachment_id}/g{generation}/thumbnail.jpg"
)
fault_injection("before_side_effect")
await put_object(original_key, body, row.content_type)
await put_object(thumbnail_key, thumbnail, "image/jpeg")
crop_key = (
@@ -182,6 +207,26 @@ async def process(payload: dict):
await put_object(crop_key, crop, "image/jpeg")
await put_object(optimized_key, optimized, "image/webp")
fault_injection("after_side_effect")
if (
os.getenv("FAULT_INJECTION_ENABLED") == "1"
and os.getenv("FAULT_INJECTION_POINT") == "pause_before_commit"
):
marker = "/tmp/lab5_pause_before_commit"
with open(marker, "w", encoding="utf-8") as file:
file.write(str(execution_id))
deadline = time.monotonic() + 180
while os.path.exists(marker):
if time.monotonic() >= deadline:
raise TimeoutError("pause_before_commit_timeout")
await asyncio.sleep(0.1)
variant = {
"name": "thumbnail",
"s3_key": thumbnail_key,
@@ -196,7 +241,7 @@ async def process(payload: dict):
async with session.begin():
result = await session.execute(
text("""
SELECT status, attempt, generation
SELECT status, attempt, generation, execution_id
FROM attachment_jobs
WHERE id = :id
FOR UPDATE
@@ -211,6 +256,7 @@ async def process(payload: dict):
or current.status != "processing"
or current.attempt != row.attempt
or current.generation != generation
or current.execution_id != execution_id
):
return
await session.execute(
@@ -283,7 +329,7 @@ async def process(payload: dict):
async with session.begin():
result = await session.execute(
text("""
SELECT status, attempt, generation
SELECT status, attempt, generation, execution_id
FROM attachment_jobs
WHERE id = :id
FOR UPDATE
@@ -298,6 +344,7 @@ async def process(payload: dict):
or current.status != "processing"
or current.attempt != row.attempt
or current.generation != generation
or current.execution_id != execution_id
):
return
if permanent or row.attempt >= 5:
@@ -368,7 +415,13 @@ def main():
def callback(ch, method, properties, body):
try:
loop.run_until_complete(process(json.loads(body)))
loop.run_until_complete(
asyncio.wait_for(
process(json.loads(body)),
timeout=MAX_PROCESSING_SECONDS,
)
)
fault_injection("before_ack")
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception:
logging.exception("Worker processing error")