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