Files
2026-10-30 16:35:46 +02:00

206 lines
5.0 KiB
Go

package api
import (
"encoding/json"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/mahmoud/db-monitor/collector"
"github.com/mahmoud/db-monitor/storage"
)
// Handler manages API endpoints
type Handler struct {
store *storage.Store
latestMu sync.RWMutex
latestData map[string]*collector.Metrics // db_name -> latest metrics
}
// NewHandler creates a new API handler
func NewHandler(store *storage.Store) *Handler {
return &Handler{
store: store,
latestData: make(map[string]*collector.Metrics),
}
}
// UpdateLatest stores the latest metrics in memory for fast access
func (h *Handler) UpdateLatest(dbName string, m *collector.Metrics) {
h.latestMu.Lock()
defer h.latestMu.Unlock()
h.latestData[dbName] = m
}
// RemoveLatest removes the metrics for a database that is no longer monitored
func (h *Handler) RemoveLatest(dbName string) {
h.latestMu.Lock()
defer h.latestMu.Unlock()
delete(h.latestData, dbName)
}
// RegisterRoutes sets up API routes on the given mux
func (h *Handler) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/api/status", h.handleStatus)
mux.HandleFunc("/api/databases", h.handleDatabases)
mux.HandleFunc("/api/metrics/", h.handleMetrics)
mux.HandleFunc("/api/history/", h.handleHistory)
}
// GET /api/status — returns status of all monitored databases
func (h *Handler) handleStatus(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
h.latestMu.RLock()
defer h.latestMu.RUnlock()
type dbStatus struct {
Name string `json:"name"`
Status string `json:"status"`
LatencyMs float64 `json:"latency_ms"`
Error string `json:"error,omitempty"`
UpdatedAt int64 `json:"updated_at"`
}
// Collect names and sort for stable order
names := make([]string, 0, len(h.latestData))
for name := range h.latestData {
names = append(names, name)
}
sort.Strings(names)
var statuses []dbStatus
for _, name := range names {
m := h.latestData[name]
statuses = append(statuses, dbStatus{
Name: name,
Status: m.Status,
LatencyMs: m.LatencyMs,
Error: m.Error,
UpdatedAt: m.CollectedAt,
})
}
writeJSON(w, map[string]interface{}{
"databases": statuses,
"checked_at": time.Now().Unix(),
})
}
// GET /api/databases — returns list of all monitored database names
func (h *Handler) handleDatabases(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
h.latestMu.RLock()
defer h.latestMu.RUnlock()
var names []string
for name := range h.latestData {
names = append(names, name)
}
writeJSON(w, map[string]interface{}{
"databases": names,
})
}
// GET /api/metrics/{db_name} — returns latest full metrics for a database
func (h *Handler) handleMetrics(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
dbName := strings.TrimPrefix(r.URL.Path, "/api/metrics/")
if dbName == "" {
http.Error(w, "database name required", http.StatusBadRequest)
return
}
h.latestMu.RLock()
m, ok := h.latestData[dbName]
h.latestMu.RUnlock()
if !ok {
http.Error(w, "database not found", http.StatusNotFound)
return
}
writeJSON(w, m)
}
// GET /api/history/{db_name}/{metric_name}?from=&to=&range= — returns time-series data
func (h *Handler) handleHistory(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
path := strings.TrimPrefix(r.URL.Path, "/api/history/")
parts := strings.SplitN(path, "/", 2)
if len(parts) < 2 {
http.Error(w, "usage: /api/history/{db}/{metric}", http.StatusBadRequest)
return
}
dbName := parts[0]
metricName := parts[1]
// Default: last 1 hour
now := time.Now().Unix()
fromTs := now - 3600
toTs := now
// Parse ?range= (in minutes)
if rangeStr := r.URL.Query().Get("range"); rangeStr != "" {
if mins, err := strconv.ParseInt(rangeStr, 10, 64); err == nil {
fromTs = now - (mins * 60)
}
}
// Parse explicit from/to
if fromStr := r.URL.Query().Get("from"); fromStr != "" {
if ts, err := strconv.ParseInt(fromStr, 10, 64); err == nil {
fromTs = ts
}
}
if toStr := r.URL.Query().Get("to"); toStr != "" {
if ts, err := strconv.ParseInt(toStr, 10, 64); err == nil {
toTs = ts
}
}
points, err := h.store.GetHistory(dbName, metricName, fromTs, toTs)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if points == nil {
points = []storage.MetricPoint{}
}
writeJSON(w, map[string]interface{}{
"database": dbName,
"metric": metricName,
"from": fromTs,
"to": toTs,
"points": points,
})
}
func writeJSON(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(data)
}