forked from mtusi2026/mtusi2026lab6
лаба на 3
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
def encode_cursor(
|
||||
chat_id: UUID,
|
||||
created_at: datetime,
|
||||
message_id: UUID,
|
||||
) -> str:
|
||||
data = {
|
||||
"chat_id": str(chat_id),
|
||||
"created_at": created_at.isoformat(),
|
||||
"message_id": str(message_id),
|
||||
}
|
||||
|
||||
raw = json.dumps(
|
||||
data,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str) -> tuple[UUID, datetime, UUID]:
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor.encode("ascii"))
|
||||
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Invalid cursor")
|
||||
|
||||
if set(data.keys()) != {
|
||||
"chat_id",
|
||||
"created_at",
|
||||
"message_id",
|
||||
}:
|
||||
raise ValueError("Invalid cursor")
|
||||
|
||||
chat_id = UUID(data["chat_id"])
|
||||
created_at = datetime.fromisoformat(data["created_at"])
|
||||
message_id = UUID(data["message_id"])
|
||||
|
||||
if created_at.tzinfo is None or created_at.utcoffset() is None:
|
||||
raise ValueError("Invalid cursor")
|
||||
|
||||
return chat_id, created_at, message_id
|
||||
|
||||
except (
|
||||
ValueError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
UnicodeError,
|
||||
binascii.Error,
|
||||
json.JSONDecodeError,
|
||||
) as exc:
|
||||
raise ValueError("Invalid cursor") from exc
|
||||
|
||||
|
||||
def encode_chat_cursor(user_id: UUID, created_at: datetime, chat_id: UUID) -> str:
|
||||
data = {
|
||||
"user_id": str(user_id),
|
||||
"created_at": created_at.isoformat(),
|
||||
"chat_id": str(chat_id),
|
||||
}
|
||||
raw = json.dumps(data, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
|
||||
def decode_chat_cursor(cursor: str) -> tuple[UUID, datetime, UUID]:
|
||||
try:
|
||||
raw = base64.b64decode(cursor.encode("ascii"), altchars=b"-_", validate=True)
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(data, dict) or set(data) != {"user_id", "created_at", "chat_id"}:
|
||||
raise ValueError("Invalid cursor")
|
||||
user_id = UUID(data["user_id"])
|
||||
created_at = datetime.fromisoformat(data["created_at"])
|
||||
chat_id = UUID(data["chat_id"])
|
||||
if created_at.tzinfo is None or created_at.utcoffset() is None:
|
||||
raise ValueError("Invalid cursor")
|
||||
return user_id, created_at, chat_id
|
||||
except (ValueError, TypeError, KeyError, UnicodeError, binascii.Error, json.JSONDecodeError) as exc:
|
||||
raise ValueError("Invalid cursor") from exc
|
||||
@@ -0,0 +1,57 @@
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
import socket
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
|
||||
|
||||
DATABASE_URL_FILE = "/run/secrets/database_url"
|
||||
|
||||
POOL_SIZE = 5
|
||||
MAX_OVERFLOW = 5
|
||||
POOL_TIMEOUT_SECONDS = 5
|
||||
DB_CONNECT_TIMEOUT_SECONDS = 5
|
||||
|
||||
|
||||
def read_database_url() -> str:
|
||||
with open(DATABASE_URL_FILE, encoding="utf-8") as file:
|
||||
return file.read().strip()
|
||||
|
||||
|
||||
database_url = read_database_url()
|
||||
|
||||
engine = create_async_engine(
|
||||
database_url,
|
||||
pool_size=POOL_SIZE,
|
||||
max_overflow=MAX_OVERFLOW,
|
||||
pool_timeout=POOL_TIMEOUT_SECONDS,
|
||||
connect_args={
|
||||
"timeout": DB_CONNECT_TIMEOUT_SECONDS,
|
||||
},
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
SessionFactory = async_sessionmaker(
|
||||
bind=engine,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
|
||||
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
||||
async with SessionFactory() as session:
|
||||
yield session
|
||||
|
||||
|
||||
async def ping_database() -> bool:
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.execute(text("SELECT 1"))
|
||||
return True
|
||||
except (SQLAlchemyError, OSError):
|
||||
return False
|
||||
@@ -0,0 +1,149 @@
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.database import SessionFactory, engine
|
||||
from src.queue import connect, publish, publish_failed
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
async def dispatch(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued',
|
||||
published_at = NULL,
|
||||
started_at = NULL,
|
||||
execution_id = NULL
|
||||
WHERE status = 'processing'
|
||||
AND started_at < now() - interval '90 seconds'
|
||||
""")
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
updated_at = now()
|
||||
WHERE status = 'processing'
|
||||
AND id IN (
|
||||
SELECT attachment_id
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
)
|
||||
""")
|
||||
)
|
||||
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation, created_at
|
||||
FROM attachment_jobs
|
||||
WHERE published_at IS NULL
|
||||
AND status = 'queued'
|
||||
AND (
|
||||
next_attempt_at IS NULL
|
||||
OR next_attempt_at <= now()
|
||||
)
|
||||
ORDER BY created_at LIMIT 25
|
||||
FOR
|
||||
UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
publish(channel, row)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def dispatch_failed(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation,
|
||||
last_error_code, created_at, finished_at
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'failed'
|
||||
AND failed_published_at IS NULL
|
||||
ORDER BY created_at
|
||||
LIMIT 25
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"type": "attachment.failed.v1",
|
||||
"job_id": str(row.id),
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"error_code": row.last_error_code,
|
||||
"created_at": row.created_at.isoformat(),
|
||||
"finished_at": (
|
||||
row.finished_at.isoformat()
|
||||
if row.finished_at
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
publish_failed(channel, payload)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET failed_published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def main():
|
||||
while True:
|
||||
connection = None
|
||||
|
||||
try:
|
||||
connection, channel = connect()
|
||||
channel.confirm_delivery()
|
||||
|
||||
while True:
|
||||
count = await dispatch(channel)
|
||||
failed_count = await dispatch_failed(channel)
|
||||
await asyncio.sleep(0.2 if count or failed_count else 1)
|
||||
|
||||
except Exception:
|
||||
logging.exception("Dispatcher reconnect")
|
||||
await asyncio.sleep(3)
|
||||
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
finally:
|
||||
asyncio.run(engine.dispose())
|
||||
@@ -0,0 +1,12 @@
|
||||
class APIError(Exception):
|
||||
def __init__(
|
||||
self,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
):
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers
|
||||
@@ -0,0 +1,71 @@
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from src.errors import APIError
|
||||
|
||||
|
||||
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||
|
||||
ALLOWED_FORMATS = {
|
||||
"PNG": "image/png",
|
||||
"JPEG": "image/jpeg",
|
||||
}
|
||||
|
||||
|
||||
def validate_image(body: bytes, content_type: str) -> tuple[int, str]:
|
||||
if content_type not in ALLOWED_FORMATS.values():
|
||||
raise APIError(
|
||||
status_code=415,
|
||||
code="unsupported_media_type",
|
||||
message="Only PNG and JPEG images are supported",
|
||||
)
|
||||
|
||||
size_bytes = len(body)
|
||||
|
||||
if size_bytes > MAX_UPLOAD_BYTES:
|
||||
raise APIError(
|
||||
status_code=413,
|
||||
code="payload_too_large",
|
||||
message="Image exceeds maximum upload size",
|
||||
)
|
||||
|
||||
if size_bytes == 0:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Image must not be empty",
|
||||
)
|
||||
|
||||
try:
|
||||
with Image.open(io.BytesIO(body)) as image:
|
||||
if image.format not in ALLOWED_FORMATS:
|
||||
raise ValueError("Unsupported image format")
|
||||
|
||||
if ALLOWED_FORMATS[image.format] != content_type:
|
||||
raise ValueError("Content-Type does not match image format")
|
||||
|
||||
width, height = image.size
|
||||
|
||||
if width * height > MAX_IMAGE_PIXELS:
|
||||
raise APIError(
|
||||
status_code=413,
|
||||
code="payload_too_large",
|
||||
message="Image exceeds maximum pixel count",
|
||||
)
|
||||
|
||||
image.load()
|
||||
|
||||
except APIError:
|
||||
raise
|
||||
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError) as exc:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Invalid image data",
|
||||
) from exc
|
||||
|
||||
return size_bytes, hashlib.sha256(body).hexdigest()
|
||||
+792
@@ -0,0 +1,792 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID, uuid4
|
||||
import os
|
||||
import re
|
||||
import base64
|
||||
import binascii
|
||||
import asyncio
|
||||
|
||||
from fastapi import Depends, FastAPI, Request, Header, Query
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from fastapi.security import (
|
||||
HTTPAuthorizationCredentials,
|
||||
HTTPBearer,
|
||||
)
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from src.database import engine, get_db_session, ping_database, SessionFactory
|
||||
from src.errors import APIError
|
||||
from src.models import CreateUser, SessionResponse, User, CreateChat, Chat, ChatPage, CreateMessage, Message, MessagePage, Attachment
|
||||
from src.repositories import (
|
||||
create_chat,
|
||||
list_chats,
|
||||
create_user as create_user_in_db,
|
||||
get_user_by_id,
|
||||
get_chat_by_id,
|
||||
get_user_credentials_by_username,
|
||||
create_message,
|
||||
get_messages,
|
||||
create_attachment,
|
||||
get_attachment,
|
||||
attachment_key_exists,
|
||||
)
|
||||
from src.security import verify_password
|
||||
from src.sessions import (
|
||||
create_session,
|
||||
delete_session,
|
||||
get_session_user_id,
|
||||
ping_session_store,
|
||||
redis_client,
|
||||
)
|
||||
from src.images import MAX_UPLOAD_BYTES, validate_image
|
||||
from src.storage import delete_object, put_object, get_object
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
yield
|
||||
await redis_client.aclose()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
|
||||
from src.telemetry import setup, HTTPMetricsMiddleware
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
|
||||
setup("messenger-api")
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.add_middleware(HTTPMetricsMiddleware)
|
||||
|
||||
INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid4())
|
||||
|
||||
bearer_security = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> User:
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": "Bearer",
|
||||
},
|
||||
)
|
||||
|
||||
user_id = await get_session_user_id(credentials.credentials)
|
||||
|
||||
if user_id is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": "Bearer",
|
||||
},
|
||||
)
|
||||
|
||||
user = await get_user_by_id(session, user_id)
|
||||
|
||||
if user is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": "Bearer",
|
||||
},
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_middleware(request: Request, call_next):
|
||||
request_id = str(uuid4())
|
||||
request.state.request_id = request_id
|
||||
|
||||
if request.method in {"POST", "PUT", "PATCH"}:
|
||||
content_type = request.headers.get("content-type")
|
||||
|
||||
if content_type is not None:
|
||||
media_type = content_type.split(";", 1)[0].strip().lower()
|
||||
|
||||
is_attachment_upload = (
|
||||
request.method == "POST"
|
||||
and re.fullmatch(
|
||||
r"/api/v1/chats/[^/]+/attachments",
|
||||
request.url.path,
|
||||
) is not None
|
||||
)
|
||||
|
||||
allowed_media_types = (
|
||||
{"image/png", "image/jpeg"}
|
||||
if is_attachment_upload
|
||||
else {"application/json"}
|
||||
)
|
||||
|
||||
if media_type not in allowed_media_types:
|
||||
return JSONResponse(
|
||||
status_code=415,
|
||||
content={
|
||||
"error": {
|
||||
"code": "unsupported_media_type",
|
||||
"message": "Unsupported media type",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers={
|
||||
"X-Request-Id": request_id,
|
||||
"X-Instance-Id": INSTANCE_ID,
|
||||
},
|
||||
)
|
||||
|
||||
response = await call_next(request)
|
||||
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(
|
||||
request: Request,
|
||||
exc: RequestValidationError,
|
||||
):
|
||||
request_id = request.state.request_id
|
||||
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={
|
||||
"error": {
|
||||
"code": "invalid_request",
|
||||
"message": "Invalid request",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(APIError)
|
||||
async def api_error_handler(request: Request, exc: APIError):
|
||||
request_id = request.state.request_id
|
||||
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": exc.code,
|
||||
"message": exc.message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers=exc.headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(SQLAlchemyError)
|
||||
async def database_exception_handler(
|
||||
request: Request,
|
||||
exc: SQLAlchemyError,
|
||||
):
|
||||
request_id = request.state.request_id
|
||||
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "Database unavailable",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(OSError)
|
||||
async def database_connection_exception_handler(
|
||||
request: Request,
|
||||
exc: OSError,
|
||||
):
|
||||
request_id = request.state.request_id
|
||||
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "Database unavailable",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(
|
||||
request: Request,
|
||||
exc: StarletteHTTPException,
|
||||
):
|
||||
request_id = request.state.request_id
|
||||
|
||||
if exc.status_code == 404:
|
||||
code = "not_found"
|
||||
message = "Not found"
|
||||
else:
|
||||
code = "invalid_request"
|
||||
message = "Invalid request"
|
||||
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers=exc.headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_exception_handler(
|
||||
request: Request,
|
||||
exc: Exception,
|
||||
):
|
||||
request_id = request.state.request_id
|
||||
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"error": {
|
||||
"code": "internal_error",
|
||||
"message": "Internal server error",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def health_ready():
|
||||
database_ready = await ping_database()
|
||||
session_store_ready = await ping_session_store()
|
||||
|
||||
if not database_ready or not session_store_ready:
|
||||
raise APIError(
|
||||
status_code=503,
|
||||
code="unavailable",
|
||||
message="Service dependencies unavailable",
|
||||
)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", response_model=User, status_code=201)
|
||||
async def create_user(
|
||||
data: CreateUser,
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
):
|
||||
try:
|
||||
async with session.begin():
|
||||
return await create_user_in_db(session, data)
|
||||
|
||||
except IntegrityError as exc:
|
||||
raise APIError(
|
||||
status_code=409,
|
||||
code="conflict",
|
||||
message="Username already exists",
|
||||
) from exc
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
async def get_me(
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
return current_user
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/auth/sessions",
|
||||
response_model=SessionResponse,
|
||||
status_code=201,
|
||||
)
|
||||
async def create_auth_session(
|
||||
authorization: str | None = Header(default=None),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
):
|
||||
credentials = None
|
||||
if authorization is not None:
|
||||
scheme, separator, encoded = authorization.partition(" ")
|
||||
if separator and scheme.lower() == "basic":
|
||||
try:
|
||||
decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8")
|
||||
if ":" in decoded:
|
||||
credentials = decoded.split(":", 1)
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
pass
|
||||
if credentials is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
|
||||
},
|
||||
)
|
||||
|
||||
user_credentials = await get_user_credentials_by_username(
|
||||
session,
|
||||
credentials[0],
|
||||
)
|
||||
|
||||
if user_credentials is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
|
||||
},
|
||||
)
|
||||
|
||||
if not verify_password(
|
||||
user_credentials.password_hash,
|
||||
credentials[1],
|
||||
):
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
|
||||
},
|
||||
)
|
||||
|
||||
user = User(
|
||||
id=user_credentials.id,
|
||||
username=user_credentials.username,
|
||||
display_name=user_credentials.display_name,
|
||||
created_at=user_credentials.created_at,
|
||||
)
|
||||
|
||||
token, ttl = await create_session(user.id)
|
||||
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl)
|
||||
|
||||
return SessionResponse(
|
||||
token=token,
|
||||
token_type="Bearer",
|
||||
expires_at=expires_at,
|
||||
user=user,
|
||||
)
|
||||
|
||||
|
||||
@app.delete(
|
||||
"/api/v1/auth/sessions/current",
|
||||
status_code=204,
|
||||
)
|
||||
async def delete_current_session(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
await delete_session(credentials.credentials)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats",
|
||||
response_model=Chat,
|
||||
status_code=201,
|
||||
)
|
||||
async def create_chat_endpoint(
|
||||
data: CreateChat,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> Chat:
|
||||
try:
|
||||
chat = await create_chat(
|
||||
session=session,
|
||||
data=data,
|
||||
current_user_id=current_user.id,
|
||||
)
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
|
||||
return chat
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats",
|
||||
response_model=ChatPage,
|
||||
)
|
||||
async def get_chats(
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> ChatPage:
|
||||
if limit < 1 or limit > 100:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Limit must be between 1 and 100",
|
||||
)
|
||||
|
||||
return await list_chats(
|
||||
session=session,
|
||||
current_user_id=current_user.id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats/{chat_id}",
|
||||
response_model=Chat,
|
||||
)
|
||||
async def get_chat_endpoint(
|
||||
chat_id: UUID,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> Chat:
|
||||
chat = await get_chat_by_id(
|
||||
session=session,
|
||||
chat_id=chat_id,
|
||||
current_user_id=current_user.id,
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise APIError(
|
||||
status_code=404,
|
||||
code="not_found",
|
||||
message="Chat not found",
|
||||
)
|
||||
|
||||
return chat
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
response_model=Message,
|
||||
status_code=201,
|
||||
)
|
||||
async def create_message_endpoint(
|
||||
chat_id: UUID,
|
||||
data: CreateMessage,
|
||||
idempotency_key: str | None = Header(
|
||||
default=None,
|
||||
alias="Idempotency-Key",
|
||||
),
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> Message:
|
||||
|
||||
if (
|
||||
idempotency_key is None
|
||||
or re.fullmatch(
|
||||
r"[A-Za-z0-9._:-]{1,128}",
|
||||
idempotency_key,
|
||||
) is None
|
||||
):
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Invalid or missing Idempotency-Key",
|
||||
)
|
||||
|
||||
try:
|
||||
message = await create_message(
|
||||
session=session,
|
||||
chat_id=chat_id,
|
||||
current_user_id=current_user.id,
|
||||
data=data,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
|
||||
return message
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
response_model=MessagePage,
|
||||
)
|
||||
async def get_messages_endpoint(
|
||||
chat_id: UUID,
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> MessagePage:
|
||||
if limit < 1 or limit > 100:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Limit must be between 1 and 100",
|
||||
)
|
||||
|
||||
return await get_messages(
|
||||
session=session,
|
||||
chat_id=chat_id,
|
||||
current_user_id=current_user.id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/attachments",
|
||||
response_model=Attachment,
|
||||
status_code=202,
|
||||
)
|
||||
async def upload_attachment_endpoint(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
filename: str = Query(min_length=1, max_length=255),
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> Attachment:
|
||||
chat = await get_chat_by_id(
|
||||
session=session,
|
||||
chat_id=chat_id,
|
||||
current_user_id=current_user.id,
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise APIError(
|
||||
status_code=404,
|
||||
code="not_found",
|
||||
message="Chat not found",
|
||||
)
|
||||
|
||||
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
|
||||
if content_type not in {"image/png", "image/jpeg"}:
|
||||
raise APIError(
|
||||
status_code=415,
|
||||
code="unsupported_media_type",
|
||||
message="Only PNG and JPEG images are supported",
|
||||
)
|
||||
|
||||
body = bytearray()
|
||||
|
||||
async for chunk in request.stream():
|
||||
if len(body) + len(chunk) > MAX_UPLOAD_BYTES:
|
||||
raise APIError(
|
||||
status_code=413,
|
||||
code="payload_too_large",
|
||||
message="Image exceeds maximum upload size",
|
||||
)
|
||||
|
||||
body.extend(chunk)
|
||||
|
||||
image_bytes = bytes(body)
|
||||
size_bytes, sha256 = validate_image(image_bytes, content_type)
|
||||
|
||||
attachment_id = uuid4()
|
||||
extension = "png" if content_type == "image/png" else "jpg"
|
||||
s3_key = f"staging/{chat_id}/{attachment_id}.{extension}"
|
||||
|
||||
try:
|
||||
await put_object(
|
||||
key=s3_key,
|
||||
body=image_bytes,
|
||||
content_type=content_type,
|
||||
)
|
||||
except (BotoCoreError, ClientError, OSError, TimeoutError) as exc:
|
||||
raise APIError(
|
||||
status_code=503,
|
||||
code="unavailable",
|
||||
message="Object storage unavailable",
|
||||
) from exc
|
||||
|
||||
try:
|
||||
attachment = await create_attachment(
|
||||
session=session,
|
||||
attachment_id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=current_user.id,
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256,
|
||||
s3_key=s3_key,
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO attachment_jobs (id, attachment_id)
|
||||
VALUES (:job_id, :attachment_id)
|
||||
"""),
|
||||
{
|
||||
"job_id": uuid4(),
|
||||
"attachment_id": attachment_id,
|
||||
},
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
|
||||
except BaseException:
|
||||
try:
|
||||
await session.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
async with SessionFactory() as verification_session:
|
||||
exists = await attachment_key_exists(
|
||||
verification_session,
|
||||
s3_key,
|
||||
)
|
||||
except Exception:
|
||||
exists = True
|
||||
|
||||
if not exists:
|
||||
try:
|
||||
await asyncio.shield(delete_object(s3_key))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raise
|
||||
|
||||
return attachment
|
||||
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/attachments/{attachment_id}",
|
||||
response_model=Attachment,
|
||||
)
|
||||
async def get_attachment_endpoint(
|
||||
attachment_id: UUID,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> Attachment:
|
||||
result = await get_attachment(
|
||||
session=session,
|
||||
attachment_id=attachment_id,
|
||||
current_user_id=current_user.id,
|
||||
)
|
||||
|
||||
if result is None:
|
||||
raise APIError(
|
||||
status_code=404,
|
||||
code="not_found",
|
||||
message="Attachment not found",
|
||||
)
|
||||
|
||||
attachment, s3_key = result
|
||||
return attachment
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def get_attachment_content_endpoint(
|
||||
attachment_id: UUID,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
variant: str = Query(default="original"),
|
||||
):
|
||||
result = await get_attachment(
|
||||
session=session,
|
||||
attachment_id=attachment_id,
|
||||
current_user_id=current_user.id,
|
||||
)
|
||||
|
||||
if result is None:
|
||||
raise APIError(
|
||||
status_code=404,
|
||||
code="not_found",
|
||||
message="Attachment not found",
|
||||
)
|
||||
|
||||
attachment, s3_key = result
|
||||
|
||||
if attachment.status != "ready":
|
||||
raise APIError(
|
||||
status_code=409,
|
||||
code="conflict",
|
||||
message="Attachment is not ready",
|
||||
)
|
||||
|
||||
if variant == "original":
|
||||
media_type = attachment.content_type
|
||||
|
||||
elif variant in {"thumbnail", "crop", "optimized"}:
|
||||
selected = next(
|
||||
(item for item in attachment.variants if item.name == variant),
|
||||
None,
|
||||
)
|
||||
|
||||
if selected is None:
|
||||
raise APIError(
|
||||
status_code=404,
|
||||
code="not_found",
|
||||
message="Variant not found",
|
||||
)
|
||||
|
||||
extension = {
|
||||
"thumbnail": "jpg",
|
||||
"crop": "jpg",
|
||||
"optimized": "webp",
|
||||
}[variant]
|
||||
|
||||
s3_key = selected.s3_key or (
|
||||
f"variants/{attachment.chat_id}/{attachment_id}/"
|
||||
f"{variant}.{extension}"
|
||||
)
|
||||
media_type = selected.content_type
|
||||
|
||||
else:
|
||||
raise APIError(
|
||||
status_code=404,
|
||||
code="not_found",
|
||||
message="Variant not found",
|
||||
)
|
||||
|
||||
try:
|
||||
body = await get_object(s3_key)
|
||||
except (BotoCoreError, ClientError, OSError, TimeoutError) as exc:
|
||||
raise APIError(
|
||||
status_code=503,
|
||||
code="unavailable",
|
||||
message="Object storage unavailable",
|
||||
) from exc
|
||||
|
||||
return Response(
|
||||
content=body,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
)
|
||||
|
||||
FastAPIInstrumentor.instrument_app(
|
||||
app,
|
||||
excluded_urls="health/live,health/ready",
|
||||
exclude_spans=["receive", "send"],
|
||||
)
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
username: str = Field(
|
||||
min_length=3,
|
||||
max_length=32,
|
||||
pattern=r"^[a-z0-9_]+$",
|
||||
)
|
||||
|
||||
display_name: str = Field(
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
)
|
||||
|
||||
password: str = Field(
|
||||
min_length=12,
|
||||
max_length=128,
|
||||
)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def validate_display_name(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("Display name must not be blank")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str = Field(
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
)
|
||||
|
||||
member_ids: list[UUID] = Field(
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def validate_title(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("Chat title must not be blank")
|
||||
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def validate_member_ids(cls, value: list[UUID]) -> list[UUID]:
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("Member IDs must be unique")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: list[UUID]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
items: list[Chat]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator("attachment_ids")
|
||||
@classmethod
|
||||
def validate_attachment_ids(cls, value: list[UUID]) -> list[UUID]:
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("Attachment IDs must be unique")
|
||||
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_content(self):
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError("Message must contain text or attachments")
|
||||
|
||||
return self
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: list[UUID] = Field(default_factory=list)
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
items: list[Message]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class Variant(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str = Field(pattern=r"^(thumbnail|crop|optimized)$")
|
||||
content_type: str = Field(pattern=r"^image/(jpeg|png|webp)$")
|
||||
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}$")
|
||||
s3_key: str | None = Field(default=None, exclude=True)
|
||||
|
||||
|
||||
class Attachment(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str = Field(min_length=1, max_length=255)
|
||||
content_type: str = Field(pattern=r"^image/(png|jpeg)$")
|
||||
size_bytes: int = Field(ge=1, le=10485760)
|
||||
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
status: str = Field(pattern=r"^(queued|processing|ready|failed)$")
|
||||
variants: list[Variant]
|
||||
error_code: str | None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
@@ -0,0 +1,78 @@
|
||||
import json
|
||||
import os
|
||||
from datetime import timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
DLQ = "attachment.failed.v1"
|
||||
|
||||
|
||||
def connect():
|
||||
password = Path(
|
||||
os.environ["RABBITMQ_PASSWORD_FILE"]
|
||||
).read_text().strip()
|
||||
|
||||
credentials = pika.PlainCredentials(
|
||||
"messenger",
|
||||
password,
|
||||
)
|
||||
|
||||
connection = pika.BlockingConnection(
|
||||
pika.ConnectionParameters(
|
||||
host=os.getenv("RABBITMQ_HOST", "rabbitmq"),
|
||||
credentials=credentials,
|
||||
heartbeat=60,
|
||||
blocked_connection_timeout=30,
|
||||
connection_attempts=3,
|
||||
retry_delay=2,
|
||||
)
|
||||
)
|
||||
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
|
||||
return connection, channel
|
||||
|
||||
|
||||
def publish(channel, row):
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(row.id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"created_at": row.created_at.astimezone(
|
||||
timezone.utc
|
||||
).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=QUEUE,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=str(row.id),
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
|
||||
def publish_failed(channel, payload: dict):
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=DLQ,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=payload["job_id"],
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
@@ -0,0 +1,875 @@
|
||||
from uuid import UUID, uuid4
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.models import Attachment, Chat, ChatPage, CreateChat, CreateUser, User, CreateMessage, Message, MessagePage
|
||||
from src.security import hash_password
|
||||
from src.errors import APIError
|
||||
from src.cursor import decode_cursor, encode_cursor, decode_chat_cursor, encode_chat_cursor
|
||||
|
||||
|
||||
async def create_user(
|
||||
session: AsyncSession,
|
||||
data: CreateUser,
|
||||
) -> User:
|
||||
user_id = uuid4()
|
||||
password_hash = hash_password(data.password)
|
||||
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES (
|
||||
:id,
|
||||
:username,
|
||||
:display_name,
|
||||
:password_hash
|
||||
)
|
||||
RETURNING
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
created_at
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": user_id,
|
||||
"username": data.username,
|
||||
"display_name": data.display_name,
|
||||
"password_hash": password_hash,
|
||||
},
|
||||
)
|
||||
|
||||
row = result.one()
|
||||
|
||||
return User(
|
||||
id=UUID(str(row.id)),
|
||||
username=row.username,
|
||||
display_name=row.display_name,
|
||||
created_at=row.created_at,
|
||||
)
|
||||
|
||||
async def get_user_credentials_by_username(
|
||||
session: AsyncSession,
|
||||
username: str,
|
||||
):
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash,
|
||||
created_at
|
||||
FROM users
|
||||
WHERE username = :username
|
||||
"""
|
||||
),
|
||||
{
|
||||
"username": username,
|
||||
},
|
||||
)
|
||||
|
||||
return result.one_or_none()
|
||||
|
||||
|
||||
async def get_user_by_id(
|
||||
session: AsyncSession,
|
||||
user_id: UUID,
|
||||
) -> User | None:
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
created_at
|
||||
FROM users
|
||||
WHERE id = :user_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"user_id": user_id,
|
||||
},
|
||||
)
|
||||
|
||||
row = result.one_or_none()
|
||||
|
||||
if row is None:
|
||||
return None
|
||||
|
||||
return User(
|
||||
id=UUID(str(row.id)),
|
||||
username=row.username,
|
||||
display_name=row.display_name,
|
||||
created_at=row.created_at,
|
||||
)
|
||||
|
||||
|
||||
async def create_chat(
|
||||
session: AsyncSession,
|
||||
data: CreateChat,
|
||||
current_user_id: UUID,
|
||||
) -> Chat:
|
||||
if current_user_id not in data.member_ids:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Current user must be a chat member",
|
||||
)
|
||||
|
||||
users_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT id
|
||||
FROM users
|
||||
WHERE id = ANY(:member_ids)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"member_ids": data.member_ids,
|
||||
},
|
||||
)
|
||||
|
||||
existing_user_ids = {
|
||||
UUID(str(row.id))
|
||||
for row in users_result
|
||||
}
|
||||
|
||||
if existing_user_ids != set(data.member_ids):
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Unknown chat member",
|
||||
)
|
||||
|
||||
chat_id = uuid4()
|
||||
|
||||
chat_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO chats (
|
||||
id,
|
||||
title
|
||||
)
|
||||
VALUES (
|
||||
:id,
|
||||
:title
|
||||
)
|
||||
RETURNING
|
||||
id,
|
||||
title,
|
||||
created_at
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": chat_id,
|
||||
"title": data.title,
|
||||
},
|
||||
)
|
||||
|
||||
chat_row = chat_result.one()
|
||||
|
||||
for member_id in data.member_ids:
|
||||
await session.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO chat_members (
|
||||
chat_id,
|
||||
user_id
|
||||
)
|
||||
VALUES (
|
||||
:chat_id,
|
||||
:user_id
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"user_id": member_id,
|
||||
},
|
||||
)
|
||||
|
||||
return Chat(
|
||||
id=UUID(str(chat_row.id)),
|
||||
title=chat_row.title,
|
||||
member_ids=data.member_ids,
|
||||
created_at=chat_row.created_at,
|
||||
)
|
||||
|
||||
|
||||
async def get_chat_by_id(
|
||||
session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
current_user_id: UUID,
|
||||
) -> Chat | None:
|
||||
chat_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS cm
|
||||
ON cm.chat_id = c.id
|
||||
WHERE c.id = :chat_id
|
||||
AND cm.user_id = :current_user_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"current_user_id": current_user_id,
|
||||
},
|
||||
)
|
||||
|
||||
chat_row = chat_result.one_or_none()
|
||||
|
||||
if chat_row is None:
|
||||
return None
|
||||
|
||||
members_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = :chat_id
|
||||
ORDER BY user_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
},
|
||||
)
|
||||
|
||||
member_ids = [
|
||||
UUID(str(row.user_id))
|
||||
for row in members_result
|
||||
]
|
||||
|
||||
return Chat(
|
||||
id=UUID(str(chat_row.id)),
|
||||
title=chat_row.title,
|
||||
member_ids=member_ids,
|
||||
created_at=chat_row.created_at,
|
||||
)
|
||||
|
||||
|
||||
async def list_chats(
|
||||
session: AsyncSession,
|
||||
current_user_id: UUID,
|
||||
limit: int,
|
||||
cursor: str | None = None,
|
||||
) -> ChatPage:
|
||||
cursor_created_at = None
|
||||
cursor_chat_id = None
|
||||
if cursor is not None:
|
||||
try:
|
||||
cursor_user_id, cursor_created_at, cursor_chat_id = decode_chat_cursor(cursor)
|
||||
except ValueError as exc:
|
||||
raise APIError(status_code=400, code="invalid_request", message="Invalid cursor") from exc
|
||||
if cursor_user_id != current_user_id:
|
||||
raise APIError(status_code=400, code="invalid_request", message="Invalid cursor")
|
||||
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = :current_user_id
|
||||
AND (
|
||||
CAST(:cursor_created_at AS timestamptz) IS NULL
|
||||
OR (c.created_at, c.id) > (
|
||||
CAST(:cursor_created_at AS timestamptz),
|
||||
CAST(:cursor_chat_id AS uuid)
|
||||
)
|
||||
)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT :fetch_limit
|
||||
"""
|
||||
),
|
||||
{
|
||||
"current_user_id": current_user_id,
|
||||
"cursor_created_at": cursor_created_at,
|
||||
"cursor_chat_id": cursor_chat_id,
|
||||
"fetch_limit": limit + 1,
|
||||
},
|
||||
)
|
||||
rows = result.all()
|
||||
has_more = len(rows) > limit
|
||||
page_rows = rows[:limit]
|
||||
items = []
|
||||
for chat_row in page_rows:
|
||||
members_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = :chat_id
|
||||
ORDER BY user_id
|
||||
"""
|
||||
),
|
||||
{"chat_id": chat_row.id},
|
||||
)
|
||||
items.append(
|
||||
Chat(
|
||||
id=UUID(str(chat_row.id)),
|
||||
title=chat_row.title,
|
||||
member_ids=[UUID(str(row.user_id)) for row in members_result],
|
||||
created_at=chat_row.created_at,
|
||||
)
|
||||
)
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = page_rows[-1]
|
||||
next_cursor = encode_chat_cursor(
|
||||
current_user_id, last.created_at, UUID(str(last.id))
|
||||
)
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
|
||||
|
||||
async def create_message(
|
||||
session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
current_user_id: UUID,
|
||||
data: CreateMessage,
|
||||
idempotency_key: str,
|
||||
) -> Message:
|
||||
membership_result = await session.execute(
|
||||
text("""
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = :chat_id
|
||||
AND user_id = :user_id
|
||||
"""),
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"user_id": current_user_id,
|
||||
},
|
||||
)
|
||||
|
||||
if membership_result.scalar_one_or_none() is None:
|
||||
raise APIError(
|
||||
status_code=404,
|
||||
code="not_found",
|
||||
message="Chat not found",
|
||||
)
|
||||
|
||||
canonical_body = json.dumps(
|
||||
{
|
||||
"text": data.text,
|
||||
"attachment_ids": [str(attachment_id) for attachment_id in data.attachment_ids],
|
||||
},
|
||||
sort_keys=True,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
|
||||
request_hash = hashlib.sha256(
|
||||
canonical_body.encode("utf-8")
|
||||
).hexdigest()
|
||||
|
||||
scope = (
|
||||
f"{current_user_id}:POST:"
|
||||
f"/api/v1/chats/{chat_id}/messages:"
|
||||
f"{idempotency_key}"
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
SELECT pg_advisory_xact_lock(
|
||||
hashtextextended(:scope, 0)
|
||||
)
|
||||
"""),
|
||||
{"scope": scope},
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = :user_id
|
||||
AND chat_id = :chat_id
|
||||
AND key = :key
|
||||
AND created_at <=
|
||||
clock_timestamp() - INTERVAL '24 hours'
|
||||
"""),
|
||||
{
|
||||
"user_id": current_user_id,
|
||||
"chat_id": chat_id,
|
||||
"key": idempotency_key,
|
||||
},
|
||||
)
|
||||
|
||||
existing_result = await session.execute(
|
||||
text("""
|
||||
SELECT
|
||||
i.request_hash,
|
||||
m.id,
|
||||
m.chat_id,
|
||||
m.sender_id,
|
||||
m.text,
|
||||
m.created_at
|
||||
FROM message_idempotency AS i
|
||||
JOIN messages AS m
|
||||
ON m.id = i.message_id
|
||||
WHERE i.user_id = :user_id
|
||||
AND i.chat_id = :chat_id
|
||||
AND i.key = :key
|
||||
"""),
|
||||
{
|
||||
"user_id": current_user_id,
|
||||
"chat_id": chat_id,
|
||||
"key": idempotency_key,
|
||||
},
|
||||
)
|
||||
|
||||
existing = existing_result.one_or_none()
|
||||
|
||||
if existing is not None:
|
||||
if existing.request_hash != request_hash:
|
||||
raise APIError(
|
||||
status_code=409,
|
||||
code="conflict",
|
||||
message=(
|
||||
"Idempotency key already used "
|
||||
"with different request body"
|
||||
),
|
||||
)
|
||||
|
||||
attachment_result = await session.execute(
|
||||
text("""
|
||||
SELECT attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = :message_id
|
||||
ORDER BY attachment_id
|
||||
"""),
|
||||
{"message_id": existing.id},
|
||||
)
|
||||
|
||||
attachment_ids = [
|
||||
UUID(str(row.attachment_id))
|
||||
for row in attachment_result.all()
|
||||
]
|
||||
|
||||
return Message(
|
||||
id=UUID(str(existing.id)),
|
||||
chat_id=UUID(str(existing.chat_id)),
|
||||
sender_id=UUID(str(existing.sender_id)),
|
||||
text=existing.text,
|
||||
created_at=existing.created_at,
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
|
||||
if data.attachment_ids:
|
||||
attachments_result = await session.execute(
|
||||
text("""
|
||||
SELECT id
|
||||
FROM attachments
|
||||
WHERE id = ANY (:attachment_ids)
|
||||
AND chat_id = :chat_id
|
||||
AND status != 'failed'
|
||||
"""),
|
||||
{
|
||||
"attachment_ids": data.attachment_ids,
|
||||
"chat_id": chat_id,
|
||||
},
|
||||
)
|
||||
|
||||
valid_attachment_ids = {
|
||||
UUID(str(row.id))
|
||||
for row in attachments_result.all()
|
||||
}
|
||||
|
||||
if valid_attachment_ids != set(data.attachment_ids):
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Invalid attachments for this chat",
|
||||
)
|
||||
|
||||
message_id = uuid4()
|
||||
|
||||
message_result = await session.execute(
|
||||
text("""
|
||||
INSERT INTO messages (
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text
|
||||
)
|
||||
VALUES (
|
||||
:id,
|
||||
:chat_id,
|
||||
:sender_id,
|
||||
:text
|
||||
)
|
||||
RETURNING
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
"""),
|
||||
{
|
||||
"id": message_id,
|
||||
"chat_id": chat_id,
|
||||
"sender_id": current_user_id,
|
||||
"text": data.text,
|
||||
},
|
||||
)
|
||||
|
||||
row = message_result.one()
|
||||
|
||||
for attachment_id in data.attachment_ids:
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO message_attachments (message_id,
|
||||
attachment_id)
|
||||
VALUES (:message_id,
|
||||
:attachment_id)
|
||||
"""),
|
||||
{
|
||||
"message_id": message_id,
|
||||
"attachment_id": attachment_id,
|
||||
},
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO message_idempotency (
|
||||
user_id,
|
||||
chat_id,
|
||||
key,
|
||||
request_hash,
|
||||
message_id
|
||||
)
|
||||
VALUES (
|
||||
:user_id,
|
||||
:chat_id,
|
||||
:key,
|
||||
:request_hash,
|
||||
:message_id
|
||||
)
|
||||
"""),
|
||||
{
|
||||
"user_id": current_user_id,
|
||||
"chat_id": chat_id,
|
||||
"key": idempotency_key,
|
||||
"request_hash": request_hash,
|
||||
"message_id": message_id,
|
||||
},
|
||||
)
|
||||
|
||||
return Message(
|
||||
id=UUID(str(row.id)),
|
||||
chat_id=UUID(str(row.chat_id)),
|
||||
sender_id=UUID(str(row.sender_id)),
|
||||
text=row.text,
|
||||
created_at=row.created_at,
|
||||
attachment_ids=data.attachment_ids,
|
||||
)
|
||||
|
||||
|
||||
async def get_messages(
|
||||
session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
current_user_id: UUID,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
) -> MessagePage:
|
||||
membership_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = :chat_id
|
||||
AND user_id = :current_user_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"current_user_id": current_user_id,
|
||||
},
|
||||
)
|
||||
|
||||
if membership_result.scalar_one_or_none() is None:
|
||||
raise APIError(
|
||||
status_code=404,
|
||||
code="not_found",
|
||||
message="Chat not found",
|
||||
)
|
||||
|
||||
cursor_created_at = None
|
||||
cursor_message_id = None
|
||||
|
||||
if cursor is not None:
|
||||
try:
|
||||
(
|
||||
cursor_chat_id,
|
||||
cursor_created_at,
|
||||
cursor_message_id,
|
||||
) = decode_cursor(cursor)
|
||||
except ValueError:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Invalid cursor",
|
||||
)
|
||||
|
||||
if cursor_chat_id != chat_id:
|
||||
raise APIError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Cursor belongs to another chat",
|
||||
)
|
||||
|
||||
if cursor is None:
|
||||
messages_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :chat_id
|
||||
ORDER BY created_at, id
|
||||
LIMIT :fetch_limit
|
||||
"""
|
||||
),
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"fetch_limit": limit + 1,
|
||||
},
|
||||
)
|
||||
else:
|
||||
messages_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :chat_id
|
||||
AND (created_at, id) > (
|
||||
:cursor_created_at,
|
||||
:cursor_message_id
|
||||
)
|
||||
ORDER BY created_at, id
|
||||
LIMIT :fetch_limit
|
||||
"""
|
||||
),
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"cursor_created_at": cursor_created_at,
|
||||
"cursor_message_id": cursor_message_id,
|
||||
"fetch_limit": limit + 1,
|
||||
},
|
||||
)
|
||||
|
||||
rows = messages_result.all()
|
||||
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
|
||||
attachments_by_message = {}
|
||||
|
||||
if rows:
|
||||
attachment_result = await session.execute(
|
||||
text("""
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY(:message_ids)
|
||||
ORDER BY message_id, attachment_id
|
||||
"""),
|
||||
{
|
||||
"message_ids": [row.id for row in rows],
|
||||
},
|
||||
)
|
||||
|
||||
for attachment_row in attachment_result.all():
|
||||
message_id = UUID(str(attachment_row.message_id))
|
||||
attachment_id = UUID(str(attachment_row.attachment_id))
|
||||
|
||||
attachments_by_message.setdefault(
|
||||
message_id, []
|
||||
).append(attachment_id)
|
||||
|
||||
items = [
|
||||
Message(
|
||||
id=UUID(str(row.id)),
|
||||
chat_id=UUID(str(row.chat_id)),
|
||||
sender_id=UUID(str(row.sender_id)),
|
||||
text=row.text,
|
||||
created_at=row.created_at,
|
||||
attachment_ids=attachments_by_message.get(
|
||||
UUID(str(row.id)), []
|
||||
),
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
next_cursor = None
|
||||
|
||||
if has_more:
|
||||
last_message = items[-1]
|
||||
|
||||
next_cursor = encode_cursor(
|
||||
chat_id=chat_id,
|
||||
created_at=last_message.created_at,
|
||||
message_id=last_message.id,
|
||||
)
|
||||
|
||||
return MessagePage(
|
||||
items=items,
|
||||
next_cursor=next_cursor,
|
||||
)
|
||||
|
||||
|
||||
def attachment_from_row(row) -> Attachment:
|
||||
return Attachment(
|
||||
id=UUID(str(row.id)),
|
||||
chat_id=UUID(str(row.chat_id)),
|
||||
owner_id=UUID(str(row.owner_id)),
|
||||
filename=row.filename,
|
||||
content_type=row.content_type,
|
||||
size_bytes=row.size_bytes,
|
||||
sha256=row.sha256,
|
||||
status=row.status,
|
||||
variants=row.variants,
|
||||
error_code=row.error_code,
|
||||
created_at=row.created_at,
|
||||
updated_at=row.updated_at,
|
||||
)
|
||||
|
||||
|
||||
async def create_attachment(
|
||||
session: AsyncSession,
|
||||
attachment_id: UUID,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
s3_key: str,
|
||||
) -> Attachment:
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id,
|
||||
chat_id,
|
||||
owner_id,
|
||||
filename,
|
||||
content_type,
|
||||
size_bytes,
|
||||
sha256,
|
||||
s3_key,
|
||||
status
|
||||
)
|
||||
VALUES (
|
||||
:id,
|
||||
:chat_id,
|
||||
:owner_id,
|
||||
:filename,
|
||||
:content_type,
|
||||
:size_bytes,
|
||||
:sha256,
|
||||
:s3_key,
|
||||
'queued'
|
||||
)
|
||||
RETURNING
|
||||
id,
|
||||
chat_id,
|
||||
owner_id,
|
||||
filename,
|
||||
content_type,
|
||||
size_bytes,
|
||||
sha256,
|
||||
status,
|
||||
variants,
|
||||
error_code,
|
||||
created_at,
|
||||
updated_at
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": attachment_id,
|
||||
"chat_id": chat_id,
|
||||
"owner_id": owner_id,
|
||||
"filename": filename,
|
||||
"content_type": content_type,
|
||||
"size_bytes": size_bytes,
|
||||
"sha256": sha256,
|
||||
"s3_key": s3_key,
|
||||
},
|
||||
)
|
||||
|
||||
return attachment_from_row(result.one())
|
||||
|
||||
|
||||
async def get_attachment(
|
||||
session: AsyncSession,
|
||||
attachment_id: UUID,
|
||||
current_user_id: UUID,
|
||||
):
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
a.id,
|
||||
a.chat_id,
|
||||
a.owner_id,
|
||||
a.filename,
|
||||
a.content_type,
|
||||
a.size_bytes,
|
||||
a.sha256,
|
||||
a.s3_key,
|
||||
a.status,
|
||||
a.variants,
|
||||
a.error_code,
|
||||
a.created_at,
|
||||
a.updated_at
|
||||
FROM attachments AS a
|
||||
JOIN chat_members AS cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
WHERE a.id = :attachment_id
|
||||
AND cm.user_id = :current_user_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"attachment_id": attachment_id,
|
||||
"current_user_id": current_user_id,
|
||||
},
|
||||
)
|
||||
|
||||
row = result.one_or_none()
|
||||
|
||||
if row is None:
|
||||
return None
|
||||
|
||||
return attachment_from_row(row), row.s3_key
|
||||
|
||||
async def attachment_key_exists(session: AsyncSession, s3_key: str) -> bool:
|
||||
result = await session.execute(
|
||||
text("SELECT 1 FROM attachments WHERE s3_key = :s3_key"),
|
||||
{"s3_key": s3_key},
|
||||
)
|
||||
return result.first() is not None
|
||||
@@ -0,0 +1,16 @@
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
|
||||
password_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return password_hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(password_hash, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
@@ -0,0 +1,87 @@
|
||||
import os
|
||||
import secrets
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from src.errors import APIError
|
||||
|
||||
|
||||
CACHE_URL_FILE = "/run/secrets/cache_url"
|
||||
DEFAULT_SESSION_TTL_SECONDS = 3600
|
||||
|
||||
|
||||
def read_cache_url() -> str:
|
||||
with open(CACHE_URL_FILE, encoding="utf-8") as file:
|
||||
return file.read().strip()
|
||||
|
||||
|
||||
def get_session_ttl_seconds() -> int:
|
||||
return int(
|
||||
os.getenv(
|
||||
"SESSION_TTL_SECONDS",
|
||||
str(DEFAULT_SESSION_TTL_SECONDS),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
redis_client = Redis.from_url(
|
||||
read_cache_url(),
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=5,
|
||||
socket_timeout=5,
|
||||
)
|
||||
|
||||
|
||||
def session_store_unavailable() -> APIError:
|
||||
return APIError(
|
||||
status_code=503,
|
||||
code="unavailable",
|
||||
message="Session store unavailable",
|
||||
)
|
||||
|
||||
|
||||
async def create_session(user_id: UUID) -> tuple[str, int]:
|
||||
token = secrets.token_urlsafe(32)
|
||||
ttl = get_session_ttl_seconds()
|
||||
|
||||
try:
|
||||
await redis_client.set(
|
||||
f"session:{token}",
|
||||
str(user_id),
|
||||
ex=ttl,
|
||||
)
|
||||
except RedisError as exc:
|
||||
raise session_store_unavailable() from exc
|
||||
|
||||
return token, ttl
|
||||
|
||||
|
||||
async def get_session_user_id(token: str) -> UUID | None:
|
||||
try:
|
||||
value = await redis_client.get(f"session:{token}")
|
||||
except RedisError as exc:
|
||||
raise session_store_unavailable() from exc
|
||||
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
async def delete_session(token: str) -> None:
|
||||
try:
|
||||
await redis_client.delete(f"session:{token}")
|
||||
except RedisError as exc:
|
||||
raise session_store_unavailable() from exc
|
||||
|
||||
|
||||
async def ping_session_store() -> bool:
|
||||
try:
|
||||
return bool(await redis_client.ping())
|
||||
except RedisError:
|
||||
return False
|
||||
@@ -0,0 +1,87 @@
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def read_secret(env_name: str) -> str:
|
||||
path = os.environ[env_name]
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
region_name=os.getenv("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE"),
|
||||
aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
connect_timeout=2,
|
||||
read_timeout=3,
|
||||
retries={"total_max_attempts": 1, "mode": "standard"},
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
S3_BUCKET = os.environ["S3_BUCKET"]
|
||||
|
||||
|
||||
async def put_object(key: str, body: bytes, content_type: str) -> None:
|
||||
await asyncio.to_thread(
|
||||
s3_client.put_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
Body=body,
|
||||
ContentType=content_type,
|
||||
)
|
||||
|
||||
|
||||
async def get_object(key: str) -> bytes:
|
||||
def download() -> bytes:
|
||||
response = s3_client.get_object(Bucket=S3_BUCKET, Key=key)
|
||||
stream = response["Body"]
|
||||
try:
|
||||
return stream.read()
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
return await asyncio.to_thread(download)
|
||||
|
||||
|
||||
async def delete_object(key: str) -> None:
|
||||
await asyncio.to_thread(
|
||||
s3_client.delete_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
|
||||
|
||||
async def ping_storage() -> bool:
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_bucket,
|
||||
Bucket=S3_BUCKET,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
async def object_exists(key: str) -> bool:
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if exc.response["Error"]["Code"] in {"404", "NoSuchKey", "NotFound"}:
|
||||
return False
|
||||
raise
|
||||
@@ -0,0 +1,257 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
|
||||
_initialized = False
|
||||
logger = logging.getLogger("messenger.telemetry")
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
context = trace.get_current_span().get_span_context()
|
||||
|
||||
return json.dumps({
|
||||
"timestamp": self.formatTime(record),
|
||||
"level": record.levelname,
|
||||
"event": record.getMessage(),
|
||||
"trace_id": (
|
||||
format(context.trace_id, "032x")
|
||||
if context.is_valid else ""
|
||||
),
|
||||
"span_id": (
|
||||
format(context.span_id, "016x")
|
||||
if context.is_valid else ""
|
||||
),
|
||||
}, ensure_ascii=False)
|
||||
|
||||
|
||||
def setup(service_name):
|
||||
global _initialized
|
||||
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
resource = Resource.create({
|
||||
"service.name": service_name,
|
||||
"service.version": os.getenv("APP_VERSION", "6.0.0"),
|
||||
"service.instance.id": os.getenv(
|
||||
"INSTANCE_ID", socket.gethostname()
|
||||
),
|
||||
"deployment.environment.name": "lab",
|
||||
})
|
||||
|
||||
endpoint = os.getenv(
|
||||
"OTEL_EXPORTER_OTLP_ENDPOINT",
|
||||
"http://otel-collector:4318",
|
||||
).rstrip("/")
|
||||
|
||||
tracer_provider = TracerProvider(resource=resource)
|
||||
tracer_provider.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
OTLPSpanExporter(
|
||||
endpoint=f"{endpoint}/v1/traces",
|
||||
timeout=3,
|
||||
),
|
||||
max_queue_size=2048,
|
||||
max_export_batch_size=256,
|
||||
schedule_delay_millis=2000,
|
||||
)
|
||||
)
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(
|
||||
endpoint=f"{endpoint}/v1/metrics",
|
||||
timeout=3,
|
||||
),
|
||||
export_interval_millis=5000,
|
||||
export_timeout_millis=3000,
|
||||
)
|
||||
|
||||
metrics.set_meter_provider(
|
||||
MeterProvider(
|
||||
resource=resource,
|
||||
metric_readers=[reader],
|
||||
)
|
||||
)
|
||||
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
logger_provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(
|
||||
endpoint=f"{endpoint}/v1/logs",
|
||||
timeout=3,
|
||||
),
|
||||
max_queue_size=2048,
|
||||
max_export_batch_size=256,
|
||||
schedule_delay_millis=2000,
|
||||
)
|
||||
)
|
||||
set_logger_provider(logger_provider)
|
||||
|
||||
handler = LoggingHandler(
|
||||
level=logging.INFO,
|
||||
logger_provider=logger_provider,
|
||||
)
|
||||
handler.setFormatter(JsonFormatter())
|
||||
|
||||
logger.handlers.clear()
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
def event(name, **fields):
|
||||
logger.info(
|
||||
json.dumps(
|
||||
{"event": name, **fields},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class HTTPMetricsMiddleware:
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
meter = metrics.get_meter("messenger.api")
|
||||
|
||||
self.requests = meter.create_counter(
|
||||
"messenger_http_requests",
|
||||
description="HTTP requests",
|
||||
)
|
||||
|
||||
self.duration = meter.create_histogram(
|
||||
"messenger_http_request_duration",
|
||||
unit="s",
|
||||
description="HTTP request duration",
|
||||
)
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
started = time.perf_counter()
|
||||
status = 500
|
||||
|
||||
async def wrapped_send(message):
|
||||
nonlocal status
|
||||
|
||||
if message["type"] == "http.response.start":
|
||||
status = message["status"]
|
||||
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, wrapped_send)
|
||||
finally:
|
||||
route = getattr(
|
||||
scope.get("route"), "path", "unmatched"
|
||||
)
|
||||
|
||||
method = scope.get("method", "OTHER")
|
||||
|
||||
if method not in {
|
||||
"GET", "POST", "PUT", "PATCH",
|
||||
"DELETE", "HEAD", "OPTIONS",
|
||||
}:
|
||||
method = "OTHER"
|
||||
|
||||
elapsed = time.perf_counter() - started
|
||||
|
||||
attributes = {
|
||||
"method": method,
|
||||
"route": route,
|
||||
"status_code": status,
|
||||
"status_class": f"{status // 100}xx",
|
||||
}
|
||||
|
||||
self.requests.add(1, attributes)
|
||||
self.duration.record(elapsed, attributes)
|
||||
|
||||
event(
|
||||
"http_request_completed",
|
||||
method=method,
|
||||
route=route,
|
||||
status_code=status,
|
||||
duration_ms=round(elapsed * 1000, 3),
|
||||
)
|
||||
|
||||
|
||||
async def observe_job(process, payload):
|
||||
tracer = trace.get_tracer("messenger.worker")
|
||||
meter = metrics.get_meter("messenger.worker")
|
||||
|
||||
jobs = meter.create_counter(
|
||||
"messenger_jobs",
|
||||
description="Job processing attempts by outcome",
|
||||
)
|
||||
|
||||
duration = meter.create_histogram(
|
||||
"messenger_job_duration",
|
||||
unit="s",
|
||||
description="Job processing duration",
|
||||
)
|
||||
|
||||
started = time.perf_counter()
|
||||
outcome = "error"
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
"attachment.process",
|
||||
kind=SpanKind.CONSUMER,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as span:
|
||||
try:
|
||||
outcome = await process(payload)
|
||||
|
||||
if outcome not in {
|
||||
"success", "failed", "retry", "skipped"
|
||||
}:
|
||||
outcome = "unknown"
|
||||
|
||||
return outcome
|
||||
|
||||
finally:
|
||||
elapsed = time.perf_counter() - started
|
||||
|
||||
span.set_attribute("job.outcome", outcome)
|
||||
span.set_attribute("job.type", "attachment.process.v1")
|
||||
|
||||
if outcome in {"failed", "retry", "error", "unknown"}:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
else:
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
|
||||
attributes = {
|
||||
"job_type": "attachment.process.v1",
|
||||
"outcome": outcome,
|
||||
}
|
||||
jobs.add(1, attributes)
|
||||
duration.record(elapsed, attributes)
|
||||
|
||||
event(
|
||||
"job_processing_completed",
|
||||
outcome=outcome,
|
||||
duration_ms=round(elapsed * 1000, 3),
|
||||
)
|
||||
+457
@@ -0,0 +1,457 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import random
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.database import SessionFactory
|
||||
from src.telemetry import setup, observe_job
|
||||
from src.queue import QUEUE, connect
|
||||
from src.storage import get_object, put_object
|
||||
from src.images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
MAX_PROCESSING_SECONDS = float(
|
||||
os.getenv("MAX_PROCESSING_SECONDS", "30")
|
||||
)
|
||||
|
||||
|
||||
class PermanentProcessingError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry_delay(attempt: int) -> float:
|
||||
base = min(60.0, 2.0 ** attempt)
|
||||
return base * random.uniform(0.75, 1.25)
|
||||
|
||||
|
||||
def validate_worker_image(body: bytes):
|
||||
if not body or len(body) > MAX_UPLOAD_BYTES:
|
||||
raise PermanentProcessingError("invalid_image_size")
|
||||
|
||||
try:
|
||||
with Image.open(io.BytesIO(body)) as image:
|
||||
if image.format not in {"PNG", "JPEG"}:
|
||||
raise PermanentProcessingError("unsupported_image_format")
|
||||
|
||||
if image.width * image.height > MAX_IMAGE_PIXELS:
|
||||
raise PermanentProcessingError("image_pixel_limit")
|
||||
|
||||
image.verify()
|
||||
|
||||
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError) as exc:
|
||||
raise PermanentProcessingError("invalid_image") from exc
|
||||
|
||||
|
||||
def make_thumbnail(body: bytes):
|
||||
with Image.open(io.BytesIO(body)) as source:
|
||||
source.load()
|
||||
image = ImageOps.exif_transpose(source)
|
||||
image.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
|
||||
if image.mode != "RGB":
|
||||
rgba = image.convert("RGBA")
|
||||
background = Image.new("RGBA", rgba.size, "white")
|
||||
background.alpha_composite(rgba)
|
||||
image = background.convert("RGB")
|
||||
|
||||
output = io.BytesIO()
|
||||
image.save(output, format="JPEG", quality=85, optimize=True)
|
||||
|
||||
return output.getvalue(), image.width, image.height
|
||||
|
||||
|
||||
def make_crop(body: bytes):
|
||||
with Image.open(io.BytesIO(body)) as source:
|
||||
source.load()
|
||||
image = ImageOps.exif_transpose(source).convert("RGB")
|
||||
image = ImageOps.fit(
|
||||
image,
|
||||
(128, 128),
|
||||
method=Image.Resampling.LANCZOS,
|
||||
centering=(0.5, 0.5),
|
||||
)
|
||||
|
||||
output = io.BytesIO()
|
||||
image.save(output, format="JPEG", quality=85, optimize=True)
|
||||
|
||||
return output.getvalue(), image.width, image.height
|
||||
|
||||
|
||||
def make_optimized(body: bytes):
|
||||
with Image.open(io.BytesIO(body)) as source:
|
||||
source.load()
|
||||
image = ImageOps.exif_transpose(source).convert("RGB")
|
||||
|
||||
output = io.BytesIO()
|
||||
image.save(output, format="WEBP", quality=80, method=4)
|
||||
|
||||
return output.getvalue(), image.width, image.height
|
||||
|
||||
|
||||
def fault_injection(point: str):
|
||||
if os.getenv("FAULT_INJECTION_ENABLED") != "1":
|
||||
return
|
||||
|
||||
if os.getenv("FAULT_INJECTION_POINT") != point:
|
||||
return
|
||||
|
||||
marker = f"/tmp/lab5_fault_{point}"
|
||||
|
||||
try:
|
||||
fd = os.open(marker, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||
except FileExistsError:
|
||||
return
|
||||
|
||||
os.close(fd)
|
||||
logging.error("FAULT INJECTION: %s", point)
|
||||
os._exit(77)
|
||||
|
||||
|
||||
async def process(payload: dict):
|
||||
job_id = UUID(payload["job_id"])
|
||||
attachment_id = UUID(payload["attachment_id"])
|
||||
generation = payload.get("generation", 1)
|
||||
execution_id = uuid4()
|
||||
|
||||
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT j.status, j.attempt, j.generation,
|
||||
a.s3_key, a.content_type, a.chat_id
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.id = :job_id
|
||||
AND j.attachment_id = :attachment_id
|
||||
FOR UPDATE OF j
|
||||
"""),
|
||||
{"job_id": job_id, "attachment_id": attachment_id},
|
||||
)
|
||||
|
||||
row = result.one_or_none()
|
||||
|
||||
if row is None or row.status in ("ready", "failed"):
|
||||
return "skipped"
|
||||
|
||||
if row.attempt != payload["attempt"]:
|
||||
return "skipped"
|
||||
|
||||
if row.generation != generation:
|
||||
return "skipped"
|
||||
|
||||
if row.status == "processing":
|
||||
return "skipped"
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'processing',
|
||||
started_at = now(),
|
||||
execution_id = :execution_id
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": job_id, "execution_id": execution_id},
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'processing', updated_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": attachment_id},
|
||||
)
|
||||
|
||||
try:
|
||||
body = await get_object(row.s3_key)
|
||||
validate_worker_image(body)
|
||||
thumbnail, width, height = await asyncio.to_thread(
|
||||
make_thumbnail, body
|
||||
)
|
||||
|
||||
crop, crop_width, crop_height = await asyncio.to_thread(
|
||||
make_crop, body
|
||||
)
|
||||
|
||||
optimized, optimized_width, optimized_height = await asyncio.to_thread(
|
||||
make_optimized, body
|
||||
)
|
||||
|
||||
original_key = (
|
||||
f"attachments/{row.chat_id}/{attachment_id}/g{generation}/original"
|
||||
)
|
||||
thumbnail_key = (
|
||||
f"variants/{row.chat_id}/{attachment_id}/g{generation}/thumbnail.jpg"
|
||||
)
|
||||
|
||||
fault_injection("before_side_effect")
|
||||
|
||||
await put_object(original_key, body, row.content_type)
|
||||
await put_object(thumbnail_key, thumbnail, "image/jpeg")
|
||||
crop_key = (
|
||||
f"variants/{row.chat_id}/{attachment_id}/g{generation}/crop.jpg"
|
||||
)
|
||||
optimized_key = (
|
||||
f"variants/{row.chat_id}/{attachment_id}/g{generation}/optimized.webp"
|
||||
)
|
||||
|
||||
await put_object(crop_key, crop, "image/jpeg")
|
||||
await put_object(optimized_key, optimized, "image/webp")
|
||||
|
||||
fault_injection("after_side_effect")
|
||||
|
||||
|
||||
if (
|
||||
os.getenv("FAULT_INJECTION_ENABLED") == "1"
|
||||
and os.getenv("FAULT_INJECTION_POINT") == "pause_before_commit"
|
||||
):
|
||||
marker = "/tmp/lab5_pause_before_commit"
|
||||
|
||||
with open(marker, "w", encoding="utf-8") as file:
|
||||
file.write(str(execution_id))
|
||||
|
||||
deadline = time.monotonic() + 180
|
||||
|
||||
while os.path.exists(marker):
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("pause_before_commit_timeout")
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
variant = {
|
||||
"name": "thumbnail",
|
||||
"s3_key": thumbnail_key,
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(thumbnail),
|
||||
"width": width,
|
||||
"height": height,
|
||||
"sha256": hashlib.sha256(thumbnail).hexdigest(),
|
||||
}
|
||||
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT status, attempt, generation, execution_id
|
||||
FROM attachment_jobs
|
||||
WHERE id = :id
|
||||
FOR UPDATE
|
||||
"""),
|
||||
{"id": job_id},
|
||||
)
|
||||
|
||||
current = result.one_or_none()
|
||||
|
||||
if (
|
||||
current is None
|
||||
or current.status != "processing"
|
||||
or current.attempt != row.attempt
|
||||
or current.generation != generation
|
||||
or current.execution_id != execution_id
|
||||
):
|
||||
return "skipped"
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'ready',
|
||||
s3_key = :key,
|
||||
variants = CAST(:variants AS json),
|
||||
error_code = NULL,
|
||||
updated_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{
|
||||
"id": attachment_id,
|
||||
"key": original_key,
|
||||
"variants": json.dumps([
|
||||
variant,
|
||||
{
|
||||
"name": "crop",
|
||||
"s3_key": crop_key,
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(crop),
|
||||
"width": crop_width,
|
||||
"height": crop_height,
|
||||
"sha256": hashlib.sha256(crop).hexdigest(),
|
||||
},
|
||||
{
|
||||
"name": "optimized",
|
||||
"s3_key": optimized_key,
|
||||
"content_type": "image/webp",
|
||||
"size_bytes": len(optimized),
|
||||
"width": optimized_width,
|
||||
"height": optimized_height,
|
||||
"sha256": hashlib.sha256(optimized).hexdigest(),
|
||||
},
|
||||
]),
|
||||
},
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'ready',
|
||||
next_attempt_at = NULL,
|
||||
last_error_code = NULL,
|
||||
finished_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": job_id},
|
||||
)
|
||||
|
||||
|
||||
return "success"
|
||||
|
||||
except Exception as exc:
|
||||
|
||||
logging.exception("Processing failed: %s", attachment_id)
|
||||
|
||||
permanent = isinstance(exc, PermanentProcessingError)
|
||||
|
||||
error_code = (
|
||||
|
||||
str(exc)[:64]
|
||||
|
||||
if permanent
|
||||
|
||||
else "temporary_processing_error"
|
||||
|
||||
)
|
||||
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT status, attempt, generation, execution_id
|
||||
FROM attachment_jobs
|
||||
WHERE id = :id
|
||||
FOR UPDATE
|
||||
"""),
|
||||
{"id": job_id},
|
||||
)
|
||||
|
||||
current = result.one_or_none()
|
||||
|
||||
if (
|
||||
current is None
|
||||
or current.status != "processing"
|
||||
or current.attempt != row.attempt
|
||||
or current.generation != generation
|
||||
or current.execution_id != execution_id
|
||||
):
|
||||
return "skipped"
|
||||
if permanent or row.attempt >= 5:
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'failed',
|
||||
next_attempt_at = NULL,
|
||||
last_error_code = :error_code,
|
||||
finished_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": job_id, "error_code": error_code},
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'failed',
|
||||
error_code = :error_code,
|
||||
updated_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{
|
||||
"id": attachment_id,
|
||||
"error_code": error_code,
|
||||
},
|
||||
)
|
||||
else:
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued',
|
||||
attempt = attempt + 1,
|
||||
published_at = NULL,
|
||||
started_at = NULL,
|
||||
next_attempt_at = now() + (:delay * interval '1 second'),
|
||||
last_error_code = :error_code
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{
|
||||
"id": job_id,
|
||||
"delay": retry_delay(row.attempt),
|
||||
"error_code": error_code,
|
||||
}
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'queued', updated_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": attachment_id},
|
||||
)
|
||||
|
||||
|
||||
return "failed" if permanent or row.attempt >= 5 else "retry"
|
||||
|
||||
|
||||
def main():
|
||||
setup("messenger-worker")
|
||||
while True:
|
||||
connection = None
|
||||
|
||||
try:
|
||||
connection, channel = connect()
|
||||
channel.basic_qos(prefetch_count=1)
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
def callback(ch, method, properties, body):
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
asyncio.wait_for(
|
||||
observe_job(process, json.loads(body)),
|
||||
timeout=MAX_PROCESSING_SECONDS,
|
||||
)
|
||||
)
|
||||
fault_injection("before_ack")
|
||||
ch.basic_ack(delivery_tag=method.delivery_tag)
|
||||
except Exception:
|
||||
logging.exception("Worker processing error")
|
||||
ch.basic_nack(
|
||||
delivery_tag=method.delivery_tag,
|
||||
requeue=True,
|
||||
)
|
||||
time.sleep(2)
|
||||
|
||||
channel.basic_consume(
|
||||
queue=QUEUE,
|
||||
on_message_callback=callback,
|
||||
)
|
||||
channel.start_consuming()
|
||||
|
||||
except Exception:
|
||||
logging.exception("Worker reconnect")
|
||||
time.sleep(3)
|
||||
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user