webhook.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Package webhook — notificador SALIENTE de alertas (Fase 8.7b).
  2. //
  3. // Implementa alerts.Notifier con entrega a una URL externa: firma
  4. // HMAC-SHA256 del body, reintentos con backoff exponencial + jitter
  5. // (4xx no se reintenta salvo 429; 5xx sí), DLQ en tabla webhook_events si
  6. // se agotan los reintentos.
  7. //
  8. // Notify NUNCA bloquea al llamador: encola el evento y un worker único lo
  9. // drena. Si la cola está llena se descarta (la alerta ya está en /api/alerts).
  10. package webhook
  11. import (
  12. "bytes"
  13. "context"
  14. "crypto/hmac"
  15. "crypto/sha256"
  16. "encoding/hex"
  17. "encoding/json"
  18. "fmt"
  19. "io"
  20. "log/slog"
  21. "math/rand"
  22. "net/http"
  23. "sync"
  24. "time"
  25. "github.com/gnacho/netpulse/server-go/internal/alerts"
  26. "github.com/gnacho/netpulse/server-go/internal/config"
  27. "github.com/gnacho/netpulse/server-go/internal/db"
  28. )
  29. const (
  30. queueCap = 64
  31. maxBodyCap = 64 << 10 // 64 KB para acotar el cuerpo aceptado
  32. )
  33. // payload es el contrato del webhook (firmado): event_id para idempotencia
  34. // del receptor y datos de la alerta.
  35. type payload struct {
  36. EventID string `json:"event_id"`
  37. Timestamp string `json:"timestamp"` // RFC3339
  38. Type string `json:"type"`
  39. Severity string `json:"severity"`
  40. Title string `json:"title"`
  41. Description string `json:"description"`
  42. Category string `json:"category"`
  43. RouterID string `json:"routerId,omitempty"`
  44. App string `json:"app"`
  45. }
  46. // Notifier implementa alerts.Notifier con entrega asíncrona y DLQ.
  47. type Notifier struct {
  48. cfg config.Webhook
  49. db *db.DB
  50. client *http.Client
  51. ch chan alerts.AlertEvent
  52. done chan struct{}
  53. once sync.Once
  54. wg sync.WaitGroup
  55. }
  56. // NewNotifier crea el Notifier y arranca su worker.
  57. func NewNotifier(cfg config.Webhook, d *db.DB) *Notifier {
  58. n := &Notifier{
  59. cfg: cfg,
  60. db: d,
  61. client: &http.Client{Timeout: cfg.Timeout},
  62. ch: make(chan alerts.AlertEvent, queueCap),
  63. done: make(chan struct{}),
  64. }
  65. n.wg.Add(1)
  66. go n.worker()
  67. return n
  68. }
  69. // Notify encola el evento y vuelve inmediatamente.
  70. func (n *Notifier) Notify(ev alerts.AlertEvent) {
  71. select {
  72. case <-n.done:
  73. return
  74. case n.ch <- ev:
  75. default:
  76. slog.Warn("webhook: cola llena, evento descartado", "alertId", ev.ID, "title", ev.Title)
  77. }
  78. }
  79. // Close para el worker y espera al envío en curso.
  80. func (n *Notifier) Close() {
  81. n.once.Do(func() {
  82. close(n.done)
  83. n.wg.Wait()
  84. })
  85. }
  86. func (n *Notifier) worker() {
  87. defer n.wg.Done()
  88. for {
  89. select {
  90. case <-n.done:
  91. return
  92. case ev := <-n.ch:
  93. n.sendWithRetry(ev)
  94. }
  95. }
  96. }
  97. // payloadJSON construye el body firmable de un evento.
  98. func payloadJSON(ev alerts.AlertEvent) ([]byte, error) {
  99. return json.Marshal(payload{
  100. EventID: ev.ID,
  101. Timestamp: time.Unix(ev.Ts, 0).UTC().Format(time.RFC3339),
  102. Type: "alert." + ev.Category,
  103. Severity: ev.Severity,
  104. Title: ev.Title,
  105. Description: ev.Description,
  106. Category: ev.Category,
  107. RouterID: ev.RouterID,
  108. App: "netpulse",
  109. })
  110. }
  111. // sign calcula la firma HMAC-SHA256 del body crudo.
  112. func sign(body []byte, secret string) string {
  113. mac := hmac.New(sha256.New, []byte(secret))
  114. mac.Write(body)
  115. return "sha256=" + hex.EncodeToString(mac.Sum(nil))
  116. }
  117. // sendWithRetry envía con backoff exponencial + jitter. 4xx (salvo 429) no se
  118. // reintenta; 429/5xx sí. Al agotar reintentos guarda en DLQ.
  119. func (n *Notifier) sendWithRetry(ev alerts.AlertEvent) {
  120. body, err := payloadJSON(ev)
  121. if err != nil {
  122. slog.Error("webhook: payload no serializable", "alertId", ev.ID, "error", err)
  123. return
  124. }
  125. var lastErr error
  126. for attempt := 0; attempt <= n.cfg.Retries; attempt++ {
  127. ctx, cancel := context.WithTimeout(context.Background(), n.cfg.Timeout)
  128. err = n.sendOnce(ctx, ev.ID, body)
  129. cancel()
  130. if err == nil {
  131. return
  132. }
  133. lastErr = err
  134. var retryable bool
  135. if httpErr, ok := err.(*httpStatusError); ok {
  136. // 4xx (salvo 429): error del emisor, no reintentar jamás.
  137. if httpErr.status >= 400 && httpErr.status < 500 && httpErr.status != http.StatusTooManyRequests {
  138. slog.Warn("webhook: 4xx permanente, no se reintenta", "alertId", ev.ID, "status", httpErr.status)
  139. n.saveDLQ(ev, body, lastErr.Error())
  140. return
  141. }
  142. retryable = true // 429/5xx → reintentar
  143. } else {
  144. // Error de transporte (DNS, timeout, conexión rehusada): la
  145. // entrega puede tener éxito en un reintento → backoff (issue #203).
  146. retryable = true
  147. }
  148. if attempt < n.cfg.Retries && retryable {
  149. jitter := time.Duration(rand.Int63n(int64(n.cfg.RetryDelay)))
  150. backoff := n.cfg.RetryDelay * time.Duration(1<<attempt)
  151. time.Sleep(backoff + jitter)
  152. }
  153. }
  154. n.saveDLQ(ev, body, lastErr.Error())
  155. }
  156. // httpStatusError marca la respuesta HTTP para la decisión de reintento.
  157. type httpStatusError struct {
  158. status int
  159. body string
  160. }
  161. func (e *httpStatusError) Error() string {
  162. return fmt.Sprintf("webhook status %d: %s", e.status, e.body)
  163. }
  164. func (n *Notifier) sendOnce(ctx context.Context, eventID string, body []byte) error {
  165. req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.cfg.URL, bytes.NewReader(body))
  166. if err != nil {
  167. return err
  168. }
  169. req.Header.Set("Content-Type", "application/json")
  170. req.Header.Set("User-Agent", "NetPulse-Webhook/2.0")
  171. req.Header.Set("X-Webhook-Signature", sign(body, n.cfg.Secret))
  172. resp, err := n.client.Do(req)
  173. if err != nil {
  174. return err
  175. }
  176. defer resp.Body.Close()
  177. respBody, _ := io.ReadAll(io.LimitReader(resp.Body, maxBodyCap))
  178. if resp.StatusCode >= 200 && resp.StatusCode < 300 {
  179. return nil
  180. }
  181. return &httpStatusError{status: resp.StatusCode, body: string(respBody)}
  182. }
  183. // saveDLQ persiste el evento no entregado para diagnóstico posterior.
  184. func (n *Notifier) saveDLQ(ev alerts.AlertEvent, body []byte, reason string) {
  185. if n.db == nil {
  186. return
  187. }
  188. if _, err := n.db.Exec(
  189. "INSERT OR REPLACE INTO webhook_events (event_id, payload, sent_at, error) VALUES (?, ?, ?, ?)",
  190. ev.ID, string(body), time.Now().Unix(), reason,
  191. ); err != nil {
  192. slog.Error("webhook: no se pudo guardar en DLQ", "alertId", ev.ID, "error", err)
  193. return
  194. }
  195. slog.Warn("webhook: evento a DLQ", "alertId", ev.ID, "error", reason)
  196. }