diff --git a/api/openapi.yaml b/api/openapi.yaml index 1a20ddaa0..fe29411d1 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -5215,6 +5215,32 @@ paths: summary: Get a run's decision trail tags: - Runs + /api/runs/{id}/cancel: + post: + operationId: cancel-run + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/RunsRunView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Cancel a run and the runs it started with workflow.call + tags: + - Runs /api/runs/{id}/retry: post: operationId: retry-run diff --git a/modules/runs/internal/store/store.go b/modules/runs/internal/store/store.go index 60cf8be07..ce819094e 100644 --- a/modules/runs/internal/store/store.go +++ b/modules/runs/internal/store/store.go @@ -54,6 +54,8 @@ var ( ErrNotParked = errors.New("run is not parked") // ErrNoStep means the run never reached the step it was to retry from. ErrNoStep = errors.New("run did not reach that step") + // ErrEnded means the run has already ended, so there is nothing to cancel. + ErrEnded = errors.New("run has already ended") ) // Run is a claimed run. @@ -429,15 +431,27 @@ const cancelDepth = 5 // Cancel asks a run, and every run it started through workflow.call, to stop. // A run not currently held ends at once; a held one sees the request at its -// next step and its worker ends it. Runs that have already ended are left -// alone. Only the named run tells its own caller: the descendants' callers are -// being cancelled in the same transaction. -func (s *Store) Cancel(ctx context.Context, id uuid.UUID) error { +// next step and its worker ends it. The named run must belong to the +// organisation and must not have ended: ending is a terminal state, so there +// is nothing left to cancel. Already-ended descendants are left alone. Only +// the named run tells its own caller: the descendants' callers are being +// cancelled in the same transaction. +func (s *Store) Cancel(ctx context.Context, orgID string, id uuid.UUID) error { tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return fmt.Errorf("cancel run: %w", err) } defer func() { _ = tx.Rollback() }() + var state string + err = tx.GetContext(ctx, &state, `SELECT state FROM runs.runs WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id) + switch { + case errors.Is(err, sql.ErrNoRows): + return ErrNoRun + case err != nil: + return fmt.Errorf("cancel run: %w", err) + case state == StateSucceeded || state == StateFailed || state == StateCancelled || state == StateDeclined: + return ErrEnded + } if _, err := tx.ExecContext(ctx, ` WITH RECURSIVE tree(id, depth) AS ( SELECT id, 0 FROM runs.runs WHERE id = $1 diff --git a/modules/runs/runs.go b/modules/runs/runs.go index afb89f546..3b2a047f1 100644 --- a/modules/runs/runs.go +++ b/modules/runs/runs.go @@ -261,9 +261,17 @@ func (e *Engine) Signal(ctx context.Context, id uuid.UUID, key string, payload j return e.db.Signal(ctx, id, key, payload) } -// Cancel asks a run to stop. -func (e *Engine) Cancel(ctx context.Context, id uuid.UUID) error { - return e.db.Cancel(ctx, id) +// ErrEnded is returned by Cancel for a run that has already ended. +var ErrEnded = errors.New("run has already ended") + +// Cancel asks a run to stop, along with every run it started through +// workflow.call. A run that has already ended is refused. +func (e *Engine) Cancel(ctx context.Context, orgID string, id uuid.UUID) error { + err := e.db.Cancel(ctx, orgID, id) + if errors.Is(err, store.ErrEnded) { + return fmt.Errorf("%w: %w", ErrEnded, err) + } + return err } // ErrNotRetryable is returned by Retry for a run that is not parked, or that diff --git a/modules/runs/trail.go b/modules/runs/trail.go index 3773dc5db..76f2dcbc7 100644 --- a/modules/runs/trail.go +++ b/modules/runs/trail.go @@ -151,6 +151,10 @@ func (e *Engine) Register(api huma.API, orgID string, origins Origins, decisions OperationID: "retry-run", Method: http.MethodPost, Path: "/api/runs/{id}/retry", Summary: "Retry a parked run from a step, keeping the results of the steps before it", Tags: tags, }, a.retry) + huma.Register(api, huma.Operation{ + OperationID: "cancel-run", Method: http.MethodPost, Path: "/api/runs/{id}/cancel", + Summary: "Cancel a run and the runs it started with workflow.call", Tags: tags, + }, a.cancel) e.registerWorkflows(api, orgID) } @@ -181,6 +185,30 @@ func (a *runAPI) retry(ctx context.Context, in *retryRunInput) (*httpapi.Reply[R return httpapi.OK(view(d.Summary, d.Result)), nil } +type cancelRunInput struct { + ID string `path:"id" format:"uuid"` +} + +func (a *runAPI) cancel(ctx context.Context, in *cancelRunInput) (*httpapi.Reply[RunView], error) { + id, err := uuid.Parse(in.ID) + if err != nil { + return nil, huma.NewError(http.StatusBadRequest, "a run id is a UUID") + } + switch err := a.engine.Cancel(ctx, a.orgID, id); { + case errors.Is(err, store.ErrNoRun): + return nil, huma.NewError(http.StatusNotFound, "no such run") + case errors.Is(err, ErrEnded): + return nil, huma.NewError(http.StatusConflict, "the run has already ended, so there is nothing to cancel") + case err != nil: + return nil, huma.NewError(http.StatusInternalServerError, "couldn't cancel the run") + } + d, ok, err := a.db.Detail(ctx, a.orgID, id) + if err != nil || !ok { + return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the run") + } + return httpapi.OK(view(d.Summary, d.Result)), nil +} + type recentRunsInput struct { Limit int `query:"limit" minimum:"1" maximum:"200" default:"50"` } diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 2df7a47d2..f577f9cf7 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -190,6 +190,8 @@ export const api = { /** Queues a parked run again from the step that parked it, or from `from`. */ retryRun: (id: string, from?: string) => request(`/api/runs/${encodeURIComponent(id)}/retry`, { method: "POST", body: from ? { from } : {} }), + /** Asks a run that has not ended to stop, along with the runs it called. */ + cancelRun: (id: string) => request(`/api/runs/${encodeURIComponent(id)}/cancel`, { method: "POST", body: {} }), approvals: () => request("/api/approvals"), answerApproval: (id: string, approved: boolean) => request(`/api/approvals/${encodeURIComponent(id)}/answer`, { method: "POST", body: { approved } }), diff --git a/ui/src/runs/RunPage.vue b/ui/src/runs/RunPage.vue index 742add8a6..cdcb6b672 100644 --- a/ui/src/runs/RunPage.vue +++ b/ui/src/runs/RunPage.vue @@ -17,7 +17,7 @@ import { api, describeError, type RunAction } from "@/lib/api"; import { usePoll, useRead } from "@/lib/use-read"; import { useLiveResource } from "@/stores/session"; import ApprovalsSection from "./ApprovalsSection.vue"; -import { stateTone } from "./state"; +import { ended, stateTone } from "./state"; /** A run's decision trail: where it came from, each action it asked to take * and how that was judged, and the steps it recorded. */ @@ -27,6 +27,7 @@ const { data, error, reload } = useRead(() => api.run(id)); onMounted(reload); useLiveResource(null, () => void reload()); const finished = computed(() => !!data.value?.run.finished_at); +const cancellable = computed(() => (data.value ? !ended(data.value.run.state) : false)); usePoll(() => { if (!finished.value) void reload(); }); @@ -56,6 +57,20 @@ async function retry(): Promise { retrying.value = false; } } +const cancelling = ref(false); +const cancelError = ref(""); +async function cancel(): Promise { + cancelling.value = true; + cancelError.value = ""; + try { + await api.cancelRun(id); + await reload(); + } catch (cause) { + cancelError.value = describeError(cause, errors.common.unknown); + } finally { + cancelling.value = false; + } +} const origin = computed(() => { const o = data.value?.origin; if (!o) return []; @@ -82,11 +97,13 @@ const result = computed(() => {{ data.run.state }} Started +