Fix phantom online agents: startup reset, init reconciliation, stale-sweep goroutine

This commit is contained in:
AetherForge
2026-06-02 22:00:21 -07:00
parent ca66f5d048
commit 60ab286403
2 changed files with 87 additions and 3 deletions

View File

@@ -169,6 +169,30 @@ func (d *Database) SetAgentOffline(id string) error {
return err
}
// MarkAllAgentsOffline resets every agent row to offline. Called once at
// server startup so rows left online by a previous crash are corrected
// before any agent has had a chance to reconnect.
func (d *Database) MarkAllAgentsOffline() error {
_, err := d.Exec("UPDATE agents SET status = 'offline' WHERE status = 'online'")
return err
}
// MarkStaleAgentsOffline marks agents offline when their last_seen timestamp
// is older than the given staleness threshold. Returns the number of rows
// updated so the caller can emit a log line when something actually changed.
func (d *Database) MarkStaleAgentsOffline(olderThan time.Duration) (int, error) {
cutoff := time.Now().Add(-olderThan)
res, err := d.Exec(
"UPDATE agents SET status = 'offline' WHERE status = 'online' AND last_seen < ?",
cutoff,
)
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
return int(n), nil
}
func (d *Database) DeleteAgent(id string) error {
_, err := d.Exec("DELETE FROM agents WHERE id = ?", id)
return err