Files
archie/modules/approvals/internal/store/store.go
T

258 lines
9.5 KiB
Go

// Package store holds the approvals module's SQL: the requests waiting for an
// answer, and what was answered.
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// Request is one judged action waiting for a person's answer.
type Request struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
RunID uuid.UUID `db:"run_id"`
Key string `db:"key"`
// DecisionID is the judged action the request is about, or for a raise
// request the raise.
DecisionID uuid.UUID `db:"decision_id"`
Kind string `db:"kind"`
Digest string `db:"digest"`
// The action's own names, kept so a request reads back without its
// 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"`
// Step is the escalation step the request is at, StepDeadline when that
// step runs out, and Asked a JSON array of the ids of the people it has
// reached so far.
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 is why an approval no longer stood.
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 records r unless a request already exists for its run and key, and
// returns the request that stands either way.
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 settles one request, and only while it is still pending. It returns
// the request as it now stands, or the one that already settled it.
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 moves a pending request to step, which has reached person and runs
// out at until. It returns false when the request is no longer pending, or has
// already moved that far, so a replayed escalation changes nothing.
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 withdraws an approval that no longer stands, and only while it has
// not been counted. It returns false when there was nothing to discard.
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 an approval as counted, once. It returns false when the approval
// was already counted or no longer stands.
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")