| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415 |
- // Package alerts — motor de alertas (SPEC-ALERTAS §1-3): dueño de la lista
- // de eventos (máx 100, más recientes primero), config por categoría con 3
- // niveles (none/urgent/all) aplicada EN CREACIÓN, dedup de 5 min por
- // (category,title,routerId), read-state en servidor y hook Notifier para el
- // push (Bloque C; nil = no-op).
- //
- // Persistencia: tabla kv (misma DB que el resto del servidor):
- // - alerts.config.v1: JSON {"router":"urgent",...} (6 claves, defaults).
- // - alerts.read.v1: JSON array de IDs leídos (cap 200, FIFO).
- package alerts
- import (
- "encoding/json"
- "fmt"
- "sort"
- "strings"
- "sync"
- "time"
- "github.com/gnacho/netpulse/server-go/internal/db"
- )
- // Categorías (taxonomía exacta del SPEC §1).
- const (
- CatRouter = "router"
- CatInternet = "internet"
- CatClients = "clients"
- CatSignal = "signal"
- CatVPN = "vpn"
- CatSystem = "system"
- )
- // Categories lista las 6 categorías válidas (orden estable para mensajes).
- var Categories = []string{CatRouter, CatInternet, CatClients, CatSignal, CatVPN, CatSystem}
- // Niveles de configuración por categoría (SPEC §2).
- const (
- LevelNone = "none" // el evento se descarta (no se guarda, no cuenta, no empuja)
- LevelUrgent = "urgent" // solo pasan eventos Urgent=true
- LevelAll = "all" // pasan todos (los urgentes además notifican)
- )
- var levels = map[string]bool{LevelNone: true, LevelUrgent: true, LevelAll: true}
- // Claves kv y límites (SPEC §2-3).
- const (
- configKey = "alerts.config.v1"
- readKey = "alerts.read.v1"
- silenceKey = "alerts.silence.v1"
- dismissKey = "alerts.dismissed.v1"
- MaxEvents = 100
- MaxReadIDs = 200
- DedupWindow = 5 * time.Minute
- )
- // AlertEvent (máx 100 en memoria, más recientes primero).
- type AlertEvent struct {
- ID string `json:"id"`
- Category string `json:"category"` // taxonomía SPEC §1
- Urgent bool `json:"urgent"` // "rompe silencio" (push + badge)
- Severity string `json:"severity"` // display: "warn"|"critical"|"info"|"ok"
- Title string `json:"title"`
- Description string `json:"description"`
- // Hint is an actionable suggestion per alert type (issue #310).
- // Filled at emission time from the Hints map; absent when not applicable.
- Hint string `json:"hint,omitempty"`
- Time string `json:"time"` // LEGADO display; se sigue rellenando
- Ts int64 `json:"ts"` // unix SEGUNDOS; el frontend calcula el relativo
- Read bool `json:"read"`
- RouterID string `json:"routerId"`
- // Type: slug estable del tipo de alerta (issue #310). Cuando viaja
- // (#671), el frontend traduce título/descripción/hint por clave i18n
- // (alerts.types.<slug>.title/.description y alerts.hints.<slug>) en el
- // idioma del usuario; los literales Title/Description/Hint siguen en el
- // evento como fallback (servidores viejos, demo, claves sin traducir).
- Type string `json:"type,omitempty"`
- // Vars: valores de interpolación para esas claves (router, mac, temp…).
- Vars map[string]string `json:"vars,omitempty"`
- // SuppressedBy is the routerId of the parent router whose offline alert
- // is suppressing this one (issue #332). Empty when not suppressed.
- SuppressedBy string `json:"suppressedBy,omitempty"`
- // ResolvedTs (#1349): unix SEGUNDOS de cuándo se resolvió la condición.
- // 0/ausente = activa. El evento resuelto NO se borra del log: queda
- // marcado para revisión posterior (pestaña Resueltas) y una
- // reincidencia con el mismo ID estable lo des-resuelve (upsert).
- ResolvedTs int64 `json:"resolvedTs,omitempty"`
- // Resolves (#1349): IDs de los eventos que este evento CIERRA (p. ej.
- // "Agent updated" resuelve "alert-agent-outdated-<id>"). La UI los
- // muestra al expandir el evento de cierre.
- Resolves []string `json:"resolves,omitempty"`
- // Resolved (#1466): datos de los eventos que este evento cerró (título,
- // ts de disparo, tipo y vars para traducir). El feed se pagina (20 por
- // página): el evento resuelto puede NO estar en la página que el cliente
- // tiene cargada, así que el payload va autocontenido y la UI no depende
- // de buscarlo en su feed local.
- Resolved []ResolvedEvent `json:"resolved,omitempty"`
- // Volatile (#966): la alerta vive SOLO en memoria (no se persiste en
- // alert_log ni sobrevive a reinicios) y desaparece del feed cuando su
- // condicion se resuelve (engine.Remove). Uso: caida de agente, cuya
- // semantica es "viva por router", no un historico de incidentes.
- Volatile bool `json:"-"`
- // seeded: fixture del dataset demo (Seed). No lo somete el filtro de
- // nivel "none" (#1659): la historia canónica del demo se sirve completa
- // aunque su config deje la categoría en "none".
- seeded bool
- }
- // ResolvedEvent (#1466): datos mínimos del evento que un cierre resolvió.
- // Type+Vars permiten traducir el título en el front; Title/Ts son el
- // fallback literal y el instante del disparo original.
- type ResolvedEvent struct {
- ID string `json:"id"`
- Title string `json:"title,omitempty"`
- Ts int64 `json:"ts"`
- Type string `json:"type,omitempty"`
- Vars map[string]string `json:"vars,omitempty"`
- }
- // Stable alert-type slugs (issue #310): keys of the Hints map.
- const (
- HintAgentDown = "agent-down"
- HintAgentDownSSH = "agent-down-ssh" // variante: satélite degrada a SSH (#671)
- HintGatewayUnrch = "gateway-unreachable"
- HintHighTemp = "high-temperature"
- HintPortFlapping = "port-flapping"
- HintDeviceOffline = "device-offline"
- HintUnknownDevice = "unknown-device"
- HintSsidImpostor = "wifi-ssid-impostor"
- HintNewNeighborSsid = "new-neighbor-ssid"
- HintNewClient = "new-client"
- HintFirmware = "firmware-outdated"
- // #1412: el target configurado es MÁS VIEJO que lo instalado (posible
- // downgrade, casi siempre un target mal puesto).
- HintFirmwareDowngrade = "firmware-downgrade-target"
- // #1444: el target configurado NO figura entre los releases publicados
- // de OpenWrt (chequeo periódico contra downloads.openwrt.org). Es un
- // aviso de configuración, no una alerta de firmware desactualizado.
- HintFirmwareUnknownTarget = "firmware-target-unknown"
- HintWanDown = "wan-down"
- HintWifiWeak = "wifi-weak"
- HintGhostPort = "ghost-port"
- HintDegradedLink = "degraded-link"
- HintAgentOutdated = "agent-outdated"
- HintWanSlow = "wan-slow"
- HintUplinkSwitch = "uplink-switched"
- HintSnmpFailing = "snmp-failing"
- )
- // Additional stable alert-type slugs (issue #712): recovery/info/beacon/rearmer
- // types emitted without Type/Vars in #671. They carry no hint.
- const (
- TypeAgentRecovered = "agent-recovered"
- TypeSSHAccessLost = "ssh-access-lost"
- TypeSSHAccessRecovered = "ssh-access-recovered"
- TypeAgentUpdated = "agent-updated"
- TypeRouterRecovered = "router-recovered"
- TypeWireguardHandshake = "wireguard-handshake"
- TypeWireguardDisconnect = "wireguard-disconnect"
- TypePortStable = "port-stable"
- TypeGhostPortRecovered = "ghost-port-recovered"
- TypeLinkRecovered = "link-recovered"
- TypeSwitchLoop = "switch-loop"
- TypePortDisabled = "port-disabled"
- TypePortRecovered = "port-recovered"
- TypeLinkDown = "link-down"
- TypeLinkUp = "link-up"
- TypeSfpRxLow = "sfp-rx-low"
- TypeSfpTempHigh = "sfp-temp-high"
- TypeSwitchRebooted = "switch-rebooted"
- TypeAgentRearmed = "agent-rearmed"
- TypeAgentReinstalled = "agent-reinstalled"
- TypeAutoRearmFailed = "auto-rearm-failed"
- TypeUplinkRestored = "uplink-restored"
- TypeSnmpRecovered = "snmp-recovered"
- // #1354: router offline (was reused from HintDeviceOffline, now its own slug)
- // and client device offline (opt-in, volatile).
- TypeRouterOffline = "router-offline"
- TypeDeviceOffline = "device-offline"
- // #1452: cierre automático de la alerta de señal débil (episodio
- // resuelto con valor de recuperación y duración).
- TypeWifiWeakRecovered = "wifi-weak-recovered"
- // #1873: una MAC que solo aparece en una tabla de reenvío, sin lease,
- // ARP, ND ni mDNS, y que sigue ahí mucho rato. Informativa, no urgente.
- TypeUnverifiedMac = "unverified-mac"
- )
- // Hints maps each alert-type slug to its actionable suggestion. Emitters copy
- // the value into AlertEvent.Hint; the feed and push render it as a helper line.
- // The canonical language is English (#1014): alertlang and the web feed swap
- // it for the catalog wording when the target language is Spanish.
- var Hints = map[string]string{
- HintAgentDown: "Check the router power and connection; if it does not recover, reinstall the agent from LuCI.",
- HintAgentDownSSH: "Check the router's power and connection; if it doesn't recover, reinstall the agent from LuCI.",
- HintGatewayUnrch: "Check the connection between the gateway and the rest of the network.",
- HintHighTemp: "Improve ventilation and keep the router away from heat sources.",
- HintPortFlapping: "Check the cable or switch port: an unstable link is usually the culprit.",
- HintDeviceOffline: "Verify the device power and network cable.",
- HintUnknownDevice: "If you do not recognize it, block it or mark it as trusted in Settings.",
- 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.",
- 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.",
- 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.",
- HintFirmware: "Your router has newer firmware available; check Firmware upgrades (Labs) or LuCI.",
- HintFirmwareDowngrade: "The configured target is older than the installed firmware; fix the target version in the fleet unit settings.",
- HintWanDown: "Check the modem/ONT and contact your ISP if the outage persists.",
- HintWifiWeak: "Move the device closer to an access point or relocate the AP.",
- HintGhostPort: "Check the cable and the connected device: an active port that goes silent usually means a loose cable or a powered-off device.",
- HintDegradedLink: "Check the cable and connectors: a degraded link is often a sign of a damaged cable or a loose connector.",
- HintAgentOutdated: "Update the agent from Settings, Agents (Update button); if it's a NetGrip panel, update it from its own panel.",
- HintUplinkSwitch: "Check the line that dropped: the router goes back to it on its own once it recovers.",
- 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).",
- HintSnmpFailing: "Check the SNMP community string and switch port: the device answers ping but not polling.",
- }
- // HintFor returns the suggestion for a slug, or "" when it does not exist.
- func HintFor(slug string) string { return Hints[slug] }
- // Notifier es el hook de notificación externa (push/webhook/telegram/ntfy).
- // El engine lo dispara solo para eventos cuya categoría permite notificación
- // según el nivel configurado (#1413): none nunca, urgent solo Urgent, all
- // siempre. La decisión de urgencia fina por canal sigue en cada integración
- // (#874, urgencyGate). Los eventos suprimidos topológicamente se guardan con
- // SuppressedBy y nunca notifican.
- type Notifier interface {
- Notify(ev AlertEvent)
- }
- // DefaultConfig devuelve una copia de los defaults del SPEC §2.
- // clients=all desde issue #196: "dispositivo desconocido" ya no es urgente
- // pero debe seguir siendo visible (con clients:urgent se descartaría entero).
- func DefaultConfig() map[string]string {
- return map[string]string{
- CatRouter: LevelUrgent,
- CatInternet: LevelUrgent,
- CatClients: LevelAll,
- CatSignal: LevelNone,
- CatVPN: LevelNone,
- CatSystem: LevelAll,
- }
- }
- // Engine es el motor: aplica config/dedup/cap en Emit y guarda el read-state.
- // Seguro para uso concurrente (los adapters emiten desde varios goroutines).
- type Engine struct {
- mu sync.Mutex
- db *db.DB // nil → solo memoria (tests)
- notifier Notifier
- // startedAt: arranque de ESTA instancia. Las alertas con Ts anterior a
- // startedAt vienen de una sesión previa: si se re-emiten (update), es
- // un episodio nuevo tras el reinicio y vuelven a no-leídas (#1094).
- startedAt time.Time
- now func() time.Time
- cfg map[string]string
- list []AlertEvent
- dedup map[string]int64 // key (cat|title|routerId) → último emit (unix ms)
- readSet map[string]bool
- readOrd []string // FIFO de IDs (cap 200) para podar readSet
- silenceMap map[string]int64 // dedup key → expiry (unix seconds); 0 = forever
- // dismissed: IDs de alertas limpiadas por el usuario (issue #833). Se
- // filtran del feed y del unread; si el mismo ID se vuelve a emitir (la
- // condición se re-dispara), sale del conjunto y reaparece.
- dismissed map[string]bool
- // suppression: grafo de dependencias topológicas (issue #332).
- // nil = sin supresión (tests o arranque sin topología).
- suppression *SuppressionGraph
- // persistLog: volcar el log a alert_log y restaurarlo al arranque
- // (issue #798). false solo en el dataset demo, que es sintético y se
- // regenera en cada arranque (cargar/re-guardar duplicaría las semillas).
- persistLog bool
- // onChange (#1434): callback invocado SIN e.mu tras una mutación que
- // altera la lista servida o el read-state (mark-read, dismiss, resolve,
- // silence). El server lo usa para reemitir el estado del feed por SSE
- // al instante; el poller ya no es el único camino de actualización.
- onChange func()
- }
- // PersistMaxEvents es la cota de filas del log persistido (issue #798): la
- // lista en memoria se queda en MaxEvents, pero en disco se conservan más
- // para restaurarlas tras un reinicio (p. ej. el del self-update).
- const PersistMaxEvents = 500
- // New crea el motor cargando config, read-state y el log persistido (si db).
- func New(d *db.DB, n Notifier) *Engine { return newEngine(d, n, true) }
- // NewVolatile crea el motor SIN persistencia del log de alertas. El dataset
- // demo es sintético y se regenera en cada arranque: cargar el log traería
- // entradas ajenas al canon y re-guardarlo duplicaría las semillas.
- func NewVolatile(d *db.DB, n Notifier) *Engine { return newEngine(d, n, false) }
- func newEngine(d *db.DB, n Notifier, persistLog bool) *Engine {
- e := &Engine{
- db: d,
- notifier: n,
- now: time.Now,
- startedAt: time.Now(),
- cfg: DefaultConfig(),
- dedup: map[string]int64{},
- readSet: map[string]bool{},
- silenceMap: map[string]int64{},
- dismissed: map[string]bool{},
- persistLog: persistLog,
- }
- if d != nil {
- var raw string
- if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", configKey).Scan(&raw); err == nil {
- saved := map[string]string{}
- if json.Unmarshal([]byte(raw), &saved) == nil {
- for _, cat := range Categories {
- if lv, ok := saved[cat]; ok && levels[lv] {
- e.cfg[cat] = lv
- }
- }
- }
- }
- if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", readKey).Scan(&raw); err == nil {
- ids := []string{}
- if json.Unmarshal([]byte(raw), &ids) == nil {
- for _, id := range ids {
- if id != "" && !e.readSet[id] {
- e.readSet[id] = true
- e.readOrd = append(e.readOrd, id)
- }
- }
- }
- }
- if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", silenceKey).Scan(&raw); err == nil {
- _ = json.Unmarshal([]byte(raw), &e.silenceMap)
- }
- if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", dismissKey).Scan(&raw); err == nil {
- ids := []string{}
- if json.Unmarshal([]byte(raw), &ids) == nil {
- for _, id := range ids {
- if id != "" {
- e.dismissed[id] = true
- }
- }
- }
- }
- e.purgeVolatileHistoryLocked()
- e.purgeSupersededWeakClosures()
- e.loadPersistedLocked()
- // #1034: poda por antigüedad al arrancar (además de la horaria de
- // main): una retención bajada mientras el daemon estaba parado se
- // aplica en el primer arranque posterior.
- e.PruneLogByRetention()
- }
- return e
- }
- // purgeVolatileHistoryLocked: purga one-shot al arrancar (#966). Las alertas
- // de caida de agente AHORA son volatiles (no se persisten), pero las
- // instalaciones previas acumularon un historico de agent-down* en alert_log
- // que seguiria reapareciendo tras cada reinicio. Se borran ANTES de cargar
- // el log, para que ni siquiera el primer arranque tras actualizar lo muestre.
- func (e *Engine) purgeVolatileHistoryLocked() {
- if e.db == nil || !e.persistLog {
- return
- }
- _, _ = e.db.Exec(
- `DELETE FROM alert_log WHERE id LIKE 'alert-agent-down-%'
- OR type IN ('agent-down', 'agent-down-ssh')`)
- }
- // purgeSupersededWeakClosures: purga one-shot al arrancar (#1518). Los
- // cierres de señal débil ANTERIORES al ID estable llevaban timestamp en el ID
- // (alert-weak-<mac>-ok-<ts>): cada episodio dejaba una "resuelta" idéntica en
- // el log. Se borran de alert_log ANTES de cargar (el ID estable nuevo las
- // reemplaza en adelante); los avisos originales resueltos no se tocan.
- func (e *Engine) purgeSupersededWeakClosures() {
- if e.db == nil || !e.persistLog {
- return
- }
- _, _ = e.db.Exec(`DELETE FROM alert_log WHERE id LIKE 'alert-weak-%-ok-%'`)
- }
- // loadPersistedLocked restaura el log desde alert_log (issue #798): los
- // últimos MaxEvents eventos (más recientes primero), reconstruyendo el mapa
- // de dedup (para no re-notificar dentro de la ventana tras un reinicio) y
- // sembrando el read-set desde la columna read espejada.
- func (e *Engine) loadPersistedLocked() {
- if !e.persistLog {
- return
- }
- rows, err := e.db.Query(
- `SELECT id, ts, category, type, severity, urgent, title, description, hint,
- router_id, suppressed_by, vars, read_flag, resolved_ts, resolves
- FROM alert_log ORDER BY ts DESC LIMIT ?`, MaxEvents)
- if err != nil {
- return
- }
- defer rows.Close()
- type row struct {
- ev AlertEvent
- read bool
- }
- loaded := []row{}
- for rows.Next() {
- var ev AlertEvent
- var typ, sev, hint, routerID, suppressedBy, varsRaw, resolvesRaw string
- var urgent, read int
- if err := rows.Scan(&ev.ID, &ev.Ts, &ev.Category, &typ, &sev, &urgent,
- &ev.Title, &ev.Description, &hint, &routerID, &suppressedBy, &varsRaw, &read, &ev.ResolvedTs, &resolvesRaw); err != nil {
- return
- }
- // #833: una alerta limpiada no vuelve a aparecer tras un reinicio.
- if e.dismissed[ev.ID] {
- continue
- }
- // #1349: un evento resuelto vuelve al feed MARCADO (historia
- // consultable en Resueltas) y nunca como pendiente de leer.
- if ev.ResolvedTs > 0 {
- read = 1
- }
- ev.Type = typ
- ev.Severity = sev
- ev.Urgent = urgent != 0
- ev.Hint = hint
- ev.RouterID = routerID
- ev.SuppressedBy = suppressedBy
- if varsRaw != "" {
- vars := map[string]string{}
- if json.Unmarshal([]byte(varsRaw), &vars) == nil {
- ev.Vars = vars
- }
- }
- // #1466: referencias del cierre (qué eventos resolvió).
- if resolvesRaw != "" {
- var ids []string
- if json.Unmarshal([]byte(resolvesRaw), &ids) == nil && len(ids) > 0 {
- ev.Resolves = ids
- }
- }
- loaded = append(loaded, row{ev: ev, read: read != 0})
- }
- // rows.Next() consumió las filas de más reciente a más antigua; la lista
- // interna ya va en ese orden (append al frente en insertaLocked).
- for _, r := range loaded {
- e.list = append(e.list, r.ev)
- key := r.ev.Category + "|" + r.ev.Title + "|" + r.ev.RouterID
- // Las filas vienen de más reciente a más antigua: solo la primera por
- // clave es el timestamp de dedup válido (no pisar con la más vieja).
- // #1349: un RESUELTO no siembra dedup - su condición está cerrada y
- // una reincidencia tras reinicio debe alertar de inmediato (mismo
- // criterio que Resolve en caliente, que borra la clave de dedup).
- if r.ev.ResolvedTs == 0 {
- if _, ok := e.dedup[key]; !ok {
- e.dedup[key] = r.ev.Ts * 1000
- }
- }
- if r.read && r.ev.ID != "" && !e.readSet[r.ev.ID] {
- e.readSet[r.ev.ID] = true
- e.readOrd = append(e.readOrd, r.ev.ID)
- }
- }
- }
- // SetNotifier sustituye el hook Notifier (wiring de Bloque C desde main;
- // nil = no-op). Seguro en caliente: Emit lo lee bajo el mismo mutex.
- func (e *Engine) SetNotifier(n Notifier) {
- e.mu.Lock()
- defer e.mu.Unlock()
- e.notifier = n
- }
- // SetClock sustituye el reloj (solo tests).
- func (e *Engine) SetClock(f func() time.Time) {
- e.mu.Lock()
- defer e.mu.Unlock()
- e.now = f
- }
- // SetSuppression wirea el grafo de dependencias topológicas (issue #332).
- // nil desactiva la supresión (tests o arranque sin topología).
- func (e *Engine) SetSuppression(g *SuppressionGraph) {
- e.mu.Lock()
- defer e.mu.Unlock()
- e.suppression = g
- }
- // SetOnChange (#1434) fija el callback de mutación del feed. Se invoca DESPUÉS
- // de soltar e.mu, así que el receptor puede leer el engine (List/UnreadCount)
- // sin riesgo de deadlock; solo hay que evitar mutar el engine desde dentro
- // (recursión de notificaciones).
- func (e *Engine) SetOnChange(f func()) {
- e.mu.Lock()
- defer e.mu.Unlock()
- e.onChange = f
- }
- // Config devuelve una copia de la config efectiva (siempre las 6 claves).
- func (e *Engine) Config() map[string]string {
- e.mu.Lock()
- defer e.mu.Unlock()
- out := make(map[string]string, len(e.cfg))
- for k, v := range e.cfg {
- out[k] = v
- }
- return out
- }
- // SetConfig aplica un parche parcial {"signal":"all"}: valida categorías y
- // niveles (error → 400 en la API), fusiona y persiste en kv.
- func (e *Engine) SetConfig(patch map[string]string) error {
- badCats, badVals := []string{}, []string{}
- for k, v := range patch {
- if !contains(Categories, k) {
- badCats = append(badCats, k)
- } else if !levels[v] {
- badVals = append(badVals, fmt.Sprintf("%s=%q", k, v))
- }
- }
- if len(badCats) > 0 || len(badVals) > 0 {
- sort.Strings(badCats)
- sort.Strings(badVals)
- parts := []string{}
- if len(badCats) > 0 {
- parts = append(parts, "categorías desconocidas: "+strings.Join(badCats, ", "))
- }
- if len(badVals) > 0 {
- parts = append(parts, "niveles inválidos: "+strings.Join(badVals, ", "))
- }
- return fmt.Errorf("invalid config (%s)", strings.Join(parts, "; "))
- }
- e.mu.Lock()
- defer e.mu.Unlock()
- for k, v := range patch {
- e.cfg[k] = v
- }
- e.saveConfigLocked()
- return nil
- }
- // notificaLocked: ¿la config de la categoría permite NOTIFICAR este evento?
- // (issue #1413: los niveles son política de notificación, no de ingesta:
- // todo se guarda en el log y el feed; el nivel solo gobierna el Notifier).
- // none = nunca; urgent = solo eventos Urgent; all = siempre. Categoría
- // desconocida: notifica (la validación estricta es de SetConfig).
- // Requiere e.mu ya tomado.
- func (e *Engine) notificaLocked(ev AlertEvent) bool {
- level, known := e.cfg[ev.Category]
- if known {
- if level == LevelNone || (level == LevelUrgent && !ev.Urgent) {
- return false
- }
- }
- return true
- }
- // hiddenByLevelLocked: una categoría en nivel "none" no existe para el
- // operador. No entra al feed, no cuenta en la campana y no se persiste
- // (issue #1659). El nivel "urgent" sigue siendo solo política de
- // notificación (#1413): sus eventos se registran y solo silencian el aviso.
- // Los fixtures del demo (Seed) quedan exentos para servir el canon completo.
- func (e *Engine) hiddenByLevelLocked(ev AlertEvent) bool {
- return !ev.seeded && e.cfg[ev.Category] == LevelNone
- }
- // insertaLocked inserta un evento nuevo al frente con dedup y cap.
- // Requiere e.mu ya tomado. Devuelve true si se guardó. skipDedup omite la
- // ventana de dedup de 5 min (issue #846: los incidentes con estado propio,
- // p.ej. offline de router, se trackean fuera del engine y su alerta debe
- // entrar aunque la ventana cubra la emisión de un incidente ya cerrado).
- func (e *Engine) insertaLocked(ev AlertEvent, now time.Time, skipDedup bool) bool {
- key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
- if e.isSilencedLocked(key) {
- return false
- }
- // #1659: el nivel "none" oculta la categoría por completo (feed, campana
- // y alert_log). Se descarta antes del dedup para no consumir la ventana.
- if e.hiddenByLevelLocked(ev) {
- return false
- }
- if !skipDedup {
- if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
- return false
- }
- e.dedup[key] = now.UnixMilli()
- }
- // #833: si el ID estaba limpiado y la condición se re-dispara, la alerta
- // vuelve al feed (dismissed solo oculta el histórico, no el presente).
- if _, was := e.dismissed[ev.ID]; was {
- delete(e.dismissed, ev.ID)
- e.saveDismissedLocked()
- }
- if ev.Ts == 0 {
- ev.Ts = now.Unix()
- }
- if ev.Time == "" {
- ev.Time = "just now"
- }
- ev.Read = false
- e.list = append([]AlertEvent{ev}, e.list...)
- if len(e.list) > MaxEvents {
- e.list = e.list[:MaxEvents]
- }
- e.persistLocked(ev)
- return true
- }
- // persistLocked escribe (o actualiza) el evento en alert_log y poda la tabla
- // a PersistMaxEvents filas (issue #798). El read NO se toca aquí: la fuente
- // de verdad del leído es el read-set de kv y se espeja aparte en MarkRead.
- // Best-effort: un fallo de BD nunca debe romper el camino de alertado.
- func (e *Engine) persistLocked(ev AlertEvent) {
- if e.db == nil || !e.persistLog || ev.ID == "" || ev.Volatile {
- return
- }
- varsRaw := ""
- if len(ev.Vars) > 0 {
- if raw, err := json.Marshal(ev.Vars); err == nil {
- varsRaw = string(raw)
- }
- }
- // #1466: las referencias del cierre se persisten; si no, tras un reinicio
- // el evento de cierre queda sin saber qué resolvió.
- resolvesRaw := ""
- if len(ev.Resolves) > 0 {
- if raw, err := json.Marshal(ev.Resolves); err == nil {
- resolvesRaw = string(raw)
- }
- }
- urgent := 0
- if ev.Urgent {
- urgent = 1
- }
- _, _ = e.db.Exec(
- `INSERT INTO alert_log (id, ts, category, type, severity, urgent, title, description, hint, router_id, suppressed_by, vars, resolved_ts, resolves)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(id) DO UPDATE SET ts=excluded.ts, category=excluded.category,
- type=excluded.type, severity=excluded.severity, urgent=excluded.urgent,
- title=excluded.title, description=excluded.description, hint=excluded.hint,
- router_id=excluded.router_id, suppressed_by=excluded.suppressed_by, vars=excluded.vars,
- resolved_ts=excluded.resolved_ts, resolves=excluded.resolves`,
- ev.ID, ev.Ts, ev.Category, ev.Type, ev.Severity, urgent,
- ev.Title, ev.Description, ev.Hint, ev.RouterID, ev.SuppressedBy, varsRaw, ev.ResolvedTs, resolvesRaw)
- _, _ = e.db.Exec(
- `DELETE FROM alert_log WHERE id NOT IN
- (SELECT id FROM alert_log ORDER BY ts DESC LIMIT ?)`, PersistMaxEvents)
- }
- // Emit aplica el dedup de 5 min y el cap de 100; devuelve true si el evento
- // se guardó. El nivel de la categoría gobierna qué se registra: "none" no
- // entra al feed ni se persiste (#1659), "urgent" sí se registra y solo
- // silencia el aviso (#1413).
- // El filtro por URGENCIA fino vive en cada canal (#874): cada transporte
- // decide si lleva solo urgentes (default) o todo.
- // Supresión topológica (#332): si el router tiene un padre offline en el
- // grafo, la alerta se guarda con SuppressedBy y NO dispara el Notifier.
- func (e *Engine) Emit(ev AlertEvent) bool {
- e.mu.Lock()
- if e.suppression != nil && ev.RouterID != "" {
- if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
- ev.SuppressedBy = parent
- }
- }
- // #914: default de Ts/Time ANTES de insertar y notificar. Hasta ahora el
- // default vivía solo en insertaLocked, cuya copia local no propagaba a
- // esta `ev`: el notifier (ntfy/Telegram/webhook) recibía Ts=0 y pintaba
- // la hora estática 16:00:00 (epoch en zona UTC-8).
- if ev.Ts == 0 {
- ev.Ts = e.now().Unix()
- }
- if ev.Time == "" {
- ev.Time = "just now"
- }
- now := e.now()
- ok := e.insertaLocked(ev, now, false)
- n := e.notifier
- notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
- e.mu.Unlock()
- if ok && notify {
- n.Notify(ev)
- }
- return ok
- }
- // EmitNoDedup es Emit sin la ventana de dedup de 5 min (silencio, cap,
- // supresión y política de notificación por categoría SÍ aplican; issue #1413:
- // la config ya no filtra la ingesta, solo la notificación). Uso:
- // alertas cuya condición se trackea por estado fuera del engine (issue #846,
- // offline de router): al ABRIR incidente la alerta debe entrar siempre,
- // porque el cierre del incidente anterior ya retiró la suya del feed y el
- // dedup la bloquearía — el "una alerta por outage" lo garantiza el tracking
- // de incidente (offlineOpen), no la ventana.
- func (e *Engine) EmitNoDedup(ev AlertEvent) bool {
- e.mu.Lock()
- if e.suppression != nil && ev.RouterID != "" {
- if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
- ev.SuppressedBy = parent
- }
- }
- // #914: mismo default de Ts/Time que en Emit antes de notificar.
- if ev.Ts == 0 {
- ev.Ts = e.now().Unix()
- }
- if ev.Time == "" {
- ev.Time = "just now"
- }
- now := e.now()
- ok := e.insertaLocked(ev, now, true)
- n := e.notifier
- notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
- e.mu.Unlock()
- if ok && notify {
- n.Notify(ev)
- }
- return ok
- }
- // EmitOrUpdate: como Emit, pero si YA existe una alerta con el mismo ID, la
- // actualiza en sitio (ts, título, descripción, severidad, urgent, router) y
- // la mueve al frente de la lista (más reciente) en vez de insertar una copia.
- // Diseñado para alertas "en curso" que se actualizan (p.ej. auto-rearme sin
- // recuperación: un incidente = una sola alerta, issue #271). El update NO
- // pasa por el dedup (consolida, no duplica); la inserción de un ID nuevo sí.
- // Devuelve true si se insertó o actualizó. La notificación obedece la
- // política de nivel de la categoría (#1413).
- func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
- e.mu.Lock()
- // #1074: mismo default de Ts/Time que en Emit (#914) ANTES de insertar y
- // notificar. La rama de inserción pasaba la `ev` original a Notify: si el
- // emisor no fijaba Ts (p. ej. agent-outdated), el notifier recibía Ts=0
- // y el push pintaba la hora estática 16:00:00 (epoch en zona UTC-8).
- if ev.Ts == 0 {
- ev.Ts = e.now().Unix()
- }
- if ev.Time == "" {
- ev.Time = "just now"
- }
- now := e.now()
- for i := range e.list {
- if e.list[i].ID == ev.ID {
- old := e.list[i]
- ev.Ts = now.Unix()
- ev.Time = "just now"
- // #1094: episodio nuevo tras reinicio (la alerta no se había
- // refrescado desde el arranque): vuelve a no-leída, que el
- // humano la vea. Un refresh de episodio en curso (p. ej. port
- // flapping, que re-emite cada ciclo) conserva su read.
- if old.Ts >= e.startedAt.Unix() {
- ev.Read = old.Read
- } else {
- // #1094: Read se DERIVA de readSet en List(), y el kv guarda
- // readOrd: hay que purgar ambos (y el espejo en alert_log)
- // o la alerta reviviría leída.
- ev.Read = false
- delete(e.readSet, ev.ID)
- for j, rid := range e.readOrd {
- if rid == ev.ID {
- e.readOrd = append(e.readOrd[:j], e.readOrd[j+1:]...)
- break
- }
- }
- e.saveReadLocked()
- if e.db != nil {
- _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 0 WHERE id = ?", ev.ID)
- }
- }
- if ev.RouterID == "" {
- ev.RouterID = old.RouterID
- }
- e.list = append(e.list[:i], e.list[i+1:]...)
- e.list = append([]AlertEvent{ev}, e.list...)
- e.persistLocked(ev)
- n := e.notifier
- notify := n != nil && e.notificaLocked(ev)
- e.mu.Unlock()
- if notify {
- n.Notify(ev)
- }
- return true
- }
- }
- ok := e.insertaLocked(ev, now, false)
- n := e.notifier
- notify := n != nil && e.notificaLocked(ev)
- e.mu.Unlock()
- if ok && notify {
- n.Notify(ev)
- }
- return ok
- }
- // EmitVolatile (#966): emite una alerta VOLÁTIL (caída de agente): NUNCA se
- // persiste en alert_log y, si ya existe una alerta con el mismo ID, se
- // actualiza en sitio y se mueve al frente (semántica "viva por router": un
- // incidente abierto = una alerta con ID estable). Si quedara una copia
- // persistida antigua con ese ID, se borra. Silencio y supresión
- // topológica aplican como en Emit; la notificación obedece el nivel de la
- // categoría (#1413). El dedup de 5 min NO aplica (el tracking del incidente
- // vive en el emisor, patrón #846). Devuelve true siempre (la volátil nunca
- // se descarta por config).
- func (e *Engine) EmitVolatile(ev AlertEvent) bool {
- ev.Volatile = true
- e.mu.Lock()
- if e.suppression != nil && ev.RouterID != "" {
- if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
- ev.SuppressedBy = parent
- }
- }
- now := e.now()
- if ev.Ts == 0 {
- ev.Ts = now.Unix()
- }
- if ev.Time == "" {
- ev.Time = "just now"
- }
- replaced := false
- for i := range e.list {
- if e.list[i].ID == ev.ID {
- ev.Read = e.readSet[ev.ID]
- e.list = append(e.list[:i], e.list[i+1:]...)
- e.list = append([]AlertEvent{ev}, e.list...)
- replaced = true
- break
- }
- }
- if !replaced {
- // #833: si el ID estaba limpiado y la condición se re-dispara, la
- // alerta vuelve al feed (igual que en insertaLocked).
- if _, was := e.dismissed[ev.ID]; was {
- delete(e.dismissed, ev.ID)
- e.saveDismissedLocked()
- }
- ev.Read = false
- e.list = append([]AlertEvent{ev}, e.list...)
- if len(e.list) > MaxEvents {
- e.list = e.list[:MaxEvents]
- }
- }
- // Defensa en profundidad: ninguna copia persistida de una volátil debe
- // sobrevivir (la purga de arranque cubre el histórico, esto el presente).
- if e.db != nil && ev.ID != "" {
- _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", ev.ID)
- }
- n := e.notifier
- notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
- e.mu.Unlock()
- if notify {
- n.Notify(ev)
- }
- return true
- }
- // Seed inserta un evento histórico (arranque del modo demo) SIN disparar el
- // Notifier (son historia). Mantiene dedup, cap y Read=false.
- // Devuelve true si se guardó.
- func (e *Engine) Seed(ev AlertEvent) bool {
- e.mu.Lock()
- defer e.mu.Unlock()
- now := e.now()
- key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
- if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
- return false
- }
- e.dedup[key] = now.UnixMilli()
- if ev.Ts == 0 {
- ev.Ts = now.Unix()
- }
- if ev.Time == "" {
- ev.Time = "just now"
- }
- ev.Read = false
- // #1659: fixture de demo, exento del filtro de nivel.
- ev.seeded = true
- e.list = append([]AlertEvent{ev}, e.list...)
- if len(e.list) > MaxEvents {
- e.list = e.list[:MaxEvents]
- }
- return true
- }
- // List devuelve copia de los eventos (más recientes primero) con Read
- // aplicado desde el read-set del servidor.
- func (e *Engine) List() []AlertEvent {
- e.mu.Lock()
- defer e.mu.Unlock()
- e.pruneSilenceLocked()
- // #1466: índice id → evento para resolver los cierres con datos propios.
- byID := make(map[string]*AlertEvent, len(e.list))
- for i := range e.list {
- byID[e.list[i].ID] = &e.list[i]
- }
- out := make([]AlertEvent, 0, len(e.list))
- // #1518: con el ajuste activo, los cierres informativos (severity ok) no
- // se sirven; los avisos resueltos (resolvedTs, otra severidad) siguen.
- hideOK := e.hideRecoveryLocked()
- for _, ev := range e.list {
- if e.dismissed[ev.ID] {
- continue
- }
- // #1659: los eventos de una categoría en nivel "none" no se sirven,
- // aunque estuvieran ya persistidos de antes del cambio de nivel.
- if e.hiddenByLevelLocked(ev) {
- continue
- }
- key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
- if e.isSilencedLocked(key) {
- continue
- }
- if hideOK && ev.Severity == "ok" {
- continue
- }
- ev.Read = e.readSet[ev.ID]
- if len(ev.Resolves) > 0 {
- ev.Resolved = make([]ResolvedEvent, 0, len(ev.Resolves))
- var missing []int
- for _, rid := range ev.Resolves {
- ref := ResolvedEvent{ID: rid}
- if orig, ok := byID[rid]; ok {
- ref.Title = orig.Title
- ref.Ts = orig.Ts
- ref.Type = orig.Type
- ref.Vars = orig.Vars
- } else {
- missing = append(missing, len(ev.Resolved))
- }
- ev.Resolved = append(ev.Resolved, ref)
- }
- // #1466: el evento resuelto casi nunca está en la lista viva,
- // porque Resolve() lo retira de ella. Sin este respaldo el cierre
- // se quedaba con el id suelto, que es lo que se reportaba.
- e.fillResolvedFromDBLocked(ev.Resolved, missing)
- }
- out = append(out, ev)
- }
- return out
- }
- // fillResolvedFromDBLocked completa los datos de los eventos resueltos que ya
- // no están en memoria (#1466). Resolve() retira el evento de la lista viva y
- // lo conserva en alert_log marcado con resolved_ts, así que la fila sigue
- // teniendo título, instante, tipo y vars. Sin esto, el cierre mostraba solo
- // el id interno. Se llama con e.mu tomado.
- func (e *Engine) fillResolvedFromDBLocked(refs []ResolvedEvent, missing []int) {
- if e.db == nil || len(missing) == 0 {
- return
- }
- ids := make([]string, 0, len(missing))
- for _, i := range missing {
- ids = append(ids, refs[i].ID)
- }
- args := make([]any, len(ids))
- for i, id := range ids {
- args[i] = id
- }
- marks := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")
- rows, err := e.db.Query(
- "SELECT id, title, ts, type, vars FROM alert_log WHERE id IN ("+marks+")", args...)
- if err != nil {
- return
- }
- defer rows.Close()
- byID := make(map[string]ResolvedEvent, len(ids))
- for rows.Next() {
- var ref ResolvedEvent
- var varsRaw string
- if rows.Scan(&ref.ID, &ref.Title, &ref.Ts, &ref.Type, &varsRaw) != nil {
- continue
- }
- if varsRaw != "" {
- _ = json.Unmarshal([]byte(varsRaw), &ref.Vars)
- }
- byID[ref.ID] = ref
- }
- for _, i := range missing {
- if got, ok := byID[refs[i].ID]; ok {
- refs[i] = got
- }
- }
- }
- // UnreadCount cuenta eventos almacenados (ya pasaron config) no leídos.
- // Es la fuente de Overview.UnreadAlerts (server truth, SPEC §4).
- func (e *Engine) UnreadCount() int {
- e.mu.Lock()
- defer e.mu.Unlock()
- n := 0
- // #1518: los eventos ocultos por el ajuste de recuperación no cuentan.
- hideOK := e.hideRecoveryLocked()
- for _, ev := range e.list {
- if e.dismissed[ev.ID] {
- continue
- }
- if e.hiddenByLevelLocked(ev) {
- continue
- }
- key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
- if e.isSilencedLocked(key) {
- continue
- }
- if hideOK && ev.Severity == "ok" {
- continue
- }
- if !e.readSet[ev.ID] {
- n++
- }
- }
- return n
- }
- // MarkRead marca IDs como leídos (persiste; cap 200 FIFO sobre los IDs que
- // ya NO son visibles; una alerta visible leída nunca vuelve a no-leída).
- // #1434: si algo cambió, avisa a OnChange (el server re-emite el estado del
- // feed por SSE para que Resumen/campana se actualicen al instante).
- func (e *Engine) MarkRead(ids ...string) {
- e.mu.Lock()
- changed := false
- for _, id := range ids {
- if id == "" || e.readSet[id] {
- continue
- }
- // La notificación solo cuenta cuando la alerta existe en el feed:
- // marcar leído un ID ajeno (o de un episodio ya cerrado) persiste
- // el leído como siempre, pero no cambia nada visible que reemitir.
- if e.idInListLocked(id) {
- changed = true
- }
- e.readSet[id] = true
- e.readOrd = append(e.readOrd, id)
- // Espejo en alert_log para restaurar el leído tras un reinicio (#798).
- if e.db != nil {
- _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 1 WHERE id = ?", id)
- }
- }
- e.pruneReadOrdLocked()
- e.saveReadLocked()
- cb := e.onChange
- e.mu.Unlock()
- if changed && cb != nil {
- cb()
- }
- }
- // pruneReadOrdLocked poda el FIFO del read-set, PERO sin expulsar IDs que
- // siguen en la lista (#966): con la poda FIFO a ciegas, marcar muchas
- // alertas como leídas podía expulsar del read-set una alerta AÚN VISIBLE,
- // que reaparecía como no leída (el badge volvía a subir tras "marcar todo
- // como leído"). Lo visible leído se queda leído; el cap aplica al resto.
- func (e *Engine) pruneReadOrdLocked() {
- visible := 0
- for _, id := range e.readOrd {
- if e.idInListLocked(id) {
- visible++
- }
- }
- budget := len(e.readOrd) - visible - MaxReadIDs
- if budget <= 0 {
- return
- }
- kept := e.readOrd[:0]
- for _, id := range e.readOrd {
- if budget > 0 && !e.idInListLocked(id) {
- delete(e.readSet, id)
- budget--
- continue
- }
- kept = append(kept, id)
- }
- e.readOrd = kept
- }
- // idInListLocked: ¿el ID sigue en la lista (potencialmente visible)?
- // Requiere e.mu ya tomado.
- func (e *Engine) idInListLocked(id string) bool {
- for _, ev := range e.list {
- if ev.ID == id {
- return true
- }
- }
- return false
- }
- // MarkAllRead marca leídas todas las alertas actuales (#1034): SOLO toca el
- // read-set (persistido en kv y espejado en alert_log.read_flag). NO borra
- // nada de alert_log ni del conjunto dismissed: el feed sigue mostrando las
- // alertas como leídas y el toggle "Solo no leídas" es lo que limpia la vista.
- // Vaciar el log es la acción destructiva aparte (DismissAll).
- func (e *Engine) MarkAllRead() {
- e.mu.Lock()
- ids := make([]string, 0, len(e.list))
- for _, ev := range e.list {
- ids = append(ids, ev.ID)
- }
- e.mu.Unlock()
- e.MarkRead(ids...)
- }
- // Dismiss limpia alertas del feed (issue #833, botón "limpiar alerta"): las
- // quita de la lista y del log persistido, las marca leídas y guarda el ID en
- // el conjunto dismissed (kv) para que no reaparezcan tras un reinicio. Si la
- // condición se re-dispara, el mismo ID se vuelve a emitir y sale del
- // conjunto (ver insertaLocked). IDs desconocidos se ignoran.
- func (e *Engine) Dismiss(ids ...string) {
- e.mu.Lock()
- changed := false
- seen := false
- drop := map[string]bool{}
- for _, id := range ids {
- if id == "" {
- continue
- }
- seen = true
- if !e.dismissed[id] {
- e.dismissed[id] = true
- changed = true
- }
- drop[id] = true
- if !e.readSet[id] {
- e.readSet[id] = true
- e.readOrd = append(e.readOrd, id)
- }
- if e.db != nil {
- _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 1 WHERE id = ?", id)
- _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
- }
- }
- e.pruneReadOrdLocked()
- if changed {
- e.saveDismissedLocked()
- e.saveReadLocked()
- }
- kept := e.list[:0]
- droppedAny := false
- for _, ev := range e.list {
- if !drop[ev.ID] {
- kept = append(kept, ev)
- } else {
- droppedAny = true
- }
- }
- e.list = kept
- cb := e.onChange
- e.mu.Unlock()
- // #1434: el feed cambió -> el server re-emite el estado por SSE.
- if seen && (changed || droppedAny) && cb != nil {
- cb()
- }
- }
- // DismissAll limpia TODAS las alertas del feed: equivale a Dismiss sobre
- // cada ID presente en la lista. Es la acción destructiva "Vaciar registro"
- // (#1034; antes el botón "Marcar todo como leído" la invocaba, #971). Las
- // persistentes se borran de alert_log y su ID queda en el conjunto
- // dismissed (kv), así que el feed vacío sobrevive a un reload; las volátiles
- // (agent-down) también salen, pero si su condición sigue viva el emisor las
- // re-emite con el mismo ID y vuelven (semántica "alerta viva": lo que no
- // vuelve es el histórico, no el presente).
- func (e *Engine) DismissAll() {
- e.mu.Lock()
- ids := make([]string, 0, len(e.list))
- for _, ev := range e.list {
- ids = append(ids, ev.ID)
- }
- e.mu.Unlock()
- e.Dismiss(ids...)
- }
- // Has informa si un ID de alerta está actualmente en la lista (persistida
- // incluida). Lo usa el agent-outdated check tras un reinicio, cuando el flag
- // en memoria (agentOutdatedAlerted) no sobrevive pero la alerta sí (#833).
- func (e *Engine) Has(id string) bool {
- e.mu.Lock()
- defer e.mu.Unlock()
- for _, ev := range e.list {
- if ev.ID == id {
- return true
- }
- }
- return false
- }
- // Resolve elimina una alerta cuya condición dejó de cumplirse (issue #833:
- // agent-outdated desaparece del feed cuando el agente se actualiza). A
- // diferencia de Dismiss NO guarda el ID en dismissed: si la condición vuelve,
- // la alerta se re-emite con normalidad. El dedup se conserva para no
- // re-notificar dentro de la ventana de 5 min.
- func (e *Engine) Resolve(id string) {
- if id == "" {
- return
- }
- e.mu.Lock()
- found := false
- for i, ev := range e.list {
- if ev.ID == id {
- e.list = append(e.list[:i], e.list[i+1:]...)
- // La condición se resolvió: una reincidencia es un incidente
- // nuevo y debe poder alertar de inmediato (sin esperar al
- // expirar la ventana de dedup de 5 min).
- delete(e.dedup, ev.Category+"|"+ev.Title+"|"+ev.RouterID)
- found = true
- break
- }
- }
- // #1107: la alerta resuelta es un episodio CERRADO. El read-set es
- // append-only (kv readOrd) y sobrevivía al Resolve: si la condición se
- // re-dispara con el mismo ID estable (p. ej. "Agent outdated" tras
- // actualizar el server y quedar otra vez desactualizado), el episodio
- // nuevo heredaba el leído viejo en List()/UnreadCount(). Mismo criterio
- // que Remove (#846): al cerrarse, se olvida el leído.
- delete(e.readSet, id)
- for j, rid := range e.readOrd {
- if rid == id {
- e.readOrd = append(e.readOrd[:j], e.readOrd[j+1:]...)
- break
- }
- }
- e.saveReadLocked()
- if e.db != nil {
- // #1349: el evento resuelto se CONSERVA en el log (marcado con su ts
- // de cierre) en vez de borrarse: el registro de actividad mantiene
- // qué pasó y cuándo se cerró. La pestaña Resueltas de la UI lo lista.
- // read_flag=0: el resuelto se muestra leído por la regla de carga
- // (resolved_ts>0 → leído), y si la condición REINCIDE con el mismo
- // ID estable, el upsert (resolved_ts=0) no puede heredar un leído
- // viejo de la fila conservada (#1107 sigue valiendo).
- _, _ = e.db.Exec("UPDATE alert_log SET resolved_ts = ?, read_flag = 0 WHERE id = ?", time.Now().Unix(), id)
- }
- cb := e.onChange
- e.mu.Unlock()
- // #1434: la lista del feed cambió -> el server re-emite el estado por
- // SSE para que Resumen/campana se actualicen al instante.
- if found && cb != nil {
- cb()
- }
- }
- // Remove elimina eventos por ID: los retira de la lista en memoria, de su
- // espejo en alert_log y del read-set (issue #846). Sirve para retirar alertas
- // "en curso" cuya condición ya no existe, p.ej. la caída de un router que
- // vuelve online: el feed no acumula incidentes cerrados.
- func (e *Engine) Remove(ids ...string) {
- e.mu.Lock()
- defer e.mu.Unlock()
- drop := map[string]bool{}
- for _, id := range ids {
- if id != "" {
- drop[id] = true
- }
- }
- if len(drop) == 0 {
- return
- }
- out := make([]AlertEvent, 0, len(e.list))
- for _, ev := range e.list {
- if !drop[ev.ID] {
- out = append(out, ev)
- }
- }
- e.list = out
- for id := range drop {
- delete(e.readSet, id)
- for i, rid := range e.readOrd {
- if rid == id {
- e.readOrd = append(e.readOrd[:i], e.readOrd[i+1:]...)
- break
- }
- }
- if e.db != nil {
- _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
- }
- }
- e.saveReadLocked()
- }
- // Silence silences alerts matching the dedup key of the given alert ID for the
- // specified duration. Duration 0 means forever. Returns the dedup key that was
- // silenced, or empty string if the alert ID was not found.
- func (e *Engine) Silence(id string, dur time.Duration) string {
- e.mu.Lock()
- var dedupKey string
- for _, ev := range e.list {
- if ev.ID == id {
- dedupKey = ev.Category + "|" + ev.Title + "|" + ev.RouterID
- break
- }
- }
- if dedupKey == "" {
- e.mu.Unlock()
- return ""
- }
- var expiry int64
- if dur > 0 {
- expiry = e.now().Add(dur).Unix()
- }
- e.silenceMap[dedupKey] = expiry
- e.saveSilenceLocked()
- cb := e.onChange
- e.mu.Unlock()
- // #1434: la lista servida cambia (la alerta queda filtrada).
- if cb != nil {
- cb()
- }
- return dedupKey
- }
- // Unsilence removes the silence for a dedup key.
- func (e *Engine) Unsilence(dedupKey string) {
- e.mu.Lock()
- delete(e.silenceMap, dedupKey)
- e.saveSilenceLocked()
- cb := e.onChange
- e.mu.Unlock()
- if cb != nil {
- cb()
- }
- }
- // Silenced returns all currently silenced dedup keys with their expiry times.
- func (e *Engine) Silenced() map[string]int64 {
- e.mu.Lock()
- defer e.mu.Unlock()
- e.pruneSilenceLocked()
- out := make(map[string]int64, len(e.silenceMap))
- for k, v := range e.silenceMap {
- out[k] = v
- }
- return out
- }
- func (e *Engine) isSilencedLocked(key string) bool {
- expiry, ok := e.silenceMap[key]
- if !ok {
- return false
- }
- if expiry == 0 {
- return true // forever
- }
- if e.now().Unix() >= expiry {
- delete(e.silenceMap, key)
- return false
- }
- return true
- }
- func (e *Engine) pruneSilenceLocked() {
- now := e.now().Unix()
- for k, expiry := range e.silenceMap {
- if expiry > 0 && now >= expiry {
- delete(e.silenceMap, k)
- }
- }
- }
- func (e *Engine) saveConfigLocked() {
- if e.db == nil {
- return
- }
- raw, err := json.Marshal(e.cfg)
- if err != nil {
- return
- }
- _, _ = e.db.Exec(
- "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
- configKey, string(raw))
- }
- func (e *Engine) saveReadLocked() {
- if e.db == nil {
- return
- }
- raw, err := json.Marshal(e.readOrd)
- if err != nil {
- return
- }
- _, _ = e.db.Exec(
- "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
- readKey, string(raw))
- }
- func (e *Engine) saveSilenceLocked() {
- if e.db == nil {
- return
- }
- raw, err := json.Marshal(e.silenceMap)
- if err != nil {
- return
- }
- _, _ = e.db.Exec(
- "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
- silenceKey, string(raw))
- }
- func (e *Engine) saveDismissedLocked() {
- if e.db == nil {
- return
- }
- ids := make([]string, 0, len(e.dismissed))
- for id := range e.dismissed {
- ids = append(ids, id)
- }
- sort.Strings(ids)
- raw, err := json.Marshal(ids)
- if err != nil {
- return
- }
- _, _ = e.db.Exec(
- "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
- dismissKey, string(raw))
- }
- func contains(list []string, v string) bool {
- for _, x := range list {
- if x == v {
- return true
- }
- }
- return false
- }
- // IsCategory reporta si v es una categoría válida (validación de query).
- func IsCategory(v string) bool { return contains(Categories, v) }
|