feat(system): report module, connector and runner health and what waits on a person (#2023)
This commit is contained in:
16 files changed
+633
-533
No files matched your search
@@ -601,6 +601,28 @@ components:
|
||||
type: string
|
||||
writeOnly: true
|
||||
type: object
|
||||
ConnectorsHealth:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
contract:
|
||||
description: connector, secretengine, guard or mcp
|
||||
type: string
|
||||
error:
|
||||
type: string
|
||||
failed_at:
|
||||
format: date-time
|
||||
type:
|
||||
- string
|
||||
- "null"
|
||||
healthy:
|
||||
type: boolean
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
- contract
|
||||
- healthy
|
||||
type: object
|
||||
ConnectorsMcpRequest:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -2508,6 +2530,31 @@ components:
|
||||
- trigger
|
||||
- filter
|
||||
type: object
|
||||
RunsRunCounts:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
parked:
|
||||
format: int64
|
||||
type: integer
|
||||
queued:
|
||||
format: int64
|
||||
type: integer
|
||||
running:
|
||||
format: int64
|
||||
type: integer
|
||||
waiting:
|
||||
format: int64
|
||||
type: integer
|
||||
waiting_approval:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- queued
|
||||
- running
|
||||
- waiting
|
||||
- waiting_approval
|
||||
- parked
|
||||
type: object
|
||||
RunsRunView:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -2899,6 +2946,105 @@ components:
|
||||
- admin_token_set
|
||||
- sealing_identity_set
|
||||
type: object
|
||||
SystemCheck:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
healthy:
|
||||
type: boolean
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
- healthy
|
||||
type: object
|
||||
SystemFailure:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
at:
|
||||
format: date-time
|
||||
type: string
|
||||
cause:
|
||||
type: string
|
||||
run_id:
|
||||
type: string
|
||||
source:
|
||||
description: A connector name, the runner, or a workflow
|
||||
type: string
|
||||
required:
|
||||
- source
|
||||
- cause
|
||||
- at
|
||||
type: object
|
||||
SystemHealth:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
checked_at:
|
||||
format: date-time
|
||||
type: string
|
||||
checks:
|
||||
items:
|
||||
$ref: "#/components/schemas/SystemCheck"
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
connectors:
|
||||
items:
|
||||
$ref: "#/components/schemas/ConnectorsHealth"
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
healthy:
|
||||
type: boolean
|
||||
last_failure:
|
||||
$ref: "#/components/schemas/SystemFailure"
|
||||
runner:
|
||||
$ref: "#/components/schemas/SystemRunner"
|
||||
version:
|
||||
type: string
|
||||
waiting:
|
||||
$ref: "#/components/schemas/SystemWaiting"
|
||||
required:
|
||||
- version
|
||||
- healthy
|
||||
- checked_at
|
||||
- checks
|
||||
- connectors
|
||||
- runner
|
||||
type: object
|
||||
SystemRunner:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
error_at:
|
||||
format: date-time
|
||||
type:
|
||||
- string
|
||||
- "null"
|
||||
healthy:
|
||||
type: boolean
|
||||
workers:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- healthy
|
||||
- workers
|
||||
type: object
|
||||
SystemWaiting:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
approvals:
|
||||
description: Approval requests waiting for an answer
|
||||
format: int64
|
||||
type: integer
|
||||
runs:
|
||||
$ref: "#/components/schemas/RunsRunCounts"
|
||||
required:
|
||||
- approvals
|
||||
- runs
|
||||
type: object
|
||||
TextInputBody:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -5781,6 +5927,25 @@ paths:
|
||||
summary: Get the bootstrap values, which only the config file sets
|
||||
tags:
|
||||
- System
|
||||
/api/system/health:
|
||||
get:
|
||||
operationId: get-system-health
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/SystemHealth"
|
||||
description: OK
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: Report whether each module, connector and the runner is working, and what waits on a person
|
||||
tags:
|
||||
- System
|
||||
/api/tokens:
|
||||
get:
|
||||
operationId: list-personal-tokens
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/modules/approvals"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
"github.com/samcharles93/archie-core/modules/system"
|
||||
)
|
||||
|
||||
// healthSources joins what each module knows about itself into the sources the
|
||||
// system health report reads. The report asks them on demand, so nothing here
|
||||
// polls or keeps state.
|
||||
func healthSources(checks *health.Registry, conns *connectors.Module, engine *runs.Engine, allow *approvals.Module) system.Sources {
|
||||
return system.Sources{
|
||||
Checks: func(ctx context.Context) []health.Result {
|
||||
return slices.DeleteFunc(checks.Results(ctx), func(r health.Result) bool {
|
||||
// The report lists each connector with its own cause.
|
||||
return r.Name == "connectors"
|
||||
})
|
||||
},
|
||||
Connectors: conns.Health,
|
||||
Runner: engine.Runner,
|
||||
Waiting: func(ctx context.Context) (system.Waiting, error) {
|
||||
pending, err := allow.Pending(ctx)
|
||||
if err != nil {
|
||||
return system.Waiting{}, fmt.Errorf("list pending approvals: %w", err)
|
||||
}
|
||||
counts, err := engine.Counts(ctx, orgID)
|
||||
if err != nil {
|
||||
return system.Waiting{}, err
|
||||
}
|
||||
return system.Waiting{Approvals: len(pending), Runs: counts}, nil
|
||||
},
|
||||
LastFailedRun: func(ctx context.Context) (*runs.RunView, error) {
|
||||
return engine.LastFailed(ctx, orgID)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -208,6 +208,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sys.UseHealth(healthSources(checks, conns, engine, allow))
|
||||
apiModules{
|
||||
settings: settings, conns: conns, system: sys, tell: tell, allow: allow, classes: classes, policies: policies,
|
||||
hear: hear, judge: judge, engine: engine, chat: talk, drafts: drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies),
|
||||
|
||||
@@ -41,14 +41,35 @@ func (r *Registry) Routes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /readyz", r.ready)
|
||||
}
|
||||
|
||||
// Result is the outcome of one readiness check; Error is empty when it passed.
|
||||
type Result struct {
|
||||
Name string `json:"name"`
|
||||
Error string `json:"error,omitzero"`
|
||||
}
|
||||
|
||||
// Results runs every check and returns the outcomes in name order. A failing
|
||||
// check does not stop the others.
|
||||
func (r *Registry) Results(ctx context.Context) []Result {
|
||||
names := r.names()
|
||||
out := make([]Result, 0, len(names))
|
||||
for _, name := range names {
|
||||
res := Result{Name: name}
|
||||
if err := r.check(name)(ctx); err != nil {
|
||||
res.Error = err.Error()
|
||||
}
|
||||
out = append(out, res)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *Registry) ready(w http.ResponseWriter, req *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
failures := map[string]string{}
|
||||
for _, name := range r.names() {
|
||||
if err := r.check(name)(ctx); err != nil {
|
||||
failures[name] = err.Error()
|
||||
for _, res := range r.Results(ctx) {
|
||||
if res.Error != "" {
|
||||
failures[res.Name] = res.Error
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
// Health is what the module knows about one accepted package right now. It is
|
||||
// read from memory, so a database outage does not hide it.
|
||||
type Health struct {
|
||||
Name string `json:"name"`
|
||||
Contract string `json:"contract" doc:"connector, secretengine, guard or mcp"`
|
||||
Healthy bool `json:"healthy"`
|
||||
// Error is why the package is not running.
|
||||
Error string `json:"error,omitzero"`
|
||||
// FailedAt is when the package last failed to start. A process that exited
|
||||
// after it started has no time.
|
||||
FailedAt *time.Time `json:"failed_at,omitzero"`
|
||||
}
|
||||
|
||||
// Health lists every package the module launched, in name order: those running,
|
||||
// those that failed to start, and those whose process has since exited or whose
|
||||
// MCP server stopped answering.
|
||||
func (m *Module) Health() []Health {
|
||||
m.mu.RLock()
|
||||
failed := maps.Clone(m.failed)
|
||||
failedAt := maps.Clone(m.failedAt)
|
||||
contracts := maps.Clone(m.contracts)
|
||||
servers := maps.Clone(m.servers)
|
||||
names := map[string]string{}
|
||||
for name := range m.running {
|
||||
names[name] = store.ContractConnector
|
||||
}
|
||||
for name := range m.engines {
|
||||
names[name] = store.ContractSecretEngine
|
||||
}
|
||||
for name := range m.guards {
|
||||
names[name] = store.ContractGuard
|
||||
}
|
||||
for name := range servers {
|
||||
names[name] = store.ContractMCP
|
||||
}
|
||||
for name := range failed {
|
||||
if _, ok := names[name]; !ok {
|
||||
names[name] = contracts[name]
|
||||
}
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
out := make([]Health, 0, len(names))
|
||||
for _, name := range slices.Sorted(maps.Keys(names)) {
|
||||
h := Health{Name: name, Contract: names[name], Healthy: true}
|
||||
server, isServer := servers[name]
|
||||
switch {
|
||||
case failed[name] != "":
|
||||
h.Healthy, h.Error = false, failed[name]
|
||||
if at, ok := failedAt[name]; ok {
|
||||
h.FailedAt = &at
|
||||
}
|
||||
case isServer:
|
||||
if err := server.Ready(); err != nil {
|
||||
h.Healthy, h.Error = false, err.Error()
|
||||
}
|
||||
case !m.host.Alive(name):
|
||||
h.Healthy, h.Error = false, "process exited"
|
||||
}
|
||||
out = append(out, h)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/jmoiron/sqlx"
|
||||
@@ -47,6 +48,11 @@ type Module struct {
|
||||
servers map[string]*Server
|
||||
stops map[string]context.CancelFunc
|
||||
failed map[string]string
|
||||
// failedAt is when a name last failed to start, and contracts is what each
|
||||
// launched name is. Both are read only for health, so an entry that outlives
|
||||
// its failure does no harm.
|
||||
failedAt map[string]time.Time
|
||||
contracts map[string]string
|
||||
// recheck, when set, re-checks saved configuration against a connector's
|
||||
// new declarations; an error refuses them.
|
||||
recheck Recheck
|
||||
@@ -452,7 +458,7 @@ func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string
|
||||
// name runs one package: whatever ran under it before is stopped first, so a
|
||||
// connector, a secret engine and an MCP server never share a name.
|
||||
func (m *Module) launch(ctx context.Context, a store.Accepted) error {
|
||||
m.release(a.Name)
|
||||
m.releaseAs(a.Name, a.Contract)
|
||||
if a.Contract == store.ContractMCP {
|
||||
return m.startServer(ctx, a)
|
||||
}
|
||||
@@ -613,12 +619,27 @@ func (m *Module) release(name string) {
|
||||
}
|
||||
}
|
||||
|
||||
// releaseAs stops whatever ran under name and records what it is about to be.
|
||||
func (m *Module) releaseAs(name, contract string) {
|
||||
m.release(name)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.contracts == nil {
|
||||
m.contracts = map[string]string{}
|
||||
}
|
||||
m.contracts[name] = contract
|
||||
}
|
||||
|
||||
func (m *Module) fail(ctx context.Context, name string, err error) error {
|
||||
m.mu.Lock()
|
||||
delete(m.running, name)
|
||||
delete(m.engines, name)
|
||||
delete(m.guards, name)
|
||||
m.failed[name] = err.Error()
|
||||
if m.failedAt == nil {
|
||||
m.failedAt = map[string]time.Time{}
|
||||
}
|
||||
m.failedAt[name] = time.Now()
|
||||
m.mu.Unlock()
|
||||
m.log.ErrorContext(ctx, "extension failed to start", "extension", name, "error", err)
|
||||
return err
|
||||
|
||||
@@ -608,13 +608,14 @@ func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[
|
||||
sections := map[string]bool{"chat": signedIn, "memory": signedIn}
|
||||
for _, name := range []string{
|
||||
"settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "memory_admin",
|
||||
"home", "system_status",
|
||||
} {
|
||||
sections[name] = p.InstanceAdmin()
|
||||
}
|
||||
for _, name := range []string{
|
||||
"home", "tasks", "work_requests", "logs", "skills", "curators", "channels",
|
||||
"tasks", "work_requests", "logs", "skills", "curators", "channels",
|
||||
"captures", "mappings", "bindings", "workflow_editor", "extension_catalogue", "model_aliases",
|
||||
"system_status", "task_execution", "organisations", "tools", "plugins", "container_runtime", "agent_profiles",
|
||||
"task_execution", "organisations", "tools", "plugins", "container_runtime", "agent_profiles",
|
||||
"org_members", "org_agents", "org_policies", "org_denials", "org_audit", "org_usage", "org_config",
|
||||
} {
|
||||
sections[name] = false
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package runs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/runs/internal/store"
|
||||
)
|
||||
|
||||
// RunnerHealth is the state of the workers that execute runs.
|
||||
type RunnerHealth struct {
|
||||
Workers int `json:"workers"`
|
||||
// Error is the last failure to claim work, until a claim succeeds again.
|
||||
Error string `json:"error,omitzero"`
|
||||
ErrorAt *time.Time `json:"error_at,omitzero"`
|
||||
}
|
||||
|
||||
// RunCounts is how many runs are in each state that still needs work or a
|
||||
// person.
|
||||
type RunCounts struct {
|
||||
Queued int `json:"queued"`
|
||||
Running int `json:"running"`
|
||||
// Waiting runs wait for a timer or a signal.
|
||||
Waiting int `json:"waiting"`
|
||||
// WaitingApproval runs ended waiting for an approval.
|
||||
WaitingApproval int `json:"waiting_approval"`
|
||||
// Parked runs stopped for a person, who retries them from a step.
|
||||
Parked int `json:"parked"`
|
||||
}
|
||||
|
||||
type claimFailure struct {
|
||||
err string
|
||||
at time.Time
|
||||
}
|
||||
|
||||
// noteClaim records the outcome of a worker's attempt to claim a run.
|
||||
func (e *Engine) noteClaim(err error) {
|
||||
if err == nil {
|
||||
e.claimFailure.Store(nil)
|
||||
return
|
||||
}
|
||||
e.claimFailure.Store(&claimFailure{err: err.Error(), at: time.Now()})
|
||||
}
|
||||
|
||||
// Runner reports the workers and the last failure to claim work.
|
||||
func (e *Engine) Runner() RunnerHealth {
|
||||
h := RunnerHealth{Workers: e.opts.Workers}
|
||||
if f := e.claimFailure.Load(); f != nil {
|
||||
h.Error, h.ErrorAt = f.err, &f.at
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// Counts returns how many of orgID's runs are in each state that still needs
|
||||
// work or a person.
|
||||
func (e *Engine) Counts(ctx context.Context, orgID string) (RunCounts, error) {
|
||||
n, err := e.db.Counts(ctx, orgID)
|
||||
if err != nil {
|
||||
return RunCounts{}, err
|
||||
}
|
||||
return RunCounts{
|
||||
Queued: n[store.StateQueued], Running: n[store.StateRunning], Waiting: n[store.StateWaiting],
|
||||
WaitingApproval: n[store.StateWaitingApproval], Parked: n[store.StateParked],
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LastFailed returns orgID's most recently failed run, or nil when none has
|
||||
// failed.
|
||||
func (e *Engine) LastFailed(ctx context.Context, orgID string) (*RunView, error) {
|
||||
s, ok, err := e.db.LastFailed(ctx, orgID)
|
||||
if err != nil || !ok {
|
||||
return nil, err
|
||||
}
|
||||
v := view(s, nil)
|
||||
return &v, nil
|
||||
}
|
||||
@@ -579,3 +579,39 @@ func nullJSON(v jsontext.Value) any {
|
||||
}
|
||||
return []byte(v)
|
||||
}
|
||||
|
||||
// Counts returns how many of an organisation's runs are in each state.
|
||||
func (s *Store) Counts(ctx context.Context, orgID string) (map[string]int, error) {
|
||||
var rows []struct {
|
||||
State string `db:"state"`
|
||||
N int `db:"n"`
|
||||
}
|
||||
if err := s.db.SelectContext(ctx, &rows, `
|
||||
SELECT state, count(*) AS n FROM runs.runs
|
||||
WHERE org_id = $1 AND NOT dry AND state IN ('queued', 'running', 'waiting', 'waiting_approval', 'parked')
|
||||
GROUP BY state`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("count runs: %w", err)
|
||||
}
|
||||
out := make(map[string]int, len(rows))
|
||||
for _, r := range rows {
|
||||
out[r.State] = r.N
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// LastFailed returns an organisation's most recently failed run; ok is false
|
||||
// when none has failed.
|
||||
func (s *Store) LastFailed(ctx context.Context, orgID string) (Summary, bool, error) {
|
||||
var out Summary
|
||||
err := s.db.GetContext(ctx, &out, `
|
||||
SELECT id, workflow, workflow_version, state, attempts, error, detail, created_at, finished_at, dry FROM runs.runs
|
||||
WHERE org_id = $1 AND NOT dry AND state = 'failed'
|
||||
ORDER BY coalesce(finished_at, created_at) DESC LIMIT 1`, orgID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Summary{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return Summary{}, false, fmt.Errorf("read last failed run: %w", err)
|
||||
}
|
||||
return out, true, nil
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -72,6 +73,9 @@ type Engine struct {
|
||||
opts Options
|
||||
mu sync.RWMutex
|
||||
deps *Deps
|
||||
// claimFailure is the last failed attempt to claim a run, cleared by the
|
||||
// next attempt that succeeds.
|
||||
claimFailure atomic.Pointer[claimFailure]
|
||||
// load turns a claimed run into the code that executes it.
|
||||
load func(ctx context.Context, run store.Run) (Workflow, error)
|
||||
}
|
||||
@@ -331,6 +335,9 @@ func (e *Engine) Work(ctx context.Context) {
|
||||
func (e *Engine) workerLoop(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
claimed, err := e.claimAndExecute(ctx)
|
||||
if ctx.Err() == nil {
|
||||
e.noteClaim(err)
|
||||
}
|
||||
if err != nil {
|
||||
e.log.ErrorContext(ctx, "run worker", "error", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/buildinfo"
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
)
|
||||
|
||||
// healthTimeout bounds the checks, so a dependency that hangs shows as
|
||||
// unhealthy instead of stalling the report.
|
||||
const healthTimeout = 5 * time.Second
|
||||
|
||||
// Sources are the facts the health report is assembled from. Each comes from
|
||||
// the module that owns it, and the composition root supplies them. A source
|
||||
// that is nil, or that fails, is reported as unhealthy.
|
||||
type Sources struct {
|
||||
// Checks runs the readiness checks, one per module or dependency.
|
||||
Checks func(context.Context) []health.Result
|
||||
// Connectors is the state of each accepted package.
|
||||
Connectors func() []connectors.Health
|
||||
// Runner is the state of the run workers.
|
||||
Runner func() runs.RunnerHealth
|
||||
// Waiting counts what waits on a person.
|
||||
Waiting func(context.Context) (Waiting, error)
|
||||
// LastFailedRun is the most recent run that failed; nil when none has.
|
||||
LastFailedRun func(context.Context) (*runs.RunView, error)
|
||||
}
|
||||
|
||||
// UseHealth sets where the health report reads from.
|
||||
func (m *Module) UseHealth(s Sources) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.sources = s
|
||||
}
|
||||
|
||||
// Waiting is what waits on a person.
|
||||
type Waiting struct {
|
||||
Approvals int `json:"approvals" doc:"Approval requests waiting for an answer"`
|
||||
// Runs are in the states that need work or a person, by state.
|
||||
Runs runs.RunCounts `json:"runs"`
|
||||
}
|
||||
|
||||
// Check is one module or dependency's readiness.
|
||||
type Check struct {
|
||||
Name string `json:"name"`
|
||||
Healthy bool `json:"healthy"`
|
||||
Error string `json:"error,omitzero"`
|
||||
}
|
||||
|
||||
// Runner is the state of the run workers.
|
||||
type Runner struct {
|
||||
Healthy bool `json:"healthy"`
|
||||
runs.RunnerHealth
|
||||
}
|
||||
|
||||
// Failure is the most recent thing that went wrong and why.
|
||||
type Failure struct {
|
||||
Source string `json:"source" doc:"A connector name, the runner, or a workflow"`
|
||||
Cause string `json:"cause"`
|
||||
At time.Time `json:"at"`
|
||||
// RunID is set when the failure is a run.
|
||||
RunID string `json:"run_id,omitzero"`
|
||||
}
|
||||
|
||||
// Health is the binary's state at the time it was read.
|
||||
type Health struct {
|
||||
Version string `json:"version"`
|
||||
Healthy bool `json:"healthy"`
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
Checks []Check `json:"checks"`
|
||||
Connectors []connectors.Health `json:"connectors"`
|
||||
Runner Runner `json:"runner"`
|
||||
// Waiting is absent when it could not be read; that is a failed check.
|
||||
Waiting *Waiting `json:"waiting,omitzero"`
|
||||
LastFailure *Failure `json:"last_failure,omitzero"`
|
||||
}
|
||||
|
||||
func (m *Module) registerHealth(api huma.API) {
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindInstance), huma.Operation{
|
||||
OperationID: "get-system-health", Method: http.MethodGet, Path: "/api/system/health",
|
||||
Summary: "Report whether each module, connector and the runner is working, and what waits on a person", Tags: []string{"System"},
|
||||
}, m.getHealth)
|
||||
}
|
||||
|
||||
// getHealth never fails because a part is down: a failing part is reported as
|
||||
// unhealthy with its cause.
|
||||
func (m *Module) getHealth(ctx context.Context, _ *struct{}) (*httpapi.Reply[Health], error) {
|
||||
m.mu.RLock()
|
||||
src := m.sources
|
||||
m.mu.RUnlock()
|
||||
ctx, cancel := context.WithTimeout(ctx, healthTimeout)
|
||||
defer cancel()
|
||||
|
||||
h := Health{Version: buildinfo.Version, CheckedAt: time.Now().UTC(), Checks: []Check{}, Connectors: []connectors.Health{}}
|
||||
if src.Checks != nil {
|
||||
for _, r := range src.Checks(ctx) {
|
||||
h.Checks = append(h.Checks, Check{Name: r.Name, Healthy: r.Error == "", Error: r.Error})
|
||||
}
|
||||
}
|
||||
if src.Connectors != nil {
|
||||
h.Connectors = src.Connectors()
|
||||
}
|
||||
h.Runner = Runner{Healthy: true}
|
||||
if src.Runner != nil {
|
||||
h.Runner.RunnerHealth = src.Runner()
|
||||
h.Runner.Healthy = h.Runner.Error == ""
|
||||
}
|
||||
if src.Waiting != nil {
|
||||
w, err := src.Waiting(ctx)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(ctx, "count what waits on a person", "error", err)
|
||||
h.Checks = append(h.Checks, Check{Name: "waiting", Error: "couldn't count approvals and runs: " + err.Error()})
|
||||
} else {
|
||||
h.Waiting = &w
|
||||
}
|
||||
}
|
||||
var lastRun *runs.RunView
|
||||
if src.LastFailedRun != nil {
|
||||
var err error
|
||||
if lastRun, err = src.LastFailedRun(ctx); err != nil {
|
||||
m.log.ErrorContext(ctx, "read the last failed run", "error", err)
|
||||
h.Checks = append(h.Checks, Check{Name: "runs", Error: "couldn't read recent runs: " + err.Error()})
|
||||
}
|
||||
}
|
||||
h.Healthy = healthy(h)
|
||||
h.LastFailure = lastFailure(h, lastRun)
|
||||
return httpapi.OK(h), nil
|
||||
}
|
||||
|
||||
func healthy(h Health) bool {
|
||||
if !h.Runner.Healthy {
|
||||
return false
|
||||
}
|
||||
for _, c := range h.Checks {
|
||||
if !c.Healthy {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, c := range h.Connectors {
|
||||
if !c.Healthy {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// lastFailure picks the newest of the failures with a time: a connector that
|
||||
// failed to start, the runner's last claim error, and the last failed run.
|
||||
func lastFailure(h Health, run *runs.RunView) *Failure {
|
||||
var out *Failure
|
||||
consider := func(f Failure) {
|
||||
if out == nil || f.At.After(out.At) {
|
||||
out = &f
|
||||
}
|
||||
}
|
||||
for _, c := range h.Connectors {
|
||||
if !c.Healthy && c.FailedAt != nil {
|
||||
consider(Failure{Source: c.Name, Cause: c.Error, At: *c.FailedAt})
|
||||
}
|
||||
}
|
||||
if h.Runner.ErrorAt != nil {
|
||||
consider(Failure{Source: "runner", Cause: h.Runner.Error, At: *h.Runner.ErrorAt})
|
||||
}
|
||||
if run != nil {
|
||||
at := run.CreatedAt
|
||||
if run.FinishedAt != nil {
|
||||
at = *run.FinishedAt
|
||||
}
|
||||
consider(Failure{Source: run.Workflow, Cause: run.Error, At: at, RunID: run.ID.String()})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -35,6 +35,7 @@ type Module struct {
|
||||
mu sync.RWMutex
|
||||
bootstrap Bootstrap
|
||||
rotate func(hash string) error
|
||||
sources Sources
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
@@ -55,6 +56,7 @@ func (m *Module) Register(api huma.API) {
|
||||
OperationID: "rotate-admin-token", Method: http.MethodPost, Path: "/api/admin/token",
|
||||
Summary: "Rotate the admin token; the new one is shown once", Tags: tags,
|
||||
}, m.rotateAdminToken)
|
||||
m.registerHealth(api)
|
||||
}
|
||||
|
||||
// adminToken is a new admin token, returned once.
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { storeToRefs } from "pinia";
|
||||
import { computed, reactive, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
|
||||
import { ChevronDown, ChevronRight } from "@lucide/vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { useSessionStore } from "@/stores/session";
|
||||
import { useTasksStore } from "@/stores/tasks";
|
||||
import { useAlerts } from "@/alerts/use-alerts";
|
||||
import ActivityRow from "./ActivityRow.vue";
|
||||
import { useOrgStore } from "@/stores/org";
|
||||
import { activityDetail } from "./activity-detail";
|
||||
import {
|
||||
ACTIVITY_FILTERS,
|
||||
activityEmptyTitle,
|
||||
filterActivity,
|
||||
type ActivityFilter,
|
||||
} from "./activity-filter";
|
||||
import { groupActivity, type ActivityGroup } from "./activity-group";
|
||||
import { describeTimelineEvent } from "@/tasks/timeline-event";
|
||||
|
||||
const identities = useOrgStore();
|
||||
identities.watchIdentities();
|
||||
|
||||
/**
|
||||
* The last 50 events, newest first, with the stream's own state on the card and
|
||||
* the All / Tasks / System filter over it. The filter and the grouping rules
|
||||
* live in activity-filter.ts and activity-group.ts and are tested there; this
|
||||
* card only renders their result.
|
||||
*/
|
||||
|
||||
const router = useRouter();
|
||||
const { summary } = storeToRefs(useTasksStore());
|
||||
const running = computed(() => summary.value?.statuses?.running || 0);
|
||||
|
||||
// Open alerts lead the feed until resolved: a stream event scrolls away, the
|
||||
// condition it reported does not.
|
||||
const { alerts } = useAlerts();
|
||||
|
||||
const { activity } = storeToRefs(
|
||||
useSessionStore(),
|
||||
);
|
||||
|
||||
/** Which view of the feed is showing: everything, task runs, or the daemon's
|
||||
* own background work. */
|
||||
const filter = ref<ActivityFilter>("tasks");
|
||||
const shown = computed(() => filterActivity(activity.value, filter.value));
|
||||
// A blocked task already leads the page under Needs attention.
|
||||
const pinned = computed(() =>
|
||||
filter.value === "tasks"
|
||||
? []
|
||||
: alerts.value.filter((alert) => alert.kind !== "task.needs_decision"),
|
||||
);
|
||||
const emptyTitle = computed(() =>
|
||||
activityEmptyTitle(shown.value.length, filter.value),
|
||||
);
|
||||
|
||||
// Expansion is keyed on label:taskID, so a live run stays open as its events
|
||||
// arrive, and a collapsed group re-collapses only when the run breaks.
|
||||
const expanded = reactive(new Set<string>());
|
||||
const groups = computed(() => groupActivity(shown.value));
|
||||
|
||||
function toggle(key: string) {
|
||||
if (expanded.has(key)) expanded.delete(key);
|
||||
else expanded.add(key);
|
||||
}
|
||||
|
||||
function isOpen(group: ActivityGroup): boolean {
|
||||
return expanded.has(group.key);
|
||||
}
|
||||
|
||||
// The collapsed group row shows what its newest event would have shown, so
|
||||
// expanding and collapsing moves no information.
|
||||
function groupDetail(group: ActivityGroup) {
|
||||
return activityDetail(group.representative, identities.identityName);
|
||||
}
|
||||
|
||||
function openTask(taskID: number) {
|
||||
void router.push(`/tasks?task=${encodeURIComponent(taskID)}`);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Section :title="running ? `Activity · ${running} running` : 'Activity'" class="mb-0">
|
||||
<template #action>
|
||||
<ToggleGroup type="single" variant="outline" size="sm" :model-value="filter" aria-label="Filter activity" @update:model-value="(value) => { if (value) filter = value as typeof filter; }">
|
||||
<ToggleGroupItem v-for="option in ACTIVITY_FILTERS" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</template>
|
||||
<!--
|
||||
role="region" names the table for landmark navigation; aria-live is
|
||||
polite, not assertive, because rows arrive constantly while the stream
|
||||
is live and an assertive region would talk over the operator. The live
|
||||
region is the table's wrapper, so new rows are announced as they
|
||||
appear without a second hidden summary to keep in sync.
|
||||
-->
|
||||
<div role="region" aria-label="Activity" aria-live="polite">
|
||||
<!--
|
||||
The feed's height is bounded to the card, not the page: group rows
|
||||
multiply with the number of interleaved tasks, so an unbounded table
|
||||
would push the rest of the dashboard off screen. The newest events
|
||||
stay visible at the top; the rest scroll inside the card. The header
|
||||
stays put via sticky so the columns keep their labels while scrolling.
|
||||
-->
|
||||
<div class="max-h-[28rem] overflow-y-auto">
|
||||
<Table>
|
||||
<TableHeader class="sticky top-0 z-10 bg-card">
|
||||
<TableRow>
|
||||
<TableHead>Event</TableHead>
|
||||
<TableHead>Task</TableHead>
|
||||
<TableHead>Detail</TableHead>
|
||||
<TableHead>When</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="alert in pinned" :key="`alert:${alert.id}`">
|
||||
<TableCell class="font-medium">
|
||||
<span class="inline-flex items-center gap-1.5">
|
||||
<StatusDot tone="warn" />Alert
|
||||
<Badge v-if="alert.count > 1" variant="idle">×{{ alert.count }}</Badge>
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell class="font-mono">–</TableCell>
|
||||
<TableCell class="w-[55%] max-w-0">
|
||||
<span class="flex items-center gap-3">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span tabindex="0" class="min-w-0 flex-1 truncate">{{ alert.title }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent v-if="alert.body">{{ alert.body }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<RouterLink v-if="alert.link" :to="alert.link" class="shrink-0 text-warn hover:underline">Fix →</RouterLink>
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell><Timestamp :at="alert.last_seen" /></TableCell>
|
||||
</TableRow>
|
||||
<TableRow v-if="!shown.length && !pinned.length">
|
||||
<TableCell colspan="4">
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>{{ emptyTitle }}</EmptyTitle>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<template v-if="shown.length">
|
||||
<template v-for="group in groups" :key="group.key">
|
||||
<!-- A singleton is exactly the row the raw feed would show. -->
|
||||
<ActivityRow
|
||||
v-if="group.count === 1"
|
||||
:event="group.representative"
|
||||
@open="openTask"
|
||||
/>
|
||||
<template v-else>
|
||||
<!--
|
||||
The row stays a row: mouse clicks open the task via the
|
||||
row handler, and the first cell holds the two real focus
|
||||
targets -- the disclosure button and, when the group
|
||||
resolves to a task, an open button carrying its title.
|
||||
-->
|
||||
<TableRow
|
||||
:class="group.taskID > 0 ? 'cursor-pointer' : ''"
|
||||
@click="group.taskID > 0 && openTask(group.taskID)"
|
||||
>
|
||||
<TableCell class="font-medium">
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center rounded hover:opacity-80 focus-visible:outline-2 focus-visible:outline-ring"
|
||||
:aria-expanded="isOpen(group)"
|
||||
:aria-label="`${isOpen(group) ? 'Hide' : 'Show'} ${group.count} ${group.label} events`"
|
||||
@click.stop="toggle(group.key)"
|
||||
>
|
||||
<ChevronDown
|
||||
v-if="isOpen(group)"
|
||||
class="size-3.5 shrink-0 text-fg-subtle"
|
||||
/>
|
||||
<ChevronRight
|
||||
v-else
|
||||
class="size-3.5 shrink-0 text-fg-subtle"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
v-if="group.taskID > 0"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded hover:opacity-80 focus-visible:outline-2 focus-visible:outline-ring"
|
||||
aria-label="Open task details"
|
||||
@click.stop="openTask(group.taskID)"
|
||||
>
|
||||
{{ describeTimelineEvent({ ...group.representative, at: undefined, detail: undefined }).title }}
|
||||
<Badge variant="idle">×{{ group.count }}</Badge>
|
||||
</button>
|
||||
<template v-else>
|
||||
{{ describeTimelineEvent({ ...group.representative, at: undefined, detail: undefined }).title }}
|
||||
<Badge variant="idle">×{{ group.count }}</Badge>
|
||||
</template>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell class="font-mono">{{
|
||||
group.taskID > 0 ? `#${group.taskID}` : "–"
|
||||
}}</TableCell>
|
||||
<TableCell class="w-[55%] max-w-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span tabindex="0" class="block truncate">{{ groupDetail(group).text }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent v-if="groupDetail(group).truncated">{{ groupDetail(group).full }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TableCell>
|
||||
<TableCell><Timestamp :at="group.representative.at" /></TableCell>
|
||||
</TableRow>
|
||||
<template v-if="isOpen(group)">
|
||||
<ActivityRow
|
||||
v-for="(event, i) in group.events"
|
||||
:key="`${group.key}:${i}`"
|
||||
:event="event"
|
||||
@open="openTask"
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
</template>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
</template>
|
||||
File renamed without changes.
@@ -1,70 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { computed, onMounted } from "vue";
|
||||
|
||||
import { Field, FieldContent, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
||||
import { useSettingsStore } from "@/stores/settings";
|
||||
import { fieldInvalid } from "./settings-form";
|
||||
import KindGate from "./KindGate.vue";
|
||||
|
||||
const KIND = "update-settings";
|
||||
type UpdateSettings = { channel: string; pin: string };
|
||||
|
||||
const store = useSettingsStore();
|
||||
onMounted(store.load);
|
||||
|
||||
const form = computed(() => store.formFor(KIND));
|
||||
const channel = computed(() => (store.draftValue(KIND) as UpdateSettings | undefined)?.channel || "stable");
|
||||
const error = computed(() => store.pageErrorFor(KIND));
|
||||
|
||||
const channels = [
|
||||
{ value: "stable", label: "Stable" },
|
||||
{ value: "next", label: "Prereleases" },
|
||||
{ value: "exact-pin", label: "Pinned" },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<KindGate v-if="!form" :kind="KIND" />
|
||||
<Section v-if="form" title="Updates">
|
||||
<Alert v-if="error" variant="destructive" class="mb-2"><AlertDescription>{{ error }}</AlertDescription></Alert>
|
||||
<FieldGroup class="@container/field-group">
|
||||
<form.Field v-slot="{ field }" name="channel">
|
||||
<Field orientation="responsive">
|
||||
<FieldContent><FieldLabel>Release channel</FieldLabel></FieldContent>
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:model-value="channel"
|
||||
aria-label="Release channel"
|
||||
@update:model-value="(value) => { if (value) field.handleChange(value); }"
|
||||
>
|
||||
<ToggleGroupItem v-for="option in channels" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
</Field>
|
||||
</form.Field>
|
||||
<form.Field v-if="channel === 'exact-pin'" v-slot="{ field }" name="pin">
|
||||
<Field orientation="responsive" :data-invalid="fieldInvalid(field)">
|
||||
<FieldContent><FieldLabel for="update-pin">Version</FieldLabel></FieldContent>
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
|
||||
<Input
|
||||
id="update-pin"
|
||||
:model-value="field.state.value"
|
||||
class="max-w-40 font-mono"
|
||||
placeholder="1.48.0"
|
||||
:aria-invalid="fieldInvalid(field)"
|
||||
@blur="field.handleBlur"
|
||||
@update:model-value="field.handleChange"
|
||||
/>
|
||||
</div>
|
||||
</Field>
|
||||
</form.Field>
|
||||
</FieldGroup>
|
||||
</Section>
|
||||
</template>
|
||||
@@ -1,214 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import CodeView from "@/base/CodeView.vue";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { ApiError, api, describeError } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { useLiveResource } from "@/stores/session";
|
||||
|
||||
/**
|
||||
* Per-component versions and the update that applies them: /api/version reports
|
||||
* what is running, what the check command claims, what is available and the
|
||||
* status between those (ok, update_available, drift, unknown).
|
||||
*/
|
||||
|
||||
interface ComponentVersion {
|
||||
id: string;
|
||||
label: string;
|
||||
install_type?: string;
|
||||
reference?: string;
|
||||
running_version?: string;
|
||||
installed_claim?: string;
|
||||
latest_available?: string;
|
||||
status: "ok" | "update_available" | "drift" | "unknown";
|
||||
}
|
||||
|
||||
const components = ref<ComponentVersion[]>([]);
|
||||
const snapshot = ref<unknown>(null);
|
||||
const available = ref<unknown[]>([]);
|
||||
const canInstall = ref(false);
|
||||
const notConfigured = ref(false);
|
||||
const loading = ref(true);
|
||||
const loadError = ref<string | null>(null);
|
||||
const installing = ref(false);
|
||||
const installProgress = ref<string[]>([]);
|
||||
const installResult = ref<string | null>(null);
|
||||
const installError = ref<string | null>(null);
|
||||
const outcome = ref<{ at: string; summary: string; failed: boolean } | null>(null);
|
||||
const outcomeError = ref<string | null>(null);
|
||||
|
||||
const updateable = computed(() =>
|
||||
components.value.filter((c) => c.status === "update_available"),
|
||||
);
|
||||
|
||||
const statusKind: Record<
|
||||
ComponentVersion["status"],
|
||||
"ok" | "warn" | "danger" | "idle"
|
||||
> = {
|
||||
ok: "ok",
|
||||
update_available: "warn",
|
||||
drift: "danger",
|
||||
unknown: "idle",
|
||||
};
|
||||
|
||||
const statusLabel: Record<ComponentVersion["status"], string> = {
|
||||
ok: "",
|
||||
update_available: "Update available",
|
||||
drift: "Version drift",
|
||||
unknown: "Unknown",
|
||||
};
|
||||
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
loadError.value = null;
|
||||
try {
|
||||
const [report, update] = await Promise.all([
|
||||
api.version<{ components: ComponentVersion[] }>(),
|
||||
api
|
||||
.updateSnapshot<{ snapshot: unknown; available: unknown[] | null; can_install: boolean }>()
|
||||
.catch((err) => {
|
||||
if (err instanceof ApiError && err.status === 501) {
|
||||
notConfigured.value = true;
|
||||
return null;
|
||||
}
|
||||
throw err;
|
||||
}),
|
||||
]);
|
||||
components.value = report.components;
|
||||
if (update) {
|
||||
snapshot.value = update.snapshot;
|
||||
available.value = update.available ?? [];
|
||||
canInstall.value = update.can_install;
|
||||
}
|
||||
} catch (err) {
|
||||
loadError.value = describeError(err, errors.common.unknown);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// The last update's outcome is the update_report event the watchdog records
|
||||
// after it restarts and health-checks the daemon.
|
||||
async function loadOutcome(): Promise<void> {
|
||||
try {
|
||||
const page = await api.audit<{
|
||||
records: {
|
||||
at: string;
|
||||
summary: string;
|
||||
detail: { data: { health_check?: string; rolled_back?: boolean } | null };
|
||||
}[];
|
||||
}>({ actions: "update_report", limit: 1 });
|
||||
const last = page.records[0];
|
||||
const data = last?.detail.data;
|
||||
outcome.value = last
|
||||
? {
|
||||
at: last.at,
|
||||
summary: last.summary,
|
||||
failed: !!data?.rolled_back || data?.health_check !== "passed",
|
||||
}
|
||||
: null;
|
||||
outcomeError.value = null;
|
||||
} catch (err) {
|
||||
outcomeError.value = describeError(err, errors.common.unknown);
|
||||
}
|
||||
}
|
||||
|
||||
// The snapshot the install endpoint demands is the one the operator saw: the
|
||||
// endpoint re-checks freshness and answers 409 when releases moved.
|
||||
function installableSnapshot(): unknown {
|
||||
return snapshot.value && available.value.length ? snapshot.value : null;
|
||||
}
|
||||
|
||||
async function install(): Promise<void> {
|
||||
const snap = installableSnapshot();
|
||||
if (!snap || installing.value) return;
|
||||
installing.value = true;
|
||||
installError.value = null;
|
||||
installProgress.value = [];
|
||||
installResult.value = null;
|
||||
try {
|
||||
const result = await api.updateInstall<{
|
||||
progress?: string[];
|
||||
result?: { installed?: Record<string, string> };
|
||||
}>(snap);
|
||||
installProgress.value = result.progress ?? [];
|
||||
const installed = result.result?.installed;
|
||||
installResult.value = installed
|
||||
? Object.entries(installed)
|
||||
.map(([id, version]) => `${id} → ${version}`)
|
||||
.join(", ")
|
||||
: "update finished";
|
||||
installResult.value = `Staged: ${installResult.value}. The outcome appears below after the restart.`;
|
||||
await load();
|
||||
} catch (err) {
|
||||
installError.value = describeError(err, errors.common.unknown);
|
||||
} finally {
|
||||
installing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
void loadOutcome();
|
||||
});
|
||||
useLiveResource("updates", () => void loadOutcome());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p v-if="notConfigured" class="text-label text-fg-muted">Update checks not configured.</p>
|
||||
<Section v-else title="Versions">
|
||||
<ReadError v-if="loadError" :message="loadError" retry-label="Retry" class="mb-3" @retry="load" />
|
||||
<p v-else-if="loading" class="text-label text-fg-muted">Checking…</p>
|
||||
<template v-else>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Component</TableHead>
|
||||
<TableHead>Running</TableHead>
|
||||
<TableHead>Available</TableHead>
|
||||
<TableHead class="w-full"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="component in components" :key="component.id">
|
||||
<TableCell>{{ component.label || component.id }}</TableCell>
|
||||
<TableCell class="font-mono text-fg-muted">{{
|
||||
component.running_version || component.installed_claim
|
||||
}}</TableCell>
|
||||
<TableCell class="font-mono text-fg-muted">{{ component.latest_available }}</TableCell>
|
||||
<TableCell>
|
||||
<Badge v-if="component.status !== 'ok'" :variant="statusKind[component.status]">{{
|
||||
statusLabel[component.status]
|
||||
}}</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<Button class="mt-4 self-start" :disabled="installing || !installableSnapshot()" @click="install">{{ installing ? "Installing…" : `Install ${updateable.map((c) => c.label || c.id).join(", ")}`.trim() }}</Button>
|
||||
|
||||
<CodeView v-if="installProgress.length" :code="installProgress.join('\n')" class="mt-3" />
|
||||
<p v-if="installResult" class="mt-2 text-label text-ok">
|
||||
{{ installResult }}
|
||||
</p>
|
||||
<p v-if="outcome" class="mt-2 text-label" :class="outcome.failed ? 'text-danger' : 'text-ok'">
|
||||
<Timestamp :at="outcome.at" /> {{ outcome.summary }}
|
||||
</p>
|
||||
<ReadError v-if="outcomeError" :message="outcomeError" class="mt-2" />
|
||||
<ReadError v-if="installError" :message="installError" class="mt-2" />
|
||||
</template>
|
||||
</Section>
|
||||
</template>
|
||||
Reference in new issue
Block a user