Files
mcma-backend/app/infrastructure/db/models/like.py
T
Цвылев Александр Вадимович 048854f92a feat(api): offline-first sync layer
Implements the stubbed /sync endpoints:
- GET /sync/changes — delta pull (likes, plays, changed playlists with
  their track ids, changed catalogue tracks) over the half-open window
  (since, cursor]; the cursor is the DB clock, so it's immune to app/DB
  skew.
- POST /sync/push — idempotent append of client like/play events
  (ON CONFLICT DO NOTHING by client-supplied id); events for tracks the
  server doesn't have are skipped (graceful degradation).

Adds a server-ingestion column `synced_at` to the likes + play_history
event logs (migration) as the delta ordering key, so an event pushed
with an older event time still surfaces for other devices. Repos gain
list_since/add_event (likes, history), list_changed_since (playlists,
tracks) and playlist.track_ids; wired via SyncService in deps.

Also fixes test isolation exposed by the registry-backed /admin/sources
endpoint: test_sources_api clears the process-cached source registry,
and test_admin_api no longer hardcodes the environment name.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-28 15:04:13 +03:00

49 lines
1.7 KiB
Python

"""ORM model for likes — an append-only event log.
A like/dislike is **never** updated in place. Current state for a ``(user,
track)`` pair is the latest event by ``created_at``. This shape is required for
future sync and as a clean ML signal (plan §4.1). Hence: no ``updated_at``,
no unique constraint on ``(user, track)``.
"""
import datetime as dt
import uuid
from sqlalchemy import DateTime, ForeignKey, Index, String, func
from sqlalchemy.orm import Mapped, mapped_column
from app.infrastructure.db.base import Base
from app.infrastructure.db.models.mixins import UUIDPrimaryKeyMixin
class LikeModel(UUIDPrimaryKeyMixin, Base):
__tablename__ = "likes"
__table_args__ = (
# Latest-event lookups query by (user, track) ordered by time.
Index("ix_likes_user_id_track_id", "user_id", "track_id"),
)
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
)
track_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("tracks.id", ondelete="CASCADE"),
nullable=False,
)
value: Mapped[str] = mapped_column(String(16), nullable=False)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True),
server_default=func.now(),
nullable=False,
)
# Server ingestion time — the delta-sync ordering key. Set once at insert and
# never changed; distinct from ``created_at`` (the real event time, which a
# sync push preserves from the client even when it happened offline earlier).
synced_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True),
server_default=func.now(),
nullable=False,
index=True,
)