forked from mtusi2026/mtusi2026lab5
Очереди и асинхронная обработка изображений, трек 1
This commit is contained in:
@@ -0,0 +1,242 @@
|
||||
import hashlib
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO
|
||||
|
||||
from fastapi import APIRouter, Header, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from app.security import get_current_user
|
||||
|
||||
router = APIRouter(tags=["attachments"])
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
ALLOWED = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
||||
BAD_FILENAME = re.compile(r'[/\\\x00-\x1f]')
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
CHUNK = 64 * 1024
|
||||
|
||||
|
||||
def error_response(status, code, message, request_id, headers=None):
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers=headers or {},
|
||||
)
|
||||
|
||||
|
||||
def validate_image(data: bytes):
|
||||
if len(data) == 0:
|
||||
raise ValueError("unsupported_media_type")
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ValueError("payload_too_large")
|
||||
try:
|
||||
img = Image.open(BytesIO(data))
|
||||
img.verify()
|
||||
img = Image.open(BytesIO(data))
|
||||
fmt = img.format
|
||||
w, h = img.size
|
||||
except (UnidentifiedImageError, OSError, ValueError):
|
||||
raise ValueError("unsupported_media_type")
|
||||
if fmt not in ALLOWED:
|
||||
raise ValueError("unsupported_media_type")
|
||||
if w * h > MAX_PIXELS:
|
||||
raise ValueError("payload_too_large")
|
||||
return ALLOWED[fmt], w, h, hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def safe_filename(name: str) -> str:
|
||||
if not name or len(name) > 255:
|
||||
raise ValueError("invalid_request")
|
||||
if BAD_FILENAME.search(name):
|
||||
raise ValueError("invalid_request")
|
||||
return name
|
||||
|
||||
|
||||
async def _auth(request, authorization):
|
||||
try:
|
||||
user, _ = await get_current_user(request, authorization)
|
||||
return user, None
|
||||
except Exception:
|
||||
return None, error_response(
|
||||
401, "unauthorized", "unauthorized", request.state.request_id,
|
||||
headers={"WWW-Authenticate": BEARER_CHALLENGE},
|
||||
)
|
||||
|
||||
|
||||
async def _read_limited(request, limit):
|
||||
buf = bytearray()
|
||||
async for chunk in request.stream():
|
||||
buf.extend(chunk)
|
||||
if len(buf) > limit:
|
||||
raise ValueError("payload_too_large")
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
@router.post("/chats/{chat_id}/attachments", status_code=202)
|
||||
async def upload_attachment(chat_id: str, filename: str, request: Request,
|
||||
authorization: str | None = Header(default=None)):
|
||||
rid = request.state.request_id
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except (ValueError, TypeError):
|
||||
return error_response(400, "invalid_request", "invalid uuid", rid)
|
||||
|
||||
user, err = await _auth(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
|
||||
if not await request.app.state.storage.is_chat_member(chat_id, user["id"]):
|
||||
return error_response(404, "not_found", "chat not found", rid)
|
||||
|
||||
try:
|
||||
safe_filename(filename)
|
||||
except ValueError:
|
||||
return error_response(400, "invalid_request", "invalid filename", rid)
|
||||
|
||||
try:
|
||||
data = await _read_limited(request, MAX_BYTES)
|
||||
except ValueError:
|
||||
return error_response(413, "payload_too_large", "payload_too_large", rid)
|
||||
|
||||
try:
|
||||
content_type, w, h, sha = validate_image(data)
|
||||
except ValueError as e:
|
||||
code = str(e)
|
||||
status = 413 if code == "payload_too_large" else 415
|
||||
return error_response(status, code, code, rid)
|
||||
|
||||
att_id = str(uuid.uuid4())
|
||||
staging_key = f"staging/{chat_id}/{att_id}"
|
||||
|
||||
try:
|
||||
request.app.state.s3.put(staging_key, data, content_type)
|
||||
except Exception:
|
||||
return error_response(503, "unavailable", "storage unavailable", rid)
|
||||
|
||||
job = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(uuid.uuid4()),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": att_id,
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
try:
|
||||
att = await request.app.state.storage.create_attachment_with_job_and_outbox(
|
||||
att_id, chat_id, user["id"], staging_key,
|
||||
filename, content_type, len(data), sha, job,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
request.app.state.s3.remove(staging_key)
|
||||
except Exception:
|
||||
pass
|
||||
return error_response(503, "unavailable", "queue unavailable", rid)
|
||||
|
||||
return att
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}")
|
||||
async def get_attachment(attachment_id: str, request: Request,
|
||||
authorization: str | None = Header(default=None)):
|
||||
rid = request.state.request_id
|
||||
try:
|
||||
uuid.UUID(attachment_id)
|
||||
except (ValueError, TypeError):
|
||||
return error_response(400, "invalid_request", "invalid uuid", rid)
|
||||
user, err = await _auth(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
att = await request.app.state.storage.get_attachment(attachment_id)
|
||||
if att is None:
|
||||
return error_response(404, "not_found", "attachment not found", rid)
|
||||
if not await request.app.state.storage.is_chat_member(att["chat_id"], user["id"]):
|
||||
return error_response(404, "not_found", "attachment not found", rid)
|
||||
att.pop("_object_key", None)
|
||||
att.pop("_variant_keys", None)
|
||||
return att
|
||||
|
||||
|
||||
@router.post("/attachments/{attachment_id}/replay", status_code=202)
|
||||
async def replay_attachment(attachment_id: str, request: Request,
|
||||
authorization: str | None = Header(default=None)):
|
||||
rid = request.state.request_id
|
||||
try:
|
||||
uuid.UUID(attachment_id)
|
||||
except (ValueError, TypeError):
|
||||
return error_response(400, "invalid_request", "invalid uuid", rid)
|
||||
user, err = await _auth(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
att = await request.app.state.storage.get_attachment(attachment_id)
|
||||
if att is None:
|
||||
return error_response(404, "not_found", "attachment not found", rid)
|
||||
if not await request.app.state.storage.is_chat_member(att["chat_id"], user["id"]):
|
||||
return error_response(404, "not_found", "attachment not found", rid)
|
||||
result = await request.app.state.storage.replay_failed_attachment(attachment_id)
|
||||
if result == "not_found":
|
||||
return error_response(404, "not_found", "attachment not found", rid)
|
||||
if result == "already_ready":
|
||||
return error_response(409, "conflict", "attachment already ready", rid)
|
||||
if result == "not_failed":
|
||||
return error_response(409, "conflict", "attachment is not failed", rid)
|
||||
att = await request.app.state.storage.get_attachment(attachment_id)
|
||||
att.pop("_object_key", None)
|
||||
att.pop("_variant_keys", None)
|
||||
return att
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}/content")
|
||||
async def download_attachment(attachment_id: str, request: Request,
|
||||
variant: str = "original",
|
||||
authorization: str | None = Header(default=None)):
|
||||
rid = request.state.request_id
|
||||
try:
|
||||
uuid.UUID(attachment_id)
|
||||
except (ValueError, TypeError):
|
||||
return error_response(400, "invalid_request", "invalid uuid", rid)
|
||||
user, err = await _auth(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
att = await request.app.state.storage.get_attachment(attachment_id)
|
||||
if att is None:
|
||||
return error_response(404, "not_found", "attachment not found", rid)
|
||||
if not await request.app.state.storage.is_chat_member(att["chat_id"], user["id"]):
|
||||
return error_response(404, "not_found", "attachment not found", rid)
|
||||
|
||||
if att["status"] in ("queued", "processing"):
|
||||
return error_response(409, "conflict", "attachment not ready", rid)
|
||||
if att["status"] == "failed":
|
||||
return error_response(409, "conflict", "attachment failed", rid)
|
||||
|
||||
if variant == "original":
|
||||
obj_key = att["_object_key"]
|
||||
content_type = att["content_type"]
|
||||
size_bytes = att["size_bytes"]
|
||||
else:
|
||||
found = next((v for v in att["variants"] if v["name"] == variant), None)
|
||||
if not found:
|
||||
return error_response(404, "not_found", "variant not found", rid)
|
||||
|
||||
obj_key = att["_variant_keys"].get(variant)
|
||||
if not obj_key:
|
||||
return error_response(404, "not_found", "variant key not found", rid)
|
||||
|
||||
content_type = found["content_type"]
|
||||
size_bytes = found["size_bytes"]
|
||||
|
||||
try:
|
||||
obj = request.app.state.s3.get(obj_key)
|
||||
except Exception:
|
||||
return error_response(503, "unavailable", "storage unavailable", rid)
|
||||
|
||||
return StreamingResponse(
|
||||
obj.stream(CHUNK),
|
||||
media_type=content_type,
|
||||
headers={"Content-Length": str(size_bytes)},
|
||||
)
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
from fastapi import APIRouter, Header, HTTPException, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.security import (
|
||||
parse_basic,
|
||||
verify_password,
|
||||
new_token,
|
||||
session_expires_at,
|
||||
get_current_user,
|
||||
)
|
||||
from app.config import config
|
||||
from app.models import Session
|
||||
|
||||
router = APIRouter(tags=["auth"])
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def error_response(
|
||||
status: int, code: str, message: str, request_id: str, headers=None,
|
||||
) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers=headers or {},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/auth/sessions", response_model=Session, status_code=201)
|
||||
async def create_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
storage = request.app.state.storage
|
||||
session_store = request.app.state.session_store
|
||||
rid = request.state.request_id
|
||||
try:
|
||||
username, password = parse_basic(authorization)
|
||||
except HTTPException:
|
||||
return error_response(
|
||||
401,
|
||||
"unauthorized",
|
||||
"invalid credentials",
|
||||
rid,
|
||||
headers={"WWW-Authenticate": BASIC_CHALLENGE},
|
||||
)
|
||||
|
||||
user_row = await storage.get_user_by_username(username)
|
||||
if user_row is None or not verify_password(password, user_row["password_hash"]):
|
||||
return error_response(
|
||||
401,
|
||||
"unauthorized",
|
||||
"invalid credentials",
|
||||
rid,
|
||||
headers={"WWW-Authenticate": BASIC_CHALLENGE},
|
||||
)
|
||||
|
||||
token = new_token()
|
||||
expires_at = session_expires_at(config.SESSION_TTL_SECONDS)
|
||||
await session_store.create(token, str(user_row["id"]), expires_at)
|
||||
|
||||
user = {
|
||||
"id": str(user_row["id"]),
|
||||
"username": user_row["username"],
|
||||
"display_name": user_row["display_name"],
|
||||
"created_at": (
|
||||
user_row["created_at"]
|
||||
.isoformat()
|
||||
.replace("+00:00", "Z")
|
||||
),
|
||||
}
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at.isoformat().replace("+00:00", "Z"),
|
||||
"user": user,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/auth/sessions/current", status_code=204)
|
||||
async def revoke_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
try:
|
||||
_, token = await get_current_user(request, authorization)
|
||||
except HTTPException:
|
||||
return error_response(
|
||||
401,
|
||||
"unauthorized",
|
||||
"unauthorized",
|
||||
rid,
|
||||
headers={"WWW-Authenticate": BEARER_CHALLENGE},
|
||||
)
|
||||
await request.app.state.session_store.delete(token)
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,174 @@
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.models import (
|
||||
Chat, CreateChat, Message, CreateMessage, ChatPage, MessagePage,
|
||||
)
|
||||
from app.security import get_current_user
|
||||
|
||||
router = APIRouter(tags=["chats"])
|
||||
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
def error_response(status, code, message, request_id, headers=None):
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers=headers or {},
|
||||
)
|
||||
|
||||
|
||||
def validate_uuid(value: str) -> None:
|
||||
try:
|
||||
uuid.UUID(value)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(status_code=400, detail="invalid uuid")
|
||||
|
||||
|
||||
def validate_idempotency_key(value: str | None) -> str:
|
||||
if value is None or not IDEMPOTENCY_RE.match(value):
|
||||
raise HTTPException(status_code=400, detail="invalid idempotency key")
|
||||
return value
|
||||
|
||||
|
||||
async def resolve_actor(request: Request, authorization: str | None):
|
||||
rid = request.state.request_id
|
||||
try:
|
||||
user, _ = await get_current_user(request, authorization)
|
||||
except HTTPException as exc:
|
||||
if exc.status_code == 503:
|
||||
return None, error_response(503, "unavailable", "auth store unavailable", rid)
|
||||
return None, error_response(
|
||||
401, "unauthorized", "unauthorized", rid,
|
||||
headers={"WWW-Authenticate": BEARER_CHALLENGE},
|
||||
)
|
||||
return user, None
|
||||
|
||||
|
||||
@router.post("/chats", response_model=Chat, status_code=201)
|
||||
async def create_chat(
|
||||
data: CreateChat,
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
actor, err = await resolve_actor(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
|
||||
if len(data.member_ids) != len(set(data.member_ids)):
|
||||
return error_response(400, "invalid_request", "duplicate member_ids", rid)
|
||||
for mid in data.member_ids:
|
||||
try:
|
||||
uuid.UUID(mid)
|
||||
except (ValueError, TypeError):
|
||||
return error_response(400, "invalid_request", "invalid member uuid", rid)
|
||||
|
||||
try:
|
||||
return await request.app.state.storage.create_chat(
|
||||
data.title, data.member_ids, actor["id"],
|
||||
)
|
||||
except ValueError as e:
|
||||
msg = str(e)
|
||||
if msg == "invalid_member":
|
||||
return error_response(400, "invalid_request", "unknown member", rid)
|
||||
if msg == "creator_not_member":
|
||||
return error_response(400, "invalid_request", "creator must be a member", rid)
|
||||
return error_response(400, "invalid_request", "bad request", rid)
|
||||
|
||||
|
||||
@router.get("/chats", response_model=ChatPage)
|
||||
async def list_chats(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = Query(None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
actor, err = await resolve_actor(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
try:
|
||||
items, next_cursor = await request.app.state.storage.list_chats(
|
||||
actor["id"], limit, cursor,
|
||||
)
|
||||
except ValueError:
|
||||
return error_response(400, "invalid_request", "bad cursor", rid)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@router.get("/chats/{chat_id}", response_model=Chat)
|
||||
async def get_chat(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
validate_uuid(chat_id)
|
||||
actor, err = await resolve_actor(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
chat = await request.app.state.storage.get_chat(chat_id, actor["id"])
|
||||
if chat is None:
|
||||
return error_response(404, "not_found", "chat not found", rid)
|
||||
return chat
|
||||
|
||||
|
||||
@router.post("/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
data: CreateMessage,
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
validate_uuid(chat_id)
|
||||
validate_idempotency_key(idempotency_key)
|
||||
actor, err = await resolve_actor(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
|
||||
if not data.text.strip() and not data.attachment_ids:
|
||||
return error_response(400, "invalid_request", "text or attachment_ids required", rid)
|
||||
|
||||
try:
|
||||
return await request.app.state.storage.add_message(
|
||||
chat_id, actor["id"], data.text,
|
||||
data.attachment_ids, idempotency_key,
|
||||
)
|
||||
except ValueError as e:
|
||||
if str(e) == "idempotency_conflict":
|
||||
return error_response(409, "conflict", "idempotency key conflict", rid)
|
||||
if str(e) == "attachment_failed":
|
||||
return error_response(409, "conflict", "attachment failed", rid)
|
||||
return error_response(404, "not_found", "chat not found", rid)
|
||||
|
||||
|
||||
@router.get("/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = Query(None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
validate_uuid(chat_id)
|
||||
actor, err = await resolve_actor(request, authorization)
|
||||
if err is not None:
|
||||
return err
|
||||
try:
|
||||
items, next_cursor = await request.app.state.storage.list_messages(
|
||||
chat_id, actor["id"], limit, cursor,
|
||||
)
|
||||
except ValueError as e:
|
||||
if str(e) == "bad_cursor":
|
||||
return error_response(400, "invalid_request", "bad cursor", rid)
|
||||
return error_response(404, "not_found", "chat not found", rid)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,53 @@
|
||||
import asyncio
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
async def liveness():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
async def _check_postgres(request: Request) -> None:
|
||||
async with request.app.state.storage._pool.acquire() as conn:
|
||||
await conn.fetchval("SELECT 1")
|
||||
|
||||
|
||||
async def _check_redis(request: Request) -> None:
|
||||
store = request.app.state.session_store
|
||||
if hasattr(store, "_client"):
|
||||
await store._client.ping()
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
async def readiness(request: Request):
|
||||
rid = getattr(request.state, "request_id", "")
|
||||
try:
|
||||
await asyncio.wait_for(_check_postgres(request), timeout=2.0)
|
||||
except Exception:
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "db unavailable",
|
||||
"request_id": rid,
|
||||
}
|
||||
},
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(_check_redis(request), timeout=2.0)
|
||||
except Exception:
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "cache unavailable",
|
||||
"request_id": rid,
|
||||
}
|
||||
},
|
||||
)
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,58 @@
|
||||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.models import User, CreateUser
|
||||
from app.security import hash_password, get_current_user
|
||||
|
||||
router = APIRouter(tags=["users"])
|
||||
|
||||
|
||||
def error_response(
|
||||
status: int, code: str, message: str, request_id: str, headers=None,
|
||||
) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers=headers or {},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/users", response_model=User, status_code=201)
|
||||
async def register_user(data: CreateUser, request: Request):
|
||||
storage = request.app.state.storage
|
||||
rid = request.state.request_id
|
||||
password_hash = hash_password(data.password)
|
||||
try:
|
||||
user = await storage.create_user(
|
||||
data.username, data.display_name, password_hash,
|
||||
)
|
||||
return user
|
||||
except ValueError:
|
||||
return error_response(409, "conflict", "username already taken", rid)
|
||||
|
||||
|
||||
@router.get("/users/me", response_model=User)
|
||||
async def current_user(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
try:
|
||||
user, _ = await get_current_user(request, authorization)
|
||||
except HTTPException as exc:
|
||||
if exc.status_code == 503:
|
||||
return error_response(503, "unavailable", "auth store unavailable", rid)
|
||||
return error_response(
|
||||
401,
|
||||
"unauthorized",
|
||||
"unauthorized",
|
||||
rid,
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
return user
|
||||
@@ -0,0 +1,69 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
import aio_pika
|
||||
from aio_pika.abc import AbstractRobustConnection
|
||||
|
||||
from app.config import config
|
||||
|
||||
_connection: AbstractRobustConnection | None = None
|
||||
_lock = asyncio.Lock()
|
||||
|
||||
PREFETCH_COUNT = int(os.getenv("PREFETCH_COUNT", "1"))
|
||||
|
||||
|
||||
async def get_connection() -> AbstractRobustConnection:
|
||||
global _connection
|
||||
async with _lock:
|
||||
if _connection is None or _connection.is_closed:
|
||||
_connection = await aio_pika.connect_robust(config.RABBITMQ_URL)
|
||||
return _connection
|
||||
|
||||
|
||||
async def publish_job(job: dict, is_dlq: bool = False) -> None:
|
||||
connection = await get_connection()
|
||||
channel = await connection.channel()
|
||||
queue_name = config.RABBITMQ_QUEUE + (".dlq" if is_dlq else "")
|
||||
|
||||
await channel.declare_queue(queue_name, durable=True)
|
||||
await channel.default_exchange.publish(
|
||||
aio_pika.Message(
|
||||
body=json.dumps(job).encode(),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
content_type="application/json",
|
||||
),
|
||||
routing_key=queue_name,
|
||||
)
|
||||
await channel.close()
|
||||
|
||||
|
||||
async def consume_jobs(handler) -> None:
|
||||
while True:
|
||||
try:
|
||||
connection = await get_connection()
|
||||
channel = await connection.channel()
|
||||
await channel.set_qos(prefetch_count=PREFETCH_COUNT)
|
||||
queue = await channel.declare_queue(config.RABBITMQ_QUEUE, durable=True)
|
||||
|
||||
# Запускаем обработчик в фоне, чтобы не блокировать цикл
|
||||
async def process_message(message: aio_pika.IncomingMessage):
|
||||
try:
|
||||
job = json.loads(message.body)
|
||||
print(f"[broker] got job: {job.get('attachment_id')}", flush=True)
|
||||
await handler(job)
|
||||
await message.ack()
|
||||
except Exception as e:
|
||||
print(f"[broker] handler error: {e}", flush=True)
|
||||
await message.reject(requeue=False)
|
||||
|
||||
async def on_message(message: aio_pika.IncomingMessage):
|
||||
# Запускаем в фоне, не ждем завершения, чтобы сразу взять следующее
|
||||
asyncio.create_task(process_message(message))
|
||||
|
||||
await queue.consume(on_message)
|
||||
print(f"[broker] listening for jobs (prefetch={PREFETCH_COUNT})...", flush=True)
|
||||
await asyncio.Future()
|
||||
except Exception as e:
|
||||
print(f"[broker] connection error: {e}. Reconnecting in 3 seconds...", flush=True)
|
||||
await asyncio.sleep(3)
|
||||
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.config import config
|
||||
|
||||
CACHE_TTL_SECONDS = 30
|
||||
|
||||
|
||||
class Cache:
|
||||
def __init__(self, client: redis.Redis) -> None:
|
||||
self._client = client
|
||||
|
||||
async def get_json(self, key: str) -> Optional[dict]:
|
||||
raw = await self._client.get(key)
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
|
||||
async def set_json(self, key: str, value: dict, ttl: int = CACHE_TTL_SECONDS) -> None:
|
||||
await self._client.set(key, json.dumps(value), ex=ttl)
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
await self._client.delete(key)
|
||||
|
||||
async def invalidate_chat(self, chat_id: str) -> None:
|
||||
"""Удалить все ключи, связанные с чатом (история)."""
|
||||
pattern = f"messages:{chat_id}:*"
|
||||
cursor = 0
|
||||
while True:
|
||||
cursor, keys = await self._client.scan(cursor=cursor, match=pattern, count=100)
|
||||
if keys:
|
||||
await self._client.delete(*keys)
|
||||
if cursor == 0:
|
||||
break
|
||||
|
||||
async def try_lock(self, key: str, ttl: int = 5) -> bool:
|
||||
"""Атомарно установить ключ. True — если установили мы."""
|
||||
result = await self._client.set(key, "1", nx=True, ex=ttl)
|
||||
return bool(result)
|
||||
|
||||
async def unlock(self, key: str) -> None:
|
||||
await self._client.delete(key)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._client.aclose()
|
||||
|
||||
|
||||
def make_cache() -> Cache:
|
||||
client = redis.from_url(
|
||||
config.CACHE_URL,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=10,
|
||||
socket_timeout=10,
|
||||
)
|
||||
return Cache(client)
|
||||
@@ -0,0 +1,29 @@
|
||||
import os
|
||||
import secrets
|
||||
|
||||
|
||||
class Config:
|
||||
DATABASE_URL: str = os.getenv(
|
||||
"DATABASE_URL",
|
||||
"postgresql://messenger:messenger@localhost:5432/messenger",
|
||||
)
|
||||
SESSION_TTL_SECONDS: int = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
APP_HOST: str = os.getenv("APP_HOST", "0.0.0.0")
|
||||
APP_PORT: int = int(os.getenv("APP_PORT", "8080"))
|
||||
SESSION_STORE: str = os.getenv("SESSION_STORE", "postgres")
|
||||
CACHE_URL: str = os.getenv("CACHE_URL", "redis://valkey:6379/0")
|
||||
INSTANCE_ID: str = os.getenv("INSTANCE_ID") or secrets.token_hex(6)
|
||||
|
||||
S3_ENDPOINT: str = os.getenv("S3_ENDPOINT", "minio:9000")
|
||||
S3_PUBLIC_ENDPOINT: str = os.getenv("S3_PUBLIC_ENDPOINT", "localhost:9000")
|
||||
S3_ACCESS_KEY: str = os.getenv("S3_ACCESS_KEY", "minioadmin")
|
||||
S3_SECRET_KEY: str = os.getenv("S3_SECRET_KEY", "minioadmin")
|
||||
S3_BUCKET: str = os.getenv("S3_BUCKET", "attachments")
|
||||
S3_SECURE: bool = os.getenv("S3_SECURE", "false").lower() == "true"
|
||||
|
||||
RABBITMQ_URL: str = os.getenv("RABBITMQ_URL", "amqp://messenger:messenger@rabbitmq:5672/")
|
||||
RABBITMQ_QUEUE: str = os.getenv("RABBITMQ_QUEUE", "attachment.process.v1")
|
||||
MAX_ATTEMPTS: int = int(os.getenv("MAX_ATTEMPTS", "5"))
|
||||
|
||||
|
||||
config = Config()
|
||||
@@ -0,0 +1,30 @@
|
||||
import asyncpg
|
||||
from app.config import config
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self) -> None:
|
||||
self._pool: asyncpg.Pool | None = None
|
||||
|
||||
async def connect(self) -> None:
|
||||
self._pool = await asyncpg.create_pool(
|
||||
config.DATABASE_URL,
|
||||
min_size=2,
|
||||
max_size=10,
|
||||
command_timeout=5,
|
||||
timeout=5,
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._pool is not None:
|
||||
await self._pool.close()
|
||||
self._pool = None
|
||||
|
||||
@property
|
||||
def pool(self) -> asyncpg.Pool:
|
||||
if self._pool is None:
|
||||
raise RuntimeError("database is not connected")
|
||||
return self._pool
|
||||
|
||||
|
||||
db = Database()
|
||||
@@ -0,0 +1,37 @@
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from app.cache import make_cache
|
||||
from app.db import db
|
||||
from app.storage import Storage
|
||||
|
||||
|
||||
async def main():
|
||||
await db.connect()
|
||||
cache = make_cache()
|
||||
storage = Storage(db.pool, cache)
|
||||
|
||||
print("[lease_checker] started", flush=True)
|
||||
while True:
|
||||
try:
|
||||
expired_jobs = await storage.get_expired_jobs()
|
||||
for job in expired_jobs:
|
||||
print(f"[lease_checker] requeueing expired job {job['job_id']}", flush=True)
|
||||
await storage.reset_job_status(str(job["job_id"]))
|
||||
job_payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(job["job_id"]),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(job["attachment_id"]),
|
||||
"pipeline_version": job["pipeline_version"],
|
||||
"attempt": job["attempt"],
|
||||
"created_at": "2026-01-01T00:00:00Z",
|
||||
}
|
||||
await storage.create_outbox(job_payload)
|
||||
except Exception as e:
|
||||
print(f"[lease_checker] error: {e}", flush=True)
|
||||
await asyncio.sleep(10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
|
||||
from app.db import db
|
||||
from app.storage import Storage
|
||||
from app.session_store import make_session_store
|
||||
from app.cache import make_cache
|
||||
from app.config import config
|
||||
from app.s3 import s3
|
||||
from app.api import health, users, auth, chats, attachments
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await db.connect()
|
||||
app.state.cache = make_cache()
|
||||
app.state.storage = Storage(db.pool, app.state.cache)
|
||||
app.state.session_store = make_session_store(db.pool)
|
||||
await app.state.session_store.delete_expired()
|
||||
s3.ensure_bucket()
|
||||
app.state.s3 = s3
|
||||
yield
|
||||
await app.state.cache.close()
|
||||
await app.state.session_store.close()
|
||||
await db.close()
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.5.0", lifespan=lifespan)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_context(request: Request, call_next):
|
||||
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = rid
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = config.INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return JSONResponse(status_code=400,
|
||||
content={"error": {"code": "invalid_request", "message": "validation error", "request_id": rid}},
|
||||
headers={"X-Request-Id": rid})
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
headers = {"X-Request-Id": rid}
|
||||
if exc.headers:
|
||||
headers.update(exc.headers)
|
||||
code_map = {400:"invalid_request",401:"unauthorized",404:"not_found",409:"conflict",
|
||||
413:"payload_too_large",415:"unsupported_media_type",429:"rate_limited",503:"unavailable"}
|
||||
code = code_map.get(exc.status_code, "internal_error")
|
||||
message = exc.detail if isinstance(exc.detail, str) else "error"
|
||||
return JSONResponse(status_code=exc.status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": rid}},
|
||||
headers=headers)
|
||||
|
||||
|
||||
try:
|
||||
from asyncpg.exceptions import (
|
||||
PostgresConnectionError, TooManyConnectionsError,
|
||||
CannotConnectNowError, ConnectionDoesNotExistError,
|
||||
)
|
||||
|
||||
@app.exception_handler(PostgresConnectionError)
|
||||
@app.exception_handler(TooManyConnectionsError)
|
||||
@app.exception_handler(CannotConnectNowError)
|
||||
@app.exception_handler(ConnectionDoesNotExistError)
|
||||
async def postgres_unavailable_handler(request: Request, exc: Exception):
|
||||
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return JSONResponse(status_code=503,
|
||||
content={"error": {"code": "unavailable", "message": "database unavailable", "request_id": rid}},
|
||||
headers={"X-Request-Id": rid})
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
try:
|
||||
import redis.exceptions as redis_exceptions
|
||||
|
||||
@app.exception_handler(redis_exceptions.ConnectionError)
|
||||
@app.exception_handler(redis_exceptions.TimeoutError)
|
||||
async def redis_unavailable_handler(request: Request, exc: Exception):
|
||||
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return JSONResponse(status_code=503,
|
||||
content={"error": {"code": "unavailable", "message": "cache unavailable", "request_id": rid}},
|
||||
headers={"X-Request-Id": rid})
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def generic_exception_handler(request: Request, exc: Exception):
|
||||
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return JSONResponse(status_code=500,
|
||||
content={"error": {"code": "internal_error", "message": "internal error", "request_id": rid}},
|
||||
headers={"X-Request-Id": rid})
|
||||
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router, prefix="/api/v1")
|
||||
app.include_router(auth.router, prefix="/api/v1")
|
||||
app.include_router(chats.router, prefix="/api/v1")
|
||||
app.include_router(attachments.router, prefix="/api/v1")
|
||||
@@ -0,0 +1,19 @@
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from app.db import db
|
||||
from app.migrations import apply_migrations
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
await db.connect()
|
||||
try:
|
||||
await apply_migrations(db.pool)
|
||||
finally:
|
||||
await db.close()
|
||||
print("migrations applied", flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -0,0 +1,31 @@
|
||||
from pathlib import Path
|
||||
import asyncpg
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
|
||||
|
||||
|
||||
async def apply_migrations(pool: asyncpg.Pool) -> None:
|
||||
async with pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS applied_migrations (
|
||||
name TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
applied = {
|
||||
row["name"]
|
||||
for row in await conn.fetch("SELECT name FROM applied_migrations")
|
||||
}
|
||||
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
||||
if path.name in applied:
|
||||
continue
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
async with conn.transaction():
|
||||
await conn.execute(sql)
|
||||
await conn.execute(
|
||||
"INSERT INTO applied_migrations (name) VALUES ($1)",
|
||||
path.name,
|
||||
)
|
||||
print(f"applied migration: {path.name}", flush=True)
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
from pydantic import BaseModel, Field, ConfigDict, field_validator
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
def _not_blank(value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("must contain non-whitespace characters")
|
||||
return value
|
||||
|
||||
|
||||
def _not_blank_or_empty(value: str) -> str:
|
||||
if value and not value.strip():
|
||||
raise ValueError("must contain non-whitespace characters")
|
||||
return value
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
password: str = Field(..., min_length=12, max_length=128)
|
||||
|
||||
_check_display_name = field_validator("display_name")(_not_blank)
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
member_ids: List[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: List[str] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
_check_title = field_validator("title")(_not_blank)
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: List[str]
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: str = Field("", max_length=4000)
|
||||
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
_check_text = field_validator("text")(_not_blank_or_empty)
|
||||
|
||||
|
||||
class Attachment(BaseModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
owner_id: str
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: List[dict]
|
||||
error_code: Optional[str]
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
error: ErrorBody
|
||||
@@ -0,0 +1,31 @@
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
|
||||
from app.broker import publish_job
|
||||
from app.cache import make_cache
|
||||
from app.db import db
|
||||
from app.storage import Storage
|
||||
|
||||
|
||||
async def main():
|
||||
await db.connect()
|
||||
cache = make_cache()
|
||||
storage = Storage(db.pool, cache)
|
||||
|
||||
print("[outbox] started", flush=True)
|
||||
while True:
|
||||
try:
|
||||
jobs = await storage.get_unpublished_outbox()
|
||||
for job in jobs:
|
||||
payload = json.loads(job["payload"]) if isinstance(job["payload"], str) else job["payload"]
|
||||
await publish_job(payload)
|
||||
await storage.mark_outbox_published(str(job["id"]))
|
||||
print(f"[outbox] published {job['job_id']}", flush=True)
|
||||
except Exception as e:
|
||||
print(f"[outbox] error: {e}", flush=True)
|
||||
await asyncio.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -0,0 +1,53 @@
|
||||
from datetime import timedelta
|
||||
from io import BytesIO
|
||||
|
||||
from minio import Minio
|
||||
|
||||
from app.config import config
|
||||
|
||||
|
||||
class S3Storage:
|
||||
def __init__(self) -> None:
|
||||
common = dict(
|
||||
access_key=config.S3_ACCESS_KEY,
|
||||
secret_key=config.S3_SECRET_KEY,
|
||||
secure=config.S3_SECURE,
|
||||
region="us-east-1",
|
||||
)
|
||||
self._client = Minio(config.S3_ENDPOINT, **common)
|
||||
self._presign_client = Minio(config.S3_PUBLIC_ENDPOINT, **common)
|
||||
self._bucket = config.S3_BUCKET
|
||||
|
||||
@property
|
||||
def client(self) -> Minio:
|
||||
return self._client
|
||||
|
||||
@property
|
||||
def bucket(self) -> str:
|
||||
return self._bucket
|
||||
|
||||
def ensure_bucket(self) -> None:
|
||||
if not self._client.bucket_exists(self._bucket):
|
||||
self._client.make_bucket(self._bucket)
|
||||
|
||||
def put(self, key: str, data: bytes, content_type: str) -> None:
|
||||
self._client.put_object(
|
||||
self._bucket, key, BytesIO(data), len(data), content_type=content_type
|
||||
)
|
||||
|
||||
def get(self, key: str):
|
||||
return self._client.get_object(self._bucket, key)
|
||||
|
||||
def stat(self, key: str):
|
||||
return self._client.stat_object(self._bucket, key)
|
||||
|
||||
def remove(self, key: str) -> None:
|
||||
self._client.remove_object(self._bucket, key)
|
||||
|
||||
def presigned_put(self, key: str, expires_seconds: int = 300) -> str:
|
||||
return self._presign_client.presigned_put_object(
|
||||
self._bucket, key, expires=timedelta(seconds=expires_seconds)
|
||||
)
|
||||
|
||||
|
||||
s3 = S3Storage()
|
||||
@@ -0,0 +1,83 @@
|
||||
import base64
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHash
|
||||
from fastapi import Header, HTTPException, Request
|
||||
|
||||
_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, InvalidHash):
|
||||
return False
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(48)
|
||||
|
||||
|
||||
def parse_basic(header: str | None) -> tuple[str, str]:
|
||||
if not header or not header.lower().startswith("basic "):
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
encoded = header.split(" ", 1)[1].strip()
|
||||
try:
|
||||
decoded = base64.b64decode(encoded).decode("utf-8")
|
||||
except Exception:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
if ":" not in decoded:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
username, password = decoded.split(":", 1)
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(header: str | None) -> str:
|
||||
if not header or not header.lower().startswith("bearer "):
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
return header.split(" ", 1)[1].strip()
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
token = parse_bearer(authorization)
|
||||
session_store = request.app.state.session_store
|
||||
storage = request.app.state.storage
|
||||
|
||||
try:
|
||||
session = await session_store.get(token)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
|
||||
if session is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
if expires_at <= datetime.now(timezone.utc):
|
||||
try:
|
||||
await session_store.delete(token)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
try:
|
||||
user = await storage.get_user(session["user_id"])
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
return user, token
|
||||
|
||||
|
||||
def session_expires_at(ttl_seconds: int) -> datetime:
|
||||
return datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)
|
||||
@@ -0,0 +1,108 @@
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import asyncpg
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.config import config
|
||||
|
||||
|
||||
def _now_iso(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
class PostgresSessionStore:
|
||||
def __init__(self, pool: asyncpg.Pool) -> None:
|
||||
self._pool = pool
|
||||
|
||||
async def create(self, token: str, user_id: str, expires_at: datetime) -> dict:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO sessions (token, user_id, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING token, user_id, created_at, expires_at
|
||||
""",
|
||||
token, user_id, expires_at,
|
||||
)
|
||||
return {
|
||||
"token": row["token"],
|
||||
"user_id": str(row["user_id"]),
|
||||
"created_at": _now_iso(row["created_at"]),
|
||||
"expires_at": _now_iso(row["expires_at"]),
|
||||
}
|
||||
|
||||
async def get(self, token: str) -> Optional[dict]:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT token, user_id, created_at, expires_at
|
||||
FROM sessions WHERE token = $1
|
||||
""",
|
||||
token,
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
return {
|
||||
"token": row["token"],
|
||||
"user_id": str(row["user_id"]),
|
||||
"created_at": _now_iso(row["created_at"]),
|
||||
"expires_at": _now_iso(row["expires_at"]),
|
||||
}
|
||||
|
||||
async def delete(self, token: str) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute("DELETE FROM sessions WHERE token = $1", token)
|
||||
|
||||
async def delete_expired(self) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute("DELETE FROM sessions WHERE expires_at <= now()")
|
||||
|
||||
async def close(self) -> None:
|
||||
pass
|
||||
|
||||
class RedisSessionStore:
|
||||
def __init__(self, client: redis.Redis) -> None:
|
||||
self._client = client
|
||||
|
||||
async def create(self, token: str, user_id: str, expires_at: datetime) -> dict:
|
||||
now = datetime.now(timezone.utc)
|
||||
ttl = max(1, int((expires_at - now).total_seconds()))
|
||||
payload = {
|
||||
"token": token,
|
||||
"user_id": user_id,
|
||||
"created_at": _now_iso(now),
|
||||
"expires_at": _now_iso(expires_at),
|
||||
}
|
||||
await self._client.set(f"session:{token}", json.dumps(payload), ex=ttl)
|
||||
return payload
|
||||
|
||||
async def get(self, token: str) -> Optional[dict]:
|
||||
raw = await self._client.get(f"session:{token}")
|
||||
if raw is None:
|
||||
return None
|
||||
return json.loads(raw)
|
||||
|
||||
async def delete(self, token: str) -> None:
|
||||
await self._client.delete(f"session:{token}")
|
||||
|
||||
async def delete_expired(self) -> None:
|
||||
pass
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._client.aclose()
|
||||
|
||||
|
||||
def make_session_store(pool: asyncpg.Pool) -> PostgresSessionStore | RedisSessionStore:
|
||||
if config.SESSION_STORE == "redis":
|
||||
client = redis.from_url(
|
||||
config.CACHE_URL,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=10,
|
||||
socket_timeout=10,
|
||||
)
|
||||
return RedisSessionStore(client)
|
||||
return PostgresSessionStore(pool)
|
||||
+511
@@ -0,0 +1,511 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app.cache import Cache
|
||||
|
||||
|
||||
def _now_iso(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _canonical_hash(payload: dict) -> str:
|
||||
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self, pool: asyncpg.Pool, cache: Cache) -> None:
|
||||
self._pool = pool
|
||||
self._cache = cache
|
||||
|
||||
async def create_user(self, username, display_name, password_hash) -> dict:
|
||||
user_id = str(uuid.uuid4())
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1,$2,$3,$4)
|
||||
RETURNING id, username, display_name, created_at""",
|
||||
user_id, username, display_name, password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
raise ValueError("conflict")
|
||||
return self._user_row(row)
|
||||
|
||||
async def get_user(self, user_id: str) -> Optional[dict]:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id=$1",
|
||||
user_id,
|
||||
)
|
||||
return self._user_row(row) if row else None
|
||||
|
||||
async def get_user_by_username(self, username: str) -> Optional[dict]:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username=$1",
|
||||
username,
|
||||
)
|
||||
return dict(row) if row else None
|
||||
|
||||
async def create_chat(self, title, member_ids, creator_id) -> dict:
|
||||
if creator_id not in member_ids:
|
||||
raise ValueError("creator_not_member")
|
||||
chat_id = str(uuid.uuid4())
|
||||
async with self._pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
existing = await conn.fetchval(
|
||||
"SELECT count(*) FROM users WHERE id = ANY($1::uuid[])", member_ids,
|
||||
)
|
||||
if existing != len(member_ids):
|
||||
raise ValueError("invalid_member")
|
||||
await conn.execute("INSERT INTO chats (id, title) VALUES ($1,$2)", chat_id, title)
|
||||
await conn.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1,$2)",
|
||||
[(chat_id, uid) for uid in member_ids],
|
||||
)
|
||||
created = await conn.fetchval("SELECT created_at FROM chats WHERE id=$1", chat_id)
|
||||
return {"id": chat_id, "title": title, "member_ids": member_ids,
|
||||
"created_at": _now_iso(created)}
|
||||
|
||||
async def get_chat(self, chat_id: str, actor_id: str) -> Optional[dict]:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT id, title, created_at FROM chats WHERE id=$1", chat_id,
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
members = await conn.fetch("SELECT user_id FROM chat_members WHERE chat_id=$1", chat_id)
|
||||
member_ids = [str(m["user_id"]) for m in members]
|
||||
if actor_id not in member_ids:
|
||||
return None
|
||||
return {"id": str(row["id"]), "title": row["title"],
|
||||
"member_ids": member_ids, "created_at": _now_iso(row["created_at"])}
|
||||
|
||||
async def list_chats(self, actor_id, limit, cursor):
|
||||
async with self._pool.acquire() as conn:
|
||||
params = [actor_id]
|
||||
where = ""
|
||||
if cursor:
|
||||
try:
|
||||
cur_actor, cur_created, cur_id = cursor.split("|", 2)
|
||||
except ValueError:
|
||||
raise ValueError("bad_cursor")
|
||||
if cur_actor != actor_id:
|
||||
raise ValueError("bad_cursor")
|
||||
where = "AND (c.created_at, c.id) > ($2,$3)"
|
||||
params += [datetime.fromisoformat(cur_created.replace("Z", "+00:00")), cur_id]
|
||||
rows = await conn.fetch(
|
||||
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=$1 {where}
|
||||
ORDER BY c.created_at, c.id LIMIT ${len(params)+1}""",
|
||||
*params, limit + 1,
|
||||
)
|
||||
items = []
|
||||
for row in rows[:limit]:
|
||||
members = await conn.fetch("SELECT user_id FROM chat_members WHERE chat_id=$1", row["id"])
|
||||
items.append({"id": str(row["id"]), "title": row["title"],
|
||||
"member_ids": [str(m["user_id"]) for m in members],
|
||||
"created_at": _now_iso(row["created_at"])})
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
last = rows[limit - 1]
|
||||
next_cursor = f"{actor_id}|{_now_iso(last['created_at'])}|{last['id']}"
|
||||
return items, next_cursor
|
||||
|
||||
async def is_chat_member(self, chat_id: str, user_id: str) -> bool:
|
||||
async with self._pool.acquire() as conn:
|
||||
return await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2",
|
||||
chat_id, user_id,
|
||||
) is not None
|
||||
|
||||
async def create_pending_attachment(self, att_id, chat_id, owner_id, object_key,
|
||||
filename, content_type, size_bytes, sha256):
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""INSERT INTO attachments
|
||||
(id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, status)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'queued')
|
||||
RETURNING id, chat_id, owner_id, object_key, filename,
|
||||
content_type, size_bytes, sha256, status,
|
||||
variants, variant_keys, error_code, created_at, updated_at""",
|
||||
att_id, chat_id, owner_id, object_key,
|
||||
filename, content_type, size_bytes, sha256,
|
||||
)
|
||||
return self._attachment_row(row, public=True)
|
||||
|
||||
async def create_attachment_with_job_and_outbox(
|
||||
self, att_id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, job: dict,
|
||||
):
|
||||
async with self._pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
row = await conn.fetchrow(
|
||||
"""INSERT INTO attachments
|
||||
(id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, status)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'queued')
|
||||
RETURNING id, chat_id, owner_id, object_key, filename,
|
||||
content_type, size_bytes, sha256, status,
|
||||
variants, variant_keys, error_code, created_at, updated_at""",
|
||||
att_id, chat_id, owner_id, object_key,
|
||||
filename, content_type, size_bytes, sha256,
|
||||
)
|
||||
await conn.execute(
|
||||
"""INSERT INTO jobs (id, attachment_id, pipeline_version, attempt, status)
|
||||
VALUES ($1,$2,$3,$4,'queued')""",
|
||||
job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"],
|
||||
)
|
||||
await conn.execute(
|
||||
"INSERT INTO outbox (id, job_id, payload) VALUES ($1, $2, $3)",
|
||||
str(uuid.uuid4()), job["job_id"], json.dumps(job),
|
||||
)
|
||||
return self._attachment_row(row, public=True)
|
||||
|
||||
async def get_attachment(self, att_id: str) -> Optional[dict]:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""SELECT id, chat_id, owner_id, object_key, filename,
|
||||
content_type, size_bytes, sha256, status,
|
||||
variants, variant_keys, error_code, created_at, updated_at
|
||||
FROM attachments WHERE id=$1""",
|
||||
att_id,
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
return self._attachment_row(row, public=False)
|
||||
|
||||
async def update_attachment_status(self, att_id: str, status: str) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status=$2, updated_at=now() WHERE id=$1",
|
||||
att_id, status,
|
||||
)
|
||||
|
||||
async def complete_attachment_ready(self, att_id, original_key, variants: list, variant_keys: dict):
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""UPDATE attachments SET status='ready', object_key=$2,
|
||||
variants=$3::jsonb, variant_keys=$4::jsonb, updated_at=now() WHERE id=$1""",
|
||||
att_id, original_key, json.dumps(variants), json.dumps(variant_keys),
|
||||
)
|
||||
|
||||
async def fail_attachment(self, att_id: str, error_code: str) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status='failed', error_code=$2, updated_at=now() WHERE id=$1",
|
||||
att_id, error_code,
|
||||
)
|
||||
|
||||
async def replay_failed_attachment(self, att_id: str) -> str:
|
||||
async with self._pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
row = await conn.fetchrow(
|
||||
"SELECT id, status FROM attachments WHERE id=$1 FOR UPDATE",
|
||||
att_id,
|
||||
)
|
||||
if row is None:
|
||||
return "not_found"
|
||||
if row["status"] == "ready":
|
||||
return "already_ready"
|
||||
if row["status"] != "failed":
|
||||
return "not_failed"
|
||||
job_id = str(uuid.uuid4())
|
||||
job = {
|
||||
"schema_version": 1,
|
||||
"job_id": job_id,
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": att_id,
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status='queued', error_code=NULL, updated_at=now() WHERE id=$1",
|
||||
att_id,
|
||||
)
|
||||
await conn.execute(
|
||||
"""INSERT INTO jobs (id, attachment_id, pipeline_version, attempt, status)
|
||||
VALUES ($1,$2,$3,$4,'queued')""",
|
||||
job_id, att_id, 1, 1,
|
||||
)
|
||||
await conn.execute(
|
||||
"INSERT INTO outbox (id, job_id, payload) VALUES ($1, $2, $3)",
|
||||
str(uuid.uuid4()), job_id, json.dumps(job),
|
||||
)
|
||||
return "queued"
|
||||
|
||||
async def create_job(self, job: dict) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""INSERT INTO jobs (id, attachment_id, pipeline_version, attempt, status)
|
||||
VALUES ($1,$2,$3,$4,'queued')""",
|
||||
job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"],
|
||||
)
|
||||
|
||||
async def increment_job_attempt(self, job_id: str) -> int:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"UPDATE jobs SET attempt=attempt+1, updated_at=now() WHERE id=$1 RETURNING attempt",
|
||||
job_id,
|
||||
)
|
||||
return int(row["attempt"]) if row is not None else 0
|
||||
|
||||
async def set_job_lease(self, job_id: str, seconds: int = 60) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET lease_until = now() + interval '1 second' * $2 WHERE id = $1",
|
||||
job_id, seconds,
|
||||
)
|
||||
|
||||
async def get_expired_jobs(self) -> list[dict]:
|
||||
async with self._pool.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"""SELECT j.id as job_id, j.attachment_id, j.pipeline_version, j.attempt, j.status, a.chat_id
|
||||
FROM jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status = 'processing' AND j.lease_until < now()"""
|
||||
)
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
async def reset_job_status(self, job_id: str) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET status='queued', lease_until=NULL WHERE id=$1",
|
||||
job_id,
|
||||
)
|
||||
|
||||
async def create_outbox(self, job: dict) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""INSERT INTO outbox (id, job_id, payload) VALUES ($1, $2, $3)""",
|
||||
str(uuid.uuid4()), job["job_id"], json.dumps(job),
|
||||
)
|
||||
|
||||
async def get_unpublished_outbox(self, limit: int = 10) -> list[dict]:
|
||||
async with self._pool.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"SELECT id, job_id, payload FROM outbox WHERE published_at IS NULL ORDER BY created_at LIMIT $1",
|
||||
limit,
|
||||
)
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
async def mark_outbox_published(self, outbox_id: str) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"UPDATE outbox SET published_at = now() WHERE id = $1",
|
||||
outbox_id,
|
||||
)
|
||||
|
||||
async def _list_attachment_ids_conn(self, conn, message_id: str) -> list[str]:
|
||||
rows = await conn.fetch(
|
||||
"SELECT attachment_id FROM message_attachments WHERE message_id=$1", message_id,
|
||||
)
|
||||
return [str(r["attachment_id"]) for r in rows]
|
||||
|
||||
async def add_message(self, chat_id, sender_id, text, attachment_ids=None,
|
||||
idempotency_key=None):
|
||||
attachment_ids = attachment_ids or []
|
||||
request_hash = _canonical_hash({"text": text, "attachment_ids": sorted(attachment_ids)})
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
method = "POST"
|
||||
|
||||
if idempotency_key is not None:
|
||||
cached = await self._get_idempotent(sender_id, method, path, idempotency_key, request_hash)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
if attachment_ids:
|
||||
valid = await conn.fetchval(
|
||||
"""SELECT count(*) FROM attachments
|
||||
WHERE id = ANY($1::uuid[]) AND chat_id=$2""",
|
||||
attachment_ids, chat_id,
|
||||
)
|
||||
if valid != len(attachment_ids):
|
||||
raise ValueError("not_found")
|
||||
failed = await conn.fetchval(
|
||||
"""SELECT count(*) FROM attachments
|
||||
WHERE id = ANY($1::uuid[]) AND chat_id=$2 AND status='failed'""",
|
||||
attachment_ids, chat_id,
|
||||
)
|
||||
if failed:
|
||||
raise ValueError("attachment_failed")
|
||||
|
||||
message_id = str(uuid.uuid4())
|
||||
row = await conn.fetchrow(
|
||||
"""INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
SELECT $1,$2,$3,$4 WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id=$2 AND user_id=$3)
|
||||
RETURNING id, chat_id, sender_id, text, created_at""",
|
||||
message_id, chat_id, sender_id, text,
|
||||
)
|
||||
if row is None:
|
||||
raise ValueError("not_found")
|
||||
if attachment_ids:
|
||||
await conn.executemany(
|
||||
"INSERT INTO message_attachments (message_id, attachment_id) VALUES ($1,$2)",
|
||||
[(message_id, aid) for aid in attachment_ids],
|
||||
)
|
||||
message = self._message_row(row, list(attachment_ids))
|
||||
await conn.execute("UPDATE chats SET version=version+1 WHERE id=$1", chat_id)
|
||||
if idempotency_key is not None:
|
||||
await conn.execute(
|
||||
"""INSERT INTO idempotency_keys
|
||||
(user_id, method, path, key, request_hash, response_status, response_body)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7)""",
|
||||
sender_id, method, path, idempotency_key,
|
||||
request_hash, 201, json.dumps(message, ensure_ascii=False),
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
cached = await self._get_idempotent(sender_id, method, path, idempotency_key, request_hash)
|
||||
if cached is not None:
|
||||
return cached
|
||||
raise
|
||||
|
||||
await self._cache.invalidate_chat(chat_id)
|
||||
return message
|
||||
|
||||
async def _get_idempotent(self, user_id, method, path, key, request_hash):
|
||||
if key is None:
|
||||
return None
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""SELECT request_hash, response_body FROM idempotency_keys
|
||||
WHERE user_id=$1 AND method=$2 AND path=$3 AND key=$4""",
|
||||
user_id, method, path, key,
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
if row["request_hash"] != request_hash:
|
||||
raise ValueError("idempotency_conflict")
|
||||
return json.loads(row["response_body"])
|
||||
|
||||
async def list_messages(self, chat_id, actor_id, limit, cursor):
|
||||
async with self._pool.acquire() as conn:
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2",
|
||||
chat_id, actor_id,
|
||||
)
|
||||
if is_member is None:
|
||||
raise ValueError("not_found")
|
||||
|
||||
cache_key = f"messages:{chat_id}:{limit}:{cursor or ''}"
|
||||
cached = await self._cache.get_json(cache_key)
|
||||
if cached is not None:
|
||||
version_now = await self._get_chat_version(chat_id)
|
||||
if cached.get("version") == version_now:
|
||||
return cached["items"], cached["next_cursor"]
|
||||
await self._cache.delete(cache_key)
|
||||
|
||||
lock_key = f"lock:{cache_key}"
|
||||
got_lock = await self._cache.try_lock(lock_key, ttl=10)
|
||||
if not got_lock:
|
||||
for _ in range(50):
|
||||
await asyncio.sleep(0.1)
|
||||
cached = await self._cache.get_json(cache_key)
|
||||
if cached is not None:
|
||||
version_now = await self._get_chat_version(chat_id)
|
||||
if cached.get("version") == version_now:
|
||||
return cached["items"], cached["next_cursor"]
|
||||
|
||||
try:
|
||||
version_before = await self._get_chat_version(chat_id)
|
||||
async with self._pool.acquire() as conn:
|
||||
params = [chat_id]
|
||||
where = ""
|
||||
if cursor:
|
||||
try:
|
||||
cur_chat, cur_created, cur_id = cursor.split("|", 2)
|
||||
except ValueError:
|
||||
raise ValueError("bad_cursor")
|
||||
if cur_chat != chat_id:
|
||||
raise ValueError("bad_cursor")
|
||||
where = "AND (created_at, id) > ($2,$3)"
|
||||
params += [datetime.fromisoformat(cur_created.replace("Z", "+00:00")), cur_id]
|
||||
rows = await conn.fetch(
|
||||
f"""SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages WHERE chat_id=$1 {where}
|
||||
ORDER BY created_at, id LIMIT ${len(params)+1}""",
|
||||
*params, limit + 1,
|
||||
)
|
||||
items = []
|
||||
for row in rows[:limit]:
|
||||
att_ids = await self._list_attachment_ids_conn(conn, row["id"])
|
||||
items.append(self._message_row(row, att_ids))
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
last = rows[limit - 1]
|
||||
next_cursor = f"{chat_id}|{_now_iso(last['created_at'])}|{last['id']}"
|
||||
version_after = await self._get_chat_version(chat_id)
|
||||
if got_lock and version_before == version_after:
|
||||
await self._cache.set_json(cache_key, {
|
||||
"items": items, "next_cursor": next_cursor, "version": version_after,
|
||||
})
|
||||
return items, next_cursor
|
||||
finally:
|
||||
if got_lock:
|
||||
await self._cache.unlock(lock_key)
|
||||
|
||||
async def _get_chat_version(self, chat_id: str) -> int:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchval("SELECT version FROM chats WHERE id=$1", chat_id)
|
||||
return int(row) if row is not None else 0
|
||||
|
||||
@staticmethod
|
||||
def _user_row(row) -> dict:
|
||||
return {"id": str(row["id"]), "username": row["username"],
|
||||
"display_name": row["display_name"], "created_at": _now_iso(row["created_at"])}
|
||||
|
||||
@staticmethod
|
||||
def _message_row(row, attachment_ids=None) -> dict:
|
||||
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]), "text": row["text"],
|
||||
"created_at": _now_iso(row["created_at"]),
|
||||
"attachment_ids": attachment_ids or []}
|
||||
|
||||
@staticmethod
|
||||
def _attachment_row(row, public: bool) -> dict:
|
||||
variants_raw = row["variants"]
|
||||
if isinstance(variants_raw, str):
|
||||
try:
|
||||
variants = json.loads(variants_raw)
|
||||
except json.JSONDecodeError:
|
||||
variants = []
|
||||
else:
|
||||
variants = variants_raw or []
|
||||
|
||||
result = {
|
||||
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["owner_id"]), "filename": row["filename"],
|
||||
"content_type": row["content_type"], "size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"], "status": row["status"],
|
||||
"variants": variants,
|
||||
"error_code": row["error_code"],
|
||||
"created_at": _now_iso(row["created_at"]),
|
||||
"updated_at": _now_iso(row["updated_at"]),
|
||||
}
|
||||
if not public:
|
||||
result["_object_key"] = row["object_key"]
|
||||
variant_keys_raw = row["variant_keys"]
|
||||
if isinstance(variant_keys_raw, str):
|
||||
try:
|
||||
result["_variant_keys"] = json.loads(variant_keys_raw)
|
||||
except json.JSONDecodeError:
|
||||
result["_variant_keys"] = {}
|
||||
else:
|
||||
result["_variant_keys"] = variant_keys_raw or {}
|
||||
return result
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import random
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from app.broker import consume_jobs, publish_job
|
||||
from app.cache import make_cache
|
||||
from app.config import config
|
||||
from app.db import db
|
||||
from app.s3 import s3
|
||||
from app.storage import Storage
|
||||
|
||||
THUMB_SIZE = 256
|
||||
CROP_SIZE = 128
|
||||
OPTIMIZED_SIZE = 1280
|
||||
|
||||
_executor = ThreadPoolExecutor(max_workers=10)
|
||||
|
||||
PERMANENT_ERRORS = (UnidentifiedImageError,)
|
||||
PERMANENT_OSERROR_MARKERS = (
|
||||
"cannot identify image",
|
||||
"image file is truncated",
|
||||
"broken data stream",
|
||||
)
|
||||
|
||||
|
||||
def is_permanent(exc: Exception) -> bool:
|
||||
if isinstance(exc, PERMANENT_ERRORS):
|
||||
return True
|
||||
if isinstance(exc, OSError):
|
||||
text = str(exc).lower()
|
||||
if any(m in text for m in PERMANENT_OSERROR_MARKERS):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def process_images(data: bytes):
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img = ImageOps.exif_transpose(img)
|
||||
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
img = img.convert("RGB", background=(255, 255, 255))
|
||||
else:
|
||||
img = img.convert("RGB")
|
||||
|
||||
results = {}
|
||||
|
||||
thumb = img.copy()
|
||||
thumb.thumbnail((THUMB_SIZE, THUMB_SIZE), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
thumb.save(buf, format="JPEG", quality=85)
|
||||
results["thumbnail"] = (buf.getvalue(), thumb.size[0], thumb.size[1], "image/jpeg")
|
||||
|
||||
crop = ImageOps.fit(img, (CROP_SIZE, CROP_SIZE), Image.LANCZOS, centering=(0.5, 0.5))
|
||||
buf = io.BytesIO()
|
||||
crop.save(buf, format="JPEG", quality=85)
|
||||
results["crop"] = (buf.getvalue(), crop.size[0], crop.size[1], "image/jpeg")
|
||||
|
||||
opt = img.copy()
|
||||
if opt.size[0] > OPTIMIZED_SIZE or opt.size[1] > OPTIMIZED_SIZE:
|
||||
opt.thumbnail((OPTIMIZED_SIZE, OPTIMIZED_SIZE), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
opt.save(buf, format="WEBP", quality=80)
|
||||
results["optimized"] = (buf.getvalue(), opt.size[0], opt.size[1], "image/webp")
|
||||
|
||||
return results
|
||||
|
||||
|
||||
async def handle_job(job: dict, storage: Storage) -> None:
|
||||
att_id = job.get("attachment_id")
|
||||
attempt = job.get("attempt", 1)
|
||||
job_id = job.get("job_id")
|
||||
|
||||
att = await storage.get_attachment(att_id)
|
||||
if att is None:
|
||||
return
|
||||
if att["status"] == "ready":
|
||||
return
|
||||
|
||||
await storage.update_attachment_status(att_id, "processing")
|
||||
await storage.set_job_lease(job_id, 60)
|
||||
|
||||
try:
|
||||
staging_key = att["_object_key"]
|
||||
original = s3.get(staging_key).read()
|
||||
|
||||
final_key = f"originals/{att['chat_id']}/{att_id}"
|
||||
s3.put(final_key, original, att["content_type"])
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
images = await loop.run_in_executor(_executor, process_images, original)
|
||||
|
||||
variants = []
|
||||
variant_keys = {}
|
||||
|
||||
for name, (data, w, h, ctype) in images.items():
|
||||
ext = "webp" if name == "optimized" else "jpg"
|
||||
key = f"{name}s/{att['chat_id']}/{att_id}.{ext}"
|
||||
s3.put(key, data, ctype)
|
||||
variants.append({
|
||||
"name": name,
|
||||
"content_type": ctype,
|
||||
"size_bytes": len(data),
|
||||
"width": w,
|
||||
"height": h,
|
||||
"sha256": hashlib.sha256(data).hexdigest()
|
||||
})
|
||||
variant_keys[name] = key
|
||||
|
||||
await storage.complete_attachment_ready(att_id, final_key, variants, variant_keys)
|
||||
|
||||
try:
|
||||
s3.remove(staging_key)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"[worker] SUCCESS {att_id}", flush=True)
|
||||
except Exception as e:
|
||||
print(f"[worker] ERROR {att_id}: {type(e).__name__} - {e}", flush=True)
|
||||
if is_permanent(e):
|
||||
await storage.fail_attachment(att_id, "invalid_image")
|
||||
await publish_job(job, is_dlq=True)
|
||||
return
|
||||
if attempt >= config.MAX_ATTEMPTS:
|
||||
await storage.fail_attachment(att_id, "retry_exhausted")
|
||||
await publish_job(job, is_dlq=True)
|
||||
return
|
||||
new_attempt = await storage.increment_job_attempt(job_id)
|
||||
job["attempt"] = new_attempt
|
||||
delay = (2 ** new_attempt) + random.uniform(0, 1)
|
||||
print(f"[worker] retrying in {delay:.2f} seconds...", flush=True)
|
||||
await asyncio.sleep(delay)
|
||||
await publish_job(job)
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
await db.connect()
|
||||
cache = make_cache()
|
||||
storage = Storage(db.pool, cache)
|
||||
s3.ensure_bucket()
|
||||
print(f"[worker] started, queue={config.RABBITMQ_QUEUE}", flush=True)
|
||||
await consume_jobs(lambda job: handle_job(job, storage))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
Reference in New Issue
Block a user