feat(go): advance validation sidecar toward production

This commit is contained in:
Luna 2026-07-22 01:52:19 -07:00
parent 6a06eba255
commit f85c2e831a
No known key found for this signature in database
92 changed files with 8881 additions and 91 deletions

View file

@ -0,0 +1,90 @@
// 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
}

View file

@ -0,0 +1,71 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package health
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestHeartbeatRoundTripAndPermissions(t *testing.T) {
directory := filepath.Join(t.TempDir(), "state")
want := time.Unix(1_753_012_345, 987_654_321)
if err := WriteHeartbeat(directory, want); err != nil {
t.Fatal(err)
}
got, err := ReadHeartbeat(directory)
if err != nil {
t.Fatal(err)
}
if !got.Equal(time.Unix(want.Unix(), 0)) {
t.Fatalf("heartbeat=%s want=%s", got, want)
}
info, err := os.Stat(filepath.Join(directory, Filename))
if err != nil {
t.Fatal(err)
}
if got := info.Mode().Perm(); got != 0o600 {
t.Fatalf("mode=%#o", got)
}
if _, err := os.Stat(filepath.Join(directory, Filename+".tmp")); !os.IsNotExist(err) {
t.Fatalf("temporary heartbeat remains: %v", err)
}
}
func TestHeartbeatRejectsMissingDirectory(t *testing.T) {
if err := WriteHeartbeat("", time.Now()); err == nil {
t.Fatal("empty directory accepted")
}
}
func TestReadHeartbeatRejectsInvalidContent(t *testing.T) {
directory := t.TempDir()
if err := os.WriteFile(filepath.Join(directory, Filename), []byte("invalid\n"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := ReadHeartbeat(directory); err == nil {
t.Fatal("invalid heartbeat accepted")
}
}
func TestCheckReportsFreshStaleAndMissing(t *testing.T) {
directory := t.TempDir()
now := time.Unix(2_000, 0)
if err := WriteHeartbeat(directory, now.Add(-30*time.Second)); err != nil {
t.Fatal(err)
}
fresh := Check(directory, now, time.Minute)
if !fresh.Healthy || fresh.AgeSeconds != 30 || fresh.Detail != "heartbeat is fresh" {
t.Fatalf("fresh=%#v", fresh)
}
stale := Check(directory, now, 10*time.Second)
if stale.Healthy || stale.Detail != "heartbeat is stale" || stale.MaxAgeSeconds != 10 {
t.Fatalf("stale=%#v", stale)
}
missing := Check(filepath.Join(directory, "missing"), now, time.Minute)
if missing.Healthy || missing.Detail == "" {
t.Fatalf("missing=%#v", missing)
}
}