import uuid from datetime import datetime from sqlalchemy import CheckConstraint, DateTime, ForeignKey, ForeignKeyConstraint, Index, Integer, String, Text, UniqueConstraint, func from sqlalchemy.dialects.postgresql import JSONB, UUID from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column class Base(DeclarativeBase): pass class User(Base): __tablename__ = "users" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) username: Mapped[str] = mapped_column(String(32), nullable=False, unique=True) display_name: Mapped[str] = mapped_column(String(100), nullable=False) password_hash: Mapped[str] = mapped_column(Text, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) class Chat(Base): __tablename__ = "chats" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) title: Mapped[str] = mapped_column(String(100), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) class ChatMember(Base): __tablename__ = "chat_members" __table_args__ = ( Index("chat_members_user_id_idx", "user_id", "chat_id"), ) chat_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True ) user_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("users.id", ondelete="RESTRICT"), primary_key=True ) class Message(Base): __tablename__ = "messages" __table_args__ = ( ForeignKeyConstraint( ["chat_id", "sender_id"], ["chat_members.chat_id", "chat_members.user_id"], name="messages_sender_is_chat_member_fk", ondelete="CASCADE", ), UniqueConstraint("id", "chat_id", name="messages_id_chat_id_uq"), Index("messages_history_idx", "chat_id", "created_at", "id"), ) id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) sender_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) text: Mapped[str] = mapped_column(String(4000), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) class IdempotencyRecord(Base): """Shared, transactional result cache for retried message POST requests.""" __tablename__ = "idempotency_records" __table_args__ = ( UniqueConstraint( "user_id", "method", "path", "idempotency_key", name="idempotency_records_scope_key_uq", ), Index("idempotency_records_expires_at_idx", "expires_at"), ) id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) user_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False ) method: Mapped[str] = mapped_column(String(8), nullable=False) path: Mapped[str] = mapped_column(String(200), nullable=False) idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False) request_hash: Mapped[str] = mapped_column(String(64), nullable=False) response_body: Mapped[dict] = mapped_column(JSONB, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) class Attachment(Base): __tablename__ = "attachments" __table_args__ = ( ForeignKeyConstraint( ["chat_id", "owner_id"], ["chat_members.chat_id", "chat_members.user_id"], name="attachments_owner_is_chat_member_fk", ondelete="CASCADE", ), UniqueConstraint("id", "chat_id", name="attachments_id_chat_id_uq"), CheckConstraint("char_length(filename) BETWEEN 1 AND 255", name="attachments_filename_length_ck"), CheckConstraint("content_type IN ('image/png', 'image/jpeg')", name="attachments_content_type_ck"), CheckConstraint("size_bytes BETWEEN 1 AND 10485760", name="attachments_size_bytes_ck"), CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="attachments_sha256_ck"), CheckConstraint("status IN ('queued', 'processing', 'ready', 'failed')", name="attachments_status_ck"), Index("attachments_chat_created_idx", "chat_id", "created_at", "id"), ) id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) filename: Mapped[str] = mapped_column(String(255), nullable=False) content_type: Mapped[str] = mapped_column(String(32), nullable=False) size_bytes: Mapped[int] = mapped_column(Integer, nullable=False) sha256: Mapped[str] = mapped_column(String(64), nullable=False) status: Mapped[str] = mapped_column(String(16), nullable=False, default="ready") variants: Mapped[list] = mapped_column(JSONB, nullable=False, default=list, server_default="[]") error_code: Mapped[str | None] = mapped_column(String(64), nullable=True) object_key: Mapped[str] = mapped_column(Text, nullable=False, unique=True) staging_key: Mapped[str | None] = mapped_column(Text, nullable=True, unique=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()) class AttachmentJob(Base): """One logical image pipeline; broker deliveries are only wake-up signals.""" __tablename__ = "attachment_jobs" __table_args__ = ( UniqueConstraint("attachment_id", name="attachment_jobs_attachment_uq"), CheckConstraint("attempt >= 1", name="attachment_jobs_attempt_ck"), CheckConstraint("max_attempts BETWEEN 1 AND 20", name="attachment_jobs_max_attempts_ck"), CheckConstraint("attempts_in_cycle BETWEEN 1 AND max_attempts", name="attachment_jobs_cycle_attempt_ck"), CheckConstraint("status IN ('queued', 'processing', 'succeeded', 'failed')", name="attachment_jobs_status_ck"), Index("attachment_jobs_due_idx", "status", "available_at"), Index("attachment_jobs_lease_idx", "status", "lease_until"), ) id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) attachment_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("attachments.id", ondelete="CASCADE"), nullable=False ) pipeline_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1) attempt: Mapped[int] = mapped_column(Integer, nullable=False, default=1) attempts_in_cycle: Mapped[int] = mapped_column(Integer, nullable=False, default=1) max_attempts: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(16), nullable=False, default="queued") available_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) last_error_code: Mapped[str | None] = mapped_column(String(64), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()) completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) class JobOutbox(Base): """Transactional intent to publish a logical job attempt to Redis Streams.""" __tablename__ = "job_outbox" __table_args__ = ( UniqueConstraint("job_id", "attempt", name="job_outbox_job_attempt_uq"), Index("job_outbox_pending_idx", "published_at", "created_at"), ) id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) job_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("attachment_jobs.id", ondelete="CASCADE"), nullable=False ) attempt: Mapped[int] = mapped_column(Integer, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) class JobReplayAudit(Base): """Operator initiated replay history; replay never creates a second job.""" __tablename__ = "job_replay_audit" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) job_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("attachment_jobs.id", ondelete="CASCADE"), nullable=False ) previous_attempt: Mapped[int] = mapped_column(Integer, nullable=False) new_attempt: Mapped[int] = mapped_column(Integer, nullable=False) operator: Mapped[str] = mapped_column(String(100), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) class MessageAttachment(Base): __tablename__ = "message_attachments" __table_args__ = ( ForeignKeyConstraint( ["message_id", "chat_id"], ["messages.id", "messages.chat_id"], name="message_attachments_message_chat_fk", ondelete="CASCADE", ), ForeignKeyConstraint( ["attachment_id", "chat_id"], ["attachments.id", "attachments.chat_id"], name="message_attachments_attachment_chat_fk", ondelete="CASCADE", ), UniqueConstraint("message_id", "position", name="message_attachments_position_uq"), Index("message_attachments_attachment_idx", "attachment_id"), ) message_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) attachment_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) position: Mapped[int] = mapped_column(Integer, nullable=False)