Files
mtusi2026lab6/internal/transport/http/internal_stats.go
T

40 lines
1.4 KiB
Go

package http
import (
"encoding/json"
"net/http"
"runtime"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/charawein/mtusi2026lab6/internal/config"
)
// NewInternalStatsHandler отдаёт счётчики пула PostgreSQL и рантайма Go.
// Нужен для поиска точки насыщения пула в экспериментах трека 1:
// рост empty_acquire_count/acquire_duration означает ожидание свободного соединения.
func NewInternalStatsHandler(pool *pgxpool.Pool, cfg config.Config) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /internal/stats", func(w http.ResponseWriter, r *http.Request) {
st := pool.Stat()
body := map[string]any{
"instance_id": cfg.InstanceID,
"cache_invalidation": cfg.CacheInvalidation,
"pool": map[string]any{
"max_conns": st.MaxConns(),
"total_conns": st.TotalConns(),
"acquired_conns": st.AcquiredConns(),
"idle_conns": st.IdleConns(),
"acquire_count": st.AcquireCount(),
"empty_acquire_count": st.EmptyAcquireCount(),
"canceled_acquire_count": st.CanceledAcquireCount(),
"acquire_duration_ms": st.AcquireDuration().Milliseconds(),
},
"goroutines": runtime.NumGoroutine(),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(body)
})
return mux
}