package api
import (
"context"
"errors"
"testing"
"time"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/ops"
)
func opsStatusWith(t *testing.T, window func() (events.Window, error)) opsStatusOut {
t.Helper()
r := ops.NewRegistry()
if err := RegisterAll(r, Deps{Version: "v", Repos: NewRepos(map[string]*Repo{}), EventWindow: window}); err != nil {
t.Fatal(err)
}
got, err := r.Invoke(ops.WithUser(context.Background(), "dan"), "ops.status", opsStatusIn{})
if err != nil {
t.Fatal(err)
}
return got.(opsStatusOut)
}
// The event stream's span is how long a node may be away before the
// window-gap rule rebuilds its stores, so the ops panel reports it beside
// the ingest lane that pays for each rebuild.
func TestTheOpsPanelReportsTheEventStreamWindow(t *testing.T) {
oldest := time.Now().Add(-57 * time.Minute)
out := opsStatusWith(t, func() (events.Window, error) {
return events.Window{FirstSeq: 7464, LastSeq: 7577, Msgs: 114, Bytes: 5_000_000,
Oldest: oldest, MaxAge: events.WindowAge}, nil
})
w := out.EventStream
if w == nil {
t.Fatal("FAIL: ops.status carries no event stream window")
}
if w.FirstSeq != 7464 || w.LastSeq != 7577 || w.Msgs != 114 || w.Bytes != 5_000_000 {
t.Errorf("FAIL: window span: %+v", *w)
}
if age := time.Duration(w.OldestAgeMs) * time.Millisecond; age < 56*time.Minute || age > 58*time.Minute {
t.Errorf("FAIL: oldest message age %s, want about 57m", age)
}
if w.MaxAgeSeconds != int(events.WindowAge/time.Second) {
t.Errorf("FAIL: max age %ds", w.MaxAgeSeconds)
}
}
// No event plane, or one that cannot answer, leaves the rest of the
// panel intact rather than failing it.
func TestTheOpsPanelWithoutAnEventWindowStillRenders(t *testing.T) {
if out := opsStatusWith(t, nil); out.EventStream != nil {
t.Errorf("FAIL: a window with nothing to read it: %+v", *out.EventStream)
}
out := opsStatusWith(t, func() (events.Window, error) { return events.Window{}, errors.New("nats down") })
if out.EventStream != nil {
t.Errorf("FAIL: a failed read reported a window: %+v", *out.EventStream)
}
}