1package stats
 2
 3import (
 4	"context"
 5	"net/http"
 6	"time"
 7
 8	"github.com/charmbracelet/soft-serve/pkg/config"
 9	"github.com/prometheus/client_golang/prometheus/promhttp"
10)
11
12// StatsServer is a server for collecting and reporting statistics.
13type StatsServer struct { //nolint:revive
14	ctx    context.Context
15	cfg    *config.Config
16	server *http.Server
17}
18
19// NewStatsServer returns a new StatsServer.
20func NewStatsServer(ctx context.Context) (*StatsServer, error) {
21	cfg := config.FromContext(ctx)
22	mux := http.NewServeMux()
23	mux.Handle("/metrics", promhttp.Handler())
24	return &StatsServer{
25		ctx: ctx,
26		cfg: cfg,
27		server: &http.Server{
28			Addr:              cfg.Stats.ListenAddr,
29			Handler:           mux,
30			ReadHeaderTimeout: time.Second * 10,
31			ReadTimeout:       time.Second * 10,
32			WriteTimeout:      time.Second * 10,
33			MaxHeaderBytes:    http.DefaultMaxHeaderBytes,
34		},
35	}, nil
36}
37
38// ListenAndServe starts the StatsServer.
39func (s *StatsServer) ListenAndServe() error {
40	return s.server.ListenAndServe()
41}
42
43// Shutdown gracefully shuts down the StatsServer.
44func (s *StatsServer) Shutdown(ctx context.Context) error {
45	return s.server.Shutdown(ctx)
46}
47
48// Close closes the StatsServer.
49func (s *StatsServer) Close() error {
50	return s.server.Close()
51}