forked from mtusi2026/mtusi2026lab5
lab5: async attachment pipeline (RabbitMQ + worker), thumbnail/crop/optimized, outbox relay, lease, idempotent replay (grade 4)
This commit is contained in:
Executable
+114
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
import psycopg
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||
|
||||
from .db import transaction
|
||||
|
||||
_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
try:
|
||||
_hasher.verify(password_hash, password)
|
||||
return True
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _ttl_seconds() -> int:
|
||||
return int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
|
||||
def _generate_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def _token_hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def create_session(user_id: str) -> dict:
|
||||
token = _generate_token()
|
||||
ttl = _ttl_seconds()
|
||||
expires_at = _now() + timedelta(seconds=ttl)
|
||||
token_hash = _token_hash(token)
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
""",
|
||||
(token_hash, user_id, expires_at, _now()),
|
||||
)
|
||||
return {"token": token, "expires_at": expires_at}
|
||||
|
||||
|
||||
def get_user_id_by_token(token: str) -> Optional[str]:
|
||||
from . import cache
|
||||
|
||||
token_hash = _token_hash(token)
|
||||
|
||||
if cache.is_revoked(token_hash):
|
||||
return None
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT user_id, expires_at
|
||||
FROM sessions
|
||||
WHERE token_hash = %s
|
||||
""",
|
||||
(token_hash,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if row["expires_at"] <= _now():
|
||||
return None
|
||||
return str(row["user_id"])
|
||||
|
||||
|
||||
def revoke_session(token: str) -> bool:
|
||||
from . import cache
|
||||
|
||||
token_hash = _token_hash(token)
|
||||
ttl = _ttl_seconds()
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT expires_at FROM sessions WHERE token_hash = %s",
|
||||
(token_hash,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is not None:
|
||||
remaining = int((row["expires_at"] - _now()).total_seconds())
|
||||
if remaining > 0:
|
||||
ttl = remaining
|
||||
cur.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = %s",
|
||||
(token_hash,),
|
||||
)
|
||||
deleted = cur.rowcount > 0
|
||||
|
||||
if deleted:
|
||||
cache.mark_revoked(token_hash, ttl)
|
||||
return deleted
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from typing import Callable, Optional
|
||||
|
||||
import pika
|
||||
from pika.exceptions import AMQPConnectionError
|
||||
|
||||
log = logging.getLogger("messenger.broker")
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
DLQ = "attachment.process.v1.dlq"
|
||||
|
||||
|
||||
def _url() -> str:
|
||||
url = os.environ.get("BROKER_URL")
|
||||
if not url:
|
||||
raise RuntimeError("BROKER_URL environment variable is required")
|
||||
return url
|
||||
|
||||
|
||||
def _connect() -> pika.BlockingConnection:
|
||||
params = pika.URLParameters(_url())
|
||||
params.heartbeat = 30
|
||||
params.blocked_connection_timeout = 5
|
||||
return pika.BlockingConnection(params)
|
||||
|
||||
|
||||
def _declare(channel: pika.channel.Channel) -> None:
|
||||
# DLQ
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
# Основная очередь с DLX на DLQ
|
||||
channel.queue_declare(
|
||||
queue=QUEUE,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-dead-letter-exchange": "",
|
||||
"x-dead-letter-routing-key": DLQ,
|
||||
"x-max-priority": 5,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def publish_job(job: dict) -> None:
|
||||
body = json.dumps(job, ensure_ascii=False).encode("utf-8")
|
||||
try:
|
||||
conn = _connect()
|
||||
except AMQPConnectionError as exc:
|
||||
raise RuntimeError(f"broker unavailable: {exc}") from exc
|
||||
try:
|
||||
ch = conn.channel()
|
||||
_declare(ch)
|
||||
ch.confirm_delivery()
|
||||
ch.basic_publish(
|
||||
exchange="",
|
||||
routing_key=QUEUE,
|
||||
body=body,
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2, # persistent
|
||||
content_type="application/json",
|
||||
message_id=job["job_id"],
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
log.info("published job %s for attachment %s", job["job_id"], job["attachment_id"])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def consume(handler: Callable[[dict], None], prefetch: int = 2) -> None:
|
||||
conn = _connect()
|
||||
ch = conn.channel()
|
||||
_declare(ch)
|
||||
ch.basic_qos(prefetch_count=prefetch)
|
||||
|
||||
def callback(ch_, method, properties, body):
|
||||
try:
|
||||
job = json.loads(body)
|
||||
except Exception as exc:
|
||||
log.error("invalid job payload: %s", exc)
|
||||
ch_.basic_nack(method.delivery_tag, requeue=False)
|
||||
return
|
||||
try:
|
||||
handler(job)
|
||||
ch_.basic_ack(method.delivery_tag)
|
||||
except Exception as exc:
|
||||
log.exception("job failed: %s", exc)
|
||||
ch_.basic_nack(method.delivery_tag, requeue=False)
|
||||
|
||||
ch.basic_consume(queue=QUEUE, on_message_callback=callback)
|
||||
log.info("worker started, queue=%s prefetch=%d", QUEUE, prefetch)
|
||||
try:
|
||||
ch.start_consuming()
|
||||
except KeyboardInterrupt:
|
||||
ch.stop_consuming()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def publish_dlq(job: dict, error: str) -> None:
|
||||
body = json.dumps(
|
||||
{"job": job, "error": error, "failed_at": job.get("created_at")},
|
||||
ensure_ascii=False,
|
||||
).encode("utf-8")
|
||||
conn = _connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.queue_declare(queue=DLQ, durable=True)
|
||||
ch.basic_publish(
|
||||
exchange="",
|
||||
routing_key=DLQ,
|
||||
body=body,
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
),
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
import redis
|
||||
|
||||
log = logging.getLogger("messenger.cache")
|
||||
|
||||
_client: Optional[redis.Redis] = None
|
||||
_failures: int = 0
|
||||
_MAX_FAILURES_BEFORE_DISABLE: int = 3
|
||||
|
||||
|
||||
def _cache_url() -> Optional[str]:
|
||||
return os.environ.get("CACHE_URL")
|
||||
|
||||
|
||||
def init_cache() -> None:
|
||||
global _client, _failures
|
||||
url = _cache_url()
|
||||
if not url:
|
||||
log.warning("CACHE_URL not set; running without cache")
|
||||
_client = None
|
||||
return
|
||||
try:
|
||||
client = redis.Redis.from_url(
|
||||
url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1.0,
|
||||
socket_timeout=1.0,
|
||||
)
|
||||
client.ping()
|
||||
_client = client
|
||||
_failures = 0
|
||||
log.info("cache connected")
|
||||
except Exception as exc:
|
||||
log.warning("cache unavailable at startup: %s; running in degraded mode", exc)
|
||||
_client = None
|
||||
|
||||
|
||||
def close_cache() -> None:
|
||||
global _client
|
||||
if _client is not None:
|
||||
try:
|
||||
_client.close()
|
||||
except Exception:
|
||||
pass
|
||||
_client = None
|
||||
|
||||
|
||||
def _note_failure() -> None:
|
||||
global _client, _failures
|
||||
_failures += 1
|
||||
if _failures >= _MAX_FAILURES_BEFORE_DISABLE and _client is not None:
|
||||
log.warning(
|
||||
"cache disabled after %d consecutive failures; running in degraded mode",
|
||||
_failures,
|
||||
)
|
||||
try:
|
||||
_client.close()
|
||||
except Exception:
|
||||
pass
|
||||
_client = None
|
||||
|
||||
|
||||
def _note_success() -> None:
|
||||
global _failures
|
||||
_failures = 0
|
||||
|
||||
|
||||
def is_available() -> bool:
|
||||
return _client is not None
|
||||
|
||||
|
||||
def mark_revoked(token_hash: str, ttl_seconds: int) -> None:
|
||||
if _client is None:
|
||||
log.warning(
|
||||
"cache unavailable; revocation not recorded in Redis "
|
||||
"(Postgres is the source of truth, next request will 401)"
|
||||
)
|
||||
return
|
||||
if ttl_seconds <= 0:
|
||||
return
|
||||
try:
|
||||
_client.setex(f"revoked:{token_hash}", ttl_seconds, "1")
|
||||
_note_success()
|
||||
except Exception as exc:
|
||||
log.warning("mark_revoked failed: %s", exc)
|
||||
_note_failure()
|
||||
|
||||
|
||||
def is_revoked(token_hash: str) -> bool:
|
||||
if _client is None:
|
||||
return False
|
||||
try:
|
||||
exists = _client.exists(f"revoked:{token_hash}")
|
||||
_note_success()
|
||||
return exists == 1
|
||||
except Exception as exc:
|
||||
log.warning("is_revoked failed: %s", exc)
|
||||
_note_failure()
|
||||
return False
|
||||
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from typing import Iterator
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
_pool: ConnectionPool | None = None
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
url = os.environ.get("DATABASE_URL")
|
||||
if not url:
|
||||
raise RuntimeError("DATABASE_URL environment variable is required")
|
||||
return url
|
||||
|
||||
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
def init_pool(min_size: int = 1, max_size: int = 10) -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
return
|
||||
|
||||
dsn = _database_url()
|
||||
sep = "&" if "?" in dsn else "?"
|
||||
dsn_with_opts = (
|
||||
dsn
|
||||
+ sep
|
||||
+ "options="
|
||||
+ "-c%20statement_timeout%3D5000"
|
||||
+ "%20-c%20lock_timeout%3D3000"
|
||||
+ "%20-c%20idle_in_transaction_session_timeout%3D10000"
|
||||
)
|
||||
|
||||
_pool = ConnectionPool(
|
||||
conninfo=dsn_with_opts,
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
kwargs={"row_factory": dict_row},
|
||||
open=True,
|
||||
timeout=5.0,
|
||||
check=ConnectionPool.check_connection,
|
||||
max_lifetime=120,
|
||||
max_idle=60,
|
||||
)
|
||||
|
||||
|
||||
def close_pool() -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
_pool.close()
|
||||
_pool = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection() -> Iterator[psycopg.Connection]:
|
||||
if _pool is None:
|
||||
raise RuntimeError("Connection pool is not initialized")
|
||||
with _pool.connection() as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
@contextmanager
|
||||
def transaction() -> Iterator[psycopg.Connection]:
|
||||
with connection() as conn:
|
||||
with conn.transaction():
|
||||
yield conn
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Callable
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from .instance import INSTANCE_ID
|
||||
from .store import ApiError
|
||||
|
||||
|
||||
REQUEST_ID_HEADER = "X-Request-Id"
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
rid = request.headers.get(REQUEST_ID_HEADER) or uuid.uuid4().hex
|
||||
request.state.request_id = rid
|
||||
response = await call_next(request)
|
||||
response.headers[REQUEST_ID_HEADER] = rid
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
def _envelope(code: str, message: str, request_id: str) -> dict:
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
|
||||
|
||||
def _rid(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", None) or uuid.uuid4().hex
|
||||
|
||||
|
||||
def _with_headers(response: JSONResponse, request: Request, status: int) -> JSONResponse:
|
||||
rid = _rid(request)
|
||||
response.headers[REQUEST_ID_HEADER] = rid
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
if status == 401:
|
||||
scheme = "Bearer"
|
||||
if request.url.path == "/api/v1/auth/sessions":
|
||||
scheme = "Basic"
|
||||
response.headers["WWW-Authenticate"] = f'{scheme} realm="messenger"'
|
||||
return response
|
||||
|
||||
|
||||
async def api_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
assert isinstance(exc, ApiError)
|
||||
response = JSONResponse(
|
||||
status_code=exc.status,
|
||||
content=_envelope(exc.code, exc.message, _rid(request)),
|
||||
)
|
||||
return _with_headers(response, request, exc.status)
|
||||
|
||||
|
||||
async def validation_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
response = JSONResponse(
|
||||
status_code=400,
|
||||
content=_envelope("invalid_request", "Request validation failed", _rid(request)),
|
||||
)
|
||||
return _with_headers(response, request, 400)
|
||||
|
||||
|
||||
async def json_decode_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
response = JSONResponse(
|
||||
status_code=400,
|
||||
content=_envelope("invalid_request", "Malformed JSON", _rid(request)),
|
||||
)
|
||||
return _with_headers(response, request, 400)
|
||||
|
||||
|
||||
async def unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
import logging
|
||||
logging.getLogger("messenger").exception(
|
||||
"unhandled error on %s %s", request.method, request.url.path
|
||||
)
|
||||
response = JSONResponse(
|
||||
status_code=500,
|
||||
content=_envelope("internal_error", "Internal error", _rid(request)),
|
||||
)
|
||||
return _with_headers(response, request, 500)
|
||||
@@ -0,0 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import uuid
|
||||
|
||||
INSTANCE_ID: str = (
|
||||
os.environ.get("INSTANCE_ID")
|
||||
or socket.gethostname()
|
||||
or uuid.uuid4().hex[:8]
|
||||
)
|
||||
Executable
+467
@@ -0,0 +1,467 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional
|
||||
import uuid
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from . import auth
|
||||
from .db import close_pool, init_pool
|
||||
from . import storage
|
||||
from . import broker, storage
|
||||
from .errors import (
|
||||
RequestIdMiddleware,
|
||||
_envelope,
|
||||
_rid,
|
||||
api_error_handler,
|
||||
json_decode_handler,
|
||||
unhandled_handler,
|
||||
validation_handler,
|
||||
)
|
||||
from .schemas import (
|
||||
Chat,
|
||||
ChatPage,
|
||||
CreateChat,
|
||||
CreateMessage,
|
||||
CreateUser,
|
||||
Health,
|
||||
Message,
|
||||
MessagePage,
|
||||
Session,
|
||||
User,
|
||||
Attachment,
|
||||
)
|
||||
from .store import (
|
||||
ApiError,
|
||||
BadRequest,
|
||||
Conflict,
|
||||
NotFound,
|
||||
PayloadTooLarge,
|
||||
Unavailable,
|
||||
UnsupportedMediaType,
|
||||
Unauthorized,
|
||||
store,
|
||||
iso,
|
||||
)
|
||||
from .cache import close_cache, init_cache
|
||||
|
||||
from .instance import INSTANCE_ID
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
|
||||
)
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool()
|
||||
init_cache()
|
||||
storage.init_storage()
|
||||
log.info("instance_id=%s", INSTANCE_ID)
|
||||
log.info("db pool, cache, storage initialized")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
close_cache()
|
||||
close_pool()
|
||||
log.info("db pool and cache closed")
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger lab2", version="1.2.0", lifespan=lifespan)
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
|
||||
app.add_exception_handler(ApiError, api_error_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_handler)
|
||||
app.add_exception_handler(Exception, unhandled_handler)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def _http_exc(request: Request, exc: StarletteHTTPException):
|
||||
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=_envelope(code, str(exc.detail), _rid(request)),
|
||||
)
|
||||
|
||||
# ---------- утилиты валидации ----------
|
||||
|
||||
def valid_uuid(value: str, name: str = "id") -> str:
|
||||
try:
|
||||
UUID(value)
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise BadRequest(f"Invalid {name}")
|
||||
return value
|
||||
|
||||
# ---------- зависимости ----------
|
||||
|
||||
def _parse_basic(header_value: str) -> tuple[str, str]:
|
||||
import base64
|
||||
if not header_value.lower().startswith("basic "):
|
||||
raise Unauthorized("Basic authentication required")
|
||||
try:
|
||||
raw = base64.b64decode(header_value.split(" ", 1)[1], validate=True)
|
||||
decoded = raw.decode("utf-8")
|
||||
username, _, password = decoded.partition(":")
|
||||
if not username:
|
||||
raise ValueError("empty username")
|
||||
return username, password
|
||||
except Exception:
|
||||
raise Unauthorized("Invalid Basic credentials") from None
|
||||
|
||||
|
||||
def _bearer_token(authorization: Optional[str]) -> str:
|
||||
if not authorization:
|
||||
raise Unauthorized("Missing Authorization header")
|
||||
parts = authorization.split(" ", 1)
|
||||
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||
raise Unauthorized("Bearer token required")
|
||||
token = parts[1].strip()
|
||||
if not token:
|
||||
raise Unauthorized("Empty bearer token")
|
||||
return token
|
||||
|
||||
|
||||
def current_user_id(
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
) -> str:
|
||||
token = _bearer_token(authorization)
|
||||
user_id = auth.get_user_id_by_token(token)
|
||||
if user_id is None:
|
||||
raise Unauthorized("Invalid or expired token")
|
||||
return user_id
|
||||
|
||||
|
||||
# ---------- health ----------
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
def liveness():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Health)
|
||||
def readiness(request: Request):
|
||||
try:
|
||||
from .db import transaction
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
except Exception:
|
||||
rid = _rid(request)
|
||||
response = JSONResponse(
|
||||
status_code=503,
|
||||
content=_envelope("unavailable", "Database unavailable", rid),
|
||||
)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
try:
|
||||
storage.check_bucket()
|
||||
except Exception:
|
||||
rid = _rid(request)
|
||||
response = JSONResponse(
|
||||
status_code=503,
|
||||
content=_envelope("unavailable", "S3 unavailable", rid),
|
||||
)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# ---------- users ----------
|
||||
|
||||
@app.post("/api/v1/users", status_code=201, response_model=User)
|
||||
def register_user(body: CreateUser):
|
||||
password_hash = auth.hash_password(body.password)
|
||||
return store.create_user(body.username, body.display_name, password_hash)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
def me(user_id: str = Depends(current_user_id)):
|
||||
user = store.get_user(user_id)
|
||||
if user is None:
|
||||
raise Unauthorized("User not found")
|
||||
return user
|
||||
|
||||
|
||||
# ---------- auth ----------
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201, response_model=Session)
|
||||
def create_session(authorization: Optional[str] = Header(default=None)):
|
||||
username, password = _parse_basic(authorization or "")
|
||||
row = store.get_user_by_username(username)
|
||||
if row is None or not auth.verify_password(password, row["password_hash"]):
|
||||
raise Unauthorized("Invalid credentials")
|
||||
session = auth.create_session(str(row["id"]))
|
||||
user = store.get_user(str(row["id"]))
|
||||
if user is None:
|
||||
raise Unauthorized("User not found")
|
||||
return {
|
||||
"token": session["token"],
|
||||
"token_type": "Bearer",
|
||||
"expires_at": iso(session["expires_at"]),
|
||||
"user": user,
|
||||
}
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(authorization: Optional[str] = Header(default=None)):
|
||||
token = _bearer_token(authorization)
|
||||
user_id = auth.get_user_id_by_token(token)
|
||||
if user_id is None:
|
||||
raise Unauthorized("Invalid or expired token")
|
||||
auth.revoke_session(token)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
# ---------- chats ----------
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201, response_model=Chat)
|
||||
def create_chat(body: CreateChat, user_id: str = Depends(current_user_id)):
|
||||
return store.create_chat(body.title, body.member_ids, user_id)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
user_id: str = Depends(current_user_id),
|
||||
):
|
||||
items, next_cursor = store.list_chats(user_id, limit, cursor)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
def get_chat(chat_id: str, user_id: str = Depends(current_user_id)):
|
||||
chat_id = valid_uuid(chat_id, "chat_id")
|
||||
chat = store.get_chat(chat_id, user_id)
|
||||
if chat is None:
|
||||
raise NotFound()
|
||||
return chat
|
||||
|
||||
|
||||
# ---------- messages ----------
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201, response_model=Message)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessage,
|
||||
user_id: str = Depends(current_user_id),
|
||||
idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key"),
|
||||
):
|
||||
chat_id = valid_uuid(chat_id, "chat_id")
|
||||
if not idempotency_key:
|
||||
raise BadRequest("Idempotency-Key header is required")
|
||||
if not re.match(r"^[A-Za-z0-9._:-]{1,128}$", idempotency_key):
|
||||
raise BadRequest("Invalid Idempotency-Key format")
|
||||
|
||||
message, status = store.add_message(
|
||||
chat_id, user_id, body.text, idempotency_key, body.attachment_ids
|
||||
)
|
||||
if status != 201:
|
||||
raise Conflict(f"Idempotency error: {status}")
|
||||
return message
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
user_id: str = Depends(current_user_id),
|
||||
):
|
||||
chat_id = valid_uuid(chat_id, "chat_id")
|
||||
items, next_cursor = store.list_messages(chat_id, user_id, limit, cursor)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
# ---------- attachments (lab4) ----------
|
||||
|
||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
ALLOWED_MIMES = {"image/png", "image/jpeg"}
|
||||
|
||||
from PIL import Image as _PILImage
|
||||
_PILImage.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
|
||||
|
||||
|
||||
import unicodedata
|
||||
|
||||
def _validate_filename(filename: str) -> None:
|
||||
if not filename:
|
||||
raise BadRequest("filename is required")
|
||||
if len(filename) > 255:
|
||||
raise BadRequest("filename too long")
|
||||
for ch in filename:
|
||||
if ch in ("/", "\\"):
|
||||
raise BadRequest("filename contains forbidden characters")
|
||||
if unicodedata.category(ch) == "Cc":
|
||||
raise BadRequest("filename contains control characters")
|
||||
|
||||
|
||||
def _sniff_mime(data: bytes) -> str:
|
||||
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return "image/png"
|
||||
if data.startswith(b"\xff\xd8\xff"):
|
||||
return "image/jpeg"
|
||||
raise UnsupportedMediaType("Only PNG and JPEG are supported")
|
||||
|
||||
|
||||
def _validate_image(data: bytes) -> tuple[int, int]:
|
||||
from PIL import Image
|
||||
import io
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
w, h = img.size
|
||||
if w * h > MAX_IMAGE_PIXELS:
|
||||
raise PayloadTooLarge(
|
||||
f"Image too large: {w*h} pixels (max {MAX_IMAGE_PIXELS})"
|
||||
)
|
||||
img.load()
|
||||
except PayloadTooLarge:
|
||||
raise
|
||||
except Image.DecompressionBombError:
|
||||
raise PayloadTooLarge(
|
||||
f"Image too large (decompression bomb protection)"
|
||||
) from None
|
||||
except Exception:
|
||||
raise UnsupportedMediaType("Image is corrupted or unsupported") from None
|
||||
return w, h
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/attachments",
|
||||
status_code=202,
|
||||
response_model=Attachment,
|
||||
)
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
filename: str = Query(..., min_length=1, max_length=255),
|
||||
user_id: str = Depends(current_user_id),
|
||||
):
|
||||
chat_id = valid_uuid(chat_id, "chat_id")
|
||||
_validate_filename(filename)
|
||||
|
||||
content_length = request.headers.get("content-length")
|
||||
if content_length is not None:
|
||||
try:
|
||||
if int(content_length) > MAX_UPLOAD_BYTES:
|
||||
raise PayloadTooLarge(
|
||||
f"File too large: {content_length} bytes (max {MAX_UPLOAD_BYTES})"
|
||||
)
|
||||
except ValueError:
|
||||
raise BadRequest("Invalid Content-Length") from None
|
||||
|
||||
client_ct = (request.headers.get("content-type") or "").split(";")[0].strip().lower()
|
||||
if client_ct not in ALLOWED_MIMES:
|
||||
raise UnsupportedMediaType(
|
||||
f"Content-Type must be image/png or image/jpeg, got {client_ct!r}"
|
||||
)
|
||||
|
||||
body = bytearray()
|
||||
async for chunk in request.stream():
|
||||
body.extend(chunk)
|
||||
if len(body) > MAX_UPLOAD_BYTES:
|
||||
raise PayloadTooLarge(
|
||||
f"File too large: > {MAX_UPLOAD_BYTES} bytes"
|
||||
)
|
||||
data = bytes(body)
|
||||
|
||||
real_mime = _sniff_mime(data)
|
||||
|
||||
_validate_image(data)
|
||||
|
||||
ext = "png" if real_mime == "image/png" else "jpg"
|
||||
staging_key = f"staging/{uuid.uuid4().hex}.{ext}"
|
||||
try:
|
||||
sha256 = storage.put_object(staging_key, data, real_mime)
|
||||
except Exception as exc:
|
||||
import logging
|
||||
logging.getLogger("messenger").warning("S3 staging upload failed: %s", exc)
|
||||
raise Unavailable("S3 unavailable") from exc
|
||||
|
||||
try:
|
||||
attachment = store.create_attachment(
|
||||
chat_id=chat_id, owner_id=user_id, filename=filename,
|
||||
content_type=real_mime, size_bytes=len(data),
|
||||
sha256=sha256, s3_key=staging_key, staging_key=staging_key,
|
||||
status="queued",
|
||||
)
|
||||
except Exception:
|
||||
storage.delete_object(staging_key)
|
||||
raise
|
||||
|
||||
job = store.create_job(attachment["id"])
|
||||
log.info("job %s created (pending), relay will publish", job["job_id"])
|
||||
|
||||
return attachment
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/attachments/{attachment_id}",
|
||||
response_model=Attachment,
|
||||
)
|
||||
def get_attachment(
|
||||
attachment_id: str,
|
||||
user_id: str = Depends(current_user_id),
|
||||
):
|
||||
attachment_id = valid_uuid(attachment_id, "attachment_id")
|
||||
att = store.get_attachment(attachment_id, user_id)
|
||||
if att is None:
|
||||
raise NotFound()
|
||||
att.pop("s3_key", None)
|
||||
return att
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
def download_attachment(
|
||||
attachment_id: str,
|
||||
variant: str = Query(default="original"),
|
||||
user_id: str = Depends(current_user_id),
|
||||
):
|
||||
attachment_id = valid_uuid(attachment_id, "attachment_id")
|
||||
att = store.get_attachment(attachment_id, user_id)
|
||||
if att is None:
|
||||
raise NotFound()
|
||||
if att["status"] != "ready":
|
||||
raise Conflict(f"Attachment not ready: {att['status']}")
|
||||
variants_map = {
|
||||
"thumbnail": ("thumbnails/{}.jpg", "image/jpeg"),
|
||||
"crop": ("crops/{}.jpg", "image/jpeg"),
|
||||
"optimized": ("optimized/{}.webp", "image/webp"),
|
||||
}
|
||||
if variant == "original":
|
||||
s3_key = att["s3_key"]
|
||||
media_type = att["content_type"]
|
||||
elif variant in variants_map:
|
||||
found = [v for v in att["variants"] if v["name"] == variant]
|
||||
if not found:
|
||||
raise NotFound()
|
||||
pattern, media_type = variants_map[variant]
|
||||
s3_key = pattern.format(attachment_id)
|
||||
else:
|
||||
raise NotFound()
|
||||
data = storage.get_object(s3_key)
|
||||
return Response(content=data, media_type=media_type)
|
||||
|
||||
def main() -> None:
|
||||
import uvicorn
|
||||
|
||||
host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
port = int(os.environ.get("APP_PORT", "8080"))
|
||||
uvicorn.run("src.main:app", host=host, port=port, log_level="info")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from . import broker
|
||||
from .db import close_pool, init_pool, transaction
|
||||
from .store import iso
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
log = logging.getLogger("messenger.relay")
|
||||
|
||||
|
||||
def _publish_pending() -> int:
|
||||
published = 0
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at
|
||||
FROM jobs
|
||||
WHERE status = 'pending'
|
||||
ORDER BY created_at
|
||||
LIMIT 10
|
||||
FOR UPDATE SKIP LOCKED
|
||||
"""
|
||||
)
|
||||
jobs = cur.fetchall()
|
||||
for job in jobs:
|
||||
job_dict = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(job["job_id"]),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(job["attachment_id"]),
|
||||
"pipeline_version": int(job["pipeline_version"]),
|
||||
"attempt": int(job["attempt"]),
|
||||
"created_at": iso(job["created_at"]),
|
||||
}
|
||||
try:
|
||||
broker.publish_job(job_dict)
|
||||
cur.execute(
|
||||
"UPDATE jobs SET status='published', published_at=NOW() WHERE job_id=%s",
|
||||
(job["job_id"],),
|
||||
)
|
||||
published += 1
|
||||
except Exception as exc:
|
||||
log.warning("publish failed for %s: %s", job["job_id"], exc)
|
||||
return published
|
||||
|
||||
|
||||
def _reclaim_expired() -> int:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'pending', lease_until = NULL
|
||||
WHERE status = 'processing'
|
||||
AND lease_until < NOW()
|
||||
RETURNING job_id
|
||||
"""
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
init_pool()
|
||||
log.info("relay started")
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
n = _publish_pending()
|
||||
if n:
|
||||
log.info("published %d pending jobs", n)
|
||||
except Exception as exc:
|
||||
log.exception("relay iteration failed: %s", exc)
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+181
@@ -0,0 +1,181 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=False)
|
||||
|
||||
|
||||
# ---------- Users ----------
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
username: str = Field(min_length=3, max_length=32)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def _username(cls, v: str) -> str:
|
||||
if not USERNAME_RE.match(v):
|
||||
raise ValueError("username must match [a-z0-9_]{3,32}")
|
||||
return v
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def _display_name(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("display_name must not be blank")
|
||||
if len(v) > 100:
|
||||
raise ValueError("display_name too long")
|
||||
return v
|
||||
|
||||
|
||||
class User(StrictModel):
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
# ---------- Chats ----------
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: List[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def _title(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("title must not be blank")
|
||||
return v
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def _members(cls, v: List[str]) -> List[str]:
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("member_ids must be unique")
|
||||
for item in v:
|
||||
try:
|
||||
uuid.UUID(item)
|
||||
except ValueError as exc:
|
||||
raise ValueError("member_ids must be UUIDs") from exc
|
||||
return v
|
||||
|
||||
|
||||
class Chat(StrictModel):
|
||||
id: str
|
||||
title: str
|
||||
member_ids: List[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatPage(StrictModel):
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
# ---------- Attachments (lab4) ----------
|
||||
|
||||
class Variant(StrictModel):
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int = Field(ge=1)
|
||||
width: int = Field(ge=1)
|
||||
height: int = Field(ge=1)
|
||||
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
|
||||
|
||||
class Attachment(StrictModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
owner_id: str
|
||||
filename: str = Field(min_length=1, max_length=255)
|
||||
content_type: str # image/png или image/jpeg
|
||||
size_bytes: int = Field(ge=1, le=10485760)
|
||||
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
status: str # 'ready' в lab4
|
||||
variants: List[Variant] = Field(default_factory=list)
|
||||
error_code: Optional[str] = None
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
# ---------- Messages ----------
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: str = Field(default="", max_length=4000)
|
||||
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def _text(cls, v: str) -> str:
|
||||
if len(v) > 4000:
|
||||
raise ValueError("text too long")
|
||||
return v
|
||||
|
||||
@field_validator("attachment_ids")
|
||||
@classmethod
|
||||
def _attachments(cls, v: List[str]) -> List[str]:
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("attachment_ids must be unique")
|
||||
for item in v:
|
||||
try:
|
||||
uuid.UUID(item)
|
||||
except ValueError as exc:
|
||||
raise ValueError("attachment_ids must be UUIDs") from exc
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _text_or_attachment(self) -> "CreateMessage":
|
||||
has_text = bool(self.text and self.text.strip())
|
||||
has_attachment = bool(self.attachment_ids)
|
||||
if not has_text and not has_attachment:
|
||||
raise ValueError("text must be non-blank or attachment_ids must be non-empty")
|
||||
return self
|
||||
|
||||
|
||||
class Message(StrictModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: List[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class MessagePage(StrictModel):
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
# ---------- Sessions ----------
|
||||
|
||||
class Session(StrictModel):
|
||||
token: str = Field(min_length=32)
|
||||
token_type: str = Field(default="Bearer")
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
|
||||
# ---------- Misc ----------
|
||||
|
||||
class Health(StrictModel):
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class ErrorBody(StrictModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorEnvelope(StrictModel):
|
||||
error: ErrorBody
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
log = logging.getLogger("messenger.storage")
|
||||
|
||||
_client = None
|
||||
|
||||
|
||||
def _env(name: str, default: Optional[str] = None) -> str:
|
||||
value = os.environ.get(name, default)
|
||||
if value is None:
|
||||
raise RuntimeError(f"Environment variable {name} is required")
|
||||
return value
|
||||
|
||||
|
||||
def init_storage() -> None:
|
||||
global _client
|
||||
if _client is not None:
|
||||
return
|
||||
_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=_env("S3_ENDPOINT"),
|
||||
region_name=_env("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=_env("S3_ACCESS_KEY_ID"),
|
||||
aws_secret_access_key=_env("S3_SECRET_ACCESS_KEY"),
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=1.0,
|
||||
read_timeout=2.0,
|
||||
retries={"max_attempts": 1, "mode": "standard"},
|
||||
),
|
||||
)
|
||||
log.info("storage client initialized")
|
||||
|
||||
|
||||
def _bucket() -> str:
|
||||
return _env("S3_BUCKET", "messenger-attachments")
|
||||
|
||||
|
||||
def new_object_key(content_type: str) -> str:
|
||||
ext = "png" if content_type == "image/png" else "jpg"
|
||||
return f"attachments/{uuid.uuid4().hex}.{ext}"
|
||||
|
||||
|
||||
def put_object(key: str, body: bytes, content_type: str) -> str:
|
||||
if _client is None:
|
||||
raise RuntimeError("storage not initialized")
|
||||
sha256 = hashlib.sha256(body).hexdigest()
|
||||
_client.put_object(
|
||||
Bucket=_bucket(),
|
||||
Key=key,
|
||||
Body=body,
|
||||
ContentType=content_type,
|
||||
Metadata={"sha256": sha256},
|
||||
)
|
||||
return sha256
|
||||
|
||||
|
||||
def get_object(key: str) -> bytes:
|
||||
if _client is None:
|
||||
raise RuntimeError("storage not initialized")
|
||||
response = _client.get_object(Bucket=_bucket(), Key=key)
|
||||
return response["Body"].read()
|
||||
|
||||
|
||||
def delete_object(key: str) -> None:
|
||||
if _client is None:
|
||||
return
|
||||
try:
|
||||
_client.delete_object(Bucket=_bucket(), Key=key)
|
||||
except ClientError as exc:
|
||||
log.warning("failed to delete object %s: %s", key, exc)
|
||||
|
||||
|
||||
def object_exists(key: str) -> bool:
|
||||
if _client is None:
|
||||
return False
|
||||
try:
|
||||
_client.head_object(Bucket=_bucket(), Key=key)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if exc.response["Error"]["Code"] in ("404", "NoSuchKey"):
|
||||
return False
|
||||
raisev
|
||||
|
||||
|
||||
def check_bucket() -> None:
|
||||
if _client is None:
|
||||
raise RuntimeError("storage not initialized")
|
||||
_client.head_bucket(Bucket=_bucket())
|
||||
Executable
+584
@@ -0,0 +1,584 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import psycopg
|
||||
from psycopg.errors import UniqueViolation
|
||||
|
||||
from .db import transaction
|
||||
|
||||
|
||||
# ---------- ошибки ----------
|
||||
|
||||
class ApiError(Exception):
|
||||
status = 500
|
||||
code = "internal_error"
|
||||
|
||||
def __init__(self, message: str = "Internal error") -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
|
||||
class BadRequest(ApiError):
|
||||
status = 400
|
||||
code = "invalid_request"
|
||||
|
||||
|
||||
class Unauthorized(ApiError):
|
||||
status = 401
|
||||
code = "unauthorized"
|
||||
|
||||
|
||||
class NotFound(ApiError):
|
||||
status = 404
|
||||
code = "not_found"
|
||||
|
||||
|
||||
class Conflict(ApiError):
|
||||
status = 409
|
||||
code = "conflict"
|
||||
|
||||
|
||||
class PayloadTooLarge(ApiError):
|
||||
status = 413
|
||||
code = "payload_too_large"
|
||||
|
||||
|
||||
class UnsupportedMediaType(ApiError):
|
||||
status = 415
|
||||
code = "unsupported_media_type"
|
||||
|
||||
|
||||
class Unavailable(ApiError):
|
||||
status = 503
|
||||
code = "unavailable"
|
||||
|
||||
|
||||
# ---------- утилиты ----------
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def iso(dt: datetime) -> str:
|
||||
return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def _user_dict(row: dict) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _chat_dict(row: dict, member_ids: List[str]) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _message_dict(row: dict, attachment_ids: List[str]) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
"attachment_ids": attachment_ids,
|
||||
}
|
||||
|
||||
|
||||
# ---------- курсор ----------
|
||||
|
||||
def _encode_cursor(scope: str, created_at: str, item_id: str) -> str:
|
||||
payload = json.dumps(
|
||||
{"s": scope, "t": created_at, "i": item_id}, separators=(",", ":")
|
||||
).encode()
|
||||
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(scope: str, cursor: str) -> Tuple[str, str]:
|
||||
pad = "=" * (-len(cursor) % 4)
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor + pad)
|
||||
data = json.loads(raw)
|
||||
if data.get("s") != scope:
|
||||
raise ValueError("scope mismatch")
|
||||
t = data.get("t")
|
||||
i = data.get("i")
|
||||
if not isinstance(t, str) or not isinstance(i, str):
|
||||
raise ValueError("invalid cursor fields")
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
try:
|
||||
datetime.fromisoformat(t.replace("Z", "+00:00"))
|
||||
except (ValueError, TypeError):
|
||||
raise ValueError("invalid timestamp in cursor") from None
|
||||
try:
|
||||
UUID(i)
|
||||
except (ValueError, TypeError):
|
||||
raise ValueError("invalid uuid in cursor") from None
|
||||
return t, i
|
||||
except Exception as exc:
|
||||
raise BadRequest("invalid cursor") from exc
|
||||
|
||||
# ---------- Store ----------
|
||||
|
||||
class Store:
|
||||
|
||||
# ---- users ----
|
||||
|
||||
def create_user(
|
||||
self, username: str, display_name: str, password_hash: str
|
||||
) -> dict:
|
||||
uid = str(uuid.uuid4())
|
||||
now = _now()
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
""",
|
||||
(uid, username, display_name, password_hash, now),
|
||||
)
|
||||
except UniqueViolation:
|
||||
raise Conflict("username already taken") from None
|
||||
return {
|
||||
"id": uid,
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"created_at": iso(now),
|
||||
}
|
||||
|
||||
def get_user(self, user_id: str) -> Optional[dict]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
|
||||
row = cur.fetchone()
|
||||
return _user_dict(row) if row else None
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[dict]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
|
||||
row = cur.fetchone()
|
||||
return row
|
||||
|
||||
# ---- chats ----
|
||||
|
||||
def create_chat(
|
||||
self, title: str, member_ids: List[str], creator_id: str
|
||||
) -> dict:
|
||||
if creator_id not in member_ids:
|
||||
raise BadRequest("creator must be in member_ids")
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s)",
|
||||
(member_ids,),
|
||||
)
|
||||
found = {str(r["id"]) for r in cur.fetchall()}
|
||||
missing = set(member_ids) - found
|
||||
if missing:
|
||||
raise BadRequest("unknown member_id")
|
||||
|
||||
cid = str(uuid.uuid4())
|
||||
now = _now()
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(cid, title, now),
|
||||
)
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
[(cid, uid) for uid in member_ids],
|
||||
)
|
||||
return {
|
||||
"id": cid,
|
||||
"title": title,
|
||||
"member_ids": list(member_ids),
|
||||
"created_at": iso(now),
|
||||
}
|
||||
|
||||
def get_chat(self, chat_id: str, viewer_id: str) -> Optional[dict]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT c.* FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = %s AND m.user_id = %s
|
||||
""",
|
||||
(chat_id, viewer_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||
(chat_id,),
|
||||
)
|
||||
members = [str(r["user_id"]) for r in cur.fetchall()]
|
||||
return _chat_dict(row, members)
|
||||
|
||||
def list_chats(
|
||||
self, viewer_id: str, limit: int, cursor: Optional[str]
|
||||
) -> Tuple[List[dict], Optional[str]]:
|
||||
scope = "chats:" + viewer_id
|
||||
params: list = [viewer_id]
|
||||
where_cursor = ""
|
||||
if cursor:
|
||||
t, i = _decode_cursor(scope, cursor)
|
||||
where_cursor = "AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend([t, i])
|
||||
params.append(limit + 1)
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = %s {where_cursor}
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
result = []
|
||||
for row in page:
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||
(row["id"],),
|
||||
)
|
||||
members = [str(r["user_id"]) for r in cur.fetchall()]
|
||||
result.append(_chat_dict(row, members))
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = _encode_cursor(scope, iso(last["created_at"]), str(last["id"]))
|
||||
return result, next_cursor
|
||||
|
||||
# ---- messages ----
|
||||
|
||||
def add_message(
|
||||
self,
|
||||
chat_id: str,
|
||||
sender_id: str,
|
||||
text: str,
|
||||
idempotency_key: str,
|
||||
attachment_ids: Optional[List[str]] = None,
|
||||
) -> tuple[dict, int]:
|
||||
attachment_ids = attachment_ids or []
|
||||
request_hash = hashlib.sha256(
|
||||
json.dumps(
|
||||
{"text": text, "attachment_ids": attachment_ids},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
).encode("utf-8")
|
||||
).hexdigest()
|
||||
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
method = "POST"
|
||||
|
||||
import time as _time
|
||||
for attempt in range(5):
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, sender_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise NotFound()
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT request_hash, response_status, response_body
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = %s AND method = %s AND path = %s AND key = %s
|
||||
""",
|
||||
(sender_id, method, path, idempotency_key),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is not None:
|
||||
if row["request_hash"] != request_hash:
|
||||
raise Conflict(
|
||||
"idempotency key reused with different body"
|
||||
)
|
||||
return row["response_body"], row["response_status"]
|
||||
|
||||
if attachment_ids:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id FROM attachments
|
||||
WHERE id = ANY(%s) AND chat_id = %s
|
||||
""",
|
||||
(attachment_ids, chat_id),
|
||||
)
|
||||
found = {str(r["id"]) for r in cur.fetchall()}
|
||||
missing = set(attachment_ids) - found
|
||||
if missing:
|
||||
raise NotFound()
|
||||
|
||||
mid = str(uuid.uuid4())
|
||||
now = _now()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
""",
|
||||
(mid, chat_id, sender_id, text, now),
|
||||
)
|
||||
|
||||
if attachment_ids:
|
||||
cur.executemany(
|
||||
"""
|
||||
INSERT INTO message_attachments
|
||||
(message_id, attachment_id, position)
|
||||
VALUES (%s, %s, %s)
|
||||
""",
|
||||
[(mid, aid, pos) for pos, aid in enumerate(attachment_ids)],
|
||||
)
|
||||
|
||||
message = {
|
||||
"id": mid,
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": text,
|
||||
"created_at": iso(now),
|
||||
"attachment_ids": list(attachment_ids),
|
||||
}
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, path, key, request_hash,
|
||||
response_status, response_body, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s, 201, %s, %s)
|
||||
""",
|
||||
(
|
||||
sender_id, method, path, idempotency_key,
|
||||
request_hash,
|
||||
json.dumps(message, ensure_ascii=False),
|
||||
now,
|
||||
),
|
||||
)
|
||||
return message, 201
|
||||
except UniqueViolation:
|
||||
_time.sleep(0.05)
|
||||
continue
|
||||
|
||||
raise Conflict("idempotency key in progress, please retry")
|
||||
|
||||
def list_messages(
|
||||
self,
|
||||
chat_id: str,
|
||||
viewer_id: str,
|
||||
limit: int,
|
||||
cursor: Optional[str],
|
||||
) -> Tuple[List[dict], Optional[str]]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, viewer_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise NotFound()
|
||||
|
||||
scope = "chat:" + chat_id
|
||||
params: list = [chat_id]
|
||||
where_cursor = ""
|
||||
if cursor:
|
||||
t, i = _decode_cursor(scope, cursor)
|
||||
where_cursor = "AND (created_at, id) > (%s, %s)"
|
||||
params.extend([t, i])
|
||||
params.append(limit + 1)
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s {where_cursor}
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
message_ids = [str(r["id"]) for r in rows]
|
||||
attachments_by_message: dict = {}
|
||||
if message_ids:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY(%s)
|
||||
ORDER BY position
|
||||
""",
|
||||
(message_ids,),
|
||||
)
|
||||
for r in cur.fetchall():
|
||||
attachments_by_message.setdefault(
|
||||
str(r["message_id"]), []
|
||||
).append(str(r["attachment_id"]))
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
result = []
|
||||
for r in page:
|
||||
result.append(_message_dict(
|
||||
r, attachments_by_message.get(str(r["id"]), [])
|
||||
))
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = _encode_cursor(scope, iso(last["created_at"]), str(last["id"]))
|
||||
return result, next_cursor
|
||||
|
||||
# ---- attachments ----
|
||||
|
||||
def create_attachment(
|
||||
self,
|
||||
chat_id: str,
|
||||
owner_id: str,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
s3_key: str,
|
||||
staging_key: Optional[str] = None,
|
||||
status: str = "queued",
|
||||
) -> dict:
|
||||
aid = str(uuid.uuid4())
|
||||
now = _now()
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, owner_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise NotFound()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, s3_key, staging_key,
|
||||
status, error_code, attempt, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NULL, 0, %s, %s)
|
||||
""",
|
||||
(aid, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, s3_key, staging_key,
|
||||
status, now, now),
|
||||
)
|
||||
return {
|
||||
"id": aid,
|
||||
"chat_id": chat_id,
|
||||
"owner_id": owner_id,
|
||||
"filename": filename,
|
||||
"content_type": content_type,
|
||||
"size_bytes": size_bytes,
|
||||
"sha256": sha256,
|
||||
"status": status,
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": iso(now),
|
||||
"updated_at": iso(now),
|
||||
}
|
||||
|
||||
def create_job(self, attachment_id: str, pipeline_version: int = 1) -> dict:
|
||||
jid = str(uuid.uuid4())
|
||||
now = _now()
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO jobs
|
||||
(job_id, attachment_id, pipeline_version,
|
||||
attempt, status, created_at)
|
||||
VALUES (%s, %s, %s, 1, 'pending', %s)
|
||||
""",
|
||||
(jid, attachment_id, pipeline_version, now),
|
||||
)
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"job_id": jid,
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": attachment_id,
|
||||
"pipeline_version": pipeline_version,
|
||||
"attempt": 1,
|
||||
"created_at": iso(now),
|
||||
}
|
||||
|
||||
def mark_job_published(self, job_id: str) -> None:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE jobs SET status='published', published_at=NOW() "
|
||||
"WHERE job_id=%s",
|
||||
(job_id,),
|
||||
)
|
||||
|
||||
def get_attachment(
|
||||
self, attachment_id: str, viewer_id: str
|
||||
) -> Optional[dict]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT a.*
|
||||
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, viewer_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
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"],
|
||||
"s3_key": row["s3_key"],
|
||||
"status": row["status"],
|
||||
"variants": row["variants"] if row.get("variants") else [],
|
||||
"error_code": row["error_code"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
"updated_at": iso(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
store = Store()
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import random
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from . import broker, storage
|
||||
from .db import init_pool, close_pool, transaction
|
||||
from .store import store, iso
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
log = logging.getLogger("messenger.worker")
|
||||
|
||||
THUMB_SIZE = (256, 256)
|
||||
MAX_ATTEMPTS = int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))
|
||||
|
||||
|
||||
def _load_original(staging_key: str) -> bytes:
|
||||
return storage.get_object(staging_key)
|
||||
|
||||
|
||||
def _make_thumbnail(data: bytes) -> tuple[bytes, int, int]:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
background = Image.new("RGB", img.size, (255, 255, 255))
|
||||
rgba = img.convert("RGBA")
|
||||
background.paste(rgba, mask=rgba.split()[-1])
|
||||
img = background
|
||||
else:
|
||||
img = img.convert("RGB")
|
||||
img.thumbnail(THUMB_SIZE, Image.LANCZOS)
|
||||
w, h = img.size
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=85, optimize=True)
|
||||
return buf.getvalue(), w, h
|
||||
|
||||
def _make_crop(data: bytes, size: int = 128) -> tuple[bytes, int, int]:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
background = Image.new("RGB", img.size, (255, 255, 255))
|
||||
rgba = img.convert("RGBA")
|
||||
background.paste(rgba, mask=rgba.split()[-1])
|
||||
img = background
|
||||
else:
|
||||
img = img.convert("RGB")
|
||||
w, h = img.size
|
||||
side = min(w, h)
|
||||
left = (w - side) // 2
|
||||
top = (h - side) // 2
|
||||
img = img.crop((left, top, left + side, top + side))
|
||||
img = img.resize((size, size), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=85, optimize=True)
|
||||
return buf.getvalue(), size, size
|
||||
|
||||
|
||||
def _make_optimized(data: bytes, max_side: int = 1280) -> tuple[bytes, int, int]:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
background = Image.new("RGB", img.size, (255, 255, 255))
|
||||
rgba = img.convert("RGBA")
|
||||
background.paste(rgba, mask=rgba.split()[-1])
|
||||
img = background
|
||||
else:
|
||||
img = img.convert("RGB")
|
||||
img.thumbnail((max_side, max_side), Image.LANCZOS)
|
||||
w, h = img.size
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="WEBP", quality=80, method=4)
|
||||
return buf.getvalue(), w, h
|
||||
|
||||
def _handle(job: dict) -> None:
|
||||
attachment_id = job["attachment_id"]
|
||||
attempt = int(job.get("attempt", 1))
|
||||
job_id = job["job_id"]
|
||||
log.info("processing attachment %s attempt %d (job %s)", attachment_id, attempt, job_id)
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'processing',
|
||||
lease_until = NOW() + INTERVAL '60 seconds'
|
||||
WHERE job_id = %s AND status IN ('published', 'pending')
|
||||
RETURNING job_id
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
acquired = cur.fetchone()
|
||||
if acquired is None:
|
||||
log.info("job %s already acquired or done, skip", job_id)
|
||||
return
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='processing', updated_at=NOW() "
|
||||
"WHERE id=%s AND status='queued'",
|
||||
(attachment_id,),
|
||||
)
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, "
|
||||
"size_bytes, sha256, s3_key, staging_key, status "
|
||||
"FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
log.error("attachment %s not found, skip", attachment_id)
|
||||
return
|
||||
if row["status"] == "ready":
|
||||
log.info("attachment %s already ready, no-op", attachment_id)
|
||||
return
|
||||
|
||||
staging_key = row.get("staging_key") or row["s3_key"]
|
||||
|
||||
data = _load_original(staging_key)
|
||||
|
||||
thumb_bytes, tw, th = _make_thumbnail(data)
|
||||
crop_bytes, cw, ch = _make_crop(data, 128)
|
||||
opt_bytes, ow, oh = _make_optimized(data, 1280)
|
||||
|
||||
ext = row["content_type"].split("/")[-1]
|
||||
final_key = f"originals/{attachment_id}.{ext}"
|
||||
if staging_key != final_key:
|
||||
storage.put_object(final_key, data, row["content_type"])
|
||||
|
||||
thumb_key = f"thumbnails/{attachment_id}.jpg"
|
||||
thumb_sha = storage.put_object(thumb_key, thumb_bytes, "image/jpeg")
|
||||
|
||||
crop_key = f"crops/{attachment_id}.jpg"
|
||||
crop_sha = storage.put_object(crop_key, crop_bytes, "image/jpeg")
|
||||
|
||||
opt_key = f"optimized/{attachment_id}.webp"
|
||||
opt_sha = storage.put_object(opt_key, opt_bytes, "image/webp")
|
||||
|
||||
import json
|
||||
variants = [
|
||||
{
|
||||
"name": "thumbnail",
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(thumb_bytes),
|
||||
"width": tw,
|
||||
"height": th,
|
||||
"sha256": thumb_sha,
|
||||
},
|
||||
{
|
||||
"name": "crop",
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(crop_bytes),
|
||||
"width": cw,
|
||||
"height": ch,
|
||||
"sha256": crop_sha,
|
||||
},
|
||||
{
|
||||
"name": "optimized",
|
||||
"content_type": "image/webp",
|
||||
"size_bytes": len(opt_bytes),
|
||||
"width": ow,
|
||||
"height": oh,
|
||||
"sha256": opt_sha,
|
||||
},
|
||||
]
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'ready',
|
||||
s3_key = %s,
|
||||
variants = %s::jsonb,
|
||||
error_code = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(final_key, json.dumps(variants), attachment_id),
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE jobs SET status='published', lease_until=NULL, published_at=NOW() "
|
||||
"WHERE job_id=%s",
|
||||
(job_id,),
|
||||
)
|
||||
|
||||
if staging_key and staging_key != final_key:
|
||||
try:
|
||||
storage.delete_object(staging_key)
|
||||
except Exception as exc:
|
||||
log.warning("staging cleanup failed: %s", exc)
|
||||
|
||||
log.info(
|
||||
"attachment %s ready: thumbnail %dx%d, crop %dx%d, optimized %dx%d",
|
||||
attachment_id, tw, th, cw, ch, ow, oh,
|
||||
)
|
||||
|
||||
|
||||
PERMANENT_ERRORS = ("invalid_image", "unsupported_media_type", "payload_too_large")
|
||||
|
||||
|
||||
def _is_permanent(exc: Exception) -> bool:
|
||||
name = type(exc).__name__.lower()
|
||||
msg = str(exc).lower()
|
||||
return any(p in name or p in msg for p in PERMANENT_ERRORS)
|
||||
|
||||
|
||||
def _handler_with_retry(job: dict) -> None:
|
||||
attempt = int(job.get("attempt", 1))
|
||||
try:
|
||||
_handle(job)
|
||||
except Exception as exc:
|
||||
log.exception("job %s attempt %d failed: %s", job.get("job_id"), attempt, exc)
|
||||
permanent = _is_permanent(exc)
|
||||
if permanent or attempt >= MAX_ATTEMPTS:
|
||||
try:
|
||||
broker.publish_dlq(job, str(exc))
|
||||
except Exception as dlq_exc:
|
||||
log.warning("DLQ publish failed: %s", dlq_exc)
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='failed', "
|
||||
"error_code=%s, updated_at=NOW() WHERE id=%s",
|
||||
("invalid_image" if permanent else "processing_failed",
|
||||
job["attachment_id"]),
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE jobs SET status='failed', lease_until=NULL "
|
||||
"WHERE job_id=%s",
|
||||
(job["job_id"],),
|
||||
)
|
||||
log.error(
|
||||
"attachment %s failed (permanent=%s) after %d attempts",
|
||||
job["attachment_id"], permanent, attempt,
|
||||
)
|
||||
return
|
||||
delay = min(60, 2 ** attempt) + random.uniform(0, 1)
|
||||
log.info("retry in %.1fs (attempt %d -> %d)", delay, attempt, attempt + 1)
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE jobs SET status='pending', lease_until=NULL, attempt=%s "
|
||||
"WHERE job_id=%s",
|
||||
(attempt + 1, job["job_id"]),
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
init_pool()
|
||||
storage.init_storage()
|
||||
log.info("worker starting, max_attempts=%d", MAX_ATTEMPTS)
|
||||
try:
|
||||
broker.consume(_handler_with_retry, prefetch=int(os.environ.get("WORKER_CONCURRENCY", "2")))
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user