77 lines
2.5 KiB
Go
77 lines
2.5 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// ErrNoPolicySet means no version of that policy set exists.
|
|
var ErrNoPolicySet = errors.New("no such policy set")
|
|
|
|
// PolicySet is one version of an organisation's policy set of one kind.
|
|
type PolicySet struct {
|
|
ID uuid.UUID `db:"id"`
|
|
OrgID string `db:"org_id"`
|
|
Kind string `db:"kind"`
|
|
Version int `db:"version"`
|
|
Body string `db:"body"`
|
|
CreatedBy string `db:"created_by"`
|
|
CreatedAt time.Time `db:"created_at"`
|
|
}
|
|
|
|
const policyColumns = `id, org_id, kind, version, body, created_by, created_at`
|
|
|
|
// Policy returns a version of a policy set, or the one in force when version
|
|
// is zero.
|
|
func (s *Store) Policy(ctx context.Context, orgID, kind string, version int) (PolicySet, error) {
|
|
var out PolicySet
|
|
query := `SELECT ` + policyColumns + ` FROM judgement.policy_sets WHERE org_id = $1 AND kind = $2`
|
|
args := []any{orgID, kind}
|
|
if version > 0 {
|
|
query += ` AND version = $3`
|
|
args = append(args, version)
|
|
} else {
|
|
query += ` ORDER BY version DESC LIMIT 1`
|
|
}
|
|
err := s.db.GetContext(ctx, &out, query, args...)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return PolicySet{}, ErrNoPolicySet
|
|
}
|
|
if err != nil {
|
|
return PolicySet{}, fmt.Errorf("read policy set: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// PolicyVersions returns every version of a policy set, newest first, without
|
|
// their bodies.
|
|
func (s *Store) PolicyVersions(ctx context.Context, orgID, kind string) ([]PolicySet, error) {
|
|
var out []PolicySet
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT id, org_id, kind, version, '' AS body, created_by, created_at
|
|
FROM judgement.policy_sets WHERE org_id = $1 AND kind = $2 ORDER BY version DESC`, orgID, kind); err != nil {
|
|
return nil, fmt.Errorf("list policy versions: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// AddPolicy stores body as the next version of the kind's policy set. Two
|
|
// writers racing for one version make the second fail on the unique key.
|
|
func (s *Store) AddPolicy(ctx context.Context, p PolicySet) (PolicySet, error) {
|
|
var out PolicySet
|
|
err := s.db.GetContext(ctx, &out, `
|
|
INSERT INTO judgement.policy_sets (id, org_id, kind, version, body, created_by)
|
|
SELECT $1, $2, $3, coalesce(max(version), 0) + 1, $4, $5
|
|
FROM judgement.policy_sets WHERE org_id = $2 AND kind = $3
|
|
RETURNING `+policyColumns, p.ID, p.OrgID, p.Kind, p.Body, p.CreatedBy)
|
|
if err != nil {
|
|
return PolicySet{}, fmt.Errorf("add policy set: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|