fix(runs): cancel a run from the API and the dashboard (#2088)
POST /api/runs/{id}/cancel now reaches Engine.Cancel, which cancels the
run and the runs it started with workflow.call, and returns the run.
Cancelling a run that has already ended is refused with a 409, and a run
from another organisation is not found. The run page shows a Cancel
action for a run that has not ended.
This commit is contained in:
7 files changed
+116
-8
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+11
-3
@@ -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
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
|
||||
@@ -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<Run>(`/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<Run>(`/api/runs/${encodeURIComponent(id)}/cancel`, { method: "POST", body: {} }),
|
||||
approvals: () => request<Approval[]>("/api/approvals"),
|
||||
answerApproval: (id: string, approved: boolean) =>
|
||||
request<Approval>(`/api/approvals/${encodeURIComponent(id)}/answer`, { method: "POST", body: { approved } }),
|
||||
|
||||
+18
-1
@@ -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<void> {
|
||||
retrying.value = false;
|
||||
}
|
||||
}
|
||||
const cancelling = ref(false);
|
||||
const cancelError = ref("");
|
||||
async function cancel(): Promise<void> {
|
||||
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(() =>
|
||||
<Badge v-if="data" :variant="stateTone(data.run.state)">{{ data.run.state }}</Badge>
|
||||
<span v-if="data" class="text-caption text-fg-muted">Started <Timestamp :at="data.run.created_at" /></span>
|
||||
<Button v-if="data?.run.state === 'parked'" size="sm" :disabled="retrying" @click="retry">Retry</Button>
|
||||
<Button v-if="cancellable" variant="destructive" size="sm" :disabled="cancelling" @click="cancel">Cancel</Button>
|
||||
</PageHeader>
|
||||
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
|
||||
<div v-else-if="!data" role="status" aria-label="Loading run" class="space-y-2"><Skeleton class="h-24 w-full" /><Skeleton class="h-48 w-full" /></div>
|
||||
<template v-else>
|
||||
<p v-if="retryError" role="alert" class="mb-2 text-caption text-danger">{{ retryError }}</p>
|
||||
<p v-if="cancelError" role="alert" class="mb-2 text-caption text-danger">{{ cancelError }}</p>
|
||||
<ApprovalsSection :run="id" @answered="reload" />
|
||||
<div class="grid gap-x-4 lg:grid-cols-2">
|
||||
<Section title="Run"><MetadataList :rows="details" /></Section>
|
||||
|
||||
@@ -24,3 +24,16 @@ export function stateTone(state: string): "ok" | "warn" | "danger" | "info" | "i
|
||||
return "idle";
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a run state is terminal: the run has ended and cannot be cancelled. */
|
||||
export function ended(state: string): boolean {
|
||||
switch (state) {
|
||||
case "succeeded":
|
||||
case "failed":
|
||||
case "cancelled":
|
||||
case "declined":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user