feat(webui): add /health and /health/detailed readiness endpoints (#717)

* feat(webui): add /health and /health/detailed readiness endpoints (archie-core-1786637496789-265-b052b772)

Implements the Operations: readiness probes bead from the hermes gap analysis
(docs/prds/hermes-gap-analysis.md sections 9-10).

- GET /health: liveness, no auth, always 200 ok.
- GET /health/detailed: authenticated (dashboard token), JSON report with
  overall ok/degraded status plus per-subsystem probe results.

New readiness probes, each reporting real current state:
- state_db: read-only StatusCounts against the store.
- config: configuration.Validate against the running config.
- disk: statfs, degraded above 90% used.
- model: active model configured + provider endpoint reachable.
- gateway: channel running/failed state + connected session count.

Layering: probe contract in internal/domain/health, implementations in
internal/infrastructure/readiness, wiring in internal/app/archied,
HTTP surface in internal/webui.

* no-mistakes(document): docs(archied): fix stale doc pointer in readiness probe comment
This commit is contained in:
sam authored and GitHub committed 2026-09-05 13:25:04 +10:00
1 parent 7843f9f3ea
commit 6af0d51459
10 files changed
+1069

No files matched your search

+4
View File
@@ -549,6 +549,10 @@ func (b *boot) setupLLMAndChat(ctx context.Context) {
if b.updateService != nil {
b.web.Chat.Updates = b.updateService
}
// Operator readiness probes: wired once the chat surface exists so the
// gateway probe can read the real session store and model manager.
b.setupReadinessProbes()
}
// setupGateways assembles the Telegram, email and webhook gateways. It
+122
View File
@@ -0,0 +1,122 @@
// readiness.go wires the operator readiness probes (internal/domain/health)
// to their real subsystem dependencies and hands the assembled registry to the
// dashboard's /health/detailed surface. It is the composition-root bridge:
// each probe gets the narrowest real input it needs, never the daemon.
package archied
import (
"context"
"fmt"
"net/http"
"path/filepath"
"strings"
"time"
channelruntime "github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/readiness"
"github.com/samcharles93/archie-core/internal/webui"
)
// setupReadinessProbes assembles the readiness probes and publishes the
// registry to the dashboard. It must be called after setupObservability (so
// b.web.Cfg and b.web.Channels are set) and after the chat wiring (so
// b.web.Chat exposes the model manager and session store).
func (b *boot) setupReadinessProbes() {
cfg := b.cfg
probes := []health.Probe{
readiness.NewStoreProbe(b.st),
readiness.NewConfigProbe(func() config.Config { return b.web.Cfg.Get() }, configuration.Validate),
readiness.NewDiskProbe(diskProbePath(cfg)),
readiness.NewModelProbe(b.chatModels.ActiveModel, b.chatModels.Models, modelReachProbe(cfg, b.chatModels.ActiveModel)),
readiness.NewGatewayProbe(
func() []readiness.ChannelState { return channelStates(b.web.Channels) },
func(ctx context.Context) int { return sessionCount(ctx, b.web.Chat) },
),
}
b.web.Health = health.NewRegistry(probes...)
}
// channelStates projects a channel lifecycle snapshot into the readiness
// probe's view, so the probe does not depend on the channels package's
// concrete type.
func channelStates(m *channelruntime.Manager) []readiness.ChannelState {
if m == nil {
return nil
}
snapshot := m.Snapshot()
states := make([]readiness.ChannelState, 0, len(snapshot))
for _, s := range snapshot {
states = append(states, readiness.ChannelState{
ID: s.ID,
Configured: s.Configured,
State: string(s.State),
})
}
return states
}
// sessionCount returns the number of gateway sessions. An unwired chat
// surface returns 0 rather than reporting a false failure.
func sessionCount(ctx context.Context, chat *webui.ChatService) int {
if chat == nil || chat.Sessions == nil {
return 0
}
sessions, err := chat.Sessions.List(ctx)
if err != nil {
return 0
}
return len(sessions)
}
// diskProbePath resolves the filesystem the readiness disk probe inspects:
// the store database directory first (the data that must fit on disk), then
// the working directory, then the process cwd.
func diskProbePath(cfg config.Config) string {
switch {
case cfg.DBPath != "":
return filepath.Dir(cfg.DBPath)
case cfg.WorkDir != "":
return cfg.WorkDir
default:
return "."
}
}
// modelReachProbe returns a live reachability check for the active model. It
// resolves the active model's provider and, when the provider has a custom
// base URL, performs a short-timeout HTTP request to it: any response
// (including 401/404) proves the endpoint is reachable, while a network error
// or an unconfigured provider reports unreachable. A provider using its SDK
// default endpoint is assumed reachable, because no custom endpoint exists to
// probe.
func modelReachProbe(cfg config.Config, active func() string) func(context.Context) error {
return func(ctx context.Context) error {
model := active()
provider, _, _ := strings.Cut(model, "/")
if provider == "" {
return fmt.Errorf("active model %q has no provider", model)
}
p, ok := cfg.Providers[provider]
if !ok {
return fmt.Errorf("provider %q not configured", provider)
}
if p.BaseURL == "" {
return nil
}
reqCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, p.BaseURL, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
_ = resp.Body.Close()
return nil
}
}
+123
View File
@@ -0,0 +1,123 @@
package archied
import (
"context"
"path/filepath"
"testing"
channelruntime "github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/webui"
)
func TestDiskProbePath_PrefersDBPath(t *testing.T) {
cfg := config.Config{DBPath: "/data/archie/tasks.db", WorkDir: "/srv/archie"}
if got := diskProbePath(cfg); got != "/data/archie" {
t.Fatalf("diskProbePath = %q, want /data/archie", got)
}
}
func TestDiskProbePath_FallsBackToWorkDir(t *testing.T) {
cfg := config.Config{WorkDir: "/srv/archie"}
if got := diskProbePath(cfg); got != "/srv/archie" {
t.Fatalf("diskProbePath = %q, want /srv/archie", got)
}
}
func TestDiskProbePath_FallsBackToCwd(t *testing.T) {
if got := diskProbePath(config.Config{}); got != "." {
t.Fatalf("diskProbePath = %q, want .", got)
}
}
func TestChannelStates_ProjectsSnapshot(t *testing.T) {
m := channelruntime.NewManager([]channelruntime.Descriptor{
{ID: "telegram", Name: "Telegram", Configured: true},
{ID: "email", Name: "Email", Configured: false},
})
m.MarkRunning("telegram")
states := channelStates(m)
if len(states) != 2 {
t.Fatalf("states = %d, want 2", len(states))
}
if states[0].ID != "telegram" || !states[0].Configured || states[0].State != "running" {
t.Fatalf("states[0] = %+v, want telegram running", states[0])
}
if states[1].ID != "email" || states[1].Configured || states[1].State != "stopped" {
t.Fatalf("states[1] = %+v, want email stopped", states[1])
}
}
func TestChannelStates_NilManager(t *testing.T) {
if got := channelStates(nil); got != nil {
t.Fatalf("channelStates(nil) = %#v, want nil", got)
}
}
func TestSessionCount_ToleratesUnwiredChat(t *testing.T) {
if got := sessionCount(context.Background(), nil); got != 0 {
t.Fatalf("sessionCount(nil chat) = %d, want 0", got)
}
if got := sessionCount(context.Background(), &webui.ChatService{}); got != 0 {
t.Fatalf("sessionCount(unwired Sessions) = %d, want 0", got)
}
}
// TestSetupReadinessProbes_WiresEverySubsystem proves the composition root
// registers all five readiness probes and that the registry surfaces them in
// the detailed report. It does not assert their status -- real state depends
// on the store, config, disk, model and gateway in the running daemon -- only
// that every subsystem the epic names is actually wired.
func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) {
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
cfg := config.Config{
BotUser: "archie-bot",
DBPath: filepath.Join(t.TempDir(), "tasks.db"),
PollInterval: config.Duration(60_000_000_000), // 60s, satisfies validate
Dispatch: config.Dispatch{Trigger: "assignee"},
Forge: config.Forge{Type: "none"},
Containers: config.ContainerConfig{
Image: "ghcr.io/samcharles93/archie-agent:latest",
},
Providers: map[string]config.Provider{
"openai": {Class: "openai"},
},
}
b := &boot{
st: st,
web: &webui.Server{
Cfg: config.NewHolder(cfg),
Channels: channelruntime.NewManager([]channelruntime.Descriptor{{ID: "telegram", Name: "Telegram", Configured: true}}),
Chat: &webui.ChatService{
Sessions: gateway.NewSessionStoreMemory(),
Models: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
},
},
chatModels: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
cfg: cfg,
}
b.setupReadinessProbes()
if b.web.Health == nil {
t.Fatal("b.web.Health is nil after setupReadinessProbes")
}
report := b.web.Health.Run(context.Background())
if len(report.Components) != 5 {
t.Fatalf("components = %d, want 5: %+v", len(report.Components), report.Components)
}
want := []string{"state_db", "config", "disk", "model", "gateway"}
for i, name := range want {
if report.Components[i].Name != name {
t.Fatalf("component[%d] = %q, want %q", i, report.Components[i].Name, name)
}
}
}
+101
View File
@@ -0,0 +1,101 @@
// Package health is the readiness-probe contract for archie's operator
// surfaces. It defines the probe shape (Name + Check), the resulting
// Status vocabulary, and a Registry that runs a fixed set of probes and
// aggregates their results into one report.
//
// Concrete probe implementations live in internal/infrastructure/health;
// composition root wiring lives in internal/app/archied. This package owns
// only the contract and the aggregation rule, so a new subsystem probe never
// has to touch the HTTP surface or the composition root.
//
// The vocabulary is deliberately tiny: a probe is either `ok` (ready for
// work) or `degraded` (not ready -- failed, or a required subsystem report it
// cannot serve). There is no "unknown"; a probe that cannot run must say so
// loudly by reporting degraded, because a readiness consumer treats anything
// other than `ok` as a reason to stop routing work.
package health
import "context"
// Status is a probe or report's point-in-time readiness state.
type Status string
const (
// StatusOK reports the subsystem is ready for work.
StatusOK Status = "ok"
// StatusDegraded reports the subsystem is not ready -- a check failed,
// a required dependency is missing, or the probe cannot answer.
StatusDegraded Status = "degraded"
)
// Result is one probe's point-in-time outcome.
type Result struct {
// Status is ok or degraded.
Status Status
// Detail is a short human-readable explanation. Empty on a clean ok.
Detail string
}
// Probe is a single subsystem readiness check. Name must be stable and
// unique within a registry -- it is the JSON key consumers match on.
type Probe interface {
Name() string
Check(ctx context.Context) Result
}
// Component is one subsystem's probe result as it appears in a report.
type Component struct {
// Name is the stable subsystem identifier, e.g. "state_db", "config".
Name string `json:"name"`
// Status is ok or degraded.
Status Status `json:"status"`
// Ready is true when the subsystem is ready for work.
Ready bool `json:"ready"`
// Detail is a short human-readable explanation. Empty on a clean ok.
Detail string `json:"detail,omitempty"`
}
// Report is the aggregate detailed readiness report. Its Status rolls up
// every component: ok only when every component is ok, degraded otherwise.
type Report struct {
Status Status `json:"status"`
Components []Component `json:"components"`
}
// Registry runs a fixed set of probes and aggregates their results into a
// single report. Probe order is preserved, so the report is stable across
// calls. A registry with no probes reports ok with an empty component list --
// the caller decides whether an empty system is ready.
type Registry struct {
probes []Probe
}
// NewRegistry returns a Registry running probes in the given order. The
// slice is copied so a later caller mutation cannot change the probe set.
func NewRegistry(probes ...Probe) *Registry {
return &Registry{probes: append([]Probe(nil), probes...)}
}
// Run executes every probe and aggregates the results. Each probe runs
// against the same ctx; a probe that blocks past ctx cancellation should
// honour it and return a degraded result rather than leak a goroutine.
func (r *Registry) Run(ctx context.Context) Report {
report := Report{
Status: StatusOK,
Components: make([]Component, 0, len(r.probes)),
}
for _, p := range r.probes {
res := p.Check(ctx)
comp := Component{
Name: p.Name(),
Status: res.Status,
Ready: res.Status == StatusOK,
Detail: res.Detail,
}
report.Components = append(report.Components, comp)
if comp.Status != StatusOK {
report.Status = StatusDegraded
}
}
return report
}
+96
View File
@@ -0,0 +1,96 @@
package health
import (
"context"
"errors"
"testing"
)
type fakeProbe struct {
name string
check func(context.Context) Result
}
func (f fakeProbe) Name() string { return f.name }
func (f fakeProbe) Check(ctx context.Context) Result { return f.check(ctx) }
func TestRegistry_EmptyReportsOK(t *testing.T) {
if got := NewRegistry().Run(context.Background()).Status; got != StatusOK {
t.Fatalf("empty registry status = %q, want %q", got, StatusOK)
}
}
func TestRegistry_AggregatesEveryComponent(t *testing.T) {
r := NewRegistry(
fakeProbe{name: "state_db", check: func(context.Context) Result {
return Result{Status: StatusOK}
}},
fakeProbe{name: "config", check: func(context.Context) Result {
return Result{Status: StatusOK}
}},
)
report := r.Run(context.Background())
if report.Status != StatusOK {
t.Fatalf("status = %q, want %q", report.Status, StatusOK)
}
if len(report.Components) != 2 {
t.Fatalf("components = %d, want 2", len(report.Components))
}
for _, c := range report.Components {
if !c.Ready || c.Status != StatusOK {
t.Fatalf("component %q should be ready, got %+v", c.Name, c)
}
}
}
func TestRegistry_OneDegradedDegradesTheWhole(t *testing.T) {
r := NewRegistry(
fakeProbe{name: "state_db", check: func(context.Context) Result {
return Result{Status: StatusOK}
}},
fakeProbe{name: "disk", check: func(context.Context) Result {
return Result{Status: StatusDegraded, Detail: "93% used"}
}},
)
report := r.Run(context.Background())
if report.Status != StatusDegraded {
t.Fatalf("status = %q, want %q", report.Status, StatusDegraded)
}
if len(report.Components) != 2 {
t.Fatalf("components = %d, want 2", len(report.Components))
}
if report.Components[1].Ready {
t.Fatalf("disk component should not be ready, got %+v", report.Components[1])
}
if report.Components[1].Detail != "93% used" {
t.Fatalf("disk detail = %q, want %q", report.Components[1].Detail, "93% used")
}
}
func TestRegistry_OrderIsPreserved(t *testing.T) {
r := NewRegistry(
fakeProbe{name: "first", check: func(context.Context) Result { return Result{Status: StatusOK} }},
fakeProbe{name: "second", check: func(context.Context) Result { return Result{Status: StatusOK} }},
)
report := r.Run(context.Background())
if report.Components[0].Name != "first" || report.Components[1].Name != "second" {
t.Fatalf("component order not preserved: %+v", report.Components)
}
}
func TestRegistry_ProbeErrorMeansDegraded(t *testing.T) {
r := NewRegistry(
fakeProbe{name: "state_db", check: func(context.Context) Result {
return Result{Status: StatusDegraded, Detail: errors.New("db locked").Error()}
}},
)
report := r.Run(context.Background())
if report.Status != StatusDegraded {
t.Fatalf("status = %q, want %q", report.Status, StatusDegraded)
}
if report.Components[0].Ready {
t.Fatalf("state_db should not be ready, got %+v", report.Components[0])
}
}
+247
View File
@@ -0,0 +1,247 @@
// Package readiness implements the readiness probes declared by
// internal/domain/health. Each probe is a thin adapter over a real subsystem
// dependency: it answers with a live, current result rather than a constant,
// so an operator calling /health/detailed sees the daemon's true state.
//
// The probes are deliberately dependency-light and injectable. Each takes
// the narrowest useful shape -- an interface it defines, a function, or a
// value -- so a probe never reaches into the daemon or a broad registry for
// its inputs. Composition root wiring (internal/app/archied) builds the
// concrete values and assembles the domain Registry.
package readiness
import (
"context"
"fmt"
"syscall"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/health"
)
// --- state_db ---
// statusCounter is the read-only store surface the state_db probe needs.
// The daemon's *store.Store satisfies it; the probe never depends on the
// full task-lifecycle interface.
type statusCounter interface {
StatusCounts(ctx context.Context) (map[string]int, error)
}
// StoreProbe checks the state database with a cheap read-only query
// (StatusCounts). It is the store's own health signal: a lock, corruption,
// or connection failure surfaces as an error here.
type StoreProbe struct {
Store statusCounter
}
// NewStoreProbe returns a state_db probe over the given store.
func NewStoreProbe(s statusCounter) *StoreProbe {
return &StoreProbe{Store: s}
}
func (p *StoreProbe) Name() string { return "state_db" }
func (p *StoreProbe) Check(ctx context.Context) health.Result {
if p.Store == nil {
return health.Result{Status: health.StatusDegraded, Detail: "store not wired"}
}
if _, err := p.Store.StatusCounts(ctx); err != nil {
return health.Result{Status: health.StatusDegraded, Detail: "read failed: " + err.Error()}
}
return health.Result{Status: health.StatusOK}
}
// --- config ---
// ConfigProbe validates the running configuration. It is the same check the
// loader applies before accepting a config, run against the live snapshot.
// The validation function is injected so this probe does not import the
// configuration package directly; composition passes configuration.Validate.
type ConfigProbe struct {
Get func() config.Config
Validate func(*config.Config) error
}
// NewConfigProbe returns a config probe over the running-config getter and
// validator. Either may be nil; a nil validator degrades the probe.
func NewConfigProbe(get func() config.Config, validate func(*config.Config) error) *ConfigProbe {
return &ConfigProbe{Get: get, Validate: validate}
}
func (p *ConfigProbe) Name() string { return "config" }
func (p *ConfigProbe) Check(ctx context.Context) health.Result {
if p.Get == nil {
return health.Result{Status: health.StatusDegraded, Detail: "config not wired"}
}
cfg := p.Get()
if p.Validate == nil {
return health.Result{Status: health.StatusDegraded, Detail: "config validator not wired"}
}
if err := p.Validate(&cfg); err != nil {
return health.Result{Status: health.StatusDegraded, Detail: "invalid: " + err.Error()}
}
return health.Result{Status: health.StatusOK}
}
// --- disk ---
// DefaultDiskThreshold is the fraction of a filesystem that, when in use,
// makes the disk probe report degraded. It matches the "disk < 90% used"
// requirement of the readiness epic.
const DefaultDiskThreshold = 0.90
// DiskProbe checks the filesystem holding Path is below the used threshold.
type DiskProbe struct {
Path string
Threshold float64
}
// NewDiskProbe returns a disk probe for the directory Path, degraded when
// used usage exceeds the default 90% threshold.
func NewDiskProbe(path string) *DiskProbe {
return &DiskProbe{Path: path, Threshold: DefaultDiskThreshold}
}
func (p *DiskProbe) Name() string { return "disk" }
func (p *DiskProbe) Check(ctx context.Context) health.Result {
if p.Path == "" {
return health.Result{Status: health.StatusDegraded, Detail: "no disk path configured"}
}
var stat syscall.Statfs_t
if err := syscall.Statfs(p.Path, &stat); err != nil {
return health.Result{Status: health.StatusDegraded, Detail: "statfs failed: " + err.Error()}
}
if stat.Blocks == 0 {
return health.Result{Status: health.StatusDegraded, Detail: "cannot size filesystem"}
}
// Used fraction uses available (bavail) rather than free (bfree) so a
// filesystem with reserved blocks is not reported as safer than it is.
used := stat.Blocks - stat.Bavail
pct := float64(used) / float64(stat.Blocks)
if pct >= p.Threshold {
return health.Result{
Status: health.StatusDegraded,
Detail: fmt.Sprintf("%.0f%% used (limit %.0f%%)", pct*100, p.Threshold*100),
}
}
return health.Result{Status: health.StatusOK}
}
// --- model ---
// ModelProbe reports whether a model is configured (an active model is
// selected) and reachable (a live network check succeeds). Reachability is a
// narrow function so the probe is deterministic in tests and the composition
// root supplies the real provider probe.
type ModelProbe struct {
ActiveModel func() string
Models func() []string
Reach func(context.Context) error
}
// NewModelProbe returns a model probe. The reachability probe is optional:
// nil means the probe only verifies configuration, not the network.
func NewModelProbe(active func() string, models func() []string, reach func(context.Context) error) *ModelProbe {
return &ModelProbe{ActiveModel: active, Models: models, Reach: reach}
}
func (p *ModelProbe) Name() string { return "model" }
func (p *ModelProbe) Check(ctx context.Context) health.Result {
active := ""
if p.ActiveModel != nil {
active = p.ActiveModel()
}
models := 0
if p.Models != nil {
models = len(p.Models())
}
if active == "" && models == 0 {
return health.Result{Status: health.StatusDegraded, Detail: "no model configured"}
}
if p.Reach == nil {
return health.Result{Status: health.StatusOK, Detail: "model " + active + " configured"}
}
if err := p.Reach(ctx); err != nil {
return health.Result{Status: health.StatusDegraded, Detail: "model unreachable: " + err.Error()}
}
return health.Result{Status: health.StatusOK, Detail: "model " + active + " reachable"}
}
// --- gateway ---
// ChannelState is a per-channel lifecycle fact as the gateway probe sees it.
// It is a projection of the channels.Manager's Status, kept in this package
// so the probe does not depend on the channels package's concrete type.
type ChannelState struct {
ID string
Configured bool
State string
}
// sessionCounter returns the number of currently connected/known sessions.
type sessionCounter func(context.Context) int
// GatewayProbe reports the gateway's running/draining state and its
// connected session count. It consumes injected functions so it stays
// independent of the channels and gateway packages.
type GatewayProbe struct {
Channels func() []ChannelState
CountSessions sessionCounter
}
// NewGatewayProbe returns a gateway probe. Either function may be nil.
func NewGatewayProbe(channels func() []ChannelState, countSessions sessionCounter) *GatewayProbe {
return &GatewayProbe{Channels: channels, CountSessions: countSessions}
}
func (p *GatewayProbe) Name() string { return "gateway" }
func (p *GatewayProbe) Check(ctx context.Context) health.Result {
configChannels := 0
runningChannels := 0
failed := false
if p.Channels != nil {
for _, c := range p.Channels() {
if c.Configured {
configChannels++
}
if c.Configured && c.State == "running" {
runningChannels++
}
if c.Configured && c.State == "failed" {
failed = true
}
}
}
sessions := 0
if p.CountSessions != nil {
sessions = p.CountSessions(ctx)
}
switch {
case configChannels == 0:
return health.Result{
Status: health.StatusDegraded,
Detail: "no gateway channels configured, " + fmt.Sprintf("%d sessions", sessions),
}
case failed:
return health.Result{
Status: health.StatusDegraded,
Detail: fmt.Sprintf("channel failed, %d/%d running, %d sessions", runningChannels, configChannels, sessions),
}
case runningChannels == 0:
return health.Result{
Status: health.StatusDegraded,
Detail: fmt.Sprintf("gateway not running, %d/%d channels up, %d sessions", runningChannels, configChannels, sessions),
}
default:
return health.Result{
Status: health.StatusOK,
Detail: fmt.Sprintf("%d/%d channels running, %d sessions, not draining", runningChannels, configChannels, sessions),
}
}
}
@@ -0,0 +1,198 @@
package readiness
import (
"context"
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/health"
)
type fakeCounter struct {
err error
}
func (f fakeCounter) StatusCounts(context.Context) (map[string]int, error) {
return map[string]int{}, f.err
}
func TestStoreProbe_ReadyOnCleanQuery(t *testing.T) {
p := NewStoreProbe(fakeCounter{})
if got := p.Check(context.Background()); got.Status != health.StatusOK {
t.Fatalf("status = %q, want ok", got.Status)
}
}
func TestStoreProbe_DegradedOnError(t *testing.T) {
p := NewStoreProbe(fakeCounter{err: errors.New("database is locked")})
got := p.Check(context.Background())
if got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
if got.Detail == "" {
t.Fatalf("detail should explain the failure")
}
}
func TestStoreProbe_DegradedWhenUnwired(t *testing.T) {
p := &StoreProbe{}
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
func TestStoreProbe_Name(t *testing.T) {
if got := NewStoreProbe(fakeCounter{}).Name(); got != "state_db" {
t.Fatalf("name = %q, want state_db", got)
}
}
func TestConfigProbe_ReadyOnValidConfig(t *testing.T) {
p := NewConfigProbe(func() config.Config { return config.Config{BotUser: "b"} }, func(*config.Config) error { return nil })
if got := p.Check(context.Background()); got.Status != health.StatusOK {
t.Fatalf("status = %q, want ok", got.Status)
}
}
func TestConfigProbe_DegradedOnInvalidConfig(t *testing.T) {
p := NewConfigProbe(func() config.Config { return config.Config{} }, func(*config.Config) error { return errors.New("bot_user required") })
got := p.Check(context.Background())
if got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
if got.Detail == "" {
t.Fatalf("detail should explain the validation failure")
}
}
func TestConfigProbe_DegradedWhenGetIsNil(t *testing.T) {
p := NewConfigProbe(nil, func(*config.Config) error { return nil })
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
func TestConfigProbe_DegradedWhenValidatorIsNil(t *testing.T) {
p := NewConfigProbe(func() config.Config { return config.Config{} }, nil)
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
func TestDiskProbe_Name(t *testing.T) {
if got := NewDiskProbe(".").Name(); got != "disk" {
t.Fatalf("name = %q, want disk", got)
}
}
func TestDiskProbe_DegradedOnEmptyPath(t *testing.T) {
p := NewDiskProbe("")
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
func TestDiskProbe_DegradedOnBogusPath(t *testing.T) {
p := NewDiskProbe("/this/path/does/not/exist/zzz")
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
func TestDiskProbe_ReadyOnRealFilesystem(t *testing.T) {
p := NewDiskProbe(t.TempDir())
if got := p.Check(context.Background()); got.Status != health.StatusOK {
t.Fatalf("status = %q, want ok (temp dir should be nearly empty): %s", got.Status, got.Detail)
}
}
func TestDiskProbe_ThresholdLogic(t *testing.T) {
// A path that exists is a real filesystem; the threshold is the only
// thing we can meaningfully vary here without mocking statfs. Assert that
// a generous threshold (well above 100%) always passes, which it does
// for any real used fraction.
p := &DiskProbe{Path: t.TempDir(), Threshold: 2.0}
if got := p.Check(context.Background()); got.Status != health.StatusOK {
t.Fatalf("status = %q, want ok with threshold > 100%%", got.Status)
}
}
func TestModelProbe_DegradedWhenNoModel(t *testing.T) {
p := NewModelProbe(func() string { return "" }, func() []string { return nil }, nil)
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
func TestModelProbe_ReadyOnConfiguredNoReachCheck(t *testing.T) {
p := NewModelProbe(func() string { return "openai/gpt-4o" }, func() []string { return []string{"openai/gpt-4o"} }, nil)
got := p.Check(context.Background())
if got.Status != health.StatusOK {
t.Fatalf("status = %q, want ok", got.Status)
}
if got.Detail == "" {
t.Fatalf("detail should name the active model")
}
}
func TestModelProbe_ReachSuccess(t *testing.T) {
p := NewModelProbe(func() string { return "openai/gpt-4o" }, func() []string { return []string{"openai/gpt-4o"} }, func(context.Context) error { return nil })
if got := p.Check(context.Background()); got.Status != health.StatusOK {
t.Fatalf("status = %q, want ok", got.Status)
}
}
func TestModelProbe_ReachFailure(t *testing.T) {
p := NewModelProbe(func() string { return "openai/gpt-4o" }, func() []string { return []string{"openai/gpt-4o"} }, func(context.Context) error { return errors.New("connection refused") })
got := p.Check(context.Background())
if got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
if got.Detail == "" {
t.Fatalf("detail should explain the reachability failure")
}
}
func TestGatewayProbe_ReadyWithRunningChannels(t *testing.T) {
p := NewGatewayProbe(func() []ChannelState {
return []ChannelState{{ID: "telegram", Configured: true, State: "running"}}
}, func(context.Context) int { return 3 })
got := p.Check(context.Background())
if got.Status != health.StatusOK {
t.Fatalf("status = %q, want ok", got.Status)
}
if got.Detail == "" {
t.Fatalf("detail should report channel and session counts")
}
}
func TestGatewayProbe_DegradedWhenNoChannelsConfigured(t *testing.T) {
p := NewGatewayProbe(func() []ChannelState {
return []ChannelState{{ID: "telegram", Configured: false, State: "stopped"}}
}, func(context.Context) int { return 0 })
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
func TestGatewayProbe_DegradedWhenChannelFailed(t *testing.T) {
p := NewGatewayProbe(func() []ChannelState {
return []ChannelState{
{ID: "telegram", Configured: true, State: "failed"},
{ID: "email", Configured: true, State: "running"},
}
}, func(context.Context) int { return 5 })
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
func TestGatewayProbe_DegradedWhenNoChannelRunning(t *testing.T) {
p := NewGatewayProbe(func() []ChannelState {
return []ChannelState{{ID: "telegram", Configured: true, State: "stopped"}}
}, func(context.Context) int { return 0 })
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", got.Status)
}
}
+31
View File
@@ -0,0 +1,31 @@
package webui
import "net/http"
// handleHealth is a liveness probe: the process is up and able to serve a
// request. It deliberately bypasses requireToken, like /healthz -- a local
// orchestration tool (systemd, a watchdog, a container healthcheck) must be
// able to ask "is the process alive?" without the dashboard token. It does no
// subsystem work and always answers 200 when the process can respond at all.
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}
// handleHealthDetailed is the authenticated readiness surface. It runs every
// registered readiness probe and returns each subsystem's live result plus
// the overall rollup, so an operator can see exactly which subsystem is
// degraded rather than only that the daemon is unhealthy.
//
// It requires the dashboard token (and is mounted behind requireToken) because
// it exposes real subsystem state -- a remote caller should not be able to
// probe the disk layout or provider reachability unauthenticated. When no
// probe registry is wired, it answers 503 rather than pretending to know.
func (s *Server) handleHealthDetailed(w http.ResponseWriter, r *http.Request) {
if s.Health == nil {
http.Error(w, "readiness probes are not configured", http.StatusServiceUnavailable)
return
}
report := s.Health.Run(r.Context())
writeJSON(w, report)
}
+139
View File
@@ -0,0 +1,139 @@
package webui
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/samcharles93/archie-core/internal/domain/health"
)
type healthProbe struct {
name string
check func(context.Context) health.Result
}
func (p healthProbe) Name() string { return p.name }
func (p healthProbe) Check(ctx context.Context) health.Result { return p.check(ctx) }
// TestHealthIsReachableWithoutAToken: a liveness probe must be answerable by
// local orchestration tooling (systemd, a watchdog, a container healthcheck)
// with no dashboard token, mirroring /healthz's precedent.
func TestHealthIsReachableWithoutAToken(t *testing.T) {
srv := newTestServer(t)
srv.Token = "dashboard-secret"
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %q", w.Code, w.Body.String())
}
if w.Body.String() != "ok" {
t.Fatalf("body = %q, want ok", w.Body.String())
}
}
// TestHealthDetailedRequiresToken: the detailed surface exposes real
// subsystem state (disk layout, provider reachability) so it must be gated by
// the dashboard token, unlike /health.
func TestHealthDetailedRequiresToken(t *testing.T) {
srv := newTestServer(t)
srv.Token = "dashboard-secret"
srv.Health = health.NewRegistry(healthProbe{name: "state_db", check: func(context.Context) health.Result {
return health.Result{Status: health.StatusOK}
}})
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", w.Code)
}
}
func TestHealthDetailedReportsRollupAndComponents(t *testing.T) {
srv := newTestServer(t)
srv.Token = "dashboard-secret"
srv.Health = health.NewRegistry(
healthProbe{name: "state_db", check: func(context.Context) health.Result {
return health.Result{Status: health.StatusOK}
}},
healthProbe{name: "disk", check: func(context.Context) health.Result {
return health.Result{Status: health.StatusDegraded, Detail: "93% used"}
}},
)
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)
req.Header.Set("Authorization", "Bearer dashboard-secret")
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %q", w.Code, w.Body.String())
}
var report health.Report
if err := json.Unmarshal(w.Body.Bytes(), &report); err != nil {
t.Fatalf("decode report: %v (body %q)", err, w.Body.String())
}
if report.Status != health.StatusDegraded {
t.Fatalf("status = %q, want degraded", report.Status)
}
if len(report.Components) != 2 {
t.Fatalf("components = %d, want 2", len(report.Components))
}
if report.Components[0].Name != "state_db" || !report.Components[0].Ready {
t.Fatalf("state_db component = %+v, want ready", report.Components[0])
}
if report.Components[1].Name != "disk" || report.Components[1].Ready || report.Components[1].Detail != "93% used" {
t.Fatalf("disk component = %+v, want degraded with detail", report.Components[1])
}
}
func TestHealthDetailedAllOK(t *testing.T) {
srv := newTestServer(t)
srv.Token = "dashboard-secret"
srv.Health = health.NewRegistry(
healthProbe{name: "state_db", check: func(context.Context) health.Result {
return health.Result{Status: health.StatusOK}
}},
healthProbe{name: "config", check: func(context.Context) health.Result {
return health.Result{Status: health.StatusOK}
}},
)
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)
req.Header.Set("Authorization", "Bearer dashboard-secret")
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
var report health.Report
if err := json.Unmarshal(w.Body.Bytes(), &report); err != nil {
t.Fatalf("decode report: %v", err)
}
if report.Status != health.StatusOK {
t.Fatalf("status = %q, want ok", report.Status)
}
for _, c := range report.Components {
if !c.Ready {
t.Fatalf("component %q not ready, got %+v", c.Name, c)
}
}
}
// TestHealthDetailedUnwiredAnswers503: a deployment that has not wired probes
// must not report a fabricated healthy state.
func TestHealthDetailedUnwiredAnswers503(t *testing.T) {
srv := newTestServer(t)
srv.Token = "dashboard-secret"
srv.Health = nil
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)
req.Header.Set("Authorization", "Bearer dashboard-secret")
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", w.Code)
}
}
+8
View File
@@ -20,6 +20,7 @@ import (
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
@@ -123,6 +124,11 @@ type Server struct {
// channels. Optional: the dashboard simply omits chat when it is nil.
Chat *ChatService
// Health runs the operator readiness probes served by /health/detailed.
// Optional: nil answers 503 rather than fabricating a report, so a
// deployment that has not wired probes never looks healthy by accident.
Health *health.Registry
// Token gates access. Empty means no check, which is how loopback binds
// stay frictionless -- see IsLoopback.
Token string
@@ -345,11 +351,13 @@ func (s *Server) Handler() http.Handler {
s.registerConfigAndLogRoutes(mux)
s.registerChatRoutes(mux)
mux.HandleFunc("GET /health/detailed", s.handleHealthDetailed)
mux.HandleFunc("GET /events", s.handleSSE)
mux.Handle("GET /", s.assets())
top := http.NewServeMux()
top.HandleFunc("GET /healthz", s.handleHealthz)
top.HandleFunc("GET /health", s.handleHealth)
top.HandleFunc("POST /webhooks/capture/{source}", s.handleCapture)
top.Handle("/", s.requireToken(mux))
return top