67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
// Command api serves the PulseCast Go API, SSE stream and cached fallback.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"pulsecast/api/internal/api"
|
|
"pulsecast/api/internal/config"
|
|
"pulsecast/api/internal/ml"
|
|
"pulsecast/api/internal/sse"
|
|
"pulsecast/api/internal/store"
|
|
)
|
|
|
|
func main() {
|
|
cfg := config.Load()
|
|
|
|
// A partial dataset is not fatal: the process starts and /api/readyz reports
|
|
// 503 until the baked artifacts are complete, instead of crash-looping.
|
|
st, err := store.Load(cfg.DataDir)
|
|
if err != nil {
|
|
slog.Error("baked data is incomplete", "dir", cfg.DataDir, "error", err)
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
hub := sse.NewHub(cfg.Heartbeat)
|
|
go hub.Run(ctx)
|
|
|
|
server := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: api.New(cfg, st, ml.NewWithToken(cfg.FastAPIURL, cfg.MLTimeout, cfg.ControlToken), hub).Handler(),
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
IdleTimeout: 120 * time.Second,
|
|
}
|
|
|
|
serveErr := make(chan error, 1)
|
|
go func() {
|
|
slog.Info("api listening", "addr", cfg.Addr, "data_dir", cfg.DataDir, "fastapi", cfg.FastAPIURL)
|
|
serveErr <- server.ListenAndServe()
|
|
}()
|
|
|
|
select {
|
|
case <-ctx.Done():
|
|
slog.Info("shutting down")
|
|
case err := <-serveErr:
|
|
if !errors.Is(err, http.ErrServerClosed) {
|
|
slog.Error("server stopped", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
return
|
|
}
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
if err := server.Shutdown(shutdownCtx); err != nil {
|
|
slog.Error("graceful shutdown failed", "error", err)
|
|
}
|
|
}
|