"""Small repository layer; each operation owns and closes its DB transaction.""" import base64 import json import uuid from datetime import datetime, timezone, timedelta import math from sqlalchemy import and_, or_, select, update from sqlalchemy.dialects.postgresql import insert from sqlalchemy.orm import selectinload from sqlalchemy.exc import IntegrityError from .database import User, Session as SessionRow, Chat, ChatMember, Message, MessageIdempotency, Attachment, SessionLocal from .auth import hash_password, verify_password, new_token, SESSION_TTL_SECONDS from . import session_cache class Store: def add_user(self, username, display_name, password): with SessionLocal() as db: user = User(username=username, display_name=display_name, password_hash=hash_password(password)) db.add(user) try: db.commit() except IntegrityError: db.rollback() raise ValueError("USERNAME_EXISTS") db.refresh(user) return user def get_user_by_id(self, user_id): with SessionLocal() as db: return db.query(User).filter(User.id == user_id).first() def verify_user_password(self, username, password): with SessionLocal() as db: user = db.query(User).filter(User.username == username).first() # A fixed dummy hash is avoided here; the public contract only requires # identical response status and challenge for unknown users/bad passwords. if not user or not verify_password(password, user.password_hash): return None return user def create_session(self, user_id): with SessionLocal() as db: row = SessionRow(token=new_token(), user_id=user_id, expires_at=datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)) db.add(row) db.commit() db.refresh(row) try: session_cache.put(row.token, row.user_id, SESSION_TTL_SECONDS) except session_cache.CacheUnavailable: db.delete(row) db.commit() raise return row def get_session_by_token(self, token): cached_user_id = session_cache.get(token) if cached_user_id: return (cached_user_id, None) with SessionLocal() as db: row = db.query(SessionRow).filter(SessionRow.token == token, SessionRow.expires_at > datetime.now(timezone.utc)).first() if not row: return None remaining = math.ceil((row.expires_at - datetime.now(timezone.utc)).total_seconds()) session_cache.put(row.token, row.user_id, remaining) return (row.user_id, row.expires_at) def delete_session(self, token): # Require successful cache invalidation before reporting a completed logout. session_cache.delete(token) with SessionLocal() as db: row = db.query(SessionRow).filter(SessionRow.token == token).first() if row: db.delete(row) db.commit() return True return False def create_chat(self, title, member_ids, creator_id): if creator_id not in member_ids: raise ValueError("CREATOR_NOT_MEMBER") if len(member_ids) != len(set(member_ids)): raise ValueError("DUPLICATE_MEMBER") with SessionLocal() as db: users = db.query(User.id).filter(User.id.in_(member_ids)).all() if len(users) != len(member_ids): raise ValueError("USER_NOT_FOUND") chat = Chat(title=title) chat.members = [ChatMember(user_id=mid) for mid in member_ids] db.add(chat) db.commit() db.refresh(chat) list(chat.members) return chat def get_chat(self, chat_id): with SessionLocal() as db: return db.query(Chat).options(selectinload(Chat.members)).filter(Chat.id == chat_id).first() def get_user_chats(self, user_id, cursor=None, limit=50): with SessionLocal() as db: query = db.query(Chat).options(selectinload(Chat.members)).join(ChatMember).filter(ChatMember.user_id == user_id) if cursor: decoded = decode_cursor(cursor, "chats") query = query.filter(or_(Chat.created_at > decoded[0], and_(Chat.created_at == decoded[0], Chat.id > decoded[1]))) rows = query.order_by(Chat.created_at, Chat.id).limit(limit).all() for row in rows: list(row.members) return rows def is_chat_member(self, chat_id, user_id): with SessionLocal() as db: return db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id).first() is not None def add_message(self, chat_id, sender_id, text): with SessionLocal() as db: if not db.query(Chat.id).filter(Chat.id == chat_id).first(): raise ValueError("CHAT_NOT_FOUND") if not db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == sender_id).first(): raise ValueError("NOT_MEMBER") msg = Message(chat_id=chat_id, sender_id=sender_id, text=text) db.add(msg) db.commit() db.refresh(msg) return msg def add_message_idempotent(self, chat_id, sender_id, text, attachment_ids, key, request_hash): """Claim a scoped key and create its message in the same DB transaction.""" with SessionLocal() as db: if not db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == sender_id).first(): raise ValueError("CHAT_NOT_FOUND") if not text.strip() and not attachment_ids: raise ValueError("EMPTY_MESSAGE") if attachment_ids: rows = db.query(Attachment).filter(Attachment.id.in_(attachment_ids), Attachment.chat_id == chat_id).all() if len(rows) != len(attachment_ids): raise ValueError("ATTACHMENT_NOT_FOUND") scope = dict(user_id=sender_id, method="POST", chat_path=f"/api/v1/chats/{chat_id}/messages", key=key) claim = insert(MessageIdempotency).values(**scope, request_hash=request_hash, message_id=None).on_conflict_do_nothing( constraint="uq_idempotency_scope").returning(MessageIdempotency.id) claimed = db.execute(claim).scalar_one_or_none() if claimed is None: record = db.execute(select(MessageIdempotency).filter_by(**scope)).scalar_one() if record.request_hash != request_hash: raise ValueError("IDEMPOTENCY_CONFLICT") msg = db.get(Message, record.message_id) if msg is None: raise RuntimeError("Idempotency record has no message") return msg msg = Message(chat_id=chat_id, sender_id=sender_id, text=text, attachment_ids=attachment_ids) db.add(msg) db.flush() db.execute(update(MessageIdempotency).where(MessageIdempotency.id == claimed).values(message_id=msg.id)) db.commit() db.refresh(msg) return msg def get_messages(self, chat_id, cursor=None, limit=50): with SessionLocal() as db: query = db.query(Message).filter(Message.chat_id == chat_id) if cursor: created, message_id = decode_cursor(cursor, chat_id) query = query.filter(or_(Message.created_at > created, and_(Message.created_at == created, Message.id > message_id))) return query.order_by(Message.created_at, Message.id).limit(limit).all() def save_attachment(self, attachment): with SessionLocal() as db: row = Attachment(**attachment) db.add(row) db.commit() db.refresh(row) return row def get_attachment(self, attachment_id, user_id): with SessionLocal() as db: return db.query(Attachment).join(ChatMember, ChatMember.chat_id == Attachment.chat_id).filter( Attachment.id == attachment_id, ChatMember.user_id == user_id).first() def encode_cursor(resource, created_at, item_id): raw = json.dumps([resource, created_at.isoformat(), item_id], separators=(",", ":")).encode() return base64.urlsafe_b64encode(raw).decode().rstrip("=") def decode_cursor(cursor, resource): try: data = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))) if data[0] != resource: raise ValueError return datetime.fromisoformat(data[1]), data[2] except Exception: raise ValueError("INVALID_CURSOR") def cursor_for_chat(chat): return encode_cursor("chats", chat.created_at, chat.id) def cursor_for_message(message): return encode_cursor(message.chat_id, message.created_at, message.id) store = Store()