refactor: isolate playback and upload use cases
ci / module boundaries / boundaries (push) Successful in 6s
ci / api / api (push) Successful in 47s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m2s
ci / db / db (push) Successful in 1m4s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m30s
ci / ts / ts (packages + web) (push) Successful in 2m54s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m14s

This commit is contained in:
mrleo1nid committed 2026-10-22 13:52:16 +03:00
1 parent c84f90e2cc
commit e158558da3
56 files changed
+3337 -2196

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
# Go API
- Сборка зависимостей: `cmd/api/main.go`; маршрутизация: `internal/server/router.go`. Конкретные адаптеры здесь допустимы.
- HTTP-типы: `internal/api/gen`; исходный контракт: корневой `api/openapi.yaml`. Генерация: `go generate ./...`.
- Области: `auth`, `library`, `uploads`, `playback`, `wave`, `search`, `genius`. Начинай с handler → операция → store затронутого сценария.
- SQL и pgx-транзакции принадлежат persistence-адаптерам. Смена статуса upload, reviewer metadata и квота должны сохранять атомарность. Read-проекции могут объединять таблицы модулей.
- Целевая проверка: `go test ./internal/<module>/...`; перед сдачей Go-рефакторинга: `go test ./...`, `go vet ./...`.
- PostgreSQL integration: `TEST_DATABASE_URL` и `go test -tags integration ./internal/dbtest ./internal/playback`. E2E API: `go test -tags integration ./cmd/api` (проверь заголовок теста/переменные окружения).
- Сканер работает внутри процесса; upload jobs используют статусы PostgreSQL и worker loops. River/sqlc сейчас не используются.
+4 -4
View File
@@ -154,10 +154,10 @@ func newApp(ctx context.Context, cfg config.API, pool *pgxpool.Pool, rdb *redis.
}
return libSvc.Root(src)
}
var dto library.DTO
pb := playback.NewHandler(playback.NewStore(pool), libStore, func() library.DTO { return dto }, signer, transcoder,
pbStore := playback.NewStore(pool)
dto := library.DTO{Signer: signer, Personal: playback.NewPersonalizer(pbStore, signer)}
pb := playback.NewHandler(pbStore, libStore, dto, signer, transcoder,
rootFor, cfg.XAccel, log)
dto = library.DTO{Signer: signer, Personal: pb}
libSvc.OnCatalogChanged = indexer.Trigger
indexer.Trigger() // индекс мог отстать (новая версия, сбой Meilisearch) — пересобираем при старте
go libSvc.Restore(ctx)
@@ -169,7 +169,7 @@ func newApp(ctx context.Context, cfg config.API, pool *pgxpool.Pool, rdb *redis.
upSvc.Run(ctx)
wh := wave.NewHandler(pool, &wave.Recommender{URL: cfg.RecommenderURL, Token: cfg.InternalToken,
Client: &http.Client{}}, libStore, func() library.DTO { return dto }, log)
Client: &http.Client{}}, libStore, dto, log)
wh.Warm = pb.Prewarm
return server.NewRouter(server.Deps{
Genius: genius.NewHandler(geniusSvc),
@@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
@@ -227,12 +228,77 @@ func TestLibraryAndUploads(t *testing.T) {
assert.Empty(t, stale, "only uploading files expire")
up.Audit(ctx, &author, "upload.test", fileID, map[string]any{"ok": true})
// Импорт: связь с файлом библиотеки, место освобождено.
require.NoError(t, up.Transition(ctx, fileID, []uploads.Status{uploads.StatusPendingReview}, uploads.StatusApproved, nil))
require.NoError(t, up.Transition(ctx, fileID, []uploads.Status{uploads.StatusApproved}, uploads.StatusImporting, nil))
require.NoError(t, up.Transition(ctx, fileID, []uploads.Status{uploads.StatusImporting}, uploads.StatusImported,
func(tx pgx.Tx) error { return uploads.MarkImported(ctx, tx, fileID, fileIDs[1]) }))
// A failure writing reviewer metadata must roll back both status and quota.
require.Error(t, up.Decide(ctx, fileID, uuid.New(), false, "invalid reviewer"))
f, err = up.File(ctx, fileID)
require.NoError(t, err)
assert.Equal(t, uploads.StatusPendingReview, f.Status)
assert.Nil(t, f.ReviewedBy)
used, _, err = up.Usage(ctx, author)
require.NoError(t, err)
assert.EqualValues(t, 400, used)
// Import operations retain the status/reason/link and quota invariants.
require.NoError(t, up.Decide(ctx, fileID, author, true, "discard on approval"))
f, err = up.File(ctx, fileID)
require.NoError(t, err)
require.NotNil(t, f.ReviewedBy)
assert.Equal(t, author, *f.ReviewedBy)
assert.Nil(t, f.StatusReason)
require.NoError(t, up.ChangeStatus(ctx, fileID, []uploads.Status{uploads.StatusApproved}, uploads.StatusImporting))
require.NoError(t, up.FailImport(ctx, fileID, "retryable failure"))
f, err = up.File(ctx, fileID)
require.NoError(t, err)
assert.Equal(t, uploads.StatusImportFailed, f.Status)
require.NotNil(t, f.StatusReason)
assert.Equal(t, "retryable failure", *f.StatusReason)
require.NoError(t, up.ChangeStatus(ctx, fileID, []uploads.Status{uploads.StatusImportFailed}, uploads.StatusApproved))
require.NoError(t, up.ChangeStatus(ctx, fileID, []uploads.Status{uploads.StatusApproved}, uploads.StatusImporting))
require.NoError(t, up.CompleteImport(ctx, fileID, src.ID, "Кино - Группа крови.flac", fileIDs[1]))
require.ErrorIs(t, up.CompleteImport(ctx, fileID, src.ID, "ignored.flac", fileIDs[1]), uploads.ErrWrongStatus)
used, _, err = up.Usage(ctx, author)
require.NoError(t, err)
assert.EqualValues(t, 0, used)
// Two reviewers cannot both decide the same pending file or release quota twice.
secondHash := sha256.Sum256([]byte("concurrent decision"))
_, reserved, err := up.CreateBatch(ctx, author, nil, []uploads.NewFile{
{ClientID: "race", Name: "race.flac", Size: 300, SHA256: secondHash[:]},
}, settings)
require.NoError(t, err)
require.Len(t, reserved, 1)
raceID := reserved[0].FileID
require.NotEqual(t, uuid.Nil, raceID)
require.NoError(t, up.ChangeStatus(ctx, raceID, []uploads.Status{uploads.StatusUploading}, uploads.StatusProcessing))
require.NoError(t, up.ChangeStatus(ctx, raceID, []uploads.Status{uploads.StatusProcessing}, uploads.StatusPendingReview))
var wg sync.WaitGroup
results := make(chan error, 2)
for _, reason := range []string{"first", "second"} {
wg.Add(1)
go func(reason string) { defer wg.Done(); results <- up.Decide(ctx, raceID, author, false, reason) }(reason)
}
wg.Wait()
close(results)
success, conflicts := 0, 0
for err := range results {
if err == nil {
success++
} else {
require.ErrorIs(t, err, uploads.ErrWrongStatus)
conflicts++
}
}
assert.Equal(t, 1, success)
assert.Equal(t, 1, conflicts)
used, _, err = up.Usage(ctx, author)
require.NoError(t, err)
assert.Zero(t, used)
f, err = up.File(ctx, raceID)
require.NoError(t, err)
assert.Equal(t, uploads.StatusRejected, f.Status)
require.NotNil(t, f.ReviewedBy)
assert.Equal(t, author, *f.ReviewedBy)
require.NotNil(t, f.StatusReason)
assert.Contains(t, []string{"first", "second"}, *f.StatusReason)
}
+69
View File
@@ -0,0 +1,69 @@
package library
import (
"context"
"errors"
"net/http"
"github.com/google/uuid"
"pipu/api/internal/auth"
"pipu/api/internal/platform/apperr"
)
type ScanStore interface {
GetSource(context.Context, uuid.UUID) (Source, error)
RetryFailedAnalysis(context.Context) (int, error)
}
type ScanStarter interface {
Start(Source, string, bool) error
}
// ScanService owns explicit and scheduled scan starts.
type ScanService struct {
store ScanStore
scanner ScanStarter
board *ProgressBoard
root func(Source) (string, error)
}
// StartScan запускает скан источника в фоне.
// RetryAnalysis возвращает в очередь треки, которые анализатор не смог обработать (например, пока диск
// не был смонтирован).
func (s *ScanService) RetryAnalysis(ctx context.Context) (int, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return 0, err
}
return s.store.RetryFailedAnalysis(ctx)
}
func (s *ScanService) StartScan(ctx context.Context, id uuid.UUID, full bool) (Progress, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return Progress{}, err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return Progress{}, notFound(err)
}
if err := s.startScan(src, full); err != nil {
return Progress{}, err
}
p, _ := s.board.Get(id)
return p, nil
}
func (s *ScanService) startScan(src Source, full bool) error {
if src.Status != "mounted" {
return apperr.New(http.StatusConflict, CodeSourceOffline, "source is not connected")
}
root, err := s.root(src)
if err != nil {
return err
}
if err := s.scanner.Start(src, root, full); errors.Is(err, ErrScanRunning) {
return apperr.Conflict(CodeScanRunning, "scan is already running")
} else if err != nil {
return err
}
return nil
}
@@ -0,0 +1,55 @@
package library
import (
"context"
"errors"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"pipu/api/internal/auth"
"pipu/api/internal/platform/apperr"
)
type scanStoreStub struct{ source Source }
func (s scanStoreStub) GetSource(context.Context, uuid.UUID) (Source, error) { return s.source, nil }
func (s scanStoreStub) RetryFailedAnalysis(context.Context) (int, error) { return 7, nil }
type scanStartFunc func(Source, string, bool) error
func (f scanStartFunc) Start(s Source, root string, full bool) error { return f(s, root, full) }
func TestScanServiceAuthorizationAndStart(t *testing.T) {
id := uuid.New()
called := false
s := &ScanService{
store: scanStoreStub{Source{ID: id, Status: "mounted"}}, board: NewProgressBoard(),
root: func(Source) (string, error) { return "music", nil },
scanner: scanStartFunc(func(src Source, root string, full bool) error {
called = true
require.Equal(t, id, src.ID)
require.Equal(t, "music", root)
require.True(t, full)
return ErrScanRunning
}),
}
_, err := s.StartScan(context.Background(), id, true)
require.Error(t, err)
require.False(t, called)
ctx := auth.WithPrincipal(context.Background(), auth.Principal{Role: auth.RoleAdmin})
_, err = s.StartScan(ctx, id, true)
var problem *apperr.Error
require.ErrorAs(t, err, &problem)
require.Equal(t, CodeScanRunning, problem.Code)
require.True(t, called)
}
func TestScanServiceDoesNotStartOfflineOrUnresolvedSource(t *testing.T) {
s := &ScanService{} // no scanner needed: errors must be returned before IO
require.Error(t, s.startScan(Source{Status: "error"}, false))
failure := errors.New("invalid root")
s.root = func(Source) (string, error) { return "", failure }
require.ErrorIs(t, s.startScan(Source{Status: "mounted"}, false), failure)
}
+118
View File
@@ -0,0 +1,118 @@
package library
import (
"context"
"errors"
"log/slog"
"time"
"github.com/google/uuid"
"pipu/api/internal/platform/apperr"
)
type ScheduleStore interface {
ListSources(context.Context) ([]Source, error)
SetSourceStatus(context.Context, uuid.UUID, string, *string) error
}
type sourceConnection interface {
connect(context.Context, Source) (Source, error)
check(context.Context, Source, bool) (string, *string)
}
type scheduledScan interface {
startScan(Source, bool) error
}
// Scheduler owns the periodic lifetime, not source or template business rules.
type Scheduler struct {
store ScheduleStore
sources sourceConnection
scans scheduledScan
log *slog.Logger
}
// Restore при старте api переподключает NFS-хранилища и проверяет local (после перезапуска агента).
func (s *Scheduler) Restore(ctx context.Context) {
sources, err := s.store.ListSources(ctx)
if err != nil {
s.log.Error("restore sources", "err", err)
return
}
for _, src := range sources {
if src.Status == "disabled" {
continue
}
if _, err := s.sources.connect(ctx, src); err != nil {
s.log.Error("restore source", "source_id", src.ID, "err", err)
}
}
}
// RunSchedule раз в минуту проверяет доступность хранилищ и запускает сканы по расписанию.
func (s *Scheduler) RunSchedule(ctx context.Context) {
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
sources, err := s.store.ListSources(ctx)
if err != nil {
s.log.Warn("schedule: list sources", "err", err)
continue
}
for _, src := range sources {
if src.Status == "disabled" {
continue
}
s.healthCheck(ctx, src)
if src.ScanInterval == nil || src.Status != "mounted" {
continue
}
if src.LastScanAt == nil || time.Since(*src.LastScanAt) >= *src.ScanInterval {
if err := s.scans.startScan(src, false); err != nil && !errors.Is(err, apperr.Conflict(CodeScanRunning, "")) {
s.log.Warn("scheduled scan", "source_id", src.ID, "err", err)
}
}
}
}
}
// healthCheck: недоступное хранилище — status=error (треки серые), вернулось — снова mounted.
func (s *Scheduler) healthCheck(ctx context.Context, src Source) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
type result struct {
status string
message *string
}
done := make(chan result, 1)
go func() {
status, message := s.sources.check(ctx, src, false)
done <- result{status, message}
}()
var status string
var message *string
select {
case r := <-done:
status, message = r.status, r.message
case <-ctx.Done():
m := "storage does not respond"
status, message = "error", &m
}
if status == "error" && src.Type == SourceNFS && src.Status == "error" {
// Попробовать перемонтировать, как при старте.
if _, err := s.sources.connect(ctx, src); err == nil {
return
}
}
if status != src.Status || deref(message) != deref(src.StatusMessage) {
if err := s.store.SetSourceStatus(ctx, src.ID, status, message); err != nil {
s.log.Warn("health check", "source_id", src.ID, "err", err)
}
}
}
+13 -772
View File
@@ -3,25 +3,10 @@ package library
import (
"context"
"errors"
"fmt"
"log/slog"
"math/rand/v2"
"net/http"
"os"
"path"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/google/uuid"
"pipu/api/internal/auth"
"pipu/api/internal/library/meta"
"pipu/api/internal/platform/apperr"
"pipu/api/internal/storageagent"
)
// Коды ошибок библиотеки.
@@ -45,24 +30,23 @@ type Config struct {
HostRoot string // LIBRARY_HOST внутри контейнера, для local-источников
}
// Service управляет хранилищами и сканами.
// Service preserves the API while each use case owns only its dependencies.
type Service struct {
store *Store
scanner *Scanner
board *ProgressBoard
agent Agent
prober Prober
cfg Config
log *slog.Logger
mu sync.Mutex // сериализует переподключение одного и того же источника
// OnCatalogChanged — каталог изменился не сканом (удалено хранилище): переиндексация поиска.
OnCatalogChanged func()
*SourceService
*TemplateService
*ScanService
*Scheduler
}
// NewService создаёт сервис.
func NewService(store *Store, scanner *Scanner, board *ProgressBoard, agent Agent, prober Prober, cfg Config, log *slog.Logger) *Service {
return &Service{store: store, scanner: scanner, board: board, agent: agent, prober: prober, cfg: cfg, log: log}
sources := &SourceService{store: store, board: board, agent: agent, cfg: cfg, log: log}
scans := &ScanService{store: store, scanner: scanner, board: board, root: sources.Root}
return &Service{
SourceService: sources,
TemplateService: &TemplateService{store: store, prober: prober, root: sources.Root},
ScanService: scans,
Scheduler: &Scheduler{store: store, sources: sources, scans: scans, log: log},
}
}
func forbidden() error { return apperr.Forbidden(auth.CodeForbidden, "not allowed") }
@@ -84,746 +68,3 @@ func notFound(err error) error {
}
return err
}
// Root — каталог источника в файловой системе api.
func (s *Service) Root(src Source) (string, error) {
switch src.Type {
case SourceLocal:
rel := ""
if src.LocalPath != nil {
rel = *src.LocalPath
}
return s.hostPath(rel)
case SourceNFS:
return filepath.Join(s.cfg.LibraryRoot, src.ID.String()), nil
}
return "", fmt.Errorf("library: unknown source type %q", src.Type)
}
// hostPath — путь внутри LIBRARY_HOST; выйти за его пределы нельзя.
func (s *Service) hostPath(rel string) (string, error) {
rel = strings.Trim(strings.ReplaceAll(rel, "\\", "/"), "/")
clean := path.Clean("/" + rel)
if clean != "/"+rel && rel != "" || strings.Contains(rel, "..") {
return "", apperr.Validation("local_path", CodeLocalPathInvalid, "path must be relative without ..", nil)
}
return filepath.Join(s.cfg.HostRoot, filepath.FromSlash(strings.TrimPrefix(clean, "/"))), nil
}
// ListSources — хранилища с прогрессом сканов.
func (s *Service) ListSources(ctx context.Context) ([]Source, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, err
}
return s.store.ListSources(ctx)
}
// GetSource — хранилище по id.
func (s *Service) GetSource(ctx context.Context, id uuid.UUID) (Source, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return Source{}, err
}
src, err := s.store.GetSource(ctx, id)
return src, notFound(err)
}
// Progress — прогресс скана источника, если он был.
func (s *Service) Progress(id uuid.UUID) (Progress, bool) { return s.board.Get(id) }
// SourceInput — поля создания / изменения хранилища. nil — не задано.
type SourceInput struct {
Name *string
Type SourceType
NFSServer *string
NFSExport *string
NFSOptions *string
LocalPath *string
TagsFirst *bool
ScanIntervalMinutes *int // 0 — выключить
Enabled *bool
AcceptsUploads *bool
WriteTemplate *string // "" — убрать
}
func (s *Service) apply(src *Source, in SourceInput) error {
if in.Name != nil {
name := strings.TrimSpace(*in.Name)
if name == "" || utf8.RuneCountInString(name) > 100 {
return apperr.Validation("name", CodeNameInvalid, "name must be 1-100 characters", map[string]any{"max": 100})
}
src.Name = name
}
if in.TagsFirst != nil {
src.TagsFirst = *in.TagsFirst
}
if in.ScanIntervalMinutes != nil {
switch m := *in.ScanIntervalMinutes; {
case m == 0:
src.ScanInterval = nil
case m < 5 || m > 60*24*30:
return apperr.Validation("scan_interval_minutes", CodeIntervalInvalid, "interval must be 5 minutes .. 30 days",
map[string]any{"min": 5})
default:
d := time.Duration(m) * time.Minute
src.ScanInterval = &d
}
}
if in.AcceptsUploads != nil {
src.AcceptsUploads = *in.AcceptsUploads
}
if in.WriteTemplate != nil {
if strings.TrimSpace(*in.WriteTemplate) == "" {
src.WriteTemplate = nil
} else {
tpl, err := meta.ParseTemplate(*in.WriteTemplate)
if err != nil {
return apperr.Validation("write_template", CodeTemplateInvalid, err.Error(), map[string]any{"reason": err.Error()})
}
text := tpl.String()
src.WriteTemplate = &text
}
}
switch src.Type {
case SourceLocal:
if in.LocalPath != nil {
rel := strings.Trim(strings.ReplaceAll(*in.LocalPath, "\\", "/"), "/")
if _, err := s.hostPath(rel); err != nil {
return err
}
src.LocalPath = &rel
}
if src.LocalPath == nil {
empty := ""
src.LocalPath = &empty
}
case SourceNFS:
if in.NFSServer != nil {
src.NFSServer = in.NFSServer
}
if in.NFSExport != nil {
src.NFSExport = in.NFSExport
}
if in.NFSOptions != nil {
src.NFSOptions = *in.NFSOptions
}
spec, err := nfsSpec(*src).Normalize(false)
if err != nil {
var ve *storageagent.ValidationError
if errors.As(err, &ve) {
return apperr.Validation(ve.Field, CodeNFSInvalid, ve.Reason, nil)
}
return err
}
src.NFSServer, src.NFSExport, src.NFSOptions = &spec.Server, &spec.Export, spec.Options
default:
return apperr.Validation("type", "validation.source_type_invalid", "unknown source type", nil)
}
return nil
}
func nfsSpec(src Source) storageagent.NFSSpec {
var spec storageagent.NFSSpec
if src.NFSServer != nil {
spec.Server = *src.NFSServer
}
if src.NFSExport != nil {
spec.Export = *src.NFSExport
}
spec.Options = src.NFSOptions
return spec
}
// CreateSource сохраняет хранилище и сразу пытается подключить его.
func (s *Service) CreateSource(ctx context.Context, in SourceInput) (Source, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return Source{}, err
}
src := Source{ID: newID(), Type: in.Type, TagsFirst: true, Status: "pending", NFSOptions: "ro,nfsvers=4.1,soft,timeo=150,retrans=3"}
if in.Name == nil {
in.Name = new(string)
}
if err := s.apply(&src, in); err != nil {
return Source{}, err
}
src, err := s.store.SaveSource(ctx, src)
if err != nil {
return Source{}, err
}
return s.connect(ctx, src)
}
// UpdateSource меняет хранилище; смена адреса или папки переподключает его.
func (s *Service) UpdateSource(ctx context.Context, id uuid.UUID, in SourceInput) (Source, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return Source{}, err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return Source{}, notFound(err)
}
before := src
in.Type = src.Type
if err := s.apply(&src, in); err != nil {
return Source{}, err
}
if src, err = s.store.SaveSource(ctx, src); err != nil {
return Source{}, err
}
location := func(x Source) string {
return fmt.Sprint(x.LocalPath != nil && *x.LocalPath != "", deref(x.LocalPath), deref(x.NFSServer), deref(x.NFSExport), x.NFSOptions,
x.Type == SourceNFS && x.AcceptsUploads)
}
switch {
case in.Enabled != nil && !*in.Enabled:
if src.Type == SourceNFS {
_ = s.agent.Unmount(ctx, src.ID)
}
if err := s.store.SetSourceStatus(ctx, src.ID, "disabled", nil); err != nil {
return Source{}, err
}
return s.store.GetSource(ctx, src.ID)
case in.Enabled != nil && *in.Enabled, location(before) != location(src), src.Status == "error":
return s.connect(ctx, src)
}
return src, nil
}
func deref(p *string) string {
if p == nil {
return ""
}
return *p
}
// connect подключает хранилище и записывает статус: local — проверка каталога, nfs — монтирование агентом.
func (s *Service) connect(ctx context.Context, src Source) (Source, error) {
s.mu.Lock()
defer s.mu.Unlock()
status, message := s.check(ctx, src, true)
if err := s.store.SetSourceStatus(ctx, src.ID, status, message); err != nil {
return Source{}, err
}
return s.store.GetSource(ctx, src.ID)
}
// check проверяет доступность; mount — смонтировать NFS (иначе только проверить точку).
func (s *Service) check(ctx context.Context, src Source, mount bool) (string, *string) {
msg := func(m string) *string { return &m }
switch src.Type {
case SourceLocal:
root, err := s.Root(src)
if err != nil {
return "error", msg(err.Error())
}
info, err := os.Stat(root)
if err != nil || !info.IsDir() {
return "error", msg("folder not found: " + deref(src.LocalPath))
}
return "mounted", nil
case SourceNFS:
if !mount {
root, _ := s.Root(src)
if _, err := os.Stat(root); err != nil {
return "error", msg(err.Error())
}
return "mounted", nil
}
res, err := s.agent.Mount(ctx, src.ID, nfsSpec(src), src.AcceptsUploads)
if err != nil {
return "error", msg(err.Error())
}
if res.Status != "mounted" {
return "error", msg(res.Message)
}
return "mounted", nil
}
return "error", msg("unknown type")
}
// DeleteSource отключает хранилище и удаляет его файлы из каталога.
func (s *Service) DeleteSource(ctx context.Context, id uuid.UUID) error {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return notFound(err)
}
if p, ok := s.board.Get(id); ok && p.Running {
return apperr.Conflict(CodeScanRunning, "scan is running")
}
if src.Type == SourceNFS {
if err := s.agent.Unmount(ctx, id); err != nil {
s.log.WarnContext(ctx, "unmount failed", "source_id", id, "err", err)
}
}
if err := s.store.DeleteSource(ctx, id); err != nil {
return notFound(err)
}
if err := s.store.CleanupOrphans(ctx); err != nil {
return err
}
if s.OnCatalogChanged != nil {
s.OnCatalogChanged()
}
return nil
}
// TestResult — итог проверки подключения.
type TestResult struct {
OK bool
Message string
AudioFiles int
Write *storageagent.WriteTestResult // только для accepts_uploads
}
// writeTarget — как агенту найти источник на запись.
func writeTarget(src Source) storageagent.WriteTestRequest {
req := storageagent.WriteTestRequest{SourceID: src.ID.String()}
if src.Type == SourceLocal {
lp := deref(src.LocalPath)
req.LocalPath = &lp
}
return req
}
// TestSource проверяет доступ к хранилищу и считает аудиофайлы (до 1000).
func (s *Service) TestSource(ctx context.Context, id uuid.UUID) (TestResult, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return TestResult{}, err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return TestResult{}, notFound(err)
}
res, err := s.testRead(ctx, src)
if err != nil || !src.AcceptsUploads {
return res, err
}
w, err := s.agent.TestWrite(ctx, writeTarget(src))
if err != nil {
w = storageagent.WriteTestResult{Message: err.Error()}
}
res.Write = &w
return res, nil
}
func (s *Service) testRead(ctx context.Context, src Source) (TestResult, error) {
if src.Type == SourceNFS {
res, err := s.agent.Test(ctx, nfsSpec(src))
if err != nil {
return TestResult{Message: err.Error()}, nil
}
return TestResult{OK: res.Status == "mounted", Message: res.Message, AudioFiles: res.AudioFiles}, nil
}
root, err := s.Root(src)
if err != nil {
return TestResult{Message: err.Error()}, nil
}
n := 0
err = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() && IsAudio(d.Name()) {
n++
if n >= 1000 {
return filepath.SkipAll
}
}
return nil
})
if err != nil {
return TestResult{Message: err.Error(), AudioFiles: n}, nil
}
return TestResult{OK: true, Message: fmt.Sprintf("found %d audio files", n), AudioFiles: n}, nil
}
// Patterns — шаблоны путей источника.
func (s *Service) Patterns(ctx context.Context, id uuid.UUID) ([]PatternRow, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, err
}
if _, err := s.store.GetSource(ctx, id); err != nil {
return nil, notFound(err)
}
return s.store.Patterns(ctx, id)
}
func compile(patterns []PatternRow) ([]meta.Pattern, error) {
var exprs []string
idx := []int{}
for i, p := range patterns {
if p.IsEnabled {
exprs = append(exprs, p.Regex)
idx = append(idx, i)
}
}
compiled, err := meta.CompilePatterns(exprs)
var pe *meta.PatternError
if errors.As(err, &pe) {
at := idx[pe.Index]
return nil, &apperr.Error{
Status: http.StatusUnprocessableEntity, Code: CodePatternInvalid, Detail: pe.Reason,
Params: map[string]any{"index": at, "reason": pe.Reason},
Fields: []apperr.FieldError{{Field: fmt.Sprintf("patterns[%d].regex", at), Code: CodePatternInvalid}},
}
}
return compiled, err
}
// PutPatterns проверяет и сохраняет шаблоны.
func (s *Service) PutPatterns(ctx context.Context, id uuid.UUID, patterns []PatternRow) ([]PatternRow, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, err
}
if _, err := s.store.GetSource(ctx, id); err != nil {
return nil, notFound(err)
}
if _, err := compile(patterns); err != nil {
return nil, err
}
if err := s.store.ReplacePatterns(ctx, id, patterns); err != nil {
return nil, err
}
return s.store.Patterns(ctx, id)
}
// PreviewItem — разбор одного файла.
type PreviewItem struct {
RelPath string
PatternIndex *int
Skipped bool
PathFields map[string]string
Tags map[string]string
Result meta.Meta
Error string
}
// Preview применяет шаблоны к выборке файлов без сохранения: из каталога, а до первого скана — из обхода.
func (s *Service) Preview(ctx context.Context, id uuid.UUID, patterns []PatternRow, sample int) ([]PreviewItem, int, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, 0, err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return nil, 0, notFound(err)
}
compiled, err := compile(patterns)
if err != nil {
return nil, 0, err
}
sample = min(max(sample, 1), 200)
root, err := s.Root(src)
if err != nil {
return nil, 0, err
}
paths, err := s.store.SampleFiles(ctx, id, sample)
if err != nil {
return nil, 0, err
}
if len(paths) == 0 {
found, err := walk(root, func(string) bool { return false })
if err != nil {
return nil, 0, apperr.New(http.StatusConflict, CodeSourceOffline, err.Error())
}
rand.Shuffle(len(found), func(i, j int) { found[i], found[j] = found[j], found[i] })
for _, w := range found[:min(sample, len(found))] {
paths = append(paths, w.rel)
}
}
slices.Sort(paths)
items := make([]PreviewItem, len(paths))
var wg sync.WaitGroup
sem := make(chan struct{}, 8)
for i, rel := range paths {
wg.Add(1)
go func() {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
items[i] = s.previewOne(ctx, root, rel, compiled, src.TagsFirst)
}()
}
wg.Wait()
unmatched := 0
for _, it := range items {
if it.PatternIndex == nil {
unmatched++
}
}
return items, unmatched, nil
}
func (s *Service) previewOne(ctx context.Context, root, rel string, patterns []meta.Pattern, tagsFirst bool) PreviewItem {
it := PreviewItem{RelPath: rel, PathFields: map[string]string{}, Tags: map[string]string{}}
m := meta.MatchPath(patterns, rel)
if m.Index >= 0 {
idx := m.Index
it.PatternIndex = &idx
}
it.Skipped = m.Skip
for k, v := range m.Fields {
it.PathFields[k] = v
}
p, err := s.prober.Probe(ctx, filepath.Join(root, filepath.FromSlash(rel)))
if err != nil {
it.Error = err.Error()
}
for k, v := range map[string]string{
"artist": p.Tags.Artist, "albumartist": p.Tags.AlbumArtist, "album": p.Tags.Album, "title": p.Tags.Title,
"genre": p.Tags.Genre, "year": p.Tags.Year, "track": p.Tags.Track, "disc": p.Tags.Disc,
} {
if v != "" {
it.Tags[k] = v
}
}
it.Result = meta.Merge(p.Tags, meta.FromPath(m.Fields), tagsFirst, rel)
if it.Result.Album == "" {
it.Result.Album = UnknownAlbum
}
return it
}
// StartScan запускает скан источника в фоне.
// RetryAnalysis возвращает в очередь треки, которые анализатор не смог обработать (например, пока диск
// не был смонтирован).
func (s *Service) RetryAnalysis(ctx context.Context) (int, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return 0, err
}
return s.store.RetryFailedAnalysis(ctx)
}
func (s *Service) StartScan(ctx context.Context, id uuid.UUID, full bool) (Progress, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return Progress{}, err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return Progress{}, notFound(err)
}
if err := s.startScan(src, full); err != nil {
return Progress{}, err
}
p, _ := s.board.Get(id)
return p, nil
}
func (s *Service) startScan(src Source, full bool) error {
if src.Status != "mounted" {
return apperr.New(http.StatusConflict, CodeSourceOffline, "source is not connected")
}
root, err := s.Root(src)
if err != nil {
return err
}
if err := s.scanner.Start(src, root, full); errors.Is(err, ErrScanRunning) {
return apperr.Conflict(CodeScanRunning, "scan is already running")
} else if err != nil {
return err
}
return nil
}
// Status — состояние библиотеки (admin, moderator).
type Status struct {
Counts Counts
Sources []Source
Analysis AnalysisCounts
Wave WaveMetrics
}
// Status собирает счётчики и состояние источников.
func (s *Service) Status(ctx context.Context) (Status, error) {
if err := requirePerm(ctx, auth.PermViewLibraryStatus); err != nil {
return Status{}, err
}
c, err := s.store.Counts(ctx)
if err != nil {
return Status{}, err
}
sources, err := s.store.ListSources(ctx)
if err != nil {
return Status{}, err
}
analysis, err := s.store.AnalysisCounts(ctx)
if err != nil {
return Status{}, err
}
wave, err := s.store.WaveMetrics(ctx)
if err != nil {
return Status{}, err
}
return Status{Counts: c, Sources: sources, Analysis: analysis, Wave: wave}, nil
}
// FileErrors — файлы с ошибками чтения.
func (s *Service) FileErrors(ctx context.Context, after string, limit int) ([]FileError, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, err
}
return s.store.FileErrors(ctx, after, limit)
}
// HostDirs — подпапки каталога LIBRARY_HOST для выбора local-хранилища.
func (s *Service) HostDirs(ctx context.Context, rel string) (string, []string, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return "", nil, err
}
dir, err := s.hostPath(rel)
if err != nil {
return "", nil, err
}
entries, err := os.ReadDir(dir)
if err != nil {
return "", nil, apperr.Validation("path", CodeLocalPathInvalid, "folder not found", nil)
}
dirs := []string{}
for _, e := range entries {
if e.IsDir() && !strings.HasPrefix(e.Name(), ".") {
dirs = append(dirs, e.Name())
}
}
slices.Sort(dirs)
return strings.Trim(strings.ReplaceAll(rel, "\\", "/"), "/"), dirs, nil
}
// Restore при старте api переподключает NFS-хранилища и проверяет local (после перезапуска агента).
func (s *Service) Restore(ctx context.Context) {
sources, err := s.store.ListSources(ctx)
if err != nil {
s.log.Error("restore sources", "err", err)
return
}
for _, src := range sources {
if src.Status == "disabled" {
continue
}
if _, err := s.connect(ctx, src); err != nil {
s.log.Error("restore source", "source_id", src.ID, "err", err)
}
}
}
// RunSchedule раз в минуту проверяет доступность хранилищ и запускает сканы по расписанию.
func (s *Service) RunSchedule(ctx context.Context) {
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
sources, err := s.store.ListSources(ctx)
if err != nil {
s.log.Warn("schedule: list sources", "err", err)
continue
}
for _, src := range sources {
if src.Status == "disabled" {
continue
}
s.healthCheck(ctx, src)
if src.ScanInterval == nil || src.Status != "mounted" {
continue
}
if src.LastScanAt == nil || time.Since(*src.LastScanAt) >= *src.ScanInterval {
if err := s.startScan(src, false); err != nil && !errors.Is(err, apperr.Conflict(CodeScanRunning, "")) {
s.log.Warn("scheduled scan", "source_id", src.ID, "err", err)
}
}
}
}
}
// healthCheck: недоступное хранилище — status=error (треки серые), вернулось — снова mounted.
func (s *Service) healthCheck(ctx context.Context, src Source) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
done := make(chan struct{})
var status string
var message *string
go func() {
status, message = s.check(ctx, src, false)
close(done)
}()
select {
case <-done:
case <-ctx.Done():
m := "storage does not respond"
status, message = "error", &m
}
if status == "error" && src.Type == SourceNFS && src.Status == "error" {
// Попробовать перемонтировать, как при старте.
if _, err := s.connect(ctx, src); err == nil {
return
}
}
if status != src.Status || deref(message) != deref(src.StatusMessage) {
if err := s.store.SetSourceStatus(ctx, src.ID, status, message); err != nil {
s.log.Warn("health check", "source_id", src.ID, "err", err)
}
}
}
// templateSampleSize — сколько треков берёт проверка шаблона записи (docs/uploads.md#7).
const templateSampleSize = 50
// SuggestWriteTemplate подбирает шаблон записи по существующим путям и выражениям источника.
func (s *Service) SuggestWriteTemplate(ctx context.Context, id uuid.UUID) (string, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return "", err
}
if _, err := s.store.GetSource(ctx, id); err != nil {
return "", notFound(err)
}
rows, err := s.store.Patterns(ctx, id)
if err != nil {
return "", err
}
var exprs []string
for _, r := range rows {
if r.IsEnabled {
exprs = append(exprs, r.Regex)
}
}
paths, err := s.store.SampleFiles(ctx, id, 200)
if err != nil {
return "", err
}
tpl, err := meta.SuggestTemplate(exprs, paths)
if err != nil {
return "", apperr.New(http.StatusUnprocessableEntity, CodeTemplateNone, "no path pattern can be turned into a template")
}
return tpl, nil
}
// CheckWriteTemplate применяет шаблон к трекам источника и разбирает пути его выражениями обратно.
func (s *Service) CheckWriteTemplate(ctx context.Context, id uuid.UUID, template string) (meta.TemplateCheck, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return meta.TemplateCheck{}, err
}
if _, err := s.store.GetSource(ctx, id); err != nil {
return meta.TemplateCheck{}, notFound(err)
}
tpl, err := meta.ParseTemplate(template)
if err != nil {
return meta.TemplateCheck{}, apperr.Validation("template", CodeTemplateInvalid, err.Error(), map[string]any{"reason": err.Error()})
}
rows, err := s.store.Patterns(ctx, id)
if err != nil {
return meta.TemplateCheck{}, err
}
compiled, err := compile(rows)
if err != nil {
return meta.TemplateCheck{}, err
}
samples, err := s.store.TemplateSamples(ctx, id, templateSampleSize)
if err != nil {
return meta.TemplateCheck{}, err
}
return meta.CheckTemplate(tpl, compiled, samples), nil
}
+464
View File
@@ -0,0 +1,464 @@
package library
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"path"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/google/uuid"
"pipu/api/internal/auth"
"pipu/api/internal/library/meta"
"pipu/api/internal/platform/apperr"
"pipu/api/internal/storageagent"
)
type SourceStore interface {
ListSources(context.Context) ([]Source, error)
GetSource(context.Context, uuid.UUID) (Source, error)
SaveSource(context.Context, Source) (Source, error)
SetSourceStatus(context.Context, uuid.UUID, string, *string) error
DeleteSource(context.Context, uuid.UUID) error
CleanupOrphans(context.Context) error
Counts(context.Context) (Counts, error)
AnalysisCounts(context.Context) (AnalysisCounts, error)
WaveMetrics(context.Context) (WaveMetrics, error)
FileErrors(context.Context, string, int) ([]FileError, error)
}
// SourceService owns source configuration, connectivity and diagnostics.
type SourceService struct {
store SourceStore
board *ProgressBoard
agent Agent
cfg Config
log *slog.Logger
mu sync.Mutex
OnCatalogChanged func()
}
// Root — каталог источника в файловой системе api.
func (s *SourceService) Root(src Source) (string, error) {
switch src.Type {
case SourceLocal:
rel := ""
if src.LocalPath != nil {
rel = *src.LocalPath
}
return s.hostPath(rel)
case SourceNFS:
return filepath.Join(s.cfg.LibraryRoot, src.ID.String()), nil
}
return "", fmt.Errorf("library: unknown source type %q", src.Type)
}
// hostPath — путь внутри LIBRARY_HOST; выйти за его пределы нельзя.
func (s *SourceService) hostPath(rel string) (string, error) {
rel = strings.Trim(strings.ReplaceAll(rel, "\\", "/"), "/")
clean := path.Clean("/" + rel)
if clean != "/"+rel && rel != "" || strings.Contains(rel, "..") {
return "", apperr.Validation("local_path", CodeLocalPathInvalid, "path must be relative without ..", nil)
}
return filepath.Join(s.cfg.HostRoot, filepath.FromSlash(strings.TrimPrefix(clean, "/"))), nil
}
// ListSources — хранилища с прогрессом сканов.
func (s *SourceService) ListSources(ctx context.Context) ([]Source, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, err
}
return s.store.ListSources(ctx)
}
// GetSource — хранилище по id.
func (s *SourceService) GetSource(ctx context.Context, id uuid.UUID) (Source, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return Source{}, err
}
src, err := s.store.GetSource(ctx, id)
return src, notFound(err)
}
// Progress — прогресс скана источника, если он был.
func (s *SourceService) Progress(id uuid.UUID) (Progress, bool) { return s.board.Get(id) }
// SourceInput — поля создания / изменения хранилища. nil — не задано.
type SourceInput struct {
Name *string
Type SourceType
NFSServer *string
NFSExport *string
NFSOptions *string
LocalPath *string
TagsFirst *bool
ScanIntervalMinutes *int // 0 — выключить
Enabled *bool
AcceptsUploads *bool
WriteTemplate *string // "" — убрать
}
func (s *SourceService) apply(src *Source, in SourceInput) error {
if in.Name != nil {
name := strings.TrimSpace(*in.Name)
if name == "" || utf8.RuneCountInString(name) > 100 {
return apperr.Validation("name", CodeNameInvalid, "name must be 1-100 characters", map[string]any{"max": 100})
}
src.Name = name
}
if in.TagsFirst != nil {
src.TagsFirst = *in.TagsFirst
}
if in.ScanIntervalMinutes != nil {
switch m := *in.ScanIntervalMinutes; {
case m == 0:
src.ScanInterval = nil
case m < 5 || m > 60*24*30:
return apperr.Validation("scan_interval_minutes", CodeIntervalInvalid, "interval must be 5 minutes .. 30 days",
map[string]any{"min": 5})
default:
d := time.Duration(m) * time.Minute
src.ScanInterval = &d
}
}
if in.AcceptsUploads != nil {
src.AcceptsUploads = *in.AcceptsUploads
}
if in.WriteTemplate != nil {
if strings.TrimSpace(*in.WriteTemplate) == "" {
src.WriteTemplate = nil
} else {
tpl, err := meta.ParseTemplate(*in.WriteTemplate)
if err != nil {
return apperr.Validation("write_template", CodeTemplateInvalid, err.Error(), map[string]any{"reason": err.Error()})
}
text := tpl.String()
src.WriteTemplate = &text
}
}
switch src.Type {
case SourceLocal:
if in.LocalPath != nil {
rel := strings.Trim(strings.ReplaceAll(*in.LocalPath, "\\", "/"), "/")
if _, err := s.hostPath(rel); err != nil {
return err
}
src.LocalPath = &rel
}
if src.LocalPath == nil {
empty := ""
src.LocalPath = &empty
}
case SourceNFS:
if in.NFSServer != nil {
src.NFSServer = in.NFSServer
}
if in.NFSExport != nil {
src.NFSExport = in.NFSExport
}
if in.NFSOptions != nil {
src.NFSOptions = *in.NFSOptions
}
spec, err := nfsSpec(*src).Normalize(false)
if err != nil {
var ve *storageagent.ValidationError
if errors.As(err, &ve) {
return apperr.Validation(ve.Field, CodeNFSInvalid, ve.Reason, nil)
}
return err
}
src.NFSServer, src.NFSExport, src.NFSOptions = &spec.Server, &spec.Export, spec.Options
default:
return apperr.Validation("type", "validation.source_type_invalid", "unknown source type", nil)
}
return nil
}
func nfsSpec(src Source) storageagent.NFSSpec {
var spec storageagent.NFSSpec
if src.NFSServer != nil {
spec.Server = *src.NFSServer
}
if src.NFSExport != nil {
spec.Export = *src.NFSExport
}
spec.Options = src.NFSOptions
return spec
}
// CreateSource сохраняет хранилище и сразу пытается подключить его.
func (s *SourceService) CreateSource(ctx context.Context, in SourceInput) (Source, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return Source{}, err
}
src := Source{ID: newID(), Type: in.Type, TagsFirst: true, Status: "pending", NFSOptions: "ro,nfsvers=4.1,soft,timeo=150,retrans=3"}
if in.Name == nil {
in.Name = new(string)
}
if err := s.apply(&src, in); err != nil {
return Source{}, err
}
src, err := s.store.SaveSource(ctx, src)
if err != nil {
return Source{}, err
}
return s.connect(ctx, src)
}
// UpdateSource меняет хранилище; смена адреса или папки переподключает его.
func (s *SourceService) UpdateSource(ctx context.Context, id uuid.UUID, in SourceInput) (Source, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return Source{}, err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return Source{}, notFound(err)
}
before := src
in.Type = src.Type
if err := s.apply(&src, in); err != nil {
return Source{}, err
}
if src, err = s.store.SaveSource(ctx, src); err != nil {
return Source{}, err
}
location := func(x Source) string {
return fmt.Sprint(x.LocalPath != nil && *x.LocalPath != "", deref(x.LocalPath), deref(x.NFSServer), deref(x.NFSExport), x.NFSOptions,
x.Type == SourceNFS && x.AcceptsUploads)
}
switch {
case in.Enabled != nil && !*in.Enabled:
if src.Type == SourceNFS {
_ = s.agent.Unmount(ctx, src.ID)
}
if err := s.store.SetSourceStatus(ctx, src.ID, "disabled", nil); err != nil {
return Source{}, err
}
return s.store.GetSource(ctx, src.ID)
case in.Enabled != nil && *in.Enabled, location(before) != location(src), src.Status == "error":
return s.connect(ctx, src)
}
return src, nil
}
func deref(p *string) string {
if p == nil {
return ""
}
return *p
}
// connect подключает хранилище и записывает статус: local — проверка каталога, nfs — монтирование агентом.
func (s *SourceService) connect(ctx context.Context, src Source) (Source, error) {
s.mu.Lock()
defer s.mu.Unlock()
status, message := s.check(ctx, src, true)
if err := s.store.SetSourceStatus(ctx, src.ID, status, message); err != nil {
return Source{}, err
}
return s.store.GetSource(ctx, src.ID)
}
// check проверяет доступность; mount — смонтировать NFS (иначе только проверить точку).
func (s *SourceService) check(ctx context.Context, src Source, mount bool) (string, *string) {
msg := func(m string) *string { return &m }
switch src.Type {
case SourceLocal:
root, err := s.Root(src)
if err != nil {
return "error", msg(err.Error())
}
info, err := os.Stat(root)
if err != nil || !info.IsDir() {
return "error", msg("folder not found: " + deref(src.LocalPath))
}
return "mounted", nil
case SourceNFS:
if !mount {
root, _ := s.Root(src)
if _, err := os.Stat(root); err != nil {
return "error", msg(err.Error())
}
return "mounted", nil
}
res, err := s.agent.Mount(ctx, src.ID, nfsSpec(src), src.AcceptsUploads)
if err != nil {
return "error", msg(err.Error())
}
if res.Status != "mounted" {
return "error", msg(res.Message)
}
return "mounted", nil
}
return "error", msg("unknown type")
}
// DeleteSource отключает хранилище и удаляет его файлы из каталога.
func (s *SourceService) DeleteSource(ctx context.Context, id uuid.UUID) error {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return notFound(err)
}
if p, ok := s.board.Get(id); ok && p.Running {
return apperr.Conflict(CodeScanRunning, "scan is running")
}
if src.Type == SourceNFS {
if err := s.agent.Unmount(ctx, id); err != nil {
s.log.WarnContext(ctx, "unmount failed", "source_id", id, "err", err)
}
}
if err := s.store.DeleteSource(ctx, id); err != nil {
return notFound(err)
}
if err := s.store.CleanupOrphans(ctx); err != nil {
return err
}
if s.OnCatalogChanged != nil {
s.OnCatalogChanged()
}
return nil
}
// TestResult — итог проверки подключения.
type TestResult struct {
OK bool
Message string
AudioFiles int
Write *storageagent.WriteTestResult // только для accepts_uploads
}
// writeTarget — как агенту найти источник на запись.
func writeTarget(src Source) storageagent.WriteTestRequest {
req := storageagent.WriteTestRequest{SourceID: src.ID.String()}
if src.Type == SourceLocal {
lp := deref(src.LocalPath)
req.LocalPath = &lp
}
return req
}
// TestSource проверяет доступ к хранилищу и считает аудиофайлы (до 1000).
func (s *SourceService) TestSource(ctx context.Context, id uuid.UUID) (TestResult, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return TestResult{}, err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return TestResult{}, notFound(err)
}
res, err := s.testRead(ctx, src)
if err != nil || !src.AcceptsUploads {
return res, err
}
w, err := s.agent.TestWrite(ctx, writeTarget(src))
if err != nil {
w = storageagent.WriteTestResult{Message: err.Error()}
}
res.Write = &w
return res, nil
}
func (s *SourceService) testRead(ctx context.Context, src Source) (TestResult, error) {
if src.Type == SourceNFS {
res, err := s.agent.Test(ctx, nfsSpec(src))
if err != nil {
return TestResult{Message: err.Error()}, nil
}
return TestResult{OK: res.Status == "mounted", Message: res.Message, AudioFiles: res.AudioFiles}, nil
}
root, err := s.Root(src)
if err != nil {
return TestResult{Message: err.Error()}, nil
}
n := 0
err = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() && IsAudio(d.Name()) {
n++
if n >= 1000 {
return filepath.SkipAll
}
}
return nil
})
if err != nil {
return TestResult{Message: err.Error(), AudioFiles: n}, nil
}
return TestResult{OK: true, Message: fmt.Sprintf("found %d audio files", n), AudioFiles: n}, nil
}
// Status — состояние библиотеки (admin, moderator).
type Status struct {
Counts Counts
Sources []Source
Analysis AnalysisCounts
Wave WaveMetrics
}
// Status собирает счётчики и состояние источников.
func (s *SourceService) Status(ctx context.Context) (Status, error) {
if err := requirePerm(ctx, auth.PermViewLibraryStatus); err != nil {
return Status{}, err
}
c, err := s.store.Counts(ctx)
if err != nil {
return Status{}, err
}
sources, err := s.store.ListSources(ctx)
if err != nil {
return Status{}, err
}
analysis, err := s.store.AnalysisCounts(ctx)
if err != nil {
return Status{}, err
}
wave, err := s.store.WaveMetrics(ctx)
if err != nil {
return Status{}, err
}
return Status{Counts: c, Sources: sources, Analysis: analysis, Wave: wave}, nil
}
// FileErrors — файлы с ошибками чтения.
func (s *SourceService) FileErrors(ctx context.Context, after string, limit int) ([]FileError, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, err
}
return s.store.FileErrors(ctx, after, limit)
}
// HostDirs — подпапки каталога LIBRARY_HOST для выбора local-хранилища.
func (s *SourceService) HostDirs(ctx context.Context, rel string) (string, []string, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return "", nil, err
}
dir, err := s.hostPath(rel)
if err != nil {
return "", nil, err
}
entries, err := os.ReadDir(dir)
if err != nil {
return "", nil, apperr.Validation("path", CodeLocalPathInvalid, "folder not found", nil)
}
dirs := []string{}
for _, e := range entries {
if e.IsDir() && !strings.HasPrefix(e.Name(), ".") {
dirs = append(dirs, e.Name())
}
}
slices.Sort(dirs)
return strings.Trim(strings.ReplaceAll(rel, "\\", "/"), "/"), dirs, nil
}
+239
View File
@@ -0,0 +1,239 @@
package library
import (
"context"
"errors"
"fmt"
"math/rand/v2"
"net/http"
"path/filepath"
"slices"
"sync"
"github.com/google/uuid"
"pipu/api/internal/auth"
"pipu/api/internal/library/meta"
"pipu/api/internal/platform/apperr"
)
type PatternStore interface {
GetSource(context.Context, uuid.UUID) (Source, error)
Patterns(context.Context, uuid.UUID) ([]PatternRow, error)
ReplacePatterns(context.Context, uuid.UUID, []PatternRow) error
SampleFiles(context.Context, uuid.UUID, int) ([]string, error)
TemplateSamples(context.Context, uuid.UUID, int) ([]meta.TemplateSample, error)
}
// TemplateService owns metadata pattern preview and write template validation.
type TemplateService struct {
store PatternStore
prober Prober
root func(Source) (string, error)
}
// Patterns — шаблоны путей источника.
func (s *TemplateService) Patterns(ctx context.Context, id uuid.UUID) ([]PatternRow, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, err
}
if _, err := s.store.GetSource(ctx, id); err != nil {
return nil, notFound(err)
}
return s.store.Patterns(ctx, id)
}
func compile(patterns []PatternRow) ([]meta.Pattern, error) {
var exprs []string
idx := []int{}
for i, p := range patterns {
if p.IsEnabled {
exprs = append(exprs, p.Regex)
idx = append(idx, i)
}
}
compiled, err := meta.CompilePatterns(exprs)
var pe *meta.PatternError
if errors.As(err, &pe) {
at := idx[pe.Index]
return nil, &apperr.Error{
Status: http.StatusUnprocessableEntity, Code: CodePatternInvalid, Detail: pe.Reason,
Params: map[string]any{"index": at, "reason": pe.Reason},
Fields: []apperr.FieldError{{Field: fmt.Sprintf("patterns[%d].regex", at), Code: CodePatternInvalid}},
}
}
return compiled, err
}
// PutPatterns проверяет и сохраняет шаблоны.
func (s *TemplateService) PutPatterns(ctx context.Context, id uuid.UUID, patterns []PatternRow) ([]PatternRow, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, err
}
if _, err := s.store.GetSource(ctx, id); err != nil {
return nil, notFound(err)
}
if _, err := compile(patterns); err != nil {
return nil, err
}
if err := s.store.ReplacePatterns(ctx, id, patterns); err != nil {
return nil, err
}
return s.store.Patterns(ctx, id)
}
// PreviewItem — разбор одного файла.
type PreviewItem struct {
RelPath string
PatternIndex *int
Skipped bool
PathFields map[string]string
Tags map[string]string
Result meta.Meta
Error string
}
// Preview применяет шаблоны к выборке файлов без сохранения: из каталога, а до первого скана — из обхода.
func (s *TemplateService) Preview(ctx context.Context, id uuid.UUID, patterns []PatternRow, sample int) ([]PreviewItem, int, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return nil, 0, err
}
src, err := s.store.GetSource(ctx, id)
if err != nil {
return nil, 0, notFound(err)
}
compiled, err := compile(patterns)
if err != nil {
return nil, 0, err
}
sample = min(max(sample, 1), 200)
root, err := s.root(src)
if err != nil {
return nil, 0, err
}
paths, err := s.store.SampleFiles(ctx, id, sample)
if err != nil {
return nil, 0, err
}
if len(paths) == 0 {
found, err := walk(root, func(string) bool { return false })
if err != nil {
return nil, 0, apperr.New(http.StatusConflict, CodeSourceOffline, err.Error())
}
rand.Shuffle(len(found), func(i, j int) { found[i], found[j] = found[j], found[i] })
for _, w := range found[:min(sample, len(found))] {
paths = append(paths, w.rel)
}
}
slices.Sort(paths)
items := make([]PreviewItem, len(paths))
var wg sync.WaitGroup
sem := make(chan struct{}, 8)
for i, rel := range paths {
wg.Add(1)
go func() {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
items[i] = s.previewOne(ctx, root, rel, compiled, src.TagsFirst)
}()
}
wg.Wait()
unmatched := 0
for _, it := range items {
if it.PatternIndex == nil {
unmatched++
}
}
return items, unmatched, nil
}
func (s *TemplateService) previewOne(ctx context.Context, root, rel string, patterns []meta.Pattern, tagsFirst bool) PreviewItem {
it := PreviewItem{RelPath: rel, PathFields: map[string]string{}, Tags: map[string]string{}}
m := meta.MatchPath(patterns, rel)
if m.Index >= 0 {
idx := m.Index
it.PatternIndex = &idx
}
it.Skipped = m.Skip
for k, v := range m.Fields {
it.PathFields[k] = v
}
p, err := s.prober.Probe(ctx, filepath.Join(root, filepath.FromSlash(rel)))
if err != nil {
it.Error = err.Error()
}
for k, v := range map[string]string{
"artist": p.Tags.Artist, "albumartist": p.Tags.AlbumArtist, "album": p.Tags.Album, "title": p.Tags.Title,
"genre": p.Tags.Genre, "year": p.Tags.Year, "track": p.Tags.Track, "disc": p.Tags.Disc,
} {
if v != "" {
it.Tags[k] = v
}
}
it.Result = meta.Merge(p.Tags, meta.FromPath(m.Fields), tagsFirst, rel)
if it.Result.Album == "" {
it.Result.Album = UnknownAlbum
}
return it
}
// templateSampleSize — сколько треков берёт проверка шаблона записи (docs/uploads.md#7).
const templateSampleSize = 50
// SuggestWriteTemplate подбирает шаблон записи по существующим путям и выражениям источника.
func (s *TemplateService) SuggestWriteTemplate(ctx context.Context, id uuid.UUID) (string, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return "", err
}
if _, err := s.store.GetSource(ctx, id); err != nil {
return "", notFound(err)
}
rows, err := s.store.Patterns(ctx, id)
if err != nil {
return "", err
}
var exprs []string
for _, r := range rows {
if r.IsEnabled {
exprs = append(exprs, r.Regex)
}
}
paths, err := s.store.SampleFiles(ctx, id, 200)
if err != nil {
return "", err
}
tpl, err := meta.SuggestTemplate(exprs, paths)
if err != nil {
return "", apperr.New(http.StatusUnprocessableEntity, CodeTemplateNone, "no path pattern can be turned into a template")
}
return tpl, nil
}
// CheckWriteTemplate применяет шаблон к трекам источника и разбирает пути его выражениями обратно.
func (s *TemplateService) CheckWriteTemplate(ctx context.Context, id uuid.UUID, template string) (meta.TemplateCheck, error) {
if err := requirePerm(ctx, auth.PermManageLibrary); err != nil {
return meta.TemplateCheck{}, err
}
if _, err := s.store.GetSource(ctx, id); err != nil {
return meta.TemplateCheck{}, notFound(err)
}
tpl, err := meta.ParseTemplate(template)
if err != nil {
return meta.TemplateCheck{}, apperr.Validation("template", CodeTemplateInvalid, err.Error(), map[string]any{"reason": err.Error()})
}
rows, err := s.store.Patterns(ctx, id)
if err != nil {
return meta.TemplateCheck{}, err
}
compiled, err := compile(rows)
if err != nil {
return meta.TemplateCheck{}, err
}
samples, err := s.store.TemplateSamples(ctx, id, templateSampleSize)
if err != nil {
return meta.TemplateCheck{}, err
}
return meta.CheckTemplate(tpl, compiled, samples), nil
}
+88
View File
@@ -0,0 +1,88 @@
package playback
import (
"context"
"time"
"github.com/google/uuid"
"pipu/api/internal/api/gen"
"pipu/api/internal/auth"
)
// EventService owns event acceptance and its transaction; HTTP only authenticates and maps DTOs.
type EventService struct {
store *Store
now func() time.Time
}
func (s EventService) Accept(ctx context.Context, p auth.Principal, events []gen.PlayEvent) (gen.PostEvents200JSONResponse, error) {
now := s.now()
ids := make([]uuid.UUID, 0, len(events))
for _, e := range events {
ids = append(ids, e.TrackId)
}
durations, err := s.store.TrackDurations(ctx, ids)
if err != nil {
return gen.PostEvents200JSONResponse{}, err
}
clientType := s.store.SessionClientType(ctx, p.SessionID)
out := gen.PostEvents200JSONResponse{}
tx, err := s.store.Begin(ctx)
if err != nil {
return gen.PostEvents200JSONResponse{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
for _, e := range events {
dur, known := durations[e.TrackId]
at := e.OccurredAt.UTC()
if !known || at.Before(now.Add(-maxEventAge)) {
out.Rejected++
continue
}
if at.After(now.Add(maxEventClockSkew)) {
at = now // часы клиента спешат
}
ev := Event{
ID: e.Id, Type: string(e.Type), TrackID: e.TrackId, OccurredAt: at, PositionMs: e.PositionMs,
PlayedMs: e.PlayedMs, ContextID: e.ContextId, WaveSessionID: e.WaveSessionId,
Offline: e.Offline != nil && *e.Offline,
}
if e.ContextType != nil {
ct := string(*e.ContextType)
ev.ContextType = &ct
}
inserted, err := s.store.InsertEvent(ctx, tx, p.UserID, clientType, ev)
if err != nil {
return gen.PostEvents200JSONResponse{}, err
}
if !inserted {
out.Duplicates++
continue
}
out.Accepted++
played := 0
if e.PlayedMs != nil {
played = *e.PlayedMs
}
o := Judge(ev.Type, played, dur)
if o != (Outcome{}) {
if err := s.store.ApplyOutcome(ctx, tx, p.UserID, ev, o); err != nil {
return gen.PostEvents200JSONResponse{}, err
}
}
if outcome := impressionOutcome(ev.Type, o); outcome != "" && ev.ContextType != nil && *ev.ContextType == "wave" &&
ev.ContextID != nil {
if sid, err := uuid.Parse(*ev.ContextID); err == nil {
if err := s.store.MarkImpression(ctx, tx, sid, ev.TrackID, outcome); err != nil {
return gen.PostEvents200JSONResponse{}, err
}
}
}
}
if err := tx.Commit(ctx); err != nil {
return gen.PostEvents200JSONResponse{}, err
}
return out, nil
}
+7 -104
View File
@@ -34,11 +34,11 @@ const (
)
// Handler реализует playback- и collection-части gen.StrictServerInterface,
// а также library.Personalizer (ссылки на стрим и реакции в треках).
// персонализация каталога вынесена в Personalizer.
type Handler struct {
store *Store
catalog *library.Store
dto func() library.DTO
dto library.DTO
signer *sign.Signer
transcoder *Transcoder
// RootFor — каталог хранилища в файловой системе api (для отдачи файлов без nginx и транскода).
@@ -48,8 +48,8 @@ type Handler struct {
now func() time.Time
}
// NewHandler создаёт обработчик. dto — DTO каталога с персонализацией (замыкание: DTO ссылается на сам Handler).
func NewHandler(store *Store, catalog *library.Store, dto func() library.DTO, signer *sign.Signer, tr *Transcoder,
// NewHandler создаёт обработчик. dto — независимо собранный DTO каталога с персонализацией.
func NewHandler(store *Store, catalog *library.Store, dto library.DTO, signer *sign.Signer, tr *Transcoder,
rootFor func(context.Context, uuid.UUID) (string, error), xAccel bool, log *slog.Logger,
) *Handler {
return &Handler{
@@ -66,34 +66,6 @@ func principal(ctx context.Context) (auth.Principal, error) {
return p, nil
}
// Personalize реализует library.Personalizer.
func (h *Handler) Personalize(ctx context.Context, rows []library.TrackRow, out []gen.Track) error {
p, ok := auth.PrincipalFrom(ctx)
if !ok {
return nil
}
ids := make([]uuid.UUID, len(rows))
for i, r := range rows {
ids[i] = r.ID
}
reactions, err := h.store.Reactions(ctx, p.UserID, ids)
if err != nil {
return err
}
now := h.now()
for i := range out {
if out[i].Available {
u := StreamURL(h.signer, p.UserID, rows[i].ID, now)
out[i].StreamUrl = &u
}
if r, ok := reactions[rows[i].ID]; ok {
rr := gen.Reaction(r)
out[i].Reaction = &rr
}
}
return nil
}
// --- стрим ---
// StreamTrack реализует gen.StrictServerInterface.
@@ -236,7 +208,7 @@ func (h *Handler) GetTracksBatch(ctx context.Context, req gen.GetTracksBatchRequ
if err != nil {
return nil, err
}
items, err := h.dto().Tracks(ctx, rows)
items, err := h.dto.Tracks(ctx, rows)
if err != nil {
return nil, err
}
@@ -251,74 +223,7 @@ func (h *Handler) PostEvents(ctx context.Context, req gen.PostEventsRequestObjec
if err != nil {
return nil, err
}
now := h.now()
ids := make([]uuid.UUID, 0, len(req.Body.Events))
for _, e := range req.Body.Events {
ids = append(ids, e.TrackId)
}
durations, err := h.store.TrackDurations(ctx, ids)
if err != nil {
return nil, err
}
clientType := h.store.SessionClientType(ctx, p.SessionID)
out := gen.PostEvents200JSONResponse{}
tx, err := h.store.Begin(ctx)
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback(ctx) }()
for _, e := range req.Body.Events {
dur, known := durations[e.TrackId]
at := e.OccurredAt.UTC()
if !known || at.Before(now.Add(-maxEventAge)) {
out.Rejected++
continue
}
if at.After(now.Add(maxEventClockSkew)) {
at = now // часы клиента спешат
}
ev := Event{
ID: e.Id, Type: string(e.Type), TrackID: e.TrackId, OccurredAt: at, PositionMs: e.PositionMs,
PlayedMs: e.PlayedMs, ContextID: e.ContextId, WaveSessionID: e.WaveSessionId,
Offline: e.Offline != nil && *e.Offline,
}
if e.ContextType != nil {
ct := string(*e.ContextType)
ev.ContextType = &ct
}
inserted, err := h.store.InsertEvent(ctx, tx, p.UserID, clientType, ev)
if err != nil {
return nil, err
}
if !inserted {
out.Duplicates++
continue
}
out.Accepted++
played := 0
if e.PlayedMs != nil {
played = *e.PlayedMs
}
o := Judge(ev.Type, played, dur)
if o != (Outcome{}) {
if err := h.store.ApplyOutcome(ctx, tx, p.UserID, ev, o); err != nil {
return nil, err
}
}
if outcome := impressionOutcome(ev.Type, o); outcome != "" && ev.ContextType != nil && *ev.ContextType == "wave" &&
ev.ContextID != nil {
if sid, err := uuid.Parse(*ev.ContextID); err == nil {
if err := h.store.MarkImpression(ctx, tx, sid, ev.TrackID, outcome); err != nil {
return nil, err
}
}
}
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return out, nil
return (EventService{store: h.store, now: h.now}).Accept(ctx, p, req.Body.Events)
}
// --- состояние плеера ---
@@ -441,7 +346,7 @@ func (h *Handler) hydrate(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]g
if err != nil {
return nil, err
}
dtos, err := h.dto().Tracks(ctx, rows)
dtos, err := h.dto.Tracks(ctx, rows)
if err != nil {
return nil, err
}
@@ -591,8 +496,6 @@ func (h *Handler) ClearTrackReaction(ctx context.Context, req gen.ClearTrackReac
return gen.ClearTrackReaction204Response{}, nil
}
var _ library.Personalizer = (*Handler)(nil)
// impressionOutcome — исход показа волны по событию: complete | skip_early | skip | like | dislike.
func impressionOutcome(eventType string, o Outcome) string {
switch {
@@ -0,0 +1,58 @@
package playback
import (
"context"
"time"
"github.com/google/uuid"
"pipu/api/internal/api/gen"
"pipu/api/internal/auth"
"pipu/api/internal/library"
"pipu/api/internal/platform/sign"
)
type ReactionReader interface {
Reactions(context.Context, uuid.UUID, []uuid.UUID) (map[uuid.UUID]string, error)
}
// Personalizer decorates catalog DTOs independently of HTTP handlers.
type Personalizer struct {
store ReactionReader
signer *sign.Signer
now func() time.Time
}
var _ library.Personalizer = (*Personalizer)(nil)
func NewPersonalizer(store ReactionReader, signer *sign.Signer) *Personalizer {
return &Personalizer{store: store, signer: signer, now: func() time.Time { return time.Now().UTC() }}
}
// Personalize реализует library.Personalizer.
func (h *Personalizer) Personalize(ctx context.Context, rows []library.TrackRow, out []gen.Track) error {
p, ok := auth.PrincipalFrom(ctx)
if !ok {
return nil
}
ids := make([]uuid.UUID, len(rows))
for i, r := range rows {
ids[i] = r.ID
}
reactions, err := h.store.Reactions(ctx, p.UserID, ids)
if err != nil {
return err
}
now := h.now()
for i := range out {
if out[i].Available {
u := StreamURL(h.signer, p.UserID, rows[i].ID, now)
out[i].StreamUrl = &u
}
if r, ok := reactions[rows[i].ID]; ok {
rr := gen.Reaction(r)
out[i].Reaction = &rr
}
}
return nil
}
@@ -0,0 +1,55 @@
package playback
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"pipu/api/internal/api/gen"
"pipu/api/internal/auth"
"pipu/api/internal/library"
"pipu/api/internal/platform/sign"
)
type reactionReaderFunc func(context.Context, uuid.UUID, []uuid.UUID) (map[uuid.UUID]string, error)
func (f reactionReaderFunc) Reactions(ctx context.Context, user uuid.UUID, ids []uuid.UUID) (map[uuid.UUID]string, error) {
return f(ctx, user, ids)
}
func TestPersonalizerBatch(t *testing.T) {
user, first, second := uuid.New(), uuid.New(), uuid.New()
calls := 0
reader := reactionReaderFunc(func(_ context.Context, got uuid.UUID, ids []uuid.UUID) (map[uuid.UUID]string, error) {
calls++
require.Equal(t, user, got)
require.Equal(t, []uuid.UUID{first, second}, ids)
return map[uuid.UUID]string{second: "dislike"}, nil
})
signer, err := sign.New("")
require.NoError(t, err)
p := NewPersonalizer(reader, signer)
now := time.Now().UTC()
p.now = func() time.Time { return now }
rows := []library.TrackRow{{ID: first}, {ID: second}}
out := []gen.Track{{Available: true}, {Available: false}}
require.NoError(t, p.Personalize(context.Background(), rows, out))
require.Zero(t, calls, "anonymous catalog does not query personal data")
ctx := auth.WithPrincipal(context.Background(), auth.Principal{UserID: user})
require.NoError(t, p.Personalize(ctx, rows, out))
require.Equal(t, 1, calls, "one reaction query for the entire batch")
require.Equal(t, StreamURL(signer, user, first, now), *out[0].StreamUrl)
require.Nil(t, out[1].StreamUrl, "unavailable tracks must not receive stream links")
require.Equal(t, gen.Reaction("dislike"), *out[1].Reaction)
}
func TestPersonalizerReadFailure(t *testing.T) {
failure := errors.New("database unavailable")
p := NewPersonalizer(reactionReaderFunc(func(context.Context, uuid.UUID, []uuid.UUID) (map[uuid.UUID]string, error) { return nil, failure }), nil)
ctx := auth.WithPrincipal(context.Background(), auth.Principal{UserID: uuid.New()})
require.ErrorIs(t, p.Personalize(ctx, nil, nil), failure)
}
+1 -1
View File
@@ -92,7 +92,7 @@ func (h *Handler) playlist(ctx context.Context, user, id uuid.UUID) (gen.Playlis
if err != nil {
return out, err
}
dtos, err := h.dto().Tracks(ctx, tracks)
dtos, err := h.dto.Tracks(ctx, tracks)
if err != nil {
return out, err
}
@@ -42,7 +42,7 @@ func TestPlaylistPersistenceAndIsolation(t *testing.T) {
require.NoError(t, err)
defer pool.Exec(ctx, `DELETE FROM tracks WHERE id=ANY($1)`, []uuid.UUID{first, second})
st := NewStore(pool)
h := &Handler{store: st, catalog: library.NewStore(pool), dto: func() library.DTO { return library.DTO{} }}
h := &Handler{store: st, catalog: library.NewStore(pool), dto: library.DTO{}}
require.NoError(t, st.savePlaylist(ctx, owner, id, " Mix ", "Description", []uuid.UUID{first, second}, 0, true))
got, err := h.playlist(ctx, owner, id)
require.NoError(t, err)
@@ -0,0 +1,99 @@
package uploads
import (
"context"
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// ChangeStatus deliberately does not expose pgx to use cases.
func (st *Store) ChangeStatus(ctx context.Context, id uuid.UUID, from []Status, to Status) error {
return st.Transition(ctx, id, from, to, nil)
}
// UpdateMetadata uses one guarded UPDATE; a concurrent decision is reported to the caller.
func (st *Store) UpdateMetadata(ctx context.Context, id uuid.UUID, m Meta, edited bool, pl placement) error {
raw, err := json.Marshal(m)
if err != nil {
return err
}
result, err := st.pool.Exec(ctx, `UPDATE upload_files SET metadata=$2, metadata_edited=$3, target_source_id=$4,
target_rel_path=$5, status_reason=$6, matched_artist_id=$7, matched_album_id=$8, updated_at=now()
WHERE id=$1 AND status IN ('pending_review','import_failed')`,
id, raw, edited, pl.SourceID, pl.RelPath, nullable(pl.Reason), pl.ArtistID, pl.AlbumID)
if err != nil {
return fmt.Errorf("uploads: update: %w", err)
}
if result.RowsAffected() != 1 {
return ErrWrongStatus
}
return nil
}
// Decide keeps quota release, status and reviewer metadata in the same transaction.
func (st *Store) Decide(ctx context.Context, id, reviewer uuid.UUID, approve bool, reason string) error {
from, to := []Status{StatusPendingReview, StatusImportFailed}, StatusRejected
if approve {
from, to, reason = []Status{StatusPendingReview}, StatusApproved, ""
}
return st.Transition(ctx, id, from, to, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE upload_files SET reviewed_by=$2, reviewed_at=now(), status_reason=$3 WHERE id=$1`, id, reviewer, nullable(reason))
return err
})
}
func (st *Store) FailImport(ctx context.Context, id uuid.UUID, reason string) error {
return st.Transition(ctx, id, []Status{StatusImporting}, StatusImportFailed, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE upload_files SET status_reason=$2 WHERE id=$1`, id, reason)
return err
})
}
func (st *Store) CompleteImport(ctx context.Context, id, sourceID uuid.UUID, rel string, mediaFileID uuid.UUID) error {
return st.Transition(ctx, id, []Status{StatusImporting}, StatusImported, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `UPDATE upload_files SET target_source_id=$2, target_rel_path=$3 WHERE id=$1`, id, sourceID, rel); err != nil {
return err
}
return MarkImported(ctx, tx, id, mediaFileID)
})
}
func (st *Store) ResetImporting(ctx context.Context) error {
_, err := st.pool.Exec(ctx, `UPDATE upload_files SET status='approved', updated_at=now() WHERE status='importing'`)
return err
}
func (st *Store) SaveOutcome(ctx context.Context, f File, o outcome) error {
return st.Transition(ctx, f.ID, []Status{StatusProcessing}, o.status, func(tx pgx.Tx) error {
var (
tags, metaJSON []byte
points []int32
)
if o.tags != nil {
tags, _ = json.Marshal(o.tags)
}
if o.meta != nil {
metaJSON, _ = json.Marshal(o.meta)
}
if o.print != nil {
points = make([]int32, len(o.print.Points))
for i, p := range o.print.Points {
points[i] = int32(p)
}
}
p := o.probe
_, err := tx.Exec(ctx, `
UPDATE upload_files SET sha256 = coalesce($2, sha256), format = NULLIF($3, ''), codec = NULLIF($4, ''),
bitrate = NULLIF($5, 0), sample_rate = NULLIF($6, 0), bit_depth = NULLIF($7, 0), duration_ms = NULLIF($8, 0),
tags = $9, metadata = $10, fingerprint = $11, duplicate_of_track_id = $12, duplicate_level = NULLIF($13, ''),
possible_duplicate = $14, quality_upgrade = $20, target_source_id = $15, target_rel_path = $16, status_reason = NULLIF($17, ''),
matched_artist_id = $18, matched_album_id = $19
WHERE id = $1`,
f.ID, o.sha, p.Format, p.Codec, p.Bitrate, p.SampleRate, p.BitDepth, p.DurationMs, tags, metaJSON, points,
o.dupTrack, o.dupLevel, o.possible, o.place.SourceID, o.place.RelPath, o.reason, o.place.ArtistID, o.place.AlbumID, o.quality)
return err
})
}
+131
View File
@@ -0,0 +1,131 @@
package uploads
import (
"context"
"errors"
"github.com/google/uuid"
"pipu/api/internal/library"
"pipu/api/internal/library/meta"
)
// Ports are owned by the upload use cases; implementations remain in library.
type SourceCatalog interface {
GetSource(context.Context, uuid.UUID) (library.Source, error)
ListSources(context.Context) ([]library.Source, error)
Patterns(context.Context, uuid.UUID) ([]library.PatternRow, error)
}
type RootResolver interface {
Root(library.Source) (string, error)
}
type ImportedScanner interface {
ScanFile(context.Context, library.Source, string, string) (uuid.UUID, error)
}
type PlacementStore interface {
Settings(context.Context) (Settings, error)
MatchCatalog(context.Context, string, string) (*uuid.UUID, *uuid.UUID, int, error)
BatchMaxDisc(context.Context, uuid.UUID, string) (int, error)
}
type PlacementPlanner struct {
store PlacementStore
lib SourceCatalog
roots RootResolver
}
// --- Раскладка в хранилище ---
// placement — куда ляжет файл; Reason — почему не получится (код), путь тогда nil.
type placement struct {
SourceID *uuid.UUID
RelPath *string
Reason string
ArtistID *uuid.UUID
AlbumID *uuid.UUID
src library.Source
root string
}
// pickSource — хранилище: выбранное админом → по умолчанию → единственное принимающее загрузки.
func (s *PlacementPlanner) pickSource(ctx context.Context, chosen *uuid.UUID) (library.Source, string) {
id := chosen
if id == nil {
st, err := s.store.Settings(ctx)
if err == nil {
id = st.DefaultSourceID
}
}
if id != nil {
src, err := s.lib.GetSource(ctx, *id)
if err != nil || !src.AcceptsUploads {
return library.Source{}, CodeNoTarget
}
return src, ""
}
sources, err := s.lib.ListSources(ctx)
if err != nil {
return library.Source{}, CodeNoTarget
}
var found []library.Source
for _, src := range sources {
if src.AcceptsUploads {
found = append(found, src)
}
}
if len(found) != 1 {
return library.Source{}, CodeNoTarget
}
return found[0], ""
}
// plan считает целевой путь по write_template хранилища; существующие папки исполнителя / альбома
// переиспользуются в их написании (docs/uploads.md#очистка-имён).
func (s *PlacementPlanner) plan(ctx context.Context, f File, m Meta, chosen *uuid.UUID) placement {
var (
pl placement
discs int // дисков в альбоме: в каталоге, в пачке, у самого файла
)
if artist, album, maxDisc, err := s.store.MatchCatalog(ctx, meta.Key(m.AlbumArtist), meta.Key(m.Album)); err == nil {
pl.ArtistID, pl.AlbumID, discs = artist, album, maxDisc
}
src, reason := s.pickSource(ctx, chosen)
if reason != "" {
pl.Reason = reason
return pl
}
pl.SourceID, pl.src = &src.ID, src
if src.WriteTemplate == nil {
pl.Reason = CodeTemplate
return pl
}
tpl, err := meta.ParseTemplate(*src.WriteTemplate)
if err != nil {
pl.Reason = CodeTemplate
return pl
}
if n, err := s.store.BatchMaxDisc(ctx, f.BatchID, m.Album); err == nil {
discs = max(discs, n)
}
if m.Disc != nil {
discs = max(discs, *m.Disc)
}
rel, err := tpl.Render(meta.TemplateInput{Fields: m.Fields(), DiscCount: discs, Ext: extFor(f)})
if err != nil {
var mf *meta.MissingFieldError
if errors.As(err, &mf) {
pl.Reason = CodeMissingField
} else {
pl.Reason = CodeTemplate
}
return pl
}
root, err := s.roots.Root(src)
if err != nil {
pl.Reason = CodeNoTarget
return pl
}
rel = reuseExisting(root, rel)
pl.RelPath, pl.root = &rel, root
return pl
}
+13 -123
View File
@@ -3,9 +3,7 @@ package uploads
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"path"
@@ -14,7 +12,6 @@ import (
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"pipu/api/internal/auth"
"pipu/api/internal/library"
@@ -30,10 +27,10 @@ type Config struct {
// Service — очередь на добавление.
type Service struct {
store *Store
lib *library.Store
libSvc *library.Service
scanner *library.Scanner
store *Store
lib SourceCatalog
*PlacementPlanner
scanner ImportedScanner
agent library.Agent
prober library.Prober
fpcalc library.FPCalc
@@ -46,10 +43,10 @@ type Service struct {
}
// NewService создаёт сервис очереди.
func NewService(store *Store, lib *library.Store, libSvc *library.Service, scanner *library.Scanner, agent library.Agent,
func NewService(store *Store, lib SourceCatalog, roots RootResolver, scanner ImportedScanner, agent library.Agent,
prober library.Prober, fpcalc library.FPCalc, cfg Config, log *slog.Logger) *Service {
return &Service{
store: store, lib: lib, libSvc: libSvc, scanner: scanner, agent: agent, prober: prober, fpcalc: fpcalc, cfg: cfg,
store: store, lib: lib, PlacementPlanner: &PlacementPlanner{store: store, lib: lib, roots: roots}, scanner: scanner, agent: agent, prober: prober, fpcalc: fpcalc, cfg: cfg,
log: log, wakeProcess: make(chan struct{}, 1), wakeImport: make(chan struct{}, 1),
now: func() time.Time { return time.Now().UTC() },
}
@@ -233,7 +230,7 @@ func cleanClientPath(p *string) *string {
// Complete — tus принял файл целиком: в обработку.
func (s *Service) Complete(ctx context.Context, f File) error {
err := s.store.Transition(ctx, f.ID, []Status{StatusUploading}, StatusProcessing, nil)
err := s.store.ChangeStatus(ctx, f.ID, []Status{StatusUploading}, StatusProcessing)
if err == nil {
wake(s.wakeProcess)
}
@@ -279,7 +276,7 @@ func (s *Service) Withdraw(ctx context.Context, id uuid.UUID) error {
if err != nil || f.AuthorID != p.UserID {
return apperr.NotFound(CodeNotFound, "upload not found")
}
if err := s.store.Transition(ctx, id, []Status{StatusUploading, StatusProcessing, StatusPendingReview}, StatusWithdrawn, nil); err != nil {
if err := s.store.ChangeStatus(ctx, id, []Status{StatusUploading, StatusProcessing, StatusPendingReview}, StatusWithdrawn); err != nil {
return notFound(err)
}
s.removeStaging(f)
@@ -324,14 +321,8 @@ func (s *Service) Update(ctx context.Context, id uuid.UUID, in UpdateInput) (Fil
target = in.TargetSourceID
}
pl := s.plan(ctx, f, m, target)
raw, _ := json.Marshal(m)
_, err = s.store.pool.Exec(ctx, `
UPDATE upload_files SET metadata = $2, metadata_edited = $3, target_source_id = $4, target_rel_path = $5,
status_reason = $6, matched_artist_id = $7, matched_album_id = $8, updated_at = now()
WHERE id = $1 AND status IN ('pending_review', 'import_failed')`,
id, raw, edited, pl.SourceID, pl.RelPath, nullable(pl.Reason), pl.ArtistID, pl.AlbumID)
if err != nil {
return File{}, fmt.Errorf("uploads: update: %w", err)
if err := s.store.UpdateMetadata(ctx, id, m, edited, pl); err != nil {
return File{}, notFound(err)
}
return s.store.File(ctx, id)
}
@@ -385,13 +376,8 @@ func (s *Service) reviewOne(ctx context.Context, reviewer, id uuid.UUID, approve
if err != nil {
return notFound(err)
}
mark := func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE upload_files SET reviewed_by = $2, reviewed_at = now(), status_reason = $3 WHERE id = $1`,
id, reviewer, nullable(reason))
return err
}
if !approve {
if err := s.store.Transition(ctx, id, []Status{StatusPendingReview, StatusImportFailed}, StatusRejected, mark); err != nil {
if err := s.store.Decide(ctx, id, reviewer, false, reason); err != nil {
return notFound(err)
}
s.removeStaging(f)
@@ -406,7 +392,7 @@ func (s *Service) reviewOne(ctx context.Context, reviewer, id uuid.UUID, approve
return apperr.Conflict(pl.Reason, "cannot place the file into a storage")
}
reason = ""
if err := s.store.Transition(ctx, id, []Status{StatusPendingReview}, StatusApproved, mark); err != nil {
if err := s.store.Decide(ctx, id, reviewer, true, reason); err != nil {
return notFound(err)
}
s.store.Audit(ctx, &reviewer, "upload.approve", id, map[string]any{"target": pl.RelPath})
@@ -418,7 +404,7 @@ func (s *Service) Retry(ctx context.Context, id uuid.UUID) (File, error) {
if _, err := principal(ctx, auth.PermReviewUploads); err != nil {
return File{}, err
}
if err := s.store.Transition(ctx, id, []Status{StatusImportFailed}, StatusApproved, nil); err != nil {
if err := s.store.ChangeStatus(ctx, id, []Status{StatusImportFailed}, StatusApproved); err != nil {
return File{}, notFound(err)
}
wake(s.wakeImport)
@@ -495,102 +481,6 @@ func (s *Service) UpdateSettings(ctx context.Context, in SettingsInput) (Setting
return st, nil
}
// --- Раскладка в хранилище ---
// placement — куда ляжет файл; Reason — почему не получится (код), путь тогда nil.
type placement struct {
SourceID *uuid.UUID
RelPath *string
Reason string
ArtistID *uuid.UUID
AlbumID *uuid.UUID
src library.Source
root string
}
// pickSource — хранилище: выбранное админом → по умолчанию → единственное принимающее загрузки.
func (s *Service) pickSource(ctx context.Context, chosen *uuid.UUID) (library.Source, string) {
id := chosen
if id == nil {
st, err := s.store.Settings(ctx)
if err == nil {
id = st.DefaultSourceID
}
}
if id != nil {
src, err := s.lib.GetSource(ctx, *id)
if err != nil || !src.AcceptsUploads {
return library.Source{}, CodeNoTarget
}
return src, ""
}
sources, err := s.lib.ListSources(ctx)
if err != nil {
return library.Source{}, CodeNoTarget
}
var found []library.Source
for _, src := range sources {
if src.AcceptsUploads {
found = append(found, src)
}
}
if len(found) != 1 {
return library.Source{}, CodeNoTarget
}
return found[0], ""
}
// plan считает целевой путь по write_template хранилища; существующие папки исполнителя / альбома
// переиспользуются в их написании (docs/uploads.md#очистка-имён).
func (s *Service) plan(ctx context.Context, f File, m Meta, chosen *uuid.UUID) placement {
var (
pl placement
discs int // дисков в альбоме: в каталоге, в пачке, у самого файла
)
if artist, album, maxDisc, err := s.store.MatchCatalog(ctx, meta.Key(m.AlbumArtist), meta.Key(m.Album)); err == nil {
pl.ArtistID, pl.AlbumID, discs = artist, album, maxDisc
}
src, reason := s.pickSource(ctx, chosen)
if reason != "" {
pl.Reason = reason
return pl
}
pl.SourceID, pl.src = &src.ID, src
if src.WriteTemplate == nil {
pl.Reason = CodeTemplate
return pl
}
tpl, err := meta.ParseTemplate(*src.WriteTemplate)
if err != nil {
pl.Reason = CodeTemplate
return pl
}
if n, err := s.store.BatchMaxDisc(ctx, f.BatchID, m.Album); err == nil {
discs = max(discs, n)
}
if m.Disc != nil {
discs = max(discs, *m.Disc)
}
rel, err := tpl.Render(meta.TemplateInput{Fields: m.Fields(), DiscCount: discs, Ext: extFor(f)})
if err != nil {
var mf *meta.MissingFieldError
if errors.As(err, &mf) {
pl.Reason = CodeMissingField
} else {
pl.Reason = CodeTemplate
}
return pl
}
root, err := s.libSvc.Root(src)
if err != nil {
pl.Reason = CodeNoTarget
return pl
}
rel = reuseExisting(root, rel)
pl.RelPath, pl.root = &rel, root
return pl
}
// extFor — расширение по реальному формату (кодек из ffprobe), иначе — по имени файла.
func extFor(f File) string {
orig := strings.TrimPrefix(strings.ToLower(path.Ext(f.OriginalName)), ".")
+6 -49
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
@@ -17,7 +16,6 @@ import (
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"pipu/api/internal/library"
"pipu/api/internal/library/meta"
@@ -114,7 +112,7 @@ type outcome struct {
func (s *Service) process(ctx context.Context, f File) error {
abs := s.stagingAbs(f.StagingPath)
o := s.analyze(ctx, f, abs)
if err := s.saveOutcome(ctx, f, o); err != nil {
if err := s.store.SaveOutcome(ctx, f, o); err != nil {
return err
}
if o.status != StatusPendingReview {
@@ -256,38 +254,6 @@ func (s *Service) sourcePatterns(ctx context.Context, id uuid.UUID) []meta.Patte
return patterns
}
func (s *Service) saveOutcome(ctx context.Context, f File, o outcome) error {
return s.store.Transition(ctx, f.ID, []Status{StatusProcessing}, o.status, func(tx pgx.Tx) error {
var (
tags, metaJSON []byte
points []int32
)
if o.tags != nil {
tags, _ = json.Marshal(o.tags)
}
if o.meta != nil {
metaJSON, _ = json.Marshal(o.meta)
}
if o.print != nil {
points = make([]int32, len(o.print.Points))
for i, p := range o.print.Points {
points[i] = int32(p)
}
}
p := o.probe
_, err := tx.Exec(ctx, `
UPDATE upload_files SET sha256 = coalesce($2, sha256), format = NULLIF($3, ''), codec = NULLIF($4, ''),
bitrate = NULLIF($5, 0), sample_rate = NULLIF($6, 0), bit_depth = NULLIF($7, 0), duration_ms = NULLIF($8, 0),
tags = $9, metadata = $10, fingerprint = $11, duplicate_of_track_id = $12, duplicate_level = NULLIF($13, ''),
possible_duplicate = $14, quality_upgrade = $20, target_source_id = $15, target_rel_path = $16, status_reason = NULLIF($17, ''),
matched_artist_id = $18, matched_album_id = $19
WHERE id = $1`,
f.ID, o.sha, p.Format, p.Codec, p.Bitrate, p.SampleRate, p.BitDepth, p.DurationMs, tags, metaJSON, points,
o.dupTrack, o.dupLevel, o.possible, o.place.SourceID, o.place.RelPath, o.reason, o.place.ArtistID, o.place.AlbumID, o.quality)
return err
})
}
// --- Импорт ---
// importNext импортирует один одобренный файл; false — работы нет.
@@ -300,17 +266,14 @@ func (s *Service) importNext(ctx context.Context) bool {
s.log.Error("uploads: next to import", "err", err)
return false
}
if err := s.store.Transition(ctx, f.ID, []Status{StatusApproved}, StatusImporting, nil); err != nil {
if err := s.store.ChangeStatus(ctx, f.ID, []Status{StatusApproved}, StatusImporting); err != nil {
// Файл успели отклонить — берём следующий; сбой БД — ждём тика.
return errors.Is(err, ErrWrongStatus)
}
if err := s.importFile(ctx, f); err != nil {
s.log.Warn("upload import failed", "upload_id", f.ID, "err", err)
msg := err.Error()
if ferr := s.store.Transition(ctx, f.ID, []Status{StatusImporting}, StatusImportFailed, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE upload_files SET status_reason = $2 WHERE id = $1`, f.ID, CodeImportFailed+": "+msg)
return err
}); ferr != nil {
if ferr := s.store.FailImport(ctx, f.ID, CodeImportFailed+": "+msg); ferr != nil {
s.log.Error("uploads: mark import failed", "upload_id", f.ID, "err", ferr)
}
}
@@ -360,13 +323,7 @@ func (s *Service) importFile(ctx context.Context, f File) error {
if err != nil {
return fmt.Errorf("scan: %w", err)
}
if err := s.store.Transition(ctx, f.ID, []Status{StatusImporting}, StatusImported, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `UPDATE upload_files SET target_source_id = $2, target_rel_path = $3 WHERE id = $1`,
f.ID, pl.src.ID, rel); err != nil {
return err
}
return MarkImported(ctx, tx, f.ID, fileID)
}); err != nil {
if err := s.store.CompleteImport(ctx, f.ID, pl.src.ID, rel, fileID); err != nil {
return err
}
s.removeStaging(f)
@@ -439,7 +396,7 @@ func (s *Service) expire(ctx context.Context) {
if err != nil {
continue
}
if err := s.store.Transition(ctx, id, []Status{StatusUploading}, StatusExpired, nil); err == nil {
if err := s.store.ChangeStatus(ctx, id, []Status{StatusUploading}, StatusExpired); err == nil {
s.removeStaging(f)
}
}
@@ -447,7 +404,7 @@ func (s *Service) expire(ctx context.Context) {
// reconcile при старте: прерванный импорт — снова в approved; осиротевшие файлы staging удаляются.
func (s *Service) reconcile(ctx context.Context) {
if _, err := s.store.pool.Exec(ctx, `UPDATE upload_files SET status = 'approved', updated_at = now() WHERE status = 'importing'`); err != nil {
if err := s.store.ResetImporting(ctx); err != nil {
s.log.Error("uploads: reset importing", "err", err)
}
inUse, err := s.store.StagingInUse(ctx)
+1 -1
View File
@@ -61,7 +61,7 @@ func (h *Handler) GetOnboarding(ctx context.Context, _ gen.GetOnboardingRequestO
artists = append(artists, a)
}
rows.Close()
dto := h.dto()
dto := h.dto
for _, a := range artists {
item := struct {
CoverColors []string `json:"cover_colors"`
+3 -3
View File
@@ -139,14 +139,14 @@ type Handler struct {
pool *pgxpool.Pool
rec *Recommender
catalog *library.Store
dto func() library.DTO
dto library.DTO
log *slog.Logger
// Warm заранее готовит транскоды выданной пачки (docs/playback.md).
Warm func(ctx context.Context, trackIDs []uuid.UUID)
}
// NewHandler создаёт обработчик.
func NewHandler(pool *pgxpool.Pool, rec *Recommender, catalog *library.Store, dto func() library.DTO, log *slog.Logger) *Handler {
func NewHandler(pool *pgxpool.Pool, rec *Recommender, catalog *library.Store, dto library.DTO, log *slog.Logger) *Handler {
return &Handler{pool: pool, rec: rec, catalog: catalog, dto: dto, log: log}
}
@@ -323,7 +323,7 @@ func (h *Handler) serve(ctx context.Context, s session, fb []Feedback) (gen.Wave
if err != nil {
return gen.WaveBatch{}, err
}
tracks, err := h.dto().Tracks(ctx, rows)
tracks, err := h.dto.Tracks(ctx, rows)
if err != nil {
return gen.WaveBatch{}, err
}