Files
memby/server/cmd/memby-server/main.go
T

493 lines
19 KiB
Go
Raw Normal View History

// Command memby-server is the Memby gateway: one HTTP service in front of Emby that
// owns auth, caching and the shaping of TV screens, so the Android client can stay thin.
package main
import (
"context"
2026-08-02 22:10:19 +12:00
"encoding/json"
"errors"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
2026-08-14 09:40:03 +12:00
"github.com/ponzischeme89/memby/server/internal/adminevents"
"github.com/ponzischeme89/memby/server/internal/api"
2026-08-06 22:33:56 +12:00
"github.com/ponzischeme89/memby/server/internal/bazarr"
"github.com/ponzischeme89/memby/server/internal/buildinfo"
"github.com/ponzischeme89/memby/server/internal/cache"
"github.com/ponzischeme89/memby/server/internal/config"
2026-08-15 09:23:26 +12:00
"github.com/ponzischeme89/memby/server/internal/credits"
"github.com/ponzischeme89/memby/server/internal/emby"
2026-07-29 15:26:27 +12:00
"github.com/ponzischeme89/memby/server/internal/foryou"
2026-08-14 09:40:03 +12:00
"github.com/ponzischeme89/memby/server/internal/integrations"
"github.com/ponzischeme89/memby/server/internal/library"
2026-07-27 21:06:51 +12:00
"github.com/ponzischeme89/memby/server/internal/logging"
2026-08-03 08:52:55 +12:00
"github.com/ponzischeme89/memby/server/internal/mdblist"
2026-08-19 06:57:59 +12:00
"github.com/ponzischeme89/memby/server/internal/notify"
2026-08-02 22:10:19 +12:00
"github.com/ponzischeme89/memby/server/internal/radarr"
"github.com/ponzischeme89/memby/server/internal/recommend"
2026-08-19 14:25:44 +12:00
"github.com/ponzischeme89/memby/server/internal/runtimestats"
2026-08-14 09:40:03 +12:00
"github.com/ponzischeme89/memby/server/internal/scheduler"
2026-07-27 21:06:51 +12:00
"github.com/ponzischeme89/memby/server/internal/sonarr"
"github.com/ponzischeme89/memby/server/internal/store"
2026-07-29 15:26:27 +12:00
"github.com/ponzischeme89/memby/server/internal/tracearr"
)
func main() {
// A distroless image has no shell or curl, so the container's healthcheck re-runs
// this binary with -healthcheck and it probes itself over the loopback interface.
healthcheck := flag.Bool("healthcheck", false, "probe the local /healthz endpoint and exit")
flag.Parse()
if *healthcheck {
if err := probeHealth(); err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
}
return
}
2026-08-17 19:09:17 +12:00
// A variable rather than a fixed level: the console can move it at runtime, which is
// the only way turning debug on is any use — a restart to watch something happen
// restarts the thing being watched.
logLevel := &slog.LevelVar{}
logLevel.Set(logging.ParseLevel(os.Getenv("MEMBY_LOG_LEVEL")))
2026-08-02 22:10:19 +12:00
logCapacity := logging.ParseCapacity(os.Getenv("MEMBY_LOG_BUFFER_CAPACITY"), 5_000)
2026-08-06 22:33:56 +12:00
logFormat := logging.ParseFormat(os.Getenv("MEMBY_LOG_FORMAT"))
2026-08-12 09:57:56 +12:00
logHistoryPath := strings.TrimSpace(os.Getenv("MEMBY_LOG_HISTORY_PATH"))
if logHistoryPath == "" {
logHistoryPath = "/data/logs/events.jsonl"
}
log, events, err := logging.NewPersistentBuffered(
os.Stdout, logLevel, logCapacity, logFormat, logHistoryPath,
)
if err != nil {
os.Stderr.WriteString("open persistent log history: " + err.Error() + "\n")
os.Exit(1)
}
defer events.Close()
2026-08-06 22:33:56 +12:00
// Every line names the build that wrote it. A gateway is deployed from a working
// tree, often while a television is running an older app, so "which server said
// this" is a real question that a reader should never have to scroll for.
log = log.With("version", buildinfo.Version())
2026-08-17 19:09:17 +12:00
if err := run(log, events, logLevel); err != nil {
log.Error("fatal", "error", err)
os.Exit(1)
}
}
2026-08-17 19:09:17 +12:00
func run(log *slog.Logger, events *logging.Buffer, logLevel *slog.LevelVar) error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Postgres may still be starting when compose brings us up; retry briefly rather
// than crash-looping the container.
st, err := openStore(ctx, cfg.DatabaseURL, log)
if err != nil {
return err
}
defer st.Close()
if err := st.Migrate(ctx); err != nil {
return err
}
ca, err := cache.Open(cfg.RedisURL)
if err != nil {
return err
}
defer ca.Close()
if err := ca.Ping(ctx); err != nil {
return err
}
// A run interrupted by a restart is still marked "running" in the database; clear
// those before anything reads the sync history.
if err := st.MarkStaleRunsFailed(ctx); err != nil {
log.Warn("could not clear interrupted sync runs", "error", err)
}
2026-08-12 13:08:53 +12:00
embyClient := emby.New(
cfg.EmbyURL, cfg.EmbyPublicURL, cfg.ClientName, cfg.GatewayClientName,
cfg.UpstreamTimeout,
)
embyClient.SetMediaURL(cfg.EmbyMediaURL)
2026-08-03 08:52:55 +12:00
mdblistClient := mdblist.New(mdblist.DefaultBaseURL, cfg.UpstreamTimeout)
2026-07-27 21:06:51 +12:00
var sonarrClient *sonarr.Client
if cfg.SonarrURL != "" {
sonarrClient = sonarr.New(cfg.SonarrURL, cfg.SonarrAPIKey, cfg.UpstreamTimeout)
log.Info("sonarr integration enabled", "url", cfg.SonarrURL)
}
2026-08-02 22:10:19 +12:00
var radarrClient *radarr.Client
if cfg.RadarrURL != "" {
radarrClient = radarr.New(cfg.RadarrURL, cfg.RadarrAPIKey, cfg.UpstreamTimeout)
log.Info("radarr integration enabled", "url", cfg.RadarrURL)
}
2026-08-06 22:33:56 +12:00
// Bazarr gets its own timeout rather than UpstreamTimeout: a manual search queries
// live subtitle providers and legitimately takes tens of seconds, and cutting it short
// reads to the viewer as "no subtitles found" rather than as a timeout.
var bazarrClient *bazarr.Client
if cfg.BazarrURL != "" {
bazarrClient = bazarr.New(cfg.BazarrURL, cfg.BazarrAPIKey, cfg.BazarrTimeout)
log.Info("bazarr integration enabled", "url", cfg.BazarrURL)
}
2026-08-06 22:33:56 +12:00
recommender := recommend.NewEngine(embyClient, log.With("component", "recommendations"))
2026-08-02 22:10:19 +12:00
if cfg.RecommendationWeights != "" {
_ = json.Unmarshal([]byte(cfg.RecommendationWeights), &recommender.WeightedConfig)
}
// Candidates come from the imported library when one exists, which keeps the
// recommendation rebuild off Emby entirely.
recommender.Library = st
2026-07-29 15:26:27 +12:00
recommender.Behavior = st
var tracearrClient *tracearr.Client
if cfg.TracearrURL != "" {
tracearrClient = tracearr.New(
cfg.TracearrURL,
cfg.TracearrAPIKey,
cfg.TracearrServerID,
cfg.UpstreamTimeout,
)
recommender.Tracearr = tracearrClient
log.Info("tracearr recommendation signals enabled", "url", cfg.TracearrURL)
}
syncer := library.NewSyncer(embyClient, st, emby.Credentials{
UserID: cfg.SyncUserID,
Token: cfg.SyncAPIKey,
DeviceID: "memby-gateway-sync",
2026-08-12 13:08:53 +12:00
Gateway: true,
2026-08-06 22:33:56 +12:00
}, log.With("component", "library"))
2026-08-18 14:59:29 +12:00
// Sonarr and Radarr are what put files on disk, so they are what the catalogue learns
// from. The worker is built whenever either webhook is configured; with neither token
// set both hooks 404 and nothing here ever has anything to do, so it is not started.
var ingester *library.Ingester
if cfg.SonarrWebhookToken != "" || cfg.RadarrWebhookToken != "" {
ingester = &library.Ingester{
Store: st,
Emby: embyClient,
Credentials: syncer.EmbyCredentials,
Log: log.With("component", "library-ingest"),
Settle: cfg.IngestSettleDelay,
}
}
2026-07-29 15:26:27 +12:00
var forYouService *foryou.Service
if tracearrClient != nil {
forYouService = foryou.New(
2026-08-06 22:33:56 +12:00
st, tracearrClient, recommender, log.With("component", "for-you"),
2026-07-29 15:26:27 +12:00
cfg.ForYouMinRebuildAge, cfg.ForYouRefreshInterval,
)
2026-08-02 22:10:19 +12:00
forYouService.ConfigureTimeContext(cfg.SonarrLocation)
2026-07-29 15:26:27 +12:00
forYouService.ConfigureHouseholdUsers(embyClient, emby.Credentials{
UserID: cfg.SyncUserID, Token: cfg.SyncAPIKey,
2026-08-12 13:08:53 +12:00
DeviceID: "memby-for-you-builder", DeviceName: "MbyGateway For You",
Gateway: true,
2026-07-29 15:26:27 +12:00
})
}
2026-08-15 09:23:26 +12:00
// Credits discovery. Deliberately built here rather than inside the API server, because
// it owns a long-running worker and a queue whose lifetime is the process's — the server
// only reads its markers and feeds it the two live signals it already receives.
creditsLoad := credits.NewPlaybackLoad()
var creditsService *credits.Service
if cfg.CreditsEnabled {
sampler := &credits.Sampler{Binary: cfg.CreditsFFmpeg}
var detector credits.Detector
if sampler.Available() {
detector = &credits.VisualDetector{Sampler: sampler}
} else {
// No decoder in the image is a deliberate deployment, not a fault. The subsystem
// still runs and still writes markers, on the household's own stop positions —
// which cost no media access at all and, on a well-watched show, agree more
// closely than any single reading of the picture.
log.Warn("credits: ffmpeg not found; running on behavioural evidence only")
}
database := credits.Postgres{Store: st}
creditsConfig := credits.Config{
PrefetchEpisodes: cfg.CreditsPrefetchEpisodes,
MaxPrefetchEpisodes: cfg.CreditsMaxPrefetch,
QueueLimit: cfg.CreditsQueueLimit,
2026-08-16 12:13:51 +12:00
RetryCooldown: credits.DefaultConfig().RetryCooldown,
2026-08-15 09:23:26 +12:00
StrongWindow: credits.DefaultConfig().StrongWindow,
UsefulWindow: credits.DefaultConfig().UsefulWindow,
WeakWindow: credits.DefaultConfig().WeakWindow,
}
2026-08-16 12:13:51 +12:00
if saved, found, settingsErr := st.CreditsSettings(ctx); settingsErr != nil {
log.Warn("credits settings unavailable; using environment defaults", "error", settingsErr)
} else if found {
creditsConfig.PrefetchEpisodes = saved.PrefetchEpisodes
creditsConfig.MaxPrefetchEpisodes = saved.MaxPrefetch
creditsConfig.QueueLimit = saved.CandidateLimit
creditsConfig.RetryCooldown = time.Duration(saved.RetryHours) * time.Hour
}
creditsConfig = credits.NormaliseConfig(creditsConfig)
2026-08-15 09:23:26 +12:00
creditsService = credits.New(credits.Deps{
Repository: database,
2026-08-16 12:13:51 +12:00
History: database,
2026-08-15 09:23:26 +12:00
Resolver: credits.NewEmbyResolver(embyClient, emby.Credentials{
UserID: cfg.SyncUserID, Token: cfg.SyncAPIKey,
DeviceID: "memby-credits", DeviceName: "MbyGateway Credits",
Gateway: true,
}),
Source: &credits.TracearrSource{DB: database, Cfg: creditsConfig},
Detector: detector,
Behaviour: database,
Load: creditsLoad,
Log: log,
Config: creditsConfig,
})
// media_url is on this line rather than the ready line because credits detection is
// the only thing that uses it, and because reading it back is the only way an
// operator can tell that a scan is taking the short path. Where it equals EmbyURL
// the scans go out the public way, which on a split host is the whole cost.
2026-08-15 09:23:26 +12:00
log.Info("credits detection enabled",
"prefetch", creditsConfig.PrefetchEpisodes,
"queue_limit", creditsConfig.QueueLimit,
"visual", detector != nil,
"media_url", cfg.EmbyMediaURL)
2026-08-15 09:23:26 +12:00
}
2026-08-14 09:40:03 +12:00
// The administrative event bus, the integration dispatcher that subscribes to it and
// the scheduler that publishes into it are built before the server, because the server
// takes all three: a handler that could not publish would have to check for nil at
// every call site, which is exactly how an event comes to be silently dropped.
adminBus := adminevents.New(st, log)
2026-08-19 06:57:59 +12:00
// The notification service is built before both the dispatcher and the server, because
// both write into it: the dispatcher records what it posted to Discord, and the server
// registers the in-app and broadcast providers on it. The store is its recorder, which
// is the whole audit trail.
notifier := notify.New(st, log)
dispatcher := integrations.New(st, log, adminBus, notifier)
2026-08-14 09:40:03 +12:00
adminBus.AddSink(dispatcher)
sched := scheduler.New(st, log, adminBus)
server := api.New(cfg, api.Deps{
Emby: embyClient,
Store: st,
Cache: ca,
Recommender: recommender,
2026-07-29 15:26:27 +12:00
ForYou: forYouService,
2026-07-27 21:06:51 +12:00
Sonarr: sonarrClient,
2026-08-02 22:10:19 +12:00
Radarr: radarrClient,
2026-08-06 22:33:56 +12:00
Bazarr: bazarrClient,
2026-08-03 08:52:55 +12:00
MDBList: mdblistClient,
2026-08-15 09:23:26 +12:00
Credits: creditsService,
CreditsLoad: creditsLoad,
Syncer: syncer,
2026-08-18 14:59:29 +12:00
Ingester: ingester,
Log: log,
2026-07-29 15:26:27 +12:00
Events: events,
2026-08-14 09:40:03 +12:00
AdminEvents: adminBus,
Scheduler: sched,
Integrations: dispatcher,
2026-08-19 06:57:59 +12:00
Notify: notifier,
2026-08-17 19:09:17 +12:00
LogLevel: logLevel,
})
2026-08-17 07:34:23 +12:00
if err := server.LoadQuietTime(ctx); err != nil {
return err
}
sched.SetPaused(server.ActivityPaused)
2026-08-19 14:25:44 +12:00
// The ranker calls Tracearr directly on the rebuild path, so it needs the operator's
// switch too — read at call time, because an integration switched off in the console
// must stop being called without a restart. It is wired here rather than where the
// engine is built because the switch belongs to the server, which does not exist yet
// at that point.
recommender.TracearrAllowed = server.TracearrEnabled
2026-08-17 07:34:23 +12:00
dispatcher.SetPaused(server.ActivityPaused)
dispatcher.Start(ctx)
if creditsService != nil {
creditsService.SetPaused(server.ActivityPaused)
2026-08-19 14:25:44 +12:00
runtimestats.Go("Credits detection", "Credits detection", func() { creditsService.Run(ctx) })
2026-08-17 07:34:23 +12:00
}
2026-08-18 14:59:29 +12:00
if ingester != nil {
// Quiet time is honoured here rather than at the hook: the webhook is recorded
// whatever the hour, and this is what waits.
ingester.Paused = server.ActivityPaused
// The news follows the scan rather than the webhook, so the banner can say a title
// is there rather than that it is coming. Installed here for the same reason
// SetAfterSync is: library stays ignorant of what an alert is.
ingester.Announce = server.AnnounceLibraryIngest
2026-08-19 14:25:44 +12:00
runtimestats.Go("Library ingest", "Library sync", func() { ingester.Run(ctx) })
2026-08-18 14:59:29 +12:00
}
2026-08-14 09:40:03 +12:00
// Registration is separate from construction so the task list reads as a declaration
// of what the gateway does in the background rather than as more wiring in here.
server.RegisterHousekeeping(sched)
2026-08-15 09:23:26 +12:00
server.RegisterCreditsTasks(sched)
2026-08-18 08:41:48 +12:00
server.RegisterWatchTimeTasks(sched)
2026-08-19 14:25:44 +12:00
server.RegisterRequestTasks(sched)
// Sonarr's daily catalogue reading, Radarr's film refresh, the Tracearr import and the
// For You rebuild all used to be goroutines with tickers of their own here. They are
// scheduler tasks now, which is what gives the console's integrations area a run
// history without a second store — and what lets an operator run any of them by hand.
server.RegisterIntegrationTasks(sched)
2026-08-14 09:40:03 +12:00
sched.Start(ctx)
2026-08-02 22:10:19 +12:00
// Installed after the server exists, because both halves of a finished import are
// its business: derived data has to be invalidated, and the TVs told the catalogue
// moved. Kept off the syncer itself so library stays ignorant of the API.
syncer.SetAfterSync(func(result library.Result) {
afterCtx, cancel := context.WithTimeout(context.Background(), cfg.RecommendTimeout)
defer cancel()
server.AnnounceLibrarySync(afterCtx, result)
if forYouService == nil || (result.Changed == 0 && result.Removed == 0) {
return
}
forYouService.MarkAllDirty(afterCtx)
})
if err := server.LoadMaintenance(ctx); err != nil {
return err
}
2026-08-17 19:09:17 +12:00
// The operator's runtime amendments to what this container was started with. Loaded
// before the watchers below, because two of them read it on their first tick.
if err := server.LoadGatewaySettings(ctx); err != nil {
return err
}
2026-08-22 08:26:10 +12:00
if err := server.LoadMetadataHeroSettings(ctx); err != nil {
return err
}
2026-08-19 14:25:44 +12:00
// Every long-running worker below is started through runtimestats.Go rather than with
// a bare `go`, so the admin console can name what is running instead of reporting a
// count of goroutines nobody can interpret. The name is the worker's identity across
// restarts and appears verbatim in the console, so it is wording rather than a symbol.
runtimestats.Go("Gateway settings watcher", "Gateway settings", func() {
server.WatchGatewaySettings(ctx, 30*time.Second)
})
runtimestats.Go("Maintenance watcher", "Gateway settings", func() {
server.WatchMaintenance(ctx, 30*time.Second)
})
runtimestats.Go("Quiet time watcher", "Gateway settings", func() {
server.WatchQuietTime(ctx, 30*time.Second)
})
2026-08-02 22:10:19 +12:00
// One probe per gateway, not per TV: the answer is the same for the whole house.
2026-08-19 14:25:44 +12:00
runtimestats.Go("Emby health probe", "Emby", func() { server.WatchEmbyReachability(ctx) })
// The trend ring behind the console's runtime page. A single instantaneous goroutine
// or heap figure cannot show a leak; this is what makes one visible.
runtimestats.Go("Runtime sampler", "Gateway API", func() { runtimestats.StartSampling(ctx) })
if err := server.LoadUpdatePolicy(ctx); err != nil {
return err
}
2026-08-19 14:25:44 +12:00
runtimestats.Go("App update policy watcher", "Gateway settings", func() {
server.WatchUpdatePolicy(ctx, 60*time.Second)
})
2026-08-19 14:25:44 +12:00
runtimestats.Go("Library sync schedule", "Library sync", func() {
syncer.Schedule(ctx, server.LibrarySyncInterval, server.ActivityPaused)
})
if cfg.SyncOnStart {
2026-08-19 14:25:44 +12:00
runtimestats.Go("Startup library sync", "Library sync", func() {
2026-08-17 07:34:23 +12:00
if server.ActivityPaused() {
return
}
if _, err := syncer.Sync(ctx, "incremental", "startup"); err != nil {
log.Warn("startup sync failed", "error", err)
}
2026-08-19 14:25:44 +12:00
})
}
2026-07-29 15:26:27 +12:00
if forYouService != nil {
2026-08-19 14:25:44 +12:00
// The import and the daily rebuild are scheduler tasks now — see
// RegisterIntegrationTasks — so what is left here is the one piece of start-up work
// neither of them is: profiles produced by an older algorithm. Only a version change
// warrants it, and normal dirty profiles still wait for the daily off-peak rebuild.
runtimestats.Go("Startup For You migration", "Recommendations", func() {
2026-08-17 07:34:23 +12:00
if server.ActivityPaused() {
return
}
2026-08-19 14:25:44 +12:00
rebuildCtx, cancel := context.WithTimeout(ctx, cfg.SyncTimeout)
defer cancel()
2026-08-02 22:10:19 +12:00
if err := forYouService.RebuildOutdated(rebuildCtx); err != nil {
log.Warn("startup outdated For You rebuild failed", "error", err)
2026-07-29 15:26:27 +12:00
}
2026-08-19 14:25:44 +12:00
})
2026-07-29 15:26:27 +12:00
}
httpServer := &http.Server{
Addr: cfg.ListenAddr,
Handler: server.Routes(),
ReadHeaderTimeout: 10 * time.Second,
// No WriteTimeout: image proxying streams bodies of unpredictable size.
IdleTimeout: 60 * time.Second,
}
errCh := make(chan error, 1)
2026-08-19 14:25:44 +12:00
runtimestats.Go("HTTP listener", "HTTP server", func() {
2026-08-06 22:33:56 +12:00
log.Info("gateway ready",
2026-07-27 21:06:51 +12:00
"listen", cfg.ListenAddr,
"emby", cfg.EmbyURL,
2026-08-06 22:33:56 +12:00
"protocol", api.ProtocolVersion,
2026-07-27 21:06:51 +12:00
"sync_every", cfg.SyncInterval,
)
2026-08-14 09:40:03 +12:00
// Announced here rather than beside the log line above, so the feed cannot record
// a start that then failed to bind to its port.
server.AnnounceServerStart(buildinfo.Version())
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- err
}
2026-08-19 14:25:44 +12:00
})
select {
case err := <-errCh:
return err
case <-ctx.Done():
log.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return httpServer.Shutdown(shutdownCtx)
}
}
// probeHealth is the container healthcheck: hit our own /healthz over loopback.
func probeHealth() error {
addr := os.Getenv("MEMBY_LISTEN_ADDR")
if addr == "" {
addr = ":8080"
}
2026-07-29 15:26:27 +12:00
// Wildcard listen addresses still mean "connect to localhost" from in here.
if idx := strings.LastIndex(addr, ":"); idx >= 0 {
addr = "127.0.0.1" + addr[idx:]
}
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Get("http://" + addr + "/healthz")
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("healthz returned %d", resp.StatusCode)
}
return nil
}
func openStore(ctx context.Context, databaseURL string, log *slog.Logger) (*store.Store, error) {
var lastErr error
for attempt := range 10 {
st, err := store.Open(ctx, databaseURL)
if err == nil {
return st, nil
}
lastErr = err
log.Warn("waiting for postgres", "attempt", attempt+1, "error", err)
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(2 * time.Second):
}
}
return nil, lastErr
}