feat: implement real-time updates and enhance monitoring system
- Add structured logging with slog throughout application - Implement real-time updates using Server-Sent Events and HTMX - Add broadcaster system for instant UI updates when agents report stats - Replace meta refresh with HTMX-powered seamless updates - Add new API endpoints for HTMX fragments and SSE events - Update templates to use HTMX for instant data refresh - Enhance README with real-time features and updated documentation - Remove obsolete template generation file
This commit is contained in:
@@ -4,12 +4,57 @@ import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"nerd-monitor/internal/stats"
|
||||
"nerd-monitor/internal/store"
|
||||
)
|
||||
|
||||
// Broadcaster manages Server-Sent Events clients.
|
||||
type Broadcaster struct {
|
||||
clients map[chan string]bool
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
var apiBroadcaster = &Broadcaster{
|
||||
clients: make(map[chan string]bool),
|
||||
}
|
||||
|
||||
// Broadcast sends a message to all connected SSE clients.
|
||||
func (b *Broadcaster) Broadcast(message string) {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
|
||||
for clientChan := range b.clients {
|
||||
select {
|
||||
case clientChan <- message:
|
||||
default:
|
||||
// Client channel is full, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AddClient adds a new SSE client.
|
||||
func (b *Broadcaster) AddClient(clientChan chan string) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.clients[clientChan] = true
|
||||
}
|
||||
|
||||
// RemoveClient removes an SSE client.
|
||||
func (b *Broadcaster) RemoveClient(clientChan chan string) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
delete(b.clients, clientChan)
|
||||
close(clientChan)
|
||||
}
|
||||
|
||||
// GetAPIBroadcaster returns the API broadcaster instance.
|
||||
func GetAPIBroadcaster() *Broadcaster {
|
||||
return apiBroadcaster
|
||||
}
|
||||
|
||||
// Handler manages HTTP requests.
|
||||
type Handler struct {
|
||||
store *store.Store
|
||||
@@ -40,6 +85,12 @@ func (h *Handler) ReportStats(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
slog.Debug("Updating agent stats", "agentID", agentID, "hostname", stat.Hostname, "cpu", stat.CPUUsage)
|
||||
h.store.UpdateAgent(agentID, &stat)
|
||||
|
||||
// Broadcast update to all connected SSE clients
|
||||
message := "event: stats-update\ndata: {\"type\": \"stats-update\", \"agentId\": \"" + agentID + "\"}\n\n"
|
||||
slog.Info("Broadcasting stats update", "agentID", agentID)
|
||||
apiBroadcaster.Broadcast(message)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
slog.Debug("Stats report processed successfully", "agentID", agentID)
|
||||
|
||||
Reference in New Issue
Block a user