package pickupclient
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
// The runner half of the pickup client, as a library: `quarry-runner
// install` makes a key, starts a runner request with its code, and
// collects the worker token the owner's approval mints. The command
// above prints a token for a shell; this hands it to a program that
// writes it to a private file, so it is in no argv and no terminal.
// ErrStillPending is a pickup that no one had answered when the wait
// ended.
var ErrStillPending = errors.New("still pending when the wait ended")
// Closed is a pickup that ended without a credential: State is the
// forge's word, denied, expired, lapsed, failed or collected.
type Closed struct{ State string }
func (c *Closed) Error() string { return "the credential cannot be collected: " + pickupWord(c.State) }
// NewKey makes a pickup key and its public code, the hex SHA-256 of the
// key. The caller keeps the key private.
func NewKey() (key []byte, code string, err error) {
key = make([]byte, 32)
if _, err = rand.Read(key); err != nil {
return nil, "", err
}
sum := sha256.Sum256(key)
return key, hex.EncodeToString(sum[:]), nil
}
// CollectOpts tunes CollectRunner; the zero value waits fifteen minutes,
// polling at the rate the route allows.
type CollectOpts struct {
Client *http.Client
Wait time.Duration
Poll time.Duration
Now func() time.Time
Sleep func(ctx context.Context, d time.Duration) error
}
// Released is a worker token the forge handed over, with what the
// forge says it is for, so the collector can check it got the request
// it meant to (another client could have bound the code first).
type Released struct {
Request string
Agent string
Repo string
TokenID string
Secret string
}
// CollectRunner polls the forge's collect route with key, asking for a
// worker token only, until it is released, closed or the wait ends.
func CollectRunner(ctx context.Context, forge string, key []byte, o CollectOpts) (Released, error) {
e := &Env{Client: o.Client, Now: o.Now, Sleep: o.Sleep}
e.fill()
if o.Wait == 0 {
o.Wait = pickupDefaultWait
}
if o.Poll == 0 {
o.Poll = pickupPoll
}
_, collectURL, err := pickupURL(forge)
if err != nil {
return Released{}, err
}
auth := "Pickup " + base64.RawURLEncoding.EncodeToString(key)
deadline := e.Now().Add(o.Wait)
backoff := time.Duration(0)
for {
status, retry, body, err := pickupPost(ctx, e, collectURL, auth, "runner")
if err != nil {
return Released{}, err
}
var ans struct {
pickupAnswer
Repo string `json:"repo"`
Agent string `json:"agent"`
}
_ = json.Unmarshal(body, &ans)
pause := o.Poll
switch {
case status == http.StatusOK:
if ans.Op != "ci.worker.token.new" || ans.Secret.Value == "" {
return Released{}, errors.New("the forge released something that is not a CI worker token")
}
return Released{Request: ans.Request, Agent: ans.Agent, Repo: ans.Repo, TokenID: ans.Result.Token.ID, Secret: ans.Secret.Value}, nil
case status == http.StatusAccepted:
backoff = 0
case status == http.StatusTooManyRequests:
if retry > 0 {
pause = retry
}
case status >= 500:
if backoff == 0 {
backoff = 2 * time.Second
} else if backoff < 30*time.Second {
backoff *= 2
}
pause = backoff
if !e.Now().Add(pause).Before(deadline) {
return Released{}, fmt.Errorf("the forge kept answering %d", status)
}
case status == http.StatusGone:
return Released{}, &Closed{State: ans.State}
case status == http.StatusConflict && ans.State == "other-kind":
return Released{}, errors.New("this request's credential is not a CI worker token; nothing was collected")
case status == http.StatusNotFound:
return Released{}, errors.New("no such pickup: the forge holds no request for this key")
default:
return Released{}, fmt.Errorf("the forge answered %d", status)
}
if !e.Now().Add(pause).Before(deadline) {
return Released{}, ErrStillPending
}
if err := e.Sleep(ctx, pause); err != nil {
return Released{}, err
}
}
}