forked from mtusi2026/mtusi2026lab6
выполение на 5
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Messenger API application package."""
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import threading
|
||||
from functools import partial
|
||||
from http.server import ThreadingHTTPServer
|
||||
|
||||
from .config import APP_HOST, APP_PORT
|
||||
from .handlers import MessengerHandler
|
||||
from .store import Store
|
||||
from .telemetry import initialize, start_runtime_metrics
|
||||
|
||||
LOGGER = logging.getLogger("messenger")
|
||||
|
||||
|
||||
def run_server():
|
||||
store = Store()
|
||||
store.open()
|
||||
start_runtime_metrics(store)
|
||||
try:
|
||||
handler = partial(MessengerHandler, store=store)
|
||||
server = ThreadingHTTPServer((APP_HOST, APP_PORT), handler)
|
||||
|
||||
def handle_shutdown(signum, frame):
|
||||
LOGGER.info("received signal %s, shutting down gracefully", signum)
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGTERM, handle_shutdown)
|
||||
signal.signal(signal.SIGINT, handle_shutdown)
|
||||
LOGGER.info("listening on %s:%s", APP_HOST, APP_PORT)
|
||||
try:
|
||||
server.serve_forever()
|
||||
finally:
|
||||
server.server_close()
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def main():
|
||||
initialize(os.getenv("OTEL_SERVICE_NAME", "messenger-api"))
|
||||
run_server()
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
LOGGER = logging.getLogger("messenger.s3.bootstrap")
|
||||
|
||||
|
||||
def secret(name: str) -> str:
|
||||
direct = os.getenv(name)
|
||||
if direct:
|
||||
return direct
|
||||
file_path = os.getenv(name + "_FILE")
|
||||
if file_path:
|
||||
return Path(file_path).read_text(encoding="utf-8").strip()
|
||||
raise RuntimeError(f"Set {name} or {name}_FILE")
|
||||
|
||||
|
||||
def main():
|
||||
client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.getenv("S3_ENDPOINT", "http://s3:8333"),
|
||||
region_name="us-east-1",
|
||||
aws_access_key_id=secret("S3_ADMIN_ACCESS_KEY_ID"),
|
||||
aws_secret_access_key=secret("S3_ADMIN_SECRET_ACCESS_KEY"),
|
||||
config=Config(connect_timeout=2, read_timeout=5, retries={"max_attempts": 3}),
|
||||
)
|
||||
bucket = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
try:
|
||||
client.head_bucket(Bucket=bucket)
|
||||
except ClientError as exc:
|
||||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
if status != 404:
|
||||
raise
|
||||
client.create_bucket(Bucket=bucket)
|
||||
client.put_bucket_acl(Bucket=bucket, ACL="private")
|
||||
LOGGER.info("private S3 bucket bootstrap completed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level="INFO", format="%(levelname)s %(message)s")
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
APP_HOST = os.getenv("APP_HOST", "0.0.0.0")
|
||||
APP_PORT = int(os.getenv("APP_PORT", "8080"))
|
||||
INSTANCE_ID = os.getenv("INSTANCE_ID", socket.gethostname() or uuid.uuid4().hex[:12])
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
IDEMPOTENCY_TTL_SECONDS = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
DB_STATEMENT_TIMEOUT_MS = int(os.getenv("DB_STATEMENT_TIMEOUT_MS", "5000"))
|
||||
DB_LOCK_TIMEOUT_MS = int(os.getenv("DB_LOCK_TIMEOUT_MS", "2000"))
|
||||
DB_POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "16"))
|
||||
DB_POOL_TIMEOUT_SECONDS = float(os.getenv("DB_POOL_TIMEOUT_SECONDS", "5"))
|
||||
MAX_INFLIGHT_REQUESTS = int(os.getenv("MAX_INFLIGHT_REQUESTS", "128"))
|
||||
MAX_REQUEST_BODY_BYTES = int(os.getenv("MAX_REQUEST_BODY_BYTES", "1048576"))
|
||||
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||
MAX_CONCURRENT_UPLOADS = int(os.getenv("MAX_CONCURRENT_UPLOADS", "10"))
|
||||
UPLOAD_TIMEOUT_SECONDS = int(os.getenv("UPLOAD_TIMEOUT_SECONDS", "60"))
|
||||
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
|
||||
S3_REGION = os.getenv("S3_REGION", "us-east-1")
|
||||
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
|
||||
|
||||
def secret_value(name: str, default: str = "") -> str:
|
||||
value = os.getenv(name)
|
||||
if value:
|
||||
return value
|
||||
file_path = os.getenv(name + "_FILE")
|
||||
if file_path:
|
||||
return Path(file_path).read_text(encoding="utf-8").strip()
|
||||
if default:
|
||||
return default
|
||||
raise RuntimeError(f"Set {name} or {name}_FILE")
|
||||
|
||||
|
||||
S3_ACCESS_KEY_ID = secret_value("S3_ACCESS_KEY_ID")
|
||||
S3_SECRET_ACCESS_KEY = secret_value("S3_SECRET_ACCESS_KEY")
|
||||
USER_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
if SESSION_TTL_SECONDS < 1:
|
||||
raise RuntimeError("SESSION_TTL_SECONDS must be positive")
|
||||
if IDEMPOTENCY_TTL_SECONDS < 86400:
|
||||
raise RuntimeError("IDEMPOTENCY_TTL_SECONDS must be at least 86400")
|
||||
if DB_STATEMENT_TIMEOUT_MS < 1 or DB_LOCK_TIMEOUT_MS < 1:
|
||||
raise RuntimeError("Database timeouts must be positive")
|
||||
if DB_POOL_MAX_SIZE < 1 or DB_POOL_TIMEOUT_SECONDS <= 0:
|
||||
raise RuntimeError("Database pool settings must be positive")
|
||||
if MAX_INFLIGHT_REQUESTS < 1 or MAX_REQUEST_BODY_BYTES < 1:
|
||||
raise RuntimeError("HTTP limits must be positive")
|
||||
if MAX_UPLOAD_BYTES < 1 or MAX_UPLOAD_BYTES > 10 * 1024 * 1024:
|
||||
raise RuntimeError("MAX_UPLOAD_BYTES must be between 1 and 10 MiB")
|
||||
if MAX_IMAGE_PIXELS < 1 or MAX_IMAGE_PIXELS > 40_000_000:
|
||||
raise RuntimeError("MAX_IMAGE_PIXELS must be between 1 and 40 million")
|
||||
if MAX_CONCURRENT_UPLOADS < 1:
|
||||
raise RuntimeError("MAX_CONCURRENT_UPLOADS must be positive")
|
||||
if UPLOAD_TIMEOUT_SECONDS < 1:
|
||||
raise RuntimeError("UPLOAD_TIMEOUT_SECONDS must be positive")
|
||||
@@ -0,0 +1,26 @@
|
||||
from typing import Dict, Optional
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, headers: Optional[Dict[str, str]] = None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
class CacheUnavailableError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class IdempotencyConflictError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotReadyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ObjectMissingError(Exception):
|
||||
pass
|
||||
+633
@@ -0,0 +1,633 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import tempfile
|
||||
import uuid
|
||||
import warnings
|
||||
import zlib
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from typing import Any, BinaryIO, Dict, List, Optional, Tuple
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
import unicodedata
|
||||
|
||||
import psycopg
|
||||
from opentelemetry import propagate
|
||||
from opentelemetry.instrumentation.utils import suppress_instrumentation
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from .config import (
|
||||
IDEMPOTENCY_KEY_RE,
|
||||
INSTANCE_ID,
|
||||
MAX_CONCURRENT_UPLOADS,
|
||||
MAX_IMAGE_PIXELS,
|
||||
MAX_INFLIGHT_REQUESTS,
|
||||
MAX_REQUEST_BODY_BYTES,
|
||||
MAX_UPLOAD_BYTES,
|
||||
UPLOAD_TIMEOUT_SECONDS,
|
||||
USER_RE,
|
||||
)
|
||||
from .errors import (
|
||||
ApiError,
|
||||
AttachmentNotReadyError,
|
||||
CacheUnavailableError,
|
||||
IdempotencyConflictError,
|
||||
ObjectMissingError,
|
||||
)
|
||||
from .security import hash_password, isoformat, valid_uuid
|
||||
from .store import Store
|
||||
from .telemetry import REQUEST_ID, record_http_request, tracer
|
||||
|
||||
LOGGER = logging.getLogger("messenger.http")
|
||||
|
||||
|
||||
class RequestGuard:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.inflight = 0
|
||||
|
||||
def acquire(self):
|
||||
with self.lock:
|
||||
if self.inflight >= MAX_INFLIGHT_REQUESTS:
|
||||
raise ApiError(503, "unavailable", "Server is busy")
|
||||
self.inflight += 1
|
||||
|
||||
def release(self):
|
||||
with self.lock:
|
||||
self.inflight = max(0, self.inflight - 1)
|
||||
|
||||
|
||||
REQUEST_GUARD = RequestGuard()
|
||||
UPLOAD_GUARD = threading.BoundedSemaphore(MAX_CONCURRENT_UPLOADS)
|
||||
IMAGE_DECODE_GUARD = threading.BoundedSemaphore(1)
|
||||
|
||||
|
||||
class MessengerHandler(BaseHTTPRequestHandler):
|
||||
def __init__(self, request, client_address, server, store: Store):
|
||||
self.store = store
|
||||
super().__init__(request, client_address, server)
|
||||
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(15)
|
||||
|
||||
def log_message(self, format: str, *args):
|
||||
return
|
||||
|
||||
def do_GET(self):
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_POST(self):
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_DELETE(self):
|
||||
self._dispatch("DELETE")
|
||||
|
||||
def _dispatch(self, method: str):
|
||||
path = urlsplit(self.path).path
|
||||
route = self._route_template(path)
|
||||
request_id = self.headers.get("X-Request-Id") or str(uuid.uuid4())
|
||||
parent_context = propagate.extract({key.lower(): value for key, value in self.headers.items()})
|
||||
started = time.perf_counter()
|
||||
token = REQUEST_ID.set(request_id)
|
||||
self._response_status = 500
|
||||
if route.startswith("/health/"):
|
||||
try:
|
||||
self._dispatch_request(method, request_id)
|
||||
finally:
|
||||
record_http_request(method, route, self._response_status, time.perf_counter() - started)
|
||||
REQUEST_ID.reset(token)
|
||||
return
|
||||
with tracer().start_as_current_span(
|
||||
f"{method} {route}",
|
||||
context=parent_context,
|
||||
kind=SpanKind.SERVER,
|
||||
attributes={
|
||||
"http.request.method": method,
|
||||
"http.route": route,
|
||||
"http.request_id": request_id,
|
||||
},
|
||||
) as span:
|
||||
try:
|
||||
self._dispatch_request(method, request_id)
|
||||
finally:
|
||||
duration = time.perf_counter() - started
|
||||
span.set_attribute("http.response.status_code", self._response_status)
|
||||
if self._response_status >= 500:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
record_http_request(method, route, self._response_status, duration)
|
||||
REQUEST_ID.reset(token)
|
||||
|
||||
@staticmethod
|
||||
def _route_template(path: str) -> str:
|
||||
if path in ("/health/live", "/health/ready", "/api/v1/users", "/api/v1/auth/sessions",
|
||||
"/api/v1/auth/sessions/current", "/api/v1/users/me", "/api/v1/chats"):
|
||||
return path
|
||||
if path.startswith("/api/v1/chats/") and path.endswith("/attachments"):
|
||||
return "/api/v1/chats/{chat_id}/attachments"
|
||||
if path.startswith("/api/v1/chats/") and path.endswith("/messages"):
|
||||
return "/api/v1/chats/{chat_id}/messages"
|
||||
if path.startswith("/api/v1/chats/"):
|
||||
return "/api/v1/chats/{chat_id}"
|
||||
if path.startswith("/api/v1/attachments/") and path.endswith("/content"):
|
||||
return "/api/v1/attachments/{attachment_id}/content"
|
||||
if path.startswith("/api/v1/attachments/"):
|
||||
return "/api/v1/attachments/{attachment_id}"
|
||||
return "unmatched"
|
||||
|
||||
def _dispatch_request(self, method: str, request_id: str):
|
||||
acquired = False
|
||||
try:
|
||||
REQUEST_GUARD.acquire()
|
||||
acquired = True
|
||||
parsed = urlsplit(self.path)
|
||||
path = parsed.path
|
||||
query = parse_qs(parsed.query, keep_blank_values=True)
|
||||
if path == "/health/live" and method == "GET":
|
||||
self._send_json(200, {"status": "ok"}, request_id)
|
||||
elif path == "/health/ready" and method == "GET":
|
||||
try:
|
||||
with suppress_instrumentation():
|
||||
self.store.ready()
|
||||
except (psycopg.Error, PoolTimeout, OSError, BotoCoreError, ClientError):
|
||||
raise ApiError(503, "unavailable", "A required storage service is unavailable")
|
||||
self._send_json(200, {"status": "ok"}, request_id)
|
||||
elif path == "/api/v1/users" and method == "POST":
|
||||
self._handle_register(request_id)
|
||||
elif path == "/api/v1/auth/sessions" and method == "POST":
|
||||
self._handle_create_session(request_id)
|
||||
elif path == "/api/v1/auth/sessions/current" and method == "DELETE":
|
||||
self._handle_revoke_session(request_id)
|
||||
elif path == "/api/v1/users/me" and method == "GET":
|
||||
self._send_json(200, self._get_actor(request_id), request_id)
|
||||
elif path == "/api/v1/chats" and method == "POST":
|
||||
self._handle_create_chat(request_id)
|
||||
elif path == "/api/v1/chats" and method == "GET":
|
||||
self._handle_list_chats(query, request_id)
|
||||
elif path.startswith("/api/v1/chats/") and path.endswith("/attachments") and method == "POST":
|
||||
chat_id = path.rsplit("/", 2)[1]
|
||||
self._handle_upload_attachment(chat_id, query, request_id)
|
||||
elif path.startswith("/api/v1/attachments/") and method == "GET":
|
||||
attachment_path = path.removeprefix("/api/v1/attachments/")
|
||||
if attachment_path.endswith("/content"):
|
||||
attachment_id = attachment_path.removesuffix("/content")
|
||||
self._handle_download_attachment(attachment_id, query, request_id)
|
||||
else:
|
||||
self._handle_get_attachment(attachment_path, request_id)
|
||||
elif path.startswith("/api/v1/chats/") and path.endswith("/messages") and method in ("GET", "POST"):
|
||||
chat_id = path.rsplit("/", 2)[1]
|
||||
if method == "POST":
|
||||
self._handle_create_message(chat_id, request_id)
|
||||
else:
|
||||
self._handle_list_messages(chat_id, query, request_id)
|
||||
elif path.startswith("/api/v1/chats/") and method == "GET":
|
||||
self._handle_get_chat(path.rsplit("/", 1)[1], request_id)
|
||||
else:
|
||||
raise ApiError(404, "not_found", "Object not found")
|
||||
except ApiError as exc:
|
||||
self._send_error(exc.status, exc.code, exc.message, request_id, exc.headers)
|
||||
except CacheUnavailableError:
|
||||
self._send_error(503, "unavailable", "Session cache is unavailable", request_id)
|
||||
except IdempotencyConflictError:
|
||||
self._send_error(409, "conflict", "Idempotency-Key was already used with another request", request_id)
|
||||
except AttachmentNotReadyError:
|
||||
self._send_error(409, "conflict", "Attachment is not ready", request_id)
|
||||
except ObjectMissingError:
|
||||
LOGGER.error("attachment object missing for request %s", request_id)
|
||||
self._send_error(503, "unavailable", "Attachment content is temporarily unavailable", request_id)
|
||||
except (BotoCoreError, ClientError):
|
||||
LOGGER.warning("object storage unavailable for request %s", request_id)
|
||||
self._send_error(503, "unavailable", "Object storage is unavailable", request_id)
|
||||
except (PoolTimeout, psycopg.OperationalError, psycopg.InterfaceError):
|
||||
self._send_error(503, "unavailable", "Database is unavailable", request_id)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
self._send_error(409, "conflict", "Username already exists", request_id)
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
self._send_error(400, "invalid_request", "Unknown member", request_id)
|
||||
except (BrokenPipeError, ConnectionResetError, TimeoutError):
|
||||
self._set_response_status(499)
|
||||
self.close_connection = True
|
||||
LOGGER.info("client disconnected before response for request %s", request_id)
|
||||
except Exception as exc:
|
||||
LOGGER.error("request %s failed with %s", request_id, type(exc).__name__)
|
||||
self._send_error(500, "internal_error", "Internal server error", request_id)
|
||||
finally:
|
||||
if acquired:
|
||||
REQUEST_GUARD.release()
|
||||
|
||||
@staticmethod
|
||||
def _trace_context():
|
||||
carrier = {}
|
||||
propagate.inject(carrier)
|
||||
return {"traceparent": carrier.get("traceparent"), "tracestate": carrier.get("tracestate")}
|
||||
|
||||
def _set_response_status(self, status: int) -> None:
|
||||
self._response_status = status
|
||||
|
||||
def _read_json(self, request_id: str) -> Any:
|
||||
if self.headers.get_content_type() != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Content-Type must be application/json")
|
||||
length = self.headers.get("Content-Length")
|
||||
if length is None:
|
||||
raise ApiError(400, "invalid_request", "Missing Content-Length")
|
||||
try:
|
||||
size = int(length)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid Content-Length")
|
||||
if size < 0:
|
||||
raise ApiError(400, "invalid_request", "Invalid Content-Length")
|
||||
if size > MAX_REQUEST_BODY_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Request body too large")
|
||||
raw = self.rfile.read(size)
|
||||
if not raw:
|
||||
raise ApiError(400, "invalid_request", "Empty body")
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ApiError(400, "invalid_request", "Malformed JSON")
|
||||
|
||||
def _get_actor(self, request_id: str) -> Dict[str, Any]:
|
||||
header = self.headers.get("Authorization", "")
|
||||
scheme, separator, token = header.partition(" ")
|
||||
if scheme.lower() != "bearer" or not separator or not token or " " in token:
|
||||
raise ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Authentication required",
|
||||
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
user = self.store.session_user(token)
|
||||
if user is None:
|
||||
raise ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Authentication required",
|
||||
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
return user
|
||||
|
||||
def _handle_register(self, request_id: str):
|
||||
body = self._read_json(request_id)
|
||||
if not isinstance(body, dict) or set(body) != {"username", "display_name", "password"}:
|
||||
raise ApiError(400, "invalid_request", "Expected username, display_name and password")
|
||||
username = body["username"]
|
||||
display_name = body["display_name"]
|
||||
password = body["password"]
|
||||
if not isinstance(username, str) or not USER_RE.fullmatch(username):
|
||||
raise ApiError(400, "invalid_request", "Invalid username")
|
||||
if not isinstance(display_name, str) or not display_name.strip() or len(display_name) > 100:
|
||||
raise ApiError(400, "invalid_request", "Invalid display_name")
|
||||
if not isinstance(password, str) or not (12 <= len(password) <= 128):
|
||||
raise ApiError(400, "invalid_request", "Invalid password")
|
||||
user = self.store.create_user(username, display_name, hash_password(password))
|
||||
self._send_json(201, user, request_id)
|
||||
|
||||
def _basic_credentials(self, request_id: str) -> Tuple[str, str]:
|
||||
value = self.headers.get("Authorization", "")
|
||||
scheme, separator, encoded = value.partition(" ")
|
||||
challenge = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
if scheme.lower() != "basic" or not separator or not encoded:
|
||||
raise ApiError(401, "unauthorized", "Invalid credentials", challenge)
|
||||
try:
|
||||
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except (ValueError, UnicodeError):
|
||||
raise ApiError(401, "unauthorized", "Invalid credentials", challenge)
|
||||
return username, password
|
||||
|
||||
def _handle_create_session(self, request_id: str):
|
||||
username, password = self._basic_credentials(request_id)
|
||||
user = self.store.authenticate(username, password)
|
||||
if user is None:
|
||||
raise ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Invalid credentials",
|
||||
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||
)
|
||||
token, expires_at = self.store.create_session(user["id"])
|
||||
self._send_json(
|
||||
201,
|
||||
{"token": token, "token_type": "Bearer", "expires_at": isoformat(expires_at), "user": user},
|
||||
request_id,
|
||||
)
|
||||
|
||||
def _handle_revoke_session(self, request_id: str):
|
||||
self._get_actor(request_id)
|
||||
token = self.headers["Authorization"].partition(" ")[2]
|
||||
if not self.store.revoke_session(token):
|
||||
raise ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Authentication required",
|
||||
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
self._set_response_status(204)
|
||||
self.send_response(204)
|
||||
self.send_header("X-Request-Id", request_id)
|
||||
self.send_header("X-Instance-Id", INSTANCE_ID)
|
||||
self.end_headers()
|
||||
|
||||
def _handle_create_chat(self, request_id: str):
|
||||
actor = self._get_actor(request_id)
|
||||
body = self._read_json(request_id)
|
||||
if not isinstance(body, dict) or set(body) != {"title", "member_ids"}:
|
||||
raise ApiError(400, "invalid_request", "Expected title and member_ids")
|
||||
title, member_ids = body["title"], body["member_ids"]
|
||||
if not isinstance(title, str) or not title.strip() or len(title) > 100:
|
||||
raise ApiError(400, "invalid_request", "Invalid title")
|
||||
if (
|
||||
not isinstance(member_ids, list)
|
||||
or not 1 <= len(member_ids) <= 100
|
||||
or any(not isinstance(item, str) or not valid_uuid(item) for item in member_ids)
|
||||
or len(member_ids) != len(set(member_ids))
|
||||
or actor["id"] not in member_ids
|
||||
):
|
||||
raise ApiError(400, "invalid_request", "Invalid member_ids")
|
||||
chat = self.store.create_chat(title, member_ids, actor["id"])
|
||||
self._send_json(201, chat, request_id)
|
||||
|
||||
def _handle_list_chats(self, query: Dict[str, List[str]], request_id: str):
|
||||
actor = self._get_actor(request_id)
|
||||
try:
|
||||
limit = int(query.get("limit", ["50"])[0])
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid limit")
|
||||
if not 1 <= limit <= 100:
|
||||
raise ApiError(400, "invalid_request", "Invalid limit")
|
||||
cursor = query.get("cursor", [None])[0]
|
||||
try:
|
||||
chats, next_cursor = self.store.list_chats(actor["id"], limit, cursor)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor")
|
||||
self._send_json(200, {"items": chats, "next_cursor": next_cursor}, request_id)
|
||||
|
||||
def _handle_get_chat(self, chat_id: str, request_id: str):
|
||||
actor = self._get_actor(request_id)
|
||||
if not valid_uuid(chat_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid chat id")
|
||||
chat = self.store.get_chat(chat_id, actor["id"])
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
self._send_json(200, chat, request_id)
|
||||
|
||||
def _handle_create_message(self, chat_id: str, request_id: str):
|
||||
actor = self._get_actor(request_id)
|
||||
if not valid_uuid(chat_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid chat id")
|
||||
chat_id = str(uuid.UUID(chat_id))
|
||||
idempotency_key = self.headers.get("Idempotency-Key", "")
|
||||
if not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
|
||||
raise ApiError(400, "invalid_request", "Invalid or missing Idempotency-Key")
|
||||
body = self._read_json(request_id)
|
||||
if not isinstance(body, dict) or set(body).difference({"text", "attachment_ids"}) or "text" not in body:
|
||||
raise ApiError(400, "invalid_request", "Expected text and optional attachment_ids")
|
||||
text = body["text"]
|
||||
attachment_ids = body.get("attachment_ids", [])
|
||||
if (
|
||||
not isinstance(text, str)
|
||||
or len(text) > 4000
|
||||
or not isinstance(attachment_ids, list)
|
||||
or len(attachment_ids) > 10
|
||||
or any(not isinstance(item, str) or not valid_uuid(item) for item in attachment_ids)
|
||||
or len(attachment_ids) != len(set(attachment_ids))
|
||||
or (not text.strip() and not attachment_ids)
|
||||
):
|
||||
raise ApiError(400, "invalid_request", "Invalid message text")
|
||||
attachment_ids = [str(uuid.UUID(item)) for item in attachment_ids]
|
||||
canonical_body = json.dumps(
|
||||
{"text": text, "attachment_ids": attachment_ids},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
message = self.store.create_idempotent_message(
|
||||
chat_id,
|
||||
actor["id"],
|
||||
text,
|
||||
attachment_ids,
|
||||
idempotency_key,
|
||||
canonical_body,
|
||||
)
|
||||
if message is None:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
self._send_json(201, message, request_id)
|
||||
|
||||
def _read_image(self, request_id: str, declared_type: str) -> Tuple[BinaryIO, str, int, str]:
|
||||
if declared_type not in ("image/png", "image/jpeg"):
|
||||
raise ApiError(415, "unsupported_media_type", "Only PNG and JPEG are supported")
|
||||
length = self.headers.get("Content-Length")
|
||||
if length is None or self.headers.get("Transfer-Encoding"):
|
||||
raise ApiError(400, "invalid_request", "A bounded Content-Length is required")
|
||||
try:
|
||||
size = int(length)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid Content-Length")
|
||||
if size <= 0:
|
||||
raise ApiError(415, "unsupported_media_type", "Image is empty")
|
||||
if size > MAX_UPLOAD_BYTES:
|
||||
self.close_connection = True
|
||||
remaining = min(size, MAX_UPLOAD_BYTES + 1)
|
||||
deadline = time.monotonic() + UPLOAD_TIMEOUT_SECONDS
|
||||
while remaining:
|
||||
remaining_time = deadline - time.monotonic()
|
||||
if remaining_time <= 0:
|
||||
break
|
||||
self.connection.settimeout(min(15, remaining_time))
|
||||
try:
|
||||
chunk = self.rfile.read(min(64 * 1024, remaining))
|
||||
except (TimeoutError, OSError):
|
||||
LOGGER.info("stopped bounded drain of oversized upload")
|
||||
break
|
||||
if not chunk:
|
||||
break
|
||||
remaining -= len(chunk)
|
||||
raise ApiError(413, "payload_too_large", "Image exceeds the 10 MiB limit")
|
||||
content = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b")
|
||||
digest = hashlib.sha256()
|
||||
bytes_read = 0
|
||||
deadline = time.monotonic() + UPLOAD_TIMEOUT_SECONDS
|
||||
try:
|
||||
while bytes_read < size:
|
||||
remaining_time = deadline - time.monotonic()
|
||||
if remaining_time <= 0:
|
||||
raise ApiError(408, "invalid_request", "Image upload timed out")
|
||||
self.connection.settimeout(min(15, remaining_time))
|
||||
chunk = self.rfile.read(min(64 * 1024, size - bytes_read))
|
||||
if not chunk:
|
||||
raise ApiError(400, "invalid_request", "Incomplete image body")
|
||||
content.write(chunk)
|
||||
digest.update(chunk)
|
||||
bytes_read += len(chunk)
|
||||
except (TimeoutError, OSError):
|
||||
content.close()
|
||||
raise ApiError(400, "invalid_request", "Incomplete image body") from None
|
||||
|
||||
try:
|
||||
content.seek(0)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(content) as image:
|
||||
actual_type = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format or "")
|
||||
if actual_type is None or actual_type != declared_type:
|
||||
raise ApiError(415, "unsupported_media_type", "Image content does not match Content-Type")
|
||||
width, height = image.size
|
||||
if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS:
|
||||
raise ApiError(413, "payload_too_large", "Image exceeds the 40 million pixel limit")
|
||||
image.verify()
|
||||
content.seek(0)
|
||||
with IMAGE_DECODE_GUARD:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(content) as image:
|
||||
image.load()
|
||||
content.seek(0)
|
||||
return content, actual_type, size, digest.hexdigest()
|
||||
except ApiError:
|
||||
content.close()
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
content.close()
|
||||
raise ApiError(413, "payload_too_large", "Image exceeds the 40 million pixel limit") from None
|
||||
except (UnidentifiedImageError, OSError, SyntaxError, ValueError, zlib.error):
|
||||
content.close()
|
||||
raise ApiError(415, "unsupported_media_type", "Image is damaged or unsupported") from None
|
||||
|
||||
@staticmethod
|
||||
def _valid_filename(filename: str) -> bool:
|
||||
return (
|
||||
1 <= len(filename) <= 255
|
||||
and not any(char in ("/", "\\", "\x00") for char in filename)
|
||||
and not any(unicodedata.category(char) == "Cc" for char in filename)
|
||||
)
|
||||
|
||||
def _handle_upload_attachment(
|
||||
self, chat_id: str, query: Dict[str, List[str]], request_id: str
|
||||
):
|
||||
actor = self._get_actor(request_id)
|
||||
if not valid_uuid(chat_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid chat id")
|
||||
chat_id = str(uuid.UUID(chat_id))
|
||||
if not self.store.can_access_chat(chat_id, actor["id"]):
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
filenames = query.get("filename", [])
|
||||
if len(filenames) != 1 or not self._valid_filename(filenames[0]):
|
||||
raise ApiError(400, "invalid_request", "Invalid filename")
|
||||
if not UPLOAD_GUARD.acquire(blocking=False):
|
||||
raise ApiError(503, "unavailable", "Upload capacity is temporarily exhausted")
|
||||
try:
|
||||
content, content_type, size, digest = self._read_image(request_id, self.headers.get_content_type())
|
||||
try:
|
||||
attachment = self.store.create_attachment(
|
||||
chat_id,
|
||||
actor["id"],
|
||||
filenames[0],
|
||||
content_type,
|
||||
content,
|
||||
size,
|
||||
digest,
|
||||
**self._trace_context(),
|
||||
)
|
||||
finally:
|
||||
content.close()
|
||||
finally:
|
||||
UPLOAD_GUARD.release()
|
||||
if attachment is None:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
self._send_json(202, attachment, request_id)
|
||||
|
||||
def _handle_get_attachment(self, attachment_id: str, request_id: str):
|
||||
actor = self._get_actor(request_id)
|
||||
if not valid_uuid(attachment_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid attachment id")
|
||||
attachment = self.store.get_attachment(str(uuid.UUID(attachment_id)), actor["id"])
|
||||
if attachment is None:
|
||||
raise ApiError(404, "not_found", "Attachment not found")
|
||||
self._send_json(200, attachment, request_id)
|
||||
|
||||
def _handle_download_attachment(
|
||||
self, attachment_id: str, query: Dict[str, List[str]], request_id: str
|
||||
):
|
||||
actor = self._get_actor(request_id)
|
||||
if not valid_uuid(attachment_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid attachment id")
|
||||
variants = query.get("variant", ["original"])
|
||||
if len(variants) != 1 or variants[0] not in ("original", "thumbnail", "crop", "optimized"):
|
||||
raise ApiError(400, "invalid_request", "Invalid attachment variant")
|
||||
variant = variants[0]
|
||||
if variant != "original" and variant not in ("thumbnail", "crop", "optimized"):
|
||||
raise ApiError(404, "not_found", "Attachment variant not found")
|
||||
result = self.store.download_attachment(str(uuid.UUID(attachment_id)), actor["id"], variant)
|
||||
if result is None:
|
||||
raise ApiError(404, "not_found", "Attachment not found")
|
||||
content_type, content = result
|
||||
self._set_response_status(200)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.send_header("X-Request-Id", request_id)
|
||||
self.send_header("X-Instance-Id", INSTANCE_ID)
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Cache-Control", "private, no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(content)
|
||||
|
||||
def _handle_list_messages(self, chat_id: str, query: Dict[str, List[str]], request_id: str):
|
||||
actor = self._get_actor(request_id)
|
||||
if not valid_uuid(chat_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid chat id")
|
||||
try:
|
||||
limit = int(query.get("limit", ["50"])[0])
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid limit")
|
||||
if not 1 <= limit <= 100:
|
||||
raise ApiError(400, "invalid_request", "Invalid limit")
|
||||
cursor = query.get("cursor", [None])[0]
|
||||
try:
|
||||
result = self.store.list_messages(chat_id, actor["id"], limit, cursor)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor")
|
||||
if result is None:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
items, next_cursor = result
|
||||
self._send_json(200, {"items": items, "next_cursor": next_cursor}, request_id)
|
||||
|
||||
def _send_json(
|
||||
self,
|
||||
status: int,
|
||||
payload: Dict[str, Any],
|
||||
request_id: str,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
):
|
||||
self._set_response_status(status)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("X-Request-Id", request_id)
|
||||
self.send_header("X-Instance-Id", INSTANCE_ID)
|
||||
if headers:
|
||||
for key, value in headers.items():
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _send_error(
|
||||
self,
|
||||
status: int,
|
||||
code: str,
|
||||
message: str,
|
||||
request_id: str,
|
||||
extra_headers: Optional[Dict[str, str]] = None,
|
||||
):
|
||||
self._send_json(
|
||||
status,
|
||||
{"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
request_id,
|
||||
extra_headers,
|
||||
)
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
|
||||
QUEUE_NAME = "attachments.process.v1"
|
||||
DEAD_QUEUE_NAME = "attachments.process.dead"
|
||||
LEASE_NETWORK_BUDGET_SECONDS = 150
|
||||
|
||||
|
||||
def broker_url() -> str:
|
||||
value = os.getenv("BROKER_URL")
|
||||
if value:
|
||||
return value
|
||||
file_path = os.getenv("BROKER_URL_FILE")
|
||||
if file_path:
|
||||
return Path(file_path).read_text(encoding="utf-8").strip()
|
||||
raise RuntimeError("Set BROKER_URL or BROKER_URL_FILE")
|
||||
|
||||
|
||||
def connect() -> pika.BlockingConnection:
|
||||
parameters = pika.URLParameters(broker_url())
|
||||
parameters.connection_attempts = 3
|
||||
parameters.retry_delay = 1
|
||||
parameters.socket_timeout = 5
|
||||
parameters.blocked_connection_timeout = 10
|
||||
return pika.BlockingConnection(parameters)
|
||||
|
||||
|
||||
def declare_queues(channel: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||
channel.queue_declare(
|
||||
queue=DEAD_QUEUE_NAME,
|
||||
durable=True,
|
||||
arguments={"x-queue-type": "quorum", "x-quorum-initial-group-size": 1},
|
||||
)
|
||||
channel.queue_declare(
|
||||
queue=QUEUE_NAME,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-queue-type": "quorum",
|
||||
"x-quorum-initial-group-size": 1,
|
||||
"x-dead-letter-exchange": "",
|
||||
"x-dead-letter-routing-key": DEAD_QUEUE_NAME,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def encode_job(job: dict) -> bytes:
|
||||
return json.dumps(job, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if __package__ in (None, ""):
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.store import Store
|
||||
else:
|
||||
from .store import Store
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level="INFO")
|
||||
store = Store()
|
||||
store.open()
|
||||
try:
|
||||
store.migrate()
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,76 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import BinaryIO, Iterator, Optional, Tuple, Union
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from .config import S3_ACCESS_KEY_ID, S3_BUCKET, S3_ENDPOINT, S3_REGION, S3_SECRET_ACCESS_KEY
|
||||
from .errors import ObjectMissingError
|
||||
|
||||
LOGGER = logging.getLogger("messenger.s3")
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
def __init__(self):
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=S3_ENDPOINT,
|
||||
region_name=S3_REGION,
|
||||
aws_access_key_id=S3_ACCESS_KEY_ID,
|
||||
aws_secret_access_key=S3_SECRET_ACCESS_KEY,
|
||||
config=Config(
|
||||
connect_timeout=2,
|
||||
read_timeout=10,
|
||||
retries={"max_attempts": 2, "mode": "standard"},
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
def put(
|
||||
self,
|
||||
key: str,
|
||||
content: Union[bytes, BinaryIO],
|
||||
content_type: str,
|
||||
size_bytes: Optional[int] = None,
|
||||
) -> None:
|
||||
if size_bytes is None:
|
||||
size_bytes = len(content)
|
||||
self.client.put_object(
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
Body=content,
|
||||
ContentLength=size_bytes,
|
||||
ContentType=content_type,
|
||||
)
|
||||
|
||||
def get(self, key: str, max_bytes: int) -> bytes:
|
||||
try:
|
||||
response = self.client.get_object(Bucket=S3_BUCKET, Key=key)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code")
|
||||
if code in ("NoSuchKey", "404", "NotFound"):
|
||||
raise ObjectMissingError from exc
|
||||
raise
|
||||
body = response["Body"]
|
||||
try:
|
||||
value = body.read(max_bytes + 1)
|
||||
finally:
|
||||
body.close()
|
||||
if len(value) > max_bytes:
|
||||
raise RuntimeError("Stored object exceeds configured safety limit")
|
||||
return value
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
self.client.delete_object(Bucket=S3_BUCKET, Key=key)
|
||||
|
||||
def ready(self) -> bool:
|
||||
self.client.head_bucket(Bucket=S3_BUCKET)
|
||||
return True
|
||||
|
||||
def objects(self) -> Iterator[Tuple[str, datetime]]:
|
||||
pages = self.client.get_paginator("list_objects_v2").paginate(Bucket=S3_BUCKET)
|
||||
for page in pages:
|
||||
for item in page.get("Contents", []):
|
||||
yield item["Key"], item["LastModified"]
|
||||
@@ -0,0 +1,4 @@
|
||||
PIPELINE_QUALITY = {
|
||||
1: {"jpeg": 85, "webp": 80},
|
||||
2: {"jpeg": 80, "webp": 75},
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from opentelemetry import propagate
|
||||
from opentelemetry.instrumentation.utils import suppress_instrumentation
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from .jobs import LEASE_NETWORK_BUDGET_SECONDS, QUEUE_NAME, connect, declare_queues, encode_job
|
||||
from .security import isoformat
|
||||
from .store import Store
|
||||
from .telemetry import initialize, tracer
|
||||
|
||||
LOGGER = logging.getLogger("messenger.publisher")
|
||||
|
||||
|
||||
def publish_pending(store: Store, channel: pika.adapters.blocking_connection.BlockingChannel) -> bool:
|
||||
with store.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
with suppress_instrumentation():
|
||||
row = store.claim_outbox(conn)
|
||||
if row is None:
|
||||
return False
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(row["job_id"]),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(row["attachment_id"]),
|
||||
"pipeline_version": row["pipeline_version"],
|
||||
"attempt": row["attempt"],
|
||||
"created_at": isoformat(row["created_at"]),
|
||||
}
|
||||
parent_context = propagate.extract(
|
||||
{
|
||||
key: row.get(key)
|
||||
for key in ("traceparent", "tracestate")
|
||||
if row.get(key) is not None
|
||||
}
|
||||
)
|
||||
with tracer().start_as_current_span(
|
||||
"attachment.publish",
|
||||
context=parent_context,
|
||||
kind=SpanKind.PRODUCER,
|
||||
attributes={"messaging.destination.name": QUEUE_NAME, "messaging.operation.type": "publish"},
|
||||
):
|
||||
carrier = {}
|
||||
propagate.inject(carrier)
|
||||
payload.update(carrier)
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=QUEUE_NAME,
|
||||
body=encode_job(payload),
|
||||
properties=pika.BasicProperties(
|
||||
content_type="application/json",
|
||||
delivery_mode=2,
|
||||
message_id=str(row["id"]),
|
||||
type="attachment.process.v1",
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE attachment_outbox SET published_at = clock_timestamp() WHERE id = %s",
|
||||
(row["id"],),
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def main() -> None:
|
||||
initialize(os.getenv("OTEL_SERVICE_NAME", "messenger-publisher"))
|
||||
store = Store()
|
||||
store.open()
|
||||
try:
|
||||
while True:
|
||||
connection = None
|
||||
try:
|
||||
connection = connect()
|
||||
channel = connection.channel()
|
||||
declare_queues(channel)
|
||||
channel.confirm_delivery()
|
||||
store.recover_expired_attachment_jobs(
|
||||
int(os.getenv("JOB_MAX_ATTEMPTS", "5")),
|
||||
int(os.getenv("JOB_TIMEOUT_SECONDS", "60")) + LEASE_NETWORK_BUDGET_SECONDS,
|
||||
)
|
||||
if not publish_pending(store, channel):
|
||||
time.sleep(1)
|
||||
except (OSError, pika.exceptions.AMQPError, psycopg.Error):
|
||||
LOGGER.exception("outbox publishing cycle failed")
|
||||
time.sleep(2)
|
||||
finally:
|
||||
if connection is not None and connection.is_open:
|
||||
connection.close()
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
if __package__ in (None, ""):
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.store import Store
|
||||
else:
|
||||
from .store import Store
|
||||
|
||||
|
||||
LOGGER = logging.getLogger("messenger.reconcile")
|
||||
|
||||
|
||||
def reconcile(
|
||||
store: Store,
|
||||
grace_seconds: int,
|
||||
apply_changes: bool,
|
||||
restore_dir: Optional[Path] = None,
|
||||
):
|
||||
started = time.monotonic()
|
||||
metadata = store.reconciliation_snapshot()
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace_seconds)
|
||||
found = set()
|
||||
orphans = []
|
||||
for key, last_modified in store.objects.objects():
|
||||
found.add(key)
|
||||
if key not in metadata and last_modified <= cutoff:
|
||||
orphans.append(key)
|
||||
|
||||
missing = [
|
||||
row for key, row in metadata.items()
|
||||
if key not in found and row.get("reconcile_type", "original") == "original"
|
||||
]
|
||||
restore_candidates = []
|
||||
if restore_dir is not None:
|
||||
root = restore_dir.resolve(strict=True)
|
||||
for row in missing:
|
||||
source = restore_dir / str(row["id"])
|
||||
try:
|
||||
resolved = source.resolve(strict=True)
|
||||
if (
|
||||
resolved.parent != root
|
||||
or not resolved.is_file()
|
||||
or resolved.stat().st_size != row["size_bytes"]
|
||||
):
|
||||
continue
|
||||
content = resolved.read_bytes()
|
||||
except OSError:
|
||||
continue
|
||||
if (
|
||||
len(content) == row["size_bytes"]
|
||||
and hashlib.sha256(content).hexdigest() == row["sha256"].strip()
|
||||
):
|
||||
restore_candidates.append((row, content))
|
||||
|
||||
restored = 0
|
||||
if apply_changes:
|
||||
for key in orphans:
|
||||
store.objects.delete(key)
|
||||
restorable_ids = set()
|
||||
for row, content in restore_candidates:
|
||||
store.objects.put(row["object_key"], content, row["content_type"])
|
||||
store.clear_missing_object(row["id"])
|
||||
restorable_ids.add(row["id"])
|
||||
restored += 1
|
||||
for row in missing:
|
||||
if row["id"] not in restorable_ids:
|
||||
store.record_missing_object(row["id"])
|
||||
for key, row in metadata.items():
|
||||
if key in found and row.get("reconcile_type", "original") == "original":
|
||||
store.clear_missing_object(row["id"])
|
||||
|
||||
unresolved_missing = len(missing) - restored
|
||||
return {
|
||||
"mode": "apply" if apply_changes else "dry-run",
|
||||
"grace_seconds": grace_seconds,
|
||||
"objects_seen": len(found),
|
||||
"metadata_seen": len({str(row["id"]) for row in metadata.values()}),
|
||||
"orphan_objects": len([key for key in found if key not in metadata]),
|
||||
"stale_orphan_candidates": len(orphans),
|
||||
"deleted_orphans": len(orphans) if apply_changes else 0,
|
||||
"missing_objects": len(missing),
|
||||
"unresolved_missing_objects": unresolved_missing,
|
||||
"restorable_missing_objects": len(restore_candidates),
|
||||
"restored_missing_objects": restored,
|
||||
"missing_incidents_recorded": len(missing) - restored if apply_changes else 0,
|
||||
"duration_ms": round((time.monotonic() - started) * 1000, 3),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Compare S3 objects with PostgreSQL attachment metadata.")
|
||||
parser.add_argument("--grace-seconds", type=int, default=3600)
|
||||
parser.add_argument("--apply", action="store_true", help="delete only stale orphan objects and record missing objects")
|
||||
parser.add_argument(
|
||||
"--restore-dir",
|
||||
type=Path,
|
||||
help="optional trusted backup directory with exact original bytes named by attachment UUID",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.grace_seconds < 60:
|
||||
parser.error("--grace-seconds must be at least 60")
|
||||
|
||||
logging.basicConfig(level="INFO", format="%(levelname)s %(message)s")
|
||||
store = Store()
|
||||
store.open()
|
||||
try:
|
||||
result = reconcile(store, args.grace_seconds, args.apply, args.restore_dir)
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
if result["unresolved_missing_objects"]:
|
||||
LOGGER.error(
|
||||
"%s database records reference missing S3 objects; metadata was retained for manual recovery",
|
||||
result["unresolved_missing_objects"],
|
||||
)
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from .store import Store
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Explicitly replay a failed attachment or start a newer pipeline version."
|
||||
)
|
||||
parser.add_argument("--attachment-id", required=True, type=uuid.UUID)
|
||||
parser.add_argument(
|
||||
"--pipeline-version",
|
||||
required=True,
|
||||
type=int,
|
||||
help="pipeline version implemented by the deployed worker",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.pipeline_version < 1:
|
||||
parser.error("--pipeline-version must be positive")
|
||||
|
||||
store = Store()
|
||||
store.open()
|
||||
try:
|
||||
result = store.replay_attachment_job(str(args.attachment_id), args.pipeline_version)
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,53 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def isoformat(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def valid_uuid(value: str) -> bool:
|
||||
try:
|
||||
uuid.UUID(value)
|
||||
return True
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
derived = hashlib.scrypt(
|
||||
password.encode("utf-8"), salt=salt, n=32768, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024
|
||||
)
|
||||
salt_text = base64.urlsafe_b64encode(salt).decode("ascii")
|
||||
hash_text = base64.urlsafe_b64encode(derived).decode("ascii")
|
||||
return f"scrypt$32768$8$1${salt_text}${hash_text}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt_text, hash_text = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
salt = base64.urlsafe_b64decode(salt_text.encode("ascii"))
|
||||
expected = base64.urlsafe_b64decode(hash_text.encode("ascii"))
|
||||
actual = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=int(n),
|
||||
r=int(r),
|
||||
p=int(p),
|
||||
dklen=len(expected),
|
||||
maxmem=64 * 1024 * 1024,
|
||||
)
|
||||
return hmac.compare_digest(actual, expected)
|
||||
except (ValueError, TypeError, UnicodeError):
|
||||
return False
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if __package__ in (None, ""):
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.app import main
|
||||
else:
|
||||
from .app import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+848
@@ -0,0 +1,848 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, BinaryIO, Dict, List, Optional, Tuple
|
||||
|
||||
import redis
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .config import (
|
||||
DB_LOCK_TIMEOUT_MS,
|
||||
DB_POOL_MAX_SIZE,
|
||||
DB_POOL_TIMEOUT_SECONDS,
|
||||
DB_STATEMENT_TIMEOUT_MS,
|
||||
IDEMPOTENCY_TTL_SECONDS,
|
||||
SESSION_TTL_SECONDS,
|
||||
)
|
||||
from .errors import (
|
||||
AttachmentNotReadyError,
|
||||
CacheUnavailableError,
|
||||
IdempotencyConflictError,
|
||||
ObjectMissingError,
|
||||
)
|
||||
from .object_store import ObjectStore
|
||||
from .pipeline_versions import PIPELINE_QUALITY
|
||||
from .security import isoformat, utc_now, valid_uuid, verify_password
|
||||
|
||||
LOGGER = logging.getLogger("messenger.store")
|
||||
|
||||
|
||||
def database_url() -> str:
|
||||
value = os.getenv("DATABASE_URL")
|
||||
if value:
|
||||
return value
|
||||
file_path = os.getenv("DATABASE_URL_FILE")
|
||||
if file_path:
|
||||
return Path(file_path).read_text(encoding="utf-8").strip()
|
||||
raise RuntimeError("Set DATABASE_URL or DATABASE_URL_FILE")
|
||||
|
||||
|
||||
class Store:
|
||||
"""PostgreSQL metadata, S3 objects, and optional Redis session cache."""
|
||||
|
||||
def __init__(self):
|
||||
self.pool = ConnectionPool(
|
||||
conninfo=database_url(),
|
||||
min_size=1,
|
||||
max_size=DB_POOL_MAX_SIZE,
|
||||
timeout=DB_POOL_TIMEOUT_SECONDS,
|
||||
kwargs={
|
||||
"row_factory": dict_row,
|
||||
"connect_timeout": 5,
|
||||
"options": (
|
||||
f"-c statement_timeout={DB_STATEMENT_TIMEOUT_MS} "
|
||||
f"-c lock_timeout={DB_LOCK_TIMEOUT_MS} "
|
||||
"-c idle_in_transaction_session_timeout=10000"
|
||||
),
|
||||
},
|
||||
open=False,
|
||||
)
|
||||
cache_url = os.getenv("CACHE_URL")
|
||||
self.cache = (
|
||||
redis.Redis.from_url(
|
||||
cache_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=0.25,
|
||||
socket_timeout=0.25,
|
||||
retry_on_timeout=False,
|
||||
max_connections=16,
|
||||
)
|
||||
if cache_url
|
||||
else None
|
||||
)
|
||||
self.objects = ObjectStore()
|
||||
|
||||
def open(self):
|
||||
self.pool.open(wait=True, timeout=10)
|
||||
|
||||
def close(self):
|
||||
if self.cache is not None:
|
||||
self.cache.close()
|
||||
self.pool.close()
|
||||
|
||||
def ready(self) -> bool:
|
||||
with self.pool.connection(timeout=2) as conn:
|
||||
conn.execute("SELECT 1")
|
||||
self.objects.ready()
|
||||
return True
|
||||
|
||||
def migrate(self):
|
||||
migrations = Path(__file__).resolve().parents[1] / "migrations"
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations "
|
||||
"(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"
|
||||
)
|
||||
conn.execute("SELECT pg_advisory_xact_lock(2741662026)")
|
||||
applied = {row["version"] for row in conn.execute("SELECT version FROM schema_migrations")}
|
||||
for migration in sorted(migrations.glob("*.sql")):
|
||||
if migration.name in applied:
|
||||
continue
|
||||
conn.execute(migration.read_text(encoding="utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (migration.name,))
|
||||
|
||||
@staticmethod
|
||||
def user(row: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": isoformat(row["created_at"]),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def chat(row: Dict[str, Any], member_ids: List[str]) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": isoformat(row["created_at"]),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def message(row: Dict[str, Any], attachment_ids: Optional[List[str]] = None) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": isoformat(row["created_at"]),
|
||||
"attachment_ids": attachment_ids or [],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def attachment(row: Dict[str, Any]) -> Dict[str, Any]:
|
||||
variants = row.get("variants") or []
|
||||
public_variants = [
|
||||
{
|
||||
name: variant[name]
|
||||
for name in ("name", "content_type", "size_bytes", "width", "height", "sha256")
|
||||
}
|
||||
for variant in variants
|
||||
]
|
||||
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"].strip(),
|
||||
"status": row.get("status", "queued"),
|
||||
"variants": public_variants,
|
||||
"error_code": row.get("error_code"),
|
||||
"created_at": isoformat(row["created_at"]),
|
||||
"updated_at": isoformat(row["updated_at"]),
|
||||
}
|
||||
|
||||
def create_user(self, username: str, display_name: str, password_hash: str) -> Dict[str, Any]:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"INSERT INTO users (username, display_name, password_hash) "
|
||||
"VALUES (%s, %s, %s) RETURNING id, username, display_name, created_at",
|
||||
(username, display_name, password_hash),
|
||||
).fetchone()
|
||||
return self.user(row)
|
||||
|
||||
def get_user(self, user_id: str) -> Optional[Dict[str, Any]]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
).fetchone()
|
||||
return self.user(row) if row else None
|
||||
|
||||
def authenticate(self, username: str, password: str) -> Optional[Dict[str, Any]]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash "
|
||||
"FROM users WHERE username = %s",
|
||||
(username,),
|
||||
).fetchone()
|
||||
if not row or not verify_password(password, row["password_hash"]):
|
||||
return None
|
||||
return self.user(row)
|
||||
|
||||
def create_session(self, user_id: str) -> Tuple[str, datetime]:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
token_hash = hashlib.sha256(token.encode("ascii")).digest()
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(token_hash, user_id, expires_at),
|
||||
)
|
||||
return token, expires_at
|
||||
|
||||
@staticmethod
|
||||
def _session_lock_key(token_hash: bytes) -> int:
|
||||
return int.from_bytes(token_hash[:8], byteorder="big", signed=True)
|
||||
|
||||
def session_user(self, token: str) -> Optional[Dict[str, Any]]:
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).digest()
|
||||
cache_key = "messenger:session:" + token_hash.hex()
|
||||
if self.cache is not None:
|
||||
try:
|
||||
cached = self.cache.get(cache_key)
|
||||
if cached:
|
||||
return json.loads(cached)
|
||||
except (redis.RedisError, ValueError, TypeError):
|
||||
LOGGER.warning("session cache read failed; falling back to PostgreSQL")
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (self._session_lock_key(token_hash),))
|
||||
row = conn.execute(
|
||||
"SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at "
|
||||
"FROM sessions s JOIN users u ON u.id = s.user_id "
|
||||
"WHERE s.token_hash = %s AND s.expires_at > now()",
|
||||
(token_hash,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
user = self.user(row)
|
||||
if self.cache is not None:
|
||||
ttl_ms = math.floor((row["expires_at"] - utc_now()).total_seconds() * 1000)
|
||||
if ttl_ms > 0:
|
||||
try:
|
||||
self.cache.set(cache_key, json.dumps(user, separators=(",", ":")), px=ttl_ms)
|
||||
except redis.RedisError:
|
||||
LOGGER.warning("session cache write failed; PostgreSQL remains authoritative")
|
||||
return user
|
||||
|
||||
def revoke_session(self, token: str) -> bool:
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).digest()
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (self._session_lock_key(token_hash),))
|
||||
if self.cache is not None:
|
||||
try:
|
||||
self.cache.delete("messenger:session:" + token_hash.hex())
|
||||
except redis.RedisError as exc:
|
||||
raise CacheUnavailableError from exc
|
||||
result = conn.execute("DELETE FROM sessions WHERE token_hash = %s", (token_hash,))
|
||||
return result.rowcount == 1
|
||||
|
||||
def create_chat(self, title: str, member_ids: List[str], actor_id: str) -> Dict[str, Any]:
|
||||
if actor_id not in member_ids or len(member_ids) != len(set(member_ids)):
|
||||
raise ValueError("invalid members")
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at",
|
||||
(title,),
|
||||
).fetchone()
|
||||
for member_id in member_ids:
|
||||
conn.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
(row["id"], member_id),
|
||||
)
|
||||
return self.chat(row, member_ids)
|
||||
|
||||
def get_chat(self, chat_id: str, user_id: str) -> Optional[Dict[str, Any]]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT c.id, c.title, c.created_at FROM chats c "
|
||||
"JOIN chat_members m ON m.chat_id = c.id "
|
||||
"WHERE c.id = %s AND m.user_id = %s",
|
||||
(chat_id, user_id),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
members = conn.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY joined_at, user_id",
|
||||
(chat_id,),
|
||||
).fetchall()
|
||||
return self.chat(row, [str(item["user_id"]) for item in members])
|
||||
|
||||
def list_chats(
|
||||
self, user_id: str, limit: int, cursor: Optional[str]
|
||||
) -> Tuple[List[Dict[str, Any]], Optional[str]]:
|
||||
where = "own.user_id = %s"
|
||||
params: List[Any] = [user_id]
|
||||
if cursor is not None:
|
||||
try:
|
||||
raw = base64.b64decode(
|
||||
cursor.encode("ascii") + b"=" * (-len(cursor) % 4),
|
||||
altchars=b"-_",
|
||||
validate=True,
|
||||
)
|
||||
cursor_user, timestamp, chat_id = raw.decode("utf-8").split("|", 2)
|
||||
if cursor_user != user_id or not valid_uuid(chat_id):
|
||||
raise ValueError("cursor scope")
|
||||
created_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
||||
if created_at.tzinfo is None or created_at.utcoffset() is None:
|
||||
raise ValueError("cursor timestamp must include a timezone")
|
||||
where += " AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend((created_at, chat_id))
|
||||
except (ValueError, UnicodeError, TypeError) as exc:
|
||||
raise ValueError("invalid cursor") from exc
|
||||
params.append(limit + 1)
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT c.id, c.title, c.created_at FROM chats c "
|
||||
"JOIN chat_members own ON own.chat_id = c.id "
|
||||
f"WHERE {where} ORDER BY c.created_at, c.id LIMIT %s",
|
||||
params,
|
||||
).fetchall()
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
result = []
|
||||
for row in page:
|
||||
members = conn.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY joined_at, user_id",
|
||||
(row["id"],),
|
||||
).fetchall()
|
||||
result.append(self.chat(row, [str(item["user_id"]) for item in members]))
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
cursor_data = f"{user_id}|{isoformat(last['created_at'])}|{last['id']}".encode("utf-8")
|
||||
next_cursor = base64.urlsafe_b64encode(cursor_data).decode("ascii").rstrip("=")
|
||||
return result, next_cursor
|
||||
|
||||
def create_idempotent_message(
|
||||
self,
|
||||
chat_id: str,
|
||||
sender_id: str,
|
||||
text: str,
|
||||
attachment_ids: List[str],
|
||||
idempotency_key: str,
|
||||
canonical_body: str,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
request_hash = hashlib.sha256(canonical_body.encode("utf-8")).digest()
|
||||
lock_material = "\0".join((sender_id, "POST", chat_id, idempotency_key)).encode("utf-8")
|
||||
lock_key = int.from_bytes(hashlib.sha256(lock_material).digest()[:8], "big", signed=True)
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
member = conn.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, sender_id),
|
||||
).fetchone()
|
||||
if not member:
|
||||
return None
|
||||
if attachment_ids:
|
||||
attachments = conn.execute(
|
||||
"SELECT id, status FROM attachments "
|
||||
"WHERE chat_id = %s AND id = ANY(%s) FOR SHARE",
|
||||
(chat_id, attachment_ids),
|
||||
).fetchall()
|
||||
if len(attachments) != len(attachment_ids):
|
||||
return None
|
||||
if any(item["status"] == "failed" for item in attachments):
|
||||
raise AttachmentNotReadyError
|
||||
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
|
||||
existing = conn.execute(
|
||||
"SELECT request_hash, response, expires_at "
|
||||
"FROM idempotency_records "
|
||||
"WHERE user_id = %s AND method = 'POST' AND chat_id = %s AND idempotency_key = %s "
|
||||
"FOR UPDATE",
|
||||
(sender_id, chat_id, idempotency_key),
|
||||
).fetchone()
|
||||
if existing and existing["expires_at"] > utc_now():
|
||||
if not hmac.compare_digest(bytes(existing["request_hash"]), request_hash):
|
||||
raise IdempotencyConflictError
|
||||
return existing["response"]
|
||||
if existing:
|
||||
conn.execute(
|
||||
"DELETE FROM idempotency_records "
|
||||
"WHERE user_id = %s AND method = 'POST' AND chat_id = %s AND idempotency_key = %s",
|
||||
(sender_id, chat_id, idempotency_key),
|
||||
)
|
||||
|
||||
row = conn.execute(
|
||||
"INSERT INTO messages (chat_id, sender_id, text) "
|
||||
"VALUES (%s, %s, %s) RETURNING id, chat_id, sender_id, text, created_at",
|
||||
(chat_id, sender_id, text),
|
||||
).fetchone()
|
||||
for ordinal, attachment_id in enumerate(attachment_ids):
|
||||
conn.execute(
|
||||
"INSERT INTO message_attachments (message_id, attachment_id, ordinal) "
|
||||
"VALUES (%s, %s, %s)",
|
||||
(row["id"], attachment_id, ordinal),
|
||||
)
|
||||
message = self.message(row, attachment_ids)
|
||||
conn.execute(
|
||||
"INSERT INTO idempotency_records "
|
||||
"(user_id, method, chat_id, idempotency_key, request_hash, response, expires_at) "
|
||||
"VALUES (%s, 'POST', %s, %s, %s, %s::jsonb, %s)",
|
||||
(
|
||||
sender_id,
|
||||
chat_id,
|
||||
idempotency_key,
|
||||
request_hash,
|
||||
json.dumps(message, ensure_ascii=False, separators=(",", ":")),
|
||||
utc_now() + timedelta(seconds=IDEMPOTENCY_TTL_SECONDS),
|
||||
),
|
||||
)
|
||||
return message
|
||||
|
||||
def list_messages(
|
||||
self, chat_id: str, user_id: str, limit: int, cursor: Optional[str]
|
||||
) -> Optional[Tuple[List[Dict[str, Any]], Optional[str]]]:
|
||||
with self.pool.connection() as conn:
|
||||
is_member = conn.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
).fetchone()
|
||||
if not is_member:
|
||||
return None
|
||||
where = "chat_id = %s"
|
||||
params: List[Any] = [chat_id]
|
||||
if cursor:
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor.encode("ascii") + b"=" * (-len(cursor) % 4))
|
||||
decoded_chat, timestamp, message_id = raw.decode("utf-8").split("|", 2)
|
||||
if decoded_chat != chat_id or not valid_uuid(message_id):
|
||||
raise ValueError("cursor scope")
|
||||
created_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
||||
where += " AND (created_at, id) > (%s, %s)"
|
||||
params.extend((created_at, message_id))
|
||||
except (ValueError, UnicodeError, TypeError) as exc:
|
||||
raise ValueError("invalid cursor") from exc
|
||||
params.append(limit + 1)
|
||||
rows = conn.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages "
|
||||
f"WHERE {where} ORDER BY created_at, id LIMIT %s",
|
||||
params,
|
||||
).fetchall()
|
||||
ids_by_message = {}
|
||||
if rows:
|
||||
links = conn.execute(
|
||||
"SELECT message_id, attachment_id FROM message_attachments "
|
||||
"WHERE message_id = ANY(%s) ORDER BY message_id, ordinal",
|
||||
([row["id"] for row in rows],),
|
||||
).fetchall()
|
||||
for link in links:
|
||||
ids_by_message.setdefault(link["message_id"], []).append(str(link["attachment_id"]))
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
cursor_data = f"{chat_id}|{isoformat(last['created_at'])}|{last['id']}".encode("utf-8")
|
||||
next_cursor = base64.urlsafe_b64encode(cursor_data).decode("ascii").rstrip("=")
|
||||
return [self.message(row, ids_by_message.get(row["id"], [])) for row in page], next_cursor
|
||||
|
||||
def can_access_chat(self, chat_id: str, user_id: str) -> bool:
|
||||
with self.pool.connection() as conn:
|
||||
return conn.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
).fetchone() is not None
|
||||
|
||||
def create_attachment(
|
||||
self,
|
||||
chat_id: str,
|
||||
owner_id: str,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
content: BinaryIO,
|
||||
size_bytes: int,
|
||||
digest: str,
|
||||
traceparent: Optional[str] = None,
|
||||
tracestate: Optional[str] = None,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if not self.can_access_chat(chat_id, owner_id):
|
||||
return None
|
||||
attachment_id = uuid.uuid4()
|
||||
job_id = uuid.uuid4()
|
||||
staging_key = f"staging/{attachment_id}"
|
||||
object_key = f"original/{attachment_id}"
|
||||
content.seek(0)
|
||||
self.objects.put(staging_key, content, content_type, size_bytes)
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"INSERT INTO attachments "
|
||||
"(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
|
||||
"object_key, staging_key, job_id) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
|
||||
"RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
|
||||
"status, variants, error_code, created_at, updated_at",
|
||||
(
|
||||
attachment_id,
|
||||
chat_id,
|
||||
owner_id,
|
||||
filename,
|
||||
content_type,
|
||||
size_bytes,
|
||||
digest,
|
||||
object_key,
|
||||
staging_key,
|
||||
job_id,
|
||||
),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"INSERT INTO attachment_outbox "
|
||||
"(id, job_id, attachment_id, pipeline_version, attempt, traceparent, tracestate) "
|
||||
"VALUES (%s, %s, %s, 1, 1, %s, %s)",
|
||||
(uuid.uuid4(), job_id, attachment_id, traceparent, tracestate),
|
||||
)
|
||||
return self.attachment(row)
|
||||
except Exception:
|
||||
try:
|
||||
self.objects.delete(staging_key)
|
||||
except Exception as cleanup_error:
|
||||
LOGGER.error(
|
||||
"attachment staging compensation failed for %s (%s)",
|
||||
attachment_id,
|
||||
type(cleanup_error).__name__,
|
||||
)
|
||||
raise
|
||||
|
||||
def get_attachment(self, attachment_id: str, user_id: str) -> Optional[Dict[str, Any]]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, "
|
||||
"a.sha256, a.status, a.variants, a.error_code, a.created_at, a.updated_at "
|
||||
"FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id "
|
||||
"WHERE a.id = %s AND m.user_id = %s",
|
||||
(attachment_id, user_id),
|
||||
).fetchone()
|
||||
return self.attachment(row) if row else None
|
||||
|
||||
def download_attachment(
|
||||
self, attachment_id: str, user_id: str, variant: str = "original"
|
||||
) -> Optional[Tuple[str, bytes]]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT a.object_key, a.staging_key, a.content_type, a.size_bytes, a.status, a.variants "
|
||||
"FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id "
|
||||
"WHERE a.id = %s AND m.user_id = %s",
|
||||
(attachment_id, user_id),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
if row["status"] != "ready":
|
||||
raise AttachmentNotReadyError
|
||||
if variant == "original":
|
||||
key, content_type, size_bytes = row["object_key"], row["content_type"], row["size_bytes"]
|
||||
else:
|
||||
match = next(
|
||||
(item for item in (row["variants"] or []) if item["name"] == variant),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
return None
|
||||
key, content_type, size_bytes = match["object_key"], match["content_type"], match["size_bytes"]
|
||||
return content_type, self.objects.get(key, size_bytes)
|
||||
|
||||
def claim_attachment_job(
|
||||
self, attachment_id: str, job_id: str, pipeline_version: int, attempt: int, lease_seconds: int
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"SELECT id, job_id, pipeline_version, attempt, status, lease_until, staging_key, "
|
||||
"object_key, content_type, size_bytes, sha256 "
|
||||
"FROM attachments WHERE id = %s FOR UPDATE",
|
||||
(attachment_id,),
|
||||
).fetchone()
|
||||
if (
|
||||
not row
|
||||
or str(row["job_id"]) != job_id
|
||||
or row["pipeline_version"] != pipeline_version
|
||||
or row["status"] in ("ready", "failed")
|
||||
or row["attempt"] != attempt
|
||||
):
|
||||
return None
|
||||
if row["status"] == "processing" and row["lease_until"] is not None:
|
||||
if row["lease_until"] > utc_now():
|
||||
return None
|
||||
return conn.execute(
|
||||
"UPDATE attachments SET status = 'processing', "
|
||||
"lease_until = clock_timestamp() + (%s * interval '1 second'), "
|
||||
"updated_at = clock_timestamp() "
|
||||
"WHERE id = %s RETURNING id, job_id, staging_key, object_key, content_type, "
|
||||
"size_bytes, sha256, attempt, pipeline_version",
|
||||
(lease_seconds, attachment_id),
|
||||
).fetchone()
|
||||
|
||||
def complete_attachment_job(
|
||||
self,
|
||||
attachment_id: str,
|
||||
job_id: str,
|
||||
pipeline_version: int,
|
||||
attempt: int,
|
||||
variants: List[Dict[str, Any]],
|
||||
) -> bool:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
updated = conn.execute(
|
||||
"UPDATE attachments SET status = 'ready', variants = %s::jsonb, error_code = NULL, "
|
||||
"lease_until = NULL, updated_at = clock_timestamp() "
|
||||
"WHERE id = %s AND job_id = %s AND pipeline_version = %s AND attempt = %s "
|
||||
"AND status = 'processing' AND lease_until > clock_timestamp()",
|
||||
(
|
||||
json.dumps(variants, separators=(",", ":")),
|
||||
attachment_id,
|
||||
job_id,
|
||||
pipeline_version,
|
||||
attempt,
|
||||
),
|
||||
)
|
||||
return updated.rowcount == 1
|
||||
|
||||
def fail_attachment_job(
|
||||
self, attachment_id: str, job_id: str, pipeline_version: int, attempt: int,
|
||||
max_attempts: int, error_code: str, retry_delay_seconds: Optional[float],
|
||||
traceparent: Optional[str] = None, tracestate: Optional[str] = None,
|
||||
) -> None:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"SELECT status, attempt FROM attachments "
|
||||
"WHERE id = %s AND job_id = %s AND pipeline_version = %s FOR UPDATE",
|
||||
(attachment_id, job_id, pipeline_version),
|
||||
).fetchone()
|
||||
if not row or row["status"] != "processing" or row["attempt"] != attempt:
|
||||
return
|
||||
if retry_delay_seconds is not None and attempt < max_attempts:
|
||||
next_attempt = attempt + 1
|
||||
conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', attempt = %s, lease_until = NULL, "
|
||||
"error_code = %s, updated_at = clock_timestamp() WHERE id = %s",
|
||||
(next_attempt, error_code, attachment_id),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO attachment_outbox "
|
||||
"(id, job_id, attachment_id, pipeline_version, attempt, available_at, traceparent, tracestate) "
|
||||
"VALUES (%s, %s, %s, %s, %s, clock_timestamp() + (%s * interval '1 second'), %s, %s) "
|
||||
"ON CONFLICT (job_id, attempt) DO NOTHING",
|
||||
(
|
||||
uuid.uuid4(), job_id, attachment_id, pipeline_version,
|
||||
next_attempt, retry_delay_seconds, traceparent, tracestate,
|
||||
),
|
||||
)
|
||||
else:
|
||||
final_code = "retry_exhausted" if attempt >= max_attempts else error_code
|
||||
conn.execute(
|
||||
"UPDATE attachments SET status = 'failed', lease_until = NULL, error_code = %s, "
|
||||
"updated_at = clock_timestamp() WHERE id = %s",
|
||||
(final_code, attachment_id),
|
||||
)
|
||||
|
||||
def replay_attachment_job(self, attachment_id: str, pipeline_version: int) -> Dict[str, Any]:
|
||||
if pipeline_version not in PIPELINE_QUALITY:
|
||||
raise ValueError("pipeline version is not implemented by this deployment")
|
||||
with self.pool.connection() as conn:
|
||||
current = conn.execute(
|
||||
"SELECT id, job_id, pipeline_version, attempt, status, staging_key, object_key, "
|
||||
"content_type, size_bytes, sha256 FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
).fetchone()
|
||||
if current is None:
|
||||
raise ValueError("attachment not found")
|
||||
if pipeline_version < current["pipeline_version"]:
|
||||
raise ValueError("pipeline version cannot move backwards")
|
||||
if pipeline_version == current["pipeline_version"] and current["status"] != "failed":
|
||||
raise ValueError("same-version replay is allowed only for failed attachments")
|
||||
if current["status"] not in ("queued", "processing", "ready", "failed"):
|
||||
raise ValueError("attachment cannot be replayed in its current state")
|
||||
|
||||
try:
|
||||
content = self.objects.get(current["object_key"], current["size_bytes"])
|
||||
except ObjectMissingError as object_error:
|
||||
try:
|
||||
content = self.objects.get(current["staging_key"], current["size_bytes"])
|
||||
except ObjectMissingError:
|
||||
raise object_error
|
||||
if (
|
||||
len(content) != current["size_bytes"]
|
||||
or hashlib.sha256(content).hexdigest() != current["sha256"].strip()
|
||||
):
|
||||
raise ValueError("stored original does not match attachment metadata")
|
||||
|
||||
prior_job_id = str(current["job_id"])
|
||||
next_job_id = uuid.uuid4()
|
||||
staging_key = f"staging/{attachment_id}/{next_job_id}"
|
||||
self.objects.put(staging_key, content, current["content_type"], len(content))
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
locked = conn.execute(
|
||||
"SELECT job_id, pipeline_version, attempt, status FROM attachments "
|
||||
"WHERE id = %s FOR UPDATE",
|
||||
(attachment_id,),
|
||||
).fetchone()
|
||||
if (
|
||||
locked is None
|
||||
or str(locked["job_id"]) != prior_job_id
|
||||
or locked["pipeline_version"] != current["pipeline_version"]
|
||||
or locked["attempt"] != current["attempt"]
|
||||
or locked["status"] != current["status"]
|
||||
):
|
||||
raise RuntimeError("attachment changed while preparing replay")
|
||||
conn.execute(
|
||||
"UPDATE attachments SET job_id = %s, pipeline_version = %s, attempt = 1, "
|
||||
"status = 'queued', staging_key = %s, variants = '[]'::jsonb, "
|
||||
"error_code = NULL, lease_until = NULL, updated_at = clock_timestamp() "
|
||||
"WHERE id = %s",
|
||||
(next_job_id, pipeline_version, staging_key, attachment_id),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO attachment_outbox "
|
||||
"(id, job_id, attachment_id, pipeline_version, attempt) "
|
||||
"VALUES (%s, %s, %s, %s, 1)",
|
||||
(uuid.uuid4(), next_job_id, attachment_id, pipeline_version),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO attachment_pipeline_events "
|
||||
"(attachment_id, prior_job_id, job_id, prior_version, pipeline_version, action) "
|
||||
"VALUES (%s, %s, %s, %s, %s, 'replay')",
|
||||
(
|
||||
attachment_id,
|
||||
prior_job_id,
|
||||
next_job_id,
|
||||
current["pipeline_version"],
|
||||
pipeline_version,
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
self.objects.delete(staging_key)
|
||||
except Exception as cleanup_error:
|
||||
LOGGER.error(
|
||||
"replay staging cleanup failed for %s (%s)",
|
||||
attachment_id,
|
||||
type(cleanup_error).__name__,
|
||||
)
|
||||
raise
|
||||
return {
|
||||
"attachment_id": str(attachment_id),
|
||||
"previous_job_id": prior_job_id,
|
||||
"job_id": str(next_job_id),
|
||||
"pipeline_version": pipeline_version,
|
||||
"attempt": 1,
|
||||
"status": "queued",
|
||||
}
|
||||
|
||||
def recover_expired_attachment_jobs(self, max_attempts: int, lease_seconds: int) -> int:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
rows = conn.execute(
|
||||
"SELECT id, job_id, pipeline_version, attempt FROM attachments "
|
||||
"WHERE status = 'processing' AND lease_until < clock_timestamp() "
|
||||
"ORDER BY lease_until FOR UPDATE SKIP LOCKED LIMIT 100"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
if row["attempt"] >= max_attempts:
|
||||
conn.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted', "
|
||||
"lease_until = NULL, updated_at = clock_timestamp() WHERE id = %s",
|
||||
(row["id"],),
|
||||
)
|
||||
continue
|
||||
next_attempt = row["attempt"] + 1
|
||||
conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', attempt = %s, lease_until = NULL, "
|
||||
"error_code = 'worker_lease_expired', updated_at = clock_timestamp() WHERE id = %s",
|
||||
(next_attempt, row["id"]),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO attachment_outbox "
|
||||
"(id, job_id, attachment_id, pipeline_version, attempt) "
|
||||
"VALUES (%s, %s, %s, %s, %s) ON CONFLICT (job_id, attempt) DO NOTHING",
|
||||
(uuid.uuid4(), row["job_id"], row["id"], row["pipeline_version"], next_attempt),
|
||||
)
|
||||
return len(rows)
|
||||
|
||||
def claim_outbox(self, conn):
|
||||
return conn.execute(
|
||||
"SELECT o.id, o.job_id, o.attachment_id, o.pipeline_version, o.attempt, "
|
||||
"o.traceparent, o.tracestate, "
|
||||
"a.created_at FROM attachment_outbox o "
|
||||
"JOIN attachments a ON a.id = o.attachment_id "
|
||||
"WHERE o.published_at IS NULL AND o.available_at <= clock_timestamp() "
|
||||
"ORDER BY o.created_at FOR UPDATE OF o SKIP LOCKED LIMIT 1"
|
||||
).fetchone()
|
||||
|
||||
def queue_snapshot(self) -> Tuple[int, float]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT count(*) AS depth, "
|
||||
"COALESCE(extract(epoch FROM clock_timestamp() - min(created_at)), 0) AS oldest_age "
|
||||
"FROM attachments WHERE status = 'queued'"
|
||||
).fetchone()
|
||||
return int(row["depth"]), float(row["oldest_age"])
|
||||
|
||||
def reconciliation_snapshot(self):
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, object_key, staging_key, status, variants, pipeline_version, created_at, "
|
||||
"size_bytes, sha256, content_type FROM attachments"
|
||||
).fetchall()
|
||||
expected = {}
|
||||
for row in rows:
|
||||
if row["status"] == "ready":
|
||||
expected[row["object_key"]] = {**row, "reconcile_type": "original"}
|
||||
for variant in row["variants"] or []:
|
||||
expected[variant["object_key"]] = {
|
||||
**row,
|
||||
"object_key": variant["object_key"],
|
||||
"size_bytes": variant["size_bytes"],
|
||||
"sha256": variant["sha256"],
|
||||
"content_type": variant["content_type"],
|
||||
"reconcile_type": "variant",
|
||||
}
|
||||
elif row["status"] in ("queued", "processing"):
|
||||
expected[row["staging_key"]] = {**row, "reconcile_type": "staging"}
|
||||
expected[row["object_key"]] = {**row, "reconcile_type": "inflight"}
|
||||
for name, extension in (
|
||||
("thumbnail", "jpg"),
|
||||
("crop", "jpg"),
|
||||
("optimized", "webp"),
|
||||
):
|
||||
key = f"variants/{row['id']}/v{row['pipeline_version']}/{name}.{extension}"
|
||||
expected[key] = {**row, "object_key": key, "reconcile_type": "inflight"}
|
||||
return expected
|
||||
|
||||
def record_missing_object(self, attachment_id: str) -> None:
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO reconciliation_incidents (attachment_id, incident_type) "
|
||||
"VALUES (%s, 'missing_object') ON CONFLICT (attachment_id, incident_type) "
|
||||
"DO UPDATE SET last_seen_at = clock_timestamp()",
|
||||
(attachment_id,),
|
||||
)
|
||||
|
||||
def clear_missing_object(self, attachment_id: str) -> None:
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"DELETE FROM reconciliation_incidents "
|
||||
"WHERE attachment_id = %s AND incident_type = 'missing_object'",
|
||||
(attachment_id,),
|
||||
)
|
||||
@@ -0,0 +1,296 @@
|
||||
import contextvars
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import psycopg
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ALWAYS_ON, ParentBased, TraceIdRatioBased
|
||||
from opentelemetry.instrumentation.utils import suppress_instrumentation
|
||||
|
||||
REQUEST_ID = contextvars.ContextVar("request_id", default="")
|
||||
_lock = threading.Lock()
|
||||
_runtime = {
|
||||
"pool_used": 0,
|
||||
"pool_waiting": 0,
|
||||
"queue_depth": 0,
|
||||
"queue_oldest_seconds": 0.0,
|
||||
"worker_busy": 0,
|
||||
"worker_capacity": 0,
|
||||
"cpu": 0.0,
|
||||
"memory": 0,
|
||||
}
|
||||
_provider = None
|
||||
_meter = None
|
||||
_service_name = "messenger"
|
||||
_enabled = True
|
||||
_request_counter = None
|
||||
_request_duration = None
|
||||
_job_counter = None
|
||||
_job_duration = None
|
||||
_time_to_ready = None
|
||||
_queue_depth = None
|
||||
_queue_oldest = None
|
||||
_pool_used = None
|
||||
_pool_waiting = None
|
||||
_worker_busy = None
|
||||
_worker_capacity = None
|
||||
_process_cpu = None
|
||||
_process_memory = None
|
||||
|
||||
|
||||
class JsonLogFormatter(logging.Formatter):
|
||||
converter = time.gmtime
|
||||
|
||||
def format(self, record):
|
||||
span_context = trace.get_current_span().get_span_context()
|
||||
document = {
|
||||
"timestamp": datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
|
||||
"severity": record.levelname,
|
||||
"service.name": _service_name,
|
||||
"event": record.getMessage(),
|
||||
"request_id": REQUEST_ID.get(),
|
||||
}
|
||||
if span_context.is_valid:
|
||||
document["trace_id"] = format(span_context.trace_id, "032x")
|
||||
document["span_id"] = format(span_context.span_id, "016x")
|
||||
if record.exc_info:
|
||||
document["exception.type"] = record.exc_info[0].__name__
|
||||
return json.dumps(document, ensure_ascii=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def _sampler():
|
||||
if os.getenv("OTEL_TRACES_SAMPLER", "parentbased_traceidratio") == "always_off":
|
||||
return ALWAYS_OFF
|
||||
if os.getenv("OTEL_TRACES_SAMPLER", "") == "always_on":
|
||||
return ALWAYS_ON
|
||||
ratio = float(os.getenv("OTEL_TRACES_SAMPLER_ARG", "1.0"))
|
||||
if not 0 <= ratio <= 1:
|
||||
raise ValueError("OTEL_TRACES_SAMPLER_ARG must be between 0 and 1")
|
||||
return ParentBased(TraceIdRatioBased(ratio))
|
||||
|
||||
|
||||
def initialize(service_name: str) -> None:
|
||||
global _enabled
|
||||
global _service_name
|
||||
global _provider, _meter
|
||||
global _request_counter, _request_duration, _job_counter, _job_duration, _time_to_ready
|
||||
global _queue_depth, _queue_oldest, _pool_used, _pool_waiting
|
||||
global _worker_busy, _worker_capacity, _process_cpu, _process_memory
|
||||
|
||||
enabled = os.getenv("OTEL_SDK_DISABLED", "false").lower() != "true"
|
||||
_enabled = enabled
|
||||
_service_name = service_name
|
||||
instance_id = os.getenv("INSTANCE_ID", socket.gethostname())
|
||||
resource = Resource.create(
|
||||
{
|
||||
"service.name": service_name,
|
||||
"service.version": os.getenv("SERVICE_VERSION", "lab6"),
|
||||
"service.instance.id": instance_id,
|
||||
"deployment.environment.name": os.getenv("APP_ENV", "lab"),
|
||||
"host.name": socket.gethostname(),
|
||||
"os.type": platform.system().lower(),
|
||||
}
|
||||
)
|
||||
if enabled:
|
||||
endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318")
|
||||
_provider = TracerProvider(resource=resource, sampler=_sampler())
|
||||
_provider.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
OTLPSpanExporter(endpoint=endpoint.rstrip("/") + "/v1/traces"),
|
||||
max_queue_size=4096,
|
||||
max_export_batch_size=512,
|
||||
schedule_delay_millis=1000,
|
||||
export_timeout_millis=10000,
|
||||
)
|
||||
)
|
||||
trace.set_tracer_provider(_provider)
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=endpoint.rstrip("/") + "/v1/metrics"),
|
||||
export_interval_millis=10000,
|
||||
export_timeout_millis=5000,
|
||||
)
|
||||
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
logger_provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(endpoint=endpoint.rstrip("/") + "/v1/logs"),
|
||||
max_queue_size=4096,
|
||||
max_export_batch_size=512,
|
||||
schedule_delay_millis=1000,
|
||||
export_timeout_millis=10000,
|
||||
)
|
||||
)
|
||||
otel_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||
otel_handler.setFormatter(JsonLogFormatter())
|
||||
else:
|
||||
trace.set_tracer_provider(TracerProvider(resource=resource, sampler=ALWAYS_OFF))
|
||||
metrics.set_meter_provider(MeterProvider(resource=resource))
|
||||
otel_handler = None
|
||||
|
||||
root = logging.getLogger()
|
||||
root.setLevel(os.getenv("LOG_LEVEL", "INFO"))
|
||||
formatter = JsonLogFormatter()
|
||||
stream_handler = logging.StreamHandler()
|
||||
stream_handler.setFormatter(formatter)
|
||||
root.handlers[:] = [stream_handler]
|
||||
if otel_handler is not None:
|
||||
root.addHandler(otel_handler)
|
||||
logging.getLogger("pika").setLevel(logging.WARNING)
|
||||
|
||||
if enabled:
|
||||
try:
|
||||
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
|
||||
from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
|
||||
|
||||
BotocoreInstrumentor().instrument()
|
||||
PsycopgInstrumentor().instrument()
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("OTel database and S3 instrumentation dependencies are required") from exc
|
||||
|
||||
_meter = metrics.get_meter("messenger.telemetry")
|
||||
_request_counter = _meter.create_counter("messenger.http.requests", unit="{request}")
|
||||
_request_duration = _meter.create_histogram("messenger.http.duration", unit="s")
|
||||
_job_counter = _meter.create_counter("messenger.jobs.processed", unit="{job}")
|
||||
_job_duration = _meter.create_histogram("messenger.jobs.duration", unit="s")
|
||||
_time_to_ready = _meter.create_histogram("messenger.attachments.time_to_ready", unit="s")
|
||||
|
||||
def observe(name, attributes=None):
|
||||
def callback(_options):
|
||||
with _lock:
|
||||
return [metrics.Observation(_runtime[name], attributes=attributes or {})]
|
||||
|
||||
return callback
|
||||
|
||||
_queue_depth = _meter.create_observable_gauge(
|
||||
"messenger.queue.depth",
|
||||
callbacks=[observe("queue_depth", {"queue.name": "attachments.process.v1"})],
|
||||
unit="{job}",
|
||||
)
|
||||
_queue_oldest = _meter.create_observable_gauge(
|
||||
"messenger.queue.oldest_age",
|
||||
callbacks=[observe("queue_oldest_seconds", {"queue.name": "attachments.process.v1"})],
|
||||
unit="s",
|
||||
)
|
||||
_pool_used = _meter.create_observable_gauge(
|
||||
"messenger.db.pool.connections.used",
|
||||
callbacks=[observe("pool_used", {"pool.name": "primary"})],
|
||||
unit="{connection}",
|
||||
)
|
||||
_pool_waiting = _meter.create_observable_gauge(
|
||||
"messenger.db.pool.requests.waiting",
|
||||
callbacks=[observe("pool_waiting", {"pool.name": "primary"})],
|
||||
unit="{request}",
|
||||
)
|
||||
_worker_busy = _meter.create_observable_gauge(
|
||||
"messenger.worker.busy", callbacks=[observe("worker_busy")], unit="{worker}"
|
||||
)
|
||||
_worker_capacity = _meter.create_observable_gauge(
|
||||
"messenger.worker.capacity", callbacks=[observe("worker_capacity")], unit="{worker}"
|
||||
)
|
||||
_process_cpu = _meter.create_observable_gauge(
|
||||
"messenger.process.cpu.utilization", callbacks=[observe("cpu")], unit="1"
|
||||
)
|
||||
_process_memory = _meter.create_observable_gauge(
|
||||
"messenger.process.memory.usage", callbacks=[observe("memory")], unit="By"
|
||||
)
|
||||
|
||||
|
||||
def tracer():
|
||||
return trace.get_tracer("messenger.application")
|
||||
|
||||
|
||||
def record_http_request(method: str, route: str, status: int, duration: float) -> None:
|
||||
attributes = {
|
||||
"http.request.method": method,
|
||||
"http.route": route,
|
||||
"status_class": f"{status // 100}xx",
|
||||
}
|
||||
if _request_counter is not None:
|
||||
_request_counter.add(1, attributes)
|
||||
_request_duration.record(duration, attributes)
|
||||
if _enabled and not route.startswith("/health/"):
|
||||
logging.getLogger("messenger.http").info(
|
||||
"http request completed method=%s route=%s status_class=%s",
|
||||
method,
|
||||
route,
|
||||
f"{status // 100}xx",
|
||||
)
|
||||
|
||||
|
||||
def record_job(outcome: str, duration: float, time_to_ready: Optional[float] = None) -> None:
|
||||
attributes = {"job.type": "attachment.process.v1", "outcome": outcome}
|
||||
if _job_counter is not None:
|
||||
_job_counter.add(1, attributes)
|
||||
_job_duration.record(duration, attributes)
|
||||
if time_to_ready is not None:
|
||||
_time_to_ready.record(time_to_ready, {"outcome": outcome})
|
||||
|
||||
|
||||
def update_runtime(**values) -> None:
|
||||
with _lock:
|
||||
_runtime.update(values)
|
||||
|
||||
|
||||
def start_runtime_metrics(store, worker_capacity: int = 0) -> Optional[threading.Thread]:
|
||||
if not _enabled:
|
||||
return None
|
||||
|
||||
def refresh():
|
||||
try:
|
||||
import psutil
|
||||
|
||||
process = psutil.Process()
|
||||
process.cpu_percent(interval=None)
|
||||
while True:
|
||||
try:
|
||||
stats = store.pool.get_stats()
|
||||
with suppress_instrumentation():
|
||||
queue_depth, oldest_age = store.queue_snapshot()
|
||||
cpu = process.cpu_percent(interval=1) / 100.0
|
||||
memory = process.memory_info().rss
|
||||
update_runtime(
|
||||
pool_used=max(0, stats.get("pool_size", 0) - stats.get("pool_available", 0)),
|
||||
pool_waiting=stats.get("requests_waiting", 0),
|
||||
queue_depth=queue_depth,
|
||||
queue_oldest_seconds=oldest_age,
|
||||
worker_capacity=worker_capacity,
|
||||
cpu=cpu,
|
||||
memory=memory,
|
||||
)
|
||||
except (psycopg.Error, OSError, RuntimeError, ValueError):
|
||||
logging.getLogger("messenger.telemetry").exception("runtime metric sample failed")
|
||||
time.sleep(9)
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
logging.getLogger("messenger.telemetry").exception("runtime metric sampler stopped")
|
||||
raise
|
||||
|
||||
thread = threading.Thread(target=refresh, name="runtime-metrics", daemon=True)
|
||||
thread.start()
|
||||
return thread
|
||||
|
||||
|
||||
def worker_started() -> None:
|
||||
with _lock:
|
||||
_runtime["worker_busy"] += 1
|
||||
|
||||
|
||||
def worker_stopped() -> None:
|
||||
with _lock:
|
||||
_runtime["worker_busy"] = max(0, _runtime["worker_busy"] - 1)
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
#!/usr/bin/env python3
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import multiprocessing
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
import uuid
|
||||
import warnings
|
||||
import zlib
|
||||
from datetime import datetime, timezone
|
||||
from typing import Callable, Optional
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from opentelemetry import propagate
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from .config import MAX_IMAGE_PIXELS
|
||||
from .jobs import LEASE_NETWORK_BUDGET_SECONDS, QUEUE_NAME, connect, declare_queues
|
||||
from .pipeline_versions import PIPELINE_QUALITY
|
||||
from .store import Store
|
||||
from .telemetry import (
|
||||
initialize,
|
||||
record_job,
|
||||
start_runtime_metrics,
|
||||
tracer,
|
||||
worker_started,
|
||||
worker_stopped,
|
||||
)
|
||||
|
||||
LOGGER = logging.getLogger("messenger.worker")
|
||||
|
||||
MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
|
||||
JOB_TIMEOUT_SECONDS = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
|
||||
WORKER_CONCURRENCY = int(os.getenv("WORKER_CONCURRENCY", "1"))
|
||||
|
||||
|
||||
class InvalidAttachment(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnsupportedPipeline(InvalidAttachment):
|
||||
pass
|
||||
|
||||
|
||||
def _rgb_image(content: bytes) -> Image.Image:
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(io.BytesIO(content)) as source:
|
||||
if source.format not in ("PNG", "JPEG"):
|
||||
raise InvalidAttachment("unsupported_image")
|
||||
width, height = source.size
|
||||
if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS:
|
||||
raise InvalidAttachment("image_too_large")
|
||||
source.load()
|
||||
image = ImageOps.exif_transpose(source)
|
||||
try:
|
||||
if "A" in image.getbands() or "transparency" in image.info:
|
||||
with image.convert("RGBA") as rgba:
|
||||
background = Image.new("RGB", rgba.size, "white")
|
||||
background.paste(rgba, mask=rgba.getchannel("A"))
|
||||
return background
|
||||
return image.convert("RGB")
|
||||
finally:
|
||||
if image is not source:
|
||||
image.close()
|
||||
except InvalidAttachment:
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning, OSError, SyntaxError,
|
||||
UnidentifiedImageError, ValueError, zlib.error) as exc:
|
||||
raise InvalidAttachment("invalid_image") from exc
|
||||
|
||||
|
||||
def _encode(image: Image.Image, image_format: str, **options) -> bytes:
|
||||
output = io.BytesIO()
|
||||
image.save(output, format=image_format, **options)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def build_variants(attachment_id: str, content: bytes, pipeline_version: int = 1):
|
||||
quality = PIPELINE_QUALITY.get(pipeline_version)
|
||||
if quality is None:
|
||||
raise UnsupportedPipeline("unsupported_pipeline_version")
|
||||
image = _rgb_image(content)
|
||||
try:
|
||||
variants = []
|
||||
thumbnail = image.copy()
|
||||
try:
|
||||
thumbnail.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
thumbnail_bytes = _encode(thumbnail, "JPEG", quality=quality["jpeg"], optimize=True)
|
||||
variants.append(("thumbnail", "image/jpeg", thumbnail.width, thumbnail.height, thumbnail_bytes))
|
||||
finally:
|
||||
thumbnail.close()
|
||||
|
||||
crop = ImageOps.fit(image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5))
|
||||
try:
|
||||
crop_bytes = _encode(crop, "JPEG", quality=quality["jpeg"], optimize=True)
|
||||
variants.append(("crop", "image/jpeg", 128, 128, crop_bytes))
|
||||
finally:
|
||||
crop.close()
|
||||
|
||||
optimized = image.copy()
|
||||
try:
|
||||
optimized.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
|
||||
optimized_bytes = _encode(optimized, "WEBP", quality=quality["webp"], method=6)
|
||||
variants.append(("optimized", "image/webp", optimized.width, optimized.height, optimized_bytes))
|
||||
finally:
|
||||
optimized.close()
|
||||
|
||||
result = []
|
||||
for name, content_type, width, height, data in variants:
|
||||
extension = "webp" if content_type == "image/webp" else "jpg"
|
||||
key = f"variants/{attachment_id}/v{pipeline_version}/{name}.{extension}"
|
||||
result.append(
|
||||
{
|
||||
"name": name,
|
||||
"content_type": content_type,
|
||||
"size_bytes": len(data),
|
||||
"width": width,
|
||||
"height": height,
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
"object_key": key,
|
||||
"content": data,
|
||||
}
|
||||
)
|
||||
return result
|
||||
finally:
|
||||
image.close()
|
||||
|
||||
|
||||
class ProcessingTimeout(TimeoutError):
|
||||
pass
|
||||
|
||||
|
||||
def _variant_process(connection, attachment_id, content, pipeline_version, builder):
|
||||
try:
|
||||
connection.send(("ok", builder(attachment_id, content, pipeline_version)))
|
||||
except InvalidAttachment as exc:
|
||||
connection.send(("invalid", str(exc)))
|
||||
except Exception as exc:
|
||||
connection.send(("error", type(exc).__name__))
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _build_variants_bounded(
|
||||
attachment_id: str,
|
||||
content: bytes,
|
||||
pipeline_version: int,
|
||||
timeout_seconds: int,
|
||||
builder=build_variants,
|
||||
):
|
||||
if timeout_seconds < 1:
|
||||
raise ValueError("timeout_seconds must be positive")
|
||||
context = multiprocessing.get_context("spawn")
|
||||
receiver, sender = context.Pipe(duplex=False)
|
||||
process = context.Process(
|
||||
target=_variant_process,
|
||||
args=(sender, attachment_id, content, pipeline_version, builder),
|
||||
)
|
||||
process.start()
|
||||
sender.close()
|
||||
try:
|
||||
if not receiver.poll(timeout_seconds):
|
||||
process.terminate()
|
||||
process.join(timeout=2)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
raise ProcessingTimeout("image processing exceeded its time budget")
|
||||
try:
|
||||
result, value = receiver.recv()
|
||||
except EOFError as exc:
|
||||
raise RuntimeError("image processing process exited without a result") from exc
|
||||
process.join(timeout=2)
|
||||
if process.is_alive():
|
||||
process.terminate()
|
||||
process.join()
|
||||
if result == "invalid":
|
||||
raise InvalidAttachment(value)
|
||||
if result == "error":
|
||||
raise RuntimeError(f"image processing failed in subprocess ({value})")
|
||||
return value
|
||||
finally:
|
||||
receiver.close()
|
||||
if process.is_alive():
|
||||
process.terminate()
|
||||
process.join()
|
||||
|
||||
|
||||
def _job(payload: bytes):
|
||||
value = json.loads(payload)
|
||||
required = {
|
||||
"schema_version", "job_id", "type", "attachment_id",
|
||||
"pipeline_version", "attempt", "created_at",
|
||||
}
|
||||
if not isinstance(value, dict) or set(value).difference(required | {"traceparent", "tracestate"}):
|
||||
raise ValueError("invalid job fields")
|
||||
if not required.issubset(value) or value["schema_version"] != 1 or value["type"] != "attachment.process.v1":
|
||||
raise ValueError("invalid job schema")
|
||||
uuid.UUID(value["job_id"])
|
||||
uuid.UUID(value["attachment_id"])
|
||||
if not isinstance(value["pipeline_version"], int) or value["pipeline_version"] < 1:
|
||||
raise ValueError("invalid pipeline version")
|
||||
if not isinstance(value["attempt"], int) or value["attempt"] < 1:
|
||||
raise ValueError("invalid job attempt")
|
||||
return value
|
||||
|
||||
|
||||
def _process(
|
||||
store: Store,
|
||||
job: dict,
|
||||
fault_injector: Optional[Callable[[str], None]] = None,
|
||||
) -> str:
|
||||
def inject(point: str) -> None:
|
||||
if fault_injector is not None:
|
||||
fault_injector(point)
|
||||
|
||||
attachment_id = job["attachment_id"]
|
||||
row = store.claim_attachment_job(
|
||||
attachment_id,
|
||||
job["job_id"],
|
||||
job["pipeline_version"],
|
||||
job["attempt"],
|
||||
JOB_TIMEOUT_SECONDS + LEASE_NETWORK_BUDGET_SECONDS,
|
||||
)
|
||||
if row is None:
|
||||
LOGGER.info("job is duplicate, stale, terminal, or already leased: %s", job["job_id"])
|
||||
return "skipped"
|
||||
|
||||
try:
|
||||
inject("after_claim")
|
||||
with tracer().start_as_current_span("attachment.read_staging"):
|
||||
content = store.objects.get(row["staging_key"], row["size_bytes"])
|
||||
if hashlib.sha256(content).hexdigest() != row["sha256"].strip():
|
||||
raise InvalidAttachment("checksum_mismatch")
|
||||
variants = _build_variants_bounded(
|
||||
attachment_id,
|
||||
content,
|
||||
job["pipeline_version"],
|
||||
JOB_TIMEOUT_SECONDS,
|
||||
)
|
||||
inject("before_original_put")
|
||||
with tracer().start_as_current_span("attachment.write_original"):
|
||||
store.objects.put(row["object_key"], content, row["content_type"], len(content))
|
||||
inject("after_original_put")
|
||||
persisted = []
|
||||
for variant in variants:
|
||||
data = variant.pop("content")
|
||||
inject(f"before_variant_put:{variant['name']}")
|
||||
with tracer().start_as_current_span("attachment.write_variant"):
|
||||
store.objects.put(variant["object_key"], data, variant["content_type"], len(data))
|
||||
inject(f"after_variant_put:{variant['name']}")
|
||||
persisted.append(variant)
|
||||
inject("before_commit")
|
||||
with tracer().start_as_current_span("attachment.commit_ready"):
|
||||
completed = store.complete_attachment_job(
|
||||
attachment_id,
|
||||
job["job_id"],
|
||||
job["pipeline_version"],
|
||||
job["attempt"],
|
||||
persisted,
|
||||
)
|
||||
if not completed:
|
||||
LOGGER.warning("job lease was superseded before completion: %s", job["job_id"])
|
||||
return "skipped"
|
||||
inject("after_commit")
|
||||
try:
|
||||
store.objects.delete(row["staging_key"])
|
||||
except (BotoCoreError, ClientError, OSError):
|
||||
LOGGER.exception("completed attachment staging cleanup failed: %s", attachment_id)
|
||||
LOGGER.info("attachment processing completed: %s", attachment_id)
|
||||
return "success"
|
||||
except InvalidAttachment as exc:
|
||||
carrier = {}
|
||||
propagate.inject(carrier)
|
||||
store.fail_attachment_job(
|
||||
attachment_id, job["job_id"], job["pipeline_version"], job["attempt"],
|
||||
MAX_ATTEMPTS, str(exc), None, carrier.get("traceparent"), carrier.get("tracestate"),
|
||||
)
|
||||
try:
|
||||
store.objects.delete(row["staging_key"])
|
||||
except (BotoCoreError, ClientError, OSError):
|
||||
LOGGER.exception("failed attachment staging cleanup failed: %s", attachment_id)
|
||||
LOGGER.warning("attachment permanently failed: %s (%s)", attachment_id, exc)
|
||||
return "failed"
|
||||
except Exception as exc:
|
||||
delay = min(60.0, 2 ** max(0, job["attempt"] - 1)) * random.uniform(0.75, 1.25)
|
||||
carrier = {}
|
||||
propagate.inject(carrier)
|
||||
store.fail_attachment_job(
|
||||
attachment_id, job["job_id"], job["pipeline_version"], job["attempt"],
|
||||
MAX_ATTEMPTS, "processing_failed", delay, carrier.get("traceparent"), carrier.get("tracestate"),
|
||||
)
|
||||
LOGGER.exception("attachment processing attempt failed: %s (%s)", attachment_id, type(exc).__name__)
|
||||
return "failed"
|
||||
|
||||
|
||||
def handle_delivery(
|
||||
store: Store,
|
||||
channel: pika.adapters.blocking_connection.BlockingChannel,
|
||||
method,
|
||||
body: bytes,
|
||||
fault_injector: Optional[Callable[[str], None]] = None,
|
||||
) -> None:
|
||||
try:
|
||||
job = _job(body)
|
||||
except (ValueError, TypeError, json.JSONDecodeError):
|
||||
LOGGER.exception("invalid broker job rejected")
|
||||
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
|
||||
return
|
||||
parent_context = propagate.extract(
|
||||
{key: job[key] for key in ("traceparent", "tracestate") if key in job}
|
||||
)
|
||||
started = time.perf_counter()
|
||||
created_at = datetime.fromisoformat(job["created_at"].replace("Z", "+00:00"))
|
||||
with tracer().start_as_current_span(
|
||||
"attachment.process",
|
||||
context=parent_context,
|
||||
kind=SpanKind.CONSUMER,
|
||||
attributes={"messaging.destination.name": QUEUE_NAME, "messaging.operation.type": "process"},
|
||||
) as span:
|
||||
worker_started()
|
||||
try:
|
||||
outcome = _process(store, job, fault_injector)
|
||||
if outcome == "failed":
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
if outcome != "skipped":
|
||||
elapsed = time.perf_counter() - started
|
||||
ready_duration = (
|
||||
max(0.0, datetime.now(timezone.utc).timestamp() - created_at.timestamp())
|
||||
if outcome == "success"
|
||||
else None
|
||||
)
|
||||
record_job(outcome, elapsed, ready_duration)
|
||||
finally:
|
||||
worker_stopped()
|
||||
if fault_injector is not None:
|
||||
fault_injector("before_ack")
|
||||
channel.basic_ack(delivery_tag=method.delivery_tag)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if MAX_ATTEMPTS < 1 or JOB_TIMEOUT_SECONDS < 1 or WORKER_CONCURRENCY < 1:
|
||||
raise RuntimeError("Worker limits must be positive")
|
||||
initialize(os.getenv("OTEL_SERVICE_NAME", "messenger-worker"))
|
||||
store = Store()
|
||||
store.open()
|
||||
start_runtime_metrics(store, WORKER_CONCURRENCY)
|
||||
connection = None
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
connection = connect()
|
||||
channel = connection.channel()
|
||||
declare_queues(channel)
|
||||
channel.basic_qos(prefetch_count=WORKER_CONCURRENCY)
|
||||
|
||||
def on_message(ch, method, properties, body):
|
||||
handle_delivery(store, ch, method, body)
|
||||
|
||||
channel.basic_consume(queue=QUEUE_NAME, on_message_callback=on_message, auto_ack=False)
|
||||
LOGGER.info("worker consuming durable attachment queue")
|
||||
channel.start_consuming()
|
||||
except (OSError, pika.exceptions.AMQPError, psycopg.Error):
|
||||
LOGGER.exception("worker connection failed")
|
||||
time.sleep(2)
|
||||
finally:
|
||||
if connection is not None and connection.is_open:
|
||||
connection.close()
|
||||
connection = None
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user