forked from mtusi2026/mtusi2026lab5
refactor
This commit is contained in:
+8
-6
@@ -83,10 +83,6 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
attachment_id, job_id = uuid4(), uuid4()
|
||||
key = f"staging/{attachment_id}/original"
|
||||
async with store.attachment_transaction() as connection:
|
||||
await s3.put(key, file, size, content_type)
|
||||
# Disabled by default; models a crash after PUT, before INSERT.
|
||||
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
try:
|
||||
max_pending = int(os.environ.get("MAX_PENDING_JOBS", "100"))
|
||||
except ValueError as error:
|
||||
@@ -94,6 +90,9 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
if max_pending < 1:
|
||||
raise ApiError(503, "unavailable", "Некорректный лимит очереди")
|
||||
await store.ensure_attachment_queue_capacity(connection, max_pending)
|
||||
await s3.put(key, file, size, content_type)
|
||||
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
attachment = await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key, job_id, connection=connection,
|
||||
@@ -130,9 +129,12 @@ async def download(attachment_id: UUID, request: Request,
|
||||
if not matching:
|
||||
raise ApiError(404, "not_found", "Вариант не найден")
|
||||
item = matching[0]
|
||||
suffix = {"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp"}[variant]
|
||||
object_key = await store.pool.fetchval(
|
||||
'SELECT object_key FROM attachment_variants WHERE attachment_id=$1 AND pipeline_version=$2 AND name=$3',
|
||||
attachment_id, attachment['pipeline_version'], variant,
|
||||
)
|
||||
data = await request.app.state.s3.download_key(
|
||||
f"variants/{attachment_id}/{suffix}", item["size_bytes"], item["sha256"]
|
||||
object_key, item["size_bytes"], item["sha256"]
|
||||
)
|
||||
content_type = item["content_type"]
|
||||
return Response(data, media_type=content_type,
|
||||
|
||||
+5
-2
@@ -51,7 +51,7 @@ async def publish(payload: dict) -> None:
|
||||
|
||||
|
||||
async def publish_dlq(payload: dict) -> None:
|
||||
payload = {**payload, "failure": "retry_exhausted"}
|
||||
payload = {**payload, "failure": payload.get('failure', 'retry_exhausted')}
|
||||
try:
|
||||
await run_in_threadpool(_publish_to, DLQ, payload)
|
||||
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
|
||||
@@ -61,9 +61,12 @@ async def publish_dlq(payload: dict) -> None:
|
||||
def _publish_to(queue: str, payload: dict) -> None:
|
||||
connection = _connection()
|
||||
try:
|
||||
connection.channel().basic_publish(
|
||||
channel = connection.channel()
|
||||
channel.confirm_delivery()
|
||||
channel.basic_publish(
|
||||
exchange="", routing_key=queue, body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent, content_type="application/json"),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@@ -22,6 +22,7 @@ _CONFIGURATION_KEYS = {
|
||||
"MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
|
||||
"UPLOAD_CONCURRENCY", "UPLOAD_TIMEOUT_SECONDS", "UPLOAD_FAULT_AFTER_S3_PUT",
|
||||
"WORKER_CONCURRENCY", "JOB_MAX_ATTEMPTS", "JOB_TIMEOUT_SECONDS", "STAGING_RETENTION_SECONDS",
|
||||
"WORKER_PREFETCH", "MAX_PENDING_JOBS", "RENDER_MEMORY_MB",
|
||||
}
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ async def run() -> None:
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
await store.schedule_due_jobs()
|
||||
await store.schedule_due_jobs(int(os.environ.get('JOB_MAX_ATTEMPTS', '5')))
|
||||
for event in await store.due_outbox_events():
|
||||
await publish(event["payload"])
|
||||
await store.mark_outbox_published(event["id"])
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Operator-only metrics for one synthetic chat; never exposes credentials."""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from uuid import UUID
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
|
||||
|
||||
async def main(chat):
|
||||
store = PostgresStore(load_settings().database_url)
|
||||
await store.connect()
|
||||
try:
|
||||
rows = await store.pool.fetch('SELECT a.id, a.status, extract(epoch from (j.first_started_at-j.created_at))::float8 AS queue_wait_seconds FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.chat_id=$1', chat)
|
||||
jobs = [dict(row, id=str(row['id'])) for row in rows]
|
||||
pending = await store.pool.fetchval("SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')")
|
||||
finally:
|
||||
await store.close()
|
||||
rss = 0
|
||||
for path in Path('/proc').glob('[0-9]*/status'):
|
||||
try:
|
||||
if int(path.parent.name) == os.getpid():
|
||||
continue
|
||||
for line in path.read_text().splitlines():
|
||||
if line.startswith('VmRSS:'):
|
||||
rss += int(line.split()[1]) * 1024
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
print(json.dumps({'jobs': jobs, 'pending': pending, 'rss_bytes': rss,
|
||||
'concurrency': int(os.environ['WORKER_CONCURRENCY']),
|
||||
'prefetch': int(os.environ['WORKER_PREFETCH'])}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main(UUID(sys.argv[1])))
|
||||
+20
-5
@@ -9,6 +9,7 @@ import argparse
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import os
|
||||
from time import perf_counter
|
||||
|
||||
from .config import load_settings
|
||||
@@ -33,7 +34,11 @@ async def scan(args, db, s3) -> dict:
|
||||
# Age is measured at scan start, not after a potentially slow inventory.
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
|
||||
started = perf_counter()
|
||||
objects, s3_pages = await s3.list_with_pages("originals/")
|
||||
objects, s3_pages = {}, 0
|
||||
for prefix in ('staging/', 'originals/', 'variants/'):
|
||||
entries, pages = await s3.list_with_pages(prefix)
|
||||
objects.update(entries)
|
||||
s3_pages += pages
|
||||
listed_at = perf_counter()
|
||||
metadata = await db.attachment_keys()
|
||||
metadata_at = perf_counter()
|
||||
@@ -74,15 +79,25 @@ async def scan(args, db, s3) -> dict:
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apply", action="store_true", help="delete only aged orphan objects")
|
||||
parser.add_argument("--grace-seconds", type=int, default=3600)
|
||||
parser.add_argument("--grace-seconds", type=int, default=int(os.environ.get('STAGING_RETENTION_SECONDS', '86400')))
|
||||
parser.add_argument('--loop', action='store_true')
|
||||
parser.add_argument("--object-key", action="append", default=[],
|
||||
help="restrict apply to these exact keys; repeatable, inventory stays complete")
|
||||
args = parser.parse_args()
|
||||
if not 0 <= args.grace_seconds <= 7 * 24 * 3600:
|
||||
parser.error("--grace-seconds must be 0..604800")
|
||||
if any(not key.startswith("originals/") for key in args.object_key):
|
||||
parser.error("--object-key must start with originals/")
|
||||
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
|
||||
if any(not key.startswith(('originals/', 'staging/', 'variants/')) for key in args.object_key):
|
||||
parser.error('unsupported object prefix')
|
||||
if args.loop:
|
||||
import time
|
||||
while True:
|
||||
try:
|
||||
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
|
||||
except Exception:
|
||||
print('cleanup deferred: dependency unavailable', flush=True)
|
||||
time.sleep(60)
|
||||
else:
|
||||
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Isolated image renderer. Parent enforces wall time and kills this process."""
|
||||
import os
|
||||
import pickle
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
if sys.platform == 'linux':
|
||||
import resource
|
||||
limit = int(os.environ.get('RENDER_MEMORY_MB', '768')) * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
from .worker import variants
|
||||
from PIL import UnidentifiedImageError, Image
|
||||
try:
|
||||
data = sys.stdin.buffer.read(10485761)
|
||||
if len(data) > 10485760:
|
||||
raise ValueError('bytes limit')
|
||||
result = variants(data, int(os.environ.get('MAX_IMAGE_PIXELS', '40000000')))
|
||||
pickle.dump(result, sys.stdout.buffer)
|
||||
except MemoryError:
|
||||
sys.exit(21)
|
||||
except (ValueError, OSError, SyntaxError, UnidentifiedImageError, Image.DecompressionBombError):
|
||||
sys.exit(20)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+35
-23
@@ -247,6 +247,11 @@ class PostgresStore:
|
||||
)
|
||||
if count != len(attachment_ids):
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
failed = await connection.fetchval(
|
||||
"SELECT 1 FROM attachments WHERE id=ANY($1::uuid[]) AND status='failed' LIMIT 1", attachment_ids
|
||||
)
|
||||
if failed:
|
||||
raise ApiError(409, 'conflict', 'Вложение завершилось ошибкой')
|
||||
claimed = await connection.fetchrow(
|
||||
"INSERT INTO idempotency_records (user_id, method, path, idempotency_key, request_hash) "
|
||||
"VALUES ($1, 'POST', $2, $3, $4) ON CONFLICT DO NOTHING RETURNING message_id",
|
||||
@@ -396,16 +401,23 @@ class PostgresStore:
|
||||
attachment_id,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET status = 'processing', lease_until = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
|
||||
"UPDATE attachment_jobs SET status = 'processing', first_started_at=COALESCE(first_started_at, now()), lease_until = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
|
||||
attachment_id, lease_seconds,
|
||||
)
|
||||
return dict(row)
|
||||
result = dict(row)
|
||||
result['claim_time'] = await connection.fetchval('SELECT processing_started_at FROM attachments WHERE id=$1', attachment_id)
|
||||
return result
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variants: list[dict]) -> None:
|
||||
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variants: list[dict], claim_time) -> bool:
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
valid = await connection.fetchval(
|
||||
"SELECT 1 FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.id=$1 AND a.status='processing' AND a.processing_started_at=$2 AND j.lease_until > now() FOR UPDATE", attachment_id, claim_time
|
||||
)
|
||||
if not valid:
|
||||
return False
|
||||
for variant in variants:
|
||||
await connection.execute(
|
||||
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256) "
|
||||
@@ -418,28 +430,20 @@ class PostgresStore:
|
||||
attachment_id, original_key,
|
||||
)
|
||||
await connection.execute("UPDATE attachment_jobs SET status = 'ready', lease_until = NULL, updated_at = now() WHERE attachment_id = $1", attachment_id)
|
||||
return True
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def fail_attachment_job(self, attachment_id: UUID, code: str) -> None:
|
||||
try:
|
||||
await self.pool.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now() WHERE id = $1", attachment_id, code
|
||||
)
|
||||
await self.pool.execute(
|
||||
"UPDATE attachment_jobs SET status = 'failed', last_error = $2, updated_at = now() WHERE attachment_id = $1", attachment_id, code
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int, delay_seconds: float) -> bool:
|
||||
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int, delay_seconds: float, claim_time, permanent_code=None) -> bool:
|
||||
"""Return true only when a bounded at-least-once retry was recorded."""
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
job = await connection.fetchrow(
|
||||
"SELECT attempt FROM attachment_jobs WHERE attachment_id = $1 FOR UPDATE", attachment_id
|
||||
"SELECT j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id=$1 AND a.status='processing' AND a.processing_started_at=$2 FOR UPDATE", attachment_id, claim_time
|
||||
)
|
||||
if job is not None and job["attempt"] < max_attempts:
|
||||
if job is None:
|
||||
return False
|
||||
if permanent_code is None and job["attempt"] < max_attempts:
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET attempt = attempt + 1, status = 'queued', last_error = 'processing_failed', lease_until = NULL, next_attempt_at = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
|
||||
attachment_id, delay_seconds,
|
||||
@@ -448,14 +452,16 @@ class PostgresStore:
|
||||
"UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", attachment_id
|
||||
)
|
||||
return True
|
||||
await self.fail_attachment_job(attachment_id, "retry_exhausted")
|
||||
return False
|
||||
code = permanent_code or 'retry_exhausted'
|
||||
await connection.execute("UPDATE attachments SET status='failed', error_code=$2, updated_at=now() WHERE id=$1", attachment_id, code)
|
||||
await connection.execute("UPDATE attachment_jobs SET status='failed', last_error=$2, lease_until=NULL, updated_at=now() WHERE attachment_id=$1", attachment_id, code)
|
||||
return False
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def due_outbox_events(self, limit: int = 20) -> list[dict]:
|
||||
try:
|
||||
return [dict(row) for row in await self.pool.fetch(
|
||||
return [{**dict(row), 'payload': json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload']} for row in await self.pool.fetch(
|
||||
"SELECT id, payload FROM attachment_outbox WHERE published_at IS NULL ORDER BY created_at LIMIT $1", limit
|
||||
)]
|
||||
except DB_ERRORS as error:
|
||||
@@ -464,7 +470,7 @@ class PostgresStore:
|
||||
async def mark_outbox_published(self, event_id: UUID) -> None:
|
||||
await self.pool.execute("UPDATE attachment_outbox SET published_at = now(), attempts = attempts + 1 WHERE id = $1", event_id)
|
||||
|
||||
async def schedule_due_jobs(self) -> None:
|
||||
async def schedule_due_jobs(self, max_attempts: int = 5) -> None:
|
||||
"""Outbox dispatcher also restores expired leases and scheduled retries."""
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
@@ -474,9 +480,15 @@ class PostgresStore:
|
||||
"FOR UPDATE SKIP LOCKED"
|
||||
)
|
||||
for row in rows:
|
||||
row = dict(row)
|
||||
if row["status"] == "processing":
|
||||
if row['attempt'] >= max_attempts:
|
||||
await connection.execute("UPDATE attachment_jobs SET status='failed', lease_until=NULL, last_error='retry_exhausted', updated_at=now() WHERE job_id=$1", row['job_id'])
|
||||
await connection.execute("UPDATE attachments SET status='failed', error_code='retry_exhausted', updated_at=now() WHERE id=$1", row['attachment_id'])
|
||||
continue
|
||||
row['attempt'] += 1
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET status = 'queued', lease_until = NULL, next_attempt_at = now(), last_error = 'lease_expired', updated_at = now() WHERE job_id = $1", row["job_id"]
|
||||
"UPDATE attachment_jobs SET status = 'queued', attempt=$2, lease_until = NULL, next_attempt_at = now(), last_error = 'lease_expired', updated_at = now() WHERE job_id = $1", row["job_id"], row['attempt']
|
||||
)
|
||||
await connection.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", row["attachment_id"])
|
||||
payload = {"schema_version": 1, "job_id": str(row["job_id"]), "type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]), "pipeline_version": row["pipeline_version"], "attempt": row["attempt"], "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
|
||||
@@ -505,7 +517,7 @@ class PostgresStore:
|
||||
async def attachment_keys(self) -> dict[str, UUID]:
|
||||
"""Inventory used only by the maintenance reconciler."""
|
||||
try:
|
||||
rows = await self.pool.fetch("SELECT COALESCE(original_key, staging_key) AS object_key, id FROM attachments")
|
||||
rows = await self.pool.fetch("SELECT staging_key AS object_key, id FROM attachments WHERE status <> 'ready' UNION ALL SELECT original_key, id FROM attachments WHERE original_key IS NOT NULL UNION ALL SELECT object_key, attachment_id AS id FROM attachment_variants")
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
return {row["object_key"]: row["id"] for row in rows}
|
||||
|
||||
+94
-26
@@ -6,8 +6,13 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import pickle
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from uuid import UUID
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
@@ -19,6 +24,32 @@ from .storage.s3 import S3Settings, S3Store
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
|
||||
|
||||
|
||||
class PermanentFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fit(image, bound):
|
||||
longest = max(image.size)
|
||||
if longest <= bound:
|
||||
return image.copy()
|
||||
return image.resize((max(1, image.width * bound // longest),
|
||||
max(1, image.height * bound // longest)), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def render_isolated(data, timeout):
|
||||
try:
|
||||
result = subprocess.run([sys.executable, '-m', 'src.render'], input=data,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
raise TimeoutError('render deadline exceeded') from error
|
||||
if result.returncode in (20, 21):
|
||||
raise PermanentFailure('invalid_image' if result.returncode == 20 else 'image_resource_limit')
|
||||
if result.returncode:
|
||||
raise RuntimeError('renderer exited')
|
||||
# Only our own child process produces this payload; no external pickle input.
|
||||
return pickle.loads(result.stdout)
|
||||
|
||||
|
||||
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
|
||||
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
|
||||
image = ImageOps.exif_transpose(source)
|
||||
@@ -28,7 +59,7 @@ def thumbnail(data: bytes) -> tuple[bytes, int, int]:
|
||||
image = background.convert("RGB")
|
||||
else:
|
||||
image = image.convert("RGB")
|
||||
image.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
image = fit(image, 256)
|
||||
output = BytesIO()
|
||||
image.save(output, format="JPEG", quality=85, optimize=True)
|
||||
return output.getvalue(), image.width, image.height
|
||||
@@ -44,8 +75,7 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
|
||||
white.alpha_composite(image)
|
||||
rgb = white.convert("RGB")
|
||||
|
||||
thumb = rgb.copy()
|
||||
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
thumb = fit(rgb, 256)
|
||||
thumbnail_out = BytesIO(); thumb.save(thumbnail_out, "JPEG", quality=85, optimize=True)
|
||||
|
||||
side = min(rgb.width, rgb.height)
|
||||
@@ -53,8 +83,7 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
|
||||
crop = rgb.crop((left, top, left + side, top + side)).resize((128, 128), Image.Resampling.LANCZOS)
|
||||
crop_out = BytesIO(); crop.save(crop_out, "JPEG", quality=85, optimize=True)
|
||||
|
||||
optimized = rgb.copy()
|
||||
optimized.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
|
||||
optimized = fit(rgb, 1280)
|
||||
optimized_out = BytesIO(); optimized.save(optimized_out, "WEBP", quality=80, method=4)
|
||||
return [
|
||||
("thumbnail", thumbnail_out.getvalue(), "image/jpeg", thumb.width, thumb.height),
|
||||
@@ -64,26 +93,50 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
|
||||
|
||||
|
||||
async def process(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> None:
|
||||
# Excludes cleanup for the whole lifetime of S3 effects, including stale attempts.
|
||||
async with store.attachment_transaction():
|
||||
await process_locked(store, s3, payload, lease_seconds)
|
||||
|
||||
|
||||
async def process_locked(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> None:
|
||||
attachment_id = UUID(payload["attachment_id"])
|
||||
attachment = await store.claim_attachment_job(attachment_id, lease_seconds)
|
||||
if attachment is None:
|
||||
return
|
||||
original_key = f"originals/{attachment_id}"
|
||||
payload['_claim_time'] = attachment['claim_time']
|
||||
payload['attempt'] = attachment.get('attempt', payload.get('attempt', 1))
|
||||
attempt_key = uuid4().hex
|
||||
original_key = f"originals/{attachment_id}/{attempt_key}"
|
||||
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
|
||||
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
|
||||
rendered = await asyncio.wait_for(
|
||||
asyncio.to_thread(variants, original, s3.settings.max_pixels), timeout=lease_seconds
|
||||
)
|
||||
rendered = await asyncio.to_thread(render_isolated, original, lease_seconds)
|
||||
metadata = []
|
||||
for name, content, content_type, width, height in rendered:
|
||||
extension = "webp" if name == "optimized" else "jpg"
|
||||
object_key = f"variants/{attachment_id}/{name}.{extension}"
|
||||
object_key = f"variants/{attachment_id}/{attempt_key}/{name}.{extension}"
|
||||
await s3.put(object_key, BytesIO(content), len(content), content_type)
|
||||
metadata.append({"name": name, "object_key": object_key, "content_type": content_type,
|
||||
"size_bytes": len(content), "width": width, "height": height,
|
||||
"sha256": sha256(content).hexdigest()})
|
||||
await store.complete_attachment_job(attachment_id, original_key, metadata)
|
||||
await s3.delete(attachment["staging_key"])
|
||||
committed = await store.complete_attachment_job(attachment_id, original_key, metadata, attachment['claim_time'])
|
||||
if committed:
|
||||
try:
|
||||
await s3.delete(attachment["staging_key"])
|
||||
except Exception:
|
||||
logging.warning('staging cleanup deferred attachment_id=%s', attachment_id)
|
||||
|
||||
|
||||
def settle_delivery(channel, delivery_tag, future):
|
||||
"""Only a successful durable disposition permits acknowledgement."""
|
||||
try:
|
||||
success = future.result() is True
|
||||
except Exception:
|
||||
success = False
|
||||
if channel.is_open:
|
||||
if success:
|
||||
channel.basic_ack(delivery_tag)
|
||||
else:
|
||||
channel.basic_nack(delivery_tag, requeue=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -104,46 +157,61 @@ def main() -> None:
|
||||
s3.client.close()
|
||||
await store.close()
|
||||
|
||||
async def schedule_retry(attachment_id, delay):
|
||||
async def schedule_retry(attachment_id, delay, claim_time, permanent_code=None):
|
||||
retry_store = PostgresStore(settings.database_url)
|
||||
await retry_store.connect()
|
||||
try:
|
||||
return await retry_store.retry_attachment_job(
|
||||
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay
|
||||
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay, claim_time, permanent_code
|
||||
)
|
||||
finally:
|
||||
await retry_store.close()
|
||||
|
||||
def handle(body):
|
||||
payload = None
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError('job must be an object')
|
||||
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
|
||||
raise ValueError("unexpected broker payload")
|
||||
UUID(payload['attachment_id'])
|
||||
UUID(payload['job_id'])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
try:
|
||||
asyncio.run(publish_dlq({'failure': 'invalid_job'}))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
try:
|
||||
asyncio.run(handle_async(payload))
|
||||
except Exception:
|
||||
logging.exception("job failed")
|
||||
except Exception as error:
|
||||
logging.warning("job failed attachment_id=%s", payload['attachment_id'])
|
||||
if '_claim_time' not in payload:
|
||||
return False
|
||||
try:
|
||||
attachment_id = UUID(payload["attachment_id"])
|
||||
attempt = int(payload.get("attempt", 1))
|
||||
delay = min(60.0, float(2 ** min(attempt, 6))) * random.uniform(0.5, 1.5)
|
||||
retry = asyncio.run(schedule_retry(attachment_id, delay))
|
||||
asyncio.run(schedule_retry(attachment_id, delay, payload['_claim_time'],
|
||||
str(error) if isinstance(error, PermanentFailure) else None))
|
||||
except Exception:
|
||||
retry = False
|
||||
if not retry:
|
||||
try:
|
||||
asyncio.run(publish_dlq(payload))
|
||||
except Exception:
|
||||
logging.exception("could not publish failed job to DLQ")
|
||||
return None
|
||||
return False
|
||||
return True
|
||||
|
||||
def consume(ch, method, properties, body):
|
||||
del properties
|
||||
future = executor.submit(handle, body)
|
||||
def acknowledged(_future):
|
||||
connection.add_callback_threadsafe(lambda: ch.basic_ack(method.delivery_tag))
|
||||
if connection.is_open:
|
||||
connection.add_callback_threadsafe(lambda: settle_delivery(ch, method.delivery_tag, _future))
|
||||
future.add_done_callback(acknowledged)
|
||||
|
||||
try:
|
||||
def heartbeat():
|
||||
Path('/tmp/worker-heartbeat').write_text(str(time.time()))
|
||||
connection.call_later(2, heartbeat)
|
||||
heartbeat()
|
||||
with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="attachment-worker") as executor:
|
||||
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
|
||||
channel.start_consuming()
|
||||
|
||||
Reference in New Issue
Block a user