package metrics import ( "context" _ "embed" "fmt" "net" "net/http" "github.com/prometheus/client_golang/prometheus/promhttp" "git.warky.dev/wdevs/pgsql-broker/pkg/broker/adapter" ) //go:embed page.html var dashboardHTML []byte // Server is the embedded HTTP server exposing /metrics (standard Prometheus // exposition format) and / (a single-page HTML dashboard that polls // /metrics). type Server struct { httpServer *http.Server listener net.Listener logger adapter.Logger } // NewServer builds a Server bound to addr (e.g. "127.0.0.1:9469"). Binding // happens immediately so a port conflict is reported to the caller rather // than surfacing later in a background goroutine. func NewServer(m *Metrics, addr string, logger adapter.Logger) (*Server, error) { listener, err := net.Listen("tcp", addr) if err != nil { return nil, fmt.Errorf("failed to bind metrics server to %s: %w", addr, err) } mux := http.NewServeMux() mux.Handle("/metrics", promhttp.HandlerFor(m.Registry, promhttp.HandlerOpts{})) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = w.Write(dashboardHTML) }) return &Server{ httpServer: &http.Server{Handler: mux}, listener: listener, logger: logger.With("component", "metrics-server"), }, nil } // Addr returns the actual bound address (useful when addr was given with a // ":0" port). func (s *Server) Addr() string { return s.listener.Addr().String() } // Start serves in the background. It returns immediately; Serve errors // (other than a clean Shutdown) are logged. func (s *Server) Start() { s.logger.Info("metrics server listening", "addr", s.Addr()) go func() { if err := s.httpServer.Serve(s.listener); err != nil && err != http.ErrServerClosed { s.logger.Error("metrics server stopped unexpectedly", "error", err) } }() } // Stop gracefully shuts down the server. func (s *Server) Stop(ctx context.Context) error { return s.httpServer.Shutdown(ctx) }