notifier.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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/alertlang"
  17. "github.com/gnacho/netpulse/server-go/internal/alerts"
  18. "github.com/gnacho/netpulse/server-go/internal/db"
  19. )
  20. const (
  21. // queueCap acota la cola: ráfagas de urgentes no pueden crecer sin
  22. // límite; si se llena se descarta (el panel ya muestra la alerta).
  23. queueCap = 64
  24. // sendTimeout por envío individual (SPEC-PUSH §1: 10 s).
  25. sendTimeout = 10 * time.Second
  26. // ttl de la notificación en el push service (1 h: si el móvil está
  27. // apagado más tiempo, la alerta ya es historia).
  28. ttlSeconds = 3600
  29. // subscriber VAPID (sub del JWT; informativo para el push service).
  30. // webpush-go antepone "mailto:" si no empieza por "https:".
  31. subscriber = "netpulse@localhost"
  32. )
  33. // payload es el JSON cifrado que recibe el Service Worker (contrato con
  34. // app/src/sw.ts: {title, body, category, severity, url, tag, hint}).
  35. // Desde #689 viaja además {type, vars}: el slug estable del tipo de alerta y
  36. // sus variables de interpolación, para que el SW traduzca la notificación al
  37. // idioma del dispositivo. Los literales title/body/hint se mantienen como
  38. // fallback (SW antiguo o tipo sin clave i18n).
  39. type payload struct {
  40. Title string `json:"title"`
  41. Body string `json:"body"`
  42. Type string `json:"type,omitempty"`
  43. Vars map[string]string `json:"vars,omitempty"`
  44. Category string `json:"category"`
  45. Severity string `json:"severity"`
  46. URL string `json:"url"`
  47. Tag string `json:"tag"` // alertId: dedup nativo del navegador
  48. Hint string `json:"hint,omitempty"` // sugerencia accionable (issue #310)
  49. }
  50. // Notifier implementa alerts.Notifier con entrega asíncrona.
  51. type Notifier struct {
  52. db *db.DB
  53. pub string
  54. priv string
  55. client *http.Client
  56. ch chan alerts.AlertEvent
  57. done chan struct{} // cerrado en Close: Notify posterior es no-op
  58. once sync.Once
  59. wg sync.WaitGroup
  60. }
  61. // NewNotifier crea el Notifier y arranca su worker. pub/priv son el par
  62. // VAPID de EnsureVAPIDKeys.
  63. func NewNotifier(d *db.DB, pub, priv string) *Notifier {
  64. return newNotifier(d, pub, priv, newSafeHTTPClient())
  65. }
  66. // NewNotifierWithClient permite inyectar un cliente HTTP. Se usa en tests que
  67. // necesitan alcanzar un push service TLS local; produccion usa NewNotifier.
  68. func NewNotifierWithClient(d *db.DB, pub, priv string, client *http.Client) *Notifier {
  69. if client == nil {
  70. client = newSafeHTTPClient()
  71. }
  72. return newNotifier(d, pub, priv, client)
  73. }
  74. func newNotifier(d *db.DB, pub, priv string, client *http.Client) *Notifier {
  75. n := &Notifier{
  76. db: d,
  77. pub: pub,
  78. priv: priv,
  79. client: client,
  80. ch: make(chan alerts.AlertEvent, queueCap),
  81. done: make(chan struct{}),
  82. }
  83. n.wg.Add(1)
  84. go n.worker()
  85. return n
  86. }
  87. // Notify encola el evento y vuelve inmediatamente (nunca bloquea el poll).
  88. // Si la cola está llena descarta con aviso: el evento ya está en /api/alerts.
  89. func (n *Notifier) Notify(ev alerts.AlertEvent) {
  90. select {
  91. case <-n.done:
  92. return
  93. case n.ch <- ev:
  94. default:
  95. slog.Warn("push: queue full, notification dropped", "alertId", ev.ID, "title", ev.Title)
  96. }
  97. }
  98. // Close para el worker y espera al envío en curso (acotado por sendTimeout).
  99. func (n *Notifier) Close() {
  100. n.once.Do(func() {
  101. close(n.done)
  102. n.wg.Wait()
  103. })
  104. }
  105. func (n *Notifier) worker() {
  106. defer n.wg.Done()
  107. for {
  108. select {
  109. case <-n.done:
  110. return
  111. case ev := <-n.ch:
  112. n.sendAll(ev)
  113. }
  114. }
  115. }
  116. // payloadJSON serializa el cuerpo de la notificación (SPEC-PUSH §1).
  117. func payloadJSON(ev alerts.AlertEvent) ([]byte, error) {
  118. return json.Marshal(payload{
  119. Title: ev.Title,
  120. Body: ev.Description,
  121. Type: ev.Type,
  122. Vars: ev.Vars,
  123. Category: ev.Category,
  124. Severity: ev.Severity,
  125. URL: "/alerts",
  126. Tag: ev.ID,
  127. Hint: ev.Hint,
  128. })
  129. }
  130. // sendAll envía el evento a TODAS las suscripciones y purga las muertas.
  131. // El payload se serializa POR suscripción (#1334: idioma por suscriptor).
  132. func (n *Notifier) sendAll(ev alerts.AlertEvent) {
  133. subs, err := ListSubscriptions(n.db)
  134. if err != nil {
  135. slog.Error("push: could not list subscriptions", "alertId", ev.ID, "error", err)
  136. return
  137. }
  138. for _, s := range subs {
  139. // #1334: la suscripción recuerda el idioma efectivo de la UI en su
  140. // alta; se compone el payload en ESE idioma (catálogo alertlang, el
  141. // mismo de la traducción global). Sin idioma (legacy): el payload ya
  142. // llega traducido al idioma global por alertlang.Notifier.
  143. evs := ev
  144. if s.Language != "" {
  145. evs = alertlang.LocalizeLang(ev, s.Language)
  146. }
  147. body, err := payloadJSON(evs)
  148. if err != nil {
  149. slog.Error("push: payload no serializable", "alertId", ev.ID, "error", err)
  150. continue
  151. }
  152. n.sendOne(evs, body, s)
  153. }
  154. }
  155. func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
  156. if err := ValidateEndpoint(s.Endpoint); err != nil {
  157. slog.Warn("push: endpoint rechazado", "endpoint", s.Endpoint, "error", err)
  158. return
  159. }
  160. resp, err := webpush.SendNotificationWithContext(context.Background(), body,
  161. &webpush.Subscription{
  162. Endpoint: s.Endpoint,
  163. Keys: webpush.Keys{Auth: s.Auth, P256dh: s.P256dh},
  164. },
  165. &webpush.Options{
  166. HTTPClient: n.client,
  167. Subscriber: subscriber,
  168. VAPIDPublicKey: n.pub,
  169. VAPIDPrivateKey: n.priv,
  170. TTL: ttlSeconds,
  171. })
  172. if err != nil {
  173. slog.Warn("push: send failed", "alertId", ev.ID, "endpoint", s.Endpoint, "error", err)
  174. return
  175. }
  176. defer resp.Body.Close()
  177. _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<16))
  178. if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone {
  179. // Suscripción muerta (expirada o dada de baja): purgar (SPEC-PUSH §1).
  180. if err := DeleteSubscription(n.db, s.Endpoint); err != nil {
  181. slog.Error("push: could not purge dead subscription", "endpoint", s.Endpoint, "error", err)
  182. }
  183. slog.Info("push: subscription purged", "endpoint", s.Endpoint, "status", resp.StatusCode)
  184. return
  185. }
  186. if resp.StatusCode >= 400 {
  187. slog.Warn("push: push service returned an error", "alertId", ev.ID, "endpoint", s.Endpoint, "status", resp.StatusCode)
  188. }
  189. }