- feat(config): TOML config with env overrides, strict parsing and validation - feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun, embedded per-driver SQL migrations with a transactional runner - feat(schema): catalog tables (artists, albums, tracks, audio_files with per-root paths), users and listening events with idempotency keys - feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only registration and login - feat(api): gin REST API under /api/v1 (health, register, login, listens) with a consistent error envelope, body limit and request logging - feat(sondad): zap logger, graceful shutdown, composition root in main - chore: example config, .gitignore for secrets, DB files, IDE and agent files
124 lines
3 KiB
Go
124 lines
3 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/listening"
|
|
"codeberg.org/squidd/sonda/internal/storage"
|
|
"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.TokenTTL())
|
|
if cfg.Log.Env == "production" {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
router := httpapi.NewRouter(httpapi.Deps{
|
|
Logger: logger,
|
|
Auth: auth.NewService(storage.NewUserRepo(db), tokens),
|
|
Tokens: tokens,
|
|
Listening: listening.NewService(storage.NewListeningRepo(db)),
|
|
})
|
|
|
|
// 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.Strings("library_roots", cfg.Library.Roots),
|
|
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
|
|
}
|