Refactor notification handling to track server status changes instead of notification timestamps

This commit is contained in:
headlessdev 2025-04-29 20:40:56 +02:00
parent 93dccaf0d5
commit 176dfac0c1

View File

@ -15,12 +15,12 @@ import (
"github.com/corecontrol/agent/internal/notifications" "github.com/corecontrol/agent/internal/notifications"
) )
// notificationState tracks the last notification time for each server // notificationState tracks the last known status for each server
var notificationState = struct { var notificationState = struct {
sync.RWMutex sync.RWMutex
lastNotification map[int]time.Time lastStatus map[int]bool
}{ }{
lastNotification: make(map[int]time.Time), lastStatus: make(map[int]bool),
} }
// MonitorServers checks and updates the status of all servers // MonitorServers checks and updates the status of all servers
@ -108,17 +108,16 @@ func MonitorServers(db *sql.DB, client *http.Client, servers []models.Server, no
} }
} }
// shouldSendNotification checks if a notification should be sent based on cooldown period // shouldSendNotification checks if a notification should be sent based on status change
func shouldSendNotification(serverID int, online bool) bool { func shouldSendNotification(serverID int, online bool) bool {
notificationState.Lock() notificationState.Lock()
defer notificationState.Unlock() defer notificationState.Unlock()
lastNotif, exists := notificationState.lastNotification[serverID] lastStatus, exists := notificationState.lastStatus[serverID]
now := time.Now()
// If no previous notification or more than 5 minutes have passed // If this is the first check or status has changed
if !exists || now.Sub(lastNotif) > 5*time.Minute { if !exists || lastStatus != online {
notificationState.lastNotification[serverID] = now notificationState.lastStatus[serverID] = online
return true return true
} }