jojo/routers/api/v1/shared/runners.go
Andreas Ahlenstorf 6ff4147688 refactor: replace WithAvailable with WithVisible when fetching runners (#11657)
When fetching runners, the option `WithAvailable` can be enabled to fetch all runners that can be used by a repository, user, or organization, not only those that are owned by the respective repository, user, or organization. In the instance scope, `WithAvailable` has no meaning. You always get _all_ runners. This means it is impossible to only fetch runners that are owned by the instance, but no others.

This PR replaces `WithAvailable` with `WithVisible`. For repositories, users, and organizations, it has the same semantics as `WithAvailable`. For the instance scope, `WithVisible=true` equals today's default behaviour (i.e., return _all_ runners), whereas `WithVisible=false` is new and would only return the runners owned by the instance itself.

The advantage of `WithVisible` is that it has a consistent meaning across all scopes. This also lays the groundwork for the introduction of a `with-visible` (tentative name) flag in the HTTP API.

## Checklist

The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org).

### Tests for Go changes

(can be removed for JavaScript changes)

- I added test coverage for Go changes...
  - [x] in their respective `*_test.go` for unit tests.
  - [x] in the `tests/integration` directory if it involves interactions with a live Forgejo server.
- I ran...
  - [x] `make pr-go` before pushing

### Tests for JavaScript changes

(can be removed for Go changes)

- I added test coverage for JavaScript changes...
  - [ ] in `web_src/js/*.test.js` if it can be unit tested.
  - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)).

### Documentation

- [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
- [x] I did not document these changes and I do not expect someone else to do it.

### Release notes

- [ ] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change.
- [x] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.

*The decision if the pull request will be shown in the release notes is up to the mergers / release team.*

The content of the `release-notes/<pull request number>.md` file will serve as the basis for the release notes. If the file does not exist, the title of the pull request will be used instead.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/11657
Reviewed-by: Mathieu Fenniak <mfenniak@noreply.codeberg.org>
Co-authored-by: Andreas Ahlenstorf <andreas@ahlenstorf.ch>
Co-committed-by: Andreas Ahlenstorf <andreas@ahlenstorf.ch>
2026-03-13 01:43:32 +01:00

222 lines
7 KiB
Go

// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package shared
import (
"errors"
"fmt"
"net/http"
"strings"
actions_model "forgejo.org/models/actions"
"forgejo.org/models/db"
"forgejo.org/modules/optional"
"forgejo.org/modules/structs"
"forgejo.org/modules/util"
"forgejo.org/modules/web"
"forgejo.org/routers/api/v1/utils"
"forgejo.org/services/context"
"forgejo.org/services/convert"
gouuid "github.com/google/uuid"
)
// RegistrationToken is a string used to register a runner with a server
type RegistrationToken struct {
Token string `json:"token"`
}
func GetRegistrationToken(ctx *context.APIContext, ownerID, repoID int64) {
optOwnerID := optional.None[int64]()
if ownerID != 0 {
optOwnerID = optional.Some(ownerID)
}
optRepoID := optional.None[int64]()
if repoID != 0 {
optRepoID = optional.Some(repoID)
}
token, err := actions_model.GetLatestRunnerToken(ctx, optOwnerID, optRepoID)
if errors.Is(err, util.ErrNotExist) || (token != nil && !token.IsActive) {
token, err = actions_model.NewRunnerToken(ctx, optOwnerID, optRepoID)
}
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusOK, RegistrationToken{Token: token.Token})
}
func GetActionRunJobs(ctx *context.APIContext, ownerID, repoID int64) {
labels := []string{}
if len(ctx.Req.Form["labels"]) > 0 {
labels = strings.Split(ctx.FormTrim("labels"), ",")
}
total, err := db.Find[actions_model.ActionRunJob](ctx, &actions_model.FindTaskOptions{
Status: []actions_model.Status{actions_model.StatusWaiting, actions_model.StatusRunning},
OwnerID: ownerID,
RepoID: repoID,
})
if err != nil {
ctx.Error(http.StatusInternalServerError, "CountWaitingActionRunJobs", err)
return
}
res := fromRunJobModelToResponse(total, labels)
ctx.JSON(http.StatusOK, res)
}
func fromRunJobModelToResponse(job []*actions_model.ActionRunJob, labels []string) []*structs.ActionRunJob {
var res []*structs.ActionRunJob
for i := range job {
if len(labels) == 0 || labels[0] == "" && len(job[i].RunsOn) == 0 || job[i].ItRunsOn(labels) {
res = append(res, &structs.ActionRunJob{
ID: job[i].ID,
RepoID: job[i].RepoID,
OwnerID: job[i].OwnerID,
Name: job[i].Name,
Needs: job[i].Needs,
RunsOn: job[i].RunsOn,
TaskID: job[i].TaskID,
Status: job[i].Status.String(),
})
}
}
return res
}
// ListRunners lists runners for api route validated ownerID and repoID
// ownerID == 0 and repoID == 0 means all runners including global runners, does not appear in sql where clause
// ownerID == 0 and repoID != 0 means all runners for the given repo
// ownerID != 0 and repoID == 0 means all runners for the given user/org
// ownerID != 0 and repoID != 0 undefined behavior
// Access rights are checked at the API route level
func ListRunners(ctx *context.APIContext, ownerID, repoID int64) {
if ownerID != 0 && repoID != 0 {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("ownerID and repoID should not be both set: %d and %d", ownerID, repoID))
return
}
listOptions := utils.GetListOptions(ctx)
runners, total, err := db.FindAndCount[actions_model.ActionRunner](ctx, &actions_model.FindRunnerOptions{
OwnerID: ownerID,
RepoID: repoID,
ListOptions: listOptions,
WithVisible: ownerID == 0 && repoID == 0,
})
if err != nil {
ctx.Error(http.StatusInternalServerError, "FindCountRunners", map[string]string{})
return
}
runnerList := make([]structs.ActionRunner, len(runners))
for i, runner := range runners {
actionRunner, err := convert.ToActionRunner(runner)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ToActionRunner", err)
return
}
runnerList[i] = actionRunner
}
ctx.SetLinkHeader(int(total), listOptions.PageSize)
ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, &runnerList)
}
// GetRunner get the runner for api route validated ownerID and repoID
// ownerID == 0 and repoID == 0 means any runner including global runners
// ownerID == 0 and repoID != 0 means any runner for the given repo
// ownerID != 0 and repoID == 0 means any runner for the given user/org
// ownerID != 0 and repoID != 0 undefined behavior
// Access rights are checked at the API route level
func GetRunner(ctx *context.APIContext, ownerID, repoID, runnerID int64) {
if ownerID != 0 && repoID != 0 {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("ownerID and repoID should not be both set: %d and %d", ownerID, repoID))
return
}
runner, err := actions_model.GetRunnerByID(ctx, runnerID)
if err != nil {
if errors.Is(err, util.ErrNotExist) {
ctx.Error(http.StatusNotFound, "GetRunnerNotFound", err)
} else {
ctx.Error(http.StatusInternalServerError, "GetRunnerFailed", err)
}
return
}
if !runner.Editable(ownerID, repoID) {
ctx.Error(http.StatusNotFound, "RunnerEdit", "No permission to get this runner")
return
}
actionRunner, err := convert.ToActionRunner(runner)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ToActionRunner", err)
}
ctx.JSON(http.StatusOK, actionRunner)
}
func RegisterRunner(ctx *context.APIContext, ownerID, repoID int64) {
if ownerID != 0 && repoID != 0 {
ctx.Error(http.StatusUnprocessableEntity, "RegisterRunner", fmt.Errorf("ownerID '%d' and repoID '%d' cannot be set simultaneously", ownerID, repoID))
return
}
options := web.GetForm(ctx).(*structs.RegisterRunnerOptions)
runner := &actions_model.ActionRunner{
UUID: gouuid.NewString(),
Name: options.Name,
OwnerID: ownerID,
RepoID: repoID,
Description: options.Description,
Ephemeral: options.Ephemeral,
}
runner.GenerateToken()
if err := actions_model.CreateRunner(ctx, runner); err != nil {
ctx.Error(http.StatusInternalServerError, "CreateRunner", err)
}
response := &structs.RegisterRunnerResponse{
ID: runner.ID,
UUID: runner.UUID,
Token: runner.Token,
}
ctx.JSON(http.StatusCreated, response)
}
// DeleteRunner deletes the runner for api route validated ownerID and repoID
// ownerID == 0 and repoID == 0 means any runner including global runners
// ownerID == 0 and repoID != 0 means any runner for the given repo
// ownerID != 0 and repoID == 0 means any runner for the given user/org
// ownerID != 0 and repoID != 0 undefined behavior
// Access rights are checked at the API route level
func DeleteRunner(ctx *context.APIContext, ownerID, repoID, runnerID int64) {
if ownerID != 0 && repoID != 0 {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("ownerID and repoID should not be both set: %d and %d", ownerID, repoID))
return
}
runner, err := actions_model.GetRunnerByID(ctx, runnerID)
if err != nil {
if errors.Is(err, util.ErrNotExist) {
ctx.Error(http.StatusNotFound, "DeleteRunnerNotFound", err)
} else {
ctx.Error(http.StatusInternalServerError, "DeleteRunnerFailed", err)
}
return
}
if !runner.Editable(ownerID, repoID) {
ctx.Error(http.StatusNotFound, "EditRunner", "No permission to delete this runner")
return
}
err = actions_model.DeleteRunner(ctx, runner)
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.Status(http.StatusNoContent)
}