notifier.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. // notifier.go — push.Notifier: implementa alerts.Notifier (SPEC-PUSH §1).
  2. // Notify NUNCA bloquea al llamador (el motor de alertas lo invoca desde el
  3. // ciclo de sondeo): encola el evento y un worker único lo drena, enviando a
  4. // todas las suscripciones con timeout de 10 s por envío. 404/410 del push
  5. // service → suscripción muerta → se purga de la DB.
  6. package push
  7. import (
  8. "context"
  9. "encoding/json"
  10. "io"
  11. "log/slog"
  12. "net/http"
  13. "sync"
  14. "time"
  15. webpush "github.com/SherClockHolmes/webpush-go"
  16. "github.com/gnacho/netpulse/server-go/internal/alerts"
  17. "github.com/gnacho/netpulse/server-go/internal/db"
  18. )
  19. const (
  20. // queueCap acota la cola: ráfagas de urgentes no pueden crecer sin
  21. // límite; si se llena se descarta (el panel ya muestra la alerta).
  22. queueCap = 64
  23. // sendTimeout por envío individual (SPEC-PUSH §1: 10 s).
  24. sendTimeout = 10 * time.Second
  25. // ttl de la notificación en el push service (1 h: si el móvil está
  26. // apagado más tiempo, la alerta ya es historia).
  27. ttlSeconds = 3600
  28. // subscriber VAPID (sub del JWT; informativo para el push service).
  29. // webpush-go antepone "mailto:" si no empieza por "https:".
  30. subscriber = "netpulse@localhost"
  31. )
  32. // payload es el JSON cifrado que recibe el Service Worker (contrato con
  33. // app/src/sw.ts: {title, body, category, severity, url, tag}).
  34. type payload struct {
  35. Title string `json:"title"`
  36. Body string `json:"body"`
  37. Category string `json:"category"`
  38. Severity string `json:"severity"`
  39. URL string `json:"url"`
  40. Tag string `json:"tag"` // alertId: dedup nativo del navegador
  41. }
  42. // Notifier implementa alerts.Notifier con entrega asíncrona.
  43. type Notifier struct {
  44. db *db.DB
  45. pub string
  46. priv string
  47. client *http.Client
  48. ch chan alerts.AlertEvent
  49. done chan struct{} // cerrado en Close: Notify posterior es no-op
  50. once sync.Once
  51. wg sync.WaitGroup
  52. }
  53. // NewNotifier crea el Notifier y arranca su worker. pub/priv son el par
  54. // VAPID de EnsureVAPIDKeys.
  55. func NewNotifier(d *db.DB, pub, priv string) *Notifier {
  56. n := &Notifier{
  57. db: d,
  58. pub: pub,
  59. priv: priv,
  60. client: &http.Client{Timeout: sendTimeout},
  61. ch: make(chan alerts.AlertEvent, queueCap),
  62. done: make(chan struct{}),
  63. }
  64. n.wg.Add(1)
  65. go n.worker()
  66. return n
  67. }
  68. // Notify encola el evento y vuelve inmediatamente (nunca bloquea el poll).
  69. // Si la cola está llena descarta con aviso: el evento ya está en /api/alerts.
  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("push: cola llena, notificación descartada", "alertId", ev.ID, "title", ev.Title)
  77. }
  78. }
  79. // Close para el worker y espera al envío en curso (acotado por sendTimeout).
  80. func (n *Notifier) Close() {
  81. n.once.Do(func() {
  82. close(n.done)
  83. close(n.ch)
  84. n.wg.Wait()
  85. })
  86. }
  87. func (n *Notifier) worker() {
  88. defer n.wg.Done()
  89. for ev := range n.ch {
  90. n.sendAll(ev)
  91. }
  92. }
  93. // payloadJSON serializa el cuerpo de la notificación (SPEC-PUSH §1).
  94. func payloadJSON(ev alerts.AlertEvent) ([]byte, error) {
  95. return json.Marshal(payload{
  96. Title: ev.Title,
  97. Body: ev.Description,
  98. Category: ev.Category,
  99. Severity: ev.Severity,
  100. URL: "/alerts",
  101. Tag: ev.ID,
  102. })
  103. }
  104. // sendAll envía el evento a TODAS las suscripciones y purga las muertas.
  105. func (n *Notifier) sendAll(ev alerts.AlertEvent) {
  106. body, err := payloadJSON(ev)
  107. if err != nil {
  108. slog.Error("push: payload no serializable", "alertId", ev.ID, "error", err)
  109. return
  110. }
  111. subs, err := ListSubscriptions(n.db)
  112. if err != nil {
  113. slog.Error("push: no se pudieron listar suscripciones", "alertId", ev.ID, "error", err)
  114. return
  115. }
  116. for _, s := range subs {
  117. n.sendOne(ev, body, s)
  118. }
  119. }
  120. func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
  121. resp, err := webpush.SendNotificationWithContext(context.Background(), body,
  122. &webpush.Subscription{
  123. Endpoint: s.Endpoint,
  124. Keys: webpush.Keys{Auth: s.Auth, P256dh: s.P256dh},
  125. },
  126. &webpush.Options{
  127. HTTPClient: n.client,
  128. Subscriber: subscriber,
  129. VAPIDPublicKey: n.pub,
  130. VAPIDPrivateKey: n.priv,
  131. TTL: ttlSeconds,
  132. })
  133. if err != nil {
  134. slog.Warn("push: envío fallido", "alertId", ev.ID, "endpoint", s.Endpoint, "error", err)
  135. return
  136. }
  137. defer resp.Body.Close()
  138. _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<16))
  139. if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone {
  140. // Suscripción muerta (expirada o dada de baja): purgar (SPEC-PUSH §1).
  141. if err := DeleteSubscription(n.db, s.Endpoint); err != nil {
  142. slog.Error("push: no se pudo purgar suscripción muerta", "endpoint", s.Endpoint, "error", err)
  143. }
  144. slog.Info("push: suscripción purgada", "endpoint", s.Endpoint, "status", resp.StatusCode)
  145. return
  146. }
  147. if resp.StatusCode >= 400 {
  148. slog.Warn("push: push service respondió error", "alertId", ev.ID, "endpoint", s.Endpoint, "status", resp.StatusCode)
  149. }
  150. }