Files
archie/modules/judgement/classes.go
T

385 lines
11 KiB
Go

package judgement
import (
"context"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"net/http"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
)
// historyLimit bounds the decisions one class's history returns.
const historyLimit = 100
// ErrNoClass means no action class has that id.
var ErrNoClass = store.ErrNoClass
// DefaultLevel is the level a class starts at, and returns to on a reset:
// reading starts at act quietly, everything else at propose and wait.
func DefaultLevel(readOnly bool) Level {
if readOnly {
return ActQuietly
}
return ProposeAndWait
}
// Outcome is what became of a decision's request for approval.
type Outcome struct {
State string
By string
At time.Time
}
// Outcomes says what became of decisions that were held for approval. It is
// the approvals module's to answer, so a class's history can show it.
type Outcomes interface {
Outcomes(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]Outcome, error)
}
// Classes owns one organisation's action classes: the level each stands at and
// the history behind it.
type Classes struct {
orgID string
store *store.Store
log *slog.Logger
now func() time.Time
}
// NewClasses returns the action classes of orgID.
func NewClasses(db *sqlx.DB, log *slog.Logger, orgID string) *Classes {
return &Classes{orgID: orgID, store: store.New(db), log: log, now: time.Now}
}
// Level returns the level c stands at, making the class at its default if this
// is the first action of it. readOnly is the action's own declaration and is
// kept with the class, so a reset knows what its default is.
func (c *Classes) Level(ctx context.Context, class Class, readOnly bool) (Level, error) {
row, err := c.store.EnsureClass(ctx, store.Class{
ID: uuid.New(), OrgID: c.orgID, Connector: class.Connector, Action: class.Action,
TargetKind: class.TargetKind, Environment: class.Environment,
ReadOnly: readOnly, Level: DefaultLevel(readOnly).String(),
})
if err != nil {
return 0, err
}
return parseLevel(row.Level)
}
func parseLevel(s string) (Level, error) {
var l Level
if err := l.UnmarshalText([]byte(s)); err != nil {
return 0, err
}
return l, nil
}
// ClassView is an action class as the API lists it.
type ClassView struct {
ID uuid.UUID `json:"id"`
Connector string `json:"connector"`
Action string `json:"action"`
TargetKind string `json:"target_kind"`
Environment string `json:"environment"`
Level Level `json:"level"`
Default Level `json:"default"`
Decisions int `json:"decisions"`
LastDecidedAt *time.Time `json:"last_decided_at,omitzero"`
ResetAt *time.Time `json:"reset_at,omitzero"`
// Count is the approvals in a row since the class was last tightened or
// raised.
Count int `json:"count"`
// TightenedAt and TightenedBecause say when and why the class last lost
// autonomy.
TightenedAt *time.Time `json:"tightened_at,omitzero"`
TightenedBecause string `json:"tightened_because,omitzero"`
}
// HistoryEntry is one decision in a class's history, with what became of its
// request for approval.
type HistoryEntry struct {
DecisionID uuid.UUID `json:"decision_id"`
RunID uuid.UUID `json:"run_id"`
Target string `json:"target"`
Level Level `json:"level"`
Refused string `json:"refused_by,omitzero"`
// Approval is the state of the request for approval: pending, approved,
// denied or expired. It is empty when none was asked.
Approval string `json:"approval,omitzero"`
AnsweredBy string `json:"answered_by,omitzero"`
At time.Time `json:"at"`
}
// ResetView is one return of a class to its default.
type ResetView struct {
From Level `json:"from"`
To Level `json:"to"`
By string `json:"by"`
At time.Time `json:"at"`
}
// RaiseView is one proposal to loosen a class by one level.
type RaiseView struct {
ID uuid.UUID `json:"id"`
From Level `json:"from"`
To Level `json:"to"`
State string `json:"state"`
Deadline time.Time `json:"deadline"`
ProposedAt time.Time `json:"proposed_at"`
AnsweredBy string `json:"answered_by,omitzero"`
AnsweredAt *time.Time `json:"answered_at,omitzero"`
// Evidence is the approvals that earned the proposal.
Evidence []RaiseEvidence `json:"evidence"`
}
// ClassDetail is a class with its history, newest first.
type ClassDetail struct {
ClassView
History []HistoryEntry `json:"history"`
Resets []ResetView `json:"resets"`
// Raises are the proposals to loosen the class, newest first. One whose
// state is pending waits for an answer.
Raises []RaiseView `json:"raises"`
}
// List returns every class, most recently decided first.
func (c *Classes) List(ctx context.Context) ([]ClassView, error) {
rows, err := c.store.Classes(ctx, c.orgID)
if err != nil {
return nil, err
}
out := make([]ClassView, 0, len(rows))
for _, r := range rows {
v, err := viewOf(r.Class)
if err != nil {
return nil, err
}
v.Decisions, v.Count = r.Decisions, r.Streak
if r.LastAt.Valid {
v.LastDecidedAt = &r.LastAt.Time
}
out = append(out, v)
}
return out, nil
}
func viewOf(r store.Class) (ClassView, error) {
level, err := parseLevel(r.Level)
if err != nil {
return ClassView{}, fmt.Errorf("class %s: %w", r.ID, err)
}
v := ClassView{
ID: r.ID, Connector: r.Connector, Action: r.Action, TargetKind: r.TargetKind,
Environment: r.Environment, Level: level, Default: DefaultLevel(r.ReadOnly),
}
if r.ResetAt.Valid {
v.ResetAt = &r.ResetAt.Time
}
if r.TightenedAt.Valid {
v.TightenedAt, v.TightenedBecause = &r.TightenedAt.Time, r.TightenedBecause.String
}
return v, nil
}
// Detail returns one class with its newest decisions and resets. The approval
// outcomes come from outcomes.
func (c *Classes) Detail(ctx context.Context, id uuid.UUID, outcomes Outcomes) (ClassDetail, error) {
row, err := c.store.ClassByID(ctx, c.orgID, id)
if err != nil {
return ClassDetail{}, err
}
view, err := viewOf(row)
if err != nil {
return ClassDetail{}, err
}
decisions, err := c.store.ClassDecisions(ctx, row, historyLimit)
if err != nil {
return ClassDetail{}, err
}
resets, err := c.store.ClassResets(ctx, id)
if err != nil {
return ClassDetail{}, err
}
if view.Count, err = c.store.ClassCount(ctx, id); err != nil {
return ClassDetail{}, err
}
raises, err := c.store.ClassRaises(ctx, id)
if err != nil {
return ClassDetail{}, err
}
ids := make([]uuid.UUID, len(decisions))
for i, d := range decisions {
ids[i] = d.ID
}
got, err := outcomes.Outcomes(ctx, ids)
if err != nil {
return ClassDetail{}, err
}
detail := ClassDetail{ClassView: view, Raises: make([]RaiseView, 0, len(raises))}
if detail.History, err = historyOf(decisions, got); err != nil {
return ClassDetail{}, err
}
if detail.Resets, err = resetViews(resets); err != nil {
return ClassDetail{}, err
}
for _, r := range raises {
v, err := c.raiseView(r)
if err != nil {
return ClassDetail{}, err
}
detail.Raises = append(detail.Raises, v)
}
return detail, nil
}
func historyOf(decisions []store.Decision, got map[uuid.UUID]Outcome) ([]HistoryEntry, error) {
out := make([]HistoryEntry, 0, len(decisions))
for _, d := range decisions {
var body Decision
if err := json.Unmarshal(d.Body, &body); err != nil {
return nil, fmt.Errorf("decision %s: %w", d.ID, err)
}
level, err := parseLevel(d.Level)
if err != nil {
return nil, fmt.Errorf("decision %s: %w", d.ID, err)
}
o := got[d.ID]
out = append(out, HistoryEntry{
DecisionID: d.ID, RunID: d.RunID, Target: body.Action.Target.ID, Level: level,
Refused: body.RefusedBy, Approval: o.State, AnsweredBy: o.By, At: d.CreatedAt,
})
}
return out, nil
}
func resetViews(resets []store.Reset) ([]ResetView, error) {
out := make([]ResetView, 0, len(resets))
for _, r := range resets {
from, err := parseLevel(r.FromLevel)
if err != nil {
return nil, err
}
to, err := parseLevel(r.ToLevel)
if err != nil {
return nil, err
}
out = append(out, ResetView{From: from, To: to, By: r.By, At: r.At})
}
return out, nil
}
func (c *Classes) raiseView(r store.Raise) (RaiseView, error) {
from, err := parseLevel(r.FromLevel)
if err != nil {
return RaiseView{}, err
}
to, err := parseLevel(r.ToLevel)
if err != nil {
return RaiseView{}, err
}
v := RaiseView{
ID: r.ID, From: from, To: to, State: r.State, Deadline: r.Deadline, ProposedAt: r.ProposedAt,
AnsweredBy: r.AnsweredBy.String, Evidence: []RaiseEvidence{},
}
if v.State == "pending" && !c.now().Before(r.Deadline) {
v.State = "expired"
}
if r.AnsweredAt.Valid {
v.AnsweredAt = &r.AnsweredAt.Time
}
if err := json.Unmarshal(r.Evidence, &v.Evidence); err != nil {
return RaiseView{}, fmt.Errorf("raise %s: %w", r.ID, err)
}
return v, nil
}
// Reset returns a class to its default level. Its decisions and earlier resets
// stay.
func (c *Classes) Reset(ctx context.Context, id uuid.UUID, by string) (ClassView, error) {
row, err := c.store.ClassByID(ctx, c.orgID, id)
if err != nil {
return ClassView{}, err
}
row, err = c.store.ResetClass(ctx, c.orgID, id, DefaultLevel(row.ReadOnly).String(), by, c.now().UTC())
if err != nil {
return ClassView{}, err
}
return viewOf(row)
}
// bootstrapAdmin names the identity the bootstrap admin token stands for.
const bootstrapAdmin = "admin"
// Routes adds the action classes API to mux behind guard.
func (c *Classes) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler, outcomes Outcomes) {
mux.Handle("GET /api/classes", guard(http.HandlerFunc(c.list)))
mux.Handle("GET /api/classes/{id}", guard(c.detail(outcomes)))
mux.Handle("POST /api/classes/{id}/reset", guard(http.HandlerFunc(c.reset)))
}
func (c *Classes) list(w http.ResponseWriter, r *http.Request) {
out, err := c.List(r.Context())
if err != nil {
c.log.ErrorContext(r.Context(), "list classes", "error", err)
httpjson.Error(w, http.StatusInternalServerError, "couldn't list action classes")
return
}
httpjson.Write(w, http.StatusOK, out)
}
func (c *Classes) detail(outcomes Outcomes) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id, ok := classID(w, r)
if !ok {
return
}
out, err := c.Detail(r.Context(), id, outcomes)
if !c.found(w, r, err) {
return
}
httpjson.Write(w, http.StatusOK, out)
})
}
func (c *Classes) reset(w http.ResponseWriter, r *http.Request) {
id, ok := classID(w, r)
if !ok {
return
}
out, err := c.Reset(r.Context(), id, bootstrapAdmin)
if !c.found(w, r, err) {
return
}
httpjson.Write(w, http.StatusOK, out)
}
func classID(w http.ResponseWriter, r *http.Request) (uuid.UUID, bool) {
id, err := uuid.Parse(r.PathValue("id"))
if err != nil {
httpjson.Error(w, http.StatusBadRequest, "id is a class id")
return uuid.Nil, false
}
return id, true
}
// found writes the error response for err and reports whether there was none.
func (c *Classes) found(w http.ResponseWriter, r *http.Request, err error) bool {
switch {
case err == nil:
return true
case errors.Is(err, ErrNoClass):
httpjson.Error(w, http.StatusNotFound, "no such action class")
default:
c.log.ErrorContext(r.Context(), "action class", "path", r.URL.Path, "error", err)
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the action class")
}
return false
}