diff --git a/internal/watcher/health/monitor/last_seen.go b/internal/watcher/health/monitor/last_seen.go new file mode 100644 index 0000000..36e7ceb --- /dev/null +++ b/internal/watcher/health/monitor/last_seen.go @@ -0,0 +1,22 @@ +package monitor + +import ( + "time" + + F "github.com/yusing/go-proxy/internal/utils/functional" +) + +var lastSeenMap = F.NewMapOf[string, time.Time]() + +func SetLastSeen(service string, lastSeen time.Time) { + lastSeenMap.Store(service, lastSeen) +} + +func UpdateLastSeen(service string) { + SetLastSeen(service, time.Now()) +} + +func GetLastSeen(service string) time.Time { + lastSeen, _ := lastSeenMap.Load(service) + return lastSeen +} diff --git a/internal/watcher/health/monitor/monitor.go b/internal/watcher/health/monitor/monitor.go index c23a476..25d710e 100644 --- a/internal/watcher/health/monitor/monitor.go +++ b/internal/watcher/health/monitor/monitor.go @@ -27,7 +27,6 @@ type ( status atomic.Value[health.Status] lastResult *health.HealthCheckResult - lastSeen time.Time checkHealth HealthCheckFunc startTime time.Time @@ -164,7 +163,7 @@ func (mon *monitor) MarshalJSON() ([]byte, error) { Started: mon.startTime, Uptime: mon.Uptime(), Latency: res.Latency, - LastSeen: mon.lastSeen, + LastSeen: GetLastSeen(mon.service), Detail: res.Detail, URL: mon.url.Load(), }).MarshalJSON() @@ -186,14 +185,17 @@ func (mon *monitor) checkUpdateHealth() error { var status health.Status if result.Healthy { status = health.StatusHealthy - mon.lastSeen = time.Now() + UpdateLastSeen(mon.service) } else { status = health.StatusUnhealthy } if result.Healthy != (mon.status.Swap(status) == health.StatusHealthy) { extras := map[string]any{ "Service Name": mon.service, - "Last Seen": strutils.FormatLastSeen(mon.lastSeen), + "Time": strutils.FormatTime(time.Now()), + } + if !result.Healthy { + extras["Last Seen"] = strutils.FormatLastSeen(GetLastSeen(mon.service)) } if !mon.url.Load().Nil() { extras["Service URL"] = mon.url.Load().String()