forked from mtusi2026/mtusi2026lab5
Выполнение ЛР5 на 5 (трек 2)
This commit is contained in:
+113
@@ -0,0 +1,113 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app import config
|
||||
from app.cache import REVOKED, SessionCache
|
||||
from app.errors import BASIC_CHALLENGE, ApiError, unauthorized
|
||||
from app.storage import Store, fmt_ts, user_row
|
||||
|
||||
_hasher = PasswordHasher()
|
||||
_hash_slots = asyncio.Semaphore(config.PASSWORD_HASH_CONCURRENCY)
|
||||
_DUMMY_HASH = _hasher.hash("dummy-password-for-timing")
|
||||
|
||||
|
||||
async def hash_password(password: str) -> str:
|
||||
async with _hash_slots:
|
||||
return await run_in_threadpool(_hasher.hash, password)
|
||||
|
||||
|
||||
async def verify_password(password_hash: str, password: str) -> bool:
|
||||
def verify() -> bool:
|
||||
try:
|
||||
return _hasher.verify(password_hash, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
async with _hash_slots:
|
||||
return await run_in_threadpool(verify)
|
||||
|
||||
|
||||
def token_digest(token: str) -> bytes:
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
|
||||
def parse_basic(header: Optional[str]) -> Tuple[str, str]:
|
||||
bad = unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
if not header:
|
||||
raise bad
|
||||
scheme, _, value = header.partition(" ")
|
||||
if scheme.lower() != "basic" or not value.strip():
|
||||
raise bad
|
||||
try:
|
||||
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise bad from None
|
||||
username, sep, password = decoded.partition(":")
|
||||
if not sep or not username.isascii() or not 12 <= len(password) <= 128:
|
||||
raise bad
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(header: Optional[str]) -> str:
|
||||
if not header:
|
||||
raise unauthorized("bearer token required")
|
||||
scheme, _, token = header.partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token or not token.isascii() or len(token) > 256:
|
||||
raise unauthorized("bearer token required")
|
||||
return token
|
||||
|
||||
|
||||
async def login(store: Store, header: Optional[str]) -> dict:
|
||||
username, password = parse_basic(header)
|
||||
row = await store.get_credentials(username)
|
||||
if row is None:
|
||||
await verify_password(_DUMMY_HASH, password)
|
||||
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
if not await verify_password(row["password_hash"], password):
|
||||
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = await store.create_session(token_digest(token), row["id"], config.SESSION_TTL_SECONDS)
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": fmt_ts(expires_at), "user": user_row(row)}
|
||||
|
||||
|
||||
async def authenticate(store: Store, cache: SessionCache, header: Optional[str]) -> dict:
|
||||
digest = token_digest(parse_bearer(header))
|
||||
cached = await cache.get(digest)
|
||||
if cached == REVOKED:
|
||||
raise unauthorized("session expired or revoked")
|
||||
if isinstance(cached, dict):
|
||||
expires_at = datetime.fromisoformat(cached["expires_at"].replace("Z", "+00:00"))
|
||||
if expires_at > datetime.now(timezone.utc):
|
||||
return cached["user"]
|
||||
raise unauthorized("session expired or revoked")
|
||||
|
||||
row = await store.find_session(digest)
|
||||
if row is None:
|
||||
raise unauthorized("session expired or revoked")
|
||||
user = user_row(row)
|
||||
remaining = int((row["expires_at"] - datetime.now(timezone.utc)).total_seconds())
|
||||
await cache.put(digest, {"user": user, "expires_at": fmt_ts(row["expires_at"])}, remaining)
|
||||
return user
|
||||
|
||||
|
||||
async def logout(store: Store, cache: SessionCache, header: Optional[str]) -> None:
|
||||
await authenticate(store, cache, header)
|
||||
digest = token_digest(parse_bearer(header))
|
||||
expires_at = await store.revoke_session(digest)
|
||||
if expires_at is None:
|
||||
raise unauthorized("session expired or revoked")
|
||||
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1
|
||||
if not await cache.revoke(digest, remaining):
|
||||
raise ApiError(503, "unavailable", "logout not confirmed by session cache, retry later")
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
"""RabbitMQ topology, job message format (contracts/jobs.schema.json) and publishing with publisher confirms.
|
||||
|
||||
Topology (declared idempotently by every producer/consumer):
|
||||
exchange attachments (direct, durable) --attachment.process.v1--> queue attachments.process (quorum, durable)
|
||||
queue attachments.process: x-dead-letter-exchange=attachments.dlx, x-delivery-limit (poison message guard)
|
||||
exchange attachments.dlx (fanout, durable) --> queue attachments.dlq (quorum, durable)
|
||||
|
||||
Quorum queues replicate/fsync messages before the publisher confirm, persistent delivery mode is used anyway.
|
||||
The message carries only IDs and service fields, never image bytes, URLs or credentials.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import aio_pika
|
||||
from aio_pika import DeliveryMode, ExchangeType, Message
|
||||
|
||||
from app import config
|
||||
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
JOB_FIELDS = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at",
|
||||
"traceparent", "tracestate"}
|
||||
REQUIRED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
|
||||
_TRACEPARENT = re.compile(r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")
|
||||
|
||||
|
||||
class InvalidJob(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def job_payload(job_id: uuid.UUID, attachment_id: uuid.UUID, pipeline_version: int, attempt: int) -> dict:
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"job_id": str(job_id),
|
||||
"type": JOB_TYPE,
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": int(pipeline_version),
|
||||
"attempt": int(attempt),
|
||||
"created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
|
||||
}
|
||||
|
||||
|
||||
def _int(value, minimum: int) -> int:
|
||||
if not isinstance(value, int) or isinstance(value, bool) or value < minimum:
|
||||
raise InvalidJob("integer field out of range")
|
||||
return value
|
||||
|
||||
|
||||
def parse_job(body: bytes) -> dict:
|
||||
"""Strict validation against jobs.schema.json (additionalProperties=false)."""
|
||||
try:
|
||||
data = json.loads(body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise InvalidJob("not JSON") from None
|
||||
if not isinstance(data, dict):
|
||||
raise InvalidJob("not an object")
|
||||
keys = set(data)
|
||||
if not REQUIRED <= keys or keys - JOB_FIELDS:
|
||||
raise InvalidJob("unexpected or missing fields")
|
||||
if data["schema_version"] != 1 or isinstance(data["schema_version"], bool) or data["type"] != JOB_TYPE:
|
||||
raise InvalidJob("unsupported schema_version/type")
|
||||
try:
|
||||
job_id = uuid.UUID(data["job_id"])
|
||||
attachment_id = uuid.UUID(data["attachment_id"])
|
||||
created = datetime.fromisoformat(str(data["created_at"]).replace("Z", "+00:00"))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise InvalidJob("bad uuid/date-time") from None
|
||||
if created.tzinfo is None:
|
||||
raise InvalidJob("created_at without timezone")
|
||||
if "traceparent" in data and not (isinstance(data["traceparent"], str) and _TRACEPARENT.match(data["traceparent"])):
|
||||
raise InvalidJob("bad traceparent")
|
||||
if "tracestate" in data and not (isinstance(data["tracestate"], str) and len(data["tracestate"]) <= 512):
|
||||
raise InvalidJob("bad tracestate")
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"attachment_id": attachment_id,
|
||||
"pipeline_version": _int(data["pipeline_version"], 1),
|
||||
"attempt": _int(data["attempt"], 1),
|
||||
}
|
||||
|
||||
|
||||
class Broker:
|
||||
def __init__(self, url: Optional[str] = None):
|
||||
self.url = url or config.BROKER_URL
|
||||
self.connection: Optional[aio_pika.abc.AbstractRobustConnection] = None
|
||||
self.channel: Optional[aio_pika.abc.AbstractChannel] = None
|
||||
self.exchange = None
|
||||
self.queue = None
|
||||
|
||||
async def connect(self, prefetch: int = 0) -> None:
|
||||
if not self.url:
|
||||
raise RuntimeError("BROKER_URL or BROKER_URL_FILE is required")
|
||||
self.connection = await aio_pika.connect_robust(self.url, timeout=5, client_properties={"connection_name": "messenger"})
|
||||
# publisher_confirms=True: publish() returns only after the broker took responsibility for the message.
|
||||
self.channel = await self.connection.channel(publisher_confirms=True)
|
||||
if prefetch:
|
||||
await self.channel.set_qos(prefetch_count=prefetch)
|
||||
await self.declare()
|
||||
|
||||
async def declare(self) -> None:
|
||||
ch = self.channel
|
||||
dlx = await ch.declare_exchange(config.BROKER_DLX, ExchangeType.FANOUT, durable=True)
|
||||
dlq = await ch.declare_queue(config.BROKER_DLQ, durable=True, arguments={"x-queue-type": "quorum"})
|
||||
await dlq.bind(dlx)
|
||||
self.exchange = await ch.declare_exchange(config.BROKER_EXCHANGE, ExchangeType.DIRECT, durable=True)
|
||||
self.queue = await ch.declare_queue(config.BROKER_QUEUE, durable=True, arguments={
|
||||
"x-queue-type": "quorum",
|
||||
"x-dead-letter-exchange": config.BROKER_DLX,
|
||||
"x-delivery-limit": config.BROKER_DELIVERY_LIMIT,
|
||||
})
|
||||
await self.queue.bind(self.exchange, routing_key=config.BROKER_ROUTING_KEY)
|
||||
|
||||
async def publish(self, payload: dict) -> None:
|
||||
"""Returns after the publisher confirm (basic.ack); raises on nack/return/connection loss."""
|
||||
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
await self.exchange.publish(
|
||||
Message(
|
||||
body,
|
||||
content_type="application/json",
|
||||
delivery_mode=DeliveryMode.PERSISTENT,
|
||||
message_id=payload["job_id"] + ":" + str(payload["attempt"]),
|
||||
type=payload["type"],
|
||||
),
|
||||
routing_key=config.BROKER_ROUTING_KEY,
|
||||
mandatory=True,
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.connection is not None:
|
||||
await self.connection.close()
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Dict, Optional, Set, Union
|
||||
|
||||
import redis.asyncio as redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from app import config
|
||||
|
||||
logger = logging.getLogger("messenger.cache")
|
||||
|
||||
REVOKED = "revoked"
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url: Optional[str]):
|
||||
self._client: Optional[redis.Redis] = None
|
||||
self._down_until = 0.0
|
||||
self._pending_revokes: Dict[bytes, float] = {}
|
||||
self._retry_tasks: Set[asyncio.Task] = set()
|
||||
if url:
|
||||
pool = redis.BlockingConnectionPool.from_url(
|
||||
url,
|
||||
max_connections=config.CACHE_POOL_MAX,
|
||||
timeout=config.CACHE_TIMEOUT,
|
||||
socket_timeout=config.CACHE_TIMEOUT,
|
||||
socket_connect_timeout=config.CACHE_TIMEOUT,
|
||||
decode_responses=True,
|
||||
)
|
||||
self._client = redis.Redis(connection_pool=pool)
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self._client is not None
|
||||
|
||||
def _usable(self) -> bool:
|
||||
return self._client is not None and time.monotonic() >= self._down_until
|
||||
|
||||
def _failed(self, op: str, exc: Exception) -> None:
|
||||
self._down_until = time.monotonic() + config.CACHE_RETRY_AFTER
|
||||
logger.warning("cache %s failed (%s); bypassing cache for %.0fs", op, type(exc).__name__, config.CACHE_RETRY_AFTER)
|
||||
|
||||
@staticmethod
|
||||
def _key(token_hash: bytes) -> str:
|
||||
return "session:" + token_hash.hex()
|
||||
|
||||
def _revoke_pending(self, token_hash: bytes) -> bool:
|
||||
deadline = self._pending_revokes.get(token_hash)
|
||||
if deadline is None:
|
||||
return False
|
||||
if time.monotonic() >= deadline:
|
||||
self._pending_revokes.pop(token_hash, None)
|
||||
return False
|
||||
return True
|
||||
|
||||
async def get(self, token_hash: bytes) -> Union[dict, str, None]:
|
||||
if not self._usable() or self._revoke_pending(token_hash):
|
||||
return None
|
||||
try:
|
||||
raw = await self._client.get(self._key(token_hash))
|
||||
except (RedisError, OSError) as exc:
|
||||
self._failed("get", exc)
|
||||
return None
|
||||
if raw is None or raw == REVOKED:
|
||||
return raw
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
async def put(self, token_hash: bytes, entry: dict, ttl_seconds: int) -> None:
|
||||
ttl = min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)
|
||||
if ttl <= 0 or not self._usable():
|
||||
return
|
||||
try:
|
||||
await self._client.set(self._key(token_hash), json.dumps(entry), ex=ttl, nx=True)
|
||||
except (RedisError, OSError) as exc:
|
||||
self._failed("set", exc)
|
||||
|
||||
async def _write_tombstone(self, token_hash: bytes, ttl_seconds: int) -> bool:
|
||||
try:
|
||||
await self._client.set(self._key(token_hash), REVOKED, ex=max(1, min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)))
|
||||
return True
|
||||
except (RedisError, OSError) as exc:
|
||||
self._failed("revoke", exc)
|
||||
return False
|
||||
|
||||
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> bool:
|
||||
if self._client is None:
|
||||
return True
|
||||
if await self._write_tombstone(token_hash, ttl_seconds):
|
||||
return True
|
||||
deadline = time.monotonic() + config.SESSION_CACHE_MAX_SECONDS + 1
|
||||
self._pending_revokes[token_hash] = deadline
|
||||
task = asyncio.create_task(self._retry_revoke(token_hash, ttl_seconds, deadline))
|
||||
self._retry_tasks.add(task)
|
||||
task.add_done_callback(self._retry_tasks.discard)
|
||||
return False
|
||||
|
||||
async def _retry_revoke(self, token_hash: bytes, ttl_seconds: int, deadline: float) -> None:
|
||||
while time.monotonic() < deadline:
|
||||
await asyncio.sleep(1)
|
||||
remaining = int(deadline - time.monotonic())
|
||||
if remaining > 0 and await self._write_tombstone(token_hash, min(ttl_seconds, remaining)):
|
||||
logger.info("revocation tombstone written after cache recovery")
|
||||
break
|
||||
self._pending_revokes.pop(token_hash, None)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
if self._client is None:
|
||||
return False
|
||||
try:
|
||||
return bool(await self._client.ping())
|
||||
except (RedisError, OSError):
|
||||
return False
|
||||
|
||||
async def close(self) -> None:
|
||||
for task in list(self._retry_tasks):
|
||||
task.cancel()
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def _secret(name: str) -> Optional[str]:
|
||||
value = os.environ.get(name)
|
||||
if value:
|
||||
return value.strip()
|
||||
path = os.environ.get(name + "_FILE")
|
||||
if path and os.path.exists(path):
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
return fh.read().strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def _int(name: str, default: int) -> int:
|
||||
return int(os.environ.get(name, default))
|
||||
|
||||
|
||||
def _float(name: str, default: float) -> float:
|
||||
return float(os.environ.get(name, default))
|
||||
|
||||
|
||||
DATABASE_URL = _secret("DATABASE_URL")
|
||||
CACHE_URL = _secret("CACHE_URL")
|
||||
|
||||
S3_ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:8333")
|
||||
S3_REGION = os.environ.get("S3_REGION", "us-east-1")
|
||||
S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
S3_ACCESS_KEY_ID = _secret("S3_ACCESS_KEY_ID")
|
||||
S3_SECRET_ACCESS_KEY = _secret("S3_SECRET_ACCESS_KEY")
|
||||
S3_CONNECT_TIMEOUT = _float("S3_CONNECT_TIMEOUT", 2)
|
||||
S3_READ_TIMEOUT = _float("S3_READ_TIMEOUT", 5)
|
||||
S3_POOL_MAX = _int("S3_POOL_MAX", 20)
|
||||
# Without this cap 20 parallel 10 MiB PUTs drove SeaweedFS (512M limit) into an OOM kill.
|
||||
S3_PUT_CONCURRENCY = _int("S3_PUT_CONCURRENCY", 4)
|
||||
|
||||
SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600)
|
||||
SESSION_CACHE_MAX_SECONDS = _int("SESSION_CACHE_MAX_SECONDS", 300)
|
||||
|
||||
DB_POOL_MAX = _int("DB_POOL_MAX", 10)
|
||||
DB_CONNECT_TIMEOUT = _float("DB_CONNECT_TIMEOUT", 3)
|
||||
DB_ACQUIRE_TIMEOUT = _float("DB_ACQUIRE_TIMEOUT", 3)
|
||||
DB_COMMAND_TIMEOUT = _float("DB_COMMAND_TIMEOUT", 5)
|
||||
|
||||
CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.3)
|
||||
CACHE_POOL_MAX = _int("CACHE_POOL_MAX", 20)
|
||||
CACHE_RETRY_AFTER = _float("CACHE_RETRY_AFTER", 5)
|
||||
|
||||
PASSWORD_HASH_CONCURRENCY = _int("PASSWORD_HASH_CONCURRENCY", 4)
|
||||
|
||||
IDEMPOTENCY_TTL_SECONDS = _int("IDEMPOTENCY_TTL_SECONDS", 86400)
|
||||
|
||||
MAX_UPLOAD_BYTES = _int("MAX_UPLOAD_BYTES", 10 * 1024 * 1024)
|
||||
MAX_IMAGE_PIXELS = _int("MAX_IMAGE_PIXELS", 40_000_000)
|
||||
UPLOAD_SPOOL_BYTES = _int("UPLOAD_SPOOL_BYTES", 1024 * 1024)
|
||||
UPLOAD_TMP_DIR = os.environ.get("UPLOAD_TMP_DIR") or None
|
||||
UPLOAD_TIMEOUT_SECONDS = _float("UPLOAD_TIMEOUT_SECONDS", 60)
|
||||
UPLOAD_CONCURRENCY = _int("UPLOAD_CONCURRENCY", 16)
|
||||
DECODE_CONCURRENCY = _int("DECODE_CONCURRENCY", 1)
|
||||
|
||||
ORPHAN_GRACE_SECONDS = _int("ORPHAN_GRACE_SECONDS", 900)
|
||||
SWEEP_INTERVAL_SECONDS = _int("SWEEP_INTERVAL_SECONDS", 60)
|
||||
|
||||
INSTANCE_ID = "api-" + secrets.token_hex(4)
|
||||
INSTANCE_ID_FILE = os.environ.get("INSTANCE_ID_FILE", "/tmp/instance-id")
|
||||
|
||||
# --- lab5: broker, worker, retries ---------------------------------------------------------------
|
||||
BROKER_URL = _secret("BROKER_URL")
|
||||
BROKER_EXCHANGE = os.environ.get("BROKER_EXCHANGE", "attachments")
|
||||
BROKER_QUEUE = os.environ.get("BROKER_QUEUE", "attachments.process")
|
||||
BROKER_DLX = os.environ.get("BROKER_DLX", "attachments.dlx")
|
||||
BROKER_DLQ = os.environ.get("BROKER_DLQ", "attachments.dlq")
|
||||
BROKER_ROUTING_KEY = "attachment.process.v1"
|
||||
# Poison-message guard of the quorum queue: a message redelivered more often goes to the DLQ.
|
||||
BROKER_DELIVERY_LIMIT = _int("BROKER_DELIVERY_LIMIT", 10)
|
||||
|
||||
PIPELINE_VERSION = _int("PIPELINE_VERSION", 1)
|
||||
WORKER_CONCURRENCY = _int("WORKER_CONCURRENCY", 2) # = AMQP prefetch = parallel child processes
|
||||
JOB_MAX_ATTEMPTS = _int("JOB_MAX_ATTEMPTS", 5)
|
||||
JOB_TIMEOUT_SECONDS = _float("JOB_TIMEOUT_SECONDS", 60) # hard limit of one image transformation
|
||||
LEASE_SECONDS = _float("LEASE_SECONDS", 20) # processing lease, renewed by heartbeat
|
||||
HEARTBEAT_SECONDS = _float("HEARTBEAT_SECONDS", 5)
|
||||
REAPER_INTERVAL_SECONDS = _float("REAPER_INTERVAL_SECONDS", 2)
|
||||
STUCK_QUEUED_SECONDS = _float("STUCK_QUEUED_SECONDS", 300) # republish a queued job whose message vanished
|
||||
RETRY_BASE_SECONDS = _float("RETRY_BASE_SECONDS", 2)
|
||||
RETRY_MAX_SECONDS = _float("RETRY_MAX_SECONDS", 60)
|
||||
WORKER_MEMORY_LIMIT_MB = _int("WORKER_MEMORY_LIMIT_MB", 768) # RLIMIT_AS of one transformation process
|
||||
STAGING_RETENTION_SECONDS = _int("STAGING_RETENTION_SECONDS", 86400)
|
||||
RELAY_BATCH = _int("RELAY_BATCH", 100)
|
||||
RELAY_POLL_SECONDS = _float("RELAY_POLL_SECONDS", 1)
|
||||
FAULT_INJECTION = os.environ.get("FAULT_INJECTION", "0") == "1"
|
||||
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status_code: int, code: str, message: str, headers: Optional[Dict[str, str]] = None):
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def unauthorized(message: str, challenge: str = BEARER_CHALLENGE) -> ApiError:
|
||||
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def unavailable() -> ApiError:
|
||||
return ApiError(503, "unavailable", "service temporarily unavailable")
|
||||
|
||||
|
||||
def payload_too_large(message: str) -> ApiError:
|
||||
return ApiError(413, "payload_too_large", message)
|
||||
|
||||
|
||||
def unsupported_media_type(message: str) -> ApiError:
|
||||
return ApiError(415, "unsupported_media_type", message)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Fault injection points for automated failure tests (track 5). Inert unless FAULT_INJECTION=1.
|
||||
|
||||
A fault is armed by the operator CLI (python -m app.ops fault arm ...) as a row in fault_injections and is
|
||||
consumed atomically by exactly one hit. Actions:
|
||||
crash os._exit(137): the process dies like SIGKILL, nothing after this point runs (no ack, no COMMIT)
|
||||
delay:<s> sleep s seconds (widen a race window, e.g. let a newer pipeline version commit first)
|
||||
transient raise a temporary failure -> retry with backoff
|
||||
permanent raise a permanent failure -> failed without retries
|
||||
|
||||
Points: worker.after_claim, worker.before_transform, worker.after_s3_before_commit,
|
||||
worker.after_commit_before_ack, relay.after_confirm_before_mark
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from app import config
|
||||
|
||||
logger = logging.getLogger("faults")
|
||||
|
||||
POINTS = {
|
||||
"worker.after_claim",
|
||||
"worker.before_transform",
|
||||
"worker.after_s3_before_commit",
|
||||
"worker.after_commit_before_ack",
|
||||
"relay.after_confirm_before_mark",
|
||||
}
|
||||
|
||||
|
||||
async def hit(pool, point: str, attachment_id: Optional[uuid.UUID], actor: str) -> None:
|
||||
if not config.FAULT_INJECTION:
|
||||
return
|
||||
async with pool.acquire() as conn:
|
||||
action = await conn.fetchval(
|
||||
"""
|
||||
UPDATE fault_injections SET remaining = remaining - 1
|
||||
WHERE id = (SELECT id FROM fault_injections
|
||||
WHERE point = $1 AND (attachment_id IS NULL OR attachment_id = $2) AND remaining > 0
|
||||
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED)
|
||||
RETURNING action
|
||||
""",
|
||||
point, attachment_id,
|
||||
)
|
||||
if action is None:
|
||||
return
|
||||
await conn.execute(
|
||||
"INSERT INTO job_events (attachment_id, event, actor, detail) VALUES ($1, 'fault_injected', $2, $3)",
|
||||
attachment_id, actor, point + " -> " + action,
|
||||
)
|
||||
logger.warning("FAULT %s -> %s (attachment %s)", point, action, attachment_id)
|
||||
if action == "crash":
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
os._exit(137)
|
||||
if action.startswith("delay:"):
|
||||
await asyncio.sleep(float(action.split(":", 1)[1]))
|
||||
return
|
||||
from app.imaging import ImageRejected, TransientFailure
|
||||
if action == "transient":
|
||||
raise TransientFailure("injected_transient")
|
||||
if action == "permanent":
|
||||
raise ImageRejected("processing_failed")
|
||||
@@ -0,0 +1,79 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unicodedata
|
||||
import warnings
|
||||
from typing import BinaryIO, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app import config
|
||||
from app.errors import ApiError, payload_too_large, unsupported_media_type
|
||||
|
||||
# Pillow itself refuses > 2x this value; our own check below rejects anything above it before decoding.
|
||||
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
||||
Image.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_MAGIC = b"\xff\xd8\xff"
|
||||
FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||||
SNIFF_BYTES = 8
|
||||
|
||||
# Bidi overrides/isolates make "gpj.exe" look like "exe.jpg"; reject them together with control characters.
|
||||
_BIDI_CONTROLS = set("")
|
||||
|
||||
|
||||
def validate_filename(name: Optional[str]) -> str:
|
||||
bad = ApiError(400, "invalid_request", "filename must be 1-255 characters without path separators or control characters")
|
||||
if name is None or not 1 <= len(name) <= 255 or not name.strip() or name in (".", ".."):
|
||||
raise bad
|
||||
for ch in name:
|
||||
if ch in "/\\" or ch in _BIDI_CONTROLS or unicodedata.category(ch) in ("Cc", "Zl", "Zp"):
|
||||
raise bad
|
||||
return name
|
||||
|
||||
|
||||
def declared_type(header: Optional[str]) -> str:
|
||||
media = (header or "").split(";", 1)[0].strip().lower()
|
||||
if media not in FORMATS:
|
||||
raise unsupported_media_type("Content-Type must be image/png or image/jpeg")
|
||||
return media
|
||||
|
||||
|
||||
def sniff(head: bytes) -> Optional[str]:
|
||||
if head.startswith(PNG_MAGIC):
|
||||
return "image/png"
|
||||
if head.startswith(JPEG_MAGIC):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def _open(fp: BinaryIO, fmt: str) -> Image.Image:
|
||||
fp.seek(0)
|
||||
return Image.open(fp, formats=[fmt])
|
||||
|
||||
|
||||
def inspect(fp: BinaryIO, content_type: str) -> Tuple[int, int]:
|
||||
"""Cheap synchronous checks before 202: format by content, dimensions from the header, pixel limit
|
||||
before any decoding, PNG chunk CRCs (no IDAT inflation). Full decoding is the worker's job (lab5): a file
|
||||
that passes these checks but cannot be decoded ends as status=failed, error_code=invalid_image.
|
||||
"""
|
||||
fmt = FORMATS[content_type]
|
||||
corrupt = unsupported_media_type("file is not a valid " + fmt + " image")
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with _open(fp, fmt) as im:
|
||||
width, height = im.size
|
||||
if width < 1 or height < 1:
|
||||
raise corrupt
|
||||
if width * height > config.MAX_IMAGE_PIXELS:
|
||||
raise payload_too_large("image exceeds %d pixels" % config.MAX_IMAGE_PIXELS)
|
||||
if fmt == "PNG":
|
||||
im.verify() # chunk structure and CRCs; the object is unusable afterwards
|
||||
except ApiError:
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise payload_too_large("image exceeds %d pixels" % config.MAX_IMAGE_PIXELS) from None
|
||||
except (OSError, SyntaxError, ValueError, EOFError, MemoryError):
|
||||
raise corrupt from None
|
||||
return width, height
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
"""Versioned image pipeline, executed in an isolated child process with time and memory limits.
|
||||
|
||||
Pipeline v1 (the main course version):
|
||||
thumbnail JPEG q=85, fit into 256x256, no upscaling, floor rounding (min 1 px), EXIF orientation applied,
|
||||
alpha composited on white -> 320x200 gives 256x160
|
||||
crop JPEG q=85, centred square 128x128 (small images are upscaled), same orientation/alpha rules
|
||||
optimized WebP q=80 method=4, fit into 1280x1280 without upscaling, alpha kept
|
||||
Metadata: no EXIF/XMP/ICC/comments are written (Pillow writes them only when passed explicitly), the
|
||||
orientation is baked into the pixels instead. Encoding is deterministic for a given Pillow build, so a retry of
|
||||
the same (attachment, version) produces byte-identical objects at the same keys.
|
||||
|
||||
Pipeline v2 exists to demonstrate versioning (track 5): different quality settings, separate S3 keys.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import multiprocessing
|
||||
import os
|
||||
import resource
|
||||
import time
|
||||
import warnings
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from app import config
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
||||
Image.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
PIPELINES: Dict[int, Dict[str, dict]] = {
|
||||
1: {
|
||||
"thumbnail": {"box": 256, "format": "JPEG", "quality": 85},
|
||||
"crop": {"size": 128, "format": "JPEG", "quality": 85},
|
||||
"optimized": {"box": 1280, "format": "WEBP", "quality": 80, "method": 4},
|
||||
},
|
||||
2: {
|
||||
"thumbnail": {"box": 256, "format": "JPEG", "quality": 90},
|
||||
"crop": {"size": 128, "format": "JPEG", "quality": 90},
|
||||
"optimized": {"box": 1280, "format": "WEBP", "quality": 72, "method": 6},
|
||||
},
|
||||
}
|
||||
MIME = {"JPEG": "image/jpeg", "WEBP": "image/webp", "PNG": "image/png"}
|
||||
FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||||
|
||||
|
||||
class ImageRejected(Exception):
|
||||
"""Permanent: retrying the same bytes cannot succeed."""
|
||||
|
||||
def __init__(self, code: str):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
|
||||
|
||||
class TransientFailure(Exception):
|
||||
def __init__(self, code: str):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
|
||||
|
||||
def fit_size(width: int, height: int, box: int) -> Tuple[int, int]:
|
||||
"""Fit into box x box keeping proportions, never upscale, round down, at least 1 px."""
|
||||
if width <= box and height <= box:
|
||||
return width, height
|
||||
if width >= height:
|
||||
return box, max(1, height * box // width)
|
||||
return max(1, width * box // height), box
|
||||
|
||||
|
||||
def _flatten(im: Image.Image) -> Image.Image:
|
||||
"""RGB for JPEG: alpha (RGBA/LA/P+transparency) composited on white."""
|
||||
if im.mode in ("I", "I;16", "I;16B", "I;16L", "F"):
|
||||
im = im.convert("I").point(lambda v: v * (1 / 256)).convert("L")
|
||||
if im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info):
|
||||
rgba = im.convert("RGBA")
|
||||
out = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||
out.paste(rgba, mask=rgba.getchannel("A"))
|
||||
return out
|
||||
return im.convert("RGB")
|
||||
|
||||
|
||||
def _with_alpha(im: Image.Image) -> Image.Image:
|
||||
if im.mode in ("I", "I;16", "I;16B", "I;16L", "F"):
|
||||
im = im.convert("I").point(lambda v: v * (1 / 256)).convert("L")
|
||||
if im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info):
|
||||
return im.convert("RGBA")
|
||||
return im.convert("RGB")
|
||||
|
||||
|
||||
def _encode(im: Image.Image, spec: dict) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
if spec["format"] == "JPEG":
|
||||
im.save(buf, "JPEG", quality=spec["quality"], optimize=True, progressive=False, subsampling="4:2:0")
|
||||
else:
|
||||
im.save(buf, "WEBP", quality=spec["quality"], method=spec["method"], exact=False)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def transform(src_path: str, content_type: str, out_dir: str, version: int) -> List[dict]:
|
||||
"""Decode once, produce every variant of `version`. Runs inside the limited child process."""
|
||||
if version not in PIPELINES:
|
||||
raise ImageRejected("unsupported_pipeline")
|
||||
spec = PIPELINES[version]
|
||||
fmt = FORMATS.get(content_type)
|
||||
if fmt is None:
|
||||
raise ImageRejected("invalid_image")
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(src_path, formats=[fmt]) as im:
|
||||
width, height = im.size
|
||||
if width < 1 or height < 1:
|
||||
raise ImageRejected("invalid_image")
|
||||
if width * height > config.MAX_IMAGE_PIXELS:
|
||||
raise ImageRejected("image_too_large")
|
||||
orientation = im.getexif().get(0x0112, 1)
|
||||
if orientation in (5, 6, 7, 8):
|
||||
width, height = height, width
|
||||
largest = spec["optimized"]["box"]
|
||||
if fmt == "JPEG":
|
||||
# DCT-domain downscale while decoding: memory ~ pixels/4..1/64 for big photos.
|
||||
im.draft("RGB", (min(width, largest), min(height, largest)))
|
||||
im.load()
|
||||
im = ImageOps.exif_transpose(im)
|
||||
except ImageRejected:
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise ImageRejected("image_too_large") from None
|
||||
except MemoryError:
|
||||
raise ImageRejected("image_too_large") from None
|
||||
except (OSError, SyntaxError, ValueError, EOFError, TypeError, IndexError):
|
||||
raise ImageRejected("invalid_image") from None
|
||||
|
||||
flat = _flatten(im)
|
||||
outputs = []
|
||||
|
||||
t = spec["thumbnail"]
|
||||
tw, th = fit_size(width, height, t["box"])
|
||||
outputs.append(("thumbnail", flat.resize((tw, th), Image.LANCZOS, reducing_gap=3.0), t))
|
||||
|
||||
c = spec["crop"]
|
||||
outputs.append(("crop", ImageOps.fit(flat, (c["size"], c["size"]), Image.LANCZOS, centering=(0.5, 0.5)), c))
|
||||
|
||||
o = spec["optimized"]
|
||||
ow, oh = fit_size(width, height, o["box"])
|
||||
rich = _with_alpha(im)
|
||||
outputs.append(("optimized", rich if rich.size == (ow, oh) else rich.resize((ow, oh), Image.LANCZOS, reducing_gap=3.0), o))
|
||||
|
||||
result = []
|
||||
for name, img, s in outputs:
|
||||
data = _encode(img, s)
|
||||
path = os.path.join(out_dir, name)
|
||||
with open(path, "wb") as fh:
|
||||
fh.write(data)
|
||||
result.append({
|
||||
"name": name,
|
||||
"content_type": MIME[s["format"]],
|
||||
"path": path,
|
||||
"size_bytes": len(data),
|
||||
"width": img.size[0],
|
||||
"height": img.size[1],
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _child(conn, src_path: str, content_type: str, out_dir: str, version: int, memory_mb: int) -> None:
|
||||
limit = memory_mb * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
try:
|
||||
conn.send(("ok", transform(src_path, content_type, out_dir, version)))
|
||||
except ImageRejected as exc:
|
||||
conn.send(("rejected", exc.code))
|
||||
except MemoryError:
|
||||
conn.send(("rejected", "image_too_large"))
|
||||
except Exception as exc: # unexpected: transient, bounded by max attempts
|
||||
conn.send(("transient", "processing_failed:" + type(exc).__name__))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
_ctx = None
|
||||
|
||||
|
||||
def _context():
|
||||
global _ctx
|
||||
if _ctx is None:
|
||||
# forkserver: children are forked from a clean single-threaded server (not from the asyncio/boto3 parent).
|
||||
_ctx = multiprocessing.get_context("forkserver")
|
||||
_ctx.set_forkserver_preload(["app.imaging"])
|
||||
return _ctx
|
||||
|
||||
|
||||
def run_isolated(src_path: str, content_type: str, out_dir: str, version: int,
|
||||
timeout: float, memory_mb: int) -> List[dict]:
|
||||
"""Blocking; call from a thread. Kills the child on timeout (hung decoder) and reports how it ended."""
|
||||
ctx = _context()
|
||||
parent, child = ctx.Pipe(duplex=False)
|
||||
proc = ctx.Process(target=_child, args=(child, src_path, content_type, out_dir, version, memory_mb), daemon=True)
|
||||
proc.start()
|
||||
child.close()
|
||||
try:
|
||||
deadline = time.monotonic() + timeout
|
||||
if not parent.poll(max(0.0, deadline - time.monotonic())):
|
||||
proc.kill()
|
||||
proc.join(5)
|
||||
raise TransientFailure("processing_timeout")
|
||||
try:
|
||||
kind, value = parent.recv()
|
||||
except EOFError:
|
||||
proc.join(5)
|
||||
# killed by the kernel/cgroup (e.g. OOM) or crashed in native code
|
||||
raise TransientFailure("worker_process_died:%s" % proc.exitcode) from None
|
||||
proc.join(5)
|
||||
finally:
|
||||
parent.close()
|
||||
if proc.is_alive():
|
||||
proc.kill()
|
||||
if kind == "ok":
|
||||
return value
|
||||
if kind == "rejected":
|
||||
raise ImageRejected(value)
|
||||
raise TransientFailure(value)
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
"""Job state machine in PostgreSQL (source of truth). The broker only wakes workers up.
|
||||
|
||||
Every state change that needs a message writes an outbox row in the SAME transaction (transactional outbox),
|
||||
so there is no window where a job is queued in the DB without a pending publication.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import random
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app import config
|
||||
from app.broker import job_payload
|
||||
|
||||
|
||||
def backoff_seconds(attempt: int) -> float:
|
||||
"""Exponential backoff with 'equal jitter': half fixed, half random. attempt = failed attempt number (1..)."""
|
||||
ceiling = min(config.RETRY_MAX_SECONDS, config.RETRY_BASE_SECONDS * (2 ** max(0, attempt - 1)))
|
||||
return ceiling / 2 + random.uniform(0, ceiling / 2)
|
||||
|
||||
|
||||
async def event(conn: asyncpg.Connection, job_id: Optional[uuid.UUID], attachment_id: Optional[uuid.UUID],
|
||||
name: str, actor: str, attempt: Optional[int] = None, detail: Optional[str] = None) -> None:
|
||||
await conn.execute(
|
||||
"INSERT INTO job_events (job_id, attachment_id, event, attempt, actor, detail) VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
job_id, attachment_id, name, attempt, actor, detail,
|
||||
)
|
||||
|
||||
|
||||
async def enqueue(conn: asyncpg.Connection, job_id: uuid.UUID, attachment_id: uuid.UUID, pipeline_version: int,
|
||||
attempt: int, delay: float = 0.0) -> None:
|
||||
"""Outbox row for the given attempt; must run inside the transaction that made the job 'queued'."""
|
||||
payload = job_payload(job_id, attachment_id, pipeline_version, attempt)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO outbox (job_id, payload, available_at)
|
||||
VALUES ($1, $2::jsonb, clock_timestamp() + make_interval(secs => $3))
|
||||
""",
|
||||
job_id, json.dumps(payload), float(delay),
|
||||
)
|
||||
if delay <= 0:
|
||||
await conn.execute("SELECT pg_notify('outbox', '')")
|
||||
|
||||
|
||||
async def create_job(conn: asyncpg.Connection, attachment_id: uuid.UUID, pipeline_version: int, actor: str) -> uuid.UUID:
|
||||
job_id = uuid.uuid4()
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO jobs (job_id, attachment_id, pipeline_version, max_attempts)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
""",
|
||||
job_id, attachment_id, pipeline_version, config.JOB_MAX_ATTEMPTS,
|
||||
)
|
||||
await enqueue(conn, job_id, attachment_id, pipeline_version, 1)
|
||||
await event(conn, job_id, attachment_id, "accepted", actor, 0, "pipeline_version=%d" % pipeline_version)
|
||||
return job_id
|
||||
|
||||
|
||||
async def fail(conn: asyncpg.Connection, job: asyncpg.Record, code: str, last_error: str, actor: str) -> None:
|
||||
"""processing -> failed. The attachment fails only if no version has been published yet."""
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'failed', lease_owner = NULL, lease_until = NULL, error_code = $2,
|
||||
last_error = $3, updated_at = clock_timestamp()
|
||||
WHERE job_id = $1
|
||||
""",
|
||||
job["job_id"], code, last_error[:200],
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE attachments SET status = 'failed', error_code = $2, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND status IN ('queued', 'processing')
|
||||
""",
|
||||
job["attachment_id"], code,
|
||||
)
|
||||
await event(conn, job["job_id"], job["attachment_id"], "failed", actor, job["attempt"], code + " (" + last_error[:120] + ")")
|
||||
|
||||
|
||||
async def retry_or_fail(conn: asyncpg.Connection, job: asyncpg.Record, reason: str, actor: str) -> str:
|
||||
"""processing -> queued (with backoff) while attempts remain, otherwise -> failed retry_exhausted."""
|
||||
if job["attempt"] >= job["max_attempts"]:
|
||||
await fail(conn, job, "retry_exhausted", reason, actor)
|
||||
return "failed"
|
||||
delay = backoff_seconds(job["attempt"])
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'queued', lease_owner = NULL, lease_until = NULL, last_error = $2,
|
||||
next_attempt_at = clock_timestamp() + make_interval(secs => $3), updated_at = clock_timestamp()
|
||||
WHERE job_id = $1
|
||||
""",
|
||||
job["job_id"], reason[:200], delay,
|
||||
)
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = $1 AND status = 'processing'",
|
||||
job["attachment_id"],
|
||||
)
|
||||
await enqueue(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1, delay)
|
||||
await event(conn, job["job_id"], job["attachment_id"], "retry_scheduled", actor, job["attempt"],
|
||||
"%s; next attempt %d in %.2fs" % (reason[:120], job["attempt"] + 1, delay))
|
||||
return "queued"
|
||||
+378
@@ -0,0 +1,378 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import tempfile
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional
|
||||
|
||||
import asyncpg
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from app import auth, config, images
|
||||
from app.cache import SessionCache
|
||||
from app.errors import ApiError, payload_too_large, unsupported_media_type
|
||||
from app.models import (Attachment, Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Health, Message, MessagePage,
|
||||
Session, User)
|
||||
from app.objects import ObjectStore, S3Unavailable, original_key, staging_key, storage_unavailable
|
||||
from app.storage import Store, attachment_row
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
store = Store()
|
||||
cache = SessionCache(config.CACHE_URL)
|
||||
objects = ObjectStore()
|
||||
upload_slots = asyncio.Semaphore(config.UPLOAD_CONCURRENCY)
|
||||
inspect_slots = asyncio.Semaphore(config.DECODE_CONCURRENCY)
|
||||
s3_put_slots = asyncio.Semaphore(config.S3_PUT_CONCURRENCY)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
if not config.DATABASE_URL:
|
||||
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
|
||||
if not (config.S3_ACCESS_KEY_ID and config.S3_SECRET_ACCESS_KEY):
|
||||
raise RuntimeError("S3_ACCESS_KEY_ID(_FILE) and S3_SECRET_ACCESS_KEY(_FILE) are required")
|
||||
await store.open()
|
||||
logger.info("session cache: %s", "valkey" if cache.enabled else "disabled")
|
||||
logger.info("object storage: %s bucket=%s", config.S3_ENDPOINT, config.S3_BUCKET)
|
||||
try:
|
||||
with open(config.INSTANCE_ID_FILE, "w", encoding="ascii") as fh:
|
||||
fh.write(config.INSTANCE_ID + "\n")
|
||||
except OSError:
|
||||
logger.warning("cannot write %s", config.INSTANCE_ID_FILE)
|
||||
logger.info("instance id: %s", config.INSTANCE_ID)
|
||||
yield
|
||||
await cache.close()
|
||||
await store.close()
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — lab5", lifespan=lifespan)
|
||||
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
DB_UNAVAILABLE = (
|
||||
OSError,
|
||||
asyncpg.PostgresConnectionError,
|
||||
asyncpg.InterfaceError,
|
||||
asyncpg.TooManyConnectionsError,
|
||||
asyncpg.exceptions.OperatorInterventionError,
|
||||
asyncpg.exceptions.QueryCanceledError,
|
||||
)
|
||||
|
||||
|
||||
def error_body(code: str, message: str, request_id: str) -> dict:
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
|
||||
|
||||
def error_response(request: Request, status: int, code: str, message: str, headers: Optional[dict] = None) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", "")
|
||||
return JSONResponse(status_code=status, content=error_body(code, message, request_id), headers=headers)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request_id = uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
logger.exception("unhandled error for request_id=%s", request_id)
|
||||
response = JSONResponse(status_code=500, content=error_body("internal_error", "internal error", request_id))
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = config.INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError):
|
||||
return error_response(request, exc.status_code, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "request failed validation")
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
code = {404: "not_found", 405: "invalid_request", 413: "payload_too_large", 415: "unsupported_media_type"}.get(
|
||||
exc.status_code, "invalid_request")
|
||||
message = exc.detail if isinstance(exc.detail, str) else "request failed"
|
||||
return error_response(request, exc.status_code, code, message)
|
||||
|
||||
|
||||
async def db_unavailable_handler(request: Request, exc: Exception):
|
||||
logger.warning("database unavailable for request_id=%s: %s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, 503, "unavailable", "service temporarily unavailable")
|
||||
|
||||
|
||||
for _exc in DB_UNAVAILABLE:
|
||||
app.add_exception_handler(_exc, db_unavailable_handler)
|
||||
|
||||
|
||||
@app.exception_handler(S3Unavailable)
|
||||
async def s3_unavailable_handler(request: Request, exc: S3Unavailable):
|
||||
err = storage_unavailable()
|
||||
return error_response(request, err.status_code, err.code, err.message)
|
||||
|
||||
|
||||
async def current_user(request: Request) -> dict:
|
||||
return await auth.authenticate(store, cache, request.headers.get("Authorization"))
|
||||
|
||||
|
||||
def parse_uuid(value: str, field: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(value)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", f"{field} is not a valid UUID") from None
|
||||
|
||||
|
||||
def not_found() -> ApiError:
|
||||
return ApiError(404, "not_found", "chat not found")
|
||||
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
async def liveness():
|
||||
return Health()
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Health)
|
||||
async def readiness():
|
||||
try:
|
||||
await store.ping()
|
||||
except DB_UNAVAILABLE:
|
||||
raise ApiError(503, "unavailable", "database is not available") from None
|
||||
return Health()
|
||||
|
||||
|
||||
@app.post("/api/v1/users", response_model=User, status_code=201)
|
||||
async def register_user(body: CreateUser):
|
||||
if not body.display_name.strip() or not body.password.strip():
|
||||
raise ApiError(400, "invalid_request", "display_name and password must not be blank")
|
||||
password_hash = await auth.hash_password(body.password)
|
||||
return await store.create_user(body.username, body.display_name, password_hash)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
async def current_user_endpoint(user: dict = Depends(current_user)):
|
||||
return user
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", response_model=Session, status_code=201)
|
||||
async def create_session(request: Request):
|
||||
return await auth.login(store, request.headers.get("Authorization"))
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def delete_session(request: Request):
|
||||
await auth.logout(store, cache, request.headers.get("Authorization"))
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
|
||||
if not body.title.strip():
|
||||
raise ApiError(400, "invalid_request", "title must not be blank")
|
||||
if len(set(body.member_ids)) != len(body.member_ids):
|
||||
raise ApiError(400, "invalid_request", "member_ids must not contain duplicates")
|
||||
if uuid.UUID(user["id"]) not in body.member_ids:
|
||||
raise ApiError(400, "invalid_request", "caller must be a member of the chat")
|
||||
return await store.create_chat(body.title, list(body.member_ids))
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
async def list_chats(
|
||||
user: dict = Depends(current_user),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
):
|
||||
return await store.list_chats(uuid.UUID(user["id"]), limit, cursor)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
async def get_chat(chat_id: str, user: dict = Depends(current_user)):
|
||||
chat = await store.get_chat_for_member(parse_uuid(chat_id, "chat_id"), uuid.UUID(user["id"]))
|
||||
if chat is None:
|
||||
raise not_found()
|
||||
return chat
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessage,
|
||||
user: dict = Depends(current_user),
|
||||
idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key"),
|
||||
):
|
||||
chat_uuid = parse_uuid(chat_id, "chat_id")
|
||||
if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
|
||||
raise ApiError(400, "invalid_request", "Idempotency-Key header is required: [A-Za-z0-9._:-]{1,128}")
|
||||
if len(set(body.attachment_ids)) != len(body.attachment_ids):
|
||||
raise ApiError(400, "invalid_request", "attachment_ids must be unique")
|
||||
if not body.text.strip() and not body.attachment_ids:
|
||||
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
|
||||
raise not_found()
|
||||
raise ApiError(400, "invalid_request", "text must not be blank without attachments")
|
||||
canonical = json.dumps(body.model_dump(mode="json"), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
||||
request_hash = hashlib.sha256(canonical.encode("utf-8")).digest()
|
||||
message = await store.create_message(
|
||||
chat_uuid, uuid.UUID(user["id"]), body.text, list(body.attachment_ids), idempotency_key, request_hash)
|
||||
if message is None:
|
||||
raise not_found()
|
||||
return message
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
user: dict = Depends(current_user),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
):
|
||||
chat_uuid = parse_uuid(chat_id, "chat_id")
|
||||
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
|
||||
raise not_found()
|
||||
return await store.list_messages(chat_uuid, limit, cursor)
|
||||
|
||||
|
||||
VARIANTS = {"original", "thumbnail", "crop", "optimized"}
|
||||
|
||||
|
||||
async def receive_body(request: Request, spool) -> tuple:
|
||||
"""Stream the body into a spooled temp file: RAM holds at most UPLOAD_SPOOL_BYTES per upload."""
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
head = b""
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > config.MAX_UPLOAD_BYTES:
|
||||
raise payload_too_large("file exceeds %d bytes" % config.MAX_UPLOAD_BYTES)
|
||||
if len(head) < images.SNIFF_BYTES:
|
||||
head += chunk[:images.SNIFF_BYTES - len(head)]
|
||||
digest.update(chunk)
|
||||
spool.write(chunk)
|
||||
return size, digest.hexdigest(), head
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=202)
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
user: dict = Depends(current_user),
|
||||
filename: Optional[str] = Query(default=None),
|
||||
):
|
||||
chat_uuid = parse_uuid(chat_id, "chat_id")
|
||||
owner_id = uuid.UUID(user["id"])
|
||||
if not await store.is_member(chat_uuid, owner_id):
|
||||
raise not_found()
|
||||
filename = images.validate_filename(filename)
|
||||
declared = images.declared_type(request.headers.get("Content-Type"))
|
||||
length = request.headers.get("Content-Length")
|
||||
if length is not None:
|
||||
if not length.isdigit():
|
||||
raise ApiError(400, "invalid_request", "invalid Content-Length")
|
||||
if int(length) > config.MAX_UPLOAD_BYTES:
|
||||
raise payload_too_large("file exceeds %d bytes" % config.MAX_UPLOAD_BYTES)
|
||||
|
||||
async with upload_slots:
|
||||
spool = tempfile.SpooledTemporaryFile(max_size=config.UPLOAD_SPOOL_BYTES, dir=config.UPLOAD_TMP_DIR)
|
||||
try:
|
||||
try:
|
||||
size, sha256, head = await asyncio.wait_for(receive_body(request, spool), config.UPLOAD_TIMEOUT_SECONDS)
|
||||
except asyncio.TimeoutError:
|
||||
raise ApiError(400, "invalid_request", "upload was not completed in time") from None
|
||||
except ClientDisconnect:
|
||||
logger.info("upload aborted by client after partial body; nothing stored")
|
||||
raise ApiError(400, "invalid_request", "upload interrupted") from None
|
||||
if size == 0:
|
||||
raise unsupported_media_type("empty body is not an image")
|
||||
detected = images.sniff(head)
|
||||
if detected is None:
|
||||
raise unsupported_media_type("content is neither PNG nor JPEG")
|
||||
if detected != declared:
|
||||
raise unsupported_media_type("content does not match Content-Type " + declared)
|
||||
async with inspect_slots:
|
||||
width, height = await run_in_threadpool(images.inspect, spool, detected)
|
||||
|
||||
attachment_id = uuid.uuid4()
|
||||
stage = staging_key(attachment_id)
|
||||
# 1) full verified original -> durable staging (S3 checks SHA-256 of the received bytes)
|
||||
async with s3_put_slots:
|
||||
await objects.put(stage, spool, size, detected, sha256)
|
||||
# 2) ONE transaction: attachment(queued) + job + outbox. Only after COMMIT do we answer 202.
|
||||
# A crash between 1) and 2) leaves an unreferenced staging object -> sweeper after the grace period.
|
||||
try:
|
||||
accepted = await store.create_queued_attachment(
|
||||
attachment_id, chat_uuid, owner_id, filename, detected, size, sha256, width, height,
|
||||
stage, original_key(attachment_id), config.INSTANCE_ID,
|
||||
)
|
||||
except DB_UNAVAILABLE:
|
||||
await objects.delete_quietly(stage)
|
||||
raise
|
||||
if accepted is None:
|
||||
await objects.delete_quietly(stage)
|
||||
raise not_found()
|
||||
return JSONResponse(status_code=202, content=accepted)
|
||||
finally:
|
||||
spool.close()
|
||||
|
||||
|
||||
async def readable_attachment(attachment_id: str, user: dict):
|
||||
row, variants = await store.get_attachment_for_member(parse_uuid(attachment_id, "attachment_id"), uuid.UUID(user["id"]))
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "attachment not found")
|
||||
return row, variants
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}", response_model=Attachment)
|
||||
async def get_attachment(attachment_id: str, user: dict = Depends(current_user)):
|
||||
row, variants = await readable_attachment(attachment_id, user)
|
||||
return attachment_row(row, variants)
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def download_attachment(
|
||||
attachment_id: str,
|
||||
user: dict = Depends(current_user),
|
||||
variant: str = Query(default="original"),
|
||||
):
|
||||
if variant not in VARIANTS:
|
||||
raise ApiError(400, "invalid_request", "unknown variant")
|
||||
row, variants = await readable_attachment(attachment_id, user)
|
||||
if row["status"] != "ready":
|
||||
raise ApiError(409, "conflict", "attachment is %s, content is not available yet" % row["status"])
|
||||
if variant == "original":
|
||||
key, ctype, expected = row["object_key"], row["content_type"], row["size_bytes"]
|
||||
else:
|
||||
found = [v for v in variants if v["name"] == variant]
|
||||
if not found:
|
||||
raise ApiError(404, "not_found", "variant not found")
|
||||
key, ctype, expected = found[0]["object_key"], found[0]["content_type"], found[0]["size_bytes"]
|
||||
chunks, length, close = await objects.open(key)
|
||||
if length != expected:
|
||||
close()
|
||||
logger.error("object size differs from metadata for attachment %s variant %s", row["id"], variant)
|
||||
raise storage_unavailable()
|
||||
return StreamingResponse(
|
||||
chunks,
|
||||
media_type=ctype,
|
||||
headers={
|
||||
"Content-Length": str(length),
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
background=BackgroundTask(close),
|
||||
)
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app import config
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("migrate")
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
|
||||
LOCK_ID = 2026_0002
|
||||
|
||||
|
||||
async def connect_with_retry(attempts: int = 30) -> asyncpg.Connection:
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
return await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT)
|
||||
except (OSError, asyncpg.PostgresError, asyncpg.InterfaceError) as exc:
|
||||
logger.warning("database not reachable (attempt %d/%d): %s", attempt, attempts, type(exc).__name__)
|
||||
await asyncio.sleep(1)
|
||||
raise SystemExit("database is not reachable")
|
||||
|
||||
|
||||
async def migrate() -> int:
|
||||
if not config.DATABASE_URL:
|
||||
raise SystemExit("DATABASE_URL or DATABASE_URL_FILE is required")
|
||||
conn = await connect_with_retry()
|
||||
applied_now = 0
|
||||
try:
|
||||
await conn.execute("SELECT pg_advisory_lock($1)", LOCK_ID)
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
done = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")}
|
||||
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
||||
version = path.stem
|
||||
if version in done:
|
||||
continue
|
||||
logger.info("applying %s", version)
|
||||
async with conn.transaction():
|
||||
await conn.execute(path.read_text(encoding="utf-8"))
|
||||
await conn.execute("INSERT INTO schema_migrations (version) VALUES ($1)", version)
|
||||
applied_now += 1
|
||||
logger.info("migrations up to date: %d applied now, %d before", applied_now, len(done))
|
||||
finally:
|
||||
await conn.execute("SELECT pg_advisory_unlock($1)", LOCK_ID)
|
||||
await conn.close()
|
||||
return applied_now
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(migrate())
|
||||
sys.exit(0)
|
||||
@@ -0,0 +1,98 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
USERNAME_PATTERN = r"^[a-z0-9_]{3,32}$"
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
username: str = Field(pattern=USERNAME_PATTERN)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: List[uuid.UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
id: uuid.UUID
|
||||
title: str
|
||||
member_ids: List[uuid.UUID]
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: List[uuid.UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: List[uuid.UUID]
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
|
||||
class Variant(BaseModel):
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
class Attachment(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
owner_id: uuid.UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: List[Variant]
|
||||
error_code: Optional[str]
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
status: str = "ok"
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import BinaryIO, Callable, Iterator, List, Optional, Tuple
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app import config
|
||||
from app.errors import ApiError
|
||||
|
||||
logger = logging.getLogger("messenger.s3")
|
||||
|
||||
# Private prefixes of the single private bucket:
|
||||
# staging/<attachment> full original accepted by the API before 202 (durable handoff)
|
||||
# attachments/<attachment>/original published original (same bytes, written by the worker)
|
||||
# attachments/<attachment>/v<N>/<variant>.* variants of pipeline version N; key = effect key, so a retry
|
||||
# overwrites the same object instead of creating a second set
|
||||
STAGING_PREFIX = "staging/"
|
||||
FINAL_PREFIX = "attachments/"
|
||||
DOWNLOAD_CHUNK = 64 * 1024
|
||||
VARIANT_EXT = {"image/jpeg": "jpg", "image/webp": "webp", "image/png": "png"}
|
||||
|
||||
|
||||
class S3Unavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class S3NotFound(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def staging_key(attachment_id: uuid.UUID) -> str:
|
||||
return STAGING_PREFIX + attachment_id.hex
|
||||
|
||||
|
||||
def original_key(attachment_id: uuid.UUID) -> str:
|
||||
return "%s%s/original" % (FINAL_PREFIX, attachment_id.hex)
|
||||
|
||||
|
||||
def variant_key(attachment_id: uuid.UUID, pipeline_version: int, name: str, content_type: str) -> str:
|
||||
return "%s%s/v%d/%s.%s" % (FINAL_PREFIX, attachment_id.hex, pipeline_version, name, VARIANT_EXT[content_type])
|
||||
|
||||
|
||||
def _client(access_key: Optional[str], secret_key: Optional[str]):
|
||||
cfg = Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=config.S3_CONNECT_TIMEOUT,
|
||||
read_timeout=config.S3_READ_TIMEOUT,
|
||||
retries={"max_attempts": 1, "mode": "standard"},
|
||||
max_pool_connections=config.S3_POOL_MAX,
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
)
|
||||
return boto3.session.Session().client(
|
||||
"s3",
|
||||
endpoint_url=config.S3_ENDPOINT,
|
||||
region_name=config.S3_REGION,
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
config=cfg,
|
||||
)
|
||||
|
||||
|
||||
def _code(exc: ClientError) -> str:
|
||||
return exc.response.get("Error", {}).get("Code", "")
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
"""Synchronous boto3 client; async wrappers run it in the threadpool."""
|
||||
|
||||
def __init__(self, access_key: Optional[str] = None, secret_key: Optional[str] = None):
|
||||
self.bucket = config.S3_BUCKET
|
||||
self._s3 = _client(access_key or config.S3_ACCESS_KEY_ID, secret_key or config.S3_SECRET_ACCESS_KEY)
|
||||
|
||||
def put_sync(self, key: str, fileobj: BinaryIO, size: int, content_type: str, sha256_hex: str) -> None:
|
||||
fileobj.seek(0)
|
||||
try:
|
||||
# x-amz-checksum-sha256: S3 rejects the PUT if the received bytes differ from what we hashed.
|
||||
self._s3.put_object(
|
||||
Bucket=self.bucket,
|
||||
Key=key,
|
||||
Body=fileobj,
|
||||
ContentLength=size,
|
||||
ContentType=content_type,
|
||||
ChecksumSHA256=base64.b64encode(bytes.fromhex(sha256_hex)).decode("ascii"),
|
||||
)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
logger.warning("s3 put failed: %s %s", type(exc).__name__, _code(exc) if isinstance(exc, ClientError) else "")
|
||||
raise S3Unavailable() from None
|
||||
|
||||
async def put(self, key: str, fileobj: BinaryIO, size: int, content_type: str, sha256_hex: str) -> None:
|
||||
await run_in_threadpool(self.put_sync, key, fileobj, size, content_type, sha256_hex)
|
||||
|
||||
def download_sync(self, key: str, fileobj: BinaryIO, max_bytes: int) -> int:
|
||||
"""Copy an object into fileobj; raises S3NotFound for a missing key (permanent), S3Unavailable otherwise."""
|
||||
try:
|
||||
obj = self._s3.get_object(Bucket=self.bucket, Key=key)
|
||||
except ClientError as exc:
|
||||
if _code(exc) in ("NoSuchKey", "404", "NotFound"):
|
||||
raise S3NotFound(key) from None
|
||||
raise S3Unavailable() from None
|
||||
except BotoCoreError:
|
||||
raise S3Unavailable() from None
|
||||
size = 0
|
||||
try:
|
||||
for chunk in obj["Body"].iter_chunks(DOWNLOAD_CHUNK):
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise S3Unavailable()
|
||||
fileobj.write(chunk)
|
||||
except BotoCoreError:
|
||||
raise S3Unavailable() from None
|
||||
finally:
|
||||
obj["Body"].close()
|
||||
return size
|
||||
|
||||
def _open(self, key: str):
|
||||
try:
|
||||
return self._s3.get_object(Bucket=self.bucket, Key=key)
|
||||
except ClientError as exc:
|
||||
logger.error("s3 get failed for existing metadata: %s", _code(exc))
|
||||
raise S3Unavailable() from None
|
||||
except BotoCoreError as exc:
|
||||
logger.warning("s3 get failed: %s", type(exc).__name__)
|
||||
raise S3Unavailable() from None
|
||||
|
||||
async def open(self, key: str) -> Tuple[Iterator[bytes], int, Callable[[], None]]:
|
||||
obj = await run_in_threadpool(self._open, key)
|
||||
body = obj["Body"]
|
||||
return body.iter_chunks(DOWNLOAD_CHUNK), int(obj["ContentLength"]), body.close
|
||||
|
||||
def delete_sync(self, key: str) -> None:
|
||||
try:
|
||||
self._s3.delete_object(Bucket=self.bucket, Key=key)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise S3Unavailable() from exc
|
||||
|
||||
async def delete_quietly(self, key: str) -> bool:
|
||||
try:
|
||||
await run_in_threadpool(self.delete_sync, key)
|
||||
return True
|
||||
except S3Unavailable:
|
||||
logger.warning("compensating delete failed; sweeper will retry later")
|
||||
return False
|
||||
|
||||
def list_prefix(self, prefix: str) -> Iterator[Tuple[str, datetime]]:
|
||||
paginator = self._s3.get_paginator("list_objects_v2")
|
||||
try:
|
||||
for page in paginator.paginate(Bucket=self.bucket, Prefix=prefix, PaginationConfig={"PageSize": 1000}):
|
||||
for item in page.get("Contents", []):
|
||||
yield item["Key"], item["LastModified"]
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise S3Unavailable() from exc
|
||||
|
||||
def delete_many(self, keys: List[str]) -> int:
|
||||
deleted = 0
|
||||
for i in range(0, len(keys), 1000):
|
||||
batch = keys[i:i + 1000]
|
||||
try:
|
||||
out = self._s3.delete_objects(Bucket=self.bucket, Delete={"Objects": [{"Key": k} for k in batch], "Quiet": True})
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise S3Unavailable() from exc
|
||||
deleted += len(batch) - len(out.get("Errors", []))
|
||||
return deleted
|
||||
|
||||
def create_bucket(self) -> bool:
|
||||
try:
|
||||
self._s3.create_bucket(Bucket=self.bucket)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if _code(exc) in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
|
||||
return False
|
||||
raise
|
||||
|
||||
|
||||
def storage_unavailable() -> ApiError:
|
||||
return ApiError(503, "unavailable", "attachment storage temporarily unavailable")
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
"""Operator CLI (runs inside the worker image, never exposed over HTTP).
|
||||
|
||||
python -m app.ops failed [--limit N] registry of failed jobs (the "DLQ" of the DB)
|
||||
python -m app.ops replay <attachment_id> --actor NAME explicit failed -> queued, audited
|
||||
python -m app.ops reprocess <attachment_id> --pipeline-version N new job for a newer pipeline version
|
||||
python -m app.ops inspect <attachment_id> JSON: attachment, jobs, variants, events, S3 keys
|
||||
python -m app.ops stats queue depth, DLQ, outbox backlog, job states
|
||||
python -m app.ops fault arm <point> <action> [--attachment ID] [--count N]
|
||||
python -m app.ops fault clear
|
||||
python -m app.ops republish <attachment_id> [--attempt N] [--pipeline-version N]
|
||||
raw publish bypassing the outbox: duplicate / stale / reordered message for fault tests
|
||||
python -m app.ops dlq-peek show (and requeue nothing from) the broker DLQ
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app import config, faults, jobs
|
||||
from app.broker import Broker, job_payload
|
||||
from app.objects import FINAL_PREFIX, ObjectStore
|
||||
|
||||
ACTOR_PREFIX = "operator:"
|
||||
|
||||
|
||||
def _ts(v):
|
||||
return v.isoformat() if v is not None else None
|
||||
|
||||
|
||||
async def connect():
|
||||
return await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT)
|
||||
|
||||
|
||||
async def cmd_failed(args) -> int:
|
||||
conn = await connect()
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt, j.max_attempts, j.error_code, j.last_error,
|
||||
j.replays, j.updated_at, a.staging_deleted_at IS NULL AS staging_present
|
||||
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status = 'failed' ORDER BY j.updated_at DESC LIMIT $1
|
||||
""", args.limit)
|
||||
print(json.dumps([{k: (str(v) if isinstance(v, uuid.UUID) else _ts(v) if hasattr(v, "isoformat") else v)
|
||||
for k, v in dict(r).items()} for r in rows], ensure_ascii=False, indent=1))
|
||||
await conn.close()
|
||||
return 0
|
||||
|
||||
|
||||
async def cmd_replay(args) -> int:
|
||||
"""failed -> queued. Refuses anything that is not failed: a ready job is never executed again."""
|
||||
if not args.actor:
|
||||
print("--actor is required for the audit log", file=sys.stderr)
|
||||
return 2
|
||||
conn = await connect()
|
||||
try:
|
||||
async with conn.transaction():
|
||||
job = await conn.fetchrow(
|
||||
"""
|
||||
SELECT j.*, a.status AS a_status, a.staging_deleted_at FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.attachment_id = $1 ORDER BY j.pipeline_version DESC LIMIT 1 FOR UPDATE OF j, a
|
||||
""", uuid.UUID(args.attachment_id))
|
||||
if job is None:
|
||||
print("no job for this attachment", file=sys.stderr)
|
||||
return 1
|
||||
if job["status"] != "failed":
|
||||
await jobs.event(conn, job["job_id"], job["attachment_id"], "replay_refused", ACTOR_PREFIX + args.actor,
|
||||
job["attempt"], "status=%s" % job["status"])
|
||||
print("refused: job is %s (attachment %s); replay applies only to failed jobs" % (job["status"], job["a_status"]))
|
||||
return 3
|
||||
if job["staging_deleted_at"] is not None and job["a_status"] != "ready":
|
||||
print("refused: staging object already removed by retention; upload the file again", file=sys.stderr)
|
||||
return 4
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'queued', max_attempts = attempt + $2, replays = replays + 1,
|
||||
error_code = NULL, next_attempt_at = clock_timestamp(), updated_at = clock_timestamp()
|
||||
WHERE job_id = $1
|
||||
""", job["job_id"], config.JOB_MAX_ATTEMPTS)
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND status = 'failed'
|
||||
""", job["attachment_id"])
|
||||
await jobs.enqueue(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1)
|
||||
await jobs.event(conn, job["job_id"], job["attachment_id"], "replay", ACTOR_PREFIX + args.actor, job["attempt"],
|
||||
"previous error %s; %d more attempts" % (job["error_code"], config.JOB_MAX_ATTEMPTS))
|
||||
print("replayed job %s (attempt %d next)" % (job["job_id"], job["attempt"] + 1))
|
||||
return 0
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def cmd_reprocess(args) -> int:
|
||||
conn = await connect()
|
||||
try:
|
||||
async with conn.transaction():
|
||||
att = await conn.fetchrow("SELECT status, pipeline_version FROM attachments WHERE id = $1 FOR UPDATE",
|
||||
uuid.UUID(args.attachment_id))
|
||||
if att is None:
|
||||
print("unknown attachment", file=sys.stderr)
|
||||
return 1
|
||||
if att["pipeline_version"] is not None and att["pipeline_version"] >= args.pipeline_version:
|
||||
print("refused: v%d already published" % att["pipeline_version"])
|
||||
return 3
|
||||
try:
|
||||
async with conn.transaction():
|
||||
job_id = await jobs.create_job(conn, uuid.UUID(args.attachment_id), args.pipeline_version,
|
||||
ACTOR_PREFIX + args.actor)
|
||||
except asyncpg.UniqueViolationError:
|
||||
print("refused: a job for this (attachment, pipeline_version) already exists")
|
||||
return 3
|
||||
print("created job %s for v%d" % (job_id, args.pipeline_version))
|
||||
return 0
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def inspect(conn, attachment_id: uuid.UUID) -> dict:
|
||||
att = await conn.fetchrow("SELECT * FROM attachments WHERE id = $1", attachment_id)
|
||||
if att is None:
|
||||
return {"attachment": None}
|
||||
job_rows = await conn.fetch("SELECT * FROM jobs WHERE attachment_id = $1 ORDER BY pipeline_version", attachment_id)
|
||||
variants = await conn.fetch(
|
||||
"SELECT pipeline_version, name, object_key, size_bytes, width, height, sha256, attempt FROM attachment_variants "
|
||||
"WHERE attachment_id = $1 ORDER BY pipeline_version, name", attachment_id)
|
||||
events = await conn.fetch(
|
||||
"SELECT event, attempt, actor, detail, created_at FROM job_events WHERE attachment_id = $1 ORDER BY id", attachment_id)
|
||||
outbox = await conn.fetch(
|
||||
"SELECT o.id, o.payload->>'attempt' AS attempt, o.published_at IS NOT NULL AS published, o.publish_count "
|
||||
"FROM outbox o JOIN jobs j ON j.job_id = o.job_id WHERE j.attachment_id = $1 ORDER BY o.id", attachment_id)
|
||||
store = ObjectStore()
|
||||
keys = await asyncio.to_thread(lambda: sorted(k for k, _ in store.list_prefix(FINAL_PREFIX + attachment_id.hex + "/")))
|
||||
staging = await asyncio.to_thread(lambda: [k for k, _ in store.list_prefix(att["staging_key"] or "-")])
|
||||
|
||||
def clean(row):
|
||||
return {k: (str(v) if isinstance(v, uuid.UUID) else _ts(v) if hasattr(v, "isoformat") else v) for k, v in dict(row).items()}
|
||||
return {
|
||||
"attachment": {k: v for k, v in clean(att).items() if k in (
|
||||
"id", "status", "error_code", "pipeline_version", "sha256", "size_bytes", "staging_deleted_at", "updated_at")},
|
||||
"jobs": [{k: v for k, v in clean(j).items() if k in (
|
||||
"job_id", "pipeline_version", "status", "attempt", "max_attempts", "error_code", "last_error", "replays",
|
||||
"lease_owner")} for j in job_rows],
|
||||
"variants": [clean(v) for v in variants],
|
||||
"events": [clean(e) for e in events],
|
||||
"outbox": [clean(o) for o in outbox],
|
||||
"s3_final_keys": keys,
|
||||
"s3_staging_keys": staging,
|
||||
}
|
||||
|
||||
|
||||
async def cmd_inspect(args) -> int:
|
||||
conn = await connect()
|
||||
print(json.dumps(await inspect(conn, uuid.UUID(args.attachment_id)), ensure_ascii=False, indent=1))
|
||||
await conn.close()
|
||||
return 0
|
||||
|
||||
|
||||
async def cmd_stats(args) -> int:
|
||||
conn = await connect()
|
||||
states = {r["status"]: r["n"] for r in await conn.fetch("SELECT status, count(*) AS n FROM jobs GROUP BY status")}
|
||||
backlog = await conn.fetchval("SELECT count(*) FROM outbox WHERE published_at IS NULL")
|
||||
await conn.close()
|
||||
broker = Broker()
|
||||
await broker.connect()
|
||||
q = await broker.channel.declare_queue(config.BROKER_QUEUE, passive=True)
|
||||
d = await broker.channel.declare_queue(config.BROKER_DLQ, passive=True)
|
||||
out = {"jobs": states, "outbox_unpublished": backlog,
|
||||
"queue_ready_messages": q.declaration_result.message_count,
|
||||
"queue_consumers": q.declaration_result.consumer_count,
|
||||
"dlq_messages": d.declaration_result.message_count}
|
||||
await broker.close()
|
||||
print(json.dumps(out))
|
||||
return 0
|
||||
|
||||
|
||||
async def cmd_fault(args) -> int:
|
||||
conn = await connect()
|
||||
if args.fault_cmd == "clear":
|
||||
n = await conn.execute("DELETE FROM fault_injections")
|
||||
print("cleared", n.split()[-1])
|
||||
elif args.fault_cmd == "arm":
|
||||
if args.point not in faults.POINTS:
|
||||
print("unknown point; one of: " + ", ".join(sorted(faults.POINTS)), file=sys.stderr)
|
||||
return 2
|
||||
if not (args.action in ("crash", "transient", "permanent") or args.action.startswith("delay:")):
|
||||
print("action: crash | transient | permanent | delay:<seconds>", file=sys.stderr)
|
||||
return 2
|
||||
await conn.execute("INSERT INTO fault_injections (point, action, attachment_id, remaining) VALUES ($1, $2, $3, $4)",
|
||||
args.point, args.action, uuid.UUID(args.attachment) if args.attachment else None, args.count)
|
||||
print("armed %s -> %s x%d" % (args.point, args.action, args.count))
|
||||
await conn.close()
|
||||
return 0
|
||||
|
||||
|
||||
async def cmd_republish(args) -> int:
|
||||
conn = await connect()
|
||||
job = await conn.fetchrow(
|
||||
"SELECT * FROM jobs WHERE attachment_id = $1 AND ($2::int IS NULL OR pipeline_version = $2) "
|
||||
"ORDER BY pipeline_version LIMIT 1", uuid.UUID(args.attachment_id), args.pipeline_version)
|
||||
await conn.close()
|
||||
if job is None:
|
||||
print("no job", file=sys.stderr)
|
||||
return 1
|
||||
attempt = args.attempt or max(1, job["attempt"])
|
||||
broker = Broker()
|
||||
await broker.connect()
|
||||
await broker.publish(job_payload(job["job_id"], job["attachment_id"], job["pipeline_version"], attempt))
|
||||
await broker.close()
|
||||
print("published raw message job=%s v%d attempt=%d" % (job["job_id"], job["pipeline_version"], attempt))
|
||||
return 0
|
||||
|
||||
|
||||
async def cmd_dlq_peek(args) -> int:
|
||||
broker = Broker()
|
||||
await broker.connect()
|
||||
q = await broker.channel.declare_queue(config.BROKER_DLQ, passive=True)
|
||||
print(json.dumps({"dlq_messages": q.declaration_result.message_count}))
|
||||
msg = await q.get(no_ack=False, fail=False)
|
||||
if msg is not None:
|
||||
print(json.dumps({"body": msg.body.decode("utf-8", "replace")[:500],
|
||||
"x-death": str((msg.headers or {}).get("x-death"))[:300]}, ensure_ascii=False))
|
||||
await msg.nack(requeue=True)
|
||||
await broker.close()
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
s = sub.add_parser("failed"); s.add_argument("--limit", type=int, default=20); s.set_defaults(fn=cmd_failed)
|
||||
s = sub.add_parser("replay"); s.add_argument("attachment_id"); s.add_argument("--actor", required=True); s.set_defaults(fn=cmd_replay)
|
||||
s = sub.add_parser("reprocess"); s.add_argument("attachment_id"); s.add_argument("--pipeline-version", type=int, required=True)
|
||||
s.add_argument("--actor", default="cli"); s.set_defaults(fn=cmd_reprocess)
|
||||
s = sub.add_parser("inspect"); s.add_argument("attachment_id"); s.set_defaults(fn=cmd_inspect)
|
||||
s = sub.add_parser("stats"); s.set_defaults(fn=cmd_stats)
|
||||
s = sub.add_parser("fault"); fs = s.add_subparsers(dest="fault_cmd", required=True)
|
||||
a = fs.add_parser("arm"); a.add_argument("point"); a.add_argument("action")
|
||||
a.add_argument("--attachment"); a.add_argument("--count", type=int, default=1)
|
||||
fs.add_parser("clear"); s.set_defaults(fn=cmd_fault)
|
||||
s = sub.add_parser("republish"); s.add_argument("attachment_id"); s.add_argument("--attempt", type=int)
|
||||
s.add_argument("--pipeline-version", type=int); s.set_defaults(fn=cmd_republish)
|
||||
s = sub.add_parser("dlq-peek"); s.set_defaults(fn=cmd_dlq_peek)
|
||||
args = p.parse_args()
|
||||
return asyncio.run(args.fn(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
"""Transactional-outbox relay: PostgreSQL outbox -> RabbitMQ with publisher confirms.
|
||||
|
||||
SELECT ... FOR UPDATE SKIP LOCKED -> publish + wait for confirm -> UPDATE published_at -> COMMIT
|
||||
|
||||
A crash after the confirm but before COMMIT republishes the row later: a duplicate message, which the worker
|
||||
treats as a no-op. A row is never marked published without a confirm, so a message accepted by the API is never
|
||||
lost between COMMIT and publish. Several relays may run concurrently (SKIP LOCKED).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
import signal
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app import config, faults
|
||||
from app.broker import Broker
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("relay")
|
||||
|
||||
HEARTBEAT_FILE = "/tmp/relay-heartbeat"
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self):
|
||||
self.id = "relay-" + secrets.token_hex(4)
|
||||
self.pool = None
|
||||
self.broker = Broker()
|
||||
self.wakeup = asyncio.Event()
|
||||
self.stopping = asyncio.Event()
|
||||
|
||||
async def publish_batch(self) -> int:
|
||||
async with self.pool.acquire() as conn, conn.transaction():
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT id, job_id, payload FROM outbox
|
||||
WHERE published_at IS NULL AND available_at <= clock_timestamp()
|
||||
ORDER BY available_at, id LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""",
|
||||
config.RELAY_BATCH,
|
||||
)
|
||||
for row in rows:
|
||||
payload = json.loads(row["payload"])
|
||||
await self.broker.publish(payload) # returns after the publisher confirm
|
||||
await faults.hit(self.pool, "relay.after_confirm_before_mark", uuid.UUID(payload["attachment_id"]), self.id)
|
||||
if rows:
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE outbox SET published_at = clock_timestamp(), publish_count = publish_count + 1
|
||||
WHERE id = ANY($1::bigint[])
|
||||
""",
|
||||
[r["id"] for r in rows],
|
||||
)
|
||||
return len(rows)
|
||||
|
||||
async def listen(self) -> asyncpg.Connection:
|
||||
conn = await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT)
|
||||
await conn.add_listener("outbox", lambda *_: self.wakeup.set())
|
||||
return conn
|
||||
|
||||
async def run(self) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
loop.add_signal_handler(sig, self.stopping.set)
|
||||
listener = None
|
||||
failures = 0
|
||||
while not self.stopping.is_set():
|
||||
try:
|
||||
if self.pool is None:
|
||||
self.pool = await asyncpg.create_pool(config.DATABASE_URL, min_size=1, max_size=3,
|
||||
timeout=config.DB_CONNECT_TIMEOUT,
|
||||
command_timeout=config.DB_COMMAND_TIMEOUT)
|
||||
if self.broker.exchange is None:
|
||||
await self.broker.connect()
|
||||
logger.info("%s connected; fault_injection=%s", self.id, config.FAULT_INJECTION)
|
||||
if listener is None or listener.is_closed():
|
||||
listener = await self.listen()
|
||||
self.wakeup.clear()
|
||||
published = await self.publish_batch()
|
||||
failures = 0
|
||||
with open(HEARTBEAT_FILE, "w", encoding="ascii") as fh:
|
||||
fh.write(str(time.time()))
|
||||
if published:
|
||||
logger.info("published %d outbox message(s)", published)
|
||||
if published == config.RELAY_BATCH:
|
||||
continue
|
||||
try:
|
||||
# NOTIFY wakes us immediately; the poll interval covers delayed (backoff) rows.
|
||||
await asyncio.wait_for(self.wakeup.wait(), config.RELAY_POLL_SECONDS)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
except Exception as exc:
|
||||
failures += 1
|
||||
delay = min(10.0, 0.5 * 2 ** min(failures, 5))
|
||||
logger.warning("relay cycle failed (%s); retry in %.1fs; rows stay unpublished", type(exc).__name__, delay)
|
||||
if self.broker.exchange is None or self.broker.connection.is_closed:
|
||||
try:
|
||||
await self.broker.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.broker = Broker()
|
||||
if listener is not None and not listener.is_closed():
|
||||
try:
|
||||
await listener.close()
|
||||
except Exception:
|
||||
pass
|
||||
listener = None
|
||||
await asyncio.sleep(delay)
|
||||
await self.broker.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(Relay().run())
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Idempotent bucket bootstrap with the admin identity (the API identity cannot create buckets).
|
||||
|
||||
Checks afterwards that anonymous access to the bucket is denied, and warms up the write path: after a
|
||||
SeaweedFS restart the first PUT waits ~2.5 s for the volume topology, which a client with a short timeout
|
||||
would see as a failed upload. The API starts only after this one-shot service exits 0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from app import config
|
||||
from app.config import _secret
|
||||
from app.objects import ObjectStore, S3Unavailable
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("s3-bootstrap")
|
||||
|
||||
|
||||
def anonymous_status(path: str) -> int:
|
||||
try:
|
||||
with urllib.request.urlopen(config.S3_ENDPOINT.rstrip("/") + path, timeout=3) as r:
|
||||
return r.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main() -> int:
|
||||
admin = ObjectStore(_secret("S3_ADMIN_ACCESS_KEY_ID"), _secret("S3_ADMIN_SECRET_ACCESS_KEY"))
|
||||
for attempt in range(1, 31):
|
||||
try:
|
||||
created = admin.create_bucket()
|
||||
break
|
||||
except (BotoCoreError, ClientError, S3Unavailable) as exc:
|
||||
logger.warning("s3 not ready (attempt %d/30): %s", attempt, type(exc).__name__)
|
||||
time.sleep(1)
|
||||
else:
|
||||
return 1
|
||||
logger.info("bucket %s %s", config.S3_BUCKET, "created" if created else "already exists")
|
||||
|
||||
for path in ("/" + config.S3_BUCKET, "/" + config.S3_BUCKET + "/originals/probe"):
|
||||
status = anonymous_status(path)
|
||||
if status not in (401, 403):
|
||||
logger.error("anonymous request %s returned %d: bucket is NOT private", path, status)
|
||||
return 1
|
||||
logger.info("anonymous list/get denied: bucket is private")
|
||||
|
||||
probe = "health/bootstrap-probe" # outside originals/, so the sweeper never looks at it
|
||||
for attempt in range(1, 31):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
admin._s3.put_object(Bucket=admin.bucket, Key=probe, Body=io.BytesIO(b"probe"))
|
||||
admin._s3.get_object(Bucket=admin.bucket, Key=probe)["Body"].read()
|
||||
admin._s3.delete_object(Bucket=admin.bucket, Key=probe)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
logger.warning("write probe failed (attempt %d/30): %s", attempt, type(exc).__name__)
|
||||
time.sleep(1)
|
||||
continue
|
||||
elapsed = time.monotonic() - started
|
||||
if elapsed < 0.5:
|
||||
logger.info("write path warm: put/get/delete probe %.3fs", elapsed)
|
||||
return 0
|
||||
logger.info("write probe slow (%.2fs), repeating", elapsed)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
sys.exit(main())
|
||||
+424
@@ -0,0 +1,424 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app import config, jobs
|
||||
from app.errors import ApiError
|
||||
|
||||
|
||||
def fmt_ts(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def user_row(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_row(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(m) for m in row["member_ids"]],
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_row(row: asyncpg.Record, attachment_ids: Optional[List[uuid.UUID]] = None) -> dict:
|
||||
if attachment_ids is None:
|
||||
attachment_ids = row["attachment_ids"]
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
"attachment_ids": [str(a) for a in attachment_ids],
|
||||
}
|
||||
|
||||
|
||||
def variant_row(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"name": row["name"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"width": row["width"],
|
||||
"height": row["height"],
|
||||
"sha256": row["sha256"],
|
||||
}
|
||||
|
||||
|
||||
VARIANT_ORDER = {"thumbnail": 0, "crop": 1, "optimized": 2}
|
||||
|
||||
|
||||
def attachment_row(row: asyncpg.Record, variants=None) -> dict:
|
||||
"""Public view: variants of the currently published pipeline version, only when ready."""
|
||||
items = sorted((variant_row(v) for v in (variants or [])), key=lambda v: VARIANT_ORDER[v["name"]])
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["owner_id"]),
|
||||
"filename": row["filename"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
"variants": items if row["status"] == "ready" else [],
|
||||
"error_code": row["error_code"] if row["status"] == "failed" else None,
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
"updated_at": fmt_ts(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
ATTACHMENT_COLUMNS = ("id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, object_key, "
|
||||
"error_code, pipeline_version, created_at, updated_at")
|
||||
|
||||
|
||||
def encode_cursor(resource: str, created_at: str, item_id: str) -> str:
|
||||
payload = json.dumps({"r": resource, "t": created_at, "i": item_id}, separators=(",", ":"))
|
||||
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(resource: str, cursor: str) -> Tuple[datetime, uuid.UUID]:
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
payload = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
|
||||
if payload.get("r") != resource:
|
||||
raise ValueError("cursor belongs to a different resource")
|
||||
created_at = datetime.fromisoformat(payload["t"].replace("Z", "+00:00"))
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError("cursor time has no timezone")
|
||||
return created_at, uuid.UUID(payload["i"])
|
||||
except Exception as exc:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
||||
|
||||
|
||||
def page_of(items: List[dict], resource: str, limit: int) -> dict:
|
||||
page = items[:limit]
|
||||
next_cursor = None
|
||||
if len(items) > limit:
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(resource, last["created_at"], last["id"])
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self):
|
||||
self.pool: Optional[asyncpg.Pool] = None
|
||||
|
||||
async def open(self) -> None:
|
||||
self.pool = await asyncpg.create_pool(
|
||||
config.DATABASE_URL,
|
||||
min_size=0,
|
||||
max_size=config.DB_POOL_MAX,
|
||||
timeout=config.DB_CONNECT_TIMEOUT,
|
||||
command_timeout=config.DB_COMMAND_TIMEOUT,
|
||||
max_inactive_connection_lifetime=60,
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.pool is not None:
|
||||
await self.pool.close()
|
||||
|
||||
def acquire(self):
|
||||
return self.pool.acquire(timeout=config.DB_ACQUIRE_TIMEOUT)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchval("SELECT 1") == 1
|
||||
|
||||
|
||||
async def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
|
||||
async with self.acquire() as conn:
|
||||
try:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
uuid.uuid4(), username, display_name, password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
raise ApiError(409, "conflict", "username already taken") from None
|
||||
return user_row(row)
|
||||
|
||||
async def get_credentials(self, username: str) -> Optional[asyncpg.Record]:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchrow(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
|
||||
username,
|
||||
)
|
||||
|
||||
|
||||
async def create_session(self, token_hash: bytes, user_id: uuid.UUID, ttl_seconds: int) -> datetime:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchval(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3))
|
||||
RETURNING expires_at
|
||||
""",
|
||||
token_hash, user_id, float(ttl_seconds),
|
||||
)
|
||||
|
||||
async def find_session(self, token_hash: bytes) -> Optional[asyncpg.Record]:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchrow(
|
||||
"""
|
||||
SELECT s.expires_at, u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.revoked_at IS NULL AND s.expires_at > clock_timestamp()
|
||||
""",
|
||||
token_hash,
|
||||
)
|
||||
|
||||
async def revoke_session(self, token_hash: bytes) -> Optional[datetime]:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchval(
|
||||
"""
|
||||
UPDATE sessions SET revoked_at = clock_timestamp()
|
||||
WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > clock_timestamp()
|
||||
RETURNING expires_at
|
||||
""",
|
||||
token_hash,
|
||||
)
|
||||
|
||||
|
||||
async def create_chat(self, title: str, member_ids: List[uuid.UUID]) -> dict:
|
||||
chat_id = uuid.uuid4()
|
||||
async with self.acquire() as conn:
|
||||
try:
|
||||
async with conn.transaction():
|
||||
row = await conn.fetchrow(
|
||||
"INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at",
|
||||
chat_id, title,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT $1, m.user_id, m.ord - 1
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS m(user_id, ord)
|
||||
""",
|
||||
chat_id, member_ids,
|
||||
)
|
||||
except asyncpg.ForeignKeyViolationError:
|
||||
raise ApiError(400, "invalid_request", "unknown member in member_ids") from None
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(m) for m in member_ids],
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
async def get_chat_for_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> Optional[dict]:
|
||||
async with self.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id ORDER BY m.position) AS member_ids
|
||||
FROM chats c JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (SELECT 1 FROM chat_members me WHERE me.chat_id = c.id AND me.user_id = $2)
|
||||
GROUP BY c.id
|
||||
""",
|
||||
chat_id, user_id,
|
||||
)
|
||||
return chat_row(row) if row else None
|
||||
|
||||
async def list_chats(self, user_id: uuid.UUID, limit: int, cursor: Optional[str]) -> dict:
|
||||
after_t, after_i = decode_cursor("chats", cursor) if cursor else (None, None)
|
||||
async with self.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id ORDER BY m.position) AS member_ids
|
||||
FROM chat_members me
|
||||
JOIN chats c ON c.id = me.chat_id
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE me.user_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
""",
|
||||
user_id, after_t, after_i, limit + 1,
|
||||
)
|
||||
return page_of([chat_row(r) for r in rows], "chats", limit)
|
||||
|
||||
async def is_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool:
|
||||
async with self.acquire() as conn:
|
||||
return bool(await conn.fetchval(
|
||||
"SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)",
|
||||
chat_id, user_id,
|
||||
))
|
||||
|
||||
|
||||
async def create_message(
|
||||
self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str, attachment_ids: List[uuid.UUID],
|
||||
key: str, request_hash: bytes,
|
||||
) -> Optional[dict]:
|
||||
async with self.acquire() as conn:
|
||||
for _ in range(3):
|
||||
try:
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"""
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3
|
||||
AND created_at < clock_timestamp() - make_interval(secs => $4)
|
||||
""",
|
||||
sender_id, chat_id, key, float(config.IDEMPOTENCY_TTL_SECONDS),
|
||||
)
|
||||
message_id = uuid.uuid4()
|
||||
claimed = await conn.fetchval(
|
||||
"""
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $1)
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
RETURNING message_id
|
||||
""",
|
||||
sender_id, chat_id, key, request_hash, message_id,
|
||||
)
|
||||
if claimed is not None:
|
||||
if attachment_ids:
|
||||
# lab5: queued/processing/ready may be linked; failed -> 409; unknown/foreign -> 404
|
||||
found = await conn.fetch(
|
||||
"SELECT status FROM attachments WHERE id = ANY($1::uuid[]) AND chat_id = $2 FOR SHARE",
|
||||
attachment_ids, chat_id,
|
||||
)
|
||||
if len(found) != len(attachment_ids):
|
||||
raise ApiError(404, "not_found", "attachment not found")
|
||||
if any(r["status"] == "failed" for r in found):
|
||||
raise ApiError(409, "conflict", "failed attachment cannot be attached")
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
""",
|
||||
message_id, chat_id, sender_id, text,
|
||||
)
|
||||
if attachment_ids:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO message_attachments (message_id, attachment_id, chat_id, position)
|
||||
SELECT $1, a.id, $2, a.ord - 1
|
||||
FROM unnest($3::uuid[]) WITH ORDINALITY AS a(id, ord)
|
||||
""",
|
||||
message_id, chat_id, attachment_ids,
|
||||
)
|
||||
return message_row(row, attachment_ids)
|
||||
except asyncpg.ForeignKeyViolationError:
|
||||
return None
|
||||
|
||||
existing = await conn.fetchrow(
|
||||
"""
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id FROM message_attachments ma WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids
|
||||
FROM idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
JOIN chat_members cm ON cm.chat_id = k.chat_id AND cm.user_id = k.user_id
|
||||
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3
|
||||
""",
|
||||
sender_id, chat_id, key,
|
||||
)
|
||||
if existing is None:
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)",
|
||||
chat_id, sender_id,
|
||||
)
|
||||
if not is_member:
|
||||
return None
|
||||
continue
|
||||
if existing["request_hash"] != request_hash:
|
||||
raise ApiError(409, "conflict", "Idempotency-Key was already used with a different request")
|
||||
return message_row(existing)
|
||||
raise ApiError(503, "unavailable", "could not settle idempotent request, retry with the same key")
|
||||
|
||||
async def list_messages(self, chat_id: uuid.UUID, limit: int, cursor: Optional[str]) -> dict:
|
||||
resource = str(chat_id)
|
||||
async with self.acquire() as conn:
|
||||
if cursor:
|
||||
after_t, after_i = decode_cursor(resource, cursor)
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id FROM message_attachments ma WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
""",
|
||||
chat_id, after_t, after_i, limit + 1,
|
||||
)
|
||||
else:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id FROM message_attachments ma WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2
|
||||
""",
|
||||
chat_id, limit + 1,
|
||||
)
|
||||
return page_of([message_row(r) for r in rows], resource, limit)
|
||||
|
||||
|
||||
async def create_queued_attachment(
|
||||
self, attachment_id: uuid.UUID, chat_id: uuid.UUID, owner_id: uuid.UUID, filename: str,
|
||||
content_type: str, size_bytes: int, sha256: str, width: int, height: int,
|
||||
staging_key: str, object_key: str, actor: str,
|
||||
) -> Optional[dict]:
|
||||
"""Durable handoff: attachment(queued) + job + outbox row in ONE transaction, after the staging PUT."""
|
||||
async with self.acquire() as conn:
|
||||
try:
|
||||
async with conn.transaction():
|
||||
row = await conn.fetchrow(
|
||||
f"""
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, object_key, staging_key, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, 'queued')
|
||||
RETURNING {ATTACHMENT_COLUMNS}
|
||||
""",
|
||||
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height,
|
||||
object_key, staging_key,
|
||||
)
|
||||
await jobs.create_job(conn, attachment_id, config.PIPELINE_VERSION, actor)
|
||||
except asyncpg.ForeignKeyViolationError:
|
||||
return None
|
||||
return attachment_row(row)
|
||||
|
||||
async def get_attachment_for_member(self, attachment_id: uuid.UUID, user_id: uuid.UUID):
|
||||
async with self.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
f"""
|
||||
SELECT {ATTACHMENT_COLUMNS} FROM attachments a
|
||||
WHERE a.id = $1
|
||||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = $2)
|
||||
""",
|
||||
attachment_id, user_id,
|
||||
)
|
||||
if row is None or row["status"] != "ready":
|
||||
return row, []
|
||||
variants = await conn.fetch(
|
||||
"""
|
||||
SELECT name, object_key, content_type, size_bytes, width, height, sha256
|
||||
FROM attachment_variants WHERE attachment_id = $1 AND pipeline_version = $2
|
||||
""",
|
||||
attachment_id, row["pipeline_version"],
|
||||
)
|
||||
return row, variants
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
"""Staging/orphan cleanup with documented retention. Never touches work that is still in progress.
|
||||
|
||||
Rules (every step idempotent, repeated runs are safe):
|
||||
1. staging/<id> of a READY attachment -> delete (the worker deletes it right after COMMIT;
|
||||
this repairs a crash/failed delete in between)
|
||||
2. staging/<id> of a FAILED attachment older than STAGING_RETENTION_SECONDS -> delete, mark staging_deleted_at
|
||||
(until then an operator replay can still use it; afterwards replay ends as failed staging_missing)
|
||||
3. staging/<id> without any attachment row, older than ORPHAN_GRACE_SECONDS -> delete
|
||||
(API crashed/failed between the staging PUT and the COMMIT of attachment+job+outbox; no 202 was sent)
|
||||
4. attachments/<id>/... without any attachment row, or not referenced by any committed row (superseded
|
||||
older pipeline version, fenced-out attempt) while no job of that attachment is active, older than grace
|
||||
5. published outbox rows older than 7 days -> delete
|
||||
Queued/processing attachments are never touched: their staging object is the only copy of accepted work.
|
||||
|
||||
python -m app.sweeper --once --dry-run # report only
|
||||
python -m app.sweeper --once # one real pass
|
||||
python -m app.sweeper # loop every SWEEP_INTERVAL_SECONDS
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import asyncpg
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app import config
|
||||
from app.objects import FINAL_PREFIX, STAGING_PREFIX, ObjectStore, S3Unavailable
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("sweeper")
|
||||
|
||||
LOCK_ID = 2026_0005
|
||||
HEARTBEAT_FILE = "/tmp/sweeper-heartbeat"
|
||||
|
||||
|
||||
def _id_from_key(key: str, prefix: str):
|
||||
part = key[len(prefix):].split("/", 1)[0]
|
||||
try:
|
||||
return uuid.UUID(hex=part)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
async def sweep(conn: asyncpg.Connection, objects: ObjectStore, grace: int, retention: int, dry_run: bool) -> dict:
|
||||
started = time.monotonic()
|
||||
report = {"dry_run": dry_run, "grace_seconds": grace, "retention_seconds": retention,
|
||||
"staging_ready_deleted": 0, "staging_failed_expired": 0, "staging_orphans": 0, "final_orphans": 0,
|
||||
"outbox_pruned": 0, "objects_scanned": 0}
|
||||
now = datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(seconds=grace)
|
||||
|
||||
# 1 + 2: staging of finished attachments
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT id, staging_key, status FROM attachments
|
||||
WHERE staging_deleted_at IS NULL AND staging_key IS NOT NULL
|
||||
AND (status = 'ready'
|
||||
OR (status = 'failed' AND updated_at < clock_timestamp() - make_interval(secs => $1)))
|
||||
""", float(retention))
|
||||
for row in rows:
|
||||
report["staging_ready_deleted" if row["status"] == "ready" else "staging_failed_expired"] += 1
|
||||
if dry_run:
|
||||
continue
|
||||
await run_in_threadpool(objects.delete_sync, row["staging_key"])
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET staging_deleted_at = clock_timestamp() WHERE id = $1 AND status IN ('ready', 'failed')",
|
||||
row["id"])
|
||||
|
||||
# 3 + 4: objects without any row (no 202 was ever sent for them)
|
||||
for prefix, counter in ((STAGING_PREFIX, "staging_orphans"), (FINAL_PREFIX, "final_orphans")):
|
||||
def old_keys():
|
||||
out = []
|
||||
for key, modified in objects.list_prefix(prefix):
|
||||
report["objects_scanned"] += 1
|
||||
if modified < cutoff:
|
||||
out.append(key)
|
||||
return out
|
||||
keys = await run_in_threadpool(old_keys)
|
||||
by_id = {}
|
||||
for key in keys:
|
||||
ident = _id_from_key(key, prefix)
|
||||
if ident is not None:
|
||||
by_id.setdefault(ident, []).append(key)
|
||||
if not by_id:
|
||||
continue
|
||||
known = {r["id"] for r in await conn.fetch("SELECT id FROM attachments WHERE id = ANY($1::uuid[])", list(by_id))}
|
||||
orphans = [k for ident, ks in by_id.items() if ident not in known for k in ks]
|
||||
if prefix == FINAL_PREFIX:
|
||||
# objects of a known attachment that no committed row references: a superseded older pipeline
|
||||
# version or a fenced-out attempt. Only after the grace period (longer than any live attempt).
|
||||
candidates = [k for ident, ks in by_id.items() if ident in known for k in ks]
|
||||
if candidates:
|
||||
referenced = {r["k"] for r in await conn.fetch(
|
||||
"""
|
||||
SELECT object_key AS k FROM attachments WHERE object_key = ANY($1::text[]) AND status = 'ready'
|
||||
UNION SELECT object_key FROM attachment_variants WHERE object_key = ANY($1::text[])
|
||||
UNION SELECT a.object_key FROM attachments a WHERE a.object_key = ANY($1::text[])
|
||||
AND a.status IN ('queued', 'processing')
|
||||
""", candidates)}
|
||||
live = {r["id"] for r in await conn.fetch(
|
||||
"SELECT DISTINCT attachment_id AS id FROM jobs WHERE status IN ('queued', 'processing')")}
|
||||
orphans += [k for k in candidates if k not in referenced and _id_from_key(k, prefix) not in live]
|
||||
report[counter] += len(orphans)
|
||||
if orphans and not dry_run:
|
||||
await run_in_threadpool(objects.delete_many, orphans)
|
||||
|
||||
# 5: outbox history
|
||||
if not dry_run:
|
||||
res = await conn.execute(
|
||||
"DELETE FROM outbox WHERE published_at < clock_timestamp() - interval '7 days'")
|
||||
report["outbox_pruned"] = int(res.split()[-1])
|
||||
|
||||
report["duration_ms"] = round((time.monotonic() - started) * 1000, 1)
|
||||
return report
|
||||
|
||||
|
||||
async def run_once(grace: int, retention: int, dry_run: bool) -> dict:
|
||||
conn = await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT)
|
||||
try:
|
||||
if not await conn.fetchval("SELECT pg_try_advisory_lock($1)", LOCK_ID):
|
||||
return {"skipped": "another sweeper holds the lock"}
|
||||
try:
|
||||
return await sweep(conn, ObjectStore(), grace, retention, dry_run)
|
||||
finally:
|
||||
await conn.execute("SELECT pg_advisory_unlock($1)", LOCK_ID)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("--once", action="store_true")
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
p.add_argument("--grace", type=int, default=config.ORPHAN_GRACE_SECONDS)
|
||||
p.add_argument("--retention", type=int, default=config.STAGING_RETENTION_SECONDS)
|
||||
p.add_argument("--interval", type=int, default=config.SWEEP_INTERVAL_SECONDS)
|
||||
args = p.parse_args()
|
||||
if args.grace < 60:
|
||||
p.error("grace below 60 s could remove an upload that is still between staging PUT and COMMIT")
|
||||
while True:
|
||||
try:
|
||||
report = await run_once(args.grace, args.retention, args.dry_run)
|
||||
print(json.dumps(report, ensure_ascii=False), flush=True)
|
||||
with open(HEARTBEAT_FILE, "w", encoding="ascii") as fh:
|
||||
fh.write(str(time.time()))
|
||||
except (OSError, asyncpg.PostgresError, asyncpg.InterfaceError, S3Unavailable) as exc:
|
||||
logger.warning("sweep failed (%s); will retry", type(exc).__name__)
|
||||
if args.once:
|
||||
return 1
|
||||
if args.once:
|
||||
return 0
|
||||
await asyncio.sleep(args.interval)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(asyncio.run(main()))
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
"""Attachment worker: consumes attachments.process, publishes the original and variants, commits the result.
|
||||
|
||||
Delivery is at-least-once; the effect is idempotent because
|
||||
* PostgreSQL (jobs) decides whether a delivery may start an attempt: claim = queued -> processing with
|
||||
attempt+1 and a lease (lease_owner, lease_until). Duplicates/stale/reordered messages are acked as no-ops.
|
||||
* (job_id, attempt) is a fencing token: the result COMMIT succeeds only if this worker still owns the lease.
|
||||
* S3 keys are the effect key (attachment, pipeline_version, variant): a retry overwrites identical bytes.
|
||||
* attachment_variants has PRIMARY KEY (attachment_id, pipeline_version, name): one row per variant.
|
||||
* A result of an older pipeline_version never replaces a newer published one (superseded).
|
||||
The message is acked only after the result (or the decision) is durably committed in PostgreSQL.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import signal
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
import asyncpg
|
||||
from aio_pika.abc import AbstractIncomingMessage
|
||||
|
||||
from app import config, faults, jobs
|
||||
from app.broker import Broker, InvalidJob, parse_job
|
||||
from app.imaging import ImageRejected, TransientFailure, run_isolated
|
||||
from app.objects import ObjectStore, S3NotFound, S3Unavailable, original_key, variant_key
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("worker")
|
||||
|
||||
HEARTBEAT_FILE = "/tmp/worker-heartbeat"
|
||||
DB_ERRORS = (OSError, asyncpg.PostgresConnectionError, asyncpg.InterfaceError, asyncpg.TooManyConnectionsError,
|
||||
asyncpg.exceptions.OperatorInterventionError, asyncio.TimeoutError)
|
||||
|
||||
|
||||
class Worker:
|
||||
def __init__(self):
|
||||
self.id = "worker-" + secrets.token_hex(4)
|
||||
self.pool: Optional[asyncpg.Pool] = None
|
||||
self.objects = ObjectStore()
|
||||
self.broker = Broker()
|
||||
self.inflight = set()
|
||||
self.stopping = asyncio.Event()
|
||||
|
||||
# ------------------------------------------------------------------ message entry point
|
||||
async def on_message(self, message: AbstractIncomingMessage) -> None:
|
||||
task = asyncio.current_task()
|
||||
self.inflight.add(task)
|
||||
try:
|
||||
await self._handle(message)
|
||||
finally:
|
||||
self.inflight.discard(task)
|
||||
|
||||
async def _handle(self, message: AbstractIncomingMessage) -> None:
|
||||
try:
|
||||
job = parse_job(message.body)
|
||||
except InvalidJob as exc:
|
||||
logger.error("rejecting malformed job message to DLQ: %s", exc)
|
||||
await message.reject(requeue=False) # -> attachments.dlx -> attachments.dlq
|
||||
return
|
||||
try:
|
||||
outcome = await self.process(job, message.redelivered)
|
||||
except DB_ERRORS as exc:
|
||||
# Nothing was decided durably. Give the message back after a pause (no hot loop); if the DB stays down
|
||||
# the lease expires and the reaper re-enqueues the job through the outbox.
|
||||
logger.warning("db unavailable while handling job %s: %s; requeue", job["job_id"], type(exc).__name__)
|
||||
await asyncio.sleep(2)
|
||||
await message.nack(requeue=True)
|
||||
return
|
||||
await faults.hit(self.pool, "worker.after_commit_before_ack", job["attachment_id"], self.id)
|
||||
await message.ack()
|
||||
logger.info("job %s attempt %s -> %s (redelivered=%s)", job["job_id"], job["attempt"], outcome, message.redelivered)
|
||||
|
||||
# ------------------------------------------------------------------ claim
|
||||
async def claim(self, job: dict, redelivered: bool):
|
||||
async with self.pool.acquire() as conn, conn.transaction():
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT j.*, a.status AS a_status, a.content_type, a.size_bytes, a.sha256, a.staging_key,
|
||||
a.staging_deleted_at, a.object_key, a.pipeline_version AS a_version,
|
||||
(j.lease_until > clock_timestamp()) AS lease_active,
|
||||
(j.next_attempt_at <= clock_timestamp() + interval '1 second') AS due
|
||||
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.job_id = $1
|
||||
FOR UPDATE OF j
|
||||
""",
|
||||
job["job_id"],
|
||||
)
|
||||
reason = None
|
||||
if row is None:
|
||||
reason = "unknown_job_noop"
|
||||
elif row["attachment_id"] != job["attachment_id"] or row["pipeline_version"] != job["pipeline_version"]:
|
||||
reason = "mismatched_message_noop"
|
||||
elif row["status"] == "done":
|
||||
reason = "duplicate_noop" # result already committed: ack after checking state
|
||||
elif row["status"] in ("failed", "superseded"):
|
||||
reason = row["status"] + "_noop"
|
||||
elif row["status"] == "processing":
|
||||
reason = "lease_held_noop" if row["lease_active"] else "lease_expired_noop"
|
||||
elif job["attempt"] != row["attempt"] + 1:
|
||||
reason = "stale_attempt_noop" # reordered/old message of an earlier attempt
|
||||
elif not row["due"]:
|
||||
reason = "early_noop"
|
||||
elif row["a_version"] is not None and row["a_version"] > row["pipeline_version"]:
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET status = 'superseded', updated_at = clock_timestamp() WHERE job_id = $1", row["job_id"])
|
||||
reason = "superseded_before_start"
|
||||
if reason:
|
||||
await jobs.event(conn, job["job_id"], job["attachment_id"] if row is None else row["attachment_id"],
|
||||
reason, self.id, job["attempt"], "redelivered=%s" % redelivered)
|
||||
return None, reason
|
||||
claimed = await conn.fetchrow(
|
||||
"""
|
||||
UPDATE jobs SET status = 'processing', attempt = attempt + 1, lease_owner = $2,
|
||||
lease_until = clock_timestamp() + make_interval(secs => $3), updated_at = clock_timestamp()
|
||||
WHERE job_id = $1
|
||||
RETURNING *
|
||||
""",
|
||||
row["job_id"], self.id, config.LEASE_SECONDS,
|
||||
)
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'processing', updated_at = clock_timestamp() WHERE id = $1 AND status = 'queued'",
|
||||
row["attachment_id"],
|
||||
)
|
||||
await jobs.event(conn, row["job_id"], row["attachment_id"], "claimed", self.id, claimed["attempt"],
|
||||
"redelivered=%s" % redelivered)
|
||||
info = dict(row)
|
||||
info.update(dict(claimed))
|
||||
return info, "claimed"
|
||||
|
||||
async def heartbeat(self, job: dict, lost: asyncio.Event) -> None:
|
||||
"""Renew the lease while the attempt is alive; a dead worker stops renewing and the lease expires."""
|
||||
while True:
|
||||
await asyncio.sleep(config.HEARTBEAT_SECONDS)
|
||||
try:
|
||||
async with self.pool.acquire() as conn:
|
||||
renewed = await conn.fetchval(
|
||||
"""
|
||||
UPDATE jobs SET lease_until = clock_timestamp() + make_interval(secs => $4)
|
||||
WHERE job_id = $1 AND status = 'processing' AND lease_owner = $2 AND attempt = $3
|
||||
RETURNING 1
|
||||
""",
|
||||
job["job_id"], self.id, job["attempt"], config.LEASE_SECONDS,
|
||||
)
|
||||
except DB_ERRORS:
|
||||
continue
|
||||
if not renewed:
|
||||
lost.set()
|
||||
return
|
||||
|
||||
# ------------------------------------------------------------------ process one delivery
|
||||
async def process(self, job: dict, redelivered: bool) -> str:
|
||||
claimed, reason = await self.claim(job, redelivered)
|
||||
if claimed is None:
|
||||
return reason
|
||||
await faults.hit(self.pool, "worker.after_claim", claimed["attachment_id"], self.id)
|
||||
lost = asyncio.Event()
|
||||
hb = asyncio.create_task(self.heartbeat(claimed, lost))
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="job-") as tmp:
|
||||
try:
|
||||
variants = await self.execute(claimed, tmp)
|
||||
await faults.hit(self.pool, "worker.after_s3_before_commit", claimed["attachment_id"], self.id)
|
||||
except ImageRejected as exc:
|
||||
return await self.finish_failure(claimed, exc.code, permanent=True)
|
||||
except (TransientFailure, S3Unavailable) as exc:
|
||||
code = exc.code if isinstance(exc, TransientFailure) else "s3_unavailable"
|
||||
return await self.finish_failure(claimed, code, permanent=False)
|
||||
return await self.commit(claimed, variants)
|
||||
finally:
|
||||
hb.cancel()
|
||||
|
||||
async def execute(self, job: dict, tmp: str) -> list:
|
||||
"""Side effects only in S3 at deterministic keys; nothing visible to clients until commit()."""
|
||||
src = os.path.join(tmp, "source")
|
||||
republish = job["a_status"] == "ready" # newer pipeline for an already published attachment
|
||||
if not republish and job["staging_deleted_at"] is not None:
|
||||
raise ImageRejected("staging_missing")
|
||||
# Source: staging, or the already published original (newer pipeline / a concurrent version committed
|
||||
# and removed staging in between). Both hold the same bytes, verified against the DB checksum below.
|
||||
keys = [job["object_key"]] if republish else [job["staging_key"], job["object_key"]]
|
||||
size = None
|
||||
for key in keys:
|
||||
try:
|
||||
with open(src, "wb") as fh:
|
||||
size = await asyncio.to_thread(self.objects.download_sync, key, fh, config.MAX_UPLOAD_BYTES)
|
||||
break
|
||||
except S3NotFound:
|
||||
continue
|
||||
if size is None:
|
||||
raise ImageRejected("staging_missing")
|
||||
digest = hashlib.sha256()
|
||||
with open(src, "rb") as fh:
|
||||
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
if size != job["size_bytes"] or digest.hexdigest() != job["sha256"]:
|
||||
raise ImageRejected("staging_corrupt") # trusted metadata from the DB disagrees with the bytes
|
||||
await faults.hit(self.pool, "worker.before_transform", job["attachment_id"], self.id)
|
||||
out = os.path.join(tmp, "out")
|
||||
os.mkdir(out)
|
||||
started = time.monotonic()
|
||||
variants = await asyncio.to_thread(run_isolated, src, job["content_type"], out, job["pipeline_version"],
|
||||
config.JOB_TIMEOUT_SECONDS, config.WORKER_MEMORY_LIMIT_MB)
|
||||
logger.info("transformed %s v%d in %.0f ms", job["attachment_id"], job["pipeline_version"],
|
||||
1000 * (time.monotonic() - started))
|
||||
if not republish:
|
||||
with open(src, "rb") as fh:
|
||||
await asyncio.to_thread(self.objects.put_sync, original_key(job["attachment_id"]), fh, size,
|
||||
job["content_type"], job["sha256"])
|
||||
for v in variants:
|
||||
v["object_key"] = variant_key(job["attachment_id"], job["pipeline_version"], v["name"], v["content_type"])
|
||||
with open(v["path"], "rb") as fh:
|
||||
await asyncio.to_thread(self.objects.put_sync, v["object_key"], fh, v["size_bytes"],
|
||||
v["content_type"], v["sha256"])
|
||||
return variants
|
||||
|
||||
async def fenced(self, conn: asyncpg.Connection, job: dict):
|
||||
row = await conn.fetchrow("SELECT * FROM jobs WHERE job_id = $1 FOR UPDATE", job["job_id"])
|
||||
if row is None or row["status"] != "processing" or row["lease_owner"] != self.id or row["attempt"] != job["attempt"]:
|
||||
await jobs.event(conn, job["job_id"], job["attachment_id"], "fenced_out", self.id, job["attempt"],
|
||||
"lease lost; result of this attempt discarded")
|
||||
return None
|
||||
return row
|
||||
|
||||
async def commit(self, job: dict, variants: list) -> str:
|
||||
async with self.pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
row = await self.fenced(conn, job)
|
||||
if row is None:
|
||||
return "fenced_out"
|
||||
current = await conn.fetchval("SELECT pipeline_version FROM attachments WHERE id = $1 FOR UPDATE",
|
||||
job["attachment_id"])
|
||||
if current is not None and current > job["pipeline_version"]:
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'superseded', lease_owner = NULL, lease_until = NULL,
|
||||
updated_at = clock_timestamp() WHERE job_id = $1
|
||||
""", job["job_id"])
|
||||
await jobs.event(conn, job["job_id"], job["attachment_id"], "superseded", self.id, job["attempt"],
|
||||
"published v%d is newer than v%d" % (current, job["pipeline_version"]))
|
||||
return "superseded"
|
||||
for v in variants:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type,
|
||||
size_bytes, width, height, sha256, job_id, attempt)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING
|
||||
""",
|
||||
job["attachment_id"], job["pipeline_version"], v["name"], v["object_key"], v["content_type"],
|
||||
v["size_bytes"], v["width"], v["height"], v["sha256"], job["job_id"], job["attempt"],
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE attachments SET status = 'ready', pipeline_version = $2, error_code = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE id = $1
|
||||
""",
|
||||
job["attachment_id"], job["pipeline_version"],
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'done', lease_owner = NULL, lease_until = NULL, error_code = NULL,
|
||||
last_error = NULL, updated_at = clock_timestamp()
|
||||
WHERE job_id = $1
|
||||
""", job["job_id"])
|
||||
await jobs.event(conn, job["job_id"], job["attachment_id"], "ready", self.id, job["attempt"],
|
||||
"v%d: %s" % (job["pipeline_version"], ",".join(v["name"] for v in variants)))
|
||||
# Staging is removed only after the result is committed; a failure here is repaired by the sweeper.
|
||||
if job["a_status"] != "ready" and job["staging_deleted_at"] is None:
|
||||
try:
|
||||
await asyncio.to_thread(self.objects.delete_sync, job["staging_key"])
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET staging_deleted_at = clock_timestamp() WHERE id = $1 AND status = 'ready'",
|
||||
job["attachment_id"])
|
||||
except (S3Unavailable, *DB_ERRORS):
|
||||
logger.warning("staging cleanup deferred to sweeper for %s", job["attachment_id"])
|
||||
return "ready"
|
||||
|
||||
async def finish_failure(self, job: dict, code: str, permanent: bool) -> str:
|
||||
async with self.pool.acquire() as conn, conn.transaction():
|
||||
row = await self.fenced(conn, job)
|
||||
if row is None:
|
||||
return "fenced_out"
|
||||
if permanent:
|
||||
await jobs.fail(conn, row, code, code, self.id)
|
||||
return "failed"
|
||||
return await jobs.retry_or_fail(conn, row, code, self.id)
|
||||
|
||||
# ------------------------------------------------------------------ reaper: expired leases, lost messages
|
||||
async def reap_once(self) -> None:
|
||||
async with self.pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
expired = await conn.fetch(
|
||||
"""
|
||||
SELECT * FROM jobs WHERE status = 'processing' AND lease_until < clock_timestamp()
|
||||
ORDER BY lease_until LIMIT 50 FOR UPDATE SKIP LOCKED
|
||||
""")
|
||||
for row in expired:
|
||||
await jobs.event(conn, row["job_id"], row["attachment_id"], "lease_expired", self.id, row["attempt"],
|
||||
"owner %s stopped renewing" % row["lease_owner"])
|
||||
await jobs.retry_or_fail(conn, row, "lease_expired", self.id)
|
||||
async with conn.transaction():
|
||||
# Safety net for a message lost after the outbox marked it published (e.g. broker volume lost).
|
||||
stuck = await conn.fetch(
|
||||
"""
|
||||
SELECT j.* FROM jobs j
|
||||
WHERE j.status = 'queued' AND j.next_attempt_at < clock_timestamp() - make_interval(secs => $1)
|
||||
AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.job_id
|
||||
AND (o.published_at IS NULL OR o.published_at > clock_timestamp() - make_interval(secs => $1)))
|
||||
LIMIT 50 FOR UPDATE OF j SKIP LOCKED
|
||||
""", config.STUCK_QUEUED_SECONDS)
|
||||
for row in stuck:
|
||||
await jobs.enqueue(conn, row["job_id"], row["attachment_id"], row["pipeline_version"], row["attempt"] + 1)
|
||||
await jobs.event(conn, row["job_id"], row["attachment_id"], "republished_stuck", self.id, row["attempt"])
|
||||
with open(HEARTBEAT_FILE, "w", encoding="ascii") as fh:
|
||||
fh.write(str(time.time()))
|
||||
|
||||
async def reaper(self) -> None:
|
||||
while not self.stopping.is_set():
|
||||
try:
|
||||
await self.reap_once()
|
||||
except DB_ERRORS as exc:
|
||||
logger.warning("reaper: db unavailable (%s)", type(exc).__name__)
|
||||
except Exception:
|
||||
logger.exception("reaper failed")
|
||||
try:
|
||||
await asyncio.wait_for(self.stopping.wait(), config.REAPER_INTERVAL_SECONDS)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------ lifecycle
|
||||
async def run(self) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
loop.add_signal_handler(sig, self.stopping.set)
|
||||
for attempt in range(1, 61):
|
||||
try:
|
||||
self.pool = await asyncpg.create_pool(config.DATABASE_URL, min_size=1,
|
||||
max_size=config.WORKER_CONCURRENCY + 4,
|
||||
timeout=config.DB_CONNECT_TIMEOUT,
|
||||
command_timeout=config.DB_COMMAND_TIMEOUT)
|
||||
await self.broker.connect(prefetch=config.WORKER_CONCURRENCY)
|
||||
break
|
||||
except Exception as exc:
|
||||
logger.warning("dependencies not ready (attempt %d): %s", attempt, type(exc).__name__)
|
||||
await asyncio.sleep(1)
|
||||
else:
|
||||
raise SystemExit("cannot connect to PostgreSQL/RabbitMQ")
|
||||
logger.info("%s consuming %s, prefetch=%d, pipeline=%d, max_attempts=%d, lease=%.0fs, fault_injection=%s",
|
||||
self.id, config.BROKER_QUEUE, config.WORKER_CONCURRENCY, config.PIPELINE_VERSION,
|
||||
config.JOB_MAX_ATTEMPTS, config.LEASE_SECONDS, config.FAULT_INJECTION)
|
||||
reaper = asyncio.create_task(self.reaper())
|
||||
tag = await self.broker.queue.consume(self.on_message, no_ack=False)
|
||||
await self.stopping.wait()
|
||||
logger.info("stopping: no new deliveries, waiting for %d in-flight jobs", len(self.inflight))
|
||||
await self.broker.queue.cancel(tag)
|
||||
if self.inflight:
|
||||
await asyncio.wait(list(self.inflight), timeout=25)
|
||||
reaper.cancel()
|
||||
await self.broker.close() # unacked deliveries (if any) return to the queue
|
||||
await self.pool.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not config.DATABASE_URL:
|
||||
raise SystemExit("DATABASE_URL(_FILE) is required")
|
||||
asyncio.run(Worker().run())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user