2026-03-21 10:08:44 +01:00
|
|
|
package api
|
|
|
|
|
|
|
|
|
|
import (
|
2026-04-03 23:18:06 +02:00
|
|
|
"context"
|
2026-03-21 10:08:44 +01:00
|
|
|
"net/http"
|
|
|
|
|
"runtime"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// ServerMetrics holds runtime metrics for the /api/v1/metrics endpoint.
|
|
|
|
|
type ServerMetrics struct {
|
|
|
|
|
Uptime string `json:"uptime"`
|
|
|
|
|
UptimeSeconds float64 `json:"uptime_seconds"`
|
|
|
|
|
GoRoutines int `json:"goroutines"`
|
|
|
|
|
HeapAllocMB float64 `json:"heap_alloc_mb"`
|
|
|
|
|
HeapSysMB float64 `json:"heap_sys_mb"`
|
|
|
|
|
NumGC uint32 `json:"num_gc"`
|
|
|
|
|
ConnectedUsers int `json:"connected_users"`
|
2026-03-29 00:51:54 +01:00
|
|
|
VoiceSessions int `json:"voice_sessions"`
|
2026-04-03 23:18:06 +02:00
|
|
|
BroadcastDrops uint64 `json:"broadcast_drops"`
|
2026-03-22 19:29:42 +01:00
|
|
|
LiveKitHealthy *bool `json:"livekit_healthy,omitempty"`
|
2026-03-21 10:08:44 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// handleMetrics returns an HTTP handler that reports runtime server metrics.
|
|
|
|
|
// getConnectedUsers is a callback to retrieve the current WebSocket client count.
|
2026-04-03 23:18:06 +02:00
|
|
|
// getBroadcastDrops is a callback to retrieve the cumulative broadcast drop counter.
|
2026-03-22 19:29:42 +01:00
|
|
|
// livekitHealthCheck is optional — if non-nil, it probes the LiveKit companion process.
|
2026-04-03 23:18:06 +02:00
|
|
|
func handleMetrics(getConnectedUsers func() int, getVoiceSessions func() int, getBroadcastDrops func() uint64, livekitHealthCheck func(context.Context) (bool, error)) http.HandlerFunc {
|
2026-03-21 10:08:44 +01:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
var m runtime.MemStats
|
|
|
|
|
runtime.ReadMemStats(&m)
|
|
|
|
|
|
|
|
|
|
uptime := time.Since(serverStartTime)
|
|
|
|
|
metrics := ServerMetrics{
|
|
|
|
|
Uptime: uptime.Truncate(time.Second).String(),
|
|
|
|
|
UptimeSeconds: uptime.Seconds(),
|
|
|
|
|
GoRoutines: runtime.NumGoroutine(),
|
|
|
|
|
HeapAllocMB: float64(m.HeapAlloc) / 1024 / 1024,
|
|
|
|
|
HeapSysMB: float64(m.HeapSys) / 1024 / 1024,
|
|
|
|
|
NumGC: m.NumGC,
|
|
|
|
|
ConnectedUsers: getConnectedUsers(),
|
2026-03-29 00:51:54 +01:00
|
|
|
VoiceSessions: getVoiceSessions(),
|
2026-04-03 23:18:06 +02:00
|
|
|
BroadcastDrops: getBroadcastDrops(),
|
2026-03-21 10:08:44 +01:00
|
|
|
}
|
|
|
|
|
|
2026-03-22 19:29:42 +01:00
|
|
|
if livekitHealthCheck != nil {
|
2026-04-03 23:18:06 +02:00
|
|
|
healthy, _ := livekitHealthCheck(r.Context())
|
2026-03-22 19:29:42 +01:00
|
|
|
metrics.LiveKitHealthy = &healthy
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-21 10:08:44 +01:00
|
|
|
writeJSON(w, http.StatusOK, metrics)
|
|
|
|
|
}
|
|
|
|
|
}
|