Files
media-preload/cmd/preload-api/main.go
T
Claude a18d45714e media-preload: on-demand VPS cache warm-up API and agent
OpenAPI 3.0 contract (api/openapi.yaml) with oapi-codegen generated server,
client and models; preload-api (Jellyfin lookup, SQLite queue, bearer roles)
runs at home, preload-agent runs on the VPS and fills the rclone cache.
mise manages Go 1.27.3 and oapi-codegen 2.8.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GUebqghNwNssAZuWTxUq1y
2026-11-04 17:49:06 -07:00

168 lines
5.6 KiB
Go

// preload-api: the media-preload control plane. Runs at home (yveltal), next to Jellyfin.
//
// Environment:
//
// LISTEN address to listen on (default :8125)
// DB_PATH SQLite file (default /data/preload.db)
// JELLYFIN_URL e.g. http://10.0.0.38:8096
// JELLYFIN_API_KEY Jellyfin API key
// CLIENT_TOKENS comma-separated bearer tokens for /v1/search and /v1/requests (e.g. the Discord bot)
// AGENT_TOKENS comma-separated bearer tokens for /v1/agent/* (the VPS preload agent)
// MAX_FILES per request (default 40)
// MAX_GB per request (default 150)
package main
import (
"context"
"crypto/subtle"
"encoding/json"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/api"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/jellyfin"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/service"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/store"
)
var version = "dev" // set with -ldflags "-X main.version=..."
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
func tokens(k string) [][]byte {
var out [][]byte
for _, t := range strings.Split(os.Getenv(k), ",") {
if t = strings.TrimSpace(t); t != "" {
out = append(out, []byte(t))
}
}
return out
}
func match(got string, list [][]byte) bool {
ok := false
for _, t := range list {
if subtle.ConstantTimeCompare([]byte(got), t) == 1 {
ok = true
}
}
return ok
}
func writeProblem(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(api.Problem{Error: msg})
}
// auth enforces bearer tokens by role: agent tokens only for /v1/agent/*, client tokens for everything else.
// /v1/health and /openapi.json are open.
func auth(next http.Handler, clients, agents [][]byte) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/health" || r.URL.Path == "/openapi.json" {
next.ServeHTTP(w, r)
return
}
tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || tok == "" {
writeProblem(w, http.StatusUnauthorized, "missing bearer token")
return
}
isAgentPath := strings.HasPrefix(r.URL.Path, "/v1/agent/")
switch {
case isAgentPath && match(tok, agents), !isAgentPath && match(tok, clients):
next.ServeHTTP(w, r)
case match(tok, agents) || match(tok, clients):
writeProblem(w, http.StatusForbidden, "this token may not use "+r.URL.Path)
default:
writeProblem(w, http.StatusUnauthorized, "invalid token")
}
})
}
func logRequests(next http.Handler, log *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, code: 200}
next.ServeHTTP(rec, r)
if r.URL.Path != "/v1/agent/claim" || rec.code != http.StatusNoContent { // idle polls are noise
log.Info("http", "method", r.Method, "path", r.URL.Path, "status", rec.code, "ms", time.Since(start).Milliseconds())
}
})
}
type statusRecorder struct {
http.ResponseWriter
code int
}
func (s *statusRecorder) WriteHeader(c int) { s.code = c; s.ResponseWriter.WriteHeader(c) }
func main() {
log := slog.New(slog.NewTextHandler(os.Stdout, nil))
clients, agents := tokens("CLIENT_TOKENS"), tokens("AGENT_TOKENS")
if len(clients) == 0 || len(agents) == 0 || os.Getenv("JELLYFIN_API_KEY") == "" {
log.Error("CLIENT_TOKENS, AGENT_TOKENS and JELLYFIN_API_KEY are required")
os.Exit(2)
}
st, err := store.Open(env("DB_PATH", "/data/preload.db"))
if err != nil {
log.Error("open db", "err", err)
os.Exit(1)
}
defer st.Close()
maxFiles, _ := strconv.Atoi(env("MAX_FILES", "40"))
maxGB, _ := strconv.ParseFloat(env("MAX_GB", "150"), 64)
svc := &service.Service{Store: st, Jellyfin: jellyfin.New(env("JELLYFIN_URL", "http://10.0.0.38:8096"), os.Getenv("JELLYFIN_API_KEY")),
Version: version, MaxFiles: maxFiles, MaxBytes: int64(maxGB * 1e9), StaleClaim: 3 * time.Hour, Log: log}
mux := http.NewServeMux()
strict := api.NewStrictHandlerWithOptions(svc, nil, api.StrictHTTPServerOptions{
RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
writeProblem(w, http.StatusBadRequest, err.Error())
},
ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
log.Error("handler", "path", r.URL.Path, "err", err)
writeProblem(w, http.StatusBadGateway, "upstream error: "+err.Error())
},
})
api.HandlerWithOptions(strict, api.StdHTTPServerOptions{BaseRouter: mux,
ErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { writeProblem(w, http.StatusBadRequest, err.Error()) }})
mux.HandleFunc("GET /openapi.json", func(w http.ResponseWriter, r *http.Request) {
spec, err := api.GetSwagger()
if err != nil {
writeProblem(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(spec)
})
srv := &http.Server{Addr: env("LISTEN", ":8125"), Handler: logRequests(auth(mux, clients, agents), log),
ReadHeaderTimeout: 10 * time.Second}
go func() {
log.Info("listening", "addr", srv.Addr, "version", version)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Error("serve", "err", err)
os.Exit(1)
}
}()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
}