// Package store holds the judgement module's SQL: every decision, with the // action type it belongs to. package store import ( "context" "database/sql" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jmoiron/sqlx" ) // Decision is one recorded decision. Body is the whole decision as JSON. type Decision struct { ID uuid.UUID `db:"id"` OrgID string `db:"org_id"` RunID uuid.UUID `db:"run_id"` Key string `db:"key"` ActionTypeID uuid.UUID `db:"action_type_id"` // Connector holds the connector's immutable package identifier, never // renamed and never given to a different package. Connector string `db:"connector"` Action string `db:"action"` TargetKind string `db:"target_kind"` Environment string `db:"environment"` // InstallationID and InstallationScope name the installation the action // resolved to. InstallationID uuid.UUID `db:"installation_id"` InstallationScope string `db:"installation_scope"` Level string `db:"level"` Dry bool `db:"dry"` Body []byte `db:"body"` // CreatedAt is set by the database and read only by the action type history. CreatedAt time.Time `db:"created_at"` } const decisionColumns = `id, org_id, run_id, key, action_type_id, connector, action, target_kind, environment, level, body` // Store is the judgement 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} } // Record stores d unless a decision with its key exists, and returns the // decision that is kept. func (s *Store) Record(ctx context.Context, d Decision) (Decision, error) { var kept Decision err := s.db.GetContext(ctx, &kept, ` INSERT INTO judgement.decisions (id, org_id, run_id, key, action_type_id, connector, installation_id, installation_scope, action, target_kind, environment, level, dry, body) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) ON CONFLICT (org_id, key) DO NOTHING RETURNING `+decisionColumns, d.ID, d.OrgID, d.RunID, d.Key, d.ActionTypeID, d.Connector, d.InstallationID, d.InstallationScope, d.Action, d.TargetKind, d.Environment, d.Level, d.Dry, d.Body) if errors.Is(err, sql.ErrNoRows) { err = s.db.GetContext(ctx, &kept, ` SELECT `+decisionColumns+` FROM judgement.decisions WHERE org_id = $1 AND key = $2`, d.OrgID, d.Key) } if err != nil { return Decision{}, fmt.Errorf("record decision: %w", err) } return kept, nil } // AppendCall adds one connector call to a decision body's calls. The request // and response therefore sit with the judgement they justified, whether they // were part of judging the action or of running it. func (s *Store) AppendCall(ctx context.Context, orgID string, id uuid.UUID, call string) error { if _, err := s.db.ExecContext(ctx, ` UPDATE judgement.decisions SET body = jsonb_set(body::jsonb, '{calls}', COALESCE(body::jsonb->'calls', '[]'::jsonb) || jsonb_build_array($3::jsonb))::json WHERE org_id = $1 AND id = $2`, orgID, id, call); err != nil { return fmt.Errorf("record connector call: %w", err) } return nil } // RecentBodies returns the newest decisions' bodies and when each was made. // The judgement control page reads them to show the last standing a guard's // model judge recorded. func (s *Store) RecentBodies(ctx context.Context, orgID string, limit int) ([]Decision, error) { var out []Decision if err := s.db.SelectContext(ctx, &out, ` SELECT `+decisionColumns+`, created_at FROM judgement.decisions WHERE org_id = $1 ORDER BY created_at DESC LIMIT $2`, orgID, limit); err != nil { return nil, fmt.Errorf("list recent decisions: %w", err) } return out, nil } // ForRun returns a run's decisions in the order they were made. func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Decision, error) { var out []Decision if err := s.db.SelectContext(ctx, &out, ` SELECT `+decisionColumns+` FROM judgement.decisions WHERE org_id = $1 AND run_id = $2 ORDER BY created_at, id`, orgID, runID); err != nil { return nil, fmt.Errorf("list decisions: %w", err) } return out, nil } // CountActions counts the decisions for actions that change something: those // of a run, and every one made since the cutoff. It leaves out the attempt // named key and anything a hard rule refused. Whether an action only reads is // in the decision body, as the encoding of connectors.Effect. func (s *Store) CountActions(ctx context.Context, orgID string, runID uuid.UUID, key string, since time.Time) (inRun, inDay int, err error) { var n struct { Run int `db:"in_run"` Day int `db:"in_day"` } err = s.db.GetContext(ctx, &n, ` SELECT count(*) FILTER (WHERE run_id = $2) AS in_run, count(*) FILTER (WHERE created_at >= $4) AS in_day FROM judgement.decisions WHERE org_id = $1 AND key <> $3 AND level <> 'never' AND NOT dry AND COALESCE((body->'action'->'effect'->>'ReadOnly')::boolean, false) = false`, orgID, runID, key, since) if err != nil { return 0, 0, fmt.Errorf("count actions: %w", err) } return n.Run, n.Day, nil }