package orchestrator import ( "context" "database/sql" "fmt" "sync" "time" "cloudipvalidator/internal/db" ) // heartbeatPersistInterval is how often a steady heartbeat is written to the // database. Between writes the last signal lives in memory only. const heartbeatPersistInterval = 60 * time.Second // heartbeatState keeps the last signal of every validator and site in memory, // so a heartbeat does not cost a database commit. type heartbeatState struct { mu sync.Mutex startedAt time.Time seen map[string]time.Time // key "v:" or "s:": last signal persisted map[string]time.Time // key: last database write } // touch records a signal now and reports whether it must be written to the // database (forced by a state change, or the last write is old enough). func (h *heartbeatState) touch(key string, force bool) bool { now := time.Now() h.mu.Lock() defer h.mu.Unlock() if h.seen == nil { h.seen = map[string]time.Time{} h.persisted = map[string]time.Time{} } h.seen[key] = now if last, ok := h.persisted[key]; !force && ok && now.Sub(last) < heartbeatPersistInterval { return false } h.persisted[key] = now return true } func (h *heartbeatState) lastSeen(key string) (time.Time, bool) { h.mu.Lock() defer h.mu.Unlock() t, ok := h.seen[key] return t, ok } // newest returns the later of the in-memory signal and the stored one. func (h *heartbeatState) newest(key string, stored *time.Time) *time.Time { t, ok := h.lastSeen(key) if !ok { return stored } t = t.UTC().Truncate(time.Millisecond) if stored != nil && !t.After(*stored) { return stored } return &t } // ValidatorHeartbeat handles a validator's sign of life. It returns // sql.ErrNoRows for an unknown validator. The database is written only when // the validator is unreachable (state change) or the last write is older than // heartbeatPersistInterval. func (o *Orchestrator) ValidatorHeartbeat(ctx context.Context, id string) error { v, err := o.DB.GetValidator(ctx, id) if err != nil { return err } if !o.hb.touch("v:"+id, v.State == db.ValidatorUnreachable) { return nil } return o.DB.Heartbeat(ctx, id) } // SiteHeartbeat is ValidatorHeartbeat for prober sites. func (o *Orchestrator) SiteHeartbeat(ctx context.Context, siteID string) error { state, err := o.siteState(ctx, siteID) if err != nil { return err } if !o.hb.touch("s:"+siteID, state == db.SiteUnreachable) { return nil } return o.DB.SiteHeartbeat(ctx, siteID) } func (o *Orchestrator) siteState(ctx context.Context, siteID string) (string, error) { sites, err := o.DB.ListSites(ctx) if err != nil { return "", err } for _, s := range sites { if s.SiteID == siteID { return s.State, nil } } return "", sql.ErrNoRows } // OverlayValidatorHeartbeat replaces v.LastHeartbeatAt with the in-memory // value when it is newer. func (o *Orchestrator) OverlayValidatorHeartbeat(v *db.Validator) { v.LastHeartbeatAt = o.hb.newest("v:"+v.ValidatorID, v.LastHeartbeatAt) } // OverlaySiteHeartbeat is OverlayValidatorHeartbeat for sites. func (o *Orchestrator) OverlaySiteHeartbeat(s *db.Site) { s.LastHeartbeatAt = o.hb.newest("s:"+s.SiteID, s.LastHeartbeatAt) } // EndStartupGrace ends the post-start sweep delay early (for tests). func (o *Orchestrator) EndStartupGrace() { o.hb.startedAt = time.Time{} } // inStartupGrace is true during the first HeartbeatTimeoutSeconds after // start: agents have not had time to report in memory yet. func (o *Orchestrator) inStartupGrace() bool { return time.Since(o.hb.startedAt) < time.Duration(o.Cfg.HeartbeatTimeoutSeconds)*time.Second } // SweepStaleHeartbeats marks validators unreachable if they haven't // heartbeated within HeartbeatTimeoutSeconds (the later of the in-memory and // stored signal counts). It does not itself reclaim their in-flight IP — that // happens independently via lease expiry. Validators on a diagnostic hold are // never touched, and nothing is marked in the startup grace period. func (o *Orchestrator) SweepStaleHeartbeats(ctx context.Context) error { if o.inStartupGrace() { return nil } cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second) all, err := o.DB.ListValidators(ctx) if err != nil { return err } for _, v := range all { if v.State == db.ValidatorUnreachable || v.State == db.ValidatorDiagnostic { continue } last := o.hb.newest("v:"+v.ValidatorID, v.LastHeartbeatAt) if last == nil || !last.Before(cutoff) { continue } if err := o.DB.MarkValidatorUnreachable(ctx, v.ValidatorID); err != nil { o.Log.Error("mark validator unreachable", "validator", v.ValidatorID, "err", err) continue } o.event(ctx, "control-api", "", nil, "validator_unreachable", fmt.Sprintf(`{"validator_id":%q}`, v.ValidatorID)) } return nil } // SweepStaleSiteHeartbeats marks prober sites unreachable if they haven't // heartbeated within HeartbeatTimeoutSeconds — mirrors SweepStaleHeartbeats. func (o *Orchestrator) SweepStaleSiteHeartbeats(ctx context.Context) error { if o.inStartupGrace() { return nil } cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second) all, err := o.DB.ListSites(ctx) if err != nil { return err } for _, s := range all { if s.State == db.SiteUnreachable { continue } last := o.hb.newest("s:"+s.SiteID, s.LastHeartbeatAt) if last == nil || !last.Before(cutoff) { continue } if err := o.DB.MarkSiteUnreachable(ctx, s.SiteID); err != nil { o.Log.Error("mark site unreachable", "site_id", s.SiteID, "err", err) continue } o.event(ctx, "control-api", "", nil, "site_unreachable", fmt.Sprintf(`{"site_id":%q}`, s.SiteID)) } return nil }