Complete lab 5 asynchronous image processing
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"""Best-effort cleanup for abandoned presigned uploads."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.models import AttachmentUpload
|
||||
from app.db.session import SessionLocal
|
||||
from app.services.object_storage import client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def cleanup_expired_uploads() -> int:
|
||||
"""Delete old pending objects and mark their upload records expired.
|
||||
|
||||
A grace period protects clients completing an upload near URL expiry.
|
||||
PostgreSQL SKIP LOCKED makes this safe across multiple API replicas.
|
||||
"""
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(
|
||||
seconds=settings.attachment_cleanup_grace_seconds
|
||||
)
|
||||
deleted_count = 0
|
||||
|
||||
with SessionLocal() as db:
|
||||
uploads = db.scalars(
|
||||
select(AttachmentUpload)
|
||||
.where(
|
||||
AttachmentUpload.status == "pending",
|
||||
AttachmentUpload.expires_at <= cutoff,
|
||||
)
|
||||
.order_by(AttachmentUpload.expires_at.asc())
|
||||
.limit(settings.attachment_cleanup_batch_size)
|
||||
.with_for_update(skip_locked=True)
|
||||
).all()
|
||||
|
||||
if not uploads:
|
||||
return 0
|
||||
|
||||
s3 = client()
|
||||
try:
|
||||
for upload in uploads:
|
||||
# DeleteObject is idempotent: a missing object is also safe.
|
||||
s3.delete_object(
|
||||
Bucket=settings.s3_bucket,
|
||||
Key=upload.object_key,
|
||||
)
|
||||
upload.status = "expired"
|
||||
deleted_count += 1
|
||||
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
logger.exception(
|
||||
"Attachment cleanup batch failed; pending records will be retried"
|
||||
)
|
||||
return 0
|
||||
|
||||
if deleted_count:
|
||||
logger.info(
|
||||
"Expired abandoned attachment uploads cleaned: count=%d",
|
||||
deleted_count,
|
||||
)
|
||||
return deleted_count
|
||||
@@ -0,0 +1,159 @@
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from redis import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.exceptions import RedisError
|
||||
from redis.retry import Retry
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.models import User
|
||||
from app.repositories.session_repository import SessionRepository
|
||||
from app.repositories.user_repository import UserRepository
|
||||
from app.services.user_service import password_hasher
|
||||
|
||||
|
||||
class InvalidCredentialsError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidSessionError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
self.sessions = SessionRepository(db)
|
||||
self.users = UserRepository(db)
|
||||
|
||||
self._redis_available = True
|
||||
|
||||
self.redis = Redis.from_url(
|
||||
settings.cache_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=0.5,
|
||||
socket_timeout=0.5,
|
||||
retry_on_timeout=False,
|
||||
retry=Retry(NoBackoff(), 0),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
def create_session(self, username: str, password: str) -> dict:
|
||||
user = self.users.get_by_username(username)
|
||||
|
||||
if user is None or not password_hasher.verify(
|
||||
password, user.password_hash
|
||||
):
|
||||
raise InvalidCredentialsError("Invalid username or password")
|
||||
|
||||
token = secrets.token_urlsafe(32)
|
||||
token_hash = self._hash_token(token)
|
||||
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(
|
||||
seconds=settings.session_ttl_seconds
|
||||
)
|
||||
|
||||
try:
|
||||
self.sessions.create(
|
||||
user_id=user.id,
|
||||
token_hash=token_hash,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
self.db.commit()
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
self._cache_session(token_hash, user.id, expires_at)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at,
|
||||
"user": user,
|
||||
}
|
||||
|
||||
def _cache_session(
|
||||
self,
|
||||
token_hash: str,
|
||||
user_id,
|
||||
expires_at,
|
||||
) -> None:
|
||||
if not self._redis_available:
|
||||
return
|
||||
|
||||
ttl = max(
|
||||
1,
|
||||
int((expires_at - datetime.now(timezone.utc)).total_seconds()),
|
||||
)
|
||||
|
||||
try:
|
||||
self.redis.setex(
|
||||
f"session:{token_hash}",
|
||||
ttl,
|
||||
str(user_id),
|
||||
)
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
|
||||
def authenticate(self, token: str) -> User:
|
||||
token_hash = self._hash_token(token)
|
||||
cached_user_id = None
|
||||
|
||||
if self._redis_available:
|
||||
try:
|
||||
cached_user_id = self.redis.get(
|
||||
f"session:{token_hash}"
|
||||
)
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
|
||||
session = self.sessions.get_valid_session(token_hash)
|
||||
|
||||
if session is None:
|
||||
if self._redis_available:
|
||||
try:
|
||||
self.redis.delete(f"session:{token_hash}")
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
|
||||
raise InvalidSessionError(
|
||||
"Session is invalid or expired"
|
||||
)
|
||||
|
||||
if cached_user_id is None:
|
||||
self._cache_session(
|
||||
token_hash,
|
||||
session.user_id,
|
||||
session.expires_at,
|
||||
)
|
||||
|
||||
return session.user
|
||||
|
||||
def delete_session(self, token: str) -> None:
|
||||
token_hash = self._hash_token(token)
|
||||
|
||||
try:
|
||||
deleted = self.sessions.delete_by_token_hash(token_hash)
|
||||
|
||||
if not deleted:
|
||||
raise InvalidSessionError(
|
||||
"Session is invalid or expired"
|
||||
)
|
||||
|
||||
self.db.commit()
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
if self._redis_available:
|
||||
try:
|
||||
self.redis.delete(f"session:{token_hash}")
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
@@ -0,0 +1,94 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.models import Chat
|
||||
from app.repositories.chat_repository import ChatRepository
|
||||
from app.repositories.user_repository import UserRepository
|
||||
|
||||
|
||||
class ChatNotFoundError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ChatAccessError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidChatDataError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ChatService:
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
self.chats = ChatRepository(db)
|
||||
self.users = UserRepository(db)
|
||||
|
||||
def create_chat(
|
||||
self,
|
||||
title: str,
|
||||
member_ids: list[str],
|
||||
creator_id: uuid.UUID,
|
||||
) -> Chat:
|
||||
title = title.strip()
|
||||
|
||||
if not title or len(title) > 100:
|
||||
raise InvalidChatDataError("Invalid chat title")
|
||||
|
||||
if not member_ids or len(member_ids) > 100:
|
||||
raise InvalidChatDataError("Invalid members")
|
||||
|
||||
try:
|
||||
parsed_ids = [uuid.UUID(str(value)) for value in member_ids]
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise InvalidChatDataError("Invalid member UUID") from None
|
||||
|
||||
if len(parsed_ids) != len(set(parsed_ids)):
|
||||
raise InvalidChatDataError("Duplicate members")
|
||||
|
||||
if creator_id not in parsed_ids:
|
||||
raise InvalidChatDataError("Creator must be a member")
|
||||
|
||||
for user_id in parsed_ids:
|
||||
if self.users.get_by_id(user_id) is None:
|
||||
raise InvalidChatDataError("Unknown member")
|
||||
|
||||
try:
|
||||
chat = self.chats.create(
|
||||
title=title,
|
||||
member_ids=parsed_ids,
|
||||
)
|
||||
self.db.commit()
|
||||
self.db.refresh(chat)
|
||||
return chat
|
||||
|
||||
except IntegrityError as exc:
|
||||
self.db.rollback()
|
||||
raise InvalidChatDataError("Unable to create chat") from exc
|
||||
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
def get_chat(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> Chat:
|
||||
chat = self.chats.get_by_id(chat_id)
|
||||
|
||||
if chat is None:
|
||||
raise ChatNotFoundError()
|
||||
|
||||
if not self.chats.is_member(chat_id, user_id):
|
||||
raise ChatNotFoundError()
|
||||
|
||||
return chat
|
||||
|
||||
def list_chats(self, user_id: uuid.UUID) -> list[Chat]:
|
||||
return self.chats.get_by_user(user_id)
|
||||
|
||||
def check_membership(
|
||||
self,
|
||||
chat_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
) -> bool:
|
||||
return self.chats.is_member(chat_id, user_id)
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Deterministic image variants for the attachment pipeline."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import multiprocessing
|
||||
import time
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProcessedVariant:
|
||||
name: str
|
||||
content_type: str
|
||||
extension: str
|
||||
width: int
|
||||
height: int
|
||||
data: bytes
|
||||
sha256: str
|
||||
|
||||
|
||||
class ImageProcessingTimeout(TimeoutError):
|
||||
"""Raised when image processing exceeds its configured deadline."""
|
||||
|
||||
|
||||
def _load_oriented(data: bytes) -> Image.Image:
|
||||
if len(data) > settings.max_upload_bytes:
|
||||
raise ValueError("image_too_large")
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = settings.max_image_pixels
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
|
||||
try:
|
||||
source = Image.open(io.BytesIO(data))
|
||||
|
||||
if source.format not in {"JPEG", "PNG"}:
|
||||
raise ValueError("unsupported_image")
|
||||
|
||||
source.verify()
|
||||
source = Image.open(io.BytesIO(data))
|
||||
image = ImageOps.exif_transpose(source)
|
||||
image.load()
|
||||
|
||||
except (
|
||||
UnidentifiedImageError,
|
||||
OSError,
|
||||
Image.DecompressionBombError,
|
||||
Image.DecompressionBombWarning,
|
||||
):
|
||||
raise ValueError("invalid_image") from None
|
||||
|
||||
if image.width * image.height > settings.max_image_pixels:
|
||||
raise ValueError("image_too_many_pixels")
|
||||
|
||||
return image
|
||||
|
||||
|
||||
def _rgb_white(image: Image.Image) -> Image.Image:
|
||||
if image.mode in ("RGBA", "LA") or (
|
||||
image.mode == "P" and "transparency" in image.info
|
||||
):
|
||||
rgba = image.convert("RGBA")
|
||||
background = Image.new(
|
||||
"RGBA",
|
||||
rgba.size,
|
||||
(255, 255, 255, 255),
|
||||
)
|
||||
return Image.alpha_composite(background, rgba).convert("RGB")
|
||||
|
||||
return image.convert("RGB")
|
||||
|
||||
|
||||
def _fit(
|
||||
image: Image.Image,
|
||||
box: tuple[int, int],
|
||||
allow_upscale: bool = False,
|
||||
) -> Image.Image:
|
||||
image = image.copy()
|
||||
image.thumbnail(box, Image.Resampling.LANCZOS)
|
||||
|
||||
if allow_upscale:
|
||||
scale = min(
|
||||
box[0] / image.width,
|
||||
box[1] / image.height,
|
||||
)
|
||||
|
||||
if scale > 1:
|
||||
image = image.resize(
|
||||
(
|
||||
max(1, int(image.width * scale)),
|
||||
max(1, int(image.height * scale)),
|
||||
),
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
|
||||
return image
|
||||
|
||||
|
||||
def _encode(
|
||||
name: str,
|
||||
image: Image.Image,
|
||||
fmt: str,
|
||||
content_type: str,
|
||||
extension: str,
|
||||
**kwargs,
|
||||
) -> ProcessedVariant:
|
||||
output = io.BytesIO()
|
||||
image.save(output, format=fmt, **kwargs)
|
||||
data = output.getvalue()
|
||||
|
||||
return ProcessedVariant(
|
||||
name=name,
|
||||
content_type=content_type,
|
||||
extension=extension,
|
||||
width=image.width,
|
||||
height=image.height,
|
||||
data=data,
|
||||
sha256=hashlib.sha256(data).hexdigest(),
|
||||
)
|
||||
|
||||
|
||||
def create_variants(original: bytes) -> list[ProcessedVariant]:
|
||||
source = _load_oriented(original)
|
||||
rgb = _rgb_white(source)
|
||||
|
||||
# 256x256 fit; never upscale; dimensions retain aspect ratio.
|
||||
thumb = _fit(rgb, (256, 256))
|
||||
thumbnail = _encode(
|
||||
"thumbnail",
|
||||
thumb,
|
||||
"JPEG",
|
||||
"image/jpeg",
|
||||
"jpg",
|
||||
quality=85,
|
||||
optimize=True,
|
||||
progressive=True,
|
||||
)
|
||||
|
||||
# Center crop to square, 128x128. Upscaling is allowed by contract.
|
||||
side = min(rgb.width, rgb.height)
|
||||
left = (rgb.width - side) // 2
|
||||
top = (rgb.height - side) // 2
|
||||
crop = rgb.crop((left, top, left + side, top + side))
|
||||
crop = crop.resize((128, 128), Image.Resampling.LANCZOS)
|
||||
|
||||
cropped = _encode(
|
||||
"crop",
|
||||
crop,
|
||||
"JPEG",
|
||||
"image/jpeg",
|
||||
"jpg",
|
||||
quality=85,
|
||||
optimize=True,
|
||||
progressive=True,
|
||||
)
|
||||
|
||||
# Optimized WebP fit 1280x1280; never upscale.
|
||||
webp_image = _fit(rgb, (1280, 1280))
|
||||
webp = _encode(
|
||||
"optimized",
|
||||
webp_image,
|
||||
"WEBP",
|
||||
"image/webp",
|
||||
"webp",
|
||||
quality=82,
|
||||
method=6,
|
||||
)
|
||||
|
||||
return [thumbnail, cropped, webp]
|
||||
|
||||
|
||||
def _variant_process_entry(connection, original: bytes) -> None:
|
||||
"""Run Pillow processing in an isolated child process."""
|
||||
|
||||
try:
|
||||
result = create_variants(original)
|
||||
connection.send(("ok", result))
|
||||
|
||||
except ValueError as exc:
|
||||
connection.send(("validation_error", str(exc)[:100]))
|
||||
|
||||
except Exception:
|
||||
connection.send(("processing_error", "processing_failed"))
|
||||
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def create_variants_with_timeout(
|
||||
original: bytes,
|
||||
timeout_seconds: float,
|
||||
) -> list[ProcessedVariant]:
|
||||
"""Run image processing in a child process with a hard deadline."""
|
||||
|
||||
if timeout_seconds <= 0:
|
||||
raise ValueError("invalid_processing_timeout")
|
||||
|
||||
context = multiprocessing.get_context("spawn")
|
||||
receive_connection, send_connection = context.Pipe(duplex=False)
|
||||
|
||||
process = context.Process(
|
||||
target=_variant_process_entry,
|
||||
args=(send_connection, original),
|
||||
name="image-processor",
|
||||
)
|
||||
|
||||
try:
|
||||
process.start()
|
||||
send_connection.close()
|
||||
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
message = None
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
if receive_connection.poll(0.1):
|
||||
try:
|
||||
message = receive_connection.recv()
|
||||
except EOFError:
|
||||
message = None
|
||||
break
|
||||
|
||||
if not process.is_alive():
|
||||
if receive_connection.poll():
|
||||
try:
|
||||
message = receive_connection.recv()
|
||||
except EOFError:
|
||||
message = None
|
||||
break
|
||||
|
||||
if message is None and process.is_alive():
|
||||
process.terminate()
|
||||
process.join(timeout=2)
|
||||
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
|
||||
raise ImageProcessingTimeout(
|
||||
"image_processing_timeout"
|
||||
)
|
||||
|
||||
process.join(timeout=2)
|
||||
|
||||
if process.is_alive():
|
||||
process.terminate()
|
||||
process.join(timeout=2)
|
||||
|
||||
if message is None:
|
||||
raise RuntimeError("image_processing_failed")
|
||||
|
||||
status, payload = message
|
||||
|
||||
if status == "ok":
|
||||
return payload
|
||||
|
||||
if status == "validation_error":
|
||||
raise ValueError(payload)
|
||||
|
||||
raise RuntimeError("image_processing_failed")
|
||||
|
||||
finally:
|
||||
if process.is_alive():
|
||||
process.terminate()
|
||||
process.join(timeout=2)
|
||||
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
|
||||
receive_connection.close()
|
||||
|
||||
try:
|
||||
send_connection.close()
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,41 @@
|
||||
from io import BytesIO
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from fastapi import HTTPException
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
ALLOWED = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
||||
|
||||
|
||||
def validate_image_file(fileobj, declared_type: str):
|
||||
"""Validate a seekable, size-limited file without loading its full encoded bytes."""
|
||||
try:
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as image:
|
||||
fmt = image.format
|
||||
width, height = image.size
|
||||
if fmt not in ALLOWED:
|
||||
raise HTTPException(415, "Only PNG and JPEG are supported")
|
||||
if width * height > MAX_PIXELS:
|
||||
raise HTTPException(413, "Image exceeds 40 million pixels")
|
||||
image.verify()
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as image:
|
||||
image.load()
|
||||
except HTTPException:
|
||||
raise
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError, Image.DecompressionBombError):
|
||||
raise HTTPException(415, "Invalid or corrupted image") from None
|
||||
actual_type = ALLOWED[fmt]
|
||||
if declared_type != actual_type:
|
||||
raise HTTPException(415, "Content-Type does not match image content")
|
||||
fileobj.seek(0)
|
||||
return actual_type, width, height
|
||||
|
||||
|
||||
def validate_image(data: bytes, declared_type: str):
|
||||
if not data:
|
||||
raise HTTPException(415, "Empty image")
|
||||
if len(data) > MAX_BYTES:
|
||||
raise HTTPException(413, "Image exceeds 10 MiB")
|
||||
return validate_image_file(BytesIO(data), declared_type)
|
||||
@@ -0,0 +1,444 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from redis import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.exceptions import RedisError
|
||||
from redis.retry import Retry
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.models import Attachment, IdempotencyRecord, Message
|
||||
from app.repositories.chat_repository import ChatRepository
|
||||
from app.repositories.message_repository import MessageRepository
|
||||
|
||||
|
||||
class MessageNotFoundError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class MessageAccessError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidMessageDataError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class IdempotencyConflictError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class MessageService:
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
self.messages = MessageRepository(db)
|
||||
self.chats = ChatRepository(db)
|
||||
|
||||
self._redis_available = True
|
||||
|
||||
self.redis = Redis.from_url(
|
||||
settings.cache_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=0.5,
|
||||
socket_timeout=0.5,
|
||||
retry_on_timeout=False,
|
||||
retry=Retry(NoBackoff(), 0),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def encode_cursor(message: Message) -> str:
|
||||
payload = {
|
||||
"created_at": message.created_at.isoformat(),
|
||||
"id": str(message.id),
|
||||
}
|
||||
|
||||
raw = json.dumps(payload).encode("utf-8")
|
||||
|
||||
return (
|
||||
base64.urlsafe_b64encode(raw)
|
||||
.decode("ascii")
|
||||
.rstrip("=")
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def decode_cursor(cursor: str | None):
|
||||
if not cursor:
|
||||
return None, None
|
||||
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
raw = base64.urlsafe_b64decode(padded.encode("ascii"))
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
|
||||
created_at = datetime.fromisoformat(payload["created_at"])
|
||||
message_id = uuid.UUID(payload["id"])
|
||||
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError("Cursor timestamp must include timezone")
|
||||
|
||||
return created_at, message_id
|
||||
|
||||
except (ValueError, TypeError, KeyError, UnicodeError):
|
||||
raise InvalidMessageDataError("Invalid cursor") from None
|
||||
|
||||
def _version_key(self, chat_id: uuid.UUID) -> str:
|
||||
return f"messages:version:{chat_id}"
|
||||
|
||||
def _cache_key(
|
||||
self,
|
||||
chat_id: uuid.UUID,
|
||||
version: int,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
) -> str:
|
||||
cursor_hash = hashlib.sha256(
|
||||
(cursor or "first-page").encode("utf-8")
|
||||
).hexdigest()[:16]
|
||||
|
||||
return (
|
||||
f"messages:{chat_id}:v{version}:"
|
||||
f"limit:{limit}:cursor:{cursor_hash}"
|
||||
)
|
||||
|
||||
def _get_version(self, chat_id: uuid.UUID) -> int:
|
||||
if not self._redis_available:
|
||||
return 0
|
||||
|
||||
try:
|
||||
value = self.redis.get(self._version_key(chat_id))
|
||||
return int(value or 0)
|
||||
except (RedisError, ValueError):
|
||||
self._redis_available = False
|
||||
return 0
|
||||
|
||||
def _bump_version(self, chat_id: uuid.UUID) -> None:
|
||||
if not self._redis_available:
|
||||
return
|
||||
|
||||
try:
|
||||
self.redis.incr(self._version_key(chat_id))
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
|
||||
@staticmethod
|
||||
def _serialize(messages, next_cursor):
|
||||
return json.dumps({
|
||||
"items": [
|
||||
{
|
||||
"id": str(message.id),
|
||||
"chat_id": str(message.chat_id),
|
||||
"sender_id": str(message.sender_id),
|
||||
"text": message.text,
|
||||
"attachment_ids": message.attachment_ids or [],
|
||||
"created_at": message.created_at.isoformat(),
|
||||
}
|
||||
for message in messages
|
||||
],
|
||||
"next_cursor": next_cursor,
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
def _deserialize(payload: str):
|
||||
data = json.loads(payload)
|
||||
|
||||
messages = [
|
||||
SimpleNamespace(
|
||||
id=uuid.UUID(item["id"]),
|
||||
chat_id=uuid.UUID(item["chat_id"]),
|
||||
sender_id=uuid.UUID(item["sender_id"]),
|
||||
text=item["text"],
|
||||
attachment_ids=item.get("attachment_ids", []),
|
||||
created_at=datetime.fromisoformat(item["created_at"]),
|
||||
)
|
||||
for item in data["items"]
|
||||
]
|
||||
|
||||
return messages, data["next_cursor"]
|
||||
|
||||
def _read_cache(self, key: str):
|
||||
if not self._redis_available:
|
||||
return None
|
||||
|
||||
try:
|
||||
payload = self.redis.get(key)
|
||||
|
||||
if payload is None:
|
||||
return None
|
||||
|
||||
return self._deserialize(payload)
|
||||
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
return None
|
||||
except (ValueError, TypeError, KeyError):
|
||||
return None
|
||||
|
||||
def _load_from_database(
|
||||
self,
|
||||
chat_id,
|
||||
limit,
|
||||
cursor_created_at,
|
||||
cursor_id,
|
||||
):
|
||||
rows = self.messages.get_history(
|
||||
chat_id=chat_id,
|
||||
limit=limit + 1,
|
||||
cursor_created_at=cursor_created_at,
|
||||
cursor_id=cursor_id,
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
items = rows[:limit]
|
||||
|
||||
next_cursor = (
|
||||
self.encode_cursor(items[-1])
|
||||
if has_more and items
|
||||
else None
|
||||
)
|
||||
|
||||
return items, next_cursor
|
||||
|
||||
def create_message(
|
||||
self,
|
||||
chat_id: uuid.UUID,
|
||||
sender_id: uuid.UUID,
|
||||
text: str,
|
||||
idempotency_key: str,
|
||||
attachment_ids: list[str] | None = None,
|
||||
) -> Message:
|
||||
text = text.strip()
|
||||
attachment_ids = attachment_ids or []
|
||||
if (not text and not attachment_ids) or len(text) > 4000 or len(attachment_ids) > 10:
|
||||
raise InvalidMessageDataError("Invalid message text")
|
||||
|
||||
# Access is checked for every retry, before consulting the key.
|
||||
if not self.chats.is_member(chat_id, sender_id):
|
||||
raise MessageNotFoundError()
|
||||
|
||||
if len(attachment_ids) != len(set(attachment_ids)):
|
||||
raise InvalidMessageDataError("Duplicate attachment IDs")
|
||||
if attachment_ids:
|
||||
try:
|
||||
parsed_attachment_ids = [uuid.UUID(value) for value in attachment_ids]
|
||||
except (ValueError, TypeError):
|
||||
raise InvalidMessageDataError("Invalid attachment UUID") from None
|
||||
|
||||
attachments = list(
|
||||
self.db.scalars(
|
||||
select(Attachment).where(
|
||||
Attachment.id.in_(parsed_attachment_ids)
|
||||
)
|
||||
).all()
|
||||
)
|
||||
|
||||
if (
|
||||
len(attachments) != len(parsed_attachment_ids)
|
||||
or any(attachment.chat_id != chat_id for attachment in attachments)
|
||||
):
|
||||
raise MessageNotFoundError()
|
||||
|
||||
method = "POST"
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
request_hash = hashlib.sha256(
|
||||
json.dumps({"text": text, "attachment_ids": attachment_ids}, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
).hexdigest()
|
||||
now = datetime.now(timezone.utc)
|
||||
expires_at = now + timedelta(seconds=max(settings.idempotency_ttl_seconds, 86400))
|
||||
scope = (
|
||||
IdempotencyRecord.user_id == sender_id,
|
||||
IdempotencyRecord.method == method,
|
||||
IdempotencyRecord.path == path,
|
||||
IdempotencyRecord.idempotency_key == idempotency_key,
|
||||
)
|
||||
|
||||
try:
|
||||
# An expired key may be reused. Deletion and claim are serialized by
|
||||
# PostgreSQL's unique constraint for the scope.
|
||||
self.db.execute(
|
||||
delete(IdempotencyRecord).where(*scope, IdempotencyRecord.expires_at <= now)
|
||||
)
|
||||
claim = (
|
||||
pg_insert(IdempotencyRecord)
|
||||
.values(
|
||||
id=uuid.uuid4(), user_id=sender_id, method=method, path=path,
|
||||
idempotency_key=idempotency_key, request_hash=request_hash,
|
||||
message_id=None, created_at=now, expires_at=expires_at,
|
||||
)
|
||||
.on_conflict_do_nothing(constraint="uq_idempotency_scope_key")
|
||||
.returning(IdempotencyRecord.id)
|
||||
)
|
||||
claimed_id = self.db.execute(claim).scalar_one_or_none()
|
||||
|
||||
if claimed_id is None:
|
||||
existing = self.db.execute(
|
||||
select(IdempotencyRecord).where(*scope).with_for_update()
|
||||
).scalar_one_or_none()
|
||||
if existing is None:
|
||||
# Rare expiration race: retry once in a fresh transaction.
|
||||
self.db.rollback()
|
||||
return self.create_message(chat_id, sender_id, text, idempotency_key, attachment_ids)
|
||||
if existing.request_hash != request_hash:
|
||||
self.db.rollback()
|
||||
raise IdempotencyConflictError()
|
||||
if existing.message_id is None:
|
||||
raise RuntimeError("Committed idempotency record has no message")
|
||||
message = self.db.get(Message, existing.message_id)
|
||||
if message is None:
|
||||
raise RuntimeError("Idempotency record references a missing message")
|
||||
self.db.commit()
|
||||
return message
|
||||
|
||||
message = self.messages.create(
|
||||
chat_id=chat_id, sender_id=sender_id, text=text, attachment_ids=attachment_ids
|
||||
)
|
||||
self.db.execute(
|
||||
update(IdempotencyRecord)
|
||||
.where(IdempotencyRecord.id == claimed_id)
|
||||
.values(message_id=message.id)
|
||||
)
|
||||
self.db.commit()
|
||||
self.db.refresh(message)
|
||||
self._bump_version(chat_id)
|
||||
return message
|
||||
except IdempotencyConflictError:
|
||||
raise
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
def get_history(
|
||||
self,
|
||||
chat_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
):
|
||||
if not 1 <= limit <= 100:
|
||||
raise InvalidMessageDataError(
|
||||
"Limit must be between 1 and 100"
|
||||
)
|
||||
|
||||
if not self.chats.is_member(chat_id, user_id):
|
||||
raise MessageNotFoundError()
|
||||
|
||||
cursor_created_at, cursor_id = self.decode_cursor(cursor)
|
||||
|
||||
version = self._get_version(chat_id)
|
||||
|
||||
cache_key = self._cache_key(
|
||||
chat_id,
|
||||
version,
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
|
||||
cached = self._read_cache(cache_key)
|
||||
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
if not self._redis_available:
|
||||
return self._load_from_database(
|
||||
chat_id,
|
||||
limit,
|
||||
cursor_created_at,
|
||||
cursor_id,
|
||||
)
|
||||
|
||||
lock_key = f"lock:{cache_key}"
|
||||
lock_token = str(uuid.uuid4())
|
||||
|
||||
try:
|
||||
acquired = self.redis.set(
|
||||
lock_key,
|
||||
lock_token,
|
||||
nx=True,
|
||||
ex=10,
|
||||
)
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
return self._load_from_database(
|
||||
chat_id,
|
||||
limit,
|
||||
cursor_created_at,
|
||||
cursor_id,
|
||||
)
|
||||
|
||||
if not acquired:
|
||||
for _ in range(10):
|
||||
time.sleep(0.05)
|
||||
|
||||
cached = self._read_cache(cache_key)
|
||||
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
if not self._redis_available:
|
||||
break
|
||||
|
||||
return self._load_from_database(
|
||||
chat_id,
|
||||
limit,
|
||||
cursor_created_at,
|
||||
cursor_id,
|
||||
)
|
||||
|
||||
try:
|
||||
cached = self._read_cache(cache_key)
|
||||
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
if not self._redis_available:
|
||||
return self._load_from_database(
|
||||
chat_id,
|
||||
limit,
|
||||
cursor_created_at,
|
||||
cursor_id,
|
||||
)
|
||||
|
||||
items, next_cursor = self._load_from_database(
|
||||
chat_id,
|
||||
limit,
|
||||
cursor_created_at,
|
||||
cursor_id,
|
||||
)
|
||||
|
||||
if self._redis_available and self._get_version(chat_id) == version:
|
||||
try:
|
||||
self.redis.setex(
|
||||
cache_key,
|
||||
settings.message_cache_ttl_seconds,
|
||||
self._serialize(items, next_cursor),
|
||||
)
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
|
||||
return items, next_cursor
|
||||
|
||||
finally:
|
||||
if self._redis_available:
|
||||
try:
|
||||
self.redis.eval(
|
||||
"""
|
||||
if redis.call('get', KEYS[1]) == ARGV[1]
|
||||
then
|
||||
return redis.call('del', KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
""",
|
||||
1,
|
||||
lock_key,
|
||||
lock_token,
|
||||
)
|
||||
except RedisError:
|
||||
self._redis_available = False
|
||||
@@ -0,0 +1,39 @@
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
def client(endpoint_url=None):
|
||||
return boto3.client(
|
||||
"s3", endpoint_url=endpoint_url or settings.s3_endpoint_url,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
region_name=settings.s3_region,
|
||||
config=Config(signature_version="s3v4", connect_timeout=3, read_timeout=15, retries={"max_attempts": 2}, s3={"addressing_style": "path"}),
|
||||
)
|
||||
|
||||
|
||||
def ensure_bucket() -> None:
|
||||
s3 = client()
|
||||
try:
|
||||
s3.head_bucket(Bucket=settings.s3_bucket)
|
||||
except Exception:
|
||||
s3.create_bucket(Bucket=settings.s3_bucket)
|
||||
|
||||
|
||||
def presigned_client():
|
||||
return client(endpoint_url=settings.s3_public_endpoint_url)
|
||||
|
||||
|
||||
def create_presigned_upload_url(object_key: str, content_type: str) -> str:
|
||||
s3 = presigned_client()
|
||||
|
||||
return s3.generate_presigned_url(
|
||||
ClientMethod="put_object",
|
||||
Params={
|
||||
"Bucket": settings.s3_bucket,
|
||||
"Key": object_key,
|
||||
"ContentType": content_type,
|
||||
},
|
||||
ExpiresIn=settings.presigned_upload_ttl_seconds,
|
||||
)
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Publish durable PostgreSQL outbox events to RabbitMQ.
|
||||
|
||||
The database row is marked published only after RabbitMQ publisher confirmation.
|
||||
If the process crashes after broker confirmation but before the DB commit, the
|
||||
same event is published again; consumers must therefore be idempotent.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import aio_pika
|
||||
from aio_pika import DeliveryMode, Message
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.models import OutboxEvent
|
||||
from app.db.session import SessionLocal
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
async def publish_once() -> int:
|
||||
"""Publish one batch; return number of confirmed events."""
|
||||
connection = await aio_pika.connect_robust(settings.rabbitmq_url)
|
||||
try:
|
||||
channel = await connection.channel(publisher_confirms=True)
|
||||
exchange = await channel.declare_exchange(
|
||||
settings.rabbitmq_exchange,
|
||||
aio_pika.ExchangeType.DIRECT,
|
||||
durable=True,
|
||||
)
|
||||
queue = await channel.declare_queue(settings.rabbitmq_queue, durable=True)
|
||||
await queue.bind(exchange, routing_key=settings.rabbitmq_queue)
|
||||
|
||||
published = 0
|
||||
db: Session = SessionLocal()
|
||||
try:
|
||||
# Lock a bounded batch. SKIP LOCKED allows multiple publisher replicas.
|
||||
events = db.scalars(
|
||||
select(OutboxEvent)
|
||||
.where(OutboxEvent.status == "pending")
|
||||
.order_by(OutboxEvent.created_at)
|
||||
.with_for_update(skip_locked=True)
|
||||
.limit(settings.outbox_batch_size)
|
||||
).all()
|
||||
|
||||
for event in events:
|
||||
body = json.dumps(event.payload, separators=(",", ":")).encode("utf-8")
|
||||
message = Message(
|
||||
body=body,
|
||||
content_type="application/json",
|
||||
delivery_mode=DeliveryMode.PERSISTENT,
|
||||
message_id=str(event.id),
|
||||
type=event.event_type,
|
||||
timestamp=utc_now(),
|
||||
)
|
||||
await exchange.publish(message, routing_key=settings.rabbitmq_queue, mandatory=True)
|
||||
event.status = "published"
|
||||
event.published_at = utc_now()
|
||||
event.attempts += 1
|
||||
published += 1
|
||||
|
||||
db.commit()
|
||||
return published
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def run_publisher() -> None:
|
||||
delay = settings.outbox_poll_interval_seconds
|
||||
while True:
|
||||
try:
|
||||
count = await publish_once()
|
||||
if count:
|
||||
logger.info("Published %s outbox events", count)
|
||||
delay = settings.outbox_poll_interval_seconds
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception("Outbox publisher iteration failed")
|
||||
delay = min(max(delay * 2, settings.outbox_poll_interval_seconds), 15.0)
|
||||
delay += random.uniform(0, delay * 0.2)
|
||||
await asyncio.sleep(delay)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
asyncio.run(run_publisher())
|
||||
@@ -0,0 +1,81 @@
|
||||
import re
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
from pwdlib import PasswordHash
|
||||
|
||||
from app.db.models import User
|
||||
from app.repositories.user_repository import UserRepository
|
||||
|
||||
|
||||
password_hasher = PasswordHash.recommended()
|
||||
|
||||
|
||||
class UsernameAlreadyExistsError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UserService:
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
self.users = UserRepository(db)
|
||||
|
||||
def register(
|
||||
self,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password: str,
|
||||
) -> User:
|
||||
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
||||
raise ValueError("Invalid username")
|
||||
|
||||
if not display_name or not display_name.strip():
|
||||
raise ValueError("Display name cannot be empty")
|
||||
|
||||
if len(display_name) > 100:
|
||||
raise ValueError("Display name is too long")
|
||||
|
||||
if not 12 <= len(password) <= 128:
|
||||
raise ValueError("Invalid password length")
|
||||
|
||||
if self.users.get_by_username(username) is not None:
|
||||
raise UsernameAlreadyExistsError(
|
||||
"Username already exists"
|
||||
)
|
||||
|
||||
password_hash = password_hasher.hash(password)
|
||||
|
||||
try:
|
||||
user = self.users.create(
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
password_hash=password_hash,
|
||||
)
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(user)
|
||||
|
||||
return user
|
||||
|
||||
except IntegrityError as exc:
|
||||
self.db.rollback()
|
||||
|
||||
raise UsernameAlreadyExistsError(
|
||||
"Username already exists"
|
||||
) from exc
|
||||
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
def verify_password(
|
||||
self,
|
||||
user: User,
|
||||
password: str,
|
||||
) -> bool:
|
||||
return password_hasher.verify(
|
||||
password,
|
||||
user.password_hash,
|
||||
)
|
||||
Reference in New Issue
Block a user