выполнение лабораторной на 5

This commit is contained in:
kaktuz20000
2026-10-26 17:55:33 +03:00
parent ec540a1a72
commit bd0b9f6849
34 changed files with 2818 additions and 49 deletions
+1
View File
@@ -0,0 +1 @@
"""Messenger API application package."""
+39
View File
@@ -0,0 +1,39 @@
import logging
import os
import signal
import threading
from functools import partial
from http.server import ThreadingHTTPServer
from .config import APP_HOST, APP_PORT
from .handlers import MessengerHandler
from .store import Store
LOGGER = logging.getLogger("messenger")
def run_server():
store = Store()
store.open()
try:
handler = partial(MessengerHandler, store=store)
server = ThreadingHTTPServer((APP_HOST, APP_PORT), handler)
def handle_shutdown(signum, frame):
LOGGER.info("received signal %s, shutting down gracefully", signum)
threading.Thread(target=server.shutdown, daemon=True).start()
signal.signal(signal.SIGTERM, handle_shutdown)
signal.signal(signal.SIGINT, handle_shutdown)
LOGGER.info("listening on %s:%s", APP_HOST, APP_PORT)
try:
server.serve_forever()
finally:
server.server_close()
finally:
store.close()
def main():
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
run_server()
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
import logging
import os
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
LOGGER = logging.getLogger("messenger.s3.bootstrap")
def secret(name: str) -> str:
direct = os.getenv(name)
if direct:
return direct
file_path = os.getenv(name + "_FILE")
if file_path:
return Path(file_path).read_text(encoding="utf-8").strip()
raise RuntimeError(f"Set {name} or {name}_FILE")
def main():
client = boto3.client(
"s3",
endpoint_url=os.getenv("S3_ENDPOINT", "http://s3:8333"),
region_name="us-east-1",
aws_access_key_id=secret("S3_ADMIN_ACCESS_KEY_ID"),
aws_secret_access_key=secret("S3_ADMIN_SECRET_ACCESS_KEY"),
config=Config(connect_timeout=2, read_timeout=5, retries={"max_attempts": 3}),
)
bucket = os.getenv("S3_BUCKET", "messenger-attachments")
try:
client.head_bucket(Bucket=bucket)
except ClientError as exc:
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
if status != 404:
raise
client.create_bucket(Bucket=bucket)
client.put_bucket_acl(Bucket=bucket, ACL="private")
LOGGER.info("private S3 bucket bootstrap completed")
if __name__ == "__main__":
logging.basicConfig(level="INFO", format="%(levelname)s %(message)s")
main()
+61
View File
@@ -0,0 +1,61 @@
import os
import re
import socket
import uuid
from pathlib import Path
APP_HOST = os.getenv("APP_HOST", "0.0.0.0")
APP_PORT = int(os.getenv("APP_PORT", "8080"))
INSTANCE_ID = os.getenv("INSTANCE_ID", socket.gethostname() or uuid.uuid4().hex[:12])
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
IDEMPOTENCY_TTL_SECONDS = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
DB_STATEMENT_TIMEOUT_MS = int(os.getenv("DB_STATEMENT_TIMEOUT_MS", "5000"))
DB_LOCK_TIMEOUT_MS = int(os.getenv("DB_LOCK_TIMEOUT_MS", "2000"))
DB_POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "16"))
DB_POOL_TIMEOUT_SECONDS = float(os.getenv("DB_POOL_TIMEOUT_SECONDS", "5"))
MAX_INFLIGHT_REQUESTS = int(os.getenv("MAX_INFLIGHT_REQUESTS", "128"))
MAX_REQUEST_BODY_BYTES = int(os.getenv("MAX_REQUEST_BODY_BYTES", "1048576"))
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
MAX_CONCURRENT_UPLOADS = int(os.getenv("MAX_CONCURRENT_UPLOADS", "10"))
UPLOAD_TIMEOUT_SECONDS = int(os.getenv("UPLOAD_TIMEOUT_SECONDS", "60"))
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
def secret_value(name: str, default: str = "") -> str:
value = os.getenv(name)
if value:
return value
file_path = os.getenv(name + "_FILE")
if file_path:
return Path(file_path).read_text(encoding="utf-8").strip()
if default:
return default
raise RuntimeError(f"Set {name} or {name}_FILE")
S3_ACCESS_KEY_ID = secret_value("S3_ACCESS_KEY_ID")
S3_SECRET_ACCESS_KEY = secret_value("S3_SECRET_ACCESS_KEY")
USER_RE = re.compile(r"^[a-z0-9_]{3,32}$")
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
if SESSION_TTL_SECONDS < 1:
raise RuntimeError("SESSION_TTL_SECONDS must be positive")
if IDEMPOTENCY_TTL_SECONDS < 86400:
raise RuntimeError("IDEMPOTENCY_TTL_SECONDS must be at least 86400")
if DB_STATEMENT_TIMEOUT_MS < 1 or DB_LOCK_TIMEOUT_MS < 1:
raise RuntimeError("Database timeouts must be positive")
if DB_POOL_MAX_SIZE < 1 or DB_POOL_TIMEOUT_SECONDS <= 0:
raise RuntimeError("Database pool settings must be positive")
if MAX_INFLIGHT_REQUESTS < 1 or MAX_REQUEST_BODY_BYTES < 1:
raise RuntimeError("HTTP limits must be positive")
if MAX_UPLOAD_BYTES < 1 or MAX_UPLOAD_BYTES > 10 * 1024 * 1024:
raise RuntimeError("MAX_UPLOAD_BYTES must be between 1 and 10 MiB")
if MAX_IMAGE_PIXELS < 1 or MAX_IMAGE_PIXELS > 40_000_000:
raise RuntimeError("MAX_IMAGE_PIXELS must be between 1 and 40 million")
if MAX_CONCURRENT_UPLOADS < 1:
raise RuntimeError("MAX_CONCURRENT_UPLOADS must be positive")
if UPLOAD_TIMEOUT_SECONDS < 1:
raise RuntimeError("UPLOAD_TIMEOUT_SECONDS must be positive")
+26
View File
@@ -0,0 +1,26 @@
from typing import Dict, Optional
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers: Optional[Dict[str, str]] = None):
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
class CacheUnavailableError(Exception):
pass
class IdempotencyConflictError(Exception):
pass
class AttachmentNotReadyError(Exception):
pass
class ObjectMissingError(Exception):
pass
+548
View File
@@ -0,0 +1,548 @@
import base64
import hashlib
import json
import logging
import threading
import time
import tempfile
import uuid
import warnings
from http.server import BaseHTTPRequestHandler
from typing import Any, BinaryIO, Dict, List, Optional, Tuple
from urllib.parse import parse_qs, urlsplit
import unicodedata
import psycopg
from botocore.exceptions import BotoCoreError, ClientError
from PIL import Image, UnidentifiedImageError
from psycopg_pool import PoolTimeout
from .config import (
IDEMPOTENCY_KEY_RE,
INSTANCE_ID,
MAX_CONCURRENT_UPLOADS,
MAX_IMAGE_PIXELS,
MAX_INFLIGHT_REQUESTS,
MAX_REQUEST_BODY_BYTES,
MAX_UPLOAD_BYTES,
UPLOAD_TIMEOUT_SECONDS,
USER_RE,
)
from .errors import (
ApiError,
AttachmentNotReadyError,
CacheUnavailableError,
IdempotencyConflictError,
ObjectMissingError,
)
from .security import hash_password, isoformat, valid_uuid
from .store import Store
LOGGER = logging.getLogger("messenger.http")
class RequestGuard:
def __init__(self):
self.lock = threading.Lock()
self.inflight = 0
def acquire(self):
with self.lock:
if self.inflight >= MAX_INFLIGHT_REQUESTS:
raise ApiError(503, "unavailable", "Server is busy")
self.inflight += 1
def release(self):
with self.lock:
self.inflight = max(0, self.inflight - 1)
REQUEST_GUARD = RequestGuard()
UPLOAD_GUARD = threading.BoundedSemaphore(MAX_CONCURRENT_UPLOADS)
class MessengerHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server, store: Store):
self.store = store
super().__init__(request, client_address, server)
def setup(self):
super().setup()
self.connection.settimeout(15)
def log_message(self, format: str, *args):
return
def do_GET(self):
self._dispatch("GET")
def do_POST(self):
self._dispatch("POST")
def do_DELETE(self):
self._dispatch("DELETE")
def _dispatch(self, method: str):
request_id = self.headers.get("X-Request-Id") or str(uuid.uuid4())
acquired = False
try:
REQUEST_GUARD.acquire()
acquired = True
parsed = urlsplit(self.path)
path = parsed.path
query = parse_qs(parsed.query, keep_blank_values=True)
if path == "/health/live" and method == "GET":
self._send_json(200, {"status": "ok"}, request_id)
elif path == "/health/ready" and method == "GET":
try:
self.store.ready()
except (psycopg.Error, PoolTimeout, OSError, BotoCoreError, ClientError):
raise ApiError(503, "unavailable", "A required storage service is unavailable")
self._send_json(200, {"status": "ok"}, request_id)
elif path == "/api/v1/users" and method == "POST":
self._handle_register(request_id)
elif path == "/api/v1/auth/sessions" and method == "POST":
self._handle_create_session(request_id)
elif path == "/api/v1/auth/sessions/current" and method == "DELETE":
self._handle_revoke_session(request_id)
elif path == "/api/v1/users/me" and method == "GET":
self._send_json(200, self._get_actor(request_id), request_id)
elif path == "/api/v1/chats" and method == "POST":
self._handle_create_chat(request_id)
elif path == "/api/v1/chats" and method == "GET":
self._handle_list_chats(query, request_id)
elif path.startswith("/api/v1/chats/") and path.endswith("/attachments") and method == "POST":
chat_id = path.rsplit("/", 2)[1]
self._handle_upload_attachment(chat_id, query, request_id)
elif path.startswith("/api/v1/attachments/") and method == "GET":
attachment_path = path.removeprefix("/api/v1/attachments/")
if attachment_path.endswith("/content"):
attachment_id = attachment_path.removesuffix("/content")
self._handle_download_attachment(attachment_id, query, request_id)
else:
self._handle_get_attachment(attachment_path, request_id)
elif path.startswith("/api/v1/chats/") and path.endswith("/messages") and method in ("GET", "POST"):
chat_id = path.rsplit("/", 2)[1]
if method == "POST":
self._handle_create_message(chat_id, request_id)
else:
self._handle_list_messages(chat_id, query, request_id)
elif path.startswith("/api/v1/chats/") and method == "GET":
self._handle_get_chat(path.rsplit("/", 1)[1], request_id)
else:
raise ApiError(404, "not_found", "Object not found")
except ApiError as exc:
self._send_error(exc.status, exc.code, exc.message, request_id, exc.headers)
except CacheUnavailableError:
self._send_error(503, "unavailable", "Session cache is unavailable", request_id)
except IdempotencyConflictError:
self._send_error(409, "conflict", "Idempotency-Key was already used with another request", request_id)
except AttachmentNotReadyError:
self._send_error(409, "conflict", "Attachment is not ready", request_id)
except ObjectMissingError:
LOGGER.error("attachment object missing for request %s", request_id)
self._send_error(503, "unavailable", "Attachment content is temporarily unavailable", request_id)
except (BotoCoreError, ClientError):
LOGGER.warning("object storage unavailable for request %s", request_id)
self._send_error(503, "unavailable", "Object storage is unavailable", request_id)
except (PoolTimeout, psycopg.OperationalError, psycopg.InterfaceError):
self._send_error(503, "unavailable", "Database is unavailable", request_id)
except psycopg.errors.UniqueViolation:
self._send_error(409, "conflict", "Username already exists", request_id)
except psycopg.errors.ForeignKeyViolation:
self._send_error(400, "invalid_request", "Unknown member", request_id)
except Exception as exc:
LOGGER.error("request %s failed with %s", request_id, type(exc).__name__)
self._send_error(500, "internal_error", "Internal server error", request_id)
finally:
if acquired:
REQUEST_GUARD.release()
def _read_json(self, request_id: str) -> Any:
if self.headers.get_content_type() != "application/json":
raise ApiError(415, "unsupported_media_type", "Content-Type must be application/json")
length = self.headers.get("Content-Length")
if length is None:
raise ApiError(400, "invalid_request", "Missing Content-Length")
try:
size = int(length)
except ValueError:
raise ApiError(400, "invalid_request", "Invalid Content-Length")
if size < 0:
raise ApiError(400, "invalid_request", "Invalid Content-Length")
if size > MAX_REQUEST_BODY_BYTES:
raise ApiError(413, "payload_too_large", "Request body too large")
raw = self.rfile.read(size)
if not raw:
raise ApiError(400, "invalid_request", "Empty body")
try:
return json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
raise ApiError(400, "invalid_request", "Malformed JSON")
def _get_actor(self, request_id: str) -> Dict[str, Any]:
header = self.headers.get("Authorization", "")
scheme, separator, token = header.partition(" ")
if scheme.lower() != "bearer" or not separator or not token or " " in token:
raise ApiError(
401,
"unauthorized",
"Authentication required",
{"WWW-Authenticate": 'Bearer realm="messenger"'},
)
user = self.store.session_user(token)
if user is None:
raise ApiError(
401,
"unauthorized",
"Authentication required",
{"WWW-Authenticate": 'Bearer realm="messenger"'},
)
return user
def _handle_register(self, request_id: str):
body = self._read_json(request_id)
if not isinstance(body, dict) or set(body) != {"username", "display_name", "password"}:
raise ApiError(400, "invalid_request", "Expected username, display_name and password")
username = body["username"]
display_name = body["display_name"]
password = body["password"]
if not isinstance(username, str) or not USER_RE.fullmatch(username):
raise ApiError(400, "invalid_request", "Invalid username")
if not isinstance(display_name, str) or not display_name.strip() or len(display_name) > 100:
raise ApiError(400, "invalid_request", "Invalid display_name")
if not isinstance(password, str) or not (12 <= len(password) <= 128):
raise ApiError(400, "invalid_request", "Invalid password")
user = self.store.create_user(username, display_name, hash_password(password))
self._send_json(201, user, request_id)
def _basic_credentials(self, request_id: str) -> Tuple[str, str]:
value = self.headers.get("Authorization", "")
scheme, separator, encoded = value.partition(" ")
challenge = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
if scheme.lower() != "basic" or not separator or not encoded:
raise ApiError(401, "unauthorized", "Invalid credentials", challenge)
try:
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
except (ValueError, UnicodeError):
raise ApiError(401, "unauthorized", "Invalid credentials", challenge)
return username, password
def _handle_create_session(self, request_id: str):
username, password = self._basic_credentials(request_id)
user = self.store.authenticate(username, password)
if user is None:
raise ApiError(
401,
"unauthorized",
"Invalid credentials",
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
)
token, expires_at = self.store.create_session(user["id"])
self._send_json(
201,
{"token": token, "token_type": "Bearer", "expires_at": isoformat(expires_at), "user": user},
request_id,
)
def _handle_revoke_session(self, request_id: str):
self._get_actor(request_id)
token = self.headers["Authorization"].partition(" ")[2]
if not self.store.revoke_session(token):
raise ApiError(
401,
"unauthorized",
"Authentication required",
{"WWW-Authenticate": 'Bearer realm="messenger"'},
)
self.send_response(204)
self.send_header("X-Request-Id", request_id)
self.send_header("X-Instance-Id", INSTANCE_ID)
self.end_headers()
def _handle_create_chat(self, request_id: str):
actor = self._get_actor(request_id)
body = self._read_json(request_id)
if not isinstance(body, dict) or set(body) != {"title", "member_ids"}:
raise ApiError(400, "invalid_request", "Expected title and member_ids")
title, member_ids = body["title"], body["member_ids"]
if not isinstance(title, str) or not title.strip() or len(title) > 100:
raise ApiError(400, "invalid_request", "Invalid title")
if (
not isinstance(member_ids, list)
or not 1 <= len(member_ids) <= 100
or any(not isinstance(item, str) or not valid_uuid(item) for item in member_ids)
or len(member_ids) != len(set(member_ids))
or actor["id"] not in member_ids
):
raise ApiError(400, "invalid_request", "Invalid member_ids")
chat = self.store.create_chat(title, member_ids, actor["id"])
self._send_json(201, chat, request_id)
def _handle_list_chats(self, query: Dict[str, List[str]], request_id: str):
actor = self._get_actor(request_id)
try:
limit = int(query.get("limit", ["50"])[0])
except ValueError:
raise ApiError(400, "invalid_request", "Invalid limit")
if not 1 <= limit <= 100:
raise ApiError(400, "invalid_request", "Invalid limit")
cursor = query.get("cursor", [None])[0]
try:
chats, next_cursor = self.store.list_chats(actor["id"], limit, cursor)
except ValueError:
raise ApiError(400, "invalid_request", "Invalid cursor")
self._send_json(200, {"items": chats, "next_cursor": next_cursor}, request_id)
def _handle_get_chat(self, chat_id: str, request_id: str):
actor = self._get_actor(request_id)
if not valid_uuid(chat_id):
raise ApiError(400, "invalid_request", "Invalid chat id")
chat = self.store.get_chat(chat_id, actor["id"])
if chat is None:
raise ApiError(404, "not_found", "Chat not found")
self._send_json(200, chat, request_id)
def _handle_create_message(self, chat_id: str, request_id: str):
actor = self._get_actor(request_id)
if not valid_uuid(chat_id):
raise ApiError(400, "invalid_request", "Invalid chat id")
chat_id = str(uuid.UUID(chat_id))
idempotency_key = self.headers.get("Idempotency-Key", "")
if not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
raise ApiError(400, "invalid_request", "Invalid or missing Idempotency-Key")
body = self._read_json(request_id)
if not isinstance(body, dict) or set(body).difference({"text", "attachment_ids"}) or "text" not in body:
raise ApiError(400, "invalid_request", "Expected text and optional attachment_ids")
text = body["text"]
attachment_ids = body.get("attachment_ids", [])
if (
not isinstance(text, str)
or len(text) > 4000
or not isinstance(attachment_ids, list)
or len(attachment_ids) > 10
or any(not isinstance(item, str) or not valid_uuid(item) for item in attachment_ids)
or len(attachment_ids) != len(set(attachment_ids))
or (not text.strip() and not attachment_ids)
):
raise ApiError(400, "invalid_request", "Invalid message text")
attachment_ids = [str(uuid.UUID(item)) for item in attachment_ids]
canonical_body = json.dumps(
{"text": text, "attachment_ids": attachment_ids},
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
message = self.store.create_idempotent_message(
chat_id,
actor["id"],
text,
attachment_ids,
idempotency_key,
canonical_body,
)
if message is None:
raise ApiError(404, "not_found", "Chat not found")
self._send_json(201, message, request_id)
def _read_image(self, request_id: str, declared_type: str) -> Tuple[BinaryIO, str, int, str]:
if declared_type not in ("image/png", "image/jpeg"):
raise ApiError(415, "unsupported_media_type", "Only PNG and JPEG are supported")
length = self.headers.get("Content-Length")
if length is None or self.headers.get("Transfer-Encoding"):
raise ApiError(400, "invalid_request", "A bounded Content-Length is required")
try:
size = int(length)
except ValueError:
raise ApiError(400, "invalid_request", "Invalid Content-Length")
if size <= 0:
raise ApiError(415, "unsupported_media_type", "Image is empty")
if size > MAX_UPLOAD_BYTES:
self.close_connection = True
remaining = min(size, MAX_UPLOAD_BYTES + 1)
deadline = time.monotonic() + UPLOAD_TIMEOUT_SECONDS
while remaining:
remaining_time = deadline - time.monotonic()
if remaining_time <= 0:
break
self.connection.settimeout(min(15, remaining_time))
try:
chunk = self.rfile.read(min(64 * 1024, remaining))
except (TimeoutError, OSError):
LOGGER.info("stopped bounded drain of oversized upload")
break
if not chunk:
break
remaining -= len(chunk)
raise ApiError(413, "payload_too_large", "Image exceeds the 10 MiB limit")
content = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b")
digest = hashlib.sha256()
bytes_read = 0
deadline = time.monotonic() + UPLOAD_TIMEOUT_SECONDS
try:
while bytes_read < size:
remaining_time = deadline - time.monotonic()
if remaining_time <= 0:
raise ApiError(408, "invalid_request", "Image upload timed out")
self.connection.settimeout(min(15, remaining_time))
chunk = self.rfile.read(min(64 * 1024, size - bytes_read))
if not chunk:
raise ApiError(400, "invalid_request", "Incomplete image body")
content.write(chunk)
digest.update(chunk)
bytes_read += len(chunk)
except (TimeoutError, OSError):
content.close()
raise ApiError(400, "invalid_request", "Incomplete image body") from None
try:
content.seek(0)
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(content) as image:
actual_type = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format or "")
if actual_type is None or actual_type != declared_type:
raise ApiError(415, "unsupported_media_type", "Image content does not match Content-Type")
width, height = image.size
if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS:
raise ApiError(413, "payload_too_large", "Image exceeds the 40 million pixel limit")
image.verify()
content.seek(0)
return content, actual_type, size, digest.hexdigest()
except ApiError:
content.close()
raise
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
content.close()
raise ApiError(413, "payload_too_large", "Image exceeds the 40 million pixel limit") from None
except (UnidentifiedImageError, OSError, SyntaxError, ValueError):
content.close()
raise ApiError(415, "unsupported_media_type", "Image is damaged or unsupported") from None
@staticmethod
def _valid_filename(filename: str) -> bool:
return (
1 <= len(filename) <= 255
and not any(char in ("/", "\\", "\x00") for char in filename)
and not any(unicodedata.category(char) == "Cc" for char in filename)
)
def _handle_upload_attachment(
self, chat_id: str, query: Dict[str, List[str]], request_id: str
):
actor = self._get_actor(request_id)
if not valid_uuid(chat_id):
raise ApiError(400, "invalid_request", "Invalid chat id")
chat_id = str(uuid.UUID(chat_id))
if not self.store.can_access_chat(chat_id, actor["id"]):
raise ApiError(404, "not_found", "Chat not found")
filenames = query.get("filename", [])
if len(filenames) != 1 or not self._valid_filename(filenames[0]):
raise ApiError(400, "invalid_request", "Invalid filename")
if not UPLOAD_GUARD.acquire(blocking=False):
raise ApiError(503, "unavailable", "Upload capacity is temporarily exhausted")
try:
content, content_type, size, digest = self._read_image(request_id, self.headers.get_content_type())
try:
attachment = self.store.create_attachment(
chat_id,
actor["id"],
filenames[0],
content_type,
content,
size,
digest,
)
finally:
content.close()
finally:
UPLOAD_GUARD.release()
if attachment is None:
raise ApiError(404, "not_found", "Chat not found")
self._send_json(201, attachment, request_id)
def _handle_get_attachment(self, attachment_id: str, request_id: str):
actor = self._get_actor(request_id)
if not valid_uuid(attachment_id):
raise ApiError(400, "invalid_request", "Invalid attachment id")
attachment = self.store.get_attachment(str(uuid.UUID(attachment_id)), actor["id"])
if attachment is None:
raise ApiError(404, "not_found", "Attachment not found")
self._send_json(200, attachment, request_id)
def _handle_download_attachment(
self, attachment_id: str, query: Dict[str, List[str]], request_id: str
):
actor = self._get_actor(request_id)
if not valid_uuid(attachment_id):
raise ApiError(400, "invalid_request", "Invalid attachment id")
if query.get("variant", ["original"]) != ["original"]:
raise ApiError(404, "not_found", "Attachment variant not found")
result = self.store.download_attachment(str(uuid.UUID(attachment_id)), actor["id"])
if result is None:
raise ApiError(404, "not_found", "Attachment not found")
content_type, content = result
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(content)))
self.send_header("X-Request-Id", request_id)
self.send_header("X-Instance-Id", INSTANCE_ID)
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Cache-Control", "private, no-store")
self.end_headers()
self.wfile.write(content)
def _handle_list_messages(self, chat_id: str, query: Dict[str, List[str]], request_id: str):
actor = self._get_actor(request_id)
if not valid_uuid(chat_id):
raise ApiError(400, "invalid_request", "Invalid chat id")
try:
limit = int(query.get("limit", ["50"])[0])
except ValueError:
raise ApiError(400, "invalid_request", "Invalid limit")
if not 1 <= limit <= 100:
raise ApiError(400, "invalid_request", "Invalid limit")
cursor = query.get("cursor", [None])[0]
try:
result = self.store.list_messages(chat_id, actor["id"], limit, cursor)
except ValueError:
raise ApiError(400, "invalid_request", "Invalid cursor")
if result is None:
raise ApiError(404, "not_found", "Chat not found")
items, next_cursor = result
self._send_json(200, {"items": items, "next_cursor": next_cursor}, request_id)
def _send_json(
self,
status: int,
payload: Dict[str, Any],
request_id: str,
headers: Optional[Dict[str, str]] = None,
):
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.send_header("X-Request-Id", request_id)
self.send_header("X-Instance-Id", INSTANCE_ID)
if headers:
for key, value in headers.items():
self.send_header(key, value)
self.end_headers()
self.wfile.write(body)
def _send_error(
self,
status: int,
code: str,
message: str,
request_id: str,
extra_headers: Optional[Dict[str, str]] = None,
):
self._send_json(
status,
{"error": {"code": code, "message": message, "request_id": request_id}},
request_id,
extra_headers,
)
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
import logging
import sys
from pathlib import Path
if __package__ in (None, ""):
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.store import Store
else:
from .store import Store
def main():
logging.basicConfig(level="INFO")
store = Store()
store.open()
try:
store.migrate()
finally:
store.close()
if __name__ == "__main__":
main()
+76
View File
@@ -0,0 +1,76 @@
import logging
from datetime import datetime
from typing import BinaryIO, Iterator, Optional, Tuple, Union
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
from .config import S3_ACCESS_KEY_ID, S3_BUCKET, S3_ENDPOINT, S3_REGION, S3_SECRET_ACCESS_KEY
from .errors import ObjectMissingError
LOGGER = logging.getLogger("messenger.s3")
class ObjectStore:
def __init__(self):
self.client = 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,
config=Config(
connect_timeout=2,
read_timeout=10,
retries={"max_attempts": 2, "mode": "standard"},
s3={"addressing_style": "path"},
),
)
def put(
self,
key: str,
content: Union[bytes, BinaryIO],
content_type: str,
size_bytes: Optional[int] = None,
) -> None:
if size_bytes is None:
size_bytes = len(content)
self.client.put_object(
Bucket=S3_BUCKET,
Key=key,
Body=content,
ContentLength=size_bytes,
ContentType=content_type,
)
def get(self, key: str, max_bytes: int) -> bytes:
try:
response = self.client.get_object(Bucket=S3_BUCKET, Key=key)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code")
if code in ("NoSuchKey", "404", "NotFound"):
raise ObjectMissingError from exc
raise
body = response["Body"]
try:
value = body.read(max_bytes + 1)
finally:
body.close()
if len(value) > max_bytes:
raise RuntimeError("Stored object exceeds configured safety limit")
return value
def delete(self, key: str) -> None:
self.client.delete_object(Bucket=S3_BUCKET, Key=key)
def ready(self) -> bool:
self.client.head_bucket(Bucket=S3_BUCKET)
return True
def objects(self) -> Iterator[Tuple[str, datetime]]:
pages = self.client.get_paginator("list_objects_v2").paginate(Bucket=S3_BUCKET)
for page in pages:
for item in page.get("Contents", []):
yield item["Key"], item["LastModified"]
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
import argparse
import hashlib
import json
import logging
import sys
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Optional
if __package__ in (None, ""):
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.store import Store
else:
from .store import Store
LOGGER = logging.getLogger("messenger.reconcile")
def reconcile(
store: Store,
grace_seconds: int,
apply_changes: bool,
restore_dir: Optional[Path] = None,
):
started = time.monotonic()
metadata = store.reconciliation_snapshot()
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace_seconds)
found = set()
orphans = []
for key, last_modified in store.objects.objects():
found.add(key)
if key not in metadata and last_modified <= cutoff:
orphans.append(key)
missing = [row for key, row in metadata.items() if key not in found]
restore_candidates = []
if restore_dir is not None:
root = restore_dir.resolve(strict=True)
for row in missing:
source = restore_dir / str(row["id"])
try:
resolved = source.resolve(strict=True)
if (
resolved.parent != root
or not resolved.is_file()
or resolved.stat().st_size != row["size_bytes"]
):
continue
content = resolved.read_bytes()
except OSError:
continue
if (
len(content) == row["size_bytes"]
and hashlib.sha256(content).hexdigest() == row["sha256"].strip()
):
restore_candidates.append((row, content))
restored = 0
if apply_changes:
for key in orphans:
store.objects.delete(key)
restorable_ids = set()
for row, content in restore_candidates:
store.objects.put(row["object_key"], content, row["content_type"])
store.clear_missing_object(row["id"])
restorable_ids.add(row["id"])
restored += 1
for row in missing:
if row["id"] not in restorable_ids:
store.record_missing_object(row["id"])
for key, row in metadata.items():
if key in found:
store.clear_missing_object(row["id"])
unresolved_missing = len(missing) - restored
return {
"mode": "apply" if apply_changes else "dry-run",
"grace_seconds": grace_seconds,
"objects_seen": len(found),
"metadata_seen": len(metadata),
"orphan_objects": len([key for key in found if key not in metadata]),
"stale_orphan_candidates": len(orphans),
"deleted_orphans": len(orphans) if apply_changes else 0,
"missing_objects": len(missing),
"unresolved_missing_objects": unresolved_missing,
"restorable_missing_objects": len(restore_candidates),
"restored_missing_objects": restored,
"missing_incidents_recorded": len(missing) - restored if apply_changes else 0,
"duration_ms": round((time.monotonic() - started) * 1000, 3),
}
def main():
parser = argparse.ArgumentParser(description="Compare S3 objects with PostgreSQL attachment metadata.")
parser.add_argument("--grace-seconds", type=int, default=3600)
parser.add_argument("--apply", action="store_true", help="delete only stale orphan objects and record missing objects")
parser.add_argument(
"--restore-dir",
type=Path,
help="optional trusted backup directory with exact original bytes named by attachment UUID",
)
args = parser.parse_args()
if args.grace_seconds < 60:
parser.error("--grace-seconds must be at least 60")
logging.basicConfig(level="INFO", format="%(levelname)s %(message)s")
store = Store()
store.open()
try:
result = reconcile(store, args.grace_seconds, args.apply, args.restore_dir)
print(json.dumps(result, sort_keys=True))
if result["unresolved_missing_objects"]:
LOGGER.error(
"%s database records reference missing S3 objects; metadata was retained for manual recovery",
result["unresolved_missing_objects"],
)
finally:
store.close()
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
import base64
import hashlib
import hmac
import secrets
import uuid
from datetime import datetime, timezone
def isoformat(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def valid_uuid(value: str) -> bool:
try:
uuid.UUID(value)
return True
except (ValueError, TypeError, AttributeError):
return False
def hash_password(password: str) -> str:
salt = secrets.token_bytes(16)
derived = hashlib.scrypt(
password.encode("utf-8"), salt=salt, n=32768, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024
)
salt_text = base64.urlsafe_b64encode(salt).decode("ascii")
hash_text = base64.urlsafe_b64encode(derived).decode("ascii")
return f"scrypt$32768$8$1${salt_text}${hash_text}"
def verify_password(password: str, stored: str) -> bool:
try:
scheme, n, r, p, salt_text, hash_text = stored.split("$")
if scheme != "scrypt":
return False
salt = base64.urlsafe_b64decode(salt_text.encode("ascii"))
expected = base64.urlsafe_b64decode(hash_text.encode("ascii"))
actual = hashlib.scrypt(
password.encode("utf-8"),
salt=salt,
n=int(n),
r=int(r),
p=int(p),
dklen=len(expected),
maxmem=64 * 1024 * 1024,
)
return hmac.compare_digest(actual, expected)
except (ValueError, TypeError, UnicodeError):
return False
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
if __package__ in (None, ""):
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.app import main
else:
from .app import main
if __name__ == "__main__":
main()
+548
View File
@@ -0,0 +1,548 @@
import base64
import hashlib
import hmac
import json
import logging
import math
import os
import secrets
import uuid
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, BinaryIO, Dict, List, Optional, Tuple
import redis
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .config import (
DB_LOCK_TIMEOUT_MS,
DB_POOL_MAX_SIZE,
DB_POOL_TIMEOUT_SECONDS,
DB_STATEMENT_TIMEOUT_MS,
IDEMPOTENCY_TTL_SECONDS,
SESSION_TTL_SECONDS,
)
from .errors import (
AttachmentNotReadyError,
CacheUnavailableError,
IdempotencyConflictError,
)
from .object_store import ObjectStore
from .security import isoformat, utc_now, valid_uuid, verify_password
LOGGER = logging.getLogger("messenger.store")
def database_url() -> str:
value = os.getenv("DATABASE_URL")
if value:
return value
file_path = os.getenv("DATABASE_URL_FILE")
if file_path:
return Path(file_path).read_text(encoding="utf-8").strip()
raise RuntimeError("Set DATABASE_URL or DATABASE_URL_FILE")
class Store:
"""PostgreSQL metadata, S3 objects, and optional Redis session cache."""
def __init__(self):
self.pool = ConnectionPool(
conninfo=database_url(),
min_size=1,
max_size=DB_POOL_MAX_SIZE,
timeout=DB_POOL_TIMEOUT_SECONDS,
kwargs={
"row_factory": dict_row,
"connect_timeout": 5,
"options": (
f"-c statement_timeout={DB_STATEMENT_TIMEOUT_MS} "
f"-c lock_timeout={DB_LOCK_TIMEOUT_MS} "
"-c idle_in_transaction_session_timeout=10000"
),
},
open=False,
)
cache_url = os.getenv("CACHE_URL")
self.cache = (
redis.Redis.from_url(
cache_url,
decode_responses=True,
socket_connect_timeout=0.25,
socket_timeout=0.25,
retry_on_timeout=False,
max_connections=16,
)
if cache_url
else None
)
self.objects = ObjectStore()
def open(self):
self.pool.open(wait=True, timeout=10)
def close(self):
if self.cache is not None:
self.cache.close()
self.pool.close()
def ready(self) -> bool:
with self.pool.connection(timeout=2) as conn:
conn.execute("SELECT 1")
self.objects.ready()
return True
def migrate(self):
migrations = Path(__file__).resolve().parents[1] / "migrations"
with self.pool.connection() as conn:
with conn.transaction():
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations "
"(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"
)
conn.execute("SELECT pg_advisory_xact_lock(2741662026)")
applied = {row["version"] for row in conn.execute("SELECT version FROM schema_migrations")}
for migration in sorted(migrations.glob("*.sql")):
if migration.name in applied:
continue
conn.execute(migration.read_text(encoding="utf-8"))
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (migration.name,))
@staticmethod
def user(row: Dict[str, Any]) -> Dict[str, Any]:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": isoformat(row["created_at"]),
}
@staticmethod
def chat(row: Dict[str, Any], member_ids: List[str]) -> Dict[str, Any]:
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": member_ids,
"created_at": isoformat(row["created_at"]),
}
@staticmethod
def message(row: Dict[str, Any], attachment_ids: Optional[List[str]] = None) -> 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": isoformat(row["created_at"]),
"attachment_ids": attachment_ids or [],
}
@staticmethod
def attachment(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"].strip(),
"status": "ready",
"variants": [],
"error_code": None,
"created_at": isoformat(row["created_at"]),
"updated_at": isoformat(row["updated_at"]),
}
def create_user(self, username: str, display_name: str, password_hash: str) -> Dict[str, Any]:
with self.pool.connection() as conn:
with conn.transaction():
row = conn.execute(
"INSERT INTO users (username, display_name, password_hash) "
"VALUES (%s, %s, %s) RETURNING id, username, display_name, created_at",
(username, display_name, password_hash),
).fetchone()
return self.user(row)
def get_user(self, user_id: str) -> Optional[Dict[str, Any]]:
with self.pool.connection() as conn:
row = conn.execute(
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
(user_id,),
).fetchone()
return self.user(row) if row else None
def authenticate(self, username: str, password: str) -> Optional[Dict[str, Any]]:
with self.pool.connection() as conn:
row = conn.execute(
"SELECT id, username, display_name, created_at, password_hash "
"FROM users WHERE username = %s",
(username,),
).fetchone()
if not row or not verify_password(password, row["password_hash"]):
return None
return self.user(row)
def create_session(self, user_id: str) -> Tuple[str, datetime]:
token = secrets.token_urlsafe(32)
expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS)
token_hash = hashlib.sha256(token.encode("ascii")).digest()
with self.pool.connection() as conn:
conn.execute(
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)",
(token_hash, user_id, expires_at),
)
return token, expires_at
@staticmethod
def _session_lock_key(token_hash: bytes) -> int:
return int.from_bytes(token_hash[:8], byteorder="big", signed=True)
def session_user(self, token: str) -> Optional[Dict[str, Any]]:
token_hash = hashlib.sha256(token.encode("utf-8")).digest()
cache_key = "messenger:session:" + token_hash.hex()
if self.cache is not None:
try:
cached = self.cache.get(cache_key)
if cached:
return json.loads(cached)
except (redis.RedisError, ValueError, TypeError):
LOGGER.warning("session cache read failed; falling back to PostgreSQL")
with self.pool.connection() as conn:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(%s)", (self._session_lock_key(token_hash),))
row = conn.execute(
"SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at "
"FROM sessions s JOIN users u ON u.id = s.user_id "
"WHERE s.token_hash = %s AND s.expires_at > now()",
(token_hash,),
).fetchone()
if not row:
return None
user = self.user(row)
if self.cache is not None:
ttl_ms = math.floor((row["expires_at"] - utc_now()).total_seconds() * 1000)
if ttl_ms > 0:
try:
self.cache.set(cache_key, json.dumps(user, separators=(",", ":")), px=ttl_ms)
except redis.RedisError:
LOGGER.warning("session cache write failed; PostgreSQL remains authoritative")
return user
def revoke_session(self, token: str) -> bool:
token_hash = hashlib.sha256(token.encode("utf-8")).digest()
with self.pool.connection() as conn:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(%s)", (self._session_lock_key(token_hash),))
if self.cache is not None:
try:
self.cache.delete("messenger:session:" + token_hash.hex())
except redis.RedisError as exc:
raise CacheUnavailableError from exc
result = conn.execute("DELETE FROM sessions WHERE token_hash = %s", (token_hash,))
return result.rowcount == 1
def create_chat(self, title: str, member_ids: List[str], actor_id: str) -> Dict[str, Any]:
if actor_id not in member_ids or len(member_ids) != len(set(member_ids)):
raise ValueError("invalid members")
with self.pool.connection() as conn:
with conn.transaction():
row = conn.execute(
"INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at",
(title,),
).fetchone()
for member_id in member_ids:
conn.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
(row["id"], member_id),
)
return self.chat(row, member_ids)
def get_chat(self, chat_id: str, user_id: str) -> Optional[Dict[str, Any]]:
with self.pool.connection() as conn:
row = 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()
if not row:
return None
members = conn.execute(
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY joined_at, user_id",
(chat_id,),
).fetchall()
return self.chat(row, [str(item["user_id"]) for item in members])
def list_chats(
self, user_id: str, limit: int, cursor: Optional[str]
) -> Tuple[List[Dict[str, Any]], Optional[str]]:
where = "own.user_id = %s"
params: List[Any] = [user_id]
if cursor is not None:
try:
raw = base64.b64decode(
cursor.encode("ascii") + b"=" * (-len(cursor) % 4),
altchars=b"-_",
validate=True,
)
cursor_user, timestamp, chat_id = raw.decode("utf-8").split("|", 2)
if cursor_user != user_id or not valid_uuid(chat_id):
raise ValueError("cursor scope")
created_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
if created_at.tzinfo is None or created_at.utcoffset() is None:
raise ValueError("cursor timestamp must include a timezone")
where += " AND (c.created_at, c.id) > (%s, %s)"
params.extend((created_at, chat_id))
except (ValueError, UnicodeError, TypeError) as exc:
raise ValueError("invalid cursor") from exc
params.append(limit + 1)
with self.pool.connection() as conn:
rows = conn.execute(
"SELECT c.id, c.title, c.created_at FROM chats c "
"JOIN chat_members own ON own.chat_id = c.id "
f"WHERE {where} ORDER BY c.created_at, c.id LIMIT %s",
params,
).fetchall()
has_more = len(rows) > limit
page = rows[:limit]
result = []
for row in page:
members = conn.execute(
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY joined_at, user_id",
(row["id"],),
).fetchall()
result.append(self.chat(row, [str(item["user_id"]) for item in members]))
next_cursor = None
if has_more and page:
last = page[-1]
cursor_data = f"{user_id}|{isoformat(last['created_at'])}|{last['id']}".encode("utf-8")
next_cursor = base64.urlsafe_b64encode(cursor_data).decode("ascii").rstrip("=")
return result, next_cursor
def create_idempotent_message(
self,
chat_id: str,
sender_id: str,
text: str,
attachment_ids: List[str],
idempotency_key: str,
canonical_body: str,
) -> Optional[Dict[str, Any]]:
request_hash = hashlib.sha256(canonical_body.encode("utf-8")).digest()
lock_material = "\0".join((sender_id, "POST", chat_id, idempotency_key)).encode("utf-8")
lock_key = int.from_bytes(hashlib.sha256(lock_material).digest()[:8], "big", signed=True)
with self.pool.connection() as conn:
with conn.transaction():
member = conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, sender_id),
).fetchone()
if not member:
return None
if attachment_ids:
attachments = conn.execute(
"SELECT id, status FROM attachments "
"WHERE chat_id = %s AND id = ANY(%s) FOR SHARE",
(chat_id, attachment_ids),
).fetchall()
if len(attachments) != len(attachment_ids):
return None
if any(item["status"] != "ready" for item in attachments):
raise AttachmentNotReadyError
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
existing = conn.execute(
"SELECT request_hash, response, expires_at "
"FROM idempotency_records "
"WHERE user_id = %s AND method = 'POST' AND chat_id = %s AND idempotency_key = %s "
"FOR UPDATE",
(sender_id, chat_id, idempotency_key),
).fetchone()
if existing and existing["expires_at"] > utc_now():
if not hmac.compare_digest(bytes(existing["request_hash"]), request_hash):
raise IdempotencyConflictError
return existing["response"]
if existing:
conn.execute(
"DELETE FROM idempotency_records "
"WHERE user_id = %s AND method = 'POST' AND chat_id = %s AND idempotency_key = %s",
(sender_id, chat_id, idempotency_key),
)
row = conn.execute(
"INSERT INTO messages (chat_id, sender_id, text) "
"VALUES (%s, %s, %s) RETURNING id, chat_id, sender_id, text, created_at",
(chat_id, sender_id, text),
).fetchone()
for ordinal, attachment_id in enumerate(attachment_ids):
conn.execute(
"INSERT INTO message_attachments (message_id, attachment_id, ordinal) "
"VALUES (%s, %s, %s)",
(row["id"], attachment_id, ordinal),
)
message = self.message(row, attachment_ids)
conn.execute(
"INSERT INTO idempotency_records "
"(user_id, method, chat_id, idempotency_key, request_hash, response, expires_at) "
"VALUES (%s, 'POST', %s, %s, %s, %s::jsonb, %s)",
(
sender_id,
chat_id,
idempotency_key,
request_hash,
json.dumps(message, ensure_ascii=False, separators=(",", ":")),
utc_now() + timedelta(seconds=IDEMPOTENCY_TTL_SECONDS),
),
)
return message
def list_messages(
self, chat_id: str, user_id: str, limit: int, cursor: Optional[str]
) -> Optional[Tuple[List[Dict[str, Any]], Optional[str]]]:
with self.pool.connection() as conn:
is_member = conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, user_id),
).fetchone()
if not is_member:
return None
where = "chat_id = %s"
params: List[Any] = [chat_id]
if cursor:
try:
raw = base64.urlsafe_b64decode(cursor.encode("ascii") + b"=" * (-len(cursor) % 4))
decoded_chat, timestamp, message_id = raw.decode("utf-8").split("|", 2)
if decoded_chat != chat_id or not valid_uuid(message_id):
raise ValueError("cursor scope")
created_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
where += " AND (created_at, id) > (%s, %s)"
params.extend((created_at, message_id))
except (ValueError, UnicodeError, TypeError) as exc:
raise ValueError("invalid cursor") from exc
params.append(limit + 1)
rows = conn.execute(
"SELECT id, chat_id, sender_id, text, created_at FROM messages "
f"WHERE {where} ORDER BY created_at, id LIMIT %s",
params,
).fetchall()
ids_by_message = {}
if rows:
links = conn.execute(
"SELECT message_id, attachment_id FROM message_attachments "
"WHERE message_id = ANY(%s) ORDER BY message_id, ordinal",
([row["id"] for row in rows],),
).fetchall()
for link in links:
ids_by_message.setdefault(link["message_id"], []).append(str(link["attachment_id"]))
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = None
if has_more and page:
last = page[-1]
cursor_data = f"{chat_id}|{isoformat(last['created_at'])}|{last['id']}".encode("utf-8")
next_cursor = base64.urlsafe_b64encode(cursor_data).decode("ascii").rstrip("=")
return [self.message(row, ids_by_message.get(row["id"], [])) for row in page], next_cursor
def can_access_chat(self, chat_id: str, user_id: str) -> bool:
with self.pool.connection() as conn:
return conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, user_id),
).fetchone() is not None
def create_attachment(
self,
chat_id: str,
owner_id: str,
filename: str,
content_type: str,
content: BinaryIO,
size_bytes: int,
digest: str,
) -> Optional[Dict[str, Any]]:
if not self.can_access_chat(chat_id, owner_id):
return None
attachment_id = uuid.uuid4()
object_key = f"original/{attachment_id}"
content.seek(0)
self.objects.put(object_key, content, content_type, size_bytes)
try:
with self.pool.connection() as conn:
with conn.transaction():
row = conn.execute(
"INSERT INTO attachments "
"(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s) "
"RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
"created_at, updated_at",
(
attachment_id,
chat_id,
owner_id,
filename,
content_type,
size_bytes,
digest,
object_key,
),
).fetchone()
return self.attachment(row)
except Exception:
try:
self.objects.delete(object_key)
except Exception as cleanup_error:
LOGGER.error(
"attachment compensation failed for %s (%s)",
attachment_id,
type(cleanup_error).__name__,
)
raise
def get_attachment(self, attachment_id: str, user_id: str) -> Optional[Dict[str, Any]]:
with self.pool.connection() as conn:
row = conn.execute(
"SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, "
"a.sha256, a.created_at, a.updated_at "
"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, user_id),
).fetchone()
return self.attachment(row) if row else None
def download_attachment(self, attachment_id: str, user_id: str) -> Optional[Tuple[str, bytes]]:
with self.pool.connection() as conn:
row = conn.execute(
"SELECT a.object_key, a.content_type, a.size_bytes "
"FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id "
"WHERE a.id = %s AND m.user_id = %s AND a.status = 'ready'",
(attachment_id, user_id),
).fetchone()
if not row:
return None
return row["content_type"], self.objects.get(row["object_key"], row["size_bytes"])
def reconciliation_snapshot(self):
with self.pool.connection() as conn:
rows = conn.execute(
"SELECT id, object_key, created_at, size_bytes, sha256, content_type FROM attachments"
).fetchall()
return {row["object_key"]: row for row in rows}
def record_missing_object(self, attachment_id: str) -> None:
with self.pool.connection() as conn:
conn.execute(
"INSERT INTO reconciliation_incidents (attachment_id, incident_type) "
"VALUES (%s, 'missing_object') ON CONFLICT (attachment_id, incident_type) "
"DO UPDATE SET last_seen_at = clock_timestamp()",
(attachment_id,),
)
def clear_missing_object(self, attachment_id: str) -> None:
with self.pool.connection() as conn:
conn.execute(
"DELETE FROM reconciliation_incidents "
"WHERE attachment_id = %s AND incident_type = 'missing_object'",
(attachment_id,),
)