Files

860 lines
30 KiB
Python

import base64
import binascii
import hashlib
import json
import logging
import os
import re
import secrets
import tempfile
import time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
import psycopg
import boto3
from botocore.exceptions import BotoCoreError, ClientError
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import StreamingResponse
from PIL import Image, UnidentifiedImageError
from psycopg.rows import dict_row
from fastapi import FastAPI, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
APP_HOST = os.getenv("APP_HOST", "0.0.0.0")
APP_PORT = int(os.getenv("APP_PORT", "8080"))
DATABASE_URL = os.getenv("DATABASE_URL", "")
DATABASE_URL_FILE = os.getenv("DATABASE_URL_FILE", "")
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
INSTANCE_ID = os.getenv("INSTANCE_ID", "api-" + uuid.uuid4().hex[:8])
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY_ID", "")
S3_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_ACCESS_KEY", "")
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
MIGRATIONS_DIR = Path(__file__).parent / "migrations"
PASSWORD_HASHER = PasswordHasher()
LOGGER = logging.getLogger("messenger")
class APIError(Exception):
def __init__(self, status_code: int, code: str, message: str):
self.status_code = status_code
self.code = code
self.message = message
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)
@field_validator("display_name", "password")
@classmethod
def validate_non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("value must not be blank")
return value
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)
@field_validator("title")
@classmethod
def validate_title(cls, value: str) -> str:
if not value.strip():
raise ValueError("title must not be blank")
return value
@field_validator("member_ids")
@classmethod
def validate_member_ids(cls, value: list[str]) -> list[str]:
if len(set(value)) != len(value):
raise ValueError("member_ids must be unique")
for member_id in value:
try:
uuid.UUID(member_id)
except ValueError as exc:
raise ValueError("member_ids must contain UUIDs") from exc
return value
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)
@field_validator("attachment_ids")
@classmethod
def validate_attachment_ids(cls, value: list[str]) -> list[str]:
if len(set(value)) != len(value):
raise ValueError("attachment_ids must be unique")
for attachment_id in value:
try:
uuid.UUID(attachment_id)
except ValueError as exc:
raise ValueError("attachment_ids must contain UUIDs") from exc
return value
class AttachmentError(Exception):
pass
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace(
"+00:00", "Z"
)
def database_url() -> str:
if DATABASE_URL:
return DATABASE_URL
if DATABASE_URL_FILE:
try:
return Path(DATABASE_URL_FILE).read_text(encoding="utf-8").strip()
except OSError as exc:
raise RuntimeError("database URL file is not readable") from exc
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
def db():
return psycopg.connect(database_url(), row_factory=dict_row)
def s3():
if not S3_ENDPOINT or not S3_ACCESS_KEY_ID or not S3_SECRET_ACCESS_KEY:
raise RuntimeError("S3 configuration is incomplete")
return boto3.client(
"s3",
endpoint_url=S3_ENDPOINT,
region_name=S3_REGION,
aws_access_key_id=S3_ACCESS_KEY_ID,
aws_secret_access_key=S3_SECRET_ACCESS_KEY,
)
def wait_for_s3() -> None:
deadline = time.monotonic() + 60
last_error: Exception | None = None
while time.monotonic() < deadline:
try:
s3().head_bucket(Bucket=S3_BUCKET)
return
except (BotoCoreError, ClientError, OSError) as exc:
last_error = exc
time.sleep(1)
raise RuntimeError("S3 bucket did not become ready") from last_error
def attachment_public(row: dict[str, Any]) -> dict[str, Any]:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"owner_id": str(row["owner_id"]),
"filename": row["filename"],
"content_type": row["content_type"],
"size_bytes": row["size_bytes"],
"sha256": row["sha256"],
"status": row["status"],
"variants": [],
"error_code": row["error_code"],
"created_at": iso(row["created_at"]),
"updated_at": iso(row["updated_at"]),
}
def attachment_ids_for_message(conn, message_id: uuid.UUID) -> list[str]:
rows = conn.execute(
"""
SELECT attachment_id FROM message_attachments
WHERE message_id = %s ORDER BY attachment_id
""",
(message_id,),
).fetchall()
return [str(row["attachment_id"]) for row in rows]
def public_message(conn, row: dict[str, Any]) -> dict[str, Any]:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": iso(row["created_at"]),
"attachment_ids": attachment_ids_for_message(conn, row["id"]),
}
def apply_migrations() -> None:
with db() as conn:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
version = path.name.split("_", 1)[0]
applied = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s", (version,)
).fetchone()
if applied is None:
for statement in path.read_text(encoding="utf-8").split(";"):
if statement.strip():
conn.execute(statement)
conn.execute(
"INSERT INTO schema_migrations(version) VALUES (%s)", (version,)
)
def wait_for_database() -> None:
deadline = time.monotonic() + 60
last_error: Exception | None = None
while time.monotonic() < deadline:
try:
apply_migrations()
return
except (OSError, psycopg.Error) as exc:
last_error = exc
time.sleep(1)
raise RuntimeError("database did not become ready") from last_error
def error_response(request: Request, status_code: int, code: str, message: str):
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
headers = {"X-Request-Id": request_id}
if status_code == 401:
headers["WWW-Authenticate"] = (
'Bearer realm="messenger"'
if request.url.path != "/api/v1/auth/sessions"
else 'Basic realm="messenger", charset="UTF-8"'
)
return JSONResponse(
status_code=status_code,
content={"error": {"code": code, "message": message, "request_id": request_id}},
headers=headers,
)
def bearer_user(request: Request) -> dict[str, Any]:
header = request.headers.get("Authorization", "")
scheme, _, token = header.partition(" ")
if scheme.lower() != "bearer" or not token or " " in token:
raise APIError(401, "unauthorized", "valid bearer session required")
hashed_token = token_hash(token)
with db() as conn:
user = conn.execute(
"""
SELECT u.id, u.username, u.display_name, u.created_at
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = %s AND s.revoked_at IS NULL
AND s.expires_at > now()
""",
(hashed_token,),
).fetchone()
if user is None:
raise APIError(401, "unauthorized", "valid bearer session required")
return user
def basic_credentials(request: Request) -> tuple[str, str]:
header = request.headers.get("Authorization", "")
scheme, _, encoded = header.partition(" ")
if scheme.lower() != "basic" or not encoded:
raise APIError(401, "unauthorized", "basic credentials required")
try:
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
username, separator, password = decoded.partition(":")
except (binascii.Error, UnicodeDecodeError):
raise APIError(401, "unauthorized", "invalid credentials") from None
if not separator or not username or not password:
raise APIError(401, "unauthorized", "invalid credentials")
return username, password
def token_hash(token: str) -> str:
try:
return hashlib.sha256(token.encode("ascii", "strict")).hexdigest()
except UnicodeEncodeError:
raise APIError(401, "unauthorized", "valid bearer session required") from None
def encode_cursor(created_at: datetime, object_id: uuid.UUID) -> str:
payload = json.dumps(
{"created_at": iso(created_at), "id": str(object_id)},
separators=(",", ":"),
).encode()
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
def decode_cursor(cursor: str) -> tuple[datetime, uuid.UUID]:
try:
padding = "=" * ((4 - len(cursor) % 4) % 4)
payload = json.loads(
base64.urlsafe_b64decode((cursor + padding).encode()).decode()
)
created_at = datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00"))
return created_at, uuid.UUID(payload["id"])
except (KeyError, TypeError, ValueError, UnicodeDecodeError, binascii.Error, json.JSONDecodeError):
raise APIError(400, "invalid_request", "cursor is invalid") from None
app = FastAPI(title="MTUSI Messenger Lab2")
@app.on_event("startup")
def startup() -> None:
wait_for_database()
wait_for_s3()
@app.middleware("http")
async def add_request_id(request: Request, call_next):
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
response = await call_next(request)
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
@app.exception_handler(APIError)
async def api_error_handler(request: Request, exc: APIError):
return error_response(request, exc.status_code, exc.code, exc.message)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "invalid request")
@app.exception_handler(Exception)
async def unexpected_error_handler(request: Request, exc: Exception):
return error_response(request, 500, "internal_error", "internal server error")
@app.get("/health/live")
def health_live():
return {"status": "ok"}
@app.get("/health/ready")
def health_ready():
try:
with db() as conn:
conn.execute("SELECT 1")
s3().head_bucket(Bucket=S3_BUCKET)
except (OSError, psycopg.Error, BotoCoreError, ClientError):
raise APIError(503, "unavailable", "required storage unavailable")
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
def create_user(payload: CreateUser):
user_id = uuid.uuid4()
password_hash = PASSWORD_HASHER.hash(payload.password)
try:
with db() as conn:
user = conn.execute(
"""
INSERT INTO users(id, username, display_name, password_hash)
VALUES (%s, %s, %s, %s)
RETURNING id, username, display_name, created_at
""",
(user_id, payload.username, payload.display_name, password_hash),
).fetchone()
except psycopg.errors.UniqueViolation:
raise APIError(409, "conflict", "user already exists") from None
return {**user, "id": str(user["id"]), "created_at": iso(user["created_at"])}
@app.post("/api/v1/auth/sessions", status_code=201)
def create_session(request: Request):
username, password = basic_credentials(request)
with db() as conn:
user = conn.execute(
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
(username,),
).fetchone()
if user is None:
raise APIError(401, "unauthorized", "invalid credentials")
try:
PASSWORD_HASHER.verify(user["password_hash"], password)
except VerificationError:
raise APIError(401, "unauthorized", "invalid credentials") from None
token = secrets.token_urlsafe(32)
expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS)
with db() as conn:
conn.execute(
"INSERT INTO sessions(token_hash, user_id, expires_at) VALUES (%s, %s, %s)",
(token_hash(token), user["id"], expires_at),
)
public_user = {
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": iso(user["created_at"]),
}
return {
"token": token,
"token_type": "Bearer",
"expires_at": iso(expires_at),
"user": public_user,
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(request: Request):
bearer_user(request)
header = request.headers["Authorization"]
token = header.split(" ", 1)[1]
with db() as conn:
conn.execute(
"UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
(token_hash(token),),
)
return Response(status_code=204)
@app.get("/api/v1/users/me")
def current_user(request: Request):
user = bearer_user(request)
return {**user, "id": str(user["id"]), "created_at": iso(user["created_at"])}
@app.post("/api/v1/chats", status_code=201)
def create_chat(payload: CreateChat, request: Request):
actor = bearer_user(request)
member_ids = [uuid.UUID(member_id) for member_id in payload.member_ids]
if actor["id"] not in member_ids:
raise APIError(400, "invalid_request", "actor must be included in member_ids")
chat_id = uuid.uuid4()
with db() as conn:
existing = conn.execute(
"SELECT id FROM users WHERE id = ANY(%s)", (member_ids,)
).fetchall()
if len(existing) != len(member_ids):
raise APIError(400, "invalid_request", "member not found")
chat = conn.execute(
"INSERT INTO chats(id, title) VALUES (%s, %s) RETURNING id, title, created_at",
(chat_id, payload.title),
).fetchone()
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)",
[(chat_id, member_id) for member_id in member_ids],
)
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": sorted(str(member_id) for member_id in member_ids),
"created_at": iso(chat["created_at"]),
}
def chat_for_user(conn, chat_id: uuid.UUID, user_id: uuid.UUID):
return conn.execute(
"""
SELECT c.id, c.title, c.created_at
FROM chats c JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = %s AND m.user_id = %s
""",
(chat_id, user_id),
).fetchone()
def public_chat(conn, chat: dict[str, Any]) -> dict[str, Any]:
members = conn.execute(
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id", (chat["id"],)
).fetchall()
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": [str(row["user_id"]) for row in members],
"created_at": iso(chat["created_at"]),
}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: uuid.UUID, request: Request):
actor = bearer_user(request)
with db() as conn:
chat = chat_for_user(conn, chat_id, actor["id"])
if chat is None:
raise APIError(404, "not_found", "chat not found")
return public_chat(conn, chat)
@app.get("/api/v1/chats")
def list_chats(request: Request, limit: int = Query(50, ge=1, le=100), cursor: str | None = None):
actor = bearer_user(request)
after = decode_cursor(cursor) if cursor else None
with db() as conn:
rows = conn.execute(
"""
SELECT c.id, c.title, c.created_at
FROM chats c JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = %s
AND (%s::timestamptz IS NULL OR (c.created_at, c.id) > (%s::timestamptz, %s::uuid))
ORDER BY c.created_at, c.id
LIMIT %s
""",
(actor["id"], after[0] if after else None, after[0] if after else None,
after[1] if after else None, limit + 1),
).fetchall()
items = [public_chat(conn, row) for row in rows[:limit]]
next_cursor = (
encode_cursor(rows[limit - 1]["created_at"], rows[limit - 1]["id"])
if len(rows) > limit
else None
)
return {"items": items, "next_cursor": next_cursor}
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(
chat_id: uuid.UUID,
payload: CreateMessage,
request: Request,
):
actor = bearer_user(request)
idempotency_key = request.headers.get("Idempotency-Key", "")
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", idempotency_key):
raise APIError(400, "invalid_request", "valid Idempotency-Key required")
attachment_ids = sorted(uuid.UUID(value) for value in payload.attachment_ids)
if not payload.text.strip() and not attachment_ids:
raise APIError(400, "invalid_request", "text or attachment is required")
request_hash = hashlib.sha256(
json.dumps(
{"text": payload.text, "attachment_ids": [str(value) for value in attachment_ids]},
ensure_ascii=False,
sort_keys=True,
).encode()
).hexdigest()
with db() as conn:
if chat_for_user(conn, chat_id, actor["id"]) is None:
raise APIError(404, "not_found", "chat not accessible")
if attachment_ids:
attachments = conn.execute(
"""
SELECT id, status FROM attachments
WHERE id = ANY(%s) AND chat_id = %s
""",
(attachment_ids, chat_id),
).fetchall()
if len(attachments) != len(attachment_ids):
raise APIError(404, "not_found", "attachment not found")
if any(row["status"] != "ready" for row in attachments):
raise APIError(409, "conflict", "attachment is not ready")
existing = conn.execute(
"""
INSERT INTO idempotency_keys(user_id, chat_id, idempotency_key, request_hash)
VALUES (%s, %s, %s, %s)
ON CONFLICT (user_id, chat_id, idempotency_key) DO NOTHING
RETURNING message_id, request_hash
""",
(actor["id"], chat_id, idempotency_key, request_hash),
).fetchone()
if existing is None:
existing = conn.execute(
"""
SELECT message_id, request_hash
FROM idempotency_keys
WHERE user_id = %s AND chat_id = %s AND idempotency_key = %s
FOR UPDATE
""",
(actor["id"], chat_id, idempotency_key),
).fetchone()
if existing["request_hash"] != request_hash:
raise APIError(409, "conflict", "idempotency key has another request")
message = conn.execute(
"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages WHERE id = %s
""",
(existing["message_id"],),
).fetchone()
if message is None:
raise APIError(503, "unavailable", "idempotent result is not ready")
return public_message(conn, message)
message_id = uuid.uuid4()
message = conn.execute(
"""
INSERT INTO messages(id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id, text, created_at
""",
(message_id, chat_id, actor["id"], payload.text),
).fetchone()
if attachment_ids:
with conn.cursor() as cur:
cur.executemany(
"""
INSERT INTO message_attachments(message_id, attachment_id)
VALUES (%s, %s)
""",
[(message_id, attachment_id) for attachment_id in attachment_ids],
)
conn.execute(
"""
UPDATE idempotency_keys SET message_id = %s
WHERE user_id = %s AND chat_id = %s AND idempotency_key = %s
""",
(message_id, actor["id"], chat_id, idempotency_key),
)
return public_message(conn, message)
def validate_filename(filename: str) -> None:
if not filename or len(filename) > 255:
raise APIError(400, "invalid_request", "filename is invalid")
if any(ord(char) < 32 for char in filename) or "/" in filename or "\\" in filename:
raise APIError(400, "invalid_request", "filename is invalid")
def inspect_image(path: Any, declared_type: str) -> tuple[str, int, int]:
try:
with Image.open(path) as image:
detected_type = {
"PNG": "image/png",
"JPEG": "image/jpeg",
}.get(image.format)
if detected_type is None or detected_type != declared_type:
raise APIError(415, "unsupported_media_type", "image type is invalid")
width, height = image.size
if width * height > MAX_IMAGE_PIXELS:
raise APIError(413, "payload_too_large", "image has too many pixels")
image.verify()
path.seek(0)
with Image.open(path) as image:
width, height = image.size
image.verify()
except APIError:
raise
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
raise APIError(415, "unsupported_media_type", "image is invalid") from None
return detected_type, width, height
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(chat_id: uuid.UUID, request: Request, filename: str):
actor = bearer_user(request)
validate_filename(filename)
declared_type = request.headers.get("content-type", "").split(";", 1)[0].lower()
if declared_type not in {"image/png", "image/jpeg"}:
raise APIError(415, "unsupported_media_type", "content type is invalid")
content_length = request.headers.get("content-length")
if content_length:
try:
if int(content_length) > MAX_UPLOAD_BYTES:
raise APIError(413, "payload_too_large", "file is too large")
except ValueError:
raise APIError(400, "invalid_request", "content length is invalid") from None
with db() as conn:
if chat_for_user(conn, chat_id, actor["id"]) is None:
raise APIError(404, "not_found", "chat not accessible")
size = 0
digest = hashlib.sha256()
object_key = "attachments/" + str(uuid.uuid4())
uploaded = False
try:
with tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b") as temporary:
async for chunk in request.stream():
size += len(chunk)
if size > MAX_UPLOAD_BYTES:
raise APIError(413, "payload_too_large", "file is too large")
digest.update(chunk)
temporary.write(chunk)
if size == 0:
raise APIError(415, "unsupported_media_type", "image is empty")
temporary.seek(0)
detected_type, _, _ = inspect_image(temporary, declared_type)
temporary.seek(0)
try:
await run_in_threadpool(
s3().upload_fileobj,
temporary,
S3_BUCKET,
object_key,
ExtraArgs={"ContentType": detected_type},
)
uploaded = True
except (BotoCoreError, ClientError, OSError):
raise APIError(503, "unavailable", "object storage unavailable") from None
except APIError:
raise
except (OSError, ValueError):
raise APIError(503, "unavailable", "upload could not be completed") from None
attachment_id = uuid.uuid4()
now = utc_now()
row = {
"id": attachment_id,
"chat_id": chat_id,
"owner_id": actor["id"],
"filename": filename,
"content_type": detected_type,
"size_bytes": size,
"sha256": digest.hexdigest(),
"status": "ready",
"error_code": None,
"created_at": now,
"updated_at": now,
}
try:
with db() as conn:
conn.execute(
"""
INSERT INTO attachments(
id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, status, object_key, error_code, created_at, updated_at
)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'ready', %s, NULL, %s, %s)
""",
(
attachment_id,
chat_id,
actor["id"],
filename,
detected_type,
size,
digest.hexdigest(),
object_key,
now,
now,
),
)
except psycopg.Error:
if uploaded:
try:
s3().delete_object(Bucket=S3_BUCKET, Key=object_key)
except (BotoCoreError, ClientError, OSError):
LOGGER.error("attachment compensation failed for object key")
raise APIError(503, "unavailable", "attachment metadata unavailable") from None
return attachment_public(row)
@app.get("/api/v1/attachments/{attachment_id}")
def get_attachment(attachment_id: uuid.UUID, request: Request):
actor = bearer_user(request)
with db() as conn:
row = conn.execute(
"""
SELECT a.*
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id
WHERE a.id = %s AND m.user_id = %s
""",
(attachment_id, actor["id"]),
).fetchone()
if row is None:
raise APIError(404, "not_found", "attachment not found")
return attachment_public(row)
@app.get("/api/v1/attachments/{attachment_id}/content")
def download_attachment(
attachment_id: uuid.UUID,
request: Request,
variant: str = "original",
):
actor = bearer_user(request)
if variant != "original":
raise APIError(404, "not_found", "attachment variant not found")
with db() as conn:
row = conn.execute(
"""
SELECT a.*
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id
WHERE a.id = %s AND m.user_id = %s
""",
(attachment_id, actor["id"]),
).fetchone()
if row is None:
raise APIError(404, "not_found", "attachment not found")
try:
object_response = s3().get_object(Bucket=S3_BUCKET, Key=row["object_key"])
except (BotoCoreError, ClientError, OSError):
raise APIError(503, "unavailable", "object storage unavailable") from None
body = object_response["Body"]
def chunks():
try:
while True:
chunk = body.read(1024 * 1024)
if not chunk:
break
yield chunk
finally:
body.close()
return StreamingResponse(
chunks(),
media_type=row["content_type"],
headers={"Content-Length": str(row["size_bytes"])},
)
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(
chat_id: uuid.UUID,
request: Request,
limit: int = Query(50, ge=1, le=100),
cursor: str | None = None,
):
actor = bearer_user(request)
after = decode_cursor(cursor) if cursor else None
with db() as conn:
if chat_for_user(conn, chat_id, actor["id"]) is None:
raise APIError(404, "not_found", "chat not accessible")
rows = conn.execute(
"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = %s
AND (%s::timestamptz IS NULL OR (created_at, id) > (%s::timestamptz, %s::uuid))
ORDER BY created_at, id
LIMIT %s
""",
(chat_id, after[0] if after else None, after[0] if after else None,
after[1] if after else None, limit + 1),
).fetchall()
items = [public_message(conn, row) for row in rows[:limit]]
next_cursor = (
encode_cursor(rows[limit - 1]["created_at"], rows[limit - 1]["id"])
if len(rows) > limit
else None
)
return {"items": items, "next_cursor": next_cursor}
if __name__ == "__main__":
import uvicorn
uvicorn.run("app:app", host=APP_HOST, port=APP_PORT, reload=False)