Управление треками и поиск
Relevant source files
The following files were used as context for generating this wiki page:
The "Управление треками и поиск" (Track Management and Search) module is a core component of the music service responsible for managing the music catalog, handling track playback logic, and providing search capabilities. It encompasses administrative functions for creating and updating tracks, as well as user-facing features such as browsing the catalog and searching for specific content.
The system is built using a layered architecture, separating concerns between the HTTP transport layer, the business logic (service) layer, and the data persistence layer (PostgreSQL and Redis). It also implements subscription-based access control, specifically enforcing daily listening limits for users with "FREE" accounts.
Архитектура и структура данных
Модель данных (Entity Relationship)
The track entity is central to the database schema, maintaining relationships with artists, albums, and genres.
Visual representation of the track entity and its database relationships. Sources: migrations/001_init.up.sql:43-53
Основные поля трека
| Field | Type | Description |
|---|---|---|
id | int64 | Unique identifier (Primary Key) |
title | string | The title of the track |
artist_id | int64 | Foreign key to the artists table |
album_id | int64 | Foreign key to the albums table (nullable) |
genre_id | int64 | Foreign key to the genres table (nullable) |
duration_seconds | int | Length of the track in seconds |
file_url | string | URL to the audio file |
is_active | bool | Status flag for soft deletion/visibility |
Sources: internal/features/tracks/transport/http/transport.go:27-35, migrations/001_init.up.sql:43-53
Бизнес-логика прослушивания (Playback)
The system manages track playback through the Play method in the service layer. This method implements a critical business rule: users with a FREE subscription are limited to a specific number of plays per day.
Процесс прослушивания
- Validation: The system checks if the track exists and is marked as
is_active. - Limit Check: For
FREEusers, it queries Redis using a key formatted asuser:{id}:daily_play_count:{date}. - Incrementing: if the limit is not exceeded, the count in Redis is incremented using a transaction (atomic pipeline) with a 24-hour expiration.
- Persistence: The event is recorded in the
listening_historytable in PostgreSQL.
Sequence of operations during track playback validation and execution. Sources: internal/features/tracks/service/play.go:21-82
Поиск и листинг (Search and Discovery)
Поиск треков
The search functionality uses the ILIKE operator in PostgreSQL to perform case-insensitive pattern matching across multiple fields: track title, artist name, album title, and genre name.
- Endpoint:
GET /api/v1/tracks/search?query=... - Logic: Returns tracks where the query string matches any of the catalog details.
Sources: internal/features/tracks/repository/postgres/track_repository.go:124-144, internal/features/tracks/transport/http/search_tracks.go:31-48
Пагинация списка
The general list of tracks supports pagination through limit and page query parameters. By default, it returns 20 tracks per page.
| Parameter | Type | Default | Description |
|---|---|---|---|
limit | int | 20 | Number of tracks per request |
page | int | 1 | Current page number |
Sources: internal/features/tracks/transport/http/list_tracks.go:34-54
Административное управление
The module provides restricted endpoints for managing the music catalog, requiring the ADMIN role.
API Эндпоинты управления
| Method | Path | Description |
|---|---|---|
POST | /admin/tracks | Create a new music track |
PUT | /admin/tracks/{id} | Update existing track details |
DELETE | /admin/tracks/{id} | Soft delete a track (sets is_active = false) |
Sources: internal/features/tracks/transport/http/transport.go:70-86
Реализация Soft Delete
Instead of removing records from the database, the system uses a SoftDelete method. This updates the is_active flag to FALSE, ensuring that historical data (like listening_history) remains valid while the track becomes unavailable for search or playback.
func (r *TrackRepository) SoftDelete(ctx context.Context, id int64) error {
query := `UPDATE tracks SET is_active = FALSE WHERE id = $1`
res, err := r.db.ExecContext(ctx, query, id)
// ... validation logic
return nil
}
Sources: internal/features/tracks/repository/postgres/track_repository.go:66-72
Заключение
Система управления треками обеспечивает гибкий механизм работы с музыкальным каталогом, совмещая в себе функции поиска, администрирования и строгого контроля доступа. Использование Redis для отслеживания дневных лимитов позволяет эффективно масштабировать бизнес-ограничения для бесплатных аккаунтов, не создавая избыточной нагрузки на основную базу данных PostgreSQL.