forked from mtusi2026/mtusi2026lab5
Принимать файл отдельно от обработки, чтобы задание переживало рестарт и повторную доставку.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Messenger lab5 application package."""
|
||||
@@ -0,0 +1,91 @@
|
||||
"""RabbitMQ publisher confirms. Payloads are job ids, never file bytes or credentials."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
|
||||
import pika
|
||||
from pika.exceptions import AMQPError, NackError, UnroutableError
|
||||
|
||||
log = logging.getLogger("messenger.broker")
|
||||
|
||||
EXCHANGE = "attachment.jobs"
|
||||
QUEUE = "attachment.process"
|
||||
DLQ = "attachment.dlq"
|
||||
ROUTING_PROCESS = "process"
|
||||
ROUTING_DLQ = "dlq"
|
||||
|
||||
|
||||
def _declare(channel) -> None:
|
||||
channel.exchange_declare(exchange=EXCHANGE, exchange_type="direct", durable=True)
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
channel.queue_bind(queue=DLQ, exchange=EXCHANGE, routing_key=ROUTING_DLQ)
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.queue_bind(queue=QUEUE, exchange=EXCHANGE, routing_key=ROUTING_PROCESS)
|
||||
|
||||
|
||||
class Publisher:
|
||||
def __init__(self, url: str):
|
||||
self._url = url
|
||||
self._lock = threading.Lock()
|
||||
self._connection = None
|
||||
self._channel = None
|
||||
|
||||
def _reset(self) -> None:
|
||||
try:
|
||||
if self._connection is not None and self._connection.is_open:
|
||||
self._connection.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._connection = None
|
||||
self._channel = None
|
||||
|
||||
def _channel_locked(self):
|
||||
if self._channel is not None and self._channel.is_open:
|
||||
return self._channel
|
||||
self._reset()
|
||||
params = pika.URLParameters(self._url)
|
||||
params.heartbeat = 30
|
||||
params.blocked_connection_timeout = 30
|
||||
params.socket_timeout = 10
|
||||
self._connection = pika.BlockingConnection(params)
|
||||
channel = self._connection.channel()
|
||||
channel.confirm_delivery()
|
||||
_declare(channel)
|
||||
self._channel = channel
|
||||
return channel
|
||||
|
||||
def publish(self, payload: dict, routing_key: str = ROUTING_PROCESS) -> bool:
|
||||
body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
with self._lock:
|
||||
try:
|
||||
channel = self._channel_locked()
|
||||
channel.basic_publish(
|
||||
exchange=EXCHANGE,
|
||||
routing_key=routing_key,
|
||||
body=body,
|
||||
properties=pika.BasicProperties(
|
||||
content_type="application/json",
|
||||
delivery_mode=2,
|
||||
type="attachment.process.v1",
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
return True
|
||||
except (AMQPError, NackError, UnroutableError, OSError):
|
||||
log.warning("broker publish was not confirmed", exc_info=True)
|
||||
self._reset()
|
||||
return False
|
||||
|
||||
|
||||
def open_consumer(url: str):
|
||||
params = pika.URLParameters(url)
|
||||
params.heartbeat = 30
|
||||
params.blocked_connection_timeout = 30
|
||||
params.socket_timeout = 10
|
||||
connection = pika.BlockingConnection(params)
|
||||
channel = connection.channel()
|
||||
_declare(channel)
|
||||
channel.basic_qos(prefetch_count=1)
|
||||
return connection, channel
|
||||
@@ -0,0 +1,99 @@
|
||||
"""PostgreSQL pool and migrations. The database is the source of truth."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
log = logging.getLogger("messenger.db")
|
||||
|
||||
_pool: ConnectionPool | None = None
|
||||
_MIGRATION = Path(__file__).resolve().parents[1] / "migrations" / "001_init.sql"
|
||||
_LOCK = 8152026
|
||||
|
||||
|
||||
def init_pool(database_url: str, min_size: int = 1, max_size: int = 8) -> ConnectionPool:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
return _pool
|
||||
deadline = time.monotonic() + 60
|
||||
last = None
|
||||
while True:
|
||||
try:
|
||||
pool = ConnectionPool(
|
||||
database_url,
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
kwargs={"row_factory": dict_row, "autocommit": False},
|
||||
open=True,
|
||||
check=ConnectionPool.check_connection,
|
||||
)
|
||||
with pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
_pool = pool
|
||||
return pool
|
||||
except Exception as exc: # noqa: BLE001 - startup must wait for Postgres
|
||||
last = exc
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError("database did not become reachable") from last
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def pool() -> ConnectionPool:
|
||||
if _pool is None:
|
||||
raise RuntimeError("database pool is not initialized")
|
||||
return _pool
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection():
|
||||
with pool().connection() as conn:
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def _statements(sql: str) -> list[str]:
|
||||
statements = []
|
||||
current: list[str] = []
|
||||
for line in sql.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("--"):
|
||||
continue
|
||||
current.append(line)
|
||||
if stripped.endswith(";"):
|
||||
statement = "\n".join(current).strip()
|
||||
if statement:
|
||||
statements.append(statement)
|
||||
current = []
|
||||
trailing = "\n".join(current).strip()
|
||||
if trailing:
|
||||
statements.append(trailing)
|
||||
return statements
|
||||
|
||||
|
||||
def migrate(database_url: str) -> None:
|
||||
init_pool(database_url)
|
||||
statements = _statements(_MIGRATION.read_text(encoding="utf-8"))
|
||||
with connection() as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (_LOCK,))
|
||||
for statement in statements:
|
||||
conn.execute(statement)
|
||||
log.info("schema ready")
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
try:
|
||||
with connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
log.warning("database ping failed", exc_info=True)
|
||||
return False
|
||||
@@ -0,0 +1,19 @@
|
||||
"""API errors that map onto the contract body. Details never include SQL or secrets."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, headers: dict | None = None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def unauthorized(kind: str) -> ApiError:
|
||||
if kind == "basic":
|
||||
header = 'Basic realm="messenger", charset="UTF-8"'
|
||||
else:
|
||||
header = 'Bearer realm="messenger"'
|
||||
return ApiError(401, "unauthorized", "Требуется действительная аутентификация", {"WWW-Authenticate": header})
|
||||
+1070
File diff suppressed because it is too large
Load Diff
+182
@@ -0,0 +1,182 @@
|
||||
"""Image inspection and variant rendering.
|
||||
|
||||
Thumbnail: JPEG, fit inside 256×256, no upscale, EXIF orientation applied, alpha on white.
|
||||
Crop: JPEG, centered square resized to 128×128; upscale is allowed.
|
||||
Optimized: WebP, fit inside 1280×1280, no upscale. Quality and metadata policy live in
|
||||
pipeline_params and are recorded in the report.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||
_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
|
||||
|
||||
class ImageRejected(Exception):
|
||||
def __init__(self, status: int, code: str, message: str):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PipelineParams:
|
||||
version: int
|
||||
jpeg_quality: int
|
||||
crop_quality: int
|
||||
webp_quality: int
|
||||
webp_method: int
|
||||
|
||||
|
||||
def pipeline_params(version: int) -> PipelineParams:
|
||||
"""Version 1 is the course pipeline. Version 2 changes only quality, so a stale
|
||||
writer can be detected by checksum without changing geometry."""
|
||||
if version == 1:
|
||||
return PipelineParams(1, jpeg_quality=85, crop_quality=85, webp_quality=80, webp_method=6)
|
||||
if version == 2:
|
||||
return PipelineParams(2, jpeg_quality=60, crop_quality=70, webp_quality=50, webp_method=4)
|
||||
raise ImageRejected(400, "invalid_request", "Неизвестная версия pipeline")
|
||||
|
||||
|
||||
def _png_size(data: bytes) -> tuple[int, int]:
|
||||
if len(data) < 24 or data[:8] != PNG_MAGIC or data[12:16] != b"IHDR":
|
||||
raise ImageRejected(415, "unsupported_media_type", "Файл не является корректным PNG")
|
||||
if b"IEND" not in data:
|
||||
raise ImageRejected(415, "unsupported_media_type", "PNG повреждён")
|
||||
width = int.from_bytes(data[16:20], "big")
|
||||
height = int.from_bytes(data[20:24], "big")
|
||||
return width, height
|
||||
|
||||
|
||||
def _jpeg_size(data: bytes) -> tuple[int, int]:
|
||||
if len(data) < 4 or data[:2] != b"\xff\xd8":
|
||||
raise ImageRejected(415, "unsupported_media_type", "Файл не является корректным JPEG")
|
||||
index = 2
|
||||
while index < len(data):
|
||||
if data[index] != 0xFF:
|
||||
raise ImageRejected(415, "unsupported_media_type", "JPEG повреждён")
|
||||
while index < len(data) and data[index] == 0xFF:
|
||||
index += 1
|
||||
if index >= len(data):
|
||||
break
|
||||
marker = data[index]
|
||||
index += 1
|
||||
if marker in {0xD8, 0xD9, 0xDA} or marker == 0x01 or 0xD0 <= marker <= 0xD7:
|
||||
if marker in {0xD9, 0xDA}:
|
||||
break
|
||||
continue
|
||||
if index + 2 > len(data):
|
||||
break
|
||||
length = int.from_bytes(data[index:index + 2], "big")
|
||||
if length < 2 or index + length > len(data):
|
||||
raise ImageRejected(415, "unsupported_media_type", "JPEG повреждён")
|
||||
if marker in _SOF:
|
||||
if length < 8:
|
||||
raise ImageRejected(415, "unsupported_media_type", "JPEG повреждён")
|
||||
height = int.from_bytes(data[index + 3:index + 5], "big")
|
||||
width = int.from_bytes(data[index + 5:index + 7], "big")
|
||||
return width, height
|
||||
index += length
|
||||
raise ImageRejected(415, "unsupported_media_type", "Не удалось прочитать размеры JPEG")
|
||||
|
||||
|
||||
def inspect_upload(data: bytes, declared: str, max_bytes: int, max_pixels: int) -> tuple[str, int, int]:
|
||||
"""Validate a client upload from headers and the container, before a full decode."""
|
||||
if len(data) > max_bytes:
|
||||
raise ImageRejected(413, "payload_too_large", "Превышен размер файла")
|
||||
if not data:
|
||||
raise ImageRejected(415, "unsupported_media_type", "Пустое изображение")
|
||||
if declared == "image/png":
|
||||
if not data.startswith(PNG_MAGIC):
|
||||
raise ImageRejected(415, "unsupported_media_type", "Содержимое не соответствует PNG")
|
||||
width, height = _png_size(data)
|
||||
content_type = "image/png"
|
||||
elif declared == "image/jpeg":
|
||||
if not data.startswith(b"\xff\xd8\xff"):
|
||||
raise ImageRejected(415, "unsupported_media_type", "Содержимое не соответствует JPEG")
|
||||
width, height = _jpeg_size(data)
|
||||
content_type = "image/jpeg"
|
||||
else:
|
||||
raise ImageRejected(415, "unsupported_media_type", "Допустимы только PNG и JPEG")
|
||||
if width < 1 or height < 1:
|
||||
raise ImageRejected(415, "unsupported_media_type", "Некорректные размеры изображения")
|
||||
if width > max_pixels or height > max_pixels or width * height > max_pixels:
|
||||
raise ImageRejected(413, "payload_too_large", "Превышено число пикселей")
|
||||
return content_type, width, height
|
||||
|
||||
|
||||
def fit_inside(width: int, height: int, box: int, allow_upscale: bool) -> tuple[int, int]:
|
||||
scale = min(box / width, box / height)
|
||||
if not allow_upscale:
|
||||
scale = min(scale, 1.0)
|
||||
return max(1, math.floor(width * scale)), max(1, math.floor(height * scale))
|
||||
|
||||
|
||||
def _to_rgb_white(image: Image.Image) -> Image.Image:
|
||||
if image.mode == "RGB":
|
||||
return image
|
||||
if image.mode == "P" and "transparency" in image.info:
|
||||
image = image.convert("RGBA")
|
||||
if image.mode in {"RGBA", "LA"}:
|
||||
rgba = image.convert("RGBA")
|
||||
background = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||
background.paste(rgba, mask=rgba.getchannel("A"))
|
||||
return background
|
||||
return image.convert("RGB")
|
||||
|
||||
|
||||
def decode_image(data: bytes, max_pixels: int) -> Image.Image:
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
try:
|
||||
image = Image.open(io.BytesIO(data))
|
||||
width, height = image.size
|
||||
if width < 1 or height < 1 or width * height > max_pixels:
|
||||
raise ImageRejected(413, "payload_too_large", "Превышено число пикселей")
|
||||
image = ImageOps.exif_transpose(image)
|
||||
width, height = image.size
|
||||
if width * height > max_pixels:
|
||||
raise ImageRejected(413, "payload_too_large", "Превышено число пикселей")
|
||||
image.load()
|
||||
except ImageRejected:
|
||||
raise
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError) as exc:
|
||||
raise ImageRejected(415, "unsupported_media_type", "Изображение повреждено") from exc
|
||||
return _to_rgb_white(image)
|
||||
|
||||
|
||||
def _jpeg_bytes(image: Image.Image, quality: int) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=False)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _webp_bytes(image: Image.Image, quality: int, method: int) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="WEBP", quality=quality, method=method, lossless=False, exact=False)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def render_variants(source: Image.Image, params: PipelineParams) -> dict[str, dict]:
|
||||
width, height = source.size
|
||||
thumb_w, thumb_h = fit_inside(width, height, 256, allow_upscale=False)
|
||||
thumbnail = source if (thumb_w, thumb_h) == (width, height) else source.resize((thumb_w, thumb_h), Image.Resampling.LANCZOS)
|
||||
side = min(width, height)
|
||||
left = (width - side) // 2
|
||||
top = (height - side) // 2
|
||||
crop = source.crop((left, top, left + side, top + side)).resize((128, 128), Image.Resampling.LANCZOS)
|
||||
opt_w, opt_h = fit_inside(width, height, 1280, allow_upscale=False)
|
||||
optimized = source if (opt_w, opt_h) == (width, height) else source.resize((opt_w, opt_h), Image.Resampling.LANCZOS)
|
||||
thumb_bytes = _jpeg_bytes(thumbnail, params.jpeg_quality)
|
||||
crop_bytes = _jpeg_bytes(crop, params.crop_quality)
|
||||
webp_bytes = _webp_bytes(optimized, params.webp_quality, params.webp_method)
|
||||
return {
|
||||
"thumbnail": {"bytes": thumb_bytes, "content_type": "image/jpeg", "width": thumb_w, "height": thumb_h},
|
||||
"crop": {"bytes": crop_bytes, "content_type": "image/jpeg", "width": 128, "height": 128},
|
||||
"optimized": {"bytes": webp_bytes, "content_type": "image/webp", "width": opt_w, "height": opt_h},
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"""API process entrypoint."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import uvicorn
|
||||
|
||||
from app.broker import Publisher
|
||||
from app.db import migrate
|
||||
from app.httpapi import create_app
|
||||
from app.outbox import start_relay
|
||||
from app.runtime import init
|
||||
from app.s3store import ObjectStore
|
||||
from app.settings import load
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
settings = load()
|
||||
migrate(settings.database_url)
|
||||
store = ObjectStore(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_region,
|
||||
settings.s3_bucket,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
)
|
||||
store.ensure_bucket()
|
||||
init(settings, store, Publisher(settings.broker_url))
|
||||
start_relay()
|
||||
uvicorn.run(create_app(), host=settings.host, port=settings.port, log_level="info", access_log=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
"""Transactional outbox and operator controls shared by the API and the worker."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from app import runtime
|
||||
from app.broker import ROUTING_DLQ
|
||||
from app.db import connection
|
||||
from app.timeutil import iso
|
||||
|
||||
log = logging.getLogger("messenger.outbox")
|
||||
|
||||
|
||||
def payload_for(job_id, attachment_id, pipeline_version: int, attempt: int, created_at) -> dict:
|
||||
created = created_at if isinstance(created_at, str) else iso(created_at)
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": int(pipeline_version),
|
||||
"attempt": int(attempt),
|
||||
"created_at": created,
|
||||
}
|
||||
|
||||
|
||||
def add_outbox(conn, job_id, attachment_id, pipeline_version: int, attempt: int, created_at) -> dict:
|
||||
body = payload_for(job_id, attachment_id, pipeline_version, attempt, created_at)
|
||||
conn.execute(
|
||||
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||
(job_id, Jsonb(body)),
|
||||
)
|
||||
return body
|
||||
|
||||
|
||||
def audit(conn, job_id, attachment_id, action: str, detail: dict) -> None:
|
||||
conn.execute(
|
||||
"INSERT INTO job_audit (job_id, attachment_id, action, detail) VALUES (%s, %s, %s, %s)",
|
||||
(job_id, attachment_id, action, Jsonb(detail)),
|
||||
)
|
||||
|
||||
|
||||
def outbox_paused(conn) -> bool:
|
||||
row = conn.execute("SELECT value FROM runtime_control WHERE key='outbox_paused'").fetchone()
|
||||
return bool(row and row["value"] is True)
|
||||
|
||||
|
||||
def relay_tick(limit: int = 10) -> int:
|
||||
"""Publish committed outbox rows. A crash after COMMIT and before confirm leaves the row unpublished."""
|
||||
settings, _store, publisher = runtime.require()
|
||||
published = 0
|
||||
with connection() as conn:
|
||||
if outbox_paused(conn):
|
||||
return 0
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE outbox AS o
|
||||
SET published_at = clock_timestamp()
|
||||
FROM jobs AS j
|
||||
WHERE o.job_id = j.job_id
|
||||
AND o.published_at IS NULL
|
||||
AND j.status IN ('ready', 'failed', 'superseded')
|
||||
"""
|
||||
)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT o.id, o.payload
|
||||
FROM outbox AS o
|
||||
JOIN jobs AS j ON j.job_id = o.job_id
|
||||
WHERE o.published_at IS NULL
|
||||
AND j.status = 'queued'
|
||||
AND (j.next_attempt_at IS NULL OR j.next_attempt_at <= clock_timestamp())
|
||||
ORDER BY o.id
|
||||
FOR UPDATE OF o SKIP LOCKED
|
||||
LIMIT %s
|
||||
""",
|
||||
(limit,),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
if publisher.publish(row["payload"]):
|
||||
conn.execute("UPDATE outbox SET published_at = clock_timestamp() WHERE id = %s", (row["id"],))
|
||||
published += 1
|
||||
else:
|
||||
break
|
||||
if published:
|
||||
log.info("published %s job message(s)", published)
|
||||
return published
|
||||
|
||||
|
||||
def publish_dlq(body: dict) -> None:
|
||||
_settings, _store, publisher = runtime.require()
|
||||
publisher.publish(body, routing_key=ROUTING_DLQ)
|
||||
|
||||
|
||||
def start_relay() -> None:
|
||||
import threading
|
||||
import time
|
||||
|
||||
def loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
relay_tick()
|
||||
except Exception:
|
||||
log.warning("outbox relay iteration failed", exc_info=True)
|
||||
time.sleep(0.4)
|
||||
|
||||
threading.Thread(target=loop, name="outbox-relay", daemon=True).start()
|
||||
|
||||
|
||||
def new_job_id() -> uuid.UUID:
|
||||
return uuid.uuid4()
|
||||
+592
@@ -0,0 +1,592 @@
|
||||
"""Idempotent attachment pipeline.
|
||||
|
||||
The effect key is (attachment_id, pipeline_version, variant). Object keys include that
|
||||
identity, database rows use it as a primary key, and a completed job is a no-op.
|
||||
Delivery is at least once; this module does not claim exactly-once delivery.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from app import runtime
|
||||
from app.db import connection
|
||||
from app.images import ImageRejected, decode_image, pipeline_params, render_variants
|
||||
from app.outbox import add_outbox, audit, publish_dlq
|
||||
|
||||
log = logging.getLogger("messenger.pipeline")
|
||||
|
||||
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
|
||||
|
||||
|
||||
class TransientJobError(Exception):
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
|
||||
class PermanentJobError(Exception):
|
||||
def __init__(self, code: str, message: str):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def _safe(text: str) -> str:
|
||||
cleaned = " ".join(text.split())
|
||||
return cleaned[:180] or "processing failed"
|
||||
|
||||
|
||||
def _parse_message(body: dict) -> dict:
|
||||
required = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
|
||||
if not isinstance(body, dict) or set(body) - required - {"traceparent", "tracestate"}:
|
||||
raise PermanentJobError("processing_failed", "invalid job message")
|
||||
if any(key not in body for key in required):
|
||||
raise PermanentJobError("processing_failed", "invalid job message")
|
||||
if body["schema_version"] != 1 or body["type"] != "attachment.process.v1":
|
||||
raise PermanentJobError("processing_failed", "invalid job message")
|
||||
try:
|
||||
return {
|
||||
"job_id": uuid.UUID(str(body["job_id"])),
|
||||
"attachment_id": uuid.UUID(str(body["attachment_id"])),
|
||||
"pipeline_version": int(body["pipeline_version"]),
|
||||
"attempt": int(body["attempt"]),
|
||||
"created_at": str(body["created_at"]),
|
||||
}
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise PermanentJobError("processing_failed", "invalid job message") from exc
|
||||
|
||||
|
||||
def _read_fault(conn) -> dict:
|
||||
row = conn.execute("SELECT value FROM runtime_control WHERE key = 'worker_fault' FOR UPDATE").fetchone()
|
||||
value = row["value"] if row else {}
|
||||
return dict(value) if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _write_fault(conn, value: dict) -> None:
|
||||
conn.execute("UPDATE runtime_control SET value = %s WHERE key = 'worker_fault'", (Jsonb(value),))
|
||||
|
||||
|
||||
def _consume_counted_fault() -> str | None:
|
||||
"""Disarm one-shot and counted faults. Crash faults stay armed until their injection point."""
|
||||
with connection() as conn:
|
||||
value = _read_fault(conn)
|
||||
if not value.get("armed"):
|
||||
return None
|
||||
mode = value.get("mode")
|
||||
if mode == "transient":
|
||||
remaining = int(value.get("remaining") or 1) - 1
|
||||
if remaining <= 0:
|
||||
_write_fault(conn, {"mode": None, "armed": False})
|
||||
else:
|
||||
_write_fault(conn, {"mode": "transient", "armed": True, "remaining": remaining})
|
||||
return "transient"
|
||||
if mode in {"permanent", "duplicate"}:
|
||||
_write_fault(conn, {"mode": None, "armed": False})
|
||||
return mode
|
||||
if mode in {"before_effect", "after_s3", "after_commit"}:
|
||||
return mode
|
||||
return None
|
||||
|
||||
|
||||
def _crash(mode: str, job_id, attachment_id) -> None:
|
||||
with connection() as conn:
|
||||
value = _read_fault(conn)
|
||||
if value.get("armed") and value.get("mode") == mode:
|
||||
_write_fault(conn, {"mode": None, "armed": False})
|
||||
audit(conn, job_id, attachment_id, "fault_" + mode, {"mode": mode})
|
||||
if mode in {"before_effect", "after_s3"}:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'queued', lease_until = NULL, lease_owner = NULL, updated_at = clock_timestamp()
|
||||
WHERE job_id = %s AND status = 'processing'
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE attachments AS a
|
||||
SET status = 'queued', updated_at = clock_timestamp()
|
||||
FROM jobs AS j
|
||||
WHERE j.job_id = %s AND a.id = j.attachment_id
|
||||
AND a.pipeline_version = j.pipeline_version AND a.status = 'processing'
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
log.warning("fault injection exit: %s", mode)
|
||||
os._exit(75)
|
||||
|
||||
|
||||
def _load(conn, message: dict):
|
||||
job = conn.execute("SELECT * FROM jobs WHERE job_id = %s FOR UPDATE", (message["job_id"],)).fetchone()
|
||||
attachment = None
|
||||
if job is not None:
|
||||
attachment = conn.execute("SELECT * FROM attachments WHERE id = %s FOR UPDATE", (job["attachment_id"],)).fetchone()
|
||||
return job, attachment
|
||||
|
||||
|
||||
def _finish_noop(conn, job, attachment, action: str, redelivered: bool) -> None:
|
||||
audit(conn, job["job_id"] if job else None, attachment["id"] if attachment else None, action, {"redelivered": redelivered})
|
||||
|
||||
|
||||
def _supersede(conn, job, attachment, redelivered: bool) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'superseded', lease_until = NULL, lease_owner = NULL, updated_at = clock_timestamp()
|
||||
WHERE job_id = %s AND status IN ('queued', 'processing')
|
||||
""",
|
||||
(job["job_id"],),
|
||||
)
|
||||
_finish_noop(conn, job, attachment, "superseded", redelivered)
|
||||
|
||||
|
||||
def _acquire(conn, job, worker_id: str, timeout_seconds: int):
|
||||
return conn.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'processing',
|
||||
lease_owner = %s,
|
||||
lease_until = clock_timestamp() + make_interval(secs => %s),
|
||||
updated_at = clock_timestamp()
|
||||
WHERE job_id = %s
|
||||
AND status IN ('queued', 'processing')
|
||||
AND (lease_until IS NULL OR lease_until < clock_timestamp() OR lease_owner = %s)
|
||||
RETURNING job_id
|
||||
""",
|
||||
(worker_id, timeout_seconds, job["job_id"], worker_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _schedule_retry(conn, job, attachment, message: str) -> None:
|
||||
settings, _store, _publisher = runtime.require()
|
||||
attempt = int(job["attempt"])
|
||||
if attempt >= settings.job_max_attempts:
|
||||
_fail(conn, job, attachment, "retry_exhausted", "transient", "retry budget exhausted")
|
||||
return
|
||||
import random
|
||||
|
||||
delay = min(settings.job_backoff_cap_seconds, settings.job_backoff_base_seconds * (2 ** (attempt - 1)))
|
||||
delay = delay * (0.5 + random.random())
|
||||
next_attempt = attempt + 1
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'queued', attempt = %s, next_attempt_at = clock_timestamp() + make_interval(secs => %s),
|
||||
lease_until = NULL, lease_owner = NULL, error_class = 'transient', error_code = 'processing_failed',
|
||||
last_error = %s, updated_at = clock_timestamp()
|
||||
WHERE job_id = %s
|
||||
""",
|
||||
(next_attempt, delay, _safe(message), job["job_id"]),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = %s AND pipeline_version = %s AND status <> 'ready'
|
||||
""",
|
||||
(attachment["id"], job["pipeline_version"]),
|
||||
)
|
||||
add_outbox(conn, job["job_id"], attachment["id"], job["pipeline_version"], next_attempt, job["created_at"])
|
||||
audit(conn, job["job_id"], attachment["id"], "retry", {"attempt": next_attempt, "delay_seconds": round(delay, 3)})
|
||||
|
||||
|
||||
def _fail(conn, job, attachment, code: str, error_class: str, message: str) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'failed', error_code = %s, error_class = %s, last_error = %s,
|
||||
lease_until = NULL, lease_owner = NULL, next_attempt_at = NULL, updated_at = clock_timestamp()
|
||||
WHERE job_id = %s
|
||||
""",
|
||||
(code, error_class, _safe(message), job["job_id"]),
|
||||
)
|
||||
if attachment["ready_pipeline_version"] is not None:
|
||||
# A failed newer attempt must not discard an already published result.
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'ready', error_code = NULL, pipeline_version = ready_pipeline_version,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE id = %s AND ready_pipeline_version IS NOT NULL
|
||||
""",
|
||||
(attachment["id"],),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = %s, updated_at = clock_timestamp()
|
||||
WHERE id = %s AND pipeline_version = %s AND status <> 'ready'
|
||||
""",
|
||||
(code, attachment["id"], job["pipeline_version"]),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO failed_jobs (job_id, attachment_id, pipeline_version, attempt, error_code, error_class, safe_message)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(job["job_id"], attachment["id"], job["pipeline_version"], job["attempt"], code, error_class, _safe(message)),
|
||||
)
|
||||
audit(conn, job["job_id"], attachment["id"], "failed", {"error_code": code, "error_class": error_class})
|
||||
publish_dlq(
|
||||
{
|
||||
"schema_version": 1,
|
||||
"job_id": str(job["job_id"]),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment["id"]),
|
||||
"pipeline_version": int(job["pipeline_version"]),
|
||||
"attempt": int(job["attempt"]),
|
||||
"created_at": message_created(job),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def message_created(job) -> str:
|
||||
from app.timeutil import iso as format_iso
|
||||
|
||||
value = job["created_at"]
|
||||
return value if isinstance(value, str) else format_iso(value)
|
||||
|
||||
|
||||
def _put_original(store, attachment, data: bytes) -> None:
|
||||
existing = store.get(attachment["original_key"])
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
if digest != attachment["sha256"]:
|
||||
raise PermanentJobError("processing_failed", "checksum mismatch")
|
||||
if existing is None:
|
||||
store.put(attachment["original_key"], data, attachment["content_type"])
|
||||
return
|
||||
if hashlib.sha256(existing).hexdigest() != attachment["sha256"]:
|
||||
raise TransientJobError("stored original does not match the accepted checksum")
|
||||
|
||||
|
||||
def _store_variants(store, attachment, version: int, rendered: dict, max_pixels: int) -> list[dict]:
|
||||
stored = []
|
||||
for name in VARIANT_NAMES:
|
||||
item = rendered[name]
|
||||
key = f"variants/{attachment['id']}/v{version}/{name}"
|
||||
existing = store.get(key)
|
||||
if existing is None:
|
||||
store.put(key, item["bytes"], item["content_type"])
|
||||
blob = item["bytes"]
|
||||
width, height = item["width"], item["height"]
|
||||
else:
|
||||
blob = existing
|
||||
if hashlib.sha256(blob).hexdigest() == hashlib.sha256(item["bytes"]).hexdigest():
|
||||
width, height = item["width"], item["height"]
|
||||
else:
|
||||
probed = decode_image(blob, max_pixels)
|
||||
width, height = probed.size
|
||||
stored.append(
|
||||
{
|
||||
"name": name,
|
||||
"content_type": item["content_type"] if existing is None else _content_type_for(name, blob, item["content_type"]),
|
||||
"size_bytes": len(blob),
|
||||
"width": width,
|
||||
"height": height,
|
||||
"sha256": hashlib.sha256(blob).hexdigest(),
|
||||
"object_key": key,
|
||||
}
|
||||
)
|
||||
return stored
|
||||
|
||||
|
||||
def _content_type_for(name: str, blob: bytes, encoded_type: str) -> str:
|
||||
if blob.startswith(b"\xff\xd8"):
|
||||
return "image/jpeg"
|
||||
if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
|
||||
return "image/webp"
|
||||
return encoded_type
|
||||
|
||||
|
||||
def _source_bytes(store, attachment) -> bytes:
|
||||
data = store.get(attachment["staging_key"])
|
||||
if data is None:
|
||||
data = store.get(attachment["original_key"])
|
||||
if data is None:
|
||||
raise TransientJobError("source object is not available yet")
|
||||
return data
|
||||
|
||||
|
||||
def _commit_success(job, attachment, variants: list[dict], worker_id: str, crash_after_commit: bool) -> bool:
|
||||
"""Returns True when this version became the published result."""
|
||||
settings, store, _publisher = runtime.require()
|
||||
with connection() as conn:
|
||||
current = conn.execute("SELECT pipeline_version, ready_pipeline_version FROM attachments WHERE id = %s FOR UPDATE", (attachment["id"],)).fetchone()
|
||||
for item in variants:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO attachment_variants (
|
||||
attachment_id, pipeline_version, name, content_type, size_bytes, width, height, sha256, object_key
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING
|
||||
""",
|
||||
(
|
||||
attachment["id"],
|
||||
job["pipeline_version"],
|
||||
item["name"],
|
||||
item["content_type"],
|
||||
item["size_bytes"],
|
||||
item["width"],
|
||||
item["height"],
|
||||
item["sha256"],
|
||||
item["object_key"],
|
||||
),
|
||||
)
|
||||
updated = conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'ready', ready_pipeline_version = %s, error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = %s
|
||||
AND pipeline_version = %s
|
||||
AND (ready_pipeline_version IS NULL OR ready_pipeline_version <= %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(job["pipeline_version"], attachment["id"], job["pipeline_version"], job["pipeline_version"]),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'ready', error_code = NULL, error_class = NULL, last_error = NULL,
|
||||
lease_until = NULL, lease_owner = NULL, next_attempt_at = NULL, updated_at = clock_timestamp()
|
||||
WHERE job_id = %s
|
||||
""",
|
||||
(job["job_id"],),
|
||||
)
|
||||
if crash_after_commit:
|
||||
_write_fault(conn, {"mode": None, "armed": False})
|
||||
audit(conn, job["job_id"], attachment["id"], "fault_after_commit", {"worker": worker_id})
|
||||
audit(
|
||||
conn,
|
||||
job["job_id"],
|
||||
attachment["id"],
|
||||
"committed",
|
||||
{"pipeline_version": job["pipeline_version"], "published": bool(updated), "variants": len(variants)},
|
||||
)
|
||||
published = updated is not None and current is not None
|
||||
if crash_after_commit:
|
||||
os._exit(75)
|
||||
if published:
|
||||
try:
|
||||
store.delete(attachment["staging_key"])
|
||||
with connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE attachments SET staging_deleted_at = clock_timestamp() WHERE id = %s AND status = 'ready'",
|
||||
(attachment["id"],),
|
||||
)
|
||||
except Exception:
|
||||
log.warning("staging cleanup deferred for %s", attachment["id"])
|
||||
return published
|
||||
|
||||
|
||||
def _execute(message: dict, attachment: dict, worker_id: str, fault: str | None) -> None:
|
||||
settings, store, _publisher = runtime.require()
|
||||
if fault == "before_effect":
|
||||
_crash("before_effect", message["job_id"], attachment["id"])
|
||||
deadline = time.monotonic() + settings.job_timeout_seconds
|
||||
data = _source_bytes(store, attachment)
|
||||
if len(data) > settings.max_upload_bytes:
|
||||
raise PermanentJobError("invalid_image", "object exceeds the byte limit")
|
||||
if time.monotonic() > deadline:
|
||||
raise TransientJobError("processing deadline exceeded")
|
||||
try:
|
||||
image = _decode_limited(data, settings.max_image_pixels, max(1, deadline - time.monotonic()))
|
||||
params = pipeline_params(int(attachment_version(message)))
|
||||
rendered = render_variants(image, params)
|
||||
except ImageRejected as exc:
|
||||
raise PermanentJobError("invalid_image", exc.message) from exc
|
||||
if time.monotonic() > deadline:
|
||||
raise TransientJobError("processing deadline exceeded")
|
||||
_put_original(store, attachment, data)
|
||||
variants = _store_variants(store, attachment, message["pipeline_version"], rendered, settings.max_image_pixels)
|
||||
if fault == "after_s3":
|
||||
_crash("after_s3", message["job_id"], attachment["id"])
|
||||
_commit_success(message_as_job(message, attachment), attachment, variants, worker_id, fault == "after_commit")
|
||||
|
||||
|
||||
def attachment_version(message: dict) -> int:
|
||||
return int(message["pipeline_version"])
|
||||
|
||||
|
||||
def message_as_job(message: dict, attachment: dict) -> dict:
|
||||
return {
|
||||
"job_id": message["job_id"],
|
||||
"pipeline_version": message["pipeline_version"],
|
||||
"attempt": message["attempt"],
|
||||
"created_at": message["created_at"],
|
||||
"attachment_id": attachment["id"],
|
||||
}
|
||||
|
||||
|
||||
def _decode_limited(data: bytes, max_pixels: int, timeout: float):
|
||||
box: dict = {}
|
||||
|
||||
def run() -> None:
|
||||
try:
|
||||
box["image"] = decode_image(data, max_pixels)
|
||||
except Exception as exc: # noqa: BLE001 - transferred to the caller
|
||||
box["error"] = exc
|
||||
|
||||
thread = threading.Thread(target=run, daemon=True)
|
||||
thread.start()
|
||||
thread.join(timeout)
|
||||
if thread.is_alive():
|
||||
raise TransientJobError("decode timed out")
|
||||
if "error" in box:
|
||||
raise box["error"]
|
||||
return box["image"]
|
||||
|
||||
|
||||
def _handle_known_error(message: dict, exc: Exception) -> None:
|
||||
with connection() as conn:
|
||||
job, attachment = _load(conn, message)
|
||||
if job is None or attachment is None or job["status"] in {"ready", "failed", "superseded"}:
|
||||
return
|
||||
if isinstance(exc, PermanentJobError):
|
||||
_fail(conn, job, attachment, exc.code, "permanent", exc.message)
|
||||
elif isinstance(exc, TransientJobError):
|
||||
_schedule_retry(conn, job, attachment, exc.message)
|
||||
else:
|
||||
_schedule_retry(conn, job, attachment, "temporary processing failure")
|
||||
|
||||
|
||||
def process_delivery(raw: bytes, redelivered: bool, worker_id: str) -> str:
|
||||
"""Returns 'ack' or 'nack'. Ack happens only after the durable decision is committed."""
|
||||
import json
|
||||
|
||||
try:
|
||||
body = json.loads(raw.decode("utf-8"))
|
||||
message = _parse_message(body)
|
||||
except (UnicodeError, json.JSONDecodeError, PermanentJobError):
|
||||
log.warning("discarding a job message that does not match the contract")
|
||||
return "ack"
|
||||
try:
|
||||
fault = _consume_counted_fault()
|
||||
except Exception:
|
||||
log.warning("fault control unreadable", exc_info=True)
|
||||
return "nack"
|
||||
if fault == "transient":
|
||||
_handle_known_error(message, TransientJobError("injected transient failure"))
|
||||
return "ack"
|
||||
if fault == "permanent":
|
||||
_handle_known_error(message, PermanentJobError("invalid_image", "injected permanent failure"))
|
||||
return "ack"
|
||||
runs = 2 if fault == "duplicate" else 1
|
||||
for _ in range(runs):
|
||||
outcome = _process_once(message, redelivered, worker_id, fault if runs == 1 else None)
|
||||
if outcome == "nack":
|
||||
return "nack"
|
||||
fault = None
|
||||
return "ack"
|
||||
|
||||
|
||||
def _process_once(message: dict, redelivered: bool, worker_id: str, fault: str | None) -> str:
|
||||
settings, _store, _publisher = runtime.require()
|
||||
with connection() as conn:
|
||||
job, attachment = _load(conn, message)
|
||||
if job is None or attachment is None:
|
||||
audit(conn, message["job_id"], message["attachment_id"], "missing", {"redelivered": redelivered})
|
||||
return "ack"
|
||||
if job["status"] in {"ready", "superseded", "failed"}:
|
||||
_finish_noop(conn, job, attachment, "noop_" + job["status"], redelivered)
|
||||
return "ack"
|
||||
if message["attempt"] != int(job["attempt"]):
|
||||
_finish_noop(conn, job, attachment, "noop_attempt", redelivered)
|
||||
return "ack"
|
||||
newer_ready = (
|
||||
attachment["ready_pipeline_version"] is not None
|
||||
and int(attachment["ready_pipeline_version"]) > int(job["pipeline_version"])
|
||||
)
|
||||
newer_desired = int(attachment["pipeline_version"]) > int(job["pipeline_version"])
|
||||
if newer_ready or newer_desired:
|
||||
_supersede(conn, job, attachment, redelivered)
|
||||
return "ack"
|
||||
if _acquire(conn, job, worker_id, settings.job_timeout_seconds) is None:
|
||||
return "nack"
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'processing', updated_at = clock_timestamp()
|
||||
WHERE id = %s AND pipeline_version = %s AND status IN ('queued', 'processing')
|
||||
""",
|
||||
(attachment["id"], job["pipeline_version"]),
|
||||
)
|
||||
audit(conn, job["job_id"], attachment["id"], "leased", {"worker": worker_id, "redelivered": redelivered})
|
||||
try:
|
||||
_execute(message, attachment, worker_id, fault)
|
||||
except (PermanentJobError, TransientJobError, ImageRejected) as exc:
|
||||
if isinstance(exc, ImageRejected):
|
||||
exc = PermanentJobError("invalid_image", exc.message)
|
||||
_handle_known_error(message, exc)
|
||||
except Exception:
|
||||
log.warning("unexpected pipeline error", exc_info=True)
|
||||
_handle_known_error(message, TransientJobError("temporary processing failure"))
|
||||
return "ack"
|
||||
|
||||
|
||||
def recover_expired_leases() -> int:
|
||||
recovered = 0
|
||||
with connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'queued', lease_until = NULL, lease_owner = NULL, updated_at = clock_timestamp()
|
||||
WHERE status = 'processing' AND lease_until IS NOT NULL AND lease_until < clock_timestamp()
|
||||
RETURNING job_id, attachment_id, pipeline_version, attempt, created_at
|
||||
"""
|
||||
).fetchall()
|
||||
for job in rows:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'queued', updated_at = clock_timestamp()
|
||||
WHERE id = %s AND pipeline_version = %s AND status = 'processing'
|
||||
""",
|
||||
(job["attachment_id"], job["pipeline_version"]),
|
||||
)
|
||||
add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"], job["created_at"])
|
||||
audit(conn, job["job_id"], job["attachment_id"], "lease_expired", {})
|
||||
recovered += 1
|
||||
if recovered:
|
||||
log.info("recovered %s expired lease(s)", recovered)
|
||||
return recovered
|
||||
|
||||
|
||||
def sweep_staging() -> None:
|
||||
settings, store, _publisher = runtime.require()
|
||||
with connection() as conn:
|
||||
ready = conn.execute(
|
||||
"""
|
||||
SELECT id, staging_key FROM attachments
|
||||
WHERE staging_deleted_at IS NULL AND status = 'ready'
|
||||
LIMIT 25
|
||||
"""
|
||||
).fetchall()
|
||||
failed = conn.execute(
|
||||
"""
|
||||
SELECT id, staging_key FROM attachments
|
||||
WHERE staging_deleted_at IS NULL AND status = 'failed'
|
||||
AND updated_at < clock_timestamp() - make_interval(secs => %s)
|
||||
LIMIT 25
|
||||
""",
|
||||
(settings.staging_retention_seconds,),
|
||||
).fetchall()
|
||||
for row in list(ready) + list(failed):
|
||||
try:
|
||||
store.delete(row["staging_key"])
|
||||
except Exception:
|
||||
log.warning("staging delete failed")
|
||||
continue
|
||||
with connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE attachments SET staging_deleted_at = clock_timestamp() WHERE id = %s",
|
||||
(row["id"],),
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Shared runtime objects created at process startup."""
|
||||
from __future__ import annotations
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.low_level import Type
|
||||
|
||||
from app.broker import Publisher
|
||||
from app.settings import Settings
|
||||
from app.s3store import ObjectStore
|
||||
|
||||
settings: Settings | None = None
|
||||
store: ObjectStore | None = None
|
||||
publisher: Publisher | None = None
|
||||
hasher = PasswordHasher(
|
||||
time_cost=2,
|
||||
memory_cost=19456,
|
||||
parallelism=1,
|
||||
hash_len=32,
|
||||
salt_len=16,
|
||||
type=Type.ID,
|
||||
)
|
||||
dummy_hash: str | None = None
|
||||
|
||||
|
||||
def init(app_settings: Settings, object_store: ObjectStore, message_publisher: Publisher) -> None:
|
||||
global settings, store, publisher, dummy_hash
|
||||
settings = app_settings
|
||||
store = object_store
|
||||
publisher = message_publisher
|
||||
if dummy_hash is None:
|
||||
dummy_hash = hasher.hash("dummy-password-for-equal-time")
|
||||
|
||||
|
||||
def require() -> tuple[Settings, ObjectStore, Publisher]:
|
||||
if settings is None or store is None or publisher is None:
|
||||
raise RuntimeError("runtime is not initialized")
|
||||
return settings, store, publisher
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Private S3-compatible store. Object keys are server-generated."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
log = logging.getLogger("messenger.s3")
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
def __init__(self, endpoint: str, region: str, bucket: str, access_key: str, secret_key: str):
|
||||
self.bucket = bucket
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
region_name=region,
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
config=Config(
|
||||
s3={"addressing_style": "path"},
|
||||
signature_version="s3v4",
|
||||
retries={"max_attempts": 3, "mode": "standard"},
|
||||
connect_timeout=3,
|
||||
read_timeout=20,
|
||||
),
|
||||
)
|
||||
|
||||
def ensure_bucket(self) -> None:
|
||||
try:
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
except ClientError:
|
||||
self.client.create_bucket(Bucket=self.bucket)
|
||||
log.info("bucket ready")
|
||||
|
||||
def healthy(self) -> bool:
|
||||
try:
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
return True
|
||||
except Exception:
|
||||
log.warning("object store ping failed", exc_info=True)
|
||||
return False
|
||||
|
||||
def put(self, key: str, data: bytes, content_type: str) -> None:
|
||||
self.client.put_object(Bucket=self.bucket, Key=key, Body=data, ContentType=content_type)
|
||||
|
||||
def get(self, key: str) -> bytes | None:
|
||||
try:
|
||||
response = self.client.get_object(Bucket=self.bucket, Key=key)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code in {"404", "NoSuchKey", "NotFound"}:
|
||||
return None
|
||||
raise
|
||||
return response["Body"].read()
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Process configuration. Secrets come from the environment or *_FILE, never from the image."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _raw(name: str, default: str | None = None) -> str:
|
||||
file_name = os.environ.get(name + "_FILE")
|
||||
if file_name:
|
||||
return Path(file_name).read_text(encoding="utf-8").strip()
|
||||
if name in os.environ and os.environ[name] != "":
|
||||
return os.environ[name]
|
||||
if default is not None:
|
||||
return default
|
||||
raise RuntimeError("missing configuration " + name)
|
||||
|
||||
|
||||
def _int(name: str, default: int) -> int:
|
||||
return int(_raw(name, str(default)))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
instance_id: str
|
||||
database_url: str
|
||||
session_ttl_seconds: int
|
||||
idempotency_ttl_seconds: int
|
||||
s3_endpoint: str
|
||||
s3_region: str
|
||||
s3_bucket: str
|
||||
s3_access_key_id: str
|
||||
s3_secret_access_key: str
|
||||
max_upload_bytes: int
|
||||
max_image_pixels: int
|
||||
broker_url: str
|
||||
worker_concurrency: int
|
||||
job_max_attempts: int
|
||||
job_timeout_seconds: int
|
||||
job_backoff_base_seconds: float
|
||||
job_backoff_cap_seconds: float
|
||||
staging_retention_seconds: int
|
||||
operator_token: str
|
||||
max_queued_jobs: int
|
||||
host: str
|
||||
port: int
|
||||
|
||||
|
||||
def load() -> Settings:
|
||||
return Settings(
|
||||
instance_id=_raw("INSTANCE_ID", "api-local"),
|
||||
database_url=_raw("DATABASE_URL"),
|
||||
session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600),
|
||||
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400),
|
||||
s3_endpoint=_raw("S3_ENDPOINT", "http://minio:9000"),
|
||||
s3_region=_raw("S3_REGION", "us-east-1"),
|
||||
s3_bucket=_raw("S3_BUCKET", "messenger-attachments"),
|
||||
s3_access_key_id=_raw("S3_ACCESS_KEY_ID"),
|
||||
s3_secret_access_key=_raw("S3_SECRET_ACCESS_KEY"),
|
||||
max_upload_bytes=_int("MAX_UPLOAD_BYTES", 10485760),
|
||||
max_image_pixels=_int("MAX_IMAGE_PIXELS", 40000000),
|
||||
broker_url=_raw("BROKER_URL"),
|
||||
worker_concurrency=max(1, _int("WORKER_CONCURRENCY", 2)),
|
||||
job_max_attempts=max(1, _int("JOB_MAX_ATTEMPTS", 5)),
|
||||
job_timeout_seconds=max(1, _int("JOB_TIMEOUT_SECONDS", 60)),
|
||||
job_backoff_base_seconds=float(_raw("JOB_BACKOFF_BASE_SECONDS", "0.5")),
|
||||
job_backoff_cap_seconds=float(_raw("JOB_BACKOFF_CAP_SECONDS", "30")),
|
||||
staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400),
|
||||
operator_token=_raw("OPERATOR_TOKEN", ""),
|
||||
max_queued_jobs=_int("MAX_QUEUED_JOBS", 500),
|
||||
host=_raw("APP_HOST", "0.0.0.0"),
|
||||
port=_int("APP_PORT", 8080),
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
"""UTC timestamps rendered as RFC 3339 with a Z suffix."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def iso(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
value = value.astimezone(timezone.utc)
|
||||
return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond:06d}Z"
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
"""Separate worker process. It never serves the public HTTP API."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from app import runtime
|
||||
from app.broker import QUEUE, open_consumer
|
||||
from app.db import migrate
|
||||
from app.outbox import start_relay
|
||||
from app.pipeline import process_delivery, recover_expired_leases, sweep_staging
|
||||
from app.runtime import init
|
||||
from app.s3store import ObjectStore
|
||||
from app.settings import load
|
||||
|
||||
log = logging.getLogger("messenger.worker")
|
||||
|
||||
|
||||
def _on_term(_signum, _frame) -> None:
|
||||
os._exit(0)
|
||||
|
||||
|
||||
def _consume(index: int, broker_url: str) -> None:
|
||||
worker_id = f"worker-{index}-{uuid.uuid4()}"
|
||||
while True:
|
||||
connection = None
|
||||
try:
|
||||
connection, channel = open_consumer(broker_url)
|
||||
|
||||
def on_message(channel, method, _properties, body, connection=connection, worker_id=worker_id):
|
||||
def work() -> None:
|
||||
try:
|
||||
result = process_delivery(body, bool(method.redelivered), worker_id)
|
||||
except Exception:
|
||||
log.exception("delivery failed")
|
||||
result = "nack"
|
||||
if result != "ack":
|
||||
time.sleep(1)
|
||||
|
||||
def finish() -> None:
|
||||
if result == "ack":
|
||||
channel.basic_ack(method.delivery_tag)
|
||||
else:
|
||||
channel.basic_nack(method.delivery_tag, requeue=True)
|
||||
|
||||
connection.add_callback_threadsafe(finish)
|
||||
|
||||
threading.Thread(target=work, name=f"delivery-{index}", daemon=True).start()
|
||||
|
||||
channel.basic_consume(queue=QUEUE, on_message_callback=on_message, auto_ack=False)
|
||||
log.info("consumer %s waiting; prefetch=1", worker_id)
|
||||
channel.start_consuming()
|
||||
except Exception:
|
||||
log.warning("consumer connection dropped", exc_info=True)
|
||||
time.sleep(1)
|
||||
finally:
|
||||
try:
|
||||
if connection is not None and connection.is_open:
|
||||
connection.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _maintain() -> None:
|
||||
while True:
|
||||
try:
|
||||
recover_expired_leases()
|
||||
sweep_staging()
|
||||
except Exception:
|
||||
log.warning("maintenance iteration failed", exc_info=True)
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
signal.signal(signal.SIGTERM, _on_term)
|
||||
signal.signal(signal.SIGINT, _on_term)
|
||||
settings = load()
|
||||
migrate(settings.database_url)
|
||||
store = ObjectStore(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_region,
|
||||
settings.s3_bucket,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
)
|
||||
store.ensure_bucket()
|
||||
from app.broker import Publisher
|
||||
|
||||
init(settings, store, Publisher(settings.broker_url))
|
||||
start_relay()
|
||||
threading.Thread(target=_maintain, name="maintenance", daemon=True).start()
|
||||
for index in range(settings.worker_concurrency):
|
||||
threading.Thread(target=_consume, args=(index, settings.broker_url), name=f"consumer-{index}", daemon=True).start()
|
||||
log.info("worker started with concurrency %s", settings.worker_concurrency)
|
||||
while True:
|
||||
time.sleep(3600)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user