alerts.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  1. // Package alerts — motor de alertas (SPEC-ALERTAS §1-3): dueño de la lista
  2. // de eventos (máx 100, más recientes primero), config por categoría con 3
  3. // niveles (none/urgent/all) aplicada EN CREACIÓN, dedup de 5 min por
  4. // (category,title,routerId), read-state en servidor y hook Notifier para el
  5. // push (Bloque C; nil = no-op).
  6. //
  7. // Persistencia: tabla kv (misma DB que el resto del servidor):
  8. // - alerts.config.v1: JSON {"router":"urgent",...} (6 claves, defaults).
  9. // - alerts.read.v1: JSON array de IDs leídos (cap 200, FIFO).
  10. package alerts
  11. import (
  12. "encoding/json"
  13. "fmt"
  14. "sort"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/gnacho/netpulse/server-go/internal/db"
  19. )
  20. // Categorías (taxonomía exacta del SPEC §1).
  21. const (
  22. CatRouter = "router"
  23. CatInternet = "internet"
  24. CatClients = "clients"
  25. CatSignal = "signal"
  26. CatVPN = "vpn"
  27. CatSystem = "system"
  28. )
  29. // Categories lista las 6 categorías válidas (orden estable para mensajes).
  30. var Categories = []string{CatRouter, CatInternet, CatClients, CatSignal, CatVPN, CatSystem}
  31. // Niveles de configuración por categoría (SPEC §2).
  32. const (
  33. LevelNone = "none" // el evento se descarta (no se guarda, no cuenta, no empuja)
  34. LevelUrgent = "urgent" // solo pasan eventos Urgent=true
  35. LevelAll = "all" // pasan todos (los urgentes además notifican)
  36. )
  37. var levels = map[string]bool{LevelNone: true, LevelUrgent: true, LevelAll: true}
  38. // Claves kv y límites (SPEC §2-3).
  39. const (
  40. configKey = "alerts.config.v1"
  41. readKey = "alerts.read.v1"
  42. silenceKey = "alerts.silence.v1"
  43. dismissKey = "alerts.dismissed.v1"
  44. MaxEvents = 100
  45. MaxReadIDs = 200
  46. DedupWindow = 5 * time.Minute
  47. )
  48. // AlertEvent (máx 100 en memoria, más recientes primero).
  49. type AlertEvent struct {
  50. ID string `json:"id"`
  51. Category string `json:"category"` // taxonomía SPEC §1
  52. Urgent bool `json:"urgent"` // "rompe silencio" (push + badge)
  53. Severity string `json:"severity"` // display: "warn"|"critical"|"info"|"ok"
  54. Title string `json:"title"`
  55. Description string `json:"description"`
  56. // Hint is an actionable suggestion per alert type (issue #310).
  57. // Filled at emission time from the Hints map; absent when not applicable.
  58. Hint string `json:"hint,omitempty"`
  59. Time string `json:"time"` // LEGADO display; se sigue rellenando
  60. Ts int64 `json:"ts"` // unix SEGUNDOS; el frontend calcula el relativo
  61. Read bool `json:"read"`
  62. RouterID string `json:"routerId"`
  63. // Type: slug estable del tipo de alerta (issue #310). Cuando viaja
  64. // (#671), el frontend traduce título/descripción/hint por clave i18n
  65. // (alerts.types.<slug>.title/.description y alerts.hints.<slug>) en el
  66. // idioma del usuario; los literales Title/Description/Hint siguen en el
  67. // evento como fallback (servidores viejos, demo, claves sin traducir).
  68. Type string `json:"type,omitempty"`
  69. // Vars: valores de interpolación para esas claves (router, mac, temp…).
  70. Vars map[string]string `json:"vars,omitempty"`
  71. // SuppressedBy is the routerId of the parent router whose offline alert
  72. // is suppressing this one (issue #332). Empty when not suppressed.
  73. SuppressedBy string `json:"suppressedBy,omitempty"`
  74. // ResolvedTs (#1349): unix SEGUNDOS de cuándo se resolvió la condición.
  75. // 0/ausente = activa. El evento resuelto NO se borra del log: queda
  76. // marcado para revisión posterior (pestaña Resueltas) y una
  77. // reincidencia con el mismo ID estable lo des-resuelve (upsert).
  78. ResolvedTs int64 `json:"resolvedTs,omitempty"`
  79. // Resolves (#1349): IDs de los eventos que este evento CIERRA (p. ej.
  80. // "Agent updated" resuelve "alert-agent-outdated-<id>"). La UI los
  81. // muestra al expandir el evento de cierre.
  82. Resolves []string `json:"resolves,omitempty"`
  83. // Resolved (#1466): datos de los eventos que este evento cerró (título,
  84. // ts de disparo, tipo y vars para traducir). El feed se pagina (20 por
  85. // página): el evento resuelto puede NO estar en la página que el cliente
  86. // tiene cargada, así que el payload va autocontenido y la UI no depende
  87. // de buscarlo en su feed local.
  88. Resolved []ResolvedEvent `json:"resolved,omitempty"`
  89. // Snoozed / SnoozedUntil (#2185): la alerta esta pospuesta. La fila SIGUE
  90. // en el feed (el incidente se sigue monitorizando y su cierre se sigue
  91. // detectando), pero no cuenta como pendiente, no dispara avisos y no se
  92. // re-emite mientras dure. SnoozedUntil 0 con Snoozed=true = sin fecha.
  93. Snoozed bool `json:"snoozed,omitempty"`
  94. SnoozedUntil int64 `json:"snoozedUntil,omitempty"`
  95. // Volatile (#966): la alerta vive SOLO en memoria (no se persiste en
  96. // alert_log ni sobrevive a reinicios) y desaparece del feed cuando su
  97. // condicion se resuelve (engine.Remove). Uso: caida de agente, cuya
  98. // semantica es "viva por router", no un historico de incidentes.
  99. Volatile bool `json:"-"`
  100. // seeded: fixture del dataset demo (Seed). No lo somete el filtro de
  101. // nivel "none" (#1659): la historia canónica del demo se sirve completa
  102. // aunque su config deje la categoría en "none".
  103. seeded bool
  104. }
  105. // ResolvedEvent (#1466): datos mínimos del evento que un cierre resolvió.
  106. // Type+Vars permiten traducir el título en el front; Title/Ts son el
  107. // fallback literal y el instante del disparo original.
  108. type ResolvedEvent struct {
  109. ID string `json:"id"`
  110. Title string `json:"title,omitempty"`
  111. Ts int64 `json:"ts"`
  112. Type string `json:"type,omitempty"`
  113. Vars map[string]string `json:"vars,omitempty"`
  114. }
  115. // Stable alert-type slugs (issue #310): keys of the Hints map.
  116. const (
  117. HintAgentDown = "agent-down"
  118. HintAgentDownSSH = "agent-down-ssh" // variante: satélite degrada a SSH (#671)
  119. HintGatewayUnrch = "gateway-unreachable"
  120. HintHighTemp = "high-temperature"
  121. HintPortFlapping = "port-flapping"
  122. HintDeviceOffline = "device-offline"
  123. HintUnknownDevice = "unknown-device"
  124. HintSsidImpostor = "wifi-ssid-impostor"
  125. HintNewNeighborSsid = "new-neighbor-ssid"
  126. HintNewClient = "new-client"
  127. HintFirmware = "firmware-outdated"
  128. // #1412: el target configurado es MÁS VIEJO que lo instalado (posible
  129. // downgrade, casi siempre un target mal puesto).
  130. HintFirmwareDowngrade = "firmware-downgrade-target"
  131. // #1444: el target configurado NO figura entre los releases publicados
  132. // de OpenWrt (chequeo periódico contra downloads.openwrt.org). Es un
  133. // aviso de configuración, no una alerta de firmware desactualizado.
  134. HintFirmwareUnknownTarget = "firmware-target-unknown"
  135. HintWanDown = "wan-down"
  136. HintWifiWeak = "wifi-weak"
  137. HintGhostPort = "ghost-port"
  138. HintDegradedLink = "degraded-link"
  139. HintAgentOutdated = "agent-outdated"
  140. HintWanSlow = "wan-slow"
  141. HintUplinkSwitch = "uplink-switched"
  142. HintSnmpFailing = "snmp-failing"
  143. )
  144. // Additional stable alert-type slugs (issue #712): recovery/info/beacon/rearmer
  145. // types emitted without Type/Vars in #671. They carry no hint.
  146. const (
  147. TypeAgentRecovered = "agent-recovered"
  148. TypeSSHAccessLost = "ssh-access-lost"
  149. TypeSSHAccessRecovered = "ssh-access-recovered"
  150. TypeAgentUpdated = "agent-updated"
  151. TypeRouterRecovered = "router-recovered"
  152. TypeWireguardHandshake = "wireguard-handshake"
  153. TypeWireguardDisconnect = "wireguard-disconnect"
  154. TypePortStable = "port-stable"
  155. TypeGhostPortRecovered = "ghost-port-recovered"
  156. TypeLinkRecovered = "link-recovered"
  157. TypeSwitchLoop = "switch-loop"
  158. TypePortDisabled = "port-disabled"
  159. TypePortRecovered = "port-recovered"
  160. TypeLinkDown = "link-down"
  161. TypeLinkUp = "link-up"
  162. TypeSfpRxLow = "sfp-rx-low"
  163. TypeSfpTempHigh = "sfp-temp-high"
  164. TypeSwitchRebooted = "switch-rebooted"
  165. TypeAgentRearmed = "agent-rearmed"
  166. TypeAgentReinstalled = "agent-reinstalled"
  167. TypeAutoRearmFailed = "auto-rearm-failed"
  168. TypeUplinkRestored = "uplink-restored"
  169. TypeSnmpRecovered = "snmp-recovered"
  170. // #1354: router offline (was reused from HintDeviceOffline, now its own slug)
  171. // and client device offline (opt-in, volatile).
  172. TypeRouterOffline = "router-offline"
  173. TypeDeviceOffline = "device-offline"
  174. // #1452: cierre automático de la alerta de señal débil (episodio
  175. // resuelto con valor de recuperación y duración).
  176. TypeWifiWeakRecovered = "wifi-weak-recovered"
  177. // #1873: una MAC que solo aparece en una tabla de reenvío, sin lease,
  178. // ARP, ND ni mDNS, y que sigue ahí mucho rato. Informativa, no urgente.
  179. TypeUnverifiedMac = "unverified-mac"
  180. // TypeWiFiNoIP: cliente asociado por WiFi que no tiene dirección (#2111).
  181. // Informativa, no urgente: es una marca visible, no un problema.
  182. TypeWiFiNoIP = "wifi-no-ip"
  183. )
  184. // Hints maps each alert-type slug to its actionable suggestion. Emitters copy
  185. // the value into AlertEvent.Hint; the feed and push render it as a helper line.
  186. // The canonical language is English (#1014): alertlang and the web feed swap
  187. // it for the catalog wording when the target language is Spanish.
  188. var Hints = map[string]string{
  189. HintAgentDown: "Check the router power and connection; if it does not recover, reinstall the agent from LuCI.",
  190. HintAgentDownSSH: "Check the router's power and connection; if it doesn't recover, reinstall the agent from LuCI.",
  191. HintGatewayUnrch: "Check the connection between the gateway and the rest of the network.",
  192. HintHighTemp: "Improve ventilation and keep the router away from heat sources.",
  193. HintPortFlapping: "Check the cable or switch port: an unstable link is usually the culprit.",
  194. HintDeviceOffline: "Verify the device power and network cable.",
  195. HintUnknownDevice: "If you do not recognize it, block it or mark it as trusted in Settings.",
  196. HintSsidImpostor: "An unknown radio is broadcasting your network name. Check the area around the hearing AP; if you do not recognize the BSSID, treat it as a rogue AP.",
  197. HintNewNeighborSsid: "A new network name has been broadcasting nearby for hours. If it is not yours, find out what it is (a new router, an IoT device in pairing mode, a hotspot); if it is a permanent neighbor you do not care about, dismiss the alert - it will not repeat.",
  198. HintNewClient: "A device just joined the network for the first time. If you recognize it, name it or mark it as trusted in Settings; if not, check what it is.",
  199. HintFirmware: "Your router has newer firmware available; check Firmware upgrades (Labs) or LuCI.",
  200. HintFirmwareDowngrade: "The configured target is older than the installed firmware; fix the target version in the fleet unit settings.",
  201. HintWanDown: "Check the modem/ONT and contact your ISP if the outage persists.",
  202. HintWifiWeak: "Move the device closer to an access point or relocate the AP.",
  203. HintGhostPort: "Check the cable and the connected device: an active port that goes silent usually means a loose cable or a powered-off device.",
  204. HintDegradedLink: "Check the cable and connectors: a degraded link is often a sign of a damaged cable or a loose connector.",
  205. HintAgentOutdated: "Update the agent from Settings, Agents (Update button); if it's a NetGrip panel, update it from its own panel.",
  206. HintUplinkSwitch: "Check the line that dropped: the router goes back to it on its own once it recovers.",
  207. HintWanSlow: "Restart the router and the modem/ONT and run the test again; if it stays low, contact your ISP (line degradation or congestion in your area).",
  208. HintSnmpFailing: "Check the SNMP community string and switch port: the device answers ping but not polling.",
  209. }
  210. // HintFor returns the suggestion for a slug, or "" when it does not exist.
  211. func HintFor(slug string) string { return Hints[slug] }
  212. // Notifier es el hook de notificación externa (push/webhook/telegram/ntfy).
  213. // El engine lo dispara solo para eventos cuya categoría permite notificación
  214. // según el nivel configurado (#1413): none nunca, urgent solo Urgent, all
  215. // siempre. La decisión de urgencia fina por canal sigue en cada integración
  216. // (#874, urgencyGate). Los eventos suprimidos topológicamente se guardan con
  217. // SuppressedBy y nunca notifican.
  218. type Notifier interface {
  219. Notify(ev AlertEvent)
  220. }
  221. // DefaultConfig devuelve una copia de los defaults del SPEC §2.
  222. // clients=all desde issue #196: "dispositivo desconocido" ya no es urgente
  223. // pero debe seguir siendo visible (con clients:urgent se descartaría entero).
  224. func DefaultConfig() map[string]string {
  225. return map[string]string{
  226. CatRouter: LevelUrgent,
  227. CatInternet: LevelUrgent,
  228. CatClients: LevelAll,
  229. CatSignal: LevelNone,
  230. CatVPN: LevelNone,
  231. CatSystem: LevelAll,
  232. }
  233. }
  234. // Engine es el motor: aplica config/dedup/cap en Emit y guarda el read-state.
  235. // Seguro para uso concurrente (los adapters emiten desde varios goroutines).
  236. type Engine struct {
  237. mu sync.Mutex
  238. db *db.DB // nil → solo memoria (tests)
  239. notifier Notifier
  240. // startedAt: arranque de ESTA instancia. Las alertas con Ts anterior a
  241. // startedAt vienen de una sesión previa: si se re-emiten (update), es
  242. // un episodio nuevo tras el reinicio y vuelven a no-leídas (#1094).
  243. startedAt time.Time
  244. now func() time.Time
  245. cfg map[string]string
  246. list []AlertEvent
  247. dedup map[string]int64 // key (cat|title|routerId) → último emit (unix ms)
  248. readSet map[string]bool
  249. readOrd []string // FIFO de IDs (cap 200) para podar readSet
  250. silenceMap map[string]int64 // dedup key → expiry (unix seconds); 0 = forever
  251. // dismissed: IDs de alertas limpiadas por el usuario (issue #833). Se
  252. // filtran del feed y del unread; si el mismo ID se vuelve a emitir (la
  253. // condición se re-dispara), sale del conjunto y reaparece.
  254. dismissed map[string]bool
  255. // suppression: grafo de dependencias topológicas (issue #332).
  256. // nil = sin supresión (tests o arranque sin topología).
  257. suppression *SuppressionGraph
  258. // persistLog: volcar el log a alert_log y restaurarlo al arranque
  259. // (issue #798). false solo en el dataset demo, que es sintético y se
  260. // regenera en cada arranque (cargar/re-guardar duplicaría las semillas).
  261. persistLog bool
  262. // onChange (#1434): callback invocado SIN e.mu tras una mutación que
  263. // altera la lista servida o el read-state (mark-read, dismiss, resolve,
  264. // silence). El server lo usa para reemitir el estado del feed por SSE
  265. // al instante; el poller ya no es el único camino de actualización.
  266. onChange func()
  267. }
  268. // PersistMaxEvents es la cota de filas del log persistido (issue #798): la
  269. // lista en memoria se queda en MaxEvents, pero en disco se conservan más
  270. // para restaurarlas tras un reinicio (p. ej. el del self-update).
  271. const PersistMaxEvents = 500
  272. // New crea el motor cargando config, read-state y el log persistido (si db).
  273. func New(d *db.DB, n Notifier) *Engine { return newEngine(d, n, true) }
  274. // NewVolatile crea el motor SIN persistencia del log de alertas. El dataset
  275. // demo es sintético y se regenera en cada arranque: cargar el log traería
  276. // entradas ajenas al canon y re-guardarlo duplicaría las semillas.
  277. func NewVolatile(d *db.DB, n Notifier) *Engine { return newEngine(d, n, false) }
  278. func newEngine(d *db.DB, n Notifier, persistLog bool) *Engine {
  279. e := &Engine{
  280. db: d,
  281. notifier: n,
  282. now: time.Now,
  283. startedAt: time.Now(),
  284. cfg: DefaultConfig(),
  285. dedup: map[string]int64{},
  286. readSet: map[string]bool{},
  287. silenceMap: map[string]int64{},
  288. dismissed: map[string]bool{},
  289. persistLog: persistLog,
  290. }
  291. if d != nil {
  292. var raw string
  293. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", configKey).Scan(&raw); err == nil {
  294. saved := map[string]string{}
  295. if json.Unmarshal([]byte(raw), &saved) == nil {
  296. for _, cat := range Categories {
  297. if lv, ok := saved[cat]; ok && levels[lv] {
  298. e.cfg[cat] = lv
  299. }
  300. }
  301. }
  302. }
  303. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", readKey).Scan(&raw); err == nil {
  304. ids := []string{}
  305. if json.Unmarshal([]byte(raw), &ids) == nil {
  306. for _, id := range ids {
  307. if id != "" && !e.readSet[id] {
  308. e.readSet[id] = true
  309. e.readOrd = append(e.readOrd, id)
  310. }
  311. }
  312. }
  313. }
  314. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", silenceKey).Scan(&raw); err == nil {
  315. _ = json.Unmarshal([]byte(raw), &e.silenceMap)
  316. }
  317. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", dismissKey).Scan(&raw); err == nil {
  318. ids := []string{}
  319. if json.Unmarshal([]byte(raw), &ids) == nil {
  320. for _, id := range ids {
  321. if id != "" {
  322. e.dismissed[id] = true
  323. }
  324. }
  325. }
  326. }
  327. e.purgeVolatileHistoryLocked()
  328. e.purgeSupersededWeakClosures()
  329. e.loadPersistedLocked()
  330. // #1034: poda por antigüedad al arrancar (además de la horaria de
  331. // main): una retención bajada mientras el daemon estaba parado se
  332. // aplica en el primer arranque posterior.
  333. e.PruneLogByRetention()
  334. }
  335. return e
  336. }
  337. // purgeVolatileHistoryLocked: purga one-shot al arrancar (#966). Las alertas
  338. // de caida de agente AHORA son volatiles (no se persisten), pero las
  339. // instalaciones previas acumularon un historico de agent-down* en alert_log
  340. // que seguiria reapareciendo tras cada reinicio. Se borran ANTES de cargar
  341. // el log, para que ni siquiera el primer arranque tras actualizar lo muestre.
  342. func (e *Engine) purgeVolatileHistoryLocked() {
  343. if e.db == nil || !e.persistLog {
  344. return
  345. }
  346. _, _ = e.db.Exec(
  347. `DELETE FROM alert_log WHERE id LIKE 'alert-agent-down-%'
  348. OR type IN ('agent-down', 'agent-down-ssh')`)
  349. }
  350. // purgeSupersededWeakClosures: purga one-shot al arrancar (#1518). Los
  351. // cierres de señal débil ANTERIORES al ID estable llevaban timestamp en el ID
  352. // (alert-weak-<mac>-ok-<ts>): cada episodio dejaba una "resuelta" idéntica en
  353. // el log. Se borran de alert_log ANTES de cargar (el ID estable nuevo las
  354. // reemplaza en adelante); los avisos originales resueltos no se tocan.
  355. func (e *Engine) purgeSupersededWeakClosures() {
  356. if e.db == nil || !e.persistLog {
  357. return
  358. }
  359. _, _ = e.db.Exec(`DELETE FROM alert_log WHERE id LIKE 'alert-weak-%-ok-%'`)
  360. }
  361. // loadPersistedLocked restaura el log desde alert_log (issue #798): los
  362. // últimos MaxEvents eventos (más recientes primero), reconstruyendo el mapa
  363. // de dedup (para no re-notificar dentro de la ventana tras un reinicio) y
  364. // sembrando el read-set desde la columna read espejada.
  365. func (e *Engine) loadPersistedLocked() {
  366. if !e.persistLog {
  367. return
  368. }
  369. rows, err := e.db.Query(
  370. `SELECT id, ts, category, type, severity, urgent, title, description, hint,
  371. router_id, suppressed_by, vars, read_flag, resolved_ts, resolves
  372. FROM alert_log ORDER BY ts DESC LIMIT ?`, MaxEvents)
  373. if err != nil {
  374. return
  375. }
  376. defer rows.Close()
  377. type row struct {
  378. ev AlertEvent
  379. read bool
  380. }
  381. loaded := []row{}
  382. for rows.Next() {
  383. var ev AlertEvent
  384. var typ, sev, hint, routerID, suppressedBy, varsRaw, resolvesRaw string
  385. var urgent, read int
  386. if err := rows.Scan(&ev.ID, &ev.Ts, &ev.Category, &typ, &sev, &urgent,
  387. &ev.Title, &ev.Description, &hint, &routerID, &suppressedBy, &varsRaw, &read, &ev.ResolvedTs, &resolvesRaw); err != nil {
  388. return
  389. }
  390. // #833: una alerta limpiada no vuelve a aparecer tras un reinicio.
  391. if e.dismissed[ev.ID] {
  392. continue
  393. }
  394. // #1349: un evento resuelto vuelve al feed MARCADO (historia
  395. // consultable en Resueltas) y nunca como pendiente de leer.
  396. if ev.ResolvedTs > 0 {
  397. read = 1
  398. }
  399. ev.Type = typ
  400. ev.Severity = sev
  401. ev.Urgent = urgent != 0
  402. ev.Hint = hint
  403. ev.RouterID = routerID
  404. ev.SuppressedBy = suppressedBy
  405. if varsRaw != "" {
  406. vars := map[string]string{}
  407. if json.Unmarshal([]byte(varsRaw), &vars) == nil {
  408. ev.Vars = vars
  409. }
  410. }
  411. // #1466: referencias del cierre (qué eventos resolvió).
  412. if resolvesRaw != "" {
  413. var ids []string
  414. if json.Unmarshal([]byte(resolvesRaw), &ids) == nil && len(ids) > 0 {
  415. ev.Resolves = ids
  416. }
  417. }
  418. loaded = append(loaded, row{ev: ev, read: read != 0})
  419. }
  420. // rows.Next() consumió las filas de más reciente a más antigua; la lista
  421. // interna ya va en ese orden (append al frente en insertaLocked).
  422. for _, r := range loaded {
  423. e.list = append(e.list, r.ev)
  424. key := r.ev.Category + "|" + r.ev.Title + "|" + r.ev.RouterID
  425. // Las filas vienen de más reciente a más antigua: solo la primera por
  426. // clave es el timestamp de dedup válido (no pisar con la más vieja).
  427. // #1349: un RESUELTO no siembra dedup - su condición está cerrada y
  428. // una reincidencia tras reinicio debe alertar de inmediato (mismo
  429. // criterio que Resolve en caliente, que borra la clave de dedup).
  430. if r.ev.ResolvedTs == 0 {
  431. if _, ok := e.dedup[key]; !ok {
  432. e.dedup[key] = r.ev.Ts * 1000
  433. }
  434. }
  435. if r.read && r.ev.ID != "" && !e.readSet[r.ev.ID] {
  436. e.readSet[r.ev.ID] = true
  437. e.readOrd = append(e.readOrd, r.ev.ID)
  438. }
  439. }
  440. }
  441. // SetNotifier sustituye el hook Notifier (wiring de Bloque C desde main;
  442. // nil = no-op). Seguro en caliente: Emit lo lee bajo el mismo mutex.
  443. func (e *Engine) SetNotifier(n Notifier) {
  444. e.mu.Lock()
  445. defer e.mu.Unlock()
  446. e.notifier = n
  447. }
  448. // SetClock sustituye el reloj (solo tests).
  449. func (e *Engine) SetClock(f func() time.Time) {
  450. e.mu.Lock()
  451. defer e.mu.Unlock()
  452. e.now = f
  453. }
  454. // SetSuppression wirea el grafo de dependencias topológicas (issue #332).
  455. // nil desactiva la supresión (tests o arranque sin topología).
  456. func (e *Engine) SetSuppression(g *SuppressionGraph) {
  457. e.mu.Lock()
  458. defer e.mu.Unlock()
  459. e.suppression = g
  460. }
  461. // SetOnChange (#1434) fija el callback de mutación del feed. Se invoca DESPUÉS
  462. // de soltar e.mu, así que el receptor puede leer el engine (List/UnreadCount)
  463. // sin riesgo de deadlock; solo hay que evitar mutar el engine desde dentro
  464. // (recursión de notificaciones).
  465. func (e *Engine) SetOnChange(f func()) {
  466. e.mu.Lock()
  467. defer e.mu.Unlock()
  468. e.onChange = f
  469. }
  470. // Config devuelve una copia de la config efectiva (siempre las 6 claves).
  471. func (e *Engine) Config() map[string]string {
  472. e.mu.Lock()
  473. defer e.mu.Unlock()
  474. out := make(map[string]string, len(e.cfg))
  475. for k, v := range e.cfg {
  476. out[k] = v
  477. }
  478. return out
  479. }
  480. // SetConfig aplica un parche parcial {"signal":"all"}: valida categorías y
  481. // niveles (error → 400 en la API), fusiona y persiste en kv.
  482. func (e *Engine) SetConfig(patch map[string]string) error {
  483. badCats, badVals := []string{}, []string{}
  484. for k, v := range patch {
  485. if !contains(Categories, k) {
  486. badCats = append(badCats, k)
  487. } else if !levels[v] {
  488. badVals = append(badVals, fmt.Sprintf("%s=%q", k, v))
  489. }
  490. }
  491. if len(badCats) > 0 || len(badVals) > 0 {
  492. sort.Strings(badCats)
  493. sort.Strings(badVals)
  494. parts := []string{}
  495. if len(badCats) > 0 {
  496. parts = append(parts, "categorías desconocidas: "+strings.Join(badCats, ", "))
  497. }
  498. if len(badVals) > 0 {
  499. parts = append(parts, "niveles inválidos: "+strings.Join(badVals, ", "))
  500. }
  501. return fmt.Errorf("invalid config (%s)", strings.Join(parts, "; "))
  502. }
  503. e.mu.Lock()
  504. defer e.mu.Unlock()
  505. for k, v := range patch {
  506. e.cfg[k] = v
  507. }
  508. e.saveConfigLocked()
  509. return nil
  510. }
  511. // notificaLocked: ¿la config de la categoría permite NOTIFICAR este evento?
  512. // (issue #1413: los niveles son política de notificación, no de ingesta:
  513. // todo se guarda en el log y el feed; el nivel solo gobierna el Notifier).
  514. // none = nunca; urgent = solo eventos Urgent; all = siempre. Categoría
  515. // desconocida: notifica (la validación estricta es de SetConfig).
  516. // Requiere e.mu ya tomado.
  517. func (e *Engine) notificaLocked(ev AlertEvent) bool {
  518. level, known := e.cfg[ev.Category]
  519. if known {
  520. if level == LevelNone || (level == LevelUrgent && !ev.Urgent) {
  521. return false
  522. }
  523. }
  524. return true
  525. }
  526. // hiddenByLevelLocked: una categoría en nivel "none" no existe para el
  527. // operador. No entra al feed, no cuenta en la campana y no se persiste
  528. // (issue #1659). El nivel "urgent" sigue siendo solo política de
  529. // notificación (#1413): sus eventos se registran y solo silencian el aviso.
  530. // Los fixtures del demo (Seed) quedan exentos para servir el canon completo.
  531. func (e *Engine) hiddenByLevelLocked(ev AlertEvent) bool {
  532. return !ev.seeded && e.cfg[ev.Category] == LevelNone
  533. }
  534. // insertaLocked inserta un evento nuevo al frente con dedup y cap.
  535. // Requiere e.mu ya tomado. Devuelve true si se guardó. skipDedup omite la
  536. // ventana de dedup de 5 min (issue #846: los incidentes con estado propio,
  537. // p.ej. offline de router, se trackean fuera del engine y su alerta debe
  538. // entrar aunque la ventana cubra la emisión de un incidente ya cerrado).
  539. func (e *Engine) insertaLocked(ev AlertEvent, now time.Time, skipDedup bool) bool {
  540. key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
  541. if e.isSilencedLocked(key) {
  542. return false
  543. }
  544. // #1659: el nivel "none" oculta la categoría por completo (feed, campana
  545. // y alert_log). Se descarta antes del dedup para no consumir la ventana.
  546. if e.hiddenByLevelLocked(ev) {
  547. return false
  548. }
  549. if !skipDedup {
  550. if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
  551. return false
  552. }
  553. e.dedup[key] = now.UnixMilli()
  554. }
  555. // #2292: una excepción activa (tipo, host, destino) descarta la alerta y
  556. // cuenta el impacto. Va después del dedup para que una condición
  557. // persistente no sume un impacto por tick.
  558. if e.db != nil && !ev.seeded {
  559. if _, ok := MatchException(e.db, ev, now); ok {
  560. return false
  561. }
  562. }
  563. // #833: si el ID estaba limpiado y la condición se re-dispara, la alerta
  564. // vuelve al feed (dismissed solo oculta el histórico, no el presente).
  565. if _, was := e.dismissed[ev.ID]; was {
  566. delete(e.dismissed, ev.ID)
  567. e.saveDismissedLocked()
  568. }
  569. if ev.Ts == 0 {
  570. ev.Ts = now.Unix()
  571. }
  572. if ev.Time == "" {
  573. ev.Time = "just now"
  574. }
  575. ev.Read = false
  576. e.list = append([]AlertEvent{ev}, e.list...)
  577. if len(e.list) > MaxEvents {
  578. e.list = e.list[:MaxEvents]
  579. }
  580. e.persistLocked(ev)
  581. return true
  582. }
  583. // persistLocked escribe (o actualiza) el evento en alert_log y poda la tabla
  584. // a PersistMaxEvents filas (issue #798). El read NO se toca aquí: la fuente
  585. // de verdad del leído es el read-set de kv y se espeja aparte en MarkRead.
  586. // Best-effort: un fallo de BD nunca debe romper el camino de alertado.
  587. func (e *Engine) persistLocked(ev AlertEvent) {
  588. if e.db == nil || !e.persistLog || ev.ID == "" || ev.Volatile {
  589. return
  590. }
  591. varsRaw := ""
  592. if len(ev.Vars) > 0 {
  593. if raw, err := json.Marshal(ev.Vars); err == nil {
  594. varsRaw = string(raw)
  595. }
  596. }
  597. // #1466: las referencias del cierre se persisten; si no, tras un reinicio
  598. // el evento de cierre queda sin saber qué resolvió.
  599. resolvesRaw := ""
  600. if len(ev.Resolves) > 0 {
  601. if raw, err := json.Marshal(ev.Resolves); err == nil {
  602. resolvesRaw = string(raw)
  603. }
  604. }
  605. urgent := 0
  606. if ev.Urgent {
  607. urgent = 1
  608. }
  609. _, _ = e.db.Exec(
  610. `INSERT INTO alert_log (id, ts, category, type, severity, urgent, title, description, hint, router_id, suppressed_by, vars, resolved_ts, resolves)
  611. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  612. ON CONFLICT(id) DO UPDATE SET ts=excluded.ts, category=excluded.category,
  613. type=excluded.type, severity=excluded.severity, urgent=excluded.urgent,
  614. title=excluded.title, description=excluded.description, hint=excluded.hint,
  615. router_id=excluded.router_id, suppressed_by=excluded.suppressed_by, vars=excluded.vars,
  616. resolved_ts=excluded.resolved_ts, resolves=excluded.resolves`,
  617. ev.ID, ev.Ts, ev.Category, ev.Type, ev.Severity, urgent,
  618. ev.Title, ev.Description, ev.Hint, ev.RouterID, ev.SuppressedBy, varsRaw, ev.ResolvedTs, resolvesRaw)
  619. _, _ = e.db.Exec(
  620. `DELETE FROM alert_log WHERE id NOT IN
  621. (SELECT id FROM alert_log ORDER BY ts DESC LIMIT ?)`, PersistMaxEvents)
  622. }
  623. // Emit aplica el dedup de 5 min y el cap de 100; devuelve true si el evento
  624. // se guardó. El nivel de la categoría gobierna qué se registra: "none" no
  625. // entra al feed ni se persiste (#1659), "urgent" sí se registra y solo
  626. // silencia el aviso (#1413).
  627. // El filtro por URGENCIA fino vive en cada canal (#874): cada transporte
  628. // decide si lleva solo urgentes (default) o todo.
  629. // Supresión topológica (#332): si el router tiene un padre offline en el
  630. // grafo, la alerta se guarda con SuppressedBy y NO dispara el Notifier.
  631. func (e *Engine) Emit(ev AlertEvent) bool {
  632. e.mu.Lock()
  633. if e.suppression != nil && ev.RouterID != "" {
  634. if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
  635. ev.SuppressedBy = parent
  636. }
  637. }
  638. // #914: default de Ts/Time ANTES de insertar y notificar. Hasta ahora el
  639. // default vivía solo en insertaLocked, cuya copia local no propagaba a
  640. // esta `ev`: el notifier (ntfy/Telegram/webhook) recibía Ts=0 y pintaba
  641. // la hora estática 16:00:00 (epoch en zona UTC-8).
  642. if ev.Ts == 0 {
  643. ev.Ts = e.now().Unix()
  644. }
  645. if ev.Time == "" {
  646. ev.Time = "just now"
  647. }
  648. now := e.now()
  649. ok := e.insertaLocked(ev, now, false)
  650. n := e.notifier
  651. notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
  652. e.mu.Unlock()
  653. if ok && notify {
  654. n.Notify(ev)
  655. }
  656. return ok
  657. }
  658. // EmitNoDedup es Emit sin la ventana de dedup de 5 min (silencio, cap,
  659. // supresión y política de notificación por categoría SÍ aplican; issue #1413:
  660. // la config ya no filtra la ingesta, solo la notificación). Uso:
  661. // alertas cuya condición se trackea por estado fuera del engine (issue #846,
  662. // offline de router): al ABRIR incidente la alerta debe entrar siempre,
  663. // porque el cierre del incidente anterior ya retiró la suya del feed y el
  664. // dedup la bloquearía — el "una alerta por outage" lo garantiza el tracking
  665. // de incidente (offlineOpen), no la ventana.
  666. func (e *Engine) EmitNoDedup(ev AlertEvent) bool {
  667. e.mu.Lock()
  668. if e.suppression != nil && ev.RouterID != "" {
  669. if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
  670. ev.SuppressedBy = parent
  671. }
  672. }
  673. // #914: mismo default de Ts/Time que en Emit antes de notificar.
  674. if ev.Ts == 0 {
  675. ev.Ts = e.now().Unix()
  676. }
  677. if ev.Time == "" {
  678. ev.Time = "just now"
  679. }
  680. now := e.now()
  681. ok := e.insertaLocked(ev, now, true)
  682. n := e.notifier
  683. notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
  684. e.mu.Unlock()
  685. if ok && notify {
  686. n.Notify(ev)
  687. }
  688. return ok
  689. }
  690. // EmitOrUpdate: como Emit, pero si YA existe una alerta con el mismo ID, la
  691. // actualiza en sitio (ts, título, descripción, severidad, urgent, router) y
  692. // la mueve al frente de la lista (más reciente) en vez de insertar una copia.
  693. // Diseñado para alertas "en curso" que se actualizan (p.ej. auto-rearme sin
  694. // recuperación: un incidente = una sola alerta, issue #271). El update NO
  695. // pasa por el dedup (consolida, no duplica); la inserción de un ID nuevo sí.
  696. // Devuelve true si se insertó o actualizó. La notificación obedece la
  697. // política de nivel de la categoría (#1413).
  698. func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
  699. e.mu.Lock()
  700. // #1074: mismo default de Ts/Time que en Emit (#914) ANTES de insertar y
  701. // notificar. La rama de inserción pasaba la `ev` original a Notify: si el
  702. // emisor no fijaba Ts (p. ej. agent-outdated), el notifier recibía Ts=0
  703. // y el push pintaba la hora estática 16:00:00 (epoch en zona UTC-8).
  704. if ev.Ts == 0 {
  705. ev.Ts = e.now().Unix()
  706. }
  707. if ev.Time == "" {
  708. ev.Time = "just now"
  709. }
  710. now := e.now()
  711. for i := range e.list {
  712. if e.list[i].ID == ev.ID {
  713. old := e.list[i]
  714. ev.Ts = now.Unix()
  715. ev.Time = "just now"
  716. // #1094: episodio nuevo tras reinicio (la alerta no se había
  717. // refrescado desde el arranque): vuelve a no-leída, que el
  718. // humano la vea. Un refresh de episodio en curso (p. ej. port
  719. // flapping, que re-emite cada ciclo) conserva su read.
  720. if old.Ts >= e.startedAt.Unix() {
  721. ev.Read = old.Read
  722. } else {
  723. // #1094: Read se DERIVA de readSet en List(), y el kv guarda
  724. // readOrd: hay que purgar ambos (y el espejo en alert_log)
  725. // o la alerta reviviría leída.
  726. ev.Read = false
  727. delete(e.readSet, ev.ID)
  728. for j, rid := range e.readOrd {
  729. if rid == ev.ID {
  730. e.readOrd = append(e.readOrd[:j], e.readOrd[j+1:]...)
  731. break
  732. }
  733. }
  734. e.saveReadLocked()
  735. if e.db != nil {
  736. _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 0 WHERE id = ?", ev.ID)
  737. }
  738. }
  739. if ev.RouterID == "" {
  740. ev.RouterID = old.RouterID
  741. }
  742. e.list = append(e.list[:i], e.list[i+1:]...)
  743. e.list = append([]AlertEvent{ev}, e.list...)
  744. e.persistLocked(ev)
  745. n := e.notifier
  746. notify := n != nil && e.notificaLocked(ev)
  747. e.mu.Unlock()
  748. if notify {
  749. n.Notify(ev)
  750. }
  751. return true
  752. }
  753. }
  754. ok := e.insertaLocked(ev, now, false)
  755. n := e.notifier
  756. notify := n != nil && e.notificaLocked(ev)
  757. e.mu.Unlock()
  758. if ok && notify {
  759. n.Notify(ev)
  760. }
  761. return ok
  762. }
  763. // EmitVolatile (#966): emite una alerta VOLÁTIL (caída de agente): NUNCA se
  764. // persiste en alert_log y, si ya existe una alerta con el mismo ID, se
  765. // actualiza en sitio y se mueve al frente (semántica "viva por router": un
  766. // incidente abierto = una alerta con ID estable). Si quedara una copia
  767. // persistida antigua con ese ID, se borra. Silencio y supresión
  768. // topológica aplican como en Emit; la notificación obedece el nivel de la
  769. // categoría (#1413). El dedup de 5 min NO aplica (el tracking del incidente
  770. // vive en el emisor, patrón #846). Devuelve true siempre (la volátil nunca
  771. // se descarta por config).
  772. func (e *Engine) EmitVolatile(ev AlertEvent) bool {
  773. ev.Volatile = true
  774. e.mu.Lock()
  775. if e.suppression != nil && ev.RouterID != "" {
  776. if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
  777. ev.SuppressedBy = parent
  778. }
  779. }
  780. now := e.now()
  781. if ev.Ts == 0 {
  782. ev.Ts = now.Unix()
  783. }
  784. if ev.Time == "" {
  785. ev.Time = "just now"
  786. }
  787. replaced := false
  788. for i := range e.list {
  789. if e.list[i].ID == ev.ID {
  790. ev.Read = e.readSet[ev.ID]
  791. e.list = append(e.list[:i], e.list[i+1:]...)
  792. e.list = append([]AlertEvent{ev}, e.list...)
  793. replaced = true
  794. break
  795. }
  796. }
  797. if !replaced {
  798. // #833: si el ID estaba limpiado y la condición se re-dispara, la
  799. // alerta vuelve al feed (igual que en insertaLocked).
  800. if _, was := e.dismissed[ev.ID]; was {
  801. delete(e.dismissed, ev.ID)
  802. e.saveDismissedLocked()
  803. }
  804. ev.Read = false
  805. e.list = append([]AlertEvent{ev}, e.list...)
  806. if len(e.list) > MaxEvents {
  807. e.list = e.list[:MaxEvents]
  808. }
  809. }
  810. // Defensa en profundidad: ninguna copia persistida de una volátil debe
  811. // sobrevivir (la purga de arranque cubre el histórico, esto el presente).
  812. if e.db != nil && ev.ID != "" {
  813. _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", ev.ID)
  814. }
  815. n := e.notifier
  816. notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
  817. e.mu.Unlock()
  818. if notify {
  819. n.Notify(ev)
  820. }
  821. return true
  822. }
  823. // Seed inserta un evento histórico (arranque del modo demo) SIN disparar el
  824. // Notifier (son historia). Mantiene dedup, cap y Read=false.
  825. // Devuelve true si se guardó.
  826. func (e *Engine) Seed(ev AlertEvent) bool {
  827. e.mu.Lock()
  828. defer e.mu.Unlock()
  829. now := e.now()
  830. key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
  831. if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
  832. return false
  833. }
  834. e.dedup[key] = now.UnixMilli()
  835. if ev.Ts == 0 {
  836. ev.Ts = now.Unix()
  837. }
  838. if ev.Time == "" {
  839. ev.Time = "just now"
  840. }
  841. ev.Read = false
  842. // #1659: fixture de demo, exento del filtro de nivel.
  843. ev.seeded = true
  844. e.list = append([]AlertEvent{ev}, e.list...)
  845. if len(e.list) > MaxEvents {
  846. e.list = e.list[:MaxEvents]
  847. }
  848. return true
  849. }
  850. // List devuelve copia de los eventos (más recientes primero) con Read
  851. // aplicado desde el read-set del servidor.
  852. func (e *Engine) List() []AlertEvent {
  853. e.mu.Lock()
  854. defer e.mu.Unlock()
  855. e.pruneSilenceLocked()
  856. // #1466: índice id → evento para resolver los cierres con datos propios.
  857. byID := make(map[string]*AlertEvent, len(e.list))
  858. for i := range e.list {
  859. byID[e.list[i].ID] = &e.list[i]
  860. }
  861. out := make([]AlertEvent, 0, len(e.list))
  862. // #1518: con el ajuste activo, los cierres informativos (severity ok) no
  863. // se sirven; los avisos resueltos (resolvedTs, otra severidad) siguen.
  864. hideOK := e.hideRecoveryLocked()
  865. for _, ev := range e.list {
  866. if e.dismissed[ev.ID] {
  867. continue
  868. }
  869. // #1659: los eventos de una categoría en nivel "none" no se sirven,
  870. // aunque estuvieran ya persistidos de antes del cambio de nivel.
  871. if e.hiddenByLevelLocked(ev) {
  872. continue
  873. }
  874. // #2185: una alerta pospuesta NO se oculta. El operador la sigue
  875. // viendo (con su marca de posposicion) porque el incidente sigue
  876. // monitorizado; solo se silencian avisos, escalado y re-emisiones.
  877. key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
  878. ev.Snoozed, ev.SnoozedUntil = e.snoozeStateLocked(key)
  879. if hideOK && ev.Severity == "ok" {
  880. continue
  881. }
  882. ev.Read = e.readSet[ev.ID]
  883. if len(ev.Resolves) > 0 {
  884. ev.Resolved = make([]ResolvedEvent, 0, len(ev.Resolves))
  885. var missing []int
  886. for _, rid := range ev.Resolves {
  887. ref := ResolvedEvent{ID: rid}
  888. if orig, ok := byID[rid]; ok {
  889. ref.Title = orig.Title
  890. ref.Ts = orig.Ts
  891. ref.Type = orig.Type
  892. ref.Vars = orig.Vars
  893. } else {
  894. missing = append(missing, len(ev.Resolved))
  895. }
  896. ev.Resolved = append(ev.Resolved, ref)
  897. }
  898. // #1466: el evento resuelto casi nunca está en la lista viva,
  899. // porque Resolve() lo retira de ella. Sin este respaldo el cierre
  900. // se quedaba con el id suelto, que es lo que se reportaba.
  901. e.fillResolvedFromDBLocked(ev.Resolved, missing)
  902. }
  903. out = append(out, ev)
  904. }
  905. return out
  906. }
  907. // fillResolvedFromDBLocked completa los datos de los eventos resueltos que ya
  908. // no están en memoria (#1466). Resolve() retira el evento de la lista viva y
  909. // lo conserva en alert_log marcado con resolved_ts, así que la fila sigue
  910. // teniendo título, instante, tipo y vars. Sin esto, el cierre mostraba solo
  911. // el id interno. Se llama con e.mu tomado.
  912. func (e *Engine) fillResolvedFromDBLocked(refs []ResolvedEvent, missing []int) {
  913. if e.db == nil || len(missing) == 0 {
  914. return
  915. }
  916. ids := make([]string, 0, len(missing))
  917. for _, i := range missing {
  918. ids = append(ids, refs[i].ID)
  919. }
  920. args := make([]any, len(ids))
  921. for i, id := range ids {
  922. args[i] = id
  923. }
  924. marks := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")
  925. rows, err := e.db.Query(
  926. "SELECT id, title, ts, type, vars FROM alert_log WHERE id IN ("+marks+")", args...)
  927. if err != nil {
  928. return
  929. }
  930. defer rows.Close()
  931. byID := make(map[string]ResolvedEvent, len(ids))
  932. for rows.Next() {
  933. var ref ResolvedEvent
  934. var varsRaw string
  935. if rows.Scan(&ref.ID, &ref.Title, &ref.Ts, &ref.Type, &varsRaw) != nil {
  936. continue
  937. }
  938. if varsRaw != "" {
  939. _ = json.Unmarshal([]byte(varsRaw), &ref.Vars)
  940. }
  941. byID[ref.ID] = ref
  942. }
  943. for _, i := range missing {
  944. if got, ok := byID[refs[i].ID]; ok {
  945. refs[i] = got
  946. }
  947. }
  948. }
  949. // UnreadCount cuenta eventos almacenados (ya pasaron config) no leídos.
  950. // Es la fuente de Overview.UnreadAlerts (server truth, SPEC §4).
  951. func (e *Engine) UnreadCount() int {
  952. e.mu.Lock()
  953. defer e.mu.Unlock()
  954. n := 0
  955. // #1518: los eventos ocultos por el ajuste de recuperación no cuentan.
  956. hideOK := e.hideRecoveryLocked()
  957. for _, ev := range e.list {
  958. if e.dismissed[ev.ID] {
  959. continue
  960. }
  961. if e.hiddenByLevelLocked(ev) {
  962. continue
  963. }
  964. key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
  965. if snoozed, _ := e.snoozeStateLocked(key); snoozed {
  966. continue
  967. }
  968. if hideOK && ev.Severity == "ok" {
  969. continue
  970. }
  971. if !e.readSet[ev.ID] {
  972. n++
  973. }
  974. }
  975. return n
  976. }
  977. // MarkRead marca IDs como leídos (persiste; cap 200 FIFO sobre los IDs que
  978. // ya NO son visibles; una alerta visible leída nunca vuelve a no-leída).
  979. // #1434: si algo cambió, avisa a OnChange (el server re-emite el estado del
  980. // feed por SSE para que Resumen/campana se actualicen al instante).
  981. func (e *Engine) MarkRead(ids ...string) {
  982. e.mu.Lock()
  983. changed := false
  984. for _, id := range ids {
  985. if id == "" || e.readSet[id] {
  986. continue
  987. }
  988. // La notificación solo cuenta cuando la alerta existe en el feed:
  989. // marcar leído un ID ajeno (o de un episodio ya cerrado) persiste
  990. // el leído como siempre, pero no cambia nada visible que reemitir.
  991. if e.idInListLocked(id) {
  992. changed = true
  993. }
  994. e.readSet[id] = true
  995. e.readOrd = append(e.readOrd, id)
  996. // Espejo en alert_log para restaurar el leído tras un reinicio (#798).
  997. if e.db != nil {
  998. _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 1 WHERE id = ?", id)
  999. }
  1000. }
  1001. e.pruneReadOrdLocked()
  1002. e.saveReadLocked()
  1003. cb := e.onChange
  1004. e.mu.Unlock()
  1005. if changed && cb != nil {
  1006. cb()
  1007. }
  1008. }
  1009. // pruneReadOrdLocked poda el FIFO del read-set, PERO sin expulsar IDs que
  1010. // siguen en la lista (#966): con la poda FIFO a ciegas, marcar muchas
  1011. // alertas como leídas podía expulsar del read-set una alerta AÚN VISIBLE,
  1012. // que reaparecía como no leída (el badge volvía a subir tras "marcar todo
  1013. // como leído"). Lo visible leído se queda leído; el cap aplica al resto.
  1014. func (e *Engine) pruneReadOrdLocked() {
  1015. visible := 0
  1016. for _, id := range e.readOrd {
  1017. if e.idInListLocked(id) {
  1018. visible++
  1019. }
  1020. }
  1021. budget := len(e.readOrd) - visible - MaxReadIDs
  1022. if budget <= 0 {
  1023. return
  1024. }
  1025. kept := e.readOrd[:0]
  1026. for _, id := range e.readOrd {
  1027. if budget > 0 && !e.idInListLocked(id) {
  1028. delete(e.readSet, id)
  1029. budget--
  1030. continue
  1031. }
  1032. kept = append(kept, id)
  1033. }
  1034. e.readOrd = kept
  1035. }
  1036. // idInListLocked: ¿el ID sigue en la lista (potencialmente visible)?
  1037. // Requiere e.mu ya tomado.
  1038. func (e *Engine) idInListLocked(id string) bool {
  1039. for _, ev := range e.list {
  1040. if ev.ID == id {
  1041. return true
  1042. }
  1043. }
  1044. return false
  1045. }
  1046. // MarkAllRead marca leídas todas las alertas actuales (#1034): SOLO toca el
  1047. // read-set (persistido en kv y espejado en alert_log.read_flag). NO borra
  1048. // nada de alert_log ni del conjunto dismissed: el feed sigue mostrando las
  1049. // alertas como leídas y el toggle "Solo no leídas" es lo que limpia la vista.
  1050. // Vaciar el log es la acción destructiva aparte (DismissAll).
  1051. func (e *Engine) MarkAllRead() {
  1052. e.mu.Lock()
  1053. ids := make([]string, 0, len(e.list))
  1054. for _, ev := range e.list {
  1055. ids = append(ids, ev.ID)
  1056. }
  1057. e.mu.Unlock()
  1058. e.MarkRead(ids...)
  1059. }
  1060. // Dismiss limpia alertas del feed (issue #833, botón "limpiar alerta"): las
  1061. // quita de la lista y del log persistido, las marca leídas y guarda el ID en
  1062. // el conjunto dismissed (kv) para que no reaparezcan tras un reinicio. Si la
  1063. // condición se re-dispara, el mismo ID se vuelve a emitir y sale del
  1064. // conjunto (ver insertaLocked). IDs desconocidos se ignoran.
  1065. func (e *Engine) Dismiss(ids ...string) {
  1066. e.mu.Lock()
  1067. changed := false
  1068. seen := false
  1069. drop := map[string]bool{}
  1070. for _, id := range ids {
  1071. if id == "" {
  1072. continue
  1073. }
  1074. seen = true
  1075. if !e.dismissed[id] {
  1076. e.dismissed[id] = true
  1077. changed = true
  1078. }
  1079. drop[id] = true
  1080. if !e.readSet[id] {
  1081. e.readSet[id] = true
  1082. e.readOrd = append(e.readOrd, id)
  1083. }
  1084. if e.db != nil {
  1085. _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 1 WHERE id = ?", id)
  1086. _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
  1087. }
  1088. }
  1089. e.pruneReadOrdLocked()
  1090. if changed {
  1091. e.saveDismissedLocked()
  1092. e.saveReadLocked()
  1093. }
  1094. kept := e.list[:0]
  1095. droppedAny := false
  1096. for _, ev := range e.list {
  1097. if !drop[ev.ID] {
  1098. kept = append(kept, ev)
  1099. } else {
  1100. droppedAny = true
  1101. }
  1102. }
  1103. e.list = kept
  1104. cb := e.onChange
  1105. e.mu.Unlock()
  1106. // #1434: el feed cambió -> el server re-emite el estado por SSE.
  1107. if seen && (changed || droppedAny) && cb != nil {
  1108. cb()
  1109. }
  1110. }
  1111. // DismissAll limpia TODAS las alertas del feed: equivale a Dismiss sobre
  1112. // cada ID presente en la lista. Es la acción destructiva "Vaciar registro"
  1113. // (#1034; antes el botón "Marcar todo como leído" la invocaba, #971). Las
  1114. // persistentes se borran de alert_log y su ID queda en el conjunto
  1115. // dismissed (kv), así que el feed vacío sobrevive a un reload; las volátiles
  1116. // (agent-down) también salen, pero si su condición sigue viva el emisor las
  1117. // re-emite con el mismo ID y vuelven (semántica "alerta viva": lo que no
  1118. // vuelve es el histórico, no el presente).
  1119. func (e *Engine) DismissAll() {
  1120. e.mu.Lock()
  1121. ids := make([]string, 0, len(e.list))
  1122. for _, ev := range e.list {
  1123. ids = append(ids, ev.ID)
  1124. }
  1125. e.mu.Unlock()
  1126. e.Dismiss(ids...)
  1127. }
  1128. // Has informa si un ID de alerta está actualmente en la lista (persistida
  1129. // incluida). Lo usa el agent-outdated check tras un reinicio, cuando el flag
  1130. // en memoria (agentOutdatedAlerted) no sobrevive pero la alerta sí (#833).
  1131. func (e *Engine) Has(id string) bool {
  1132. e.mu.Lock()
  1133. defer e.mu.Unlock()
  1134. for _, ev := range e.list {
  1135. if ev.ID == id {
  1136. return true
  1137. }
  1138. }
  1139. return false
  1140. }
  1141. // Resolve elimina una alerta cuya condición dejó de cumplirse (issue #833:
  1142. // agent-outdated desaparece del feed cuando el agente se actualiza). A
  1143. // diferencia de Dismiss NO guarda el ID en dismissed: si la condición vuelve,
  1144. // la alerta se re-emite con normalidad. El dedup se conserva para no
  1145. // re-notificar dentro de la ventana de 5 min.
  1146. func (e *Engine) Resolve(id string) {
  1147. if id == "" {
  1148. return
  1149. }
  1150. e.mu.Lock()
  1151. found := false
  1152. for i, ev := range e.list {
  1153. if ev.ID == id {
  1154. e.list = append(e.list[:i], e.list[i+1:]...)
  1155. // La condición se resolvió: una reincidencia es un incidente
  1156. // nuevo y debe poder alertar de inmediato (sin esperar al
  1157. // expirar la ventana de dedup de 5 min).
  1158. delete(e.dedup, ev.Category+"|"+ev.Title+"|"+ev.RouterID)
  1159. found = true
  1160. break
  1161. }
  1162. }
  1163. // #1107: la alerta resuelta es un episodio CERRADO. El read-set es
  1164. // append-only (kv readOrd) y sobrevivía al Resolve: si la condición se
  1165. // re-dispara con el mismo ID estable (p. ej. "Agent outdated" tras
  1166. // actualizar el server y quedar otra vez desactualizado), el episodio
  1167. // nuevo heredaba el leído viejo en List()/UnreadCount(). Mismo criterio
  1168. // que Remove (#846): al cerrarse, se olvida el leído.
  1169. delete(e.readSet, id)
  1170. for j, rid := range e.readOrd {
  1171. if rid == id {
  1172. e.readOrd = append(e.readOrd[:j], e.readOrd[j+1:]...)
  1173. break
  1174. }
  1175. }
  1176. e.saveReadLocked()
  1177. if e.db != nil {
  1178. // #1349: el evento resuelto se CONSERVA en el log (marcado con su ts
  1179. // de cierre) en vez de borrarse: el registro de actividad mantiene
  1180. // qué pasó y cuándo se cerró. La pestaña Resueltas de la UI lo lista.
  1181. // read_flag=0: el resuelto se muestra leído por la regla de carga
  1182. // (resolved_ts>0 → leído), y si la condición REINCIDE con el mismo
  1183. // ID estable, el upsert (resolved_ts=0) no puede heredar un leído
  1184. // viejo de la fila conservada (#1107 sigue valiendo).
  1185. _, _ = e.db.Exec("UPDATE alert_log SET resolved_ts = ?, read_flag = 0 WHERE id = ?", time.Now().Unix(), id)
  1186. }
  1187. cb := e.onChange
  1188. e.mu.Unlock()
  1189. // #1434: la lista del feed cambió -> el server re-emite el estado por
  1190. // SSE para que Resumen/campana se actualicen al instante.
  1191. if found && cb != nil {
  1192. cb()
  1193. }
  1194. }
  1195. // Remove elimina eventos por ID: los retira de la lista en memoria, de su
  1196. // espejo en alert_log y del read-set (issue #846). Sirve para retirar alertas
  1197. // "en curso" cuya condición ya no existe, p.ej. la caída de un router que
  1198. // vuelve online: el feed no acumula incidentes cerrados.
  1199. func (e *Engine) Remove(ids ...string) {
  1200. e.mu.Lock()
  1201. defer e.mu.Unlock()
  1202. drop := map[string]bool{}
  1203. for _, id := range ids {
  1204. if id != "" {
  1205. drop[id] = true
  1206. }
  1207. }
  1208. if len(drop) == 0 {
  1209. return
  1210. }
  1211. out := make([]AlertEvent, 0, len(e.list))
  1212. for _, ev := range e.list {
  1213. if !drop[ev.ID] {
  1214. out = append(out, ev)
  1215. }
  1216. }
  1217. e.list = out
  1218. for id := range drop {
  1219. delete(e.readSet, id)
  1220. for i, rid := range e.readOrd {
  1221. if rid == id {
  1222. e.readOrd = append(e.readOrd[:i], e.readOrd[i+1:]...)
  1223. break
  1224. }
  1225. }
  1226. if e.db != nil {
  1227. _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
  1228. }
  1229. }
  1230. e.saveReadLocked()
  1231. }
  1232. // Silence pospone las alertas que comparten la dedup key de la alerta dada
  1233. // durante la duracion indicada (#2185: "posponer"). Duration 0 = sin fecha.
  1234. // La alerta NO se oculta del feed: la fila queda marcada con Snoozed y deja
  1235. // de contar como pendiente, de notificar y de re-emitirse. Devuelve la dedup
  1236. // key pospuesta, o cadena vacia si el ID no existe.
  1237. func (e *Engine) Silence(id string, dur time.Duration) string {
  1238. e.mu.Lock()
  1239. var dedupKey string
  1240. for _, ev := range e.list {
  1241. if ev.ID == id {
  1242. dedupKey = ev.Category + "|" + ev.Title + "|" + ev.RouterID
  1243. break
  1244. }
  1245. }
  1246. if dedupKey == "" {
  1247. e.mu.Unlock()
  1248. return ""
  1249. }
  1250. var expiry int64
  1251. if dur > 0 {
  1252. expiry = e.now().Add(dur).Unix()
  1253. }
  1254. e.silenceMap[dedupKey] = expiry
  1255. e.saveSilenceLocked()
  1256. cb := e.onChange
  1257. e.mu.Unlock()
  1258. // #1434: la lista servida cambia (la alerta pasa a pospuesta).
  1259. if cb != nil {
  1260. cb()
  1261. }
  1262. return dedupKey
  1263. }
  1264. // SnoozeKey devuelve la dedup key de la alerta con ese ID (vacia si no
  1265. // existe). Permite quitar la posposicion desde el cliente sin reconstruir
  1266. // la clave.
  1267. func (e *Engine) SnoozeKey(id string) string {
  1268. e.mu.Lock()
  1269. defer e.mu.Unlock()
  1270. for _, ev := range e.list {
  1271. if ev.ID == id {
  1272. return ev.Category + "|" + ev.Title + "|" + ev.RouterID
  1273. }
  1274. }
  1275. return ""
  1276. }
  1277. // Unsilence removes the silence for a dedup key.
  1278. func (e *Engine) Unsilence(dedupKey string) {
  1279. e.mu.Lock()
  1280. delete(e.silenceMap, dedupKey)
  1281. e.saveSilenceLocked()
  1282. cb := e.onChange
  1283. e.mu.Unlock()
  1284. if cb != nil {
  1285. cb()
  1286. }
  1287. }
  1288. // Silenced returns all currently silenced dedup keys with their expiry times.
  1289. func (e *Engine) Silenced() map[string]int64 {
  1290. e.mu.Lock()
  1291. defer e.mu.Unlock()
  1292. e.pruneSilenceLocked()
  1293. out := make(map[string]int64, len(e.silenceMap))
  1294. for k, v := range e.silenceMap {
  1295. out[k] = v
  1296. }
  1297. return out
  1298. }
  1299. func (e *Engine) isSilencedLocked(key string) bool {
  1300. snoozed, _ := e.snoozeStateLocked(key)
  1301. return snoozed
  1302. }
  1303. // snoozeStateLocked dice si la dedup key esta pospuesta y hasta cuando
  1304. // (0 = sin fecha). Poda la entrada si ya expiro. Requiere e.mu tomado.
  1305. func (e *Engine) snoozeStateLocked(key string) (bool, int64) {
  1306. expiry, ok := e.silenceMap[key]
  1307. if !ok {
  1308. return false, 0
  1309. }
  1310. if expiry == 0 {
  1311. return true, 0 // sin fecha
  1312. }
  1313. if e.now().Unix() >= expiry {
  1314. delete(e.silenceMap, key)
  1315. return false, 0
  1316. }
  1317. return true, expiry
  1318. }
  1319. func (e *Engine) pruneSilenceLocked() {
  1320. now := e.now().Unix()
  1321. for k, expiry := range e.silenceMap {
  1322. if expiry > 0 && now >= expiry {
  1323. delete(e.silenceMap, k)
  1324. }
  1325. }
  1326. }
  1327. func (e *Engine) saveConfigLocked() {
  1328. if e.db == nil {
  1329. return
  1330. }
  1331. raw, err := json.Marshal(e.cfg)
  1332. if err != nil {
  1333. return
  1334. }
  1335. _, _ = e.db.Exec(
  1336. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  1337. configKey, string(raw))
  1338. }
  1339. func (e *Engine) saveReadLocked() {
  1340. if e.db == nil {
  1341. return
  1342. }
  1343. raw, err := json.Marshal(e.readOrd)
  1344. if err != nil {
  1345. return
  1346. }
  1347. _, _ = e.db.Exec(
  1348. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  1349. readKey, string(raw))
  1350. }
  1351. func (e *Engine) saveSilenceLocked() {
  1352. if e.db == nil {
  1353. return
  1354. }
  1355. raw, err := json.Marshal(e.silenceMap)
  1356. if err != nil {
  1357. return
  1358. }
  1359. _, _ = e.db.Exec(
  1360. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  1361. silenceKey, string(raw))
  1362. }
  1363. func (e *Engine) saveDismissedLocked() {
  1364. if e.db == nil {
  1365. return
  1366. }
  1367. ids := make([]string, 0, len(e.dismissed))
  1368. for id := range e.dismissed {
  1369. ids = append(ids, id)
  1370. }
  1371. sort.Strings(ids)
  1372. raw, err := json.Marshal(ids)
  1373. if err != nil {
  1374. return
  1375. }
  1376. _, _ = e.db.Exec(
  1377. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  1378. dismissKey, string(raw))
  1379. }
  1380. func contains(list []string, v string) bool {
  1381. for _, x := range list {
  1382. if x == v {
  1383. return true
  1384. }
  1385. }
  1386. return false
  1387. }
  1388. // IsCategory reporta si v es una categoría válida (validación de query).
  1389. func IsCategory(v string) bool { return contains(Categories, v) }