- feat(storage): libraries table (name, path); audio_files points at a library
by id instead of repeating the root path; migration 0005 for both drivers
turns every existing root into a library and keeps file ids, tracks and the
missing flag
- feat(library): Libraries service validates names and paths: absolute, an
existing directory, never the filesystem root, never inside or around
another library (checked on real paths, so symlinks cannot hide an overlap)
- feat(api): admin-only GET/POST /libraries, PATCH/DELETE /libraries/{id} and
POST /libraries/{id}/scan; deleting a library drops its index entries and
keeps tracks and listening history
- feat(library): the scanner and the scan manager work on libraries; scanning
with no libraries answers 409 no_libraries
- feat(streaming): the library directory comes from the database instead of
a configured list of roots
- breaking(config): library.roots is removed; an old config fails with a hint
to use POST /api/v1/libraries
- test: CRUD and duplicates on both databases, path change keeps files,
upgrade of a database written before libraries existed
136 lines
3.6 KiB
Go
136 lines
3.6 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
|
|
httpapi "codeberg.org/squidd/sonda/internal/api/http"
|
|
"codeberg.org/squidd/sonda/internal/auth"
|
|
"codeberg.org/squidd/sonda/internal/config"
|
|
"codeberg.org/squidd/sonda/internal/library"
|
|
"codeberg.org/squidd/sonda/internal/listening"
|
|
"codeberg.org/squidd/sonda/internal/storage"
|
|
"codeberg.org/squidd/sonda/internal/streaming"
|
|
"codeberg.org/squidd/sonda/migrations"
|
|
)
|
|
|
|
const defaultConfigFile = "sonda.toml"
|
|
|
|
func main() {
|
|
if err := run(); err != nil {
|
|
fmt.Fprintln(os.Stderr, "sondad:", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run() error {
|
|
configPath := flag.String("config", "", "path to the TOML config file (default ./"+defaultConfigFile+" if present)")
|
|
flag.Parse()
|
|
|
|
path := *configPath
|
|
if path == "" {
|
|
if _, err := os.Stat(defaultConfigFile); err == nil {
|
|
path = defaultConfigFile
|
|
}
|
|
}
|
|
|
|
cfg, err := config.Load(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := cfg.Validate(); err != nil {
|
|
return fmt.Errorf("invalid config: %w", err)
|
|
}
|
|
|
|
logger, err := newLogger(cfg.Log.Env)
|
|
if err != nil {
|
|
return fmt.Errorf("create logger: %w", err)
|
|
}
|
|
defer func() { _ = logger.Sync() }()
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
target := cfg.Database.Path
|
|
if cfg.Database.Driver == storage.DriverPostgres {
|
|
target = cfg.Database.DSN
|
|
}
|
|
db, err := storage.Open(cfg.Database.Driver, target)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
|
|
dbMigrations, err := migrations.For(cfg.Database.Driver)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := storage.Migrate(ctx, db, dbMigrations); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Composition root: build services and hand them to the HTTP layer.
|
|
tokens := auth.NewTokenIssuer(cfg.Auth.JWTSecret, cfg.Auth.AccessTTL())
|
|
if cfg.Log.Env == "production" {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
libraryRepo := storage.NewLibraryRepo(db)
|
|
if err := libraryRepo.RefreshMatchKeys(ctx); err != nil {
|
|
return err
|
|
}
|
|
scanner := library.NewScanner(libraryRepo, library.TaglibReader{}, library.NewHub(), cfg.Library.ScanWorkers)
|
|
scans := library.NewManager(scanner, libraryRepo)
|
|
logScanResults(logger, scans)
|
|
|
|
router := httpapi.NewRouter(httpapi.Deps{
|
|
Logger: logger,
|
|
Auth: auth.NewService(storage.NewUserRepo(db), storage.NewRefreshRepo(db), tokens, cfg.Auth.RefreshTTL()),
|
|
Tokens: tokens,
|
|
Listening: listening.NewService(storage.NewListeningRepo(db)),
|
|
Scan: scanControl{ctx: ctx, m: scans},
|
|
Libraries: library.NewLibraries(libraryRepo),
|
|
Streams: streaming.NewService(libraryRepo),
|
|
})
|
|
|
|
// No WriteTimeout: audio streaming (later) needs long responses.
|
|
srv := &http.Server{
|
|
Addr: cfg.Server.Listen,
|
|
Handler: router,
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
IdleTimeout: 2 * time.Minute,
|
|
}
|
|
|
|
logger.Info("sondad starting",
|
|
zap.String("config", path),
|
|
zap.String("env", cfg.Log.Env),
|
|
zap.String("listen", cfg.Server.Listen),
|
|
zap.String("database_driver", cfg.Database.Driver), // never log the DSN: it holds the password
|
|
)
|
|
|
|
serveErr := make(chan error, 1)
|
|
go func() { serveErr <- srv.ListenAndServe() }()
|
|
|
|
select {
|
|
case err := <-serveErr:
|
|
return fmt.Errorf("http server: %w", err)
|
|
case <-ctx.Done():
|
|
logger.Info("shutting down")
|
|
}
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
return fmt.Errorf("shutdown: %w", err)
|
|
}
|
|
return nil
|
|
}
|