package api
import (
"context"
"errors"
"fmt"
"strings"
"time"
"craftdesign.group/quarry/internal/cibridge"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/runner"
"craftdesign.group/quarry/internal/zitcli"
)
// DeliverCheckoutToken answers the bridge's checkout route for the CI
// task taskID ("<run>.<job>"): a login that reads this repository and
// nothing else, for the runner to fetch the task's check-in with, so a
// runner needs its worker token and no account of its own.
//
// It is a run token held read-only (oltp.RunTokenSpec.ReadOnly): sync
// scope alone, the read letters alone, one repository, any branch, and
// revoked with its run or by TaskEnded. Unlike a job's own run token
// it is no grant of anything the repository's policy withholds, so no
// branch, environment or event rule applies; only a run the forge
// recorded, still going, in this repository. The bridge has already
// shown the caller holds the task. Its life is the job's timeout when
// the run's start names one, and RunTokenMaxLife at most.
func (d Deps) DeliverCheckoutToken(repo, taskID string) (cibridge.CheckoutLogin, error) {
if d.Secrets == nil {
return cibridge.CheckoutLogin{}, fmt.Errorf("%w: this forge keeps no run records", ErrSecretRefused)
}
runID, job, ok := strings.Cut(taskID, ".")
if !ok || runID == "" || job == "" {
return cibridge.CheckoutLogin{}, fmt.Errorf("%w: %q is not a task id", ErrSecretRefused, taskID)
}
if err := d.awaitRecord(repo, runID); err != nil {
return cibridge.CheckoutLogin{}, err
}
life := oltp.RunTokenMaxLife
if _, _, jobs, err := d.Secrets.CIRunStart(runID); err == nil {
if g, ok := jobs[job]; ok && g.Timeout > 0 && time.Duration(g.Timeout)*time.Minute < life {
life = time.Duration(g.Timeout) * time.Minute
}
}
login, value, tok, err := d.Secrets.MintRunToken(oltp.RunTokenSpec{Run: runID, Repo: repo, Job: job, ReadOnly: true, Expires: time.Now().Add(life)})
var refusal oltp.Refusal
if errors.As(err, &refusal) {
return cibridge.CheckoutLogin{}, fmt.Errorf("%w: %s", ErrSecretRefused, refusal.Error())
}
if err != nil {
return cibridge.CheckoutLogin{}, err
}
return cibridge.CheckoutLogin{User: login, Token: value, Expires: tok.Expires}, nil
}
// TaskEnded is the bridge's word that a runner resolved a task for good
// (completed or failed it): its checkout token goes with it. A task id
// that names no run or job has no token to end.
func (d Deps) TaskEnded(repo, taskID string) error {
runID, job, ok := strings.Cut(taskID, ".")
if d.Secrets == nil || !ok || runID == "" || job == "" {
return nil
}
return d.Secrets.RevokeCheckoutToken(runID, job)
}
// awaitRecord waits for the run's record, as a job's ask for its
// token does for its start (awaitRun).
func (d Deps) awaitRecord(repo, runID string) error {
timedOut, err := awaitRun(func() (bool, error) {
_, found, err := d.Secrets.CIRunByID(repo, runID)
return found, err
})
if err == nil && timedOut {
err = fmt.Errorf("%w: no run %.12s in %s", ErrSecretRefused, runID, repo)
}
return err
}
// DeliverTrunkTasks answers the bridge's start-up route: the task types
// ci/runner.json names at trunk, sorted, none when trunk has no such
// file. A file that names none, or that does not parse, is refused in
// words, as a runner reading it itself would have been.
func (d Deps) DeliverTrunkTasks(repo string) ([]string, error) {
r, err := d.repo(repo)
if err != nil {
return nil, err
}
if r.Zit == nil {
return nil, fmt.Errorf("%s has no store to read trunk from", repo)
}
raw, err := r.Zit.Cat(context.Background(), runner.ManifestPath, "trunk")
if errors.Is(err, zitcli.ErrNoEntry) {
return nil, nil
}
if err != nil {
return nil, err
}
m, err := runner.ParseManifest(raw)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrSecretRefused, err)
}
return m.Names(), nil
}