// SPDX-License-Identifier: GPL-3.0-or-later // Package health persists the migration service liveness marker. package health import ( "fmt" "os" "path/filepath" "strconv" "strings" "time" ) const Filename = "heartbeat" const Schema = "enodia.go.health.v1" // Status is the stable machine-readable result returned by the health command. type Status struct { Schema string `json:"schema"` Healthy bool `json:"healthy"` Heartbeat string `json:"heartbeat,omitempty"` AgeSeconds int64 `json:"age_seconds,omitempty"` MaxAgeSeconds int64 `json:"max_age_seconds"` Detail string `json:"detail"` } // WriteHeartbeat atomically stores a Unix timestamp in the state directory. // A stale retained value is intentional: watchdogs can distinguish a stopped // or wedged process from a service that has never completed a sweep. func WriteHeartbeat(stateDir string, now time.Time) error { if stateDir == "" { return fmt.Errorf("state directory is required") } if err := os.MkdirAll(stateDir, 0o750); err != nil { return fmt.Errorf("create heartbeat directory: %w", err) } path := filepath.Join(stateDir, Filename) temporary := path + ".tmp" content := []byte(strconv.FormatInt(now.Unix(), 10) + "\n") if err := os.WriteFile(temporary, content, 0o600); err != nil { return fmt.Errorf("write heartbeat: %w", err) } if err := os.Rename(temporary, path); err != nil { return fmt.Errorf("replace heartbeat: %w", err) } if err := os.Chmod(path, 0o600); err != nil { return fmt.Errorf("protect heartbeat: %w", err) } return nil } // ReadHeartbeat loads the retained Unix timestamp. func ReadHeartbeat(stateDir string) (time.Time, error) { raw, err := os.ReadFile(filepath.Join(stateDir, Filename)) if err != nil { return time.Time{}, err } seconds, err := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64) if err != nil { return time.Time{}, fmt.Errorf("parse heartbeat: %w", err) } return time.Unix(seconds, 0), nil } // Check evaluates the retained heartbeat against the configured maximum age. // Missing or malformed state is represented in the result instead of returned // as an error so callers can always emit a complete health record. func Check(stateDir string, now time.Time, maxAge time.Duration) Status { status := Status{Schema: Schema, MaxAgeSeconds: int64(maxAge / time.Second)} heartbeat, err := ReadHeartbeat(stateDir) if err != nil { status.Detail = "heartbeat unavailable: " + err.Error() return status } age := now.Sub(heartbeat) if age < 0 { age = 0 } status.Heartbeat = heartbeat.Local().Format(time.RFC3339) status.AgeSeconds = int64(age / time.Second) status.Healthy = age <= maxAge if status.Healthy { status.Detail = "heartbeat is fresh" } else { status.Detail = "heartbeat is stale" } return status }