mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-04 11:57:35 +00:00
feat(actions): Add Actions API endpoints for workflow run management and logs (#35382)
Implements the missing REST API endpoints for Actions workflow run
management:
1. `POST /actions/runs/{run}/cancel` cancels a run and its jobs, `409`
when it already finished
1. `POST /actions/runs/{run}/approve` approves a run awaiting approval,
idempotent, `409` when it never awaited one
1. `GET /actions/runs/{run}/logs` downloads the latest attempt's job
logs as a zip archive
`ActionWorkflowRun` gains `created_at`, `updated_at` and the `jobs_url`,
`logs_url`, `artifacts_url`, `cancel_url` and `rerun_url` fields, and
now always emits `conclusion` and `head_branch`.
Cancellation is shared with the web handler in `services/actions`.
Fixes https://github.com/go-gitea/gitea/issues/35176
Fixes https://github.com/go-gitea/gitea/issues/36554
---------
Co-authored-by: Claude Sonnet 4.6 <claude-sonnet-4-6@anthropic.com>
Co-authored-by: OpenCode Agent <opencode@rossgolder.com>
Co-authored-by: Nicolas <bircni@icloud.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
@@ -14,9 +14,11 @@ import (
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
func ApproveRuns(ctx context.Context, repo *repo_model.Repository, doer *user_model.User, runIDs []int64) error {
|
||||
// ApproveRuns returns the approved runs in the same order as runIDs.
|
||||
func ApproveRuns(ctx context.Context, repo *repo_model.Repository, doer *user_model.User, runIDs []int64) ([]*actions_model.ActionRun, error) {
|
||||
updatedJobs := make([]*actions_model.ActionRunJob, 0)
|
||||
cancelledConcurrencyJobs := make([]*actions_model.ActionRunJob, 0)
|
||||
// Track runs whose reusable callers were just expanded so we can re-emit after the tx commits.
|
||||
@@ -36,7 +38,7 @@ func ApproveRuns(ctx context.Context, repo *repo_model.Repository, doer *user_mo
|
||||
if err := actions_model.UpdateRun(ctx, run, "need_approval", "approved_by"); err != nil {
|
||||
return err
|
||||
}
|
||||
jobs, err := actions_model.GetLatestAttemptJobsByRepoAndRunID(ctx, repo.ID, run.ID)
|
||||
jobs, err := actions_model.GetLatestAttemptJobsByRun(ctx, run)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -107,7 +109,7 @@ func ApproveRuns(ctx context.Context, repo *repo_model.Repository, doer *user_mo
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Re-emit AFTER the tx commits so the newly inserted callee rows transition Blocked -> Waiting.
|
||||
@@ -122,5 +124,26 @@ func ApproveRuns(ctx context.Context, repo *repo_model.Repository, doer *user_mo
|
||||
|
||||
EmitJobsIfReadyByJobs(cancelledConcurrencyJobs)
|
||||
|
||||
return nil
|
||||
// The batches above already notified every run whose jobs changed, which is the only way
|
||||
// approving alters a run's status, so reload purely to answer the caller.
|
||||
reloaded, err := actions_model.GetRunsByRepoAndID(ctx, repo.ID, runIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GetRunsByRepoAndID: %w", err)
|
||||
}
|
||||
runsByID := make(map[int64]*actions_model.ActionRun, len(reloaded))
|
||||
for _, run := range reloaded {
|
||||
run.Repo = repo // the caller resolved runIDs against this repo, so spare every consumer a reload
|
||||
runsByID[run.ID] = run
|
||||
}
|
||||
|
||||
approvedRuns := make([]*actions_model.ActionRun, 0, len(runIDs))
|
||||
for _, runID := range runIDs {
|
||||
run := runsByID[runID]
|
||||
if run == nil {
|
||||
return nil, util.NewNotExistErrorf("run %d no longer exists after approval", runID)
|
||||
}
|
||||
approvedRuns = append(approvedRuns, run)
|
||||
}
|
||||
|
||||
return approvedRuns, nil
|
||||
}
|
||||
|
||||
@@ -32,36 +32,64 @@ func TestApproveRuns(t *testing.T) {
|
||||
require.NoError(t, db.Insert(t.Context(), run))
|
||||
return run
|
||||
}
|
||||
insertJob := func(run *actions_model.ActionRun, status actions_model.Status) *actions_model.ActionRunJob {
|
||||
insertJob := func(run *actions_model.ActionRun, status actions_model.Status, needs ...string) *actions_model.ActionRunJob {
|
||||
job := &actions_model.ActionRunJob{
|
||||
RunID: run.ID, RepoID: run.RepoID, OwnerID: run.OwnerID, CommitSHA: run.CommitSHA,
|
||||
Name: "job1", Attempt: 1, JobID: "job1", Status: status,
|
||||
RunsOn: []string{"ubuntu-latest"},
|
||||
RunsOn: []string{"ubuntu-latest"}, Needs: needs,
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), job))
|
||||
return job
|
||||
}
|
||||
|
||||
t.Run("approve blocked run", func(t *testing.T) {
|
||||
t.Run("approve unblocks a job with no dependencies", func(t *testing.T) {
|
||||
run := insertRun(1001, actions_model.StatusBlocked, true, 0)
|
||||
job := insertJob(run, actions_model.StatusBlocked)
|
||||
|
||||
require.NoError(t, ApproveRuns(t.Context(), repo, doer, []int64{run.ID}))
|
||||
approved, err := ApproveRuns(t.Context(), repo, doer, []int64{run.ID})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, approved, 1)
|
||||
assert.False(t, approved[0].NeedApproval)
|
||||
assert.Equal(t, doer.ID, approved[0].ApprovedBy)
|
||||
|
||||
run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run.ID})
|
||||
assert.False(t, run.NeedApproval)
|
||||
assert.Equal(t, doer.ID, run.ApprovedBy)
|
||||
assert.Equal(t, actions_model.StatusWaiting, unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: job.ID}).Status)
|
||||
})
|
||||
|
||||
t.Run("a job with unmet dependencies stays blocked", func(t *testing.T) {
|
||||
run := insertRun(1002, actions_model.StatusBlocked, true, 0)
|
||||
job := insertJob(run, actions_model.StatusBlocked, "some-other-job")
|
||||
|
||||
approved, err := ApproveRuns(t.Context(), repo, doer, []int64{run.ID})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, approved, 1)
|
||||
assert.False(t, approved[0].NeedApproval)
|
||||
|
||||
assert.Equal(t, actions_model.StatusBlocked, unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: job.ID}).Status)
|
||||
})
|
||||
|
||||
t.Run("re-approving an approved run is a no-op", func(t *testing.T) {
|
||||
run := insertRun(1002, actions_model.StatusRunning, false, 4)
|
||||
run := insertRun(1005, actions_model.StatusRunning, false, 4)
|
||||
job := insertJob(run, actions_model.StatusRunning)
|
||||
|
||||
require.NoError(t, ApproveRuns(t.Context(), repo, doer, []int64{run.ID}))
|
||||
|
||||
run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run.ID})
|
||||
assert.EqualValues(t, 4, run.ApprovedBy, "approver must not be overwritten")
|
||||
approved, err := ApproveRuns(t.Context(), repo, doer, []int64{run.ID})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, approved, 1)
|
||||
assert.EqualValues(t, 4, approved[0].ApprovedBy, "approver must not be overwritten")
|
||||
assert.Equal(t, actions_model.StatusRunning, unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: job.ID}).Status, "started job must not be reset to waiting")
|
||||
})
|
||||
|
||||
t.Run("approving several runs returns them in the requested order", func(t *testing.T) {
|
||||
run1 := insertRun(1003, actions_model.StatusBlocked, true, 0)
|
||||
insertJob(run1, actions_model.StatusBlocked)
|
||||
run2 := insertRun(1004, actions_model.StatusBlocked, true, 0)
|
||||
insertJob(run2, actions_model.StatusBlocked)
|
||||
|
||||
approved, err := ApproveRuns(t.Context(), repo, doer, []int64{run2.ID, run1.ID})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, approved, 2)
|
||||
assert.Equal(t, run2.ID, approved[0].ID)
|
||||
assert.Equal(t, run1.ID, approved[1].ID)
|
||||
assert.False(t, approved[0].NeedApproval)
|
||||
assert.False(t, approved[1].NeedApproval)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package actions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
)
|
||||
|
||||
// CancelRun cancels a run's cancellable jobs and returns the run's post-cancellation state.
|
||||
func CancelRun(ctx context.Context, run *actions_model.ActionRun, jobs []*actions_model.ActionRunJob) (*actions_model.ActionRun, error) {
|
||||
var updatedJobs []*actions_model.ActionRunJob
|
||||
if err := db.WithTx(ctx, func(ctx context.Context) (err error) {
|
||||
updatedJobs, err = actions_model.CancelJobs(ctx, jobs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("CancelJobs: %w", err)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
CreateCommitStatusForRunJobs(ctx, run, jobs...)
|
||||
EmitJobsIfReadyByJobs(updatedJobs)
|
||||
NotifyWorkflowJobsStatusUpdate(ctx, updatedJobs...)
|
||||
if len(updatedJobs) == 0 {
|
||||
return run, nil
|
||||
}
|
||||
|
||||
reloaded, err := actions_model.GetRunByRepoAndID(ctx, run.RepoID, run.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GetRunByRepoAndID: %w", err)
|
||||
}
|
||||
NotifyWorkflowRunStatusUpdate(ctx, reloaded)
|
||||
return reloaded, nil
|
||||
}
|
||||
@@ -155,7 +155,8 @@ func TestApproveRuns_MaxParallel(t *testing.T) {
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: run.RepoID})
|
||||
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
require.NoError(t, ApproveRuns(t.Context(), repo, doer, []int64{run.ID}))
|
||||
_, err := ApproveRuns(t.Context(), repo, doer, []int64{run.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, map[actions_model.Status]int{
|
||||
actions_model.StatusWaiting: 2,
|
||||
@@ -203,7 +204,8 @@ func TestApproveRuns_MaxParallelStarvedSkipsConcurrency(t *testing.T) {
|
||||
run := insertMaxParallelRun(t, maxParallelConcurrencyWorkflow, true)
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: run.RepoID})
|
||||
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
require.NoError(t, ApproveRuns(t.Context(), repo, doer, []int64{run.ID}))
|
||||
_, err := ApproveRuns(t.Context(), repo, doer, []int64{run.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, map[actions_model.Status]int{
|
||||
actions_model.StatusWaiting: 1,
|
||||
|
||||
@@ -293,7 +293,7 @@ func ToActionWorkflowRun(ctx context.Context, run *actions_model.ActionRun, atte
|
||||
completedAt = attempt.Stopped.AsLocalTime()
|
||||
triggerUser = attempt.TriggerUser
|
||||
if attempt.Attempt > 1 {
|
||||
url := fmt.Sprintf("%s/actions/runs/%d/attempts/%d", run.Repo.APIURL(ctx), run.ID, attempt.Attempt-1)
|
||||
url := fmt.Sprintf("%s/attempts/%d", run.APIURL(ctx), attempt.Attempt-1)
|
||||
previousAttemptURL = &url
|
||||
}
|
||||
}
|
||||
@@ -305,13 +305,21 @@ func ToActionWorkflowRun(ctx context.Context, run *actions_model.ActionRun, atte
|
||||
}
|
||||
}
|
||||
|
||||
runURL := run.APIURL(ctx)
|
||||
return &api.ActionWorkflowRun{
|
||||
ID: run.ID,
|
||||
URL: fmt.Sprintf("%s/actions/runs/%d", run.Repo.APIURL(ctx), run.ID),
|
||||
URL: runURL,
|
||||
PreviousAttemptURL: previousAttemptURL,
|
||||
HTMLURL: run.HTMLURL(ctx),
|
||||
JobsURL: runURL + "/jobs",
|
||||
LogsURL: runURL + "/logs",
|
||||
ArtifactsURL: runURL + "/artifacts",
|
||||
CancelURL: runURL + "/cancel",
|
||||
RerunURL: runURL + "/rerun",
|
||||
RunNumber: run.Index,
|
||||
RunAttempt: runAttempt,
|
||||
CreatedAt: run.Created.AsLocalTime(),
|
||||
UpdatedAt: run.Updated.AsLocalTime(),
|
||||
StartedAt: startedAt,
|
||||
CompletedAt: completedAt,
|
||||
Event: run.TriggerEvent,
|
||||
|
||||
@@ -222,6 +222,9 @@ func prepareDBConsistencyChecks() []consistencyCheck {
|
||||
// find action without repository
|
||||
genericOrphanCheck("Action entries without existing repository",
|
||||
"action", "repository", "action.repo_id=repository.id"),
|
||||
// find action runs without repository
|
||||
genericOrphanCheck("Action runs without existing repository",
|
||||
"action_run", "repository", "action_run.repo_id=repository.id"),
|
||||
// find action without user
|
||||
genericOrphanCheck("Action entries without existing user",
|
||||
"action", "user", "action.act_user_id=`user`.id"),
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -42,8 +41,7 @@ type expansion struct {
|
||||
}
|
||||
|
||||
var globalVars = sync.OnceValue(func() (ret struct {
|
||||
defaultTransformers []transformer
|
||||
fileNameSanitizeRegexp *regexp.Regexp
|
||||
defaultTransformers []transformer
|
||||
},
|
||||
) {
|
||||
ret.defaultTransformers = []transformer{
|
||||
@@ -55,10 +53,6 @@ var globalVars = sync.OnceValue(func() (ret struct {
|
||||
{Name: "UPPER", Transform: strings.ToUpper},
|
||||
{Name: "TITLE", Transform: util.ToTitleCase},
|
||||
}
|
||||
|
||||
// invalid filename contents, based on https://github.com/sindresorhus/filename-reserved-regex
|
||||
// "COM10" needs to be opened with UNC "\\.\COM10" on Windows, so itself is valid
|
||||
ret.fileNameSanitizeRegexp = regexp.MustCompile(`(?i)[<>:"/\\|?*\x{0000}-\x{001F}]|^(con|prn|aux|nul|com\d|lpt\d)$`)
|
||||
return ret
|
||||
})
|
||||
|
||||
@@ -340,7 +334,9 @@ func (gro GenerateRepoOptions) IsValid() bool {
|
||||
func filePathSanitize(s string) string {
|
||||
fields := strings.Split(filepath.ToSlash(s), "/")
|
||||
for i, field := range fields {
|
||||
field = strings.TrimSpace(strings.TrimSpace(globalVars().fileNameSanitizeRegexp.ReplaceAllString(field, "_")))
|
||||
field = util.PathNameValidator().InvalidChars.ReplaceAllString(field, "_")
|
||||
field = util.PathNameValidator().InvalidNames.ReplaceAllString(field, "_")
|
||||
field = strings.TrimSpace(field)
|
||||
if strings.HasPrefix(field, "..") {
|
||||
field = "__" + field[2:]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user