refresh.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // refresh.go — POST /api/refresh: sondeo manual bajo demanda (botón
  2. // "Refrescar" de la página Topología). No devuelve datos: encola un ciclo de
  3. // sondeo inmediato (tier rápido; los caches LLDP 45 s / backhaul 5 min del
  4. // adapter live se respetan) y el snapshot fresco llega por el SSE normal.
  5. // Anti-martilleo: mínimo 5 s entre refreshes manuales → 429 + Retry-After.
  6. package httpapi
  7. import (
  8. "math"
  9. "net/http"
  10. "strconv"
  11. "time"
  12. )
  13. // refreshMinInterval es el mínimo entre sondeos manuales (global: el sondeo
  14. // es de todos los routers, da igual qué usuario lo pida).
  15. const refreshMinInterval = 5 * time.Second
  16. func (s *server) handleRefresh(w http.ResponseWriter, _ *http.Request) {
  17. s.refreshMu.Lock()
  18. if since := time.Since(s.lastRefresh); since < refreshMinInterval {
  19. retry := int(math.Ceil((refreshMinInterval - since).Seconds()))
  20. s.refreshMu.Unlock()
  21. w.Header().Set("Retry-After", strconv.Itoa(retry))
  22. writeJSON(w, http.StatusTooManyRequests, map[string]any{
  23. "error": "rate_limited",
  24. "retryAfterSec": retry,
  25. })
  26. return
  27. }
  28. s.lastRefresh = time.Now()
  29. s.refreshMu.Unlock()
  30. // Dispara el sondeo en background (nil en tests sin poller → no-op). En
  31. // modo demo el poller re-emite el snapshot demo por SSE igualmente; en
  32. // live sondea todos los routers (tier rápido). Nunca 500 por esto.
  33. if s.pollNow != nil {
  34. s.pollNow()
  35. }
  36. writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
  37. }