Files
releasekit/internal/woodpecker/client.go

276 lines
9.1 KiB
Go

// Package woodpecker observes Woodpecker repositories and diagnostic pipelines.
package woodpecker
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"go.maximumdirect.net/releasekit/internal/git"
)
// Client borrows its HTTP client and carries a separate observation credential.
type Client struct {
BaseURL string
RepositoryID int64
Token string
HTTPClient *http.Client
}
type Pipeline struct {
ID int64 `json:"id"`
Number int64 `json:"number"`
Event string `json:"event"`
Ref string `json:"ref"`
Commit string `json:"commit"`
Status string `json:"status"`
Workflows []Workflow `json:"workflows"`
}
type Workflow struct {
ID int64 `json:"id"`
Name string `json:"name"`
State string `json:"state"`
Steps []Step `json:"children"`
}
type Step struct {
ID int64 `json:"id"`
Name string `json:"name"`
State string `json:"state"`
}
// Error carries the status without exposing response bodies or credentials.
type Error struct {
Operation string
Status int
Cause error
}
// ValidateConfiguration checks the selected endpoint and credential locally.
func (c Client) ValidateConfiguration() error {
_, err := c.endpoint("")
return err
}
func (e *Error) Error() string {
if e.Status != 0 {
return fmt.Sprintf("woodpecker %s: HTTP %d", e.Operation, e.Status)
}
if e.Cause != nil {
return fmt.Sprintf("woodpecker %s: %v", e.Operation, e.Cause)
}
return "woodpecker " + e.Operation
}
func (e *Error) Unwrap() error { return e.Cause }
func (c Client) endpoint(suffix string) (string, error) {
u, err := url.Parse(c.BaseURL)
if err != nil || u == nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return "", errors.New("Woodpecker base URL must be an absolute HTTP(S) URL without credentials, query, or fragment")
}
if c.RepositoryID <= 0 {
return "", errors.New("Woodpecker repository ID must be positive")
}
if strings.TrimSpace(c.Token) == "" {
return "", errors.New("Woodpecker token is required")
}
u.Path = strings.TrimRight(u.Path, "/") + "/api/repos/" + strconv.FormatInt(c.RepositoryID, 10) + suffix
u.RawPath = ""
return u.String(), nil
}
func (c Client) open(ctx context.Context, operation, suffix string, query url.Values) (io.ReadCloser, error) {
endpoint, err := c.endpoint(suffix)
if err != nil {
return nil, &Error{Operation: operation, Cause: err}
}
if len(query) > 0 {
endpoint += "?" + query.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, &Error{Operation: operation, Cause: err}
}
req.Header.Set("Authorization", "Bearer "+c.Token)
req.Header.Set("Accept", "application/json")
client := http.DefaultClient
if c.HTTPClient != nil {
client = c.HTTPClient
}
copyClient := *client
copyClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
resp, err := copyClient.Do(req)
if err != nil {
return nil, &Error{Operation: operation, Cause: err}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
resp.Body.Close()
return nil, &Error{Operation: operation, Status: resp.StatusCode}
}
return resp.Body, nil
}
func (c Client) read(ctx context.Context, operation, suffix string, query url.Values, value any) error {
body, err := c.open(ctx, operation, suffix, query)
if err != nil {
return err
}
defer body.Close()
dec := json.NewDecoder(body)
if err := dec.Decode(value); err != nil {
return &Error{Operation: operation, Cause: fmt.Errorf("invalid response: %w", err)}
}
var extra any
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
return &Error{Operation: operation, Cause: errors.New("invalid trailing response data")}
}
return nil
}
// CheckRepository verifies authenticated read access to the configured repository.
func (c Client) CheckRepository(ctx context.Context) error {
var repository struct {
ID int64 `json:"id"`
}
if err := c.read(ctx, "read repository", "", nil, &repository); err != nil {
return err
}
if repository.ID != c.RepositoryID {
return &Error{Operation: "read repository", Cause: errors.New("repository response does not match configured ID")}
}
return nil
}
// MatchingPipelines follows every page and matches exact tag event, ref and commit.
func (c Client) MatchingPipelines(ctx context.Context, tag, commit string) ([]Pipeline, error) {
if !git.ValidObjectID(commit) || tag == "" {
return nil, errors.New("exact tag and full commit are required")
}
var matches []Pipeline
type pipelineIdentity struct {
number int64
ref, commit, event string
}
seen := map[int64]pipelineIdentity{}
indices := map[int64]int{}
for page := 1; ; page++ {
query := url.Values{"page": {strconv.Itoa(page)}, "perPage": {"50"}, "event": {"tag"}, "ref": {"refs/tags/" + tag}}
var items []Pipeline
if err := c.read(ctx, "list pipelines", "/pipelines", query, &items); err != nil {
return nil, err
}
if items == nil {
return nil, &Error{Operation: "list pipelines", Cause: errors.New("pipeline response must be an array")}
}
if len(items) == 0 {
return matches, nil
}
for _, item := range items {
if item.ID <= 0 || item.Number <= 0 || item.Ref == "" || item.Commit == "" || item.Event == "" || item.Status == "" {
return nil, &Error{Operation: "list pipelines", Cause: errors.New("pipeline response omits required identity")}
}
identity := pipelineIdentity{item.Number, item.Ref, strings.ToLower(item.Commit), item.Event}
if previous, exists := seen[item.ID]; exists {
if previous != identity {
return nil, &Error{Operation: "list pipelines", Cause: errors.New("pagination returned conflicting pipeline identity")}
}
if index, matched := indices[item.ID]; matched {
matches[index] = item
}
continue
}
seen[item.ID] = identity
if item.Event == "tag" && item.Ref == "refs/tags/"+tag && git.EqualObjectID(item.Commit, commit) {
indices[item.ID] = len(matches)
matches = append(matches, item)
}
}
}
}
// Job identifies one exact matching workflow and step, including reruns or
// matrix jobs. Unknown states remain unknown rather than becoming success.
type Job struct {
PipelineID, PipelineNumber, WorkflowID, StepID int64
PipelineStatus, WorkflowState, StepState string
}
// Jobs finds every named step in the requested named workflow.
func (p Pipeline) Jobs(workflow, step string) ([]Job, error) {
if workflow == "" || step == "" || p.ID <= 0 || p.Number <= 0 {
return nil, errors.New("pipeline, workflow, and step identity are required")
}
var jobs []Job
for _, w := range p.Workflows {
if w.Name != workflow {
continue
}
if w.ID <= 0 || w.State == "" {
return nil, errors.New("workflow response omits identity or state")
}
for _, s := range w.Steps {
if s.Name != step {
continue
}
if s.ID <= 0 || s.State == "" {
return nil, errors.New("step response omits identity or state")
}
jobs = append(jobs, Job{PipelineID: p.ID, PipelineNumber: p.Number, WorkflowID: w.ID, StepID: s.ID, PipelineStatus: p.Status, WorkflowState: w.State, StepState: s.State})
}
}
if len(jobs) == 0 {
return nil, errors.New("configured workflow and step are absent from pipeline")
}
return jobs, nil
}
// Pipeline retrieves one exact numbered pipeline, including workflow and step IDs.
func (c Client) Pipeline(ctx context.Context, number int64) (Pipeline, error) {
if number <= 0 {
return Pipeline{}, errors.New("pipeline number must be positive")
}
var p Pipeline
if err := c.read(ctx, "read pipeline", "/pipelines/"+strconv.FormatInt(number, 10), nil, &p); err != nil {
return Pipeline{}, err
}
if p.ID <= 0 || p.Number != number || p.Event == "" || p.Ref == "" || p.Commit == "" || p.Status == "" {
return Pipeline{}, &Error{Operation: "read pipeline", Cause: errors.New("pipeline response omits required identity")}
}
return p, nil
}
// DiagnosticPipeline binds a detail response to the exact event being tracked.
func (c Client) DiagnosticPipeline(ctx context.Context, number int64, tag, commit string) (Pipeline, error) {
p, err := c.Pipeline(ctx, number)
if err != nil {
return Pipeline{}, err
}
if tag == "" || p.Event != "tag" || p.Ref != "refs/tags/"+tag || !git.EqualObjectID(p.Commit, commit) {
return Pipeline{}, &Error{Operation: "read pipeline", Cause: errors.New("pipeline does not match diagnostic tag and commit")}
}
return p, nil
}
// OpenLog returns a streaming log; the caller must close it.
func (c Client) OpenLog(ctx context.Context, number, stepID int64) (io.ReadCloser, error) {
if number <= 0 || stepID <= 0 {
return nil, errors.New("pipeline number and step ID must be positive")
}
return c.open(ctx, "download step log", "/logs/"+strconv.FormatInt(number, 10)+"/"+strconv.FormatInt(stepID, 10)+"/download", nil)
}
// StateClass distinguishes active, terminal and unrecognized server states.
func StateClass(state string) string {
switch state {
case "pending", "running", "blocked", "created":
return "active"
case "success", "failure", "error", "killed", "skipped", "declined":
return "terminal"
default:
return "unknown"
}
}