Five tasks, four delegated to agents on disjoint files and one on the critical
path. Board and verification log: ~/.opencode/plan/vellum-beta-tasks.md
T1 Async scans (coordinator)
- migration 0007 adds ref_id + result to jobs, indexed by (kind, ref_id, id),
so a job can be found by what it operates on and can report back.
- jobs: EnqueueRef, JobID(ctx) so a handler can attach a result, SetResult.
- POST /libraries/{id}/scan now enqueues and returns 202; a real library takes
longer than any request timeout, and a hanging request looks like a broken
server. GET /libraries/{id}/scan/status reports the latest run.
- Libraries.svelte polls and shows "Scanning…" instead of freezing.
T2 Admin CLI (agent)
- internal/cli: `user add|passwd|list`, `backup <path>` via VACUUM INTO, with
tests. Wired into main.go, which the coordinator kept.
T3 Deploy (agent)
- compose.yml now mounts all six media kinds read-only with :z and carries the
metadata env keys. DEPLOY.md covers volumes, SELinux, admin bootstrap, TLS,
backup and upgrade.
T4 Pagination (agent)
- GET /items takes offset and returns total; Browse loads 60 at a time with
"Load more" and "Showing X of Y" instead of silently truncating at 300.
T5 Password change UI (agent)
- A Password section in Settings with validation, busy and success states.
Verified end to end: scan returns 202 in 0.7 ms and polls to done; the CLI
created a user, changed a password, and produced a complete 240 KB backup while
the server ran; pagination reports total 8 and pages correctly; compose parses
with every mount :z. go vet and 14 test packages pass; svelte-check 0/0.
191 lines
6 KiB
Go
191 lines
6 KiB
Go
// Command vellum is the unified media server: one process, one database,
|
|
// every media type.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/mithral/vellum/internal/auth"
|
|
"github.com/mithral/vellum/internal/cli"
|
|
"github.com/mithral/vellum/internal/core"
|
|
"github.com/mithral/vellum/internal/httpapi"
|
|
"github.com/mithral/vellum/internal/jobs"
|
|
"github.com/mithral/vellum/internal/library"
|
|
"github.com/mithral/vellum/internal/media"
|
|
"github.com/mithral/vellum/internal/metadata"
|
|
"github.com/mithral/vellum/internal/modules/comics"
|
|
"github.com/mithral/vellum/internal/modules/ebooks"
|
|
"github.com/mithral/vellum/internal/modules/games"
|
|
_ "github.com/mithral/vellum/internal/modules/photos" // registers the thumbnail extractor
|
|
"github.com/mithral/vellum/internal/search"
|
|
"github.com/mithral/vellum/migrations"
|
|
)
|
|
|
|
// version is overridden at build time with -ldflags "-X main.version=...".
|
|
var version = "dev"
|
|
|
|
func main() {
|
|
cfg, err := core.LoadConfig()
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "vellum: fatal:", err)
|
|
os.Exit(1)
|
|
}
|
|
log := core.NewLogger(cfg.LogLevel, cfg.LogFormat)
|
|
|
|
// Administrative subcommands run instead of the server. This is the way
|
|
// back in when someone is locked out, and the way to take a backup while
|
|
// the server is stopped.
|
|
if handled, err := cli.Run(os.Args[1:], cfg, log); handled {
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "vellum:", err)
|
|
os.Exit(1)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := run(cfg, log); err != nil {
|
|
fmt.Fprintln(os.Stderr, "vellum: fatal:", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run(cfg core.Config, log *slog.Logger) error {
|
|
log.Info("starting vellum", "version", version, "listen", cfg.Listen)
|
|
|
|
if err := cfg.Validate(); err != nil {
|
|
return err
|
|
}
|
|
|
|
db, err := core.OpenDB(cfg.DBPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer db.Close()
|
|
|
|
migCtx, cancelMig := context.WithTimeout(context.Background(), 60*time.Second)
|
|
err = core.Migrate(migCtx, db, migrations.FS, log)
|
|
cancelMig()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
api := httpapi.New(db, log, version)
|
|
|
|
authenticator := auth.NewAuthenticator(db, cfg.CookieName, cfg.SessionTTL, cfg.CookieSecure, log)
|
|
if !cfg.CookieSecure {
|
|
log.Warn("VELLUM_COOKIE_SECURE is false; session cookies will be sent over plain HTTP. " +
|
|
"Set it to true when serving over TLS.")
|
|
}
|
|
|
|
if err := auth.EnsureAdminFromEnv(context.Background(), db, log, cfg.AdminUser, cfg.AdminPassword); err != nil {
|
|
return fmt.Errorf("bootstrap admin: %w", err)
|
|
}
|
|
|
|
authHandlers := auth.NewHandlers(authenticator, log)
|
|
authHandlers.Register(api.Mux())
|
|
api.SetAuth(authenticator)
|
|
|
|
// Background work: a table-backed queue in the same database. Created
|
|
// before the modules so a module's handlers can enqueue work.
|
|
queue := jobs.New(db, log)
|
|
|
|
library.NewHandlers(db, log, authenticator, queue).Register(api.Mux())
|
|
media.NewHandlers(db, log, authenticator, cfg.ConfigDir).Register(api.Mux())
|
|
ebooks.NewHandlers(db, log, authenticator).Register(api.Mux())
|
|
comics.NewHandlers(db, log, authenticator).Register(api.Mux())
|
|
games.NewHandlers(db, log, authenticator).Register(api.Mux())
|
|
search.NewHandlers(db, log, authenticator).Register(api.Mux())
|
|
|
|
// Scans run on the queue rather than inside the request: a real library
|
|
// takes longer than any sensible timeout, and a hanging request is
|
|
// indistinguishable from a broken server. The result is written back so
|
|
// the UI can read progress.
|
|
queue.Register(library.ScanJobKind, func(ctx context.Context, payload json.RawMessage) error {
|
|
var p library.ScanPayload
|
|
if err := json.Unmarshal(payload, &p); err != nil {
|
|
return fmt.Errorf("scan: bad payload: %w", err)
|
|
}
|
|
lib, err := library.Get(ctx, db, p.LibraryID)
|
|
if err != nil {
|
|
return nil // deleted since the job was queued
|
|
}
|
|
res, err := library.Scan(ctx, db, lib, log)
|
|
if jobID, ok := jobs.JobID(ctx); ok {
|
|
if serr := jobs.SetResult(ctx, db, jobID, res); serr != nil {
|
|
log.Warn("record scan result", "err", serr)
|
|
}
|
|
}
|
|
return err
|
|
})
|
|
|
|
// Providers are registered primary-first; a fallback is only consulted
|
|
// when the primary returns nothing.
|
|
metadata.Register(metadata.NewOpenLibrary())
|
|
metadata.Register(metadata.NewGoogleBooks())
|
|
metadata.Register(metadata.NewMusicBrainz())
|
|
if cfg.ComicVineAPIKey != "" {
|
|
metadata.Register(metadata.NewComicVine(cfg.ComicVineAPIKey))
|
|
} else {
|
|
log.Info("comic metadata disabled: set VELLUM_COMICVINE_API_KEY to enable ComicVine lookups")
|
|
}
|
|
if cfg.IGDBClientID != "" && cfg.IGDBClientSecret != "" {
|
|
metadata.Register(metadata.NewIGDB(cfg.IGDBClientID, cfg.IGDBClientSecret))
|
|
} else {
|
|
log.Info("game metadata disabled: set VELLUM_IGDB_CLIENT_ID and VELLUM_IGDB_CLIENT_SECRET to enable IGDB lookups")
|
|
}
|
|
enricher := metadata.NewEnricher(db, log, cfg.ConfigDir)
|
|
queue.Register(metadata.JobKind, enricher.Handle)
|
|
metadata.NewHandlers(db, log, authenticator, queue).Register(api.Mux())
|
|
|
|
jobCtx, cancelJobs := context.WithCancel(context.Background())
|
|
defer cancelJobs()
|
|
go queue.Run(jobCtx)
|
|
|
|
srv := &http.Server{
|
|
Addr: cfg.Listen,
|
|
Handler: api.Handler(),
|
|
// ReadHeaderTimeout protects against slowloris. WriteTimeout is
|
|
// deliberately zero: streaming large media files must not be cut off.
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
ReadTimeout: cfg.ReadTimeout,
|
|
WriteTimeout: cfg.WriteTimeout,
|
|
IdleTimeout: cfg.IdleTimeout,
|
|
ErrorLog: nil,
|
|
}
|
|
|
|
errCh := make(chan error, 1)
|
|
go func() {
|
|
log.Info("listening", "addr", cfg.Listen, "data_dir", cfg.DataDir)
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
errCh <- err
|
|
}
|
|
}()
|
|
|
|
stop := make(chan os.Signal, 1)
|
|
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
|
|
|
select {
|
|
case err := <-errCh:
|
|
return fmt.Errorf("http server: %w", err)
|
|
case sig := <-stop:
|
|
log.Info("shutting down", "signal", sig.String())
|
|
}
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
return fmt.Errorf("graceful shutdown: %w", err)
|
|
}
|
|
cancelJobs()
|
|
log.Info("stopped")
|
|
return nil
|
|
}
|