feat(httpapi): the API is described by an OpenAPI document generated with Huma (#2028)
Every /api operation is registered with Huma behind one admin-token middleware, served at /api/openapi.json with a docs page at /api/docs, and committed as api/openapi.yaml, which task check keeps current.
This commit is contained in:
32 files changed
+4467
-1105
No files matched your search
+147
-162
@@ -10,7 +10,6 @@ import (
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
@@ -18,10 +17,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/drafts/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/events"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
@@ -69,14 +69,37 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, g Groups, w Workflow
|
||||
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)))
|
||||
// Register adds the draft API.
|
||||
func (m *Module) Register(api huma.API) {
|
||||
tags := []string{"Drafts"}
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "list-drafts", Method: http.MethodGet, Path: "/api/drafts",
|
||||
Summary: "List drafts", Tags: tags,
|
||||
}, m.list)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "draft-group", Method: http.MethodPost, Path: "/api/groups/{id}/draft",
|
||||
Summary: "Draft a trigger and workflow for a group of unmatched events", Tags: tags,
|
||||
}, m.create)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-draft", Method: http.MethodGet, Path: "/api/drafts/{id}",
|
||||
Summary: "Get a draft", Tags: tags,
|
||||
}, m.get)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "edit-draft", Method: http.MethodPut, Path: "/api/drafts/{id}",
|
||||
Summary: "Change a draft's name, workflow and policy", Tags: tags,
|
||||
}, m.edit)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "dry-run-draft", Method: http.MethodPost, Path: "/api/drafts/{id}/dry-run",
|
||||
Summary: "Replay one of the group's events through the draft, changing nothing", Tags: tags,
|
||||
}, m.dryRun)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "publish-draft", Method: http.MethodPost, Path: "/api/drafts/{id}/publish",
|
||||
Summary: "Install the draft's workflow, policy and trigger", Tags: tags,
|
||||
}, m.publish)
|
||||
}
|
||||
|
||||
type idInput struct {
|
||||
ID string `path:"id" format:"uuid"`
|
||||
}
|
||||
|
||||
// View is a draft as the API returns it.
|
||||
@@ -183,105 +206,93 @@ func defaultName(g events.Group) string {
|
||||
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)
|
||||
func (m *Module) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]View], error) {
|
||||
rows, err := m.store.List(ctx, m.orgID)
|
||||
if err != nil {
|
||||
m.fail(w, r, "list drafts", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "list drafts", err)
|
||||
}
|
||||
out := make([]View, 0, len(rows))
|
||||
for _, d := range rows {
|
||||
v, err := m.view(r.Context(), d)
|
||||
v, err := m.view(ctx, d)
|
||||
if err != nil {
|
||||
m.fail(w, r, "read draft", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "read draft", err)
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, out)
|
||||
return httpapi.OK(out), nil
|
||||
}
|
||||
|
||||
// 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
|
||||
func (m *Module) create(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) {
|
||||
id, err := uuid.Parse(in.ID)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("an id is a UUID")
|
||||
}
|
||||
g, found, err := m.groups.Group(r.Context(), id)
|
||||
g, found, err := m.groups.Group(ctx, id)
|
||||
switch {
|
||||
case err != nil:
|
||||
m.fail(w, r, "read group", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "read group", err)
|
||||
case !found:
|
||||
httpjson.Error(w, http.StatusNotFound, "no such group")
|
||||
return
|
||||
return nil, huma.Error404NotFound("no such group")
|
||||
}
|
||||
filter, err := json.Marshal(g.Filter)
|
||||
if err != nil {
|
||||
m.fail(w, r, "encode filter", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "encode filter", err)
|
||||
}
|
||||
d, err := m.store.Create(r.Context(), store.Draft{
|
||||
d, err := m.store.Create(ctx, 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
|
||||
return nil, m.fail(ctx, "create draft", err)
|
||||
}
|
||||
m.respond(w, r, d)
|
||||
return m.respond(ctx, d)
|
||||
}
|
||||
|
||||
func (m *Module) get(w http.ResponseWriter, r *http.Request) {
|
||||
d, ok := m.draft(w, r)
|
||||
if !ok {
|
||||
return
|
||||
func (m *Module) get(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) {
|
||||
d, err := m.draft(ctx, in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.respond(w, r, d)
|
||||
return m.respond(ctx, d)
|
||||
}
|
||||
|
||||
type editRequest struct {
|
||||
Name string `json:"name"`
|
||||
Workflow string `json:"workflow"`
|
||||
PolicyKind string `json:"policy_kind"`
|
||||
Policy string `json:"policy"`
|
||||
type editInput struct {
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body struct {
|
||||
Name string `json:"name"`
|
||||
Workflow string `json:"workflow" doc:"The workflow document"`
|
||||
PolicyKind string `json:"policy_kind" enum:"hard_rules,change_request"`
|
||||
Policy string `json:"policy,omitzero" doc:"Cedar policy text added when the draft is published"`
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
func (m *Module) edit(ctx context.Context, in *editInput) (*httpapi.Reply[View], error) {
|
||||
d, err := m.draft(ctx, in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.PublishedAt.Valid {
|
||||
httpjson.Error(w, http.StatusConflict, "a published draft can't be edited")
|
||||
return
|
||||
return nil, huma.Error409Conflict("a published draft can't be edited")
|
||||
}
|
||||
var req editRequest
|
||||
if err := httpjson.Read(r, &req); err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
req := in.Body
|
||||
if err := m.check(ctx, req.Name, req.Workflow, req.PolicyKind, req.Policy); err != nil {
|
||||
return nil, invalid(err)
|
||||
}
|
||||
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); {
|
||||
switch err := m.store.Edit(ctx, 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
|
||||
return nil, huma.Error409Conflict("another draft has that name")
|
||||
case err != nil:
|
||||
m.fail(w, r, "edit draft", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "edit draft", err)
|
||||
}
|
||||
d, err := m.store.ByID(r.Context(), m.orgID, d.ID)
|
||||
d, err = m.store.ByID(ctx, m.orgID, d.ID)
|
||||
if err != nil {
|
||||
m.fail(w, r, "read draft", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "read draft", err)
|
||||
}
|
||||
m.respond(w, r, d)
|
||||
return m.respond(ctx, d)
|
||||
}
|
||||
|
||||
// check validates what a draft would put in force.
|
||||
@@ -301,71 +312,68 @@ func (m *Module) check(ctx context.Context, name, document, policyKind, policy s
|
||||
return m.policies.Check(ctx, policyKind, policy)
|
||||
}
|
||||
|
||||
func writeInvalid(w http.ResponseWriter, err error) {
|
||||
var invalid *runs.InvalidError
|
||||
func invalid(err error) error {
|
||||
var problem *runs.InvalidError
|
||||
switch {
|
||||
case errors.As(err, &invalid):
|
||||
httpjson.Write(w, http.StatusBadRequest, map[string]any{"error": invalid.Error(), "problems": invalid.Problems})
|
||||
case errors.As(err, &problem):
|
||||
details := make([]error, 0, len(problem.Problems))
|
||||
for _, p := range problem.Problems {
|
||||
details = append(details, &huma.ErrorDetail{Location: p.Path, Message: p.Message})
|
||||
}
|
||||
return huma.Error400BadRequest(problem.Error(), details...)
|
||||
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()}},
|
||||
})
|
||||
return huma.Error400BadRequest(err.Error(), &huma.ErrorDetail{Location: "policy", Message: err.Error()})
|
||||
default:
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't check the draft")
|
||||
return huma.Error500InternalServerError("couldn't check the draft")
|
||||
}
|
||||
}
|
||||
|
||||
type dryRunRequest struct {
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
type dryRunInput struct {
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body *struct {
|
||||
EventID uuid.UUID `json:"event_id,omitzero" doc:"The stored event to replay; the newest by default"`
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
func (m *Module) dryRun(ctx context.Context, in *dryRunInput) (*httpapi.Reply[View], error) {
|
||||
d, err := m.draft(ctx, in.ID)
|
||||
if err != nil {
|
||||
m.fail(w, r, "read the group's events", err)
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
event, found := pick(stored, req.EventID)
|
||||
var eventID uuid.UUID
|
||||
if in.Body != nil {
|
||||
eventID = in.Body.EventID
|
||||
}
|
||||
if err := m.check(ctx, d.Name, d.Document, d.PolicyKind, d.Policy); err != nil {
|
||||
return nil, invalid(err)
|
||||
}
|
||||
stored, err := m.groups.GroupEvents(ctx, d.GroupID, replayable)
|
||||
if err != nil {
|
||||
return nil, m.fail(ctx, "read the group's events", err)
|
||||
}
|
||||
event, found := pick(stored, eventID)
|
||||
if !found {
|
||||
httpjson.Error(w, http.StatusConflict, "the group has no stored event to replay")
|
||||
return
|
||||
return nil, huma.Error409Conflict("the group has no stored event to replay")
|
||||
}
|
||||
runID, err := m.workflows.StartDry(r.Context(), runs.DryRequest{
|
||||
runID, err := m.workflows.StartDry(ctx, 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
|
||||
return nil, m.fail(ctx, "start the dry run", err)
|
||||
}
|
||||
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.groups.Replayed(ctx, event.ID, d.Name, runID); err != nil {
|
||||
return nil, m.fail(ctx, "record the replay", err)
|
||||
}
|
||||
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
|
||||
if err := m.store.SetDryRun(ctx, m.orgID, d.ID, runID, event.ID); err != nil {
|
||||
return nil, m.fail(ctx, "record the dry run", err)
|
||||
}
|
||||
d, err = m.store.ByID(r.Context(), m.orgID, d.ID)
|
||||
d, err = m.store.ByID(ctx, m.orgID, d.ID)
|
||||
if err != nil {
|
||||
m.fail(w, r, "read draft", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "read draft", err)
|
||||
}
|
||||
m.respond(w, r, d)
|
||||
return m.respond(ctx, d)
|
||||
}
|
||||
|
||||
// pick returns the event asked for, or the newest when none is.
|
||||
@@ -382,102 +390,79 @@ func pick(stored []events.Stored, id uuid.UUID) (events.Stored, bool) {
|
||||
// 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
|
||||
func (m *Module) publish(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) {
|
||||
d, err := m.draft(ctx, in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx := r.Context()
|
||||
if err := m.check(ctx, d.Name, d.Document, d.PolicyKind, d.Policy); err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
return nil, invalid(err)
|
||||
}
|
||||
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
|
||||
return nil, m.fail(ctx, "check the workflow name", err)
|
||||
}
|
||||
if taken {
|
||||
httpjson.Error(w, http.StatusConflict, "a workflow named "+d.Name+" already exists; rename the draft")
|
||||
return
|
||||
return nil, huma.Error409Conflict("a workflow named " + d.Name + " already exists; rename the draft")
|
||||
}
|
||||
}
|
||||
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
|
||||
return nil, m.fail(ctx, "add the policy", err)
|
||||
}
|
||||
}
|
||||
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
|
||||
return nil, m.fail(ctx, "install the workflow", err)
|
||||
}
|
||||
if err := m.store.MarkInstalled(ctx, m.orgID, d.ID, version); err != nil {
|
||||
m.fail(w, r, "record the workflow version", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "record the workflow version", err)
|
||||
}
|
||||
var filter map[string]string
|
||||
if err := json.Unmarshal(d.Filter, &filter); err != nil {
|
||||
m.fail(w, r, "read the trigger filter", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "read the trigger filter", err)
|
||||
}
|
||||
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
|
||||
return nil, m.fail(ctx, "save the trigger", err)
|
||||
}
|
||||
if err := m.store.MarkPublished(ctx, m.orgID, d.ID); err != nil {
|
||||
m.fail(w, r, "mark the draft published", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "mark the draft published", err)
|
||||
}
|
||||
d, err = m.store.ByID(ctx, m.orgID, d.ID)
|
||||
if err != nil {
|
||||
m.fail(w, r, "read draft", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "read draft", err)
|
||||
}
|
||||
m.respond(w, r, d)
|
||||
return m.respond(ctx, 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
|
||||
func (m *Module) draft(ctx context.Context, rawID string) (store.Draft, error) {
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
return store.Draft{}, huma.Error400BadRequest("an id is a UUID")
|
||||
}
|
||||
d, err := m.store.ByID(r.Context(), m.orgID, id)
|
||||
d, err := m.store.ByID(ctx, m.orgID, id)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
httpjson.Error(w, http.StatusNotFound, "no such draft")
|
||||
return store.Draft{}, false
|
||||
return store.Draft{}, huma.Error404NotFound("no such draft")
|
||||
case err != nil:
|
||||
m.fail(w, r, "read draft", err)
|
||||
return store.Draft{}, false
|
||||
return store.Draft{}, m.fail(ctx, "read draft", err)
|
||||
}
|
||||
return d, true
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (m *Module) respond(w http.ResponseWriter, r *http.Request, d store.Draft) {
|
||||
v, err := m.view(r.Context(), d)
|
||||
func (m *Module) respond(ctx context.Context, d store.Draft) (*httpapi.Reply[View], error) {
|
||||
v, err := m.view(ctx, d)
|
||||
if err != nil {
|
||||
m.fail(w, r, "read draft", err)
|
||||
return
|
||||
return nil, m.fail(ctx, "read draft", err)
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, v)
|
||||
return httpapi.OK(v), nil
|
||||
}
|
||||
|
||||
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
|
||||
func (m *Module) fail(ctx context.Context, what string, err error) error {
|
||||
m.log.ErrorContext(ctx, what, "error", err)
|
||||
return huma.Error500InternalServerError("couldn't " + what)
|
||||
}
|
||||
Reference in new issue
Block a user