Files
api-go/cmd/api/main.go

70 lines
1.7 KiB
Go

// Command api serves the PulseCast Go API, SSE stream and runtime snapshot cache.
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"pulsecast/api/internal/api"
"pulsecast/api/internal/cache"
"pulsecast/api/internal/config"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/sse"
)
func main() {
cfg := config.Load()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
client := ml.NewWithToken(cfg.FastAPIURL, cfg.MLTimeout, cfg.ControlToken)
snapshots := cache.New(client, cache.Options{
RefreshInterval: cfg.RefreshInterval,
Timeout: cfg.BootstrapTimeout,
})
// Loading happens in the background so the process can answer /api/readyz
// with 503 immediately instead of crash-looping while FastAPI starts.
go snapshots.Run(ctx)
hub := sse.NewHub(cfg.Heartbeat)
go hub.Run(ctx)
server := &http.Server{
Addr: cfg.Addr,
Handler: api.New(cfg, snapshots, client, hub).Handler(),
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 120 * time.Second,
}
serveErr := make(chan error, 1)
go func() {
slog.Info("api listening", "addr", cfg.Addr, "fastapi", cfg.FastAPIURL,
"refresh", cfg.RefreshInterval)
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)
}
}