From dd80500e7a8600eb2702def3ced9106a4f9bcba8 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 16 Nov 2026 10:04:44 +1100 Subject: [PATCH] feat(drafts): a draft bundles trigger, workflow and policy with a summary and a dry run, and publishes them (#2008) --- internal/app/archie/run.go | 29 +- modules/drafts/drafts.go | 483 +++++++++++++++++++++++++ modules/drafts/internal/store/store.go | 154 ++++++++ 3 files changed, 661 insertions(+), 5 deletions(-) create mode 100644 modules/drafts/drafts.go create mode 100644 modules/drafts/internal/store/store.go diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 8c62d446b..59744dae2 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -27,6 +27,7 @@ import ( "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/dashboard" "github.com/samcharles93/archie-core/modules/deliveries" + "github.com/samcharles93/archie-core/modules/drafts" "github.com/samcharles93/archie-core/modules/events" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" @@ -98,20 +99,38 @@ func Run(ctx context.Context, configPath string) error { hear := events.NewModule(db, log.With("module", "events"), orgID, conns, engine, allow, tell) hear.Routes(mux, guard) judge := newJudgement(db, log, conns, classes, policies, settings, hear) - engine.Register("investigate", 1, runs.Investigate(settings, conns, judge, allow, tell, memory.NewModule(db, orgID))) //nolint:contextcheck // see above + if err := useWorkflows(ctx, engine, runs.Deps{Settings: settings, Toolbox: conns, Judge: judge, Approver: allow, Notifier: tell, Memory: memory.NewModule(db, orgID)}); err != nil { + return err + } engine.Routes(mux, guard, orgID, hear, judge, allow) + drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies).Routes(mux, guard) dashboard.Routes(mux, ui.DistDirFS) + return serveWithWork(ctx, log, cfg.Listen, mux, engine.Work, hear.Work, tell.Work) +} + +// serveWithWork serves mux while the loops run, and stops the loops once it +// returns. +func serveWithWork(ctx context.Context, log *slog.Logger, addr string, mux *http.ServeMux, loops ...func(context.Context)) error { ctx, stop := context.WithCancel(ctx) defer stop() - wait := work(ctx, engine.Work, hear.Work, tell.Work) - - err = serve(ctx, log, cfg.Listen, mux) + wait := work(ctx, loops...) + err := serve(ctx, log, addr, mux) stop() wait() return err } +// useWorkflows gives the engine what workflow steps use and installs the +// workflow that ships with the binary. +func useWorkflows(ctx context.Context, engine *runs.Engine, deps runs.Deps) error { + engine.Use(deps) + if _, err := engine.Install(ctx, orgID, "investigate", runs.InvestigateDocument(), "starter"); err != nil { + return fmt.Errorf("install the investigate workflow: %w", err) + } + return nil +} + // work runs each loop until ctx ends and returns a function that waits for // them all. func work(ctx context.Context, loops ...func(context.Context)) func() { @@ -152,7 +171,7 @@ func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, class const orgID = "default" // schemas are the module schemas the runtime role is granted DML on. -var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory"} +var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "drafts"} // owner names this process in run leases. func owner() string { diff --git a/modules/drafts/drafts.go b/modules/drafts/drafts.go new file mode 100644 index 000000000..c8a3ccc03 --- /dev/null +++ b/modules/drafts/drafts.go @@ -0,0 +1,483 @@ +// Package drafts holds what an unmatched group of events could become: the +// trigger it proposes, the workflow that trigger would start and any policy +// that workflow needs, with a plain-language summary and a dry run. Nothing in +// a draft is in force until it is published. +package drafts + +import ( + "context" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "regexp" + "slices" + "strings" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/modules/drafts/internal/store" + "github.com/samcharles93/archie-core/modules/events" + "github.com/samcharles93/archie-core/modules/judgement" + "github.com/samcharles93/archie-core/modules/runs" +) + +// replayable is how many of a group's newest events a dry run can choose from. +const replayable = 50 + +// Groups is where a draft finds the unmatched events it is made from, and +// where its trigger is saved. +type Groups interface { + Group(ctx context.Context, id uuid.UUID) (events.Group, bool, error) + GroupEvents(ctx context.Context, id uuid.UUID, limit int) ([]events.Stored, error) + Replayed(ctx context.Context, eventID uuid.UUID, trigger string, runID uuid.UUID) error + SaveTrigger(ctx context.Context, t events.TriggerSpec) error +} + +// Workflows stores workflow documents and runs them dry. +type Workflows interface { + Install(ctx context.Context, orgID, name, body, by string) (int, error) + Has(ctx context.Context, orgID, name string) (bool, error) + StartDry(ctx context.Context, req runs.DryRequest) (uuid.UUID, error) + DryReport(ctx context.Context, orgID string, id uuid.UUID) (runs.DryReport, bool, error) +} + +// Policies checks a draft's policy against the set in force and adds it. +type Policies interface { + Check(ctx context.Context, kind, extra string) error + Append(ctx context.Context, kind, extra, by string) (judgement.PolicySetView, error) +} + +// Module holds one organisation's drafts. +type Module struct { + orgID string + store *store.Store + groups Groups + workflows Workflows + policies Policies + log *slog.Logger +} + +// NewModule returns the drafts module for orgID. +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, g Groups, w Workflows, p Policies) *Module { + return &Module{orgID: orgID, store: store.New(db), groups: g, workflows: w, policies: p, log: log} +} + +// Routes adds the draft API behind guard. +func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) { + mux.Handle("GET /api/drafts", guard(http.HandlerFunc(m.list))) + mux.Handle("POST /api/groups/{id}/draft", guard(http.HandlerFunc(m.create))) + mux.Handle("GET /api/drafts/{id}", guard(http.HandlerFunc(m.get))) + mux.Handle("PUT /api/drafts/{id}", guard(http.HandlerFunc(m.edit))) + mux.Handle("POST /api/drafts/{id}/dry-run", guard(http.HandlerFunc(m.dryRun))) + mux.Handle("POST /api/drafts/{id}/publish", guard(http.HandlerFunc(m.publish))) +} + +// View is a draft as the API returns it. +type View struct { + ID uuid.UUID `json:"id"` + GroupID uuid.UUID `json:"group_id"` + Name string `json:"name"` + Trigger Trigger `json:"trigger"` + // Workflow is the workflow document the trigger would start. + Workflow string `json:"workflow"` + PolicyKind string `json:"policy_kind"` + // Policy is Cedar policy text added to the set in force when published. + Policy string `json:"policy"` + Summary string `json:"summary"` + // DryRun is the last dry run of the draft as it stands. + DryRun *runs.DryReport `json:"dry_run,omitzero"` + DryEventID *uuid.UUID `json:"dry_event_id,omitzero"` + PublishedAt *time.Time `json:"published_at,omitzero"` +} + +// Trigger is the trigger a draft proposes. +type Trigger struct { + Source string `json:"source"` + EventType string `json:"event_type"` + Filter jsontext.Value `json:"filter"` +} + +func (m *Module) view(ctx context.Context, d store.Draft) (View, error) { + v := View{ + ID: d.ID, GroupID: d.GroupID, Name: d.Name, + Trigger: Trigger{Source: d.Source, EventType: d.EventType, Filter: d.Filter}, + Workflow: d.Document, PolicyKind: d.PolicyKind, Policy: d.Policy, + Summary: summarize(d), + } + if d.PublishedAt.Valid { + v.PublishedAt = &d.PublishedAt.Time + } + if d.DryEventID.Valid { + v.DryEventID = &d.DryEventID.UUID + } + if d.DryRunID.Valid { + rep, ok, err := m.workflows.DryReport(ctx, m.orgID, d.DryRunID.UUID) + if err != nil { + return View{}, fmt.Errorf("read dry run: %w", err) + } + if ok { + v.DryRun = &rep + } + } + return v, nil +} + +var ( + policyID = regexp.MustCompile(`@id\("([^"]+)"\)`) + nameChars = regexp.MustCompile(`[^a-z0-9]+`) + validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`) + policyKinds = map[string]string{judgement.KindHardRules: "hard rule", judgement.KindChangeRequest: "change request rule"} +) + +// summarize says in plain language when a draft fires and what it does. It is +// built from the draft's own fields, so it can't disagree with them. +func summarize(d store.Draft) string { + var filter map[string]string + _ = json.Unmarshal(d.Filter, &filter) + var b strings.Builder + fmt.Fprintf(&b, "When %s sends %s", d.Source, d.EventType) + if len(filter) > 0 { + pairs := make([]string, 0, len(filter)) + for k, v := range filter { + pairs = append(pairs, k+"="+v) + } + slices.Sort(pairs) + b.WriteString(" matching " + strings.Join(pairs, ", ")) + } + fmt.Fprintf(&b, ", Archie runs %q.", d.Name) + doc, err := runs.ParseDocument(d.Document) + if err != nil { + b.WriteString(" The workflow is not valid.") + } + for _, line := range doc.Describe() { + b.WriteString(" " + line + ".") + } + if strings.TrimSpace(d.Policy) != "" { + ids := policyID.FindAllStringSubmatch(d.Policy, -1) + names := make([]string, 0, len(ids)) + for _, id := range ids { + names = append(names, id[1]) + } + fmt.Fprintf(&b, " It adds %s policies", policyKinds[d.PolicyKind]) + if len(names) > 0 { + b.WriteString(": " + strings.Join(names, ", ")) + } + b.WriteString(".") + } + return b.String() +} + +// defaultName is a trigger name that is valid and tells groups apart. +func defaultName(g events.Group) string { + slug := strings.Trim(nameChars.ReplaceAllString(strings.ToLower(g.Source+"-"+g.EventType), "-"), "-") + if len(slug) > 50 { + slug = strings.Trim(slug[:50], "-") + } + return slug + "-" + g.ID.String()[:6] +} + +func (m *Module) list(w http.ResponseWriter, r *http.Request) { + rows, err := m.store.List(r.Context(), m.orgID) + if err != nil { + m.fail(w, r, "list drafts", err) + return + } + out := make([]View, 0, len(rows)) + for _, d := range rows { + v, err := m.view(r.Context(), d) + if err != nil { + m.fail(w, r, "read draft", err) + return + } + out = append(out, v) + } + httpjson.Write(w, http.StatusOK, out) +} + +// create makes a group's draft, or returns the one it has. A new draft +// proposes the group's trigger and a copy of the investigate workflow. +func (m *Module) create(w http.ResponseWriter, r *http.Request) { + id, ok := pathID(w, r) + if !ok { + return + } + g, found, err := m.groups.Group(r.Context(), id) + switch { + case err != nil: + m.fail(w, r, "read group", err) + return + case !found: + httpjson.Error(w, http.StatusNotFound, "no such group") + return + } + filter, err := json.Marshal(g.Filter) + if err != nil { + m.fail(w, r, "encode filter", err) + return + } + d, err := m.store.Create(r.Context(), store.Draft{ + ID: uuid.New(), OrgID: m.orgID, GroupID: g.ID, Name: defaultName(g), Source: g.Source, EventType: g.EventType, + Filter: filter, Document: runs.InvestigateDocument(), PolicyKind: judgement.KindHardRules, + }) + if err != nil { + m.fail(w, r, "create draft", err) + return + } + m.respond(w, r, d) +} + +func (m *Module) get(w http.ResponseWriter, r *http.Request) { + d, ok := m.draft(w, r) + if !ok { + return + } + m.respond(w, r, d) +} + +type editRequest struct { + Name string `json:"name"` + Workflow string `json:"workflow"` + PolicyKind string `json:"policy_kind"` + Policy string `json:"policy"` +} + +// edit replaces a draft's name, workflow and policy after checking them. What +// doesn't validate changes nothing. +func (m *Module) edit(w http.ResponseWriter, r *http.Request) { + d, ok := m.draft(w, r) + if !ok { + return + } + if d.PublishedAt.Valid { + httpjson.Error(w, http.StatusConflict, "a published draft can't be edited") + return + } + var req editRequest + if err := httpjson.Read(r, &req); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if err := m.check(r.Context(), req.Name, req.Workflow, req.PolicyKind, req.Policy); err != nil { + writeInvalid(w, err) + return + } + switch err := m.store.Edit(r.Context(), m.orgID, d.ID, req.Name, req.Workflow, req.PolicyKind, req.Policy); { + case errors.Is(err, store.ErrTaken): + httpjson.Error(w, http.StatusConflict, "another draft has that name") + return + case err != nil: + m.fail(w, r, "edit draft", err) + return + } + d, err := m.store.ByID(r.Context(), m.orgID, d.ID) + if err != nil { + m.fail(w, r, "read draft", err) + return + } + m.respond(w, r, d) +} + +// check validates what a draft would put in force. +func (m *Module) check(ctx context.Context, name, document, policyKind, policy string) error { + if !validName.MatchString(name) { + return &runs.InvalidError{Problems: []runs.Problem{{Path: "name", Message: "lowercase letters, digits and hyphens, starting with a letter"}}} + } + if _, err := runs.ParseDocument(document); err != nil { + return err + } + if _, ok := policyKinds[policyKind]; !ok { + return &runs.InvalidError{Problems: []runs.Problem{{Path: "policy_kind", Message: "hard_rules or change_request"}}} + } + if strings.TrimSpace(policy) == "" { + return nil + } + return m.policies.Check(ctx, policyKind, policy) +} + +func writeInvalid(w http.ResponseWriter, err error) { + var invalid *runs.InvalidError + switch { + case errors.As(err, &invalid): + httpjson.Write(w, http.StatusBadRequest, map[string]any{"error": invalid.Error(), "problems": invalid.Problems}) + case errors.Is(err, judgement.ErrInvalidPolicy): + httpjson.Write(w, http.StatusBadRequest, map[string]any{ + "error": err.Error(), "problems": []runs.Problem{{Path: "policy", Message: err.Error()}}, + }) + default: + httpjson.Error(w, http.StatusInternalServerError, "couldn't check the draft") + } +} + +type dryRunRequest struct { + EventID uuid.UUID `json:"event_id"` +} + +// dryRun replays one of the group's stored events through the draft's workflow +// in dry mode: the newest by default. +func (m *Module) dryRun(w http.ResponseWriter, r *http.Request) { + d, ok := m.draft(w, r) + if !ok { + return + } + var req dryRunRequest + if err := httpjson.Read(r, &req); err != nil && !errors.Is(err, io.EOF) { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if err := m.check(r.Context(), d.Name, d.Document, d.PolicyKind, d.Policy); err != nil { + writeInvalid(w, err) + return + } + stored, err := m.groups.GroupEvents(r.Context(), d.GroupID, replayable) + if err != nil { + m.fail(w, r, "read the group's events", err) + return + } + event, found := pick(stored, req.EventID) + if !found { + httpjson.Error(w, http.StatusConflict, "the group has no stored event to replay") + return + } + runID, err := m.workflows.StartDry(r.Context(), runs.DryRequest{ + OrgID: m.orgID, Workflow: d.Name, Document: d.Document, PolicyKind: d.PolicyKind, Policy: d.Policy, Input: event.Input, + }) + if err != nil { + m.fail(w, r, "start the dry run", err) + return + } + if err := m.groups.Replayed(r.Context(), event.ID, d.Name, runID); err != nil { + m.fail(w, r, "record the replay", err) + return + } + if err := m.store.SetDryRun(r.Context(), m.orgID, d.ID, runID, event.ID); err != nil { + m.fail(w, r, "record the dry run", err) + return + } + d, err = m.store.ByID(r.Context(), m.orgID, d.ID) + if err != nil { + m.fail(w, r, "read draft", err) + return + } + m.respond(w, r, d) +} + +// pick returns the event asked for, or the newest when none is. +func pick(stored []events.Stored, id uuid.UUID) (events.Stored, bool) { + for _, e := range stored { + if id == uuid.Nil || e.ID == id { + return e, true + } + } + return events.Stored{}, false +} + +// publish puts a draft in force: its policy is added to the set, its workflow +// is installed as the next version, and last its trigger is saved, so nothing +// fires before the rules that govern it exist. A retry after a failure carries +// on from where it stopped. +func (m *Module) publish(w http.ResponseWriter, r *http.Request) { + d, ok := m.draft(w, r) + if !ok { + return + } + ctx := r.Context() + if err := m.check(ctx, d.Name, d.Document, d.PolicyKind, d.Policy); err != nil { + writeInvalid(w, err) + return + } + if !d.InstalledVersion.Valid { + taken, err := m.workflows.Has(ctx, m.orgID, d.Name) + if err != nil { + m.fail(w, r, "check the workflow name", err) + return + } + if taken { + httpjson.Error(w, http.StatusConflict, "a workflow named "+d.Name+" already exists; rename the draft") + return + } + } + by := "draft:" + d.Name + if strings.TrimSpace(d.Policy) != "" { + if _, err := m.policies.Append(ctx, d.PolicyKind, d.Policy, by); err != nil { + m.fail(w, r, "add the policy", err) + return + } + } + version, err := m.workflows.Install(ctx, m.orgID, d.Name, d.Document, by) + if err != nil { + m.fail(w, r, "install the workflow", err) + return + } + if err := m.store.MarkInstalled(ctx, m.orgID, d.ID, version); err != nil { + m.fail(w, r, "record the workflow version", err) + return + } + var filter map[string]string + if err := json.Unmarshal(d.Filter, &filter); err != nil { + m.fail(w, r, "read the trigger filter", err) + return + } + if err := m.groups.SaveTrigger(ctx, events.TriggerSpec{ + Name: d.Name, Source: d.Source, EventType: d.EventType, Filter: filter, Workflow: d.Name, + }); err != nil { + m.fail(w, r, "save the trigger", err) + return + } + if err := m.store.MarkPublished(ctx, m.orgID, d.ID); err != nil { + m.fail(w, r, "mark the draft published", err) + return + } + d, err = m.store.ByID(ctx, m.orgID, d.ID) + if err != nil { + m.fail(w, r, "read draft", err) + return + } + m.respond(w, r, d) +} + +func (m *Module) draft(w http.ResponseWriter, r *http.Request) (store.Draft, bool) { + id, ok := pathID(w, r) + if !ok { + return store.Draft{}, false + } + d, err := m.store.ByID(r.Context(), m.orgID, id) + switch { + case errors.Is(err, store.ErrNotFound): + httpjson.Error(w, http.StatusNotFound, "no such draft") + return store.Draft{}, false + case err != nil: + m.fail(w, r, "read draft", err) + return store.Draft{}, false + } + return d, true +} + +func (m *Module) respond(w http.ResponseWriter, r *http.Request, d store.Draft) { + v, err := m.view(r.Context(), d) + if err != nil { + m.fail(w, r, "read draft", err) + return + } + httpjson.Write(w, http.StatusOK, v) +} + +func (m *Module) fail(w http.ResponseWriter, r *http.Request, what string, err error) { + m.log.ErrorContext(r.Context(), what, "error", err) + httpjson.Error(w, http.StatusInternalServerError, "couldn't "+what) +} + +func pathID(w http.ResponseWriter, r *http.Request) (uuid.UUID, bool) { + id, err := uuid.Parse(r.PathValue("id")) + if err != nil { + httpjson.Error(w, http.StatusBadRequest, "an id is a UUID") + return uuid.Nil, false + } + return id, true +} diff --git a/modules/drafts/internal/store/store.go b/modules/drafts/internal/store/store.go new file mode 100644 index 000000000..cd4249d41 --- /dev/null +++ b/modules/drafts/internal/store/store.go @@ -0,0 +1,154 @@ +// Package store holds the drafts module's SQL. +package store + +import ( + "context" + "database/sql" + "encoding/json/jsontext" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jmoiron/sqlx" +) + +// ErrNotFound means no such draft. +var ErrNotFound = errors.New("no such draft") + +// ErrTaken means another draft already has that name or that group. +var ErrTaken = errors.New("name already used by another draft") + +// Draft is one stored draft. +type Draft struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + GroupID uuid.UUID `db:"group_id"` + Name string `db:"name"` + Source string `db:"source"` + EventType string `db:"event_type"` + Filter jsontext.Value `db:"filter"` + Document string `db:"document"` + PolicyKind string `db:"policy_kind"` + Policy string `db:"policy"` + DryRunID uuid.NullUUID `db:"dry_run_id"` + DryEventID uuid.NullUUID `db:"dry_event_id"` + // InstalledVersion is the workflow version a publish installed, once one did. + InstalledVersion sql.NullInt32 `db:"installed_version"` + PublishedAt sql.NullTime `db:"published_at"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` +} + +const columns = `id, org_id, group_id, name, source, event_type, filter, document, policy_kind, policy, + dry_run_id, dry_event_id, installed_version, published_at, created_at, updated_at` + +// Store is the drafts 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 stores d unless its group already has a draft, and returns the draft +// the group has. +func (s *Store) Create(ctx context.Context, d Draft) (Draft, error) { + _, err := s.db.ExecContext(ctx, ` + INSERT INTO drafts.drafts (id, org_id, group_id, name, source, event_type, filter, document, policy_kind, policy) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (org_id, group_id) DO NOTHING`, + d.ID, d.OrgID, d.GroupID, d.Name, d.Source, d.EventType, d.Filter, d.Document, d.PolicyKind, d.Policy) + if err != nil { + return Draft{}, fmt.Errorf("create draft: %w", err) + } + return s.ByGroup(ctx, d.OrgID, d.GroupID) +} + +// ByGroup returns a group's draft. +func (s *Store) ByGroup(ctx context.Context, orgID string, groupID uuid.UUID) (Draft, error) { + return s.one(ctx, `WHERE org_id = $1 AND group_id = $2`, orgID, groupID) +} + +// ByID returns one draft. +func (s *Store) ByID(ctx context.Context, orgID string, id uuid.UUID) (Draft, error) { + return s.one(ctx, `WHERE org_id = $1 AND id = $2`, orgID, id) +} + +func (s *Store) one(ctx context.Context, where string, args ...any) (Draft, error) { + var d Draft + err := s.db.GetContext(ctx, &d, `SELECT `+columns+` FROM drafts.drafts `+where, args...) + if errors.Is(err, sql.ErrNoRows) { + return Draft{}, ErrNotFound + } + if err != nil { + return Draft{}, fmt.Errorf("read draft: %w", err) + } + return d, nil +} + +// List returns an organisation's drafts, newest first. +func (s *Store) List(ctx context.Context, orgID string) ([]Draft, error) { + var out []Draft + if err := s.db.SelectContext(ctx, &out, ` + SELECT `+columns+` FROM drafts.drafts WHERE org_id = $1 ORDER BY created_at DESC LIMIT 200`, orgID); err != nil { + return nil, fmt.Errorf("list drafts: %w", err) + } + return out, nil +} + +// Edit replaces what a person edits of an unpublished draft. A dry run made of +// an earlier version no longer describes it, so it is cleared. +func (s *Store) Edit(ctx context.Context, orgID string, id uuid.UUID, name, document, policyKind, policy string) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE drafts.drafts + SET name = $3, document = $4, policy_kind = $5, policy = $6, + dry_run_id = NULL, dry_event_id = NULL, updated_at = now() + WHERE org_id = $1 AND id = $2 AND published_at IS NULL`, orgID, id, name, document, policyKind, policy) + if err != nil { + if isUnique(err) { + return ErrTaken + } + return fmt.Errorf("edit draft: %w", err) + } + if n, _ := res.RowsAffected(); n == 0 { + return ErrNotFound + } + return nil +} + +// SetDryRun records the dry run last made of a draft and the event it replayed. +func (s *Store) SetDryRun(ctx context.Context, orgID string, id, runID, eventID uuid.UUID) error { + if _, err := s.db.ExecContext(ctx, ` + UPDATE drafts.drafts SET dry_run_id = $3, dry_event_id = $4, updated_at = now() + WHERE org_id = $1 AND id = $2`, orgID, id, runID, eventID); err != nil { + return fmt.Errorf("record dry run: %w", err) + } + return nil +} + +// MarkInstalled records the workflow version a publish installed. +func (s *Store) MarkInstalled(ctx context.Context, orgID string, id uuid.UUID, version int) error { + if _, err := s.db.ExecContext(ctx, ` + UPDATE drafts.drafts SET installed_version = $3, updated_at = now() WHERE org_id = $1 AND id = $2`, + orgID, id, version); err != nil { + return fmt.Errorf("record installed version: %w", err) + } + return nil +} + +// MarkPublished records that a draft is in force. +func (s *Store) MarkPublished(ctx context.Context, orgID string, id uuid.UUID) error { + if _, err := s.db.ExecContext(ctx, ` + UPDATE drafts.drafts SET published_at = COALESCE(published_at, now()), updated_at = now() + WHERE org_id = $1 AND id = $2`, orgID, id); err != nil { + return fmt.Errorf("mark draft published: %w", err) + } + return nil +} + +func isUnique(err error) bool { + var pgerr *pgconn.PgError + return errors.As(err, &pgerr) && pgerr.Code == "23505" +}