webhook.go 6.1 KB

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