Files
archie/modules/approvals/internal/store/store.go
T
samandCopilot 64dfad6d53 feat(runs): add typed results and model aliases (#2043)
Also fix repository-free message.send validation (#2046) and add a single-binary development smoke path (#1977).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-18 23:47:35 +11:00

253 lines
9.3 KiB
Go

// Package store persists approval requests, responses and rejections.
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// Request is the stored record of an action or raise approval request.
type Request struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
RunID uuid.UUID `db:"run_id"`
Key string `db:"key"`
// DecisionID identifies the judgement decision or the proposed raise.
DecisionID uuid.UUID `db:"decision_id"`
Kind string `db:"kind"`
Digest string `db:"digest"`
// Copy the action details so the request can be read without loading the decision.
Connector string `db:"connector"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
TargetID string `db:"target_id"`
Level string `db:"level"`
Summary string `db:"summary"`
State string `db:"state"`
Deadline time.Time `db:"deadline"`
CreatedAt time.Time `db:"created_at"`
AnsweredAt sql.NullTime `db:"answered_at"`
AnsweredBy sql.NullString `db:"answered_by"`
AnsweredVia sql.NullString `db:"answered_via"`
// Asked is a JSON array of person IDs reached so far, not just the
// person assigned to the current step.
Step int `db:"step"`
StepDeadline sql.NullTime `db:"step_deadline"`
Asked string `db:"asked"`
// ChangeRequest is whether the request went through a change request
// rather than the approvers' channels.
ChangeRequest bool `db:"change_request"`
// Counted is whether the approval was counted toward raising its class.
Counted bool `db:"counted"`
DiscardedBecause sql.NullString `db:"discarded_because"`
}
// Store is the approvals module's Postgres store.
type Store struct {
db *sqlx.DB
}
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, action, target_kind,
target_id, level, summary, state, deadline, created_at, answered_at, answered_by, answered_via,
step, step_deadline, asked::text AS asked, change_request, counted, discarded_because`
// Put inserts r or returns the existing request for the same organisation,
// run and key.
func (s *Store) Put(ctx context.Context, r Request) (Request, error) {
var out Request
err := s.db.GetContext(ctx, &out, `
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, action,
target_kind, target_id, level, summary, state, deadline, step_deadline, asked, change_request)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, CAST($17 AS jsonb), $18)
ON CONFLICT (org_id, run_id, key) DO NOTHING
RETURNING `+requestColumns,
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Kind, r.Digest, r.Connector, r.Action, r.TargetKind,
r.TargetID, r.Level, r.Summary, r.State, r.Deadline, r.StepDeadline, r.askedOrEmpty(), r.ChangeRequest)
if errors.Is(err, sql.ErrNoRows) {
return s.Get(ctx, r.OrgID, r.RunID, r.Key)
}
if err != nil {
return Request{}, fmt.Errorf("put request: %w", err)
}
return out, nil
}
func (r Request) askedOrEmpty() string {
if r.Asked == "" {
return "[]"
}
return r.Asked
}
// Get returns the request for one run's key.
func (s *Store) Get(ctx context.Context, orgID string, runID uuid.UUID, key string) (Request, error) {
var out Request
if err := s.db.GetContext(ctx, &out, `
SELECT `+requestColumns+` FROM approvals.requests
WHERE org_id = $1 AND run_id = $2 AND key = $3`, orgID, runID, key); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return Request{}, ErrNotFound
}
return Request{}, fmt.Errorf("read request: %w", err)
}
return out, nil
}
// Answer updates only pending requests. If another response already settled
// the request, it returns the stored record unchanged.
func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, by, via string, at time.Time) (Request, error) {
var out Request
err := s.db.GetContext(ctx, &out, `
UPDATE approvals.requests
SET state = $3, answered_at = $4, answered_by = $5, answered_via = $6
WHERE org_id = $1 AND id = $2 AND state = 'pending'
RETURNING `+requestColumns, orgID, id, state, at, by, via)
if errors.Is(err, sql.ErrNoRows) {
return s.ByID(ctx, orgID, id)
}
if err != nil {
return Request{}, fmt.Errorf("answer request: %w", err)
}
return out, nil
}
// Escalate advances a pending request to step, sets the deadline to until and
// records person if supplied. It returns false if the request has already
// reached that step or is no longer pending.
func (s *Store) Escalate(ctx context.Context, orgID string, id uuid.UUID, step int, person string, until time.Time) (Request, bool, error) {
var out Request
err := s.db.GetContext(ctx, &out, `
UPDATE approvals.requests
SET step = $3, step_deadline = $4,
asked = CASE WHEN $5::text = '' OR asked @> to_jsonb($5::text) THEN asked ELSE asked || to_jsonb($5::text) END
WHERE org_id = $1 AND id = $2 AND state = 'pending' AND step < $3
RETURNING `+requestColumns, orgID, id, step, until, person)
if errors.Is(err, sql.ErrNoRows) {
return Request{}, false, nil
}
if err != nil {
return Request{}, false, fmt.Errorf("escalate request: %w", err)
}
return out, true, nil
}
// Discard invalidates an approval only if it has not yet been counted.
// It returns false if no record was updated.
func (s *Store) Discard(ctx context.Context, orgID string, id uuid.UUID, because string) (Request, bool, error) {
var out Request
err := s.db.GetContext(ctx, &out, `
UPDATE approvals.requests SET state = 'discarded', discarded_because = $3
WHERE org_id = $1 AND id = $2 AND state = 'approved' AND NOT counted
RETURNING `+requestColumns, orgID, id, because)
if errors.Is(err, sql.ErrNoRows) {
return Request{}, false, nil
}
if err != nil {
return Request{}, false, fmt.Errorf("discard approval: %w", err)
}
return out, true, nil
}
// Count marks a valid action approval as counted. It returns false if no
// eligible approval was updated.
func (s *Store) Count(ctx context.Context, orgID string, id uuid.UUID) (Request, bool, error) {
var out Request
err := s.db.GetContext(ctx, &out, `
UPDATE approvals.requests SET counted = true
WHERE org_id = $1 AND id = $2 AND state = 'approved' AND NOT counted AND kind = 'action'
RETURNING `+requestColumns, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Request{}, false, nil
}
if err != nil {
return Request{}, false, fmt.Errorf("count approval: %w", err)
}
return out, true, nil
}
// ByID returns one request.
func (s *Store) ByID(ctx context.Context, orgID string, id uuid.UUID) (Request, error) {
var out Request
if err := s.db.GetContext(ctx, &out, `
SELECT `+requestColumns+` FROM approvals.requests WHERE org_id = $1 AND id = $2`, orgID, id); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return Request{}, ErrNotFound
}
return Request{}, fmt.Errorf("read request: %w", err)
}
return out, nil
}
// Pending returns the requests still waiting for an answer, oldest first.
func (s *Store) Pending(ctx context.Context, orgID string) ([]Request, error) {
var out []Request
if err := s.db.SelectContext(ctx, &out, `
SELECT `+requestColumns+` FROM approvals.requests
WHERE org_id = $1 AND state = 'pending' ORDER BY created_at`, orgID); err != nil {
return nil, fmt.Errorf("list pending requests: %w", err)
}
return out, nil
}
// ForRun returns a run's requests, oldest first.
func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Request, error) {
var out []Request
if err := s.db.SelectContext(ctx, &out, `
SELECT `+requestColumns+` FROM approvals.requests
WHERE org_id = $1 AND run_id = $2 ORDER BY created_at, id`, orgID, runID); err != nil {
return nil, fmt.Errorf("list run requests: %w", err)
}
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
}
// Refusal is an answer that was not accepted, and why.
type Refusal struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
RequestID uuid.UUID `db:"request_id"`
Identity string `db:"identity"`
Via string `db:"via"`
Reason string `db:"reason"`
At time.Time `db:"at"`
}
// Refuse records an answer that wasn't accepted.
func (s *Store) Refuse(ctx context.Context, r Refusal) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO approvals.refusals (id, org_id, request_id, identity, via, reason, at)
VALUES (:id, :org_id, :request_id, :identity, :via, :reason, :at)`, r); err != nil {
return fmt.Errorf("record refusal: %w", err)
}
return nil
}
// ErrNotFound means no request has that id or key.
var ErrNotFound = errors.New("no such approval request")