alerts.go 49 KB

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