feat(judgement,approvals,ui): action classes are records with a level, history and reset; the precedent guard reads the class level (#2003)
This commit is contained in:
15 files changed
+900
-16
No files matched your search
@@ -262,6 +262,27 @@ func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Request, error)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Outcomes says what became of the requests made for the decisions in ids,
|
||||
// for the history of the action class they belong to.
|
||||
func (m *Module) Outcomes(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]judgement.Outcome, error) {
|
||||
rows, err := m.store.ByDecisions(ctx, m.orgID, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[uuid.UUID]judgement.Outcome, len(rows))
|
||||
for _, row := range rows {
|
||||
o := judgement.Outcome{State: row.State}
|
||||
if row.AnsweredBy.Valid {
|
||||
o.By = row.AnsweredBy.String
|
||||
}
|
||||
if row.AnsweredAt.Valid {
|
||||
o.At = row.AnsweredAt.Time
|
||||
}
|
||||
out[row.DecisionID] = o
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Routes adds the approvals API to mux behind guard.
|
||||
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
|
||||
mux.Handle("GET /api/approvals", guard(http.HandlerFunc(m.list)))
|
||||
|
||||
@@ -136,5 +136,23 @@ func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Re
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ByDecisions returns the requests made for the decisions in ids.
|
||||
func (s *Store) ByDecisions(ctx context.Context, orgID string, ids []uuid.UUID) ([]Request, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
query, args, err := sqlx.In(`
|
||||
SELECT `+requestColumns+` FROM approvals.requests
|
||||
WHERE org_id = ? AND decision_id IN (?) ORDER BY created_at`, orgID, ids)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list requests by decision: %w", err)
|
||||
}
|
||||
var out []Request
|
||||
if err := s.db.SelectContext(ctx, &out, s.db.Rebind(query), args...); err != nil {
|
||||
return nil, fmt.Errorf("list requests by decision: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ErrNotFound means no request has that id or key.
|
||||
var ErrNotFound = errors.New("no such approval request")
|
||||
@@ -0,0 +1,302 @@
|
||||
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"`
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// ClassDetail is a class with its history, newest first.
|
||||
type ClassDetail struct {
|
||||
ClassView
|
||||
History []HistoryEntry `json:"history"`
|
||||
Resets []ResetView `json:"resets"`
|
||||
}
|
||||
|
||||
// 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 = r.Decisions
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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, History: make([]HistoryEntry, 0, len(decisions)), Resets: make([]ResetView, 0, len(resets))}
|
||||
for _, d := range decisions {
|
||||
var body Decision
|
||||
if err := json.Unmarshal(d.Body, &body); err != nil {
|
||||
return ClassDetail{}, fmt.Errorf("decision %s: %w", d.ID, err)
|
||||
}
|
||||
level, err := parseLevel(d.Level)
|
||||
if err != nil {
|
||||
return ClassDetail{}, fmt.Errorf("decision %s: %w", d.ID, err)
|
||||
}
|
||||
o := got[d.ID]
|
||||
detail.History = append(detail.History, 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,
|
||||
})
|
||||
}
|
||||
for _, r := range resets {
|
||||
from, err := parseLevel(r.FromLevel)
|
||||
if err != nil {
|
||||
return ClassDetail{}, err
|
||||
}
|
||||
to, err := parseLevel(r.ToLevel)
|
||||
if err != nil {
|
||||
return ClassDetail{}, err
|
||||
}
|
||||
detail.Resets = append(detail.Resets, ResetView{From: from, To: to, By: r.By, At: r.At})
|
||||
}
|
||||
return detail, 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
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package judgement
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
)
|
||||
@@ -33,10 +34,17 @@ func (Reversibility) Judge(_ context.Context, a Action) (Verdict, error) {
|
||||
return Verdict{}, errors.New("the connector declares no reversibility for this action")
|
||||
}
|
||||
|
||||
// Precedent sets a ceiling from the action class's earned level. Until a
|
||||
// class has history, it is the fresh-install default: read-only classes act
|
||||
// quietly, every other class proposes and waits.
|
||||
type Precedent struct{}
|
||||
// ClassLevels says what level an action class stands at.
|
||||
type ClassLevels interface {
|
||||
Level(ctx context.Context, c Class, readOnly bool) (Level, error)
|
||||
}
|
||||
|
||||
// Precedent sets a ceiling from the action class's current level. A class
|
||||
// starts at its default (read-only classes act quietly, every other class
|
||||
// proposes and waits) and stays wherever its history has put it.
|
||||
type Precedent struct {
|
||||
Classes ClassLevels
|
||||
}
|
||||
|
||||
// Name is the guard's name in verdicts.
|
||||
func (Precedent) Name() string { return "precedent" }
|
||||
@@ -45,9 +53,10 @@ func (Precedent) Name() string { return "precedent" }
|
||||
func (Precedent) Advisory() bool { return false }
|
||||
|
||||
// Judge returns the class's level.
|
||||
func (Precedent) Judge(_ context.Context, a Action) (Verdict, error) {
|
||||
if a.Effect.ReadOnly {
|
||||
return Verdict{Ceiling: ActQuietly}, nil
|
||||
func (p Precedent) Judge(ctx context.Context, a Action) (Verdict, error) {
|
||||
level, err := p.Classes.Level(ctx, a.Class(), a.Effect.ReadOnly)
|
||||
if err != nil {
|
||||
return Verdict{}, fmt.Errorf("read class level: %w", err)
|
||||
}
|
||||
return Verdict{Ceiling: ProposeAndWait, Findings: []Finding{{Text: "this action class has no approvals yet"}}}, nil
|
||||
return Verdict{Ceiling: level, Findings: []Finding{{Text: "this action class is at " + level.String()}}}, nil
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrNoClass means no class has that id.
|
||||
var ErrNoClass = errors.New("no such action class")
|
||||
|
||||
// Class is one action class and the level it stands at.
|
||||
type Class struct {
|
||||
ID uuid.UUID `db:"id"`
|
||||
OrgID string `db:"org_id"`
|
||||
Connector string `db:"connector"`
|
||||
Action string `db:"action"`
|
||||
TargetKind string `db:"target_kind"`
|
||||
Environment string `db:"environment"`
|
||||
ReadOnly bool `db:"read_only"`
|
||||
Level string `db:"level"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
ResetAt sql.NullTime `db:"reset_at"`
|
||||
}
|
||||
|
||||
// ClassSummary is a class with how many decisions it holds.
|
||||
type ClassSummary struct {
|
||||
Class
|
||||
Decisions int `db:"decisions"`
|
||||
LastAt sql.NullTime `db:"last_at"`
|
||||
}
|
||||
|
||||
// Reset is one return of a class to its default.
|
||||
type Reset struct {
|
||||
ID uuid.UUID `db:"id"`
|
||||
FromLevel string `db:"from_level"`
|
||||
ToLevel string `db:"to_level"`
|
||||
By string `db:"by"`
|
||||
At time.Time `db:"at"`
|
||||
}
|
||||
|
||||
const classColumns = `id, org_id, connector, action, target_kind, environment, read_only, level, created_at, reset_at`
|
||||
|
||||
// EnsureClass returns the class c names, creating it at c.Level when it is
|
||||
// new. An existing class keeps its level.
|
||||
func (s *Store) EnsureClass(ctx context.Context, c Class) (Class, error) {
|
||||
var out Class
|
||||
err := s.db.GetContext(ctx, &out, `
|
||||
INSERT INTO judgement.classes (id, org_id, connector, action, target_kind, environment, read_only, level)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT (org_id, connector, action, target_kind, environment)
|
||||
DO UPDATE SET read_only = judgement.classes.read_only
|
||||
RETURNING `+classColumns,
|
||||
c.ID, c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment, c.ReadOnly, c.Level)
|
||||
if err != nil {
|
||||
return Class{}, fmt.Errorf("ensure class: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Classes returns every class, most recently decided first.
|
||||
func (s *Store) Classes(ctx context.Context, orgID string) ([]ClassSummary, error) {
|
||||
var out []ClassSummary
|
||||
err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT c.id, c.org_id, c.connector, c.action, c.target_kind, c.environment, c.read_only, c.level,
|
||||
c.created_at, c.reset_at, count(d.id) AS decisions, max(d.created_at) AS last_at
|
||||
FROM judgement.classes c
|
||||
LEFT JOIN judgement.decisions d ON d.org_id = c.org_id AND d.connector = c.connector
|
||||
AND d.action = c.action AND d.target_kind = c.target_kind AND d.environment = c.environment
|
||||
WHERE c.org_id = $1
|
||||
GROUP BY c.id
|
||||
ORDER BY coalesce(max(d.created_at), c.created_at) DESC, c.id`, orgID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list classes: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ClassByID returns one class.
|
||||
func (s *Store) ClassByID(ctx context.Context, orgID string, id uuid.UUID) (Class, error) {
|
||||
var out Class
|
||||
err := s.db.GetContext(ctx, &out, `SELECT `+classColumns+` FROM judgement.classes WHERE org_id = $1 AND id = $2`, orgID, id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Class{}, ErrNoClass
|
||||
}
|
||||
if err != nil {
|
||||
return Class{}, fmt.Errorf("read class: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ClassDecisions returns a class's newest decisions, newest first.
|
||||
func (s *Store) ClassDecisions(ctx context.Context, c Class, limit int) ([]Decision, error) {
|
||||
var out []Decision
|
||||
err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body, created_at
|
||||
FROM judgement.decisions
|
||||
WHERE org_id = $1 AND connector = $2 AND action = $3 AND target_kind = $4 AND environment = $5
|
||||
ORDER BY created_at DESC, id LIMIT $6`,
|
||||
c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list class decisions: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ClassResets returns a class's resets, newest first.
|
||||
func (s *Store) ClassResets(ctx context.Context, id uuid.UUID) ([]Reset, error) {
|
||||
var out []Reset
|
||||
err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT id, from_level, to_level, by, at FROM judgement.class_resets
|
||||
WHERE class_id = $1 ORDER BY at DESC, id`, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list class resets: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ResetClass sets a class to level and records the reset, in one transaction.
|
||||
func (s *Store) ResetClass(ctx context.Context, orgID string, id uuid.UUID, level, by string, at time.Time) (Class, error) {
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
if err != nil {
|
||||
return Class{}, fmt.Errorf("reset class: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
var before Class
|
||||
err = tx.GetContext(ctx, &before, `SELECT `+classColumns+` FROM judgement.classes WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Class{}, ErrNoClass
|
||||
}
|
||||
if err != nil {
|
||||
return Class{}, fmt.Errorf("reset class: %w", err)
|
||||
}
|
||||
var out Class
|
||||
if err := tx.GetContext(ctx, &out, `
|
||||
UPDATE judgement.classes SET level = $2, reset_at = $3 WHERE id = $1 RETURNING `+classColumns, id, level, at); err != nil {
|
||||
return Class{}, fmt.Errorf("reset class: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO judgement.class_resets (id, org_id, class_id, from_level, to_level, by, at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`, uuid.New(), orgID, id, before.Level, level, by, at); err != nil {
|
||||
return Class{}, fmt.Errorf("record reset: %w", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Class{}, fmt.Errorf("reset class: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
@@ -24,6 +25,8 @@ type Decision struct {
|
||||
Environment string `db:"environment"`
|
||||
Level string `db:"level"`
|
||||
Body []byte `db:"body"`
|
||||
// CreatedAt is set by the database and read only by the class history.
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
}
|
||||
|
||||
// Store is the judgement module's Postgres store.
|
||||
|
||||
@@ -266,3 +266,35 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type classLevel struct{ level Level }
|
||||
|
||||
func (c classLevel) Level(context.Context, Class, bool) (Level, error) { return c.level, nil }
|
||||
|
||||
// TestPrecedentCeilingIsTheClassLevel guards the earned-autonomy seam: the
|
||||
// precedent guard's ceiling is the level its action class stands at, not a
|
||||
// default, so a class that was reset, raised or lowered judges accordingly.
|
||||
func TestPrecedentCeilingIsTheClassLevel(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
level Level
|
||||
read bool
|
||||
}{
|
||||
{name: "a read-only class at its default", level: ActQuietly, read: true},
|
||||
{name: "a changing class raised to act and tell", level: ActAndTell},
|
||||
{name: "a changing class at its default", level: ProposeAndWait},
|
||||
{name: "a read-only class lowered to escalate", level: Escalate, read: true},
|
||||
{name: "a class that never runs", level: Never},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
v, err := Precedent{Classes: classLevel{tt.level}}.Judge(t.Context(), Action{Effect: connectors.Effect{ReadOnly: tt.read}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v.Ceiling != tt.level {
|
||||
t.Fatalf("ceiling = %s, want the class level %s", v.Ceiling, tt.level)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user