Files
archie/modules/proposals/internal/store/store.go
T
sam 911152c9d1 merge: proposals module (#1995)
# Conflicts:
#	internal/platform/pg/migrations/00008_drafts.sql
#	modules/drafts/drafts.go
#	modules/drafts/internal/store/store.go
2026-11-24 03:11:07 +11:00

298 lines
12 KiB
Go

// Package store holds the proposals module's SQL.
package store
import (
"context"
"database/sql"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jmoiron/sqlx"
)
var (
// ErrNotFound means no such proposal.
ErrNotFound = errors.New("no such proposal")
// ErrAnswered means the proposal was not waiting for an answer.
ErrAnswered = errors.New("the proposal is not waiting for an answer")
// ErrTaken means another proposal already holds the trigger name.
ErrTaken = errors.New("name already used by another proposal")
)
// Proposal is one stored proposal.
type Proposal struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
Kind string `db:"kind"`
State string `db:"state"`
Needs string `db:"needs"`
Title string `db:"title"`
Summary string `db:"summary"`
Evidence jsontext.Value `db:"evidence"`
Change jsontext.Value `db:"change"`
TargetKind string `db:"target_kind"`
TargetID string `db:"target_id"`
BaseVersion sql.NullInt32 `db:"base_version"`
// PromptedBy is a JSON array of the events that led to the proposal.
PromptedBy jsontext.Value `db:"prompted_by"`
OriginRunID uuid.NullUUID `db:"origin_run_id"`
RunID uuid.NullUUID `db:"run_id"`
ProposedByID string `db:"proposed_by_id"`
CreatedAt time.Time `db:"created_at"`
AnsweredByID sql.NullString `db:"answered_by_id"`
AnsweredAt sql.NullTime `db:"answered_at"`
AnswerReason string `db:"answer_reason"`
PublishedAt sql.NullTime `db:"published_at"`
}
// Action is one action a proposal will take.
type Action struct {
ProposalID uuid.UUID `db:"proposal_id"`
Seq int `db:"seq"`
Connector string `db:"connector"`
InstallationID uuid.UUID `db:"installation_id"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
TargetID string `db:"target_id"`
Input jsontext.Value `db:"input"`
Digest string `db:"digest"`
DecisionID uuid.UUID `db:"decision_id"`
State string `db:"state"`
Outcome string `db:"outcome"`
SettledAt sql.NullTime `db:"settled_at"`
}
const proposalColumns = `id, org_id, kind, state, needs, title, summary, evidence, change, target_kind, target_id,
base_version, to_jsonb(prompted_by) AS prompted_by, origin_run_id, run_id, proposed_by_id, created_at,
answered_by_id, answered_at, answer_reason, published_at`
const actionColumns = `proposal_id, seq, connector, installation_id, action, target_kind, target_id, input, digest,
decision_id, state, outcome, settled_at`
// Store is the proposals 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} }
// Create inserts a proposal with its actions. It reports false, and inserts
// nothing, when a unique index already holds an equivalent open proposal.
func (s *Store) Create(ctx context.Context, p Proposal, actions []Action) (bool, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return false, fmt.Errorf("begin: %w", err)
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `
INSERT INTO proposals.proposals (id, org_id, kind, state, needs, title, summary, evidence, change,
target_kind, target_id, base_version, prompted_by, origin_run_id, proposed_by_id)
VALUES ($1, $2, $3, 'pending', $4, $5, $6, $7, $8, $9, $10, $11,
ARRAY(SELECT jsonb_array_elements_text($12::jsonb)::uuid), $13, $14)
ON CONFLICT DO NOTHING`,
p.ID, p.OrgID, p.Kind, p.Needs, p.Title, p.Summary, p.Evidence, p.Change,
p.TargetKind, p.TargetID, p.BaseVersion, string(p.PromptedBy), p.OriginRunID, p.ProposedByID)
if err != nil {
return false, fmt.Errorf("create proposal: %w", err)
}
if n, _ := res.RowsAffected(); n == 0 {
return false, nil
}
for _, a := range actions {
if _, err := tx.ExecContext(ctx, `
INSERT INTO proposals.actions (proposal_id, seq, connector, installation_id, action, target_kind, target_id,
input, digest, decision_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
p.ID, a.Seq, a.Connector, a.InstallationID, a.Action, a.TargetKind, a.TargetID, a.Input, a.Digest, a.DecisionID); err != nil {
return false, fmt.Errorf("create proposal action: %w", err)
}
}
if err := tx.Commit(); err != nil {
return false, fmt.Errorf("commit proposal: %w", err)
}
return true, nil
}
// ByID returns one proposal.
func (s *Store) ByID(ctx context.Context, orgID string, id uuid.UUID) (Proposal, error) {
return s.one(ctx, `WHERE org_id = $1 AND id = $2`, orgID, id)
}
// ByGroup returns the live trigger proposal for a group of unmatched events.
func (s *Store) ByGroup(ctx context.Context, orgID string, groupID uuid.UUID) (Proposal, error) {
return s.one(ctx, `WHERE org_id = $1 AND kind = 'trigger' AND change ->> 'group_id' = $2
AND state IN ('pending', 'approved', 'published')`, orgID, groupID.String())
}
// OpenRootCause returns the open root-cause proposal for a cause on a target.
func (s *Store) OpenRootCause(ctx context.Context, orgID, targetKind, targetID, cause string) (Proposal, error) {
return s.one(ctx, `WHERE org_id = $1 AND kind = 'root_cause_fix' AND target_kind = $2 AND target_id = $3
AND change ->> 'cause' = $4 AND state IN ('pending', 'approved')`, orgID, targetKind, targetID, cause)
}
func (s *Store) one(ctx context.Context, where string, args ...any) (Proposal, error) {
var p Proposal
err := s.db.GetContext(ctx, &p, `SELECT `+proposalColumns+` FROM proposals.proposals `+where, args...)
if errors.Is(err, sql.ErrNoRows) {
return Proposal{}, ErrNotFound
}
if err != nil {
return Proposal{}, fmt.Errorf("read proposal: %w", err)
}
return p, nil
}
// List returns an organisation's proposals, newest first. An empty state lists
// every state.
func (s *Store) List(ctx context.Context, orgID, state string) ([]Proposal, error) {
var out []Proposal
if err := s.db.SelectContext(ctx, &out, `
SELECT `+proposalColumns+` FROM proposals.proposals
WHERE org_id = $1 AND ($2 = '' OR state = $2) ORDER BY created_at DESC LIMIT 200`, orgID, state); err != nil {
return nil, fmt.Errorf("list proposals: %w", err)
}
return out, nil
}
// Unfinished returns approved proposals whose change is not yet applied, oldest
// answer first.
func (s *Store) Unfinished(ctx context.Context, orgID string, limit int) ([]Proposal, error) {
var out []Proposal
if err := s.db.SelectContext(ctx, &out, `
SELECT `+proposalColumns+` FROM proposals.proposals
WHERE org_id = $1 AND state = 'approved' ORDER BY answered_at LIMIT $2`, orgID, limit); err != nil {
return nil, fmt.Errorf("list approved proposals: %w", err)
}
return out, nil
}
// Actions returns a proposal's actions in order.
func (s *Store) Actions(ctx context.Context, id uuid.UUID) ([]Action, error) {
var out []Action
if err := s.db.SelectContext(ctx, &out, `
SELECT `+actionColumns+` FROM proposals.actions WHERE proposal_id = $1 ORDER BY seq`, id); err != nil {
return nil, fmt.Errorf("list proposal actions: %w", err)
}
return out, nil
}
// Patch merges fields into the change of a pending proposal and sets who it
// needs. A null value clears a field.
func (s *Store) Patch(ctx context.Context, orgID string, id uuid.UUID, patch map[string]any, needs string) error {
raw, err := json.Marshal(patch)
if err != nil {
return fmt.Errorf("encode change: %w", err)
}
res, err := s.db.ExecContext(ctx, `
UPDATE proposals.proposals SET change = change || $3::jsonb, needs = $4
WHERE org_id = $1 AND id = $2 AND state = 'pending'`, orgID, id, string(raw), needs)
return affected(res, err, "edit proposal")
}
// PatchApproved merges fields into the change of a proposal that is being
// applied, to record progress that a retry skips.
func (s *Store) PatchApproved(ctx context.Context, orgID string, id uuid.UUID, patch map[string]any) error {
raw, err := json.Marshal(patch)
if err != nil {
return fmt.Errorf("encode change: %w", err)
}
res, err := s.db.ExecContext(ctx, `
UPDATE proposals.proposals SET change = change || $3::jsonb
WHERE org_id = $1 AND id = $2 AND state = 'approved'`, orgID, id, string(raw))
return affected(res, err, "record proposal progress")
}
// Retitle replaces a pending proposal's title and summary.
func (s *Store) Retitle(ctx context.Context, orgID string, id uuid.UUID, title, summary string) error {
res, err := s.db.ExecContext(ctx, `
UPDATE proposals.proposals SET title = $3, summary = $4 WHERE org_id = $1 AND id = $2 AND state = 'pending'`,
orgID, id, title, summary)
return affected(res, err, "retitle proposal")
}
// Refresh replaces the evidence and summary of a pending proposal.
func (s *Store) Refresh(ctx context.Context, orgID string, id uuid.UUID, summary string, evidence jsontext.Value) error {
res, err := s.db.ExecContext(ctx, `
UPDATE proposals.proposals SET summary = $3, evidence = $4 WHERE org_id = $1 AND id = $2 AND state = 'pending'`,
orgID, id, summary, evidence)
return affected(res, err, "refresh proposal")
}
// Answer settles a pending proposal as approved or rejected by one account. It
// returns ErrAnswered when the proposal was no longer waiting, so two answers
// never both succeed.
func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, byID, reason string) (Proposal, error) {
var out Proposal
err := s.db.GetContext(ctx, &out, `
UPDATE proposals.proposals
SET state = $3, answered_by_id = $4, answered_at = now(), answer_reason = $5
WHERE org_id = $1 AND id = $2 AND state = 'pending'
RETURNING `+proposalColumns, orgID, id, state, byID, reason)
if errors.Is(err, sql.ErrNoRows) {
return Proposal{}, ErrAnswered
}
if err != nil {
return Proposal{}, fmt.Errorf("answer proposal: %w", err)
}
return out, nil
}
// SetRun records the run that takes an approved proposal's actions. It keeps
// the first run recorded.
func (s *Store) SetRun(ctx context.Context, orgID string, id, runID uuid.UUID) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE proposals.proposals SET run_id = COALESCE(run_id, $3) WHERE org_id = $1 AND id = $2`, orgID, id, runID); err != nil {
return fmt.Errorf("record proposal run: %w", err)
}
return nil
}
// SettleAction records how an action ended. An action that already settled
// keeps its outcome.
func (s *Store) SettleAction(ctx context.Context, id uuid.UUID, seq int, state, outcome string) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE proposals.actions SET state = $3, outcome = $4, settled_at = now()
WHERE proposal_id = $1 AND seq = $2 AND state = 'pending'`, id, seq, state, outcome); err != nil {
return fmt.Errorf("settle proposal action: %w", err)
}
return nil
}
// Publish marks an approved proposal published once none of its actions is
// still pending. It reports whether the proposal is published.
func (s *Store) Publish(ctx context.Context, orgID string, id uuid.UUID) (bool, error) {
res, err := s.db.ExecContext(ctx, `
UPDATE proposals.proposals p SET state = 'published', published_at = now()
WHERE p.org_id = $1 AND p.id = $2 AND p.state = 'approved'
AND NOT EXISTS (SELECT 1 FROM proposals.actions a WHERE a.proposal_id = p.id AND a.state = 'pending')`, orgID, id)
if err != nil {
return false, fmt.Errorf("publish proposal: %w", err)
}
n, _ := res.RowsAffected()
return n > 0, nil
}
func affected(res sql.Result, err error, what string) error {
if err != nil {
if isUnique(err) {
return ErrTaken
}
return fmt.Errorf("%s: %w", what, err)
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
func isUnique(err error) bool {
var pgerr *pgconn.PgError
return errors.As(err, &pgerr) && pgerr.Code == "23505"
}