forked from mtusi2026/mtusi2026lab4
Lab4: MinIO attachments
This commit is contained in:
@@ -0,0 +1,323 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .cursors import decode_cursor, encode_cursor
|
||||
from .db import close_engine, init_engine, ping
|
||||
from .errors import AppError, error_response, request_id_of
|
||||
from .images import (
|
||||
max_upload_bytes,
|
||||
sniff_image,
|
||||
validate_filename,
|
||||
validate_image_pixels,
|
||||
)
|
||||
from .models import CreateChat, CreateMessage, CreateUser
|
||||
from .s3util import close_s3, ensure_bucket, ping_s3
|
||||
from .store import store
|
||||
|
||||
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or socket.gethostname()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_engine()
|
||||
ensure_bucket()
|
||||
yield
|
||||
close_s3()
|
||||
close_engine()
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger lab4", version="1.4.0", lifespan=lifespan)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def attach_request_and_instance(request: Request, call_next):
|
||||
incoming = request.headers.get("x-request-id")
|
||||
request.state.request_id = incoming.strip() if incoming and incoming.strip() else str(uuid.uuid4())
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(AppError)
|
||||
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
|
||||
return error_response(
|
||||
exc.status_code,
|
||||
exc.code,
|
||||
exc.message,
|
||||
request_id_of(request),
|
||||
headers=exc.headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
return error_response(
|
||||
400,
|
||||
"invalid_request",
|
||||
"Request validation failed",
|
||||
request_id_of(request),
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
||||
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
||||
headers = None
|
||||
if exc.status_code == 401:
|
||||
code = "unauthorized"
|
||||
headers = BEARER_CHALLENGE
|
||||
elif exc.status_code >= 500:
|
||||
code = "internal_error"
|
||||
message = exc.detail if isinstance(exc.detail, str) else "Request failed"
|
||||
return error_response(
|
||||
exc.status_code,
|
||||
code,
|
||||
message,
|
||||
request_id_of(request),
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
return error_response(500, "internal_error", "Internal server error", request_id_of(request))
|
||||
|
||||
|
||||
def current_user_id(authorization: Optional[str] = Header(default=None)) -> str:
|
||||
if authorization is None or not authorization.strip():
|
||||
raise AppError(401, "unauthorized", "Missing bearer token", headers=BEARER_CHALLENGE)
|
||||
scheme, _, credential = authorization.partition(" ")
|
||||
if scheme.lower() != "bearer" or not credential.strip():
|
||||
raise AppError(401, "unauthorized", "Bearer token required", headers=BEARER_CHALLENGE)
|
||||
return store.resolve_bearer(credential.strip())
|
||||
|
||||
|
||||
def require_chat_member(chat_id: UUID, user_id: str):
|
||||
chat = store.get_chat(str(chat_id))
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise AppError(404, "not_found", "Chat not found")
|
||||
return chat
|
||||
|
||||
|
||||
def parse_basic_credentials(authorization: Optional[str]) -> tuple[str, str]:
|
||||
if authorization is None or not authorization.strip():
|
||||
raise AppError(401, "unauthorized", "Missing basic credentials", headers=BASIC_CHALLENGE)
|
||||
scheme, _, credential = authorization.partition(" ")
|
||||
if scheme.lower() != "basic" or not credential.strip():
|
||||
raise AppError(401, "unauthorized", "Basic credentials required", headers=BASIC_CHALLENGE)
|
||||
try:
|
||||
decoded = base64.b64decode(credential.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError, ValueError) as exc:
|
||||
raise AppError(401, "unauthorized", "Invalid basic credentials", headers=BASIC_CHALLENGE) from exc
|
||||
if ":" not in decoded:
|
||||
raise AppError(401, "unauthorized", "Invalid basic credentials", headers=BASIC_CHALLENGE)
|
||||
username, password = decoded.split(":", 1)
|
||||
if not username or not username.isascii():
|
||||
raise AppError(401, "unauthorized", "Invalid basic credentials", headers=BASIC_CHALLENGE)
|
||||
return username, password
|
||||
|
||||
|
||||
def require_idempotency_key(idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key")) -> str:
|
||||
if idempotency_key is None or not idempotency_key.strip():
|
||||
raise AppError(400, "invalid_request", "Idempotency-Key is required")
|
||||
key = idempotency_key.strip()
|
||||
if not IDEMPOTENCY_KEY_RE.fullmatch(key):
|
||||
raise AppError(400, "invalid_request", "Idempotency-Key format is invalid")
|
||||
return key
|
||||
|
||||
|
||||
async def read_upload_body(request: Request) -> bytes:
|
||||
limit = max_upload_bytes()
|
||||
content_length = request.headers.get("content-length")
|
||||
if content_length is not None:
|
||||
try:
|
||||
declared = int(content_length)
|
||||
except ValueError as exc:
|
||||
raise AppError(400, "invalid_request", "Invalid Content-Length") from exc
|
||||
if declared > limit:
|
||||
raise AppError(413, "payload_too_large", "Upload exceeds size limit")
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
async for chunk in request.stream():
|
||||
if not chunk:
|
||||
continue
|
||||
total += len(chunk)
|
||||
if total > limit:
|
||||
raise AppError(413, "payload_too_large", "Upload exceeds size limit")
|
||||
chunks.append(chunk)
|
||||
data = b"".join(chunks)
|
||||
if not data:
|
||||
raise AppError(400, "invalid_request", "Empty upload body")
|
||||
return data
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
def health_ready():
|
||||
if not ping():
|
||||
raise AppError(503, "unavailable", "Database is unavailable")
|
||||
if not ping_s3():
|
||||
raise AppError(503, "unavailable", "Object storage is unavailable")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
def register_user(body: CreateUser):
|
||||
user = store.create_user(body.username, body.display_name, body.password)
|
||||
return user.to_dict()
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
def create_session(authorization: Optional[str] = Header(default=None)):
|
||||
username, password = parse_basic_credentials(authorization)
|
||||
session = store.create_session(username, password)
|
||||
return session.to_dict()
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def revoke_session(authorization: Optional[str] = Header(default=None)):
|
||||
if authorization is None or not authorization.strip():
|
||||
raise AppError(401, "unauthorized", "Missing bearer token", headers=BEARER_CHALLENGE)
|
||||
scheme, _, credential = authorization.partition(" ")
|
||||
if scheme.lower() != "bearer" or not credential.strip():
|
||||
raise AppError(401, "unauthorized", "Bearer token required", headers=BEARER_CHALLENGE)
|
||||
store.revoke_session(credential.strip())
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def get_me(user_id: str = Depends(current_user_id)):
|
||||
user = store.get_user(user_id)
|
||||
if user is None:
|
||||
raise AppError(401, "unauthorized", "Unknown user", headers=BEARER_CHALLENGE)
|
||||
return user.to_dict()
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(body: CreateChat, user_id: str = Depends(current_user_id)):
|
||||
member_ids = [str(m) for m in body.member_ids]
|
||||
if user_id not in member_ids:
|
||||
raise AppError(400, "invalid_request", "Caller must be included in member_ids")
|
||||
chat = store.create_chat(body.title, member_ids)
|
||||
return chat.to_dict()
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(
|
||||
user_id: str = Depends(current_user_id),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
):
|
||||
resource = f"chats:{user_id}"
|
||||
after = decode_cursor(cursor, resource) if cursor else None
|
||||
page, last_for_cursor = store.list_chats_for_user(user_id, limit, after)
|
||||
next_cursor = None
|
||||
if last_for_cursor is not None:
|
||||
next_cursor = encode_cursor(last_for_cursor.created_at, last_for_cursor.id, resource)
|
||||
return {"items": [c.to_dict() for c in page], "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(chat_id: UUID, user_id: str = Depends(current_user_id)):
|
||||
chat = require_chat_member(chat_id, user_id)
|
||||
return chat.to_dict()
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(
|
||||
chat_id: UUID,
|
||||
body: CreateMessage,
|
||||
request: Request,
|
||||
user_id: str = Depends(current_user_id),
|
||||
idempotency_key: str = Depends(require_idempotency_key),
|
||||
):
|
||||
require_chat_member(chat_id, user_id)
|
||||
message = store.create_message(
|
||||
str(chat_id),
|
||||
user_id,
|
||||
body.text,
|
||||
[str(item) for item in body.attachment_ids],
|
||||
idempotency_key=idempotency_key,
|
||||
request_path=request.url.path,
|
||||
)
|
||||
return message.to_dict()
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(
|
||||
chat_id: UUID,
|
||||
user_id: str = Depends(current_user_id),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
):
|
||||
require_chat_member(chat_id, user_id)
|
||||
resource = f"messages:{chat_id}"
|
||||
after = decode_cursor(cursor, resource) if cursor else None
|
||||
page, last_for_cursor = store.list_messages(str(chat_id), limit, after)
|
||||
next_cursor = None
|
||||
if last_for_cursor is not None:
|
||||
next_cursor = encode_cursor(last_for_cursor.created_at, last_for_cursor.id, resource)
|
||||
return {"items": [m.to_dict() for m in page], "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
filename: str = Query(...),
|
||||
user_id: str = Depends(current_user_id),
|
||||
):
|
||||
require_chat_member(chat_id, user_id)
|
||||
safe_name = validate_filename(filename)
|
||||
content_type = (request.headers.get("content-type") or "").split(";")[0].strip().lower()
|
||||
data = await read_upload_body(request)
|
||||
detected = sniff_image(data, content_type)
|
||||
validate_image_pixels(data, detected)
|
||||
attachment = store.create_attachment(
|
||||
str(chat_id),
|
||||
user_id,
|
||||
safe_name,
|
||||
detected,
|
||||
data,
|
||||
)
|
||||
return attachment.to_dict()
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
def get_attachment(attachment_id: UUID, user_id: str = Depends(current_user_id)):
|
||||
attachment = store.get_attachment_for_user(str(attachment_id), user_id)
|
||||
return attachment.to_dict()
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
def download_attachment(
|
||||
attachment_id: UUID,
|
||||
user_id: str = Depends(current_user_id),
|
||||
variant: str = Query(default="original"),
|
||||
):
|
||||
data, content_type = store.download_attachment_for_user(
|
||||
str(attachment_id), user_id, variant=variant
|
||||
)
|
||||
return Response(content=data, media_type=content_type)
|
||||
@@ -0,0 +1,34 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from typing import Tuple
|
||||
|
||||
from .errors import AppError
|
||||
|
||||
|
||||
def encode_cursor(created_at: str, item_id: str, resource: str) -> str:
|
||||
raw = json.dumps(
|
||||
{"t": created_at, "i": item_id, "r": resource},
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str, expected_resource: str) -> Tuple[str, str]:
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
|
||||
created_at = data["t"]
|
||||
item_id = data["i"]
|
||||
resource = data["r"]
|
||||
if not isinstance(created_at, str) or not isinstance(item_id, str):
|
||||
raise ValueError("bad cursor fields")
|
||||
if resource != expected_resource:
|
||||
raise AppError(400, "invalid_request", "Cursor does not belong to this resource")
|
||||
return created_at, item_id
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise AppError(400, "invalid_request", "Invalid cursor") from exc
|
||||
@@ -0,0 +1,115 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Iterator, Optional
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
_engine: Optional[Engine] = None
|
||||
_SessionLocal: Optional[sessionmaker[Session]] = None
|
||||
|
||||
|
||||
def _read_database_url() -> str:
|
||||
url_file = os.environ.get("DATABASE_URL_FILE")
|
||||
if url_file:
|
||||
url = Path(url_file).read_text(encoding="utf-8").strip()
|
||||
else:
|
||||
url = os.environ.get("DATABASE_URL")
|
||||
if not url:
|
||||
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
|
||||
url = url.strip()
|
||||
if url.startswith("postgresql://"):
|
||||
url = "postgresql+psycopg://" + url[len("postgresql://") :]
|
||||
elif url.startswith("postgres://"):
|
||||
url = "postgresql+psycopg://" + url[len("postgres://") :]
|
||||
return url
|
||||
|
||||
|
||||
def init_engine() -> Engine:
|
||||
global _engine, _SessionLocal
|
||||
if _engine is not None:
|
||||
return _engine
|
||||
_engine = create_engine(
|
||||
_read_database_url(),
|
||||
pool_size=5,
|
||||
max_overflow=5,
|
||||
pool_pre_ping=True,
|
||||
pool_timeout=10,
|
||||
)
|
||||
_SessionLocal = sessionmaker(bind=_engine, expire_on_commit=False)
|
||||
return _engine
|
||||
|
||||
|
||||
def get_engine() -> Engine:
|
||||
if _engine is None:
|
||||
raise RuntimeError("database engine is not initialized")
|
||||
return _engine
|
||||
|
||||
|
||||
@contextmanager
|
||||
def session_scope() -> Iterator[Session]:
|
||||
if _SessionLocal is None:
|
||||
raise RuntimeError("database engine is not initialized")
|
||||
session = _SessionLocal()
|
||||
try:
|
||||
yield session
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def close_engine() -> None:
|
||||
global _engine, _SessionLocal
|
||||
if _engine is not None:
|
||||
_engine.dispose()
|
||||
_engine = None
|
||||
_SessionLocal = None
|
||||
|
||||
|
||||
def migrations_dir() -> Path:
|
||||
return Path(__file__).resolve().parents[2] / "migrations"
|
||||
|
||||
|
||||
def apply_migrations() -> None:
|
||||
engine = get_engine()
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
applied = {
|
||||
row[0]
|
||||
for row in conn.execute(text("SELECT version FROM schema_migrations")).fetchall()
|
||||
}
|
||||
for path in sorted(migrations_dir().glob("*.sql")):
|
||||
version = path.name
|
||||
if version in applied:
|
||||
continue
|
||||
conn.exec_driver_sql(path.read_text(encoding="utf-8"))
|
||||
conn.execute(
|
||||
text("INSERT INTO schema_migrations (version) VALUES (:version)"),
|
||||
{"version": version},
|
||||
)
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
try:
|
||||
engine = get_engine()
|
||||
with engine.connect() as conn:
|
||||
conn.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
@@ -0,0 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class AppError(Exception):
|
||||
def __init__(
|
||||
self,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: Optional[dict] = None,
|
||||
) -> None:
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
def request_id_of(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", "unknown")
|
||||
|
||||
|
||||
def error_response(
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
request_id: str,
|
||||
headers: Optional[dict] = None,
|
||||
) -> JSONResponse:
|
||||
payload = {
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
}
|
||||
response_headers = {"X-Request-Id": request_id}
|
||||
if headers:
|
||||
response_headers.update(headers)
|
||||
return JSONResponse(status_code=status_code, content=payload, headers=response_headers)
|
||||
@@ -0,0 +1,68 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
from typing import Tuple
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from .errors import AppError
|
||||
|
||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_MAGIC = b"\xff\xd8\xff"
|
||||
|
||||
|
||||
def max_upload_bytes() -> int:
|
||||
return max(1, int(os.environ.get("MAX_UPLOAD_BYTES", "10485760")))
|
||||
|
||||
|
||||
def max_image_pixels() -> int:
|
||||
return max(1, int(os.environ.get("MAX_IMAGE_PIXELS", "40000000")))
|
||||
|
||||
|
||||
def validate_filename(filename: str) -> str:
|
||||
if len(filename) < 1 or len(filename) > 255:
|
||||
raise AppError(400, "invalid_request", "filename length is invalid")
|
||||
for ch in filename:
|
||||
code = ord(ch)
|
||||
if ch in "/\\" or code == 0 or code < 32:
|
||||
raise AppError(400, "invalid_request", "filename contains forbidden characters")
|
||||
return filename
|
||||
|
||||
|
||||
def sniff_image(data: bytes, declared_content_type: str) -> str:
|
||||
if declared_content_type not in {"image/png", "image/jpeg"}:
|
||||
raise AppError(415, "unsupported_media_type", "Unsupported media type")
|
||||
if data.startswith(PNG_MAGIC):
|
||||
detected = "image/png"
|
||||
elif data.startswith(JPEG_MAGIC):
|
||||
detected = "image/jpeg"
|
||||
else:
|
||||
raise AppError(415, "unsupported_media_type", "Unsupported or corrupted image")
|
||||
if detected != declared_content_type:
|
||||
raise AppError(415, "unsupported_media_type", "Content-Type does not match body")
|
||||
return detected
|
||||
|
||||
|
||||
def validate_image_pixels(data: bytes, content_type: str) -> Tuple[int, int]:
|
||||
Image.MAX_IMAGE_PIXELS = max_image_pixels()
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as img:
|
||||
fmt = (img.format or "").upper()
|
||||
if content_type == "image/png" and fmt != "PNG":
|
||||
raise AppError(415, "unsupported_media_type", "Invalid PNG image")
|
||||
if content_type == "image/jpeg" and fmt not in {"JPEG", "MPO"}:
|
||||
raise AppError(415, "unsupported_media_type", "Invalid JPEG image")
|
||||
width, height = img.size
|
||||
if width < 1 or height < 1:
|
||||
raise AppError(415, "unsupported_media_type", "Invalid image dimensions")
|
||||
if width * height > max_image_pixels():
|
||||
raise AppError(413, "payload_too_large", "Image exceeds pixel limit")
|
||||
img.load()
|
||||
return width, height
|
||||
except AppError:
|
||||
raise
|
||||
except Image.DecompressionBombError as exc:
|
||||
raise AppError(413, "payload_too_large", "Image exceeds pixel limit") from exc
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as exc:
|
||||
raise AppError(415, "unsupported_media_type", "Unsupported or corrupted image") from exc
|
||||
@@ -0,0 +1,81 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import List
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
def _not_blank(value: str, field_name: str) -> str:
|
||||
if value.strip() == "":
|
||||
raise ValueError(f"{field_name} must not be blank")
|
||||
return value
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
username: str
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def validate_username(cls, value: str) -> str:
|
||||
if not USERNAME_RE.fullmatch(value):
|
||||
raise ValueError("username must match [a-z0-9_]{3,32}")
|
||||
return value
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def validate_display_name(cls, value: str) -> str:
|
||||
return _not_blank(value, "display_name")
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def validate_password(cls, value: str) -> str:
|
||||
if len(value) < 12 or len(value) > 128:
|
||||
raise ValueError("password length must be 12-128")
|
||||
return value
|
||||
|
||||
|
||||
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:
|
||||
return _not_blank(value, "title")
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def validate_members(cls, value: List[UUID]) -> List[UUID]:
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("member_ids must be unique")
|
||||
return value
|
||||
|
||||
|
||||
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_text_or_attachments(self) -> "CreateMessage":
|
||||
if self.text.strip() == "" and not self.attachment_ids:
|
||||
raise ValueError("text must not be blank without attachments")
|
||||
return self
|
||||
@@ -0,0 +1,113 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import boto3
|
||||
from botocore.client import BaseClient, Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from .errors import AppError
|
||||
|
||||
_client: Optional[BaseClient] = None
|
||||
|
||||
|
||||
def _read_secret(env_name: str, file_env_name: str) -> str:
|
||||
path = os.environ.get(file_env_name)
|
||||
if path:
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
value = os.environ.get(env_name)
|
||||
if not value:
|
||||
raise RuntimeError(f"{env_name} or {file_env_name} is required")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def s3_endpoint() -> str:
|
||||
return os.environ.get("S3_ENDPOINT", "http://s3:9000").rstrip("/")
|
||||
|
||||
|
||||
def s3_bucket() -> str:
|
||||
return os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
|
||||
|
||||
def s3_region() -> str:
|
||||
return os.environ.get("S3_REGION", "us-east-1")
|
||||
|
||||
|
||||
def get_s3_client() -> BaseClient:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=s3_endpoint(),
|
||||
region_name=s3_region(),
|
||||
aws_access_key_id=_read_secret("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE"),
|
||||
aws_secret_access_key=_read_secret(
|
||||
"S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE"
|
||||
),
|
||||
config=Config(s3={"addressing_style": "path"}),
|
||||
)
|
||||
return _client
|
||||
|
||||
|
||||
def ensure_bucket() -> None:
|
||||
client = get_s3_client()
|
||||
bucket = s3_bucket()
|
||||
try:
|
||||
client.head_bucket(Bucket=bucket)
|
||||
except ClientError:
|
||||
try:
|
||||
client.create_bucket(Bucket=bucket)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code not in {"BucketAlreadyOwnedByYou", "BucketAlreadyExists"}:
|
||||
raise
|
||||
try:
|
||||
client.put_public_access_block(
|
||||
Bucket=bucket,
|
||||
PublicAccessBlockConfiguration={
|
||||
"BlockPublicAcls": True,
|
||||
"IgnorePublicAcls": True,
|
||||
"BlockPublicPolicy": True,
|
||||
"RestrictPublicBuckets": True,
|
||||
},
|
||||
)
|
||||
except ClientError:
|
||||
pass
|
||||
|
||||
|
||||
def put_object(object_key: str, data: bytes, content_type: str) -> None:
|
||||
try:
|
||||
get_s3_client().put_object(
|
||||
Bucket=s3_bucket(),
|
||||
Key=object_key,
|
||||
Body=data,
|
||||
ContentType=content_type,
|
||||
)
|
||||
except ClientError as exc:
|
||||
raise AppError(503, "unavailable", "Object storage is unavailable") from exc
|
||||
|
||||
|
||||
def get_object_bytes(object_key: str) -> bytes:
|
||||
try:
|
||||
response = get_s3_client().get_object(Bucket=s3_bucket(), Key=object_key)
|
||||
return response["Body"].read()
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code in {"NoSuchKey", "404", "NotFound"}:
|
||||
raise AppError(404, "not_found", "Attachment not found") from exc
|
||||
raise AppError(503, "unavailable", "Object storage is unavailable") from exc
|
||||
|
||||
|
||||
def ping_s3() -> bool:
|
||||
try:
|
||||
get_s3_client().head_bucket(Bucket=s3_bucket())
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def close_s3() -> None:
|
||||
global _client
|
||||
_client = None
|
||||
@@ -0,0 +1,559 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Optional, Tuple
|
||||
from uuid import UUID
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
from sqlalchemy import delete, func, select, tuple_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from .db import session_scope
|
||||
from .errors import AppError
|
||||
from .s3util import get_object_bytes, put_object
|
||||
from .tables import (
|
||||
AttachmentRow,
|
||||
ChatMemberRow,
|
||||
ChatRow,
|
||||
IdempotencyRow,
|
||||
MessageAttachmentRow,
|
||||
MessageRow,
|
||||
SessionRow,
|
||||
UserRow,
|
||||
)
|
||||
|
||||
password_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def format_ts(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def parse_ts(value: str) -> datetime:
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
def session_ttl_seconds() -> int:
|
||||
raw = os.environ.get("SESSION_TTL_SECONDS", "3600")
|
||||
return max(1, int(raw))
|
||||
|
||||
|
||||
def idempotency_ttl_seconds() -> int:
|
||||
raw = os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400")
|
||||
return max(1, int(raw))
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def request_body_hash(text: str, attachment_ids: List[str]) -> str:
|
||||
normalized = json.dumps(
|
||||
{"text": text, "attachment_ids": attachment_ids},
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def idempotency_scope(user_id: str, method: str, path: str, key: str) -> str:
|
||||
return f"{user_id}|{method.upper()}|{path}|{key}"
|
||||
|
||||
|
||||
@dataclass
|
||||
class User:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"username": self.username,
|
||||
"display_name": self.display_name,
|
||||
"created_at": self.created_at,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Chat:
|
||||
id: str
|
||||
title: str
|
||||
member_ids: List[str]
|
||||
created_at: str
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"title": self.title,
|
||||
"member_ids": list(self.member_ids),
|
||||
"created_at": self.created_at,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Message:
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: List[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"chat_id": self.chat_id,
|
||||
"sender_id": self.sender_id,
|
||||
"text": self.text,
|
||||
"created_at": self.created_at,
|
||||
"attachment_ids": list(self.attachment_ids),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Attachment:
|
||||
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
|
||||
object_key: str = ""
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"chat_id": self.chat_id,
|
||||
"owner_id": self.owner_id,
|
||||
"filename": self.filename,
|
||||
"content_type": self.content_type,
|
||||
"size_bytes": self.size_bytes,
|
||||
"sha256": self.sha256,
|
||||
"status": self.status,
|
||||
"variants": list(self.variants),
|
||||
"error_code": self.error_code,
|
||||
"created_at": self.created_at,
|
||||
"updated_at": self.updated_at,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"token": self.token,
|
||||
"token_type": self.token_type,
|
||||
"expires_at": self.expires_at,
|
||||
"user": self.user.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def _user_from_row(row: UserRow) -> User:
|
||||
return User(
|
||||
id=str(row.id),
|
||||
username=row.username,
|
||||
display_name=row.display_name,
|
||||
created_at=format_ts(row.created_at),
|
||||
)
|
||||
|
||||
|
||||
def _chat_from_row(row: ChatRow, member_ids: List[str]) -> Chat:
|
||||
return Chat(
|
||||
id=str(row.id),
|
||||
title=row.title,
|
||||
member_ids=member_ids,
|
||||
created_at=format_ts(row.created_at),
|
||||
)
|
||||
|
||||
|
||||
def _attachment_from_row(row: AttachmentRow) -> Attachment:
|
||||
return Attachment(
|
||||
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=int(row.size_bytes),
|
||||
sha256=row.sha256,
|
||||
status=row.status,
|
||||
variants=[],
|
||||
error_code=row.error_code,
|
||||
created_at=format_ts(row.created_at),
|
||||
updated_at=format_ts(row.updated_at),
|
||||
object_key=row.object_key,
|
||||
)
|
||||
|
||||
|
||||
def _message_attachment_ids(session, message_id: UUID) -> List[str]:
|
||||
rows = session.scalars(
|
||||
select(MessageAttachmentRow.attachment_id)
|
||||
.where(MessageAttachmentRow.message_id == message_id)
|
||||
.order_by(MessageAttachmentRow.position.asc())
|
||||
).all()
|
||||
return [str(attachment_id) for attachment_id in rows]
|
||||
|
||||
|
||||
def _message_from_row(session, row: MessageRow) -> Message:
|
||||
return Message(
|
||||
id=str(row.id),
|
||||
chat_id=str(row.chat_id),
|
||||
sender_id=str(row.sender_id),
|
||||
text=row.text,
|
||||
created_at=format_ts(row.created_at),
|
||||
attachment_ids=_message_attachment_ids(session, row.id),
|
||||
)
|
||||
|
||||
|
||||
def _member_ids(session, chat_id: UUID) -> List[str]:
|
||||
rows = session.scalars(
|
||||
select(ChatMemberRow.user_id)
|
||||
.where(ChatMemberRow.chat_id == chat_id)
|
||||
.order_by(ChatMemberRow.user_id)
|
||||
).all()
|
||||
return [str(user_id) for user_id in rows]
|
||||
|
||||
|
||||
def _aware(value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
return value
|
||||
|
||||
|
||||
def _is_chat_member(session, chat_id: UUID, user_id: str) -> bool:
|
||||
row = session.get(ChatMemberRow, {"chat_id": chat_id, "user_id": UUID(user_id)})
|
||||
return row is not None
|
||||
|
||||
|
||||
class Store:
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
row = UserRow(
|
||||
id=uuid.uuid4(),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
password_hash=password_hasher.hash(password),
|
||||
created_at=utc_now(),
|
||||
)
|
||||
try:
|
||||
with session_scope() as session:
|
||||
session.add(row)
|
||||
session.flush()
|
||||
return _user_from_row(row)
|
||||
except IntegrityError as exc:
|
||||
raise AppError(409, "conflict", "Username is already taken") from exc
|
||||
|
||||
def get_user(self, user_id: str) -> Optional[User]:
|
||||
with session_scope() as session:
|
||||
row = session.get(UserRow, UUID(user_id))
|
||||
return _user_from_row(row) if row else None
|
||||
|
||||
def create_session(self, username: str, password: str) -> Session:
|
||||
with session_scope() as session:
|
||||
row = session.scalar(select(UserRow).where(UserRow.username == username))
|
||||
if row is None:
|
||||
raise AppError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Invalid credentials",
|
||||
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||
)
|
||||
try:
|
||||
password_hasher.verify(row.password_hash, password)
|
||||
except VerifyMismatchError as exc:
|
||||
raise AppError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Invalid credentials",
|
||||
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||
) from exc
|
||||
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = utc_now() + timedelta(seconds=session_ttl_seconds())
|
||||
session.add(
|
||||
SessionRow(
|
||||
token_hash=hash_token(token),
|
||||
user_id=row.id,
|
||||
expires_at=expires_at,
|
||||
created_at=utc_now(),
|
||||
)
|
||||
)
|
||||
user = _user_from_row(row)
|
||||
return Session(
|
||||
token=token,
|
||||
token_type="Bearer",
|
||||
expires_at=format_ts(expires_at),
|
||||
user=user,
|
||||
)
|
||||
|
||||
def resolve_bearer(self, token: str) -> str:
|
||||
with session_scope() as session:
|
||||
row = session.get(SessionRow, hash_token(token))
|
||||
challenge = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
if row is None:
|
||||
raise AppError(401, "unauthorized", "Invalid session", headers=challenge)
|
||||
if row.revoked_at is not None:
|
||||
raise AppError(401, "unauthorized", "Session revoked", headers=challenge)
|
||||
if _aware(row.expires_at) <= utc_now():
|
||||
raise AppError(401, "unauthorized", "Session expired", headers=challenge)
|
||||
return str(row.user_id)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
with session_scope() as session:
|
||||
row = session.get(SessionRow, hash_token(token), with_for_update=True)
|
||||
challenge = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
if row is None:
|
||||
raise AppError(401, "unauthorized", "Invalid session", headers=challenge)
|
||||
if row.revoked_at is not None:
|
||||
raise AppError(401, "unauthorized", "Session revoked", headers=challenge)
|
||||
if _aware(row.expires_at) <= utc_now():
|
||||
raise AppError(401, "unauthorized", "Session expired", headers=challenge)
|
||||
row.revoked_at = utc_now()
|
||||
|
||||
def create_chat(self, title: str, member_ids: List[str]) -> Chat:
|
||||
chat_id = uuid.uuid4()
|
||||
member_uuids = [UUID(m) for m in member_ids]
|
||||
with session_scope() as session:
|
||||
existing = session.scalar(
|
||||
select(func.count()).select_from(UserRow).where(UserRow.id.in_(member_uuids))
|
||||
)
|
||||
if existing != len(member_uuids):
|
||||
raise AppError(400, "invalid_request", "Unknown member in member_ids")
|
||||
chat = ChatRow(id=chat_id, title=title, created_at=utc_now())
|
||||
session.add(chat)
|
||||
for member_id in member_uuids:
|
||||
session.add(ChatMemberRow(chat_id=chat_id, user_id=member_id))
|
||||
session.flush()
|
||||
return _chat_from_row(chat, list(member_ids))
|
||||
|
||||
def get_chat(self, chat_id: str) -> Optional[Chat]:
|
||||
with session_scope() as session:
|
||||
row = session.get(ChatRow, UUID(chat_id))
|
||||
if row is None:
|
||||
return None
|
||||
return _chat_from_row(row, _member_ids(session, row.id))
|
||||
|
||||
def list_chats_for_user(
|
||||
self,
|
||||
user_id: str,
|
||||
limit: int,
|
||||
after: Optional[Tuple[str, str]] = None,
|
||||
) -> Tuple[List[Chat], Optional[Chat]]:
|
||||
with session_scope() as session:
|
||||
stmt = (
|
||||
select(ChatRow)
|
||||
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
|
||||
.where(ChatMemberRow.user_id == UUID(user_id))
|
||||
)
|
||||
if after is not None:
|
||||
stmt = stmt.where(
|
||||
tuple_(ChatRow.created_at, ChatRow.id)
|
||||
> (parse_ts(after[0]), UUID(after[1]))
|
||||
)
|
||||
stmt = stmt.order_by(ChatRow.created_at.asc(), ChatRow.id.asc()).limit(limit + 1)
|
||||
rows = list(session.scalars(stmt).all())
|
||||
chats = [_chat_from_row(row, _member_ids(session, row.id)) for row in rows]
|
||||
page = chats[:limit]
|
||||
has_more = len(chats) > limit
|
||||
last = page[-1] if page and has_more else None
|
||||
return page, last
|
||||
|
||||
def create_attachment(
|
||||
self,
|
||||
chat_id: str,
|
||||
owner_id: str,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
data: bytes,
|
||||
) -> Attachment:
|
||||
attachment_id = uuid.uuid4()
|
||||
object_key = f"attachments/{chat_id}/{attachment_id}"
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
now = utc_now()
|
||||
put_object(object_key, data, content_type)
|
||||
with session_scope() as session:
|
||||
row = AttachmentRow(
|
||||
id=attachment_id,
|
||||
chat_id=UUID(chat_id),
|
||||
owner_id=UUID(owner_id),
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
size_bytes=len(data),
|
||||
sha256=digest,
|
||||
object_key=object_key,
|
||||
status="ready",
|
||||
error_code=None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
session.add(row)
|
||||
session.flush()
|
||||
return _attachment_from_row(row)
|
||||
|
||||
def get_attachment_for_user(self, attachment_id: str, user_id: str) -> Attachment:
|
||||
with session_scope() as session:
|
||||
row = session.get(AttachmentRow, UUID(attachment_id))
|
||||
if row is None or not _is_chat_member(session, row.chat_id, user_id):
|
||||
raise AppError(404, "not_found", "Attachment not found")
|
||||
return _attachment_from_row(row)
|
||||
|
||||
def download_attachment_for_user(
|
||||
self, attachment_id: str, user_id: str, variant: str = "original"
|
||||
) -> Tuple[bytes, str]:
|
||||
if variant != "original":
|
||||
raise AppError(400, "invalid_request", "Unsupported variant")
|
||||
with session_scope() as session:
|
||||
row = session.get(AttachmentRow, UUID(attachment_id))
|
||||
if row is None or not _is_chat_member(session, row.chat_id, user_id):
|
||||
raise AppError(404, "not_found", "Attachment not found")
|
||||
if row.status != "ready":
|
||||
raise AppError(409, "conflict", "Attachment is not ready")
|
||||
object_key = row.object_key
|
||||
content_type = row.content_type
|
||||
return get_object_bytes(object_key), content_type
|
||||
|
||||
def create_message(
|
||||
self,
|
||||
chat_id: str,
|
||||
sender_id: str,
|
||||
text: str,
|
||||
attachment_ids: List[str],
|
||||
*,
|
||||
idempotency_key: str,
|
||||
request_path: str,
|
||||
) -> Message:
|
||||
scope = idempotency_scope(sender_id, "POST", request_path, idempotency_key)
|
||||
body_hash = request_body_hash(text, attachment_ids)
|
||||
|
||||
for _ in range(5):
|
||||
try:
|
||||
with session_scope() as session:
|
||||
existing = session.get(IdempotencyRow, scope, with_for_update=True)
|
||||
if existing is not None:
|
||||
if _aware(existing.expires_at) > utc_now():
|
||||
if existing.request_hash != body_hash:
|
||||
raise AppError(
|
||||
409,
|
||||
"conflict",
|
||||
"Idempotency-Key reused with a different request body",
|
||||
)
|
||||
message = session.get(MessageRow, existing.message_id)
|
||||
if message is None:
|
||||
raise AppError(500, "internal_error", "Idempotent message missing")
|
||||
return _message_from_row(session, message)
|
||||
session.execute(
|
||||
delete(IdempotencyRow).where(IdempotencyRow.scope_key == scope)
|
||||
)
|
||||
session.flush()
|
||||
|
||||
attachment_uuids = [UUID(item) for item in attachment_ids]
|
||||
if attachment_uuids:
|
||||
rows = list(
|
||||
session.scalars(
|
||||
select(AttachmentRow).where(AttachmentRow.id.in_(attachment_uuids))
|
||||
).all()
|
||||
)
|
||||
by_id = {row.id: row for row in rows}
|
||||
for attachment_id in attachment_uuids:
|
||||
row = by_id.get(attachment_id)
|
||||
if row is None or str(row.chat_id) != chat_id:
|
||||
raise AppError(404, "not_found", "Attachment not found")
|
||||
if row.status == "failed":
|
||||
raise AppError(409, "conflict", "Failed attachment cannot be linked")
|
||||
if row.status != "ready":
|
||||
raise AppError(409, "conflict", "Attachment is not ready")
|
||||
|
||||
message = MessageRow(
|
||||
id=uuid.uuid4(),
|
||||
chat_id=UUID(chat_id),
|
||||
sender_id=UUID(sender_id),
|
||||
text=text,
|
||||
created_at=utc_now(),
|
||||
)
|
||||
session.add(message)
|
||||
session.flush()
|
||||
for position, attachment_id in enumerate(attachment_uuids):
|
||||
session.add(
|
||||
MessageAttachmentRow(
|
||||
message_id=message.id,
|
||||
attachment_id=attachment_id,
|
||||
position=position,
|
||||
)
|
||||
)
|
||||
session.add(
|
||||
IdempotencyRow(
|
||||
scope_key=scope,
|
||||
request_hash=body_hash,
|
||||
message_id=message.id,
|
||||
created_at=utc_now(),
|
||||
expires_at=utc_now() + timedelta(seconds=idempotency_ttl_seconds()),
|
||||
)
|
||||
)
|
||||
session.flush()
|
||||
return _message_from_row(session, message)
|
||||
except IntegrityError:
|
||||
continue
|
||||
|
||||
with session_scope() as session:
|
||||
existing = session.get(IdempotencyRow, scope)
|
||||
if existing is not None and _aware(existing.expires_at) > utc_now():
|
||||
if existing.request_hash != body_hash:
|
||||
raise AppError(
|
||||
409,
|
||||
"conflict",
|
||||
"Idempotency-Key reused with a different request body",
|
||||
)
|
||||
message = session.get(MessageRow, existing.message_id)
|
||||
if message is not None:
|
||||
return _message_from_row(session, message)
|
||||
raise AppError(503, "unavailable", "Could not complete idempotent write")
|
||||
|
||||
def list_messages(
|
||||
self,
|
||||
chat_id: str,
|
||||
limit: int,
|
||||
after: Optional[Tuple[str, str]] = None,
|
||||
) -> Tuple[List[Message], Optional[Message]]:
|
||||
with session_scope() as session:
|
||||
stmt = select(MessageRow).where(MessageRow.chat_id == UUID(chat_id))
|
||||
if after is not None:
|
||||
stmt = stmt.where(
|
||||
tuple_(MessageRow.created_at, MessageRow.id)
|
||||
> (parse_ts(after[0]), UUID(after[1]))
|
||||
)
|
||||
stmt = stmt.order_by(MessageRow.created_at.asc(), MessageRow.id.asc()).limit(
|
||||
limit + 1
|
||||
)
|
||||
rows = list(session.scalars(stmt).all())
|
||||
messages = [_message_from_row(session, row) for row in rows]
|
||||
page = messages[:limit]
|
||||
has_more = len(messages) > limit
|
||||
last = page[-1] if page and has_more else None
|
||||
return page, last
|
||||
|
||||
|
||||
store = Store()
|
||||
@@ -0,0 +1,102 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, ForeignKey, Integer, String, Text, Uuid
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class UserRow(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True)
|
||||
username: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
|
||||
display_name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
|
||||
class ChatRow(Base):
|
||||
__tablename__ = "chats"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True)
|
||||
title: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
members: Mapped[List["ChatMemberRow"]] = relationship(back_populates="chat")
|
||||
|
||||
|
||||
class ChatMemberRow(Base):
|
||||
__tablename__ = "chat_members"
|
||||
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
Uuid, ForeignKey("chats.id"), primary_key=True
|
||||
)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
Uuid, ForeignKey("users.id"), primary_key=True
|
||||
)
|
||||
chat: Mapped[ChatRow] = relationship(back_populates="members")
|
||||
|
||||
|
||||
class MessageRow(Base):
|
||||
__tablename__ = "messages"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("chats.id"), nullable=False)
|
||||
sender_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id"), nullable=False)
|
||||
text: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
|
||||
class MessageAttachmentRow(Base):
|
||||
__tablename__ = "message_attachments"
|
||||
|
||||
message_id: Mapped[uuid.UUID] = mapped_column(
|
||||
Uuid, ForeignKey("messages.id"), primary_key=True
|
||||
)
|
||||
attachment_id: Mapped[uuid.UUID] = mapped_column(
|
||||
Uuid, ForeignKey("attachments.id"), primary_key=True
|
||||
)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
|
||||
class AttachmentRow(Base):
|
||||
__tablename__ = "attachments"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("chats.id"), nullable=False)
|
||||
owner_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id"), nullable=False)
|
||||
filename: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
content_type: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
size_bytes: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
sha256: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
object_key: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
|
||||
status: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
|
||||
class SessionRow(Base):
|
||||
__tablename__ = "sessions"
|
||||
|
||||
token_hash: Mapped[str] = mapped_column(String, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id"), nullable=False)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
revoked_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
|
||||
class IdempotencyRow(Base):
|
||||
__tablename__ = "idempotency_records"
|
||||
|
||||
scope_key: Mapped[str] = mapped_column(Text, primary_key=True)
|
||||
request_hash: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
message_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("messages.id"), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
Reference in New Issue
Block a user