Добавить приватное хранилище вложений и отдачу файла через API.

Байты лежат в SeaweedFS, метаданные в Postgres. Другая реплика скачивает тот же объект, потому что локальный диск API не является источником файла.
This commit is contained in:
2026-11-09 00:25:36 +03:00
parent d208a87ae8
commit 00445bc41b
19 changed files with 889 additions and 52 deletions
+214
View File
@@ -0,0 +1,214 @@
"""Upload path: validate bytes, PUT, then commit metadata. See migration 003."""
from __future__ import annotations
import asyncio
import hashlib
import logging
from datetime import datetime, timezone
from uuid import UUID, uuid4
from app import config, db, s3
from app.errors import AppError
from app.store import format_ts
logger = logging.getLogger("messenger.attachments")
_sweep_task: asyncio.Task | None = None
def _public(row) -> dict:
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": None,
"created_at": format_ts(row["created_at"]),
"updated_at": format_ts(row["updated_at"]),
}
async def _drop_intent(key: str) -> None:
async with db.require().acquire() as conn:
await conn.execute(
"DELETE FROM blob_writes WHERE object_key = $1 AND NOT committed",
key,
)
async def _compensate(key: str) -> None:
try:
await s3.delete_key(key)
except AppError:
logger.warning("orphan object left for sweeper key=%s", key)
return
try:
await _drop_intent(key)
except Exception:
logger.warning("orphan intent left for sweeper key=%s", key)
async def create_attachment(
chat_id: str,
owner_id: str,
filename: str,
content_type: str,
data: bytes,
) -> dict:
attachment_id = uuid4()
key = f"originals/{attachment_id}"
created = datetime.now(timezone.utc)
digest = hashlib.sha256(data).hexdigest()
async with db.require().acquire() as conn:
await conn.execute(
"""
INSERT INTO blob_writes (object_key, committed, created_at)
VALUES ($1, FALSE, $2)
""",
key,
created,
)
try:
await s3.put_bytes(key, data, content_type)
except Exception:
await _compensate(key)
raise
try:
async with db.require().acquire() as conn:
async with conn.transaction():
intent = await conn.fetchrow(
"SELECT committed FROM blob_writes WHERE object_key = $1 FOR UPDATE",
key,
)
if intent is None or intent["committed"]:
raise AppError(503, "service unavailable")
await conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, object_key, status, error_code, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'ready', NULL, $9, $9)
""",
attachment_id,
UUID(chat_id),
UUID(owner_id),
filename,
content_type,
len(data),
digest,
key,
created,
)
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
key,
)
except AppError:
await _compensate(key)
raise
except Exception:
await _compensate(key)
raise AppError(503, "service unavailable") from None
return _public(
{
"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,
"status": "ready",
"created_at": created,
"updated_at": created,
}
)
async def get_for_member(attachment_id: str, user_id: str):
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.object_key, a.status, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
WHERE a.id = $1
""",
UUID(attachment_id),
UUID(user_id),
)
return row
async def sweep_orphans() -> int:
"""Delete uncommitted objects older than the grace period. In-use rows stay."""
deleted = 0
async with db.require().acquire() as conn:
async with conn.transaction():
rows = await conn.fetch(
"""
SELECT object_key
FROM blob_writes
WHERE NOT committed
AND created_at < now() - ($1::int * interval '1 second')
ORDER BY created_at
LIMIT 50
FOR UPDATE SKIP LOCKED
""",
config.ORPHAN_GRACE_SECONDS,
)
for row in rows:
key = row["object_key"]
linked = await conn.fetchval(
"SELECT 1 FROM attachments WHERE object_key = $1",
key,
)
if linked:
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
key,
)
continue
await s3.delete_key(key)
await conn.execute("DELETE FROM blob_writes WHERE object_key = $1", key)
deleted += 1
if deleted:
logger.info("removed %s uncommitted objects past grace", deleted)
return deleted
async def _sweep_loop() -> None:
while True:
try:
await sweep_orphans()
except asyncio.CancelledError:
raise
except Exception:
logger.warning("orphan sweep failed")
await asyncio.sleep(config.S3_SWEEP_INTERVAL_SECONDS)
def start_sweeper() -> None:
global _sweep_task
if _sweep_task is None or _sweep_task.done():
_sweep_task = asyncio.create_task(_sweep_loop())
async def stop_sweeper() -> None:
global _sweep_task
task = _sweep_task
_sweep_task = None
if task is None:
return
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
+9
View File
@@ -36,6 +36,15 @@ LB_DRAIN_SECONDS = float(_env("LB_DRAIN_SECONDS", "2"))
# Stable for the life of this process. Compose leaves it unset so each
# container uses its own hostname; stop-one.sh maps that value to one replica.
INSTANCE_ID = _env("INSTANCE_ID", socket.gethostname())
S3_ENDPOINT = _env("S3_ENDPOINT", "http://s3:9000")
S3_REGION = _env("S3_REGION", "us-east-1")
S3_BUCKET = _env("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY_ID = _file_or_env("S3_ACCESS_KEY_ID")
S3_SECRET_ACCESS_KEY = _file_or_env("S3_SECRET_ACCESS_KEY")
MAX_UPLOAD_BYTES = min(int(_env("MAX_UPLOAD_BYTES", "10485760")), 10_485_760)
MAX_IMAGE_PIXELS = min(int(_env("MAX_IMAGE_PIXELS", "40000000")), 40_000_000)
ORPHAN_GRACE_SECONDS = int(_env("ORPHAN_GRACE_SECONDS", "120"))
S3_SWEEP_INTERVAL_SECONDS = int(_env("S3_SWEEP_INTERVAL_SECONDS", "30"))
def lab_mode() -> bool:
+107
View File
@@ -0,0 +1,107 @@
"""PNG/JPEG checks that reject bad files before a full pixel decode."""
from __future__ import annotations
import io
from typing import Optional, Tuple
from PIL import Image, ImageFile, UnidentifiedImageError
from app import config
ImageFile.LOAD_TRUNCATED_IMAGES = False
_PNG = b"\x89PNG\r\n\x1a\n"
_JPEG = b"\xff\xd8\xff"
_SOF = {0xC0, 0xC1, 0xC2}
class ImageRejected(Exception):
def __init__(self, status: int, message: str) -> None:
super().__init__(message)
self.status = status
self.message = message
def _reject(status: int, message: str) -> None:
raise ImageRejected(status, message)
def sniff(data: bytes) -> Optional[str]:
if data.startswith(_PNG):
return "image/png"
if data.startswith(_JPEG):
return "image/jpeg"
return None
def _png_size(data: bytes) -> Tuple[int, int]:
if len(data) < 24 or data[12:16] != b"IHDR":
_reject(415, "unsupported or damaged image")
length = int.from_bytes(data[8:12], "big")
if length != 13 or len(data) < 33:
_reject(415, "unsupported or damaged image")
width = int.from_bytes(data[16:20], "big")
height = int.from_bytes(data[20:24], "big")
return width, height
def _jpeg_size(data: bytes) -> Tuple[int, int]:
index = 2
size = len(data)
while index < size:
if data[index] != 0xFF:
_reject(415, "unsupported or damaged image")
while index < size and data[index] == 0xFF:
index += 1
if index >= size:
break
marker = data[index]
index += 1
if marker in (0xD8, 0xD9, 0x01) or 0xD0 <= marker <= 0xD7:
continue
if index + 1 >= size:
break
segment = int.from_bytes(data[index : index + 2], "big")
if segment < 2 or index + segment > size:
_reject(415, "unsupported or damaged image")
if marker in _SOF:
if segment < 7:
_reject(415, "unsupported or damaged image")
height = int.from_bytes(data[index + 3 : index + 5], "big")
width = int.from_bytes(data[index + 5 : index + 7], "big")
return width, height
if marker == 0xDA:
break
index += segment
_reject(415, "unsupported or damaged image")
return 0, 0
def _check_pixels(width: int, height: int) -> None:
limit = config.MAX_IMAGE_PIXELS
if width <= 0 or height <= 0:
_reject(415, "unsupported or damaged image")
if width > limit or height > limit or width * height > limit:
_reject(413, "image dimensions exceed the limit")
def _verify(data: bytes) -> None:
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
try:
with Image.open(io.BytesIO(data)) as image:
image.verify()
except Image.DecompressionBombError:
_reject(413, "image dimensions exceed the limit")
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
_reject(415, "unsupported or damaged image")
def inspect_image(data: bytes, declared: str) -> str:
"""Return the sniffed content type or raise ImageRejected (413 or 415)."""
found = sniff(data)
if found is None or found != declared:
_reject(415, "unsupported or damaged image")
width, height = _png_size(data) if found == "image/png" else _jpeg_size(data)
_check_pixels(width, height)
_verify(data)
return found
+11 -1
View File
@@ -12,7 +12,7 @@ from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route
from app import config, db, rediscli
from app import attachments, config, db, rediscli
from app.docs import openapi_json, swagger_ui
from app.errors import AppError, error_response, from_app_error
from app.middleware import RequestContextMiddleware
@@ -21,15 +21,19 @@ from app.routes import (
create_message,
create_session,
current_user,
download_attachment,
get_attachment,
get_chat,
health_live,
health_ready,
lab_flags,
lab_metrics,
lab_sweep,
list_chats,
list_messages,
register_user,
revoke_session,
upload_attachment,
)
@@ -63,9 +67,11 @@ async def startup() -> None:
if config.MIGRATIONS_ON_START:
await db.apply_migrations()
await rediscli.connect()
attachments.start_sweeper()
async def shutdown() -> None:
await attachments.stop_sweeper()
await rediscli.close()
await db.close()
@@ -86,8 +92,12 @@ def build_app() -> Starlette:
Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]),
Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]),
Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]),
Route("/api/v1/chats/{chat_id}/attachments", upload_attachment, methods=["POST"]),
Route("/api/v1/attachments/{attachment_id}", get_attachment, methods=["GET"]),
Route("/api/v1/attachments/{attachment_id}/content", download_attachment, methods=["GET"]),
Route("/api/v1/_lab/metrics", lab_metrics, methods=["GET"]),
Route("/api/v1/_lab/flags", lab_flags, methods=["POST"]),
Route("/api/v1/_lab/sweep", lab_sweep, methods=["POST"]),
],
exception_handlers={404: not_found_handler, AppError: app_error_handler},
on_startup=[startup],
+40 -25
View File
@@ -1,11 +1,10 @@
import logging
import time
import uuid
from typing import Callable
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.datastructures import MutableHeaders
from starlette.responses import Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from app.config import INSTANCE_ID
from app.errors import AppError, error_response, from_app_error
@@ -13,36 +12,52 @@ from app.errors import AppError, error_response, from_app_error
logger = logging.getLogger("messenger.access")
def _stamp(response: Response, request_id: str) -> Response:
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
class RequestContextMiddleware:
"""Pure ASGI middleware so upload handlers can read the body stream themselves."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
class RequestContextMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: Callable) -> Response:
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
if request.app.state.shutting_down and request.url.path not in ("/health/live", "/health/ready"):
return _stamp(error_response(503, "service is shutting down", request_id), request_id)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
headers = {key.decode("latin1").lower(): value.decode("latin1") for key, value in scope.get("headers", [])}
request_id = headers.get("x-request-id") or str(uuid.uuid4())
raw_state = scope.get("state")
if not isinstance(raw_state, dict):
raw_state = {}
scope["state"] = raw_state
raw_state["request_id"] = request_id
path = scope.get("path", "")
started = time.perf_counter()
async def send_wrapper(message: Message) -> None:
if message["type"] == "http.response.start":
response_headers = MutableHeaders(scope=message)
response_headers["X-Request-Id"] = request_id
response_headers["X-Instance-Id"] = INSTANCE_ID
await send(message)
app = scope.get("app")
shutting_down = bool(app and getattr(app.state, "shutting_down", False))
if shutting_down and path not in ("/health/live", "/health/ready"):
response: Response = error_response(503, "service is shutting down", request_id)
await response(scope, receive, send_wrapper)
return
try:
response = await call_next(request)
await self.app(scope, receive, send_wrapper)
except AppError as exc:
return _stamp(from_app_error(exc, request_id), request_id)
await from_app_error(exc, request_id)(scope, receive, send_wrapper)
except Exception:
logger.exception("request_id=%s unhandled error path=%s", request_id, request.url.path)
return _stamp(error_response(500, "internal error", request_id), request_id)
logger.exception("request_id=%s unhandled error path=%s", request_id, path)
await error_response(500, "internal error", request_id)(scope, receive, send_wrapper)
return
elapsed_ms = (time.perf_counter() - started) * 1000
_stamp(response, request_id)
logger.info(
"request_id=%s method=%s path=%s status=%s duration_ms=%.2f",
"request_id=%s method=%s path=%s duration_ms=%.2f",
request_id,
request.method,
request.url.path,
response.status_code,
scope.get("method", ""),
path,
elapsed_ms,
)
return response
+96 -3
View File
@@ -4,14 +4,16 @@ import binascii
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from app import cache, config, db, rediscli, sessions, store
from app import attachments, cache, config, db, images, rediscli, s3, sessions, store
from app.cursor_codec import decode_cursor, encode_cursor
from app.errors import BASIC_CHALLENGE, BEARER_CHALLENGE, AppError, error_response
from app.passwords import dummy_hash, hash_password, verify_password
from app.validation import (
parse_json_body,
require_exact_keys,
parse_attachment_ids,
validate_display_name,
validate_filename,
validate_limit,
validate_idempotency_key,
validate_message_text,
@@ -52,6 +54,7 @@ async def health_ready(request: Request) -> Response:
return error_response(503, "service is shutting down", rid)
await db.ping()
await rediscli.ping()
await s3.head_bucket()
return _json({"status": "ok"}, rid)
@@ -202,9 +205,13 @@ async def create_message(request: Request) -> Response:
if err:
return error_response(400, err, rid)
assert body is not None
if require_exact_keys(body, {"text"}, {"text"}):
if require_exact_keys(body, {"text", "attachment_ids"}, {"text"}):
return error_response(400, "invalid message payload", rid)
if validate_message_text(body["text"]):
attachment_ids, attachment_err = parse_attachment_ids(body.get("attachment_ids"))
if attachment_err:
return error_response(400, attachment_err, rid)
assert attachment_ids is not None
if validate_message_text(body["text"], allow_blank=bool(attachment_ids)):
return error_response(400, "invalid message text", rid)
if validate_idempotency_key(request.headers.get("Idempotency-Key")):
return error_response(400, "invalid idempotency key", rid)
@@ -214,11 +221,14 @@ async def create_message(request: Request) -> Response:
body["text"],
request.headers.get("Idempotency-Key") or "",
request.url.path,
attachment_ids,
)
if msg_err == "not_found":
return error_response(404, "chat not found", rid)
if msg_err == "conflict":
return error_response(409, "idempotency key reused with a different body", rid)
if msg_err == "not_ready":
return error_response(409, "attachment is not ready", rid)
assert message is not None
return _json(message, rid, 201)
@@ -253,6 +263,89 @@ async def list_messages(request: Request) -> Response:
return _json({"items": page, "next_cursor": next_cursor}, rid)
def _media_type(value: str) -> str:
return value.split(";", 1)[0].strip().lower()
async def _read_limited(request: Request, limit: int) -> bytes:
received = bytearray()
async for chunk in request.stream():
if len(received) + len(chunk) > limit:
raise AppError(413, "file exceeds upload limit")
received.extend(chunk)
return bytes(received)
async def upload_attachment(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
chat_id = request.path_params["chat_id"]
if validate_uuid(chat_id):
return error_response(400, "invalid chat id", rid)
if validate_filename(request.query_params.get("filename")):
return error_response(400, "invalid filename", rid)
filename = request.query_params.get("filename") or ""
declared = _media_type(request.headers.get("content-type", ""))
if declared not in ("image/png", "image/jpeg"):
return error_response(415, "unsupported media type", rid)
content_length = request.headers.get("content-length")
if content_length is not None:
try:
announced = int(content_length)
except ValueError:
return error_response(400, "invalid content length", rid)
if announced > config.MAX_UPLOAD_BYTES:
return error_response(413, "file exceeds upload limit", rid)
if announced <= 0:
return error_response(415, "unsupported or damaged image", rid)
if await store.load_chat_for_member(chat_id, user["id"]) is None:
return error_response(404, "chat not found", rid)
data = await _read_limited(request, config.MAX_UPLOAD_BYTES)
if not data:
return error_response(415, "unsupported or damaged image", rid)
try:
content_type = images.inspect_image(data, declared)
except images.ImageRejected as exc:
return error_response(exc.status, exc.message, rid)
created = await attachments.create_attachment(chat_id, user["id"], filename, content_type, data)
return _json(created, rid, 201)
async def get_attachment(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
row = await attachments.get_for_member(attachment_id, user["id"])
if row is None:
return error_response(404, "attachment not found", rid)
return _json(attachments._public(row), rid)
async def download_attachment(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
variant = request.query_params.get("variant")
if variant not in (None, "original"):
return error_response(400, "invalid variant", rid)
row = await attachments.get_for_member(attachment_id, user["id"])
if row is None:
return error_response(404, "attachment not found", rid)
payload = await s3.get_bytes(row["object_key"])
return Response(payload, status_code=200, media_type=row["content_type"], headers={"X-Request-Id": rid})
async def lab_sweep(request: Request) -> Response:
if not config.lab_mode():
return error_response(404, "not found", request.state.request_id)
deleted = await attachments.sweep_orphans()
return _json({"deleted": deleted}, request.state.request_id)
async def lab_metrics(request: Request) -> Response:
if not config.lab_mode():
return error_response(404, "not found", request.state.request_id)
+109
View File
@@ -0,0 +1,109 @@
"""Private bucket access. The API never redirects a client to this endpoint."""
from __future__ import annotations
import asyncio
import logging
import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
from app import config
from app.errors import AppError
logger = logging.getLogger("messenger.s3")
_client = None
def _client_or_create():
global _client
if _client is None:
if not config.S3_ACCESS_KEY_ID or not config.S3_SECRET_ACCESS_KEY:
raise AppError(503, "service unavailable")
_client = boto3.client(
"s3",
endpoint_url=config.S3_ENDPOINT,
aws_access_key_id=config.S3_ACCESS_KEY_ID,
aws_secret_access_key=config.S3_SECRET_ACCESS_KEY,
region_name=config.S3_REGION,
config=Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=2,
read_timeout=20,
retries={"max_attempts": 2},
),
)
return _client
def _unavailable(exc: Exception) -> AppError:
code = ""
if isinstance(exc, ClientError):
code = exc.response.get("Error", {}).get("Code", "")
logger.warning("object storage call failed code=%s", code or type(exc).__name__)
return AppError(503, "service unavailable")
async def head_bucket() -> None:
def _head() -> None:
_client_or_create().head_bucket(Bucket=config.S3_BUCKET)
try:
await asyncio.to_thread(_head)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
async def put_bytes(key: str, data: bytes, content_type: str) -> None:
def _put() -> None:
_client_or_create().put_object(
Bucket=config.S3_BUCKET,
Key=key,
Body=data,
ContentType=content_type,
ContentLength=len(data),
)
try:
await asyncio.to_thread(_put)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
async def get_bytes(key: str) -> bytes:
def _get() -> bytes:
response = _client_or_create().get_object(Bucket=config.S3_BUCKET, Key=key)
body = response["Body"].read()
response["Body"].close()
return body
try:
return await asyncio.to_thread(_get)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
async def delete_key(key: str) -> None:
def _delete() -> None:
try:
_client_or_create().delete_object(Bucket=config.S3_BUCKET, Key=key)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code in {"NoSuchKey", "404", "NoSuchBucket"}:
return
raise
try:
await asyncio.to_thread(_delete)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
+48
View File
@@ -0,0 +1,48 @@
"""Create the private bucket if it is missing. Safe to run again."""
import os
import sys
import time
import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
def main() -> None:
endpoint = os.environ["S3_ENDPOINT"]
bucket = os.environ["S3_BUCKET"]
client = boto3.client(
"s3",
endpoint_url=endpoint,
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
region_name=os.environ.get("S3_REGION", "us-east-1"),
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 2}),
)
last_error = "not attempted"
for _ in range(20):
try:
client.head_bucket(Bucket=bucket)
print("bucket ready")
return
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code not in {"404", "NoSuchBucket", "NotFound"}:
last_error = code or "ClientError"
else:
try:
client.create_bucket(Bucket=bucket)
print("bucket created")
return
except ClientError as create_exc:
last_error = create_exc.response.get("Error", {}).get("Code", "create failed")
except BotoCoreError:
last_error = "connection failed"
time.sleep(1)
print("bucket bootstrap failed:", last_error, file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
+58 -11
View File
@@ -37,12 +37,16 @@ def chat_dict(row, member_ids: List[str]) -> dict:
def message_dict(row) -> dict:
raw_ids = row["attachment_ids"] if "attachment_ids" in row.keys() else []
if raw_ids is None:
raw_ids = []
return {
"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": [str(item) for item in raw_ids],
}
@@ -192,10 +196,10 @@ async def list_chats(user_id: str, limit: int, after: Optional[Tuple[str, str]]
return items, next_key
def _canonical_message(text: str) -> str:
def _canonical_message(text: str, attachment_ids: List[str]) -> str:
# Missing attachment_ids and [] are the same message. Key order does not matter.
return json.dumps(
{"attachment_ids": [], "text": text},
{"attachment_ids": attachment_ids, "text": text},
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
@@ -208,13 +212,15 @@ async def add_message(
text: str,
idem_key: str,
path: str,
attachment_ids: Optional[List[str]] = None,
) -> Tuple[Optional[dict], Optional[str]]:
"""Insert one message or replay the stored 201. The row and the result commit together.
Same user+method+path+key is serialized with a Postgres advisory lock so two
replicas cannot insert two messages. A failed transaction stores nothing.
"""
digest = hashlib.sha256(_canonical_message(text).encode("utf-8")).hexdigest()
attachment_ids = list(attachment_ids or [])
digest = hashlib.sha256(_canonical_message(text, attachment_ids).encode("utf-8")).hexdigest()
lock_key = f"{sender_id}|POST|{path}|{idem_key}"
payload: Optional[dict] = None
created_new = False
@@ -262,6 +268,24 @@ async def add_message(
path,
idem_key,
)
resolved: List[str] = []
if attachment_ids:
rows = await conn.fetch(
"""
SELECT id, chat_id, status
FROM attachments
WHERE id = ANY($1::uuid[])
""",
[UUID(item) for item in attachment_ids],
)
found = {str(row["id"]): row for row in rows}
if len(found) != len(attachment_ids) or any(
str(found[item]["chat_id"]) != chat_id for item in attachment_ids
):
return None, "not_found"
if any(found[item]["status"] != "ready" for item in attachment_ids):
return None, "not_ready"
resolved = attachment_ids
message_id = uuid4()
created = datetime.now(timezone.utc)
await conn.execute(
@@ -275,6 +299,14 @@ async def add_message(
text,
created,
)
if resolved:
await conn.executemany(
"""
INSERT INTO message_attachments (message_id, attachment_id, position)
VALUES ($1, $2, $3)
""",
[(message_id, UUID(item), index) for index, item in enumerate(resolved)],
)
payload = message_dict(
{
"id": message_id,
@@ -282,6 +314,7 @@ async def add_message(
"sender_id": UUID(sender_id),
"text": text,
"created_at": created,
"attachment_ids": resolved,
}
)
await conn.execute(
@@ -323,10 +356,17 @@ async def list_messages(chat_id: str, user_id: str, limit: int, after: Optional[
rows = await _run(
_fetch(
"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
ORDER BY created_at, id
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
COALESCE(
array_agg(ma.attachment_id ORDER BY ma.position)
FILTER (WHERE ma.attachment_id IS NOT NULL),
ARRAY[]::uuid[]
) AS attachment_ids
FROM messages m
LEFT JOIN message_attachments ma ON ma.message_id = m.id
WHERE m.chat_id = $1
GROUP BY m.id
ORDER BY m.created_at, m.id
LIMIT $2
""",
UUID(chat_id),
@@ -337,10 +377,17 @@ async def list_messages(chat_id: str, user_id: str, limit: int, after: Optional[
rows = await _run(
_fetch(
"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
COALESCE(
array_agg(ma.attachment_id ORDER BY ma.position)
FILTER (WHERE ma.attachment_id IS NOT NULL),
ARRAY[]::uuid[]
) AS attachment_ids
FROM messages m
LEFT JOIN message_attachments ma ON ma.message_id = m.id
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
GROUP BY m.id
ORDER BY m.created_at, m.id
LIMIT $4
""",
UUID(chat_id),
+32 -3
View File
@@ -80,16 +80,45 @@ def validate_idempotency_key(value: Optional[str]) -> Optional[str]:
return None
def validate_message_text(value: Any) -> Optional[str]:
def validate_message_text(value: Any, *, allow_blank: bool = False) -> Optional[str]:
if not isinstance(value, str):
return "invalid text"
if not value.strip():
return "text must not be blank"
if len(value) > 4000:
return "text too long"
if not allow_blank and not value.strip():
return "text must not be blank"
return None
def validate_filename(value: Optional[str]) -> Optional[str]:
if not isinstance(value, str) or not value.strip() or len(value) > 255:
return "invalid filename"
for char in value:
code = ord(char)
if code < 32 or code == 127 or char in "/\\":
return "invalid filename"
return None
def parse_attachment_ids(value: Any) -> Tuple[Optional[list], Optional[str]]:
if value is None:
return [], None
if not isinstance(value, list):
return None, "invalid attachment_ids"
if len(value) > 10:
return None, "too many attachments"
seen = set()
ids = []
for item in value:
if validate_uuid(item):
return None, "invalid attachment id"
if item in seen:
return None, "duplicate attachment_ids"
seen.add(item)
ids.append(item)
return ids, None
def validate_limit(value: Optional[str], default: int = 50) -> Tuple[Optional[int], Optional[str]]:
if value is None:
return default, None