Bladeren bron

feat(alerts): per-channel verbosity - urgent-only or everything (#874) (#878)

Splits what gets logged from what gets pushed. The alert engine now notifies the channel chain for every event that passes the feed config (still honouring suppression); the urgent-only filter moves into a per-channel gate reading <channel>.urgent_only from kv, so it applies without restarting and each transport decides for itself. Default is urgent-only everywhere (no behaviour change). The ntfy card gains an Urgent alerts only toggle; telegram/webhook/web push use the same kv key when their UI grows one.

Closes #874
Nacho 2 maanden geleden
bovenliggende
commit
8bfde2d951

+ 3 - 1
app/public/locales/en/translation.json

@@ -1666,7 +1666,9 @@
       "tokenSet": "set",
       "incomplete": "Topic is required",
       "sendTest": "Test",
-      "hint": "The topic acts as a password: anyone who knows it receives the notifications. Use a long random one."
+      "hint": "The topic acts as a password: anyone who knows it receives the notifications. Use a long random one.",
+      "urgentOnly": "Urgent alerts only",
+      "urgentOnlyHint": "On: the channel receives only urgent alerts (recommended, the usual behavior). Turn it off to receive everything that shows in the feed according to the level chosen in Alerts."
     },
     "mqtt": {
       "title": "MQTT / Home Assistant",

+ 3 - 1
app/public/locales/es/translation.json

@@ -1666,7 +1666,9 @@
       "tokenSet": "configurado",
       "incomplete": "El topic es obligatorio",
       "sendTest": "Probar",
-      "hint": "El topic funciona como contraseña: quien lo conozca recibirá las notificaciones. Usa uno largo y aleatorio."
+      "hint": "El topic funciona como contraseña: quien lo conozca recibirá las notificaciones. Usa uno largo y aleatorio.",
+      "urgentOnly": "Solo alertas urgentes",
+      "urgentOnlyHint": "Activado: el canal recibe solo las alertas urgentes (recomendado, el comportamiento habitual). Desactívalo para que llegue todo lo que aparece en el feed según el nivel elegido en Alertas."
     },
     "mqtt": {
       "title": "MQTT / Home Assistant",

+ 14 - 2
app/src/components/NtfyCard.tsx

@@ -10,6 +10,7 @@ interface NtfyConfig {
   topic: string
   token: string
   enabled: boolean
+  urgentOnly: boolean
 }
 
 // NtfyCard (#766): canal ntfy (ntfy.sh o self-hosted). El topic actúa como
@@ -18,7 +19,7 @@ interface NtfyConfig {
 export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void; bare?: boolean }) {
   const { t } = useTranslation()
   const [state, setState] = useState<NtfyState>('loading')
-  const [cfg, setCfg] = useState<NtfyConfig>({ server: 'https://ntfy.sh', topic: '', token: '', enabled: false })
+  const [cfg, setCfg] = useState<NtfyConfig>({ server: 'https://ntfy.sh', topic: '', token: '', enabled: false, urgentOnly: true })
   const [tokenSet, setTokenSet] = useState(false)
   const [showToken, setShowToken] = useState(false)
   const [error, setError] = useState('')
@@ -29,7 +30,7 @@ export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void
       .then((r) => (r.ok ? r.json() : null))
       .then((d) => {
         if (!alive || !d) return
-        setCfg({ server: d.server || 'https://ntfy.sh', topic: d.topic || '', token: '', enabled: !!d.enabled })
+        setCfg({ server: d.server || 'https://ntfy.sh', topic: d.topic || '', token: '', enabled: !!d.enabled, urgentOnly: d.urgentOnly !== false })
         setTokenSet(!!d.tokenSet)
         setState('idle')
       })
@@ -54,6 +55,7 @@ export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void
         server: cfg.server.trim() || 'https://ntfy.sh',
         topic: cfg.topic.trim(),
         enabled: cfg.enabled,
+        urgentOnly: cfg.urgentOnly,
       }
       if (cfg.token.trim()) body.token = cfg.token.trim()
       const res = await fetch('/api/settings/ntfy', {
@@ -124,6 +126,16 @@ export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void
         />
       </div>
 
+      <div className="flex items-center justify-between gap-4 py-1">
+        <span className="text-sm font-medium text-text-primary">{t('settings.ntfy.urgentOnly')}</span>
+        <Switch
+          checked={cfg.urgentOnly}
+          onCheckedChange={(v) => setCfg((c) => ({ ...c, urgentOnly: v }))}
+          aria-label={t('settings.ntfy.urgentOnly')}
+        />
+      </div>
+      <p className="-mt-1 mb-1 text-[11px] leading-relaxed text-text-muted">{t('settings.ntfy.urgentOnlyHint')}</p>
+
       <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
         <div>
           <label className="mb-1 block text-[11px] font-medium uppercase tracking-wider text-text-muted">

+ 29 - 4
server-go/cmd/netpulse/main.go

@@ -371,18 +371,22 @@ func run() error {
 	// interfaz NO es nil y `if n != nil` de notifierChain no lo filtra →
 	// panic al Notify. Filtrar ANTES de empaquetar.
 	if pushNotifier != nil || webhookNotifier != nil || telegramNotifier != nil || ntfyNotifier != nil {
+		// #874: el filtro de urgencia vive en cada canal (default: solo
+		// urgentes, comportamiento de siempre). El engine dispara todo lo que
+		// pasa config; cada gate recorta según su kv <canal>.urgent_only.
+		kv := &mainKVAdapter{db: dbHandle.DB}
 		chain := notifierChain{}
 		if pushNotifier != nil {
-			chain = append(chain, pushNotifier)
+			chain = append(chain, urgencyGate{n: pushNotifier, kv: kv, key: "push.urgent_only"})
 		}
 		if webhookNotifier != nil {
-			chain = append(chain, webhookNotifier)
+			chain = append(chain, urgencyGate{n: webhookNotifier, kv: kv, key: "webhook.urgent_only"})
 		}
 		if telegramNotifier != nil {
-			chain = append(chain, telegramNotifier)
+			chain = append(chain, urgencyGate{n: telegramNotifier, kv: kv, key: "telegram.urgent_only"})
 		}
 		if ntfyNotifier != nil {
-			chain = append(chain, ntfyNotifier)
+			chain = append(chain, urgencyGate{n: ntfyNotifier, kv: kv, key: "ntfy.urgent_only"})
 		}
 		adapter.AlertsEngine().SetNotifier(chain)
 	}
@@ -756,6 +760,27 @@ func checkAgentToken(d *db.DB, slug, token string) bool {
 	return subtle.ConstantTimeCompare([]byte(got), []byte(stored)) == 1
 }
 
+// urgencyGate implementa alerts.Notifier filtrando por urgencia según un
+// flag por canal en kv (#874). Default (sin flag o "true") = solo urgentes,
+// el comportamiento histórico; con "false" el canal recibe todo lo que pasa
+// el filtro de config del engine. La lectura es por evento: los cambios en
+// la UI aplican sin reiniciar.
+type urgencyGate struct {
+	n   alerts.Notifier
+	kv  *mainKVAdapter
+	key string
+}
+
+func (g urgencyGate) Notify(ev alerts.AlertEvent) {
+	if !ev.Urgent {
+		if v, ok := g.kv.Get(g.key); ok && v == "false" {
+			g.n.Notify(ev)
+		}
+		return
+	}
+	g.n.Notify(ev)
+}
+
 // notifierChain implementa alerts.Notifier encadenando varios notifiers
 // (push + webhook). El motor de alertas solo admite UNO (SetNotifier), así
 // que este compuesto reparte cada evento a todos los miembros no nulos.

+ 32 - 0
server-go/cmd/netpulse/main_test.go

@@ -10,6 +10,7 @@ import (
 	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/db"
 )
 
 // nilNotifier implementa alerts.Notifier; un puntero nil a este tipo,
@@ -115,3 +116,34 @@ func TestWebhookHostForLog(t *testing.T) {
 		t.Fatalf("el host no debe contener credenciales: %q", s)
 	}
 }
+
+// #874: urgencyGate — default (sin kv) = solo urgentes; con
+// "<canal>.urgent_only"="false" = pasa también lo no urgente.
+func TestUrgencyGateDefaultUrgentOnly(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatal(err)
+	}
+	spy := &spyN{}
+	g := urgencyGate{n: spy, kv: &mainKVAdapter{db: d.DB}, key: "ntfy.urgent_only"}
+
+	g.Notify(alerts.AlertEvent{ID: "u1", Urgent: true})
+	g.Notify(alerts.AlertEvent{ID: "n1", Urgent: false})
+	if len(spy.got) != 1 || spy.got[0].ID != "u1" {
+		t.Fatalf("default: %+v", spy.got)
+	}
+
+	if _, err := d.DB.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`,
+		"ntfy.urgent_only", "false"); err != nil {
+		t.Fatal(err)
+	}
+	g.Notify(alerts.AlertEvent{ID: "n2", Urgent: false})
+	if len(spy.got) != 2 || spy.got[1].ID != "n2" {
+		t.Fatalf("con urgent_only=false: %+v", spy.got)
+	}
+}
+
+type spyN struct{ got []alerts.AlertEvent }
+
+func (s *spyN) Notify(ev alerts.AlertEvent) { s.got = append(s.got, ev) }

+ 11 - 7
server-go/internal/alerts/alerts.go

@@ -146,7 +146,9 @@ var Hints = map[string]string{
 // HintFor returns the suggestion for a slug, or "" when it does not exist.
 func HintFor(slug string) string { return Hints[slug] }
 
-// Notifier es el hook de push (Bloque C lo implementa; ahora nil/no-op).
+// Notifier es el hook de notificación externa (push/webhook/telegram/ntfy).
+// El engine dispara TODOS los eventos que pasan config (salvo suprimidos);
+// la decisión de urgencia es por canal (#874).
 // Se llama SOLO para eventos que pasan config Y son Urgent=true.
 type Notifier interface {
 	Notify(ev AlertEvent)
@@ -474,8 +476,10 @@ func (e *Engine) persistLocked(ev AlertEvent) {
 }
 
 // Emit aplica la semántica none/urgent/all EN CREACIÓN, el dedup de 5 min y
-// el cap de 100; devuelve true si el evento pasó (se guardó). Los urgentes
-// que pasan disparan el Notifier (hook de Bloque C).
+// el cap de 100; devuelve true si el evento pasó (se guardó). Los eventos
+// que pasan disparan el Notifier (hook de Bloque C) con SU suppressión; el
+// filtro por URGENCIA vive en cada canal (#874): cada transporte decide si
+// lleva solo urgentes (default) o todo.
 // Supresión topológica (#332): si el router tiene un padre offline en el
 // grafo, la alerta se guarda con SuppressedBy y NO dispara el Notifier.
 func (e *Engine) Emit(ev AlertEvent) bool {
@@ -493,7 +497,7 @@ func (e *Engine) Emit(ev AlertEvent) bool {
 	ok := e.insertaLocked(ev, now, false)
 	n := e.notifier
 	e.mu.Unlock()
-	if ok && n != nil && ev.Urgent && ev.SuppressedBy == "" {
+	if ok && n != nil && ev.SuppressedBy == "" {
 		n.Notify(ev)
 	}
 	return ok
@@ -521,7 +525,7 @@ func (e *Engine) EmitNoDedup(ev AlertEvent) bool {
 	ok := e.insertaLocked(ev, now, true)
 	n := e.notifier
 	e.mu.Unlock()
-	if ok && n != nil && ev.Urgent && ev.SuppressedBy == "" {
+	if ok && n != nil && ev.SuppressedBy == "" {
 		n.Notify(ev)
 	}
 	return ok
@@ -555,7 +559,7 @@ func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
 			e.persistLocked(ev)
 			n := e.notifier
 			e.mu.Unlock()
-			if n != nil && ev.Urgent {
+			if n != nil {
 				n.Notify(ev)
 			}
 			return true
@@ -564,7 +568,7 @@ func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
 	ok := e.insertaLocked(ev, now, false)
 	n := e.notifier
 	e.mu.Unlock()
-	if ok && n != nil && ev.Urgent {
+	if ok && n != nil {
 		n.Notify(ev)
 	}
 	return ok

+ 24 - 3
server-go/internal/alerts/alerts_test.go

@@ -233,13 +233,34 @@ type spyNotifier struct{ got []AlertEvent }
 
 func (s *spyNotifier) Notify(ev AlertEvent) { s.got = append(s.got, ev) }
 
-func TestNotifierOnlyUrgentThatPass(t *testing.T) {
+// #874: el engine dispara el Notifier con TODO lo que pasa el filtro de
+// config (salvo suprimidos); el filtro de URGENCIA vive en cada canal
+// (urgencyGate en main), no aquí.
+func TestNotifierAllPassingNotSuppressed(t *testing.T) {
 	spy := &spyNotifier{}
 	e := New(nil, spy)
-	e.Emit(ev("n1", CatSystem, false)) // pasa, no urgente → sin notify
+	e.Emit(ev("n1", CatSystem, false)) // pasa, no urgente → notify (lo recorta el canal)
 	e.Emit(ev("n2", CatSystem, true))  // pasa, urgente → notify
 	e.Emit(ev("n3", CatSignal, true))  // signal:none → descartado, sin notify
-	if len(spy.got) != 1 || spy.got[0].ID != "n2" {
+	if len(spy.got) != 2 || spy.got[0].ID != "n1" || spy.got[1].ID != "n2" {
+		t.Fatalf("notifier: %+v", spy.got)
+	}
+}
+
+// Suprimidas (SuppressedBy != "") nunca disparan Notifier, urgente o no.
+func TestNotifierSuppressedNeverNotifies(t *testing.T) {
+	spy := &spyNotifier{}
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatal(err)
+	}
+	e := New(d, spy)
+	// Sin grafo de supresión no hay SuppressedBy: se inyecta directo.
+	evSup := ev("s1", CatRouter, true)
+	evSup.SuppressedBy = "gateway"
+	e.Emit(evSup)
+	e.EmitOrUpdate(ev("s2", CatRouter, true))
+	if len(spy.got) != 1 || spy.got[0].ID != "s2" {
 		t.Fatalf("notifier: %+v", spy.got)
 	}
 }

+ 17 - 9
server-go/internal/httpapi/ntfy_settings.go

@@ -10,10 +10,11 @@ import (
 )
 
 type ntfyConfigResponse struct {
-	Server   string `json:"server"`
-	Topic    string `json:"topic"`
-	TokenSet bool   `json:"tokenSet"`
-	Enabled  bool   `json:"enabled"`
+	Server     string `json:"server"`
+	Topic      string `json:"topic"`
+	TokenSet   bool   `json:"tokenSet"`
+	Enabled    bool   `json:"enabled"`
+	UrgentOnly bool   `json:"urgentOnly"`
 }
 
 func (s *server) registerNtfyRoutes(mux *http.ServeMux) {
@@ -22,10 +23,11 @@ func (s *server) registerNtfyRoutes(mux *http.ServeMux) {
 	mux.Handle("GET /api/settings/ntfy", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		cfg := ntfy.LoadConfig(adapter)
 		writeJSON(w, http.StatusOK, ntfyConfigResponse{
-			Server:   cfg.Server,
-			Topic:    cfg.Topic,
-			TokenSet: cfg.Token != "",
-			Enabled:  cfg.Enabled,
+			Server:     cfg.Server,
+			Topic:      cfg.Topic,
+			TokenSet:   cfg.Token != "",
+			Enabled:    cfg.Enabled,
+			UrgentOnly: cfg.UrgentOnly,
 		})
 	})))
 
@@ -35,6 +37,9 @@ func (s *server) registerNtfyRoutes(mux *http.ServeMux) {
 			Topic   string `json:"topic"`
 			Token   string `json:"token"`
 			Enabled bool   `json:"enabled"`
+			// UrgentOnly (#874): nil = no tocar (los bool planos no distinguen
+			// "no mandado" de false).
+			UrgentOnly *bool `json:"urgentOnly"`
 			// Clear: desactivar y limpiar el canal entero (como el disable de
 			// telegram): el PUT normal con enabled=false solo apaga.
 			Clear bool `json:"clear"`
@@ -44,7 +49,7 @@ func (s *server) registerNtfyRoutes(mux *http.ServeMux) {
 		}
 		cfg := ntfy.LoadConfig(adapter)
 		if body.Clear {
-			cfg = ntfy.Config{Server: ntfy.DefaultServer}
+			cfg = ntfy.Config{Server: ntfy.DefaultServer, UrgentOnly: true}
 		} else {
 			if body.Server != "" {
 				cfg.Server = body.Server
@@ -56,6 +61,9 @@ func (s *server) registerNtfyRoutes(mux *http.ServeMux) {
 				cfg.Token = body.Token
 			}
 			cfg.Enabled = body.Enabled
+			if body.UrgentOnly != nil {
+				cfg.UrgentOnly = *body.UrgentOnly
+			}
 		}
 		if err := ntfy.SaveConfig(adapter, cfg); err != nil {
 			writeError(w, http.StatusBadRequest, "invalid_input", err.Error())

+ 21 - 4
server-go/internal/ntfy/ntfy.go

@@ -26,10 +26,11 @@ import (
 )
 
 const (
-	kvKeyServer  = "ntfy.server"
-	kvKeyTopic   = "ntfy.topic"
-	kvKeyToken   = "ntfy.token"
-	kvKeyEnabled = "ntfy.enabled"
+	kvKeyServer     = "ntfy.server"
+	kvKeyTopic      = "ntfy.topic"
+	kvKeyToken      = "ntfy.token"
+	kvKeyEnabled    = "ntfy.enabled"
+	kvKeyUrgentOnly = "ntfy.urgent_only"
 
 	// DefaultServer: ntfy.sh público; un self-hosted se configura igual.
 	DefaultServer = "https://ntfy.sh"
@@ -53,6 +54,11 @@ type Config struct {
 	Topic   string `json:"topic"`
 	Token   string `json:"token,omitempty"` // write-only: nunca vuelve por la API
 	Enabled bool   `json:"enabled"`
+	// UrgentOnly (#874): true (default) = el canal recibe solo alertas
+	// urgentes (comportamiento histórico); false = todo lo que pasa el
+	// filtro de config del feed. La UI lo edita; el gate del engine lee la
+	// MISMA clave kv.
+	UrgentOnly bool `json:"urgentOnly"`
 }
 
 // LoadConfig lee la config con defaults sanos (server vacío = ntfy.sh).
@@ -73,6 +79,10 @@ func LoadConfig(kv kvStore) Config {
 	if v, ok := kv.Get(kvKeyEnabled); ok {
 		cfg.Enabled = v == "true"
 	}
+	cfg.UrgentOnly = true
+	if v, ok := kv.Get(kvKeyUrgentOnly); ok {
+		cfg.UrgentOnly = v != "false"
+	}
 	return cfg
 }
 
@@ -108,6 +118,13 @@ func SaveConfig(kv kvStore, cfg Config) error {
 	if err := kv.Set(kvKeyEnabled, enabled); err != nil {
 		return fmt.Errorf("save enabled: %w", err)
 	}
+	urgentOnly := "true"
+	if !cfg.UrgentOnly {
+		urgentOnly = "false"
+	}
+	if err := kv.Set(kvKeyUrgentOnly, urgentOnly); err != nil {
+		return fmt.Errorf("save urgent_only: %w", err)
+	}
 	return nil
 }