deploy / plan (push) Successful in 6s
deploy / archied-image (push) Canceled after 0s
deploy / agent-image (push) Canceled after 0s
deploy / dist-zip (push) Canceled after 0s
deploy / gate (push) Canceled after 5m37s
ci/woodpecker/push/deploy Pipeline was canceled
415 lines
16 KiB
Go
415 lines
16 KiB
Go
// Package taskstate defines task statuses and which operator actions each
|
|
// allows. It has no dependencies.
|
|
package taskstate
|
|
|
|
import (
|
|
"fmt"
|
|
"slices"
|
|
"time"
|
|
)
|
|
|
|
// Action is an operator control whose availability is determined solely by a
|
|
// task's persisted lifecycle state. The Web API returns these values with each
|
|
// task so every presentation surface derives from this table instead of
|
|
// keeping its own copy.
|
|
type Action string
|
|
|
|
const (
|
|
ActionCancel Action = "cancel"
|
|
ActionStop Action = "stop"
|
|
ActionApprove Action = "approve"
|
|
ActionReject Action = "reject"
|
|
ActionRereview Action = "rereview"
|
|
ActionRetry Action = "retry"
|
|
ActionAbandon Action = "abandon"
|
|
ActionMerge Action = "merge"
|
|
ActionOpenPR Action = "open_pr"
|
|
ActionOpenIssue Action = "open_issue"
|
|
ActionArchive Action = "archive"
|
|
)
|
|
|
|
// Task lifecycle statuses. The store persists these strings, so they are
|
|
// part of the on-disk format: renaming one is a migration, not a rename.
|
|
const (
|
|
Queued = "queued"
|
|
Running = "running"
|
|
WaitingApproval = "waiting_approval"
|
|
PROpen = "pr_open"
|
|
Merged = "merged"
|
|
Parked = "parked"
|
|
Dead = "dead"
|
|
|
|
// Rejected means the forge closed the pull request without merging it.
|
|
// It is an outcome archie observed, not a decision an operator made --
|
|
// use Declined for that.
|
|
Rejected = "rejected"
|
|
|
|
// Declined means an operator refused the work. Whether they said so from
|
|
// the dashboard or from chat, the task lands here.
|
|
Declined = "closed_wont_do"
|
|
|
|
// Completed means a workflow that opens no pull request finished its
|
|
// work, such as a run with no repository.
|
|
Completed = "completed"
|
|
)
|
|
|
|
// Actions returns the actions valid for status, as a new slice. Reject is
|
|
// available in every non-terminal state; terminal states offer archive.
|
|
func Actions(status string) []Action {
|
|
var actions []Action
|
|
switch status {
|
|
case Queued:
|
|
actions = []Action{ActionCancel, ActionReject}
|
|
case Running:
|
|
actions = []Action{ActionStop, ActionReject}
|
|
case WaitingApproval:
|
|
actions = []Action{ActionApprove, ActionReject, ActionRereview}
|
|
case Parked:
|
|
actions = []Action{ActionRetry, ActionAbandon, ActionReject}
|
|
case PROpen:
|
|
actions = []Action{ActionMerge, ActionOpenPR, ActionOpenIssue, ActionReject}
|
|
case Merged, Rejected, Dead, Declined, Completed:
|
|
actions = []Action{ActionArchive}
|
|
}
|
|
return actions
|
|
}
|
|
|
|
// ActionTarget returns the status an action moves a task to. Actions that
|
|
// change no status (archive, and the forge links) report false.
|
|
func ActionTarget(action Action) (string, bool) {
|
|
switch action {
|
|
case ActionApprove, ActionRetry, ActionRereview:
|
|
return Queued, true
|
|
case ActionStop:
|
|
return Parked, true
|
|
case ActionCancel, ActionReject, ActionAbandon:
|
|
return Declined, true
|
|
case ActionMerge:
|
|
return Merged, true
|
|
default:
|
|
return "", false
|
|
}
|
|
}
|
|
|
|
// CheckAction rejects stale, illegal and unknown operator controls.
|
|
func CheckAction(status string, action Action) error {
|
|
if slices.Contains(Actions(status), action) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("action %q is not available while task is %s", action, status)
|
|
}
|
|
|
|
// CheckApprove allows approval only from WaitingApproval.
|
|
func CheckApprove(status string) error {
|
|
if status != WaitingApproval {
|
|
return fmt.Errorf("task is %s, not awaiting approval", status)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Approval kinds: what a task in WaitingApproval asks the operator to decide.
|
|
const (
|
|
// ApprovalPlan is a plan from a workflow.approve step, read as task.plan.
|
|
ApprovalPlan = "plan"
|
|
// ApprovalReview is a review gate's findings.
|
|
ApprovalReview = "review"
|
|
// ApprovalBudget is a stage that reached its step budget and asks to
|
|
// continue with more steps.
|
|
ApprovalBudget = "budget"
|
|
)
|
|
|
|
// ApprovalKind is what a task waits on the operator to approve, or "" when it
|
|
// is not waiting for approval.
|
|
func ApprovalKind(status, reviewGate, retryMode string) string {
|
|
switch {
|
|
case status != WaitingApproval:
|
|
return ""
|
|
case NormalizeRetryMode(retryMode) == RetryKeepWorktree:
|
|
return ApprovalBudget
|
|
case reviewGate != "":
|
|
return ApprovalReview
|
|
default:
|
|
return ApprovalPlan
|
|
}
|
|
}
|
|
|
|
// RetryMode is the worktree mode for a retried task's next dispatch. Stored
|
|
// on the task row.
|
|
type RetryMode string
|
|
|
|
const (
|
|
// RetryRefreshOntoBase starts the retry from the current base branch,
|
|
// discarding anything an earlier attempt committed on the task branch.
|
|
// It is the default for work that is not an open pull request.
|
|
RetryRefreshOntoBase RetryMode = "refresh_onto_base"
|
|
// RetryContinuePushedWork resumes the branch the task already pushed, so
|
|
// the retry continues the work an earlier attempt committed instead of
|
|
// resetting over it. It requires a branch to resume.
|
|
RetryContinuePushedWork RetryMode = "continue_pushed_work"
|
|
// RetryKeepWorktree resumes in the task's worktree as it stands, with its
|
|
// uncommitted changes. A stage that stopped on its step budget sets it
|
|
// while it waits for approval to continue; it is never an operator
|
|
// choice.
|
|
RetryKeepWorktree RetryMode = "keep_worktree"
|
|
)
|
|
|
|
// NormalizeRetryMode maps a stored retry mode to the mode it means. Empty and
|
|
// unknown values fall back to RefreshOntoBase: a retry that carries no explicit
|
|
// choice resets onto base, which is the safe default for work that is not an
|
|
// open pull request.
|
|
func NormalizeRetryMode(mode string) RetryMode {
|
|
switch RetryMode(mode) {
|
|
case RetryContinuePushedWork, RetryKeepWorktree:
|
|
return RetryMode(mode)
|
|
}
|
|
return RetryRefreshOntoBase
|
|
}
|
|
|
|
// ResolveRetryMode validates a retry mode; "" means RetryRefreshOntoBase and
|
|
// unknown values are rejected.
|
|
func ResolveRetryMode(mode string) (RetryMode, bool) {
|
|
switch RetryMode(mode) {
|
|
case "", RetryRefreshOntoBase:
|
|
return RetryRefreshOntoBase, true
|
|
case RetryContinuePushedWork:
|
|
return RetryContinuePushedWork, true
|
|
default:
|
|
return "", false
|
|
}
|
|
}
|
|
|
|
// RetryModeMeta describes how to present a retry mode. The dashboard renders
|
|
// the operator's choice from this catalog rather than keeping its own copy.
|
|
type RetryModeMeta struct {
|
|
ID string `json:"id"`
|
|
Label string `json:"label"`
|
|
Description string `json:"description"`
|
|
Default bool `json:"default"`
|
|
// RequiresBranch reports that the mode can only land when the task has a
|
|
// branch to resume. The dashboard disables it otherwise; the action refuses
|
|
// the same combination, so the UI check is a convenience, not the rule.
|
|
RequiresBranch bool `json:"requires_branch"`
|
|
}
|
|
|
|
// RetryModes returns the presentation catalog for the retry modes, in display
|
|
// order. Callers receive a fresh slice.
|
|
func RetryModes() []RetryModeMeta {
|
|
return []RetryModeMeta{
|
|
{ID: string(RetryRefreshOntoBase), Label: "Refresh onto base", Description: "Retry from the current base; discards pushed commits.", Default: true},
|
|
{ID: string(RetryContinuePushedWork), Label: "Continue pushed work", Description: "Resume the pushed branch.", RequiresBranch: true},
|
|
}
|
|
}
|
|
|
|
// CheckDecline allows declining any non-terminal task.
|
|
func CheckDecline(status string) error {
|
|
for _, action := range Actions(status) {
|
|
switch action {
|
|
case ActionCancel, ActionStop, ActionReject, ActionAbandon:
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("task cannot be declined while %s", status)
|
|
}
|
|
|
|
// StatusMeta describes how to present a lifecycle status. It is the single
|
|
// source for the dashboard's label, pill severity and "needs you" grouping, so
|
|
// the frontend never has to keep a hand-synced copy of the vocabulary.
|
|
type StatusMeta struct {
|
|
ID string `json:"id"`
|
|
Label string `json:"label"`
|
|
Kind string `json:"kind"` // pill severity: idle, info, ok, warn, danger
|
|
NeedsAttention bool `json:"needs_attention"` // counts toward the "Needs attention" filter
|
|
}
|
|
|
|
// ActionMeta describes how to present an operator control. Confirmation text
|
|
// uses "{title}" as a placeholder for the task title.
|
|
type ActionMeta struct {
|
|
ID string `json:"id"`
|
|
Label string `json:"label"`
|
|
Kind string `json:"kind"` // button variant: primary, quiet, danger, link
|
|
Confirm string `json:"confirm"` // optional confirm prompt, may be ""
|
|
}
|
|
|
|
// Statuses returns the presentation catalog for every lifecycle status, in
|
|
// display order. Callers receive a fresh slice.
|
|
func Statuses() []StatusMeta {
|
|
return []StatusMeta{
|
|
{ID: Queued, Label: "Queued", Kind: "idle"},
|
|
{ID: Running, Label: "Running", Kind: "info"},
|
|
{ID: WaitingApproval, Label: "Waiting for approval", Kind: "warn", NeedsAttention: true},
|
|
{ID: PROpen, Label: "In review", Kind: "ok"},
|
|
{ID: Merged, Label: "Merged", Kind: "ok"},
|
|
{ID: Completed, Label: "Done", Kind: "ok"},
|
|
{ID: Parked, Label: "Blocked", Kind: "warn", NeedsAttention: true},
|
|
{ID: Dead, Label: "Stopped: retry cap", Kind: "danger"},
|
|
{ID: Rejected, Label: "Rejected", Kind: "danger"},
|
|
{ID: Declined, Label: "Won't do", Kind: "idle"},
|
|
}
|
|
}
|
|
|
|
// ActionCatalog returns the presentation catalog for every operator control.
|
|
// Callers receive a fresh slice.
|
|
func ActionCatalog() []ActionMeta {
|
|
return []ActionMeta{
|
|
{ID: string(ActionCancel), Label: "Cancel", Kind: "quiet", Confirm: `Cancel "{title}"? Closes the issue.`},
|
|
{ID: string(ActionStop), Label: "Stop", Kind: "primary", Confirm: `Stop "{title}"? Work stays parked.`},
|
|
{ID: string(ActionApprove), Label: "Approve", Kind: "primary"},
|
|
{ID: string(ActionRereview), Label: "Re-review", Kind: "quiet"},
|
|
{ID: string(ActionReject), Label: "Reject", Kind: "quiet", Confirm: `Reject "{title}"? Closes the issue.`},
|
|
{ID: string(ActionRetry), Label: "Retry", Kind: "primary"},
|
|
{ID: string(ActionAbandon), Label: "Abandon", Kind: "quiet", Confirm: `Abandon "{title}"? The issue stays open.`},
|
|
{ID: string(ActionArchive), Label: "Archive", Kind: "quiet", Confirm: `Archive the local record for "{title}"?`},
|
|
{ID: string(ActionMerge), Label: "Merge", Kind: "primary", Confirm: `Merge the pull request for "{title}"?`},
|
|
{ID: string(ActionOpenPR), Label: "Open PR", Kind: "link"},
|
|
{ID: string(ActionOpenIssue), Label: "Open issue", Kind: "link"},
|
|
}
|
|
}
|
|
|
|
// Park classes: the producer-side answer to "what kind of intervention does
|
|
// this park need?". The class is recorded at the park site, where the cause is
|
|
// known, and is never inferred later from reason text. It is part of the
|
|
// on-disk format.
|
|
const (
|
|
// ParkNeedsDecision parks need an operator decision: gate failures,
|
|
// review verdicts, diff caps, remediation round caps. It is the
|
|
// default, so an unclassified park always reads as operator-actionable.
|
|
ParkNeedsDecision ParkClass = "needs_decision"
|
|
// ParkTransient parks are environmental: storage, container pool,
|
|
// grants, transport. Nothing about the work is wrong; a requeue can
|
|
// succeed. The daemon requeues them with backoff (TransientRetryDue);
|
|
// past MaxTransientRetries the park becomes needs_decision (ParkClassFor).
|
|
ParkTransient ParkClass = "transient"
|
|
// ParkTerminal parks cannot be retried into success: the repo left the
|
|
// config, the owning identity retired. An operator archives these.
|
|
ParkTerminal ParkClass = "terminal"
|
|
)
|
|
|
|
// Blockers: what a parked task is missing, recorded at the park site so the
|
|
// dashboard can route an operator to the page that supplies it. Part of the
|
|
// on-disk format.
|
|
const (
|
|
// BlockerWorkflowDisabled: the task's org has the workflow turned off.
|
|
BlockerWorkflowDisabled Blocker = "workflow_disabled"
|
|
// BlockerWorkflowIdentity: the workflow declares no usable identity.
|
|
BlockerWorkflowIdentity Blocker = "workflow_identity"
|
|
// BlockerAgentAssignment: the execution identity is inactive or not
|
|
// assigned to the task's org.
|
|
BlockerAgentAssignment Blocker = "agent_assignment"
|
|
// BlockerPolicyDenied: an access policy refuses the run.
|
|
BlockerPolicyDenied Blocker = "policy_denied"
|
|
// BlockerConnectionPermit: the run's identity may not use the
|
|
// repository's connection for an operation the workflow needs.
|
|
BlockerConnectionPermit Blocker = "connection_permit"
|
|
// BlockerRepository: the repository has no policy or no connection.
|
|
BlockerRepository Blocker = "repository"
|
|
// BlockerConnectionCredential: the connection's credential is unusable.
|
|
BlockerConnectionCredential Blocker = "connection_credential"
|
|
// BlockerForgeExtension: no running forge extension serves the connection.
|
|
BlockerForgeExtension Blocker = "forge_extension"
|
|
// BlockerModelCredential: a model provider the run needs has no usable
|
|
// credential.
|
|
BlockerModelCredential Blocker = "model_credential"
|
|
// BlockerModelCredit: a model provider refused the run for want of
|
|
// credit or quota on its account.
|
|
BlockerModelCredit Blocker = "model_credit"
|
|
)
|
|
|
|
// Blocker is the persisted park blocker string.
|
|
type Blocker = string
|
|
|
|
// ParkClass is the persisted park classification string.
|
|
type ParkClass = string
|
|
|
|
// NormalizeParkClass maps a park class written by a producer to the value
|
|
// the store persists. Empty and unknown fall back to NeedsDecision: the safe
|
|
// misread is "an operator should look at this", never "nothing to do".
|
|
func NormalizeParkClass(class string) ParkClass {
|
|
switch class {
|
|
case ParkTransient, ParkTerminal:
|
|
return class
|
|
default:
|
|
return ParkNeedsDecision
|
|
}
|
|
}
|
|
|
|
// MaxTransientRetries is how many times a transient park is requeued
|
|
// automatically before it needs an operator.
|
|
const MaxTransientRetries = 5
|
|
|
|
// transientBackoffBase is the wait before the first automatic retry; each
|
|
// further retry waits twice as long.
|
|
const transientBackoffBase = 30 * time.Second
|
|
|
|
// ParkClassFor is the class a park is stored with: NormalizeParkClass, except
|
|
// a transient park whose task has already used its retries becomes
|
|
// needs_decision, so it raises the operator alert instead of waiting unseen.
|
|
func ParkClassFor(class string, retries int) ParkClass {
|
|
class = NormalizeParkClass(class)
|
|
if class == ParkTransient && retries >= MaxTransientRetries {
|
|
return ParkNeedsDecision
|
|
}
|
|
return class
|
|
}
|
|
|
|
// TransientRetryDue reports whether a task parked as class at parkedAt, after
|
|
// retries earlier retries, should be requeued automatically at now.
|
|
func TransientRetryDue(class string, retries int, parkedAt, now time.Time) bool {
|
|
if class != ParkTransient || retries >= MaxTransientRetries {
|
|
return false
|
|
}
|
|
return !now.Before(parkedAt.Add(transientBackoffBase << retries))
|
|
}
|
|
|
|
// MaxRestartRequeues is how many times daemon restarts may re-queue a task
|
|
// that was running before it parks for an operator.
|
|
const MaxRestartRequeues = 3
|
|
|
|
// RecoveryInput is what the store knows about a task a restart found running.
|
|
type RecoveryInput struct {
|
|
// Restarts is how many earlier restarts re-queued the task.
|
|
Restarts int
|
|
// Stage is the root step the restart interrupted, "" when none was running.
|
|
Stage string
|
|
// PriorResults are the step results recorded by the last step this attempt
|
|
// finished before Stage, nil when it finished none.
|
|
PriorResults []byte
|
|
// RetryMode, ResumeFrom and ResumeResults are the task row's own.
|
|
RetryMode, ResumeFrom string
|
|
ResumeResults []byte
|
|
}
|
|
|
|
// Recovery is how a task a restart found running continues.
|
|
type Recovery struct {
|
|
// Park reports that the task goes to an operator instead of the queue.
|
|
Park bool
|
|
ParkReason string
|
|
// RetryMode, ResumeFrom and ResumeResults are written to the re-queued row.
|
|
RetryMode, ResumeFrom string
|
|
ResumeResults []byte
|
|
}
|
|
|
|
// PlanRecovery decides how a restart treats a task left running: it resumes
|
|
// at the interrupted step in its kept worktree, with the results of the steps
|
|
// before it, rather than repaying them. A task already re-queued
|
|
// MaxRestartRequeues times parks instead.
|
|
func PlanRecovery(in RecoveryInput) Recovery {
|
|
if in.Restarts >= MaxRestartRequeues {
|
|
return Recovery{Park: true, ParkReason: fmt.Sprintf("interrupted by %d daemon restarts in a row; retry to run it again", in.Restarts)}
|
|
}
|
|
rec := Recovery{RetryMode: in.RetryMode, ResumeFrom: in.ResumeFrom, ResumeResults: in.ResumeResults}
|
|
if in.Stage == "" {
|
|
return rec
|
|
}
|
|
switch {
|
|
case in.PriorResults != nil:
|
|
rec.ResumeFrom, rec.ResumeResults = in.Stage, in.PriorResults
|
|
case in.ResumeFrom == in.Stage:
|
|
// The attempt was itself resumed at this step and finished none since.
|
|
default:
|
|
// The first step of a fresh attempt: nothing is finished, so start over.
|
|
return Recovery{RetryMode: in.RetryMode, ResumeResults: []byte("{}")}
|
|
}
|
|
rec.RetryMode = string(RetryKeepWorktree)
|
|
return rec
|
|
}
|