@@ -0,0 +1,231 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +// Package api is the shithubd-runner client for the S41c runner HTTP API. |
| 4 | +package api |
| 5 | + |
| 6 | +import ( |
| 7 | + "bytes" |
| 8 | + "context" |
| 9 | + "encoding/base64" |
| 10 | + "encoding/json" |
| 11 | + "fmt" |
| 12 | + "io" |
| 13 | + "net/http" |
| 14 | + "net/url" |
| 15 | + "strconv" |
| 16 | + "strings" |
| 17 | + "time" |
| 18 | +) |
| 19 | + |
| 20 | +type Config struct { |
| 21 | + BaseURL string |
| 22 | + RunnerToken string |
| 23 | + HTTPClient *http.Client |
| 24 | +} |
| 25 | + |
| 26 | +type Client struct { |
| 27 | + base *url.URL |
| 28 | + runnerToken string |
| 29 | + http *http.Client |
| 30 | +} |
| 31 | + |
| 32 | +func New(cfg Config) (*Client, error) { |
| 33 | + base, err := url.Parse(strings.TrimRight(strings.TrimSpace(cfg.BaseURL), "/")) |
| 34 | + if err != nil || base.Scheme == "" || base.Host == "" { |
| 35 | + return nil, fmt.Errorf("runner api: invalid base URL %q", cfg.BaseURL) |
| 36 | + } |
| 37 | + if strings.TrimSpace(cfg.RunnerToken) == "" { |
| 38 | + return nil, fmt.Errorf("runner api: runner token is required") |
| 39 | + } |
| 40 | + hc := cfg.HTTPClient |
| 41 | + if hc == nil { |
| 42 | + hc = http.DefaultClient |
| 43 | + } |
| 44 | + return &Client{base: base, runnerToken: strings.TrimSpace(cfg.RunnerToken), http: hc}, nil |
| 45 | +} |
| 46 | + |
| 47 | +type HeartbeatRequest struct { |
| 48 | + Labels []string `json:"labels"` |
| 49 | + Capacity int `json:"capacity"` |
| 50 | +} |
| 51 | + |
| 52 | +type Claim struct { |
| 53 | + Token string `json:"token"` |
| 54 | + ExpiresAt time.Time `json:"expires_at"` |
| 55 | + Job Job `json:"job"` |
| 56 | +} |
| 57 | + |
| 58 | +type Job struct { |
| 59 | + ID int64 `json:"id"` |
| 60 | + RunID int64 `json:"run_id"` |
| 61 | + RepoID int64 `json:"repo_id"` |
| 62 | + RunIndex int64 `json:"run_index"` |
| 63 | + WorkflowFile string `json:"workflow_file"` |
| 64 | + WorkflowName string `json:"workflow_name"` |
| 65 | + HeadSHA string `json:"head_sha"` |
| 66 | + HeadRef string `json:"head_ref"` |
| 67 | + Event string `json:"event"` |
| 68 | + JobKey string `json:"job_key"` |
| 69 | + JobName string `json:"job_name"` |
| 70 | + RunsOn string `json:"runs_on"` |
| 71 | + Needs []string `json:"needs"` |
| 72 | + If string `json:"if"` |
| 73 | + TimeoutMinutes int32 `json:"timeout_minutes"` |
| 74 | + Permissions json.RawMessage `json:"permissions"` |
| 75 | + Env map[string]string `json:"env"` |
| 76 | + Steps []Step `json:"steps"` |
| 77 | +} |
| 78 | + |
| 79 | +type Step struct { |
| 80 | + ID int64 `json:"id"` |
| 81 | + Index int32 `json:"index"` |
| 82 | + StepID string `json:"step_id"` |
| 83 | + Name string `json:"name"` |
| 84 | + If string `json:"if"` |
| 85 | + Run string `json:"run"` |
| 86 | + Uses string `json:"uses"` |
| 87 | + WorkingDirectory string `json:"working_directory"` |
| 88 | + Env map[string]string `json:"env"` |
| 89 | + With map[string]string `json:"with"` |
| 90 | + ContinueOnError bool `json:"continue_on_error"` |
| 91 | +} |
| 92 | + |
| 93 | +type StatusRequest struct { |
| 94 | + Status string `json:"status"` |
| 95 | + Conclusion string `json:"conclusion,omitempty"` |
| 96 | + StartedAt time.Time `json:"-"` |
| 97 | + CompletedAt time.Time `json:"-"` |
| 98 | +} |
| 99 | + |
| 100 | +func (r StatusRequest) MarshalJSON() ([]byte, error) { |
| 101 | + type wire struct { |
| 102 | + Status string `json:"status"` |
| 103 | + Conclusion string `json:"conclusion,omitempty"` |
| 104 | + StartedAt string `json:"started_at,omitempty"` |
| 105 | + CompletedAt string `json:"completed_at,omitempty"` |
| 106 | + } |
| 107 | + out := wire{Status: r.Status, Conclusion: r.Conclusion} |
| 108 | + if !r.StartedAt.IsZero() { |
| 109 | + out.StartedAt = r.StartedAt.UTC().Format(time.RFC3339Nano) |
| 110 | + } |
| 111 | + if !r.CompletedAt.IsZero() { |
| 112 | + out.CompletedAt = r.CompletedAt.UTC().Format(time.RFC3339Nano) |
| 113 | + } |
| 114 | + return json.Marshal(out) |
| 115 | +} |
| 116 | + |
| 117 | +type StatusResponse struct { |
| 118 | + Status string `json:"status"` |
| 119 | + Conclusion *string `json:"conclusion"` |
| 120 | + RunStatus string `json:"run_status,omitempty"` |
| 121 | + RunConclusion string `json:"run_conclusion,omitempty"` |
| 122 | + NextToken string `json:"next_token,omitempty"` |
| 123 | + NextTokenExpiresAt time.Time `json:"next_token_expires_at,omitempty"` |
| 124 | +} |
| 125 | + |
| 126 | +type LogRequest struct { |
| 127 | + Seq int32 `json:"seq"` |
| 128 | + Chunk []byte `json:"-"` |
| 129 | + StepID int64 `json:"step_id,omitempty"` |
| 130 | +} |
| 131 | + |
| 132 | +func (r LogRequest) MarshalJSON() ([]byte, error) { |
| 133 | + type wire struct { |
| 134 | + Seq int32 `json:"seq"` |
| 135 | + Chunk string `json:"chunk"` |
| 136 | + StepID int64 `json:"step_id,omitempty"` |
| 137 | + } |
| 138 | + return json.Marshal(wire{ |
| 139 | + Seq: r.Seq, |
| 140 | + Chunk: base64.StdEncoding.EncodeToString(r.Chunk), |
| 141 | + StepID: r.StepID, |
| 142 | + }) |
| 143 | +} |
| 144 | + |
| 145 | +type LogResponse struct { |
| 146 | + Accepted bool `json:"accepted"` |
| 147 | + NextToken string `json:"next_token"` |
| 148 | + NextTokenExpiresAt time.Time `json:"next_token_expires_at"` |
| 149 | +} |
| 150 | + |
| 151 | +type CancelCheckResponse struct { |
| 152 | + Cancelled bool `json:"cancelled"` |
| 153 | + NextToken string `json:"next_token"` |
| 154 | + NextTokenExpiresAt time.Time `json:"next_token_expires_at"` |
| 155 | +} |
| 156 | + |
| 157 | +func (c *Client) Heartbeat(ctx context.Context, req HeartbeatRequest) (*Claim, error) { |
| 158 | + var claim Claim |
| 159 | + status, err := c.do(ctx, http.MethodPost, "/api/v1/runners/heartbeat", c.runnerToken, req, &claim) |
| 160 | + if err != nil { |
| 161 | + return nil, err |
| 162 | + } |
| 163 | + if status == http.StatusNoContent { |
| 164 | + return nil, nil |
| 165 | + } |
| 166 | + return &claim, nil |
| 167 | +} |
| 168 | + |
| 169 | +func (c *Client) UpdateStatus(ctx context.Context, jobID int64, token string, req StatusRequest) (StatusResponse, error) { |
| 170 | + var out StatusResponse |
| 171 | + _, err := c.do(ctx, http.MethodPost, jobPath(jobID, "status"), token, req, &out) |
| 172 | + return out, err |
| 173 | +} |
| 174 | + |
| 175 | +func (c *Client) AppendLog(ctx context.Context, jobID int64, token string, req LogRequest) (LogResponse, error) { |
| 176 | + var out LogResponse |
| 177 | + _, err := c.do(ctx, http.MethodPost, jobPath(jobID, "logs"), token, req, &out) |
| 178 | + return out, err |
| 179 | +} |
| 180 | + |
| 181 | +func (c *Client) CancelCheck(ctx context.Context, jobID int64, token string) (CancelCheckResponse, error) { |
| 182 | + var out CancelCheckResponse |
| 183 | + _, err := c.do(ctx, http.MethodPost, jobPath(jobID, "cancel-check"), token, map[string]string{}, &out) |
| 184 | + return out, err |
| 185 | +} |
| 186 | + |
| 187 | +func jobPath(jobID int64, suffix string) string { |
| 188 | + return "/api/v1/jobs/" + strconv.FormatInt(jobID, 10) + "/" + suffix |
| 189 | +} |
| 190 | + |
| 191 | +func (c *Client) do(ctx context.Context, method, path, bearer string, body, out any) (int, error) { |
| 192 | + var r io.Reader |
| 193 | + if body != nil { |
| 194 | + var buf bytes.Buffer |
| 195 | + if err := json.NewEncoder(&buf).Encode(body); err != nil { |
| 196 | + return 0, fmt.Errorf("runner api: encode %s %s: %w", method, path, err) |
| 197 | + } |
| 198 | + r = &buf |
| 199 | + } |
| 200 | + u := c.base.ResolveReference(&url.URL{Path: path}) |
| 201 | + req, err := http.NewRequestWithContext(ctx, method, u.String(), r) |
| 202 | + if err != nil { |
| 203 | + return 0, err |
| 204 | + } |
| 205 | + req.Header.Set("Accept", "application/json") |
| 206 | + if body != nil { |
| 207 | + req.Header.Set("Content-Type", "application/json") |
| 208 | + } |
| 209 | + if strings.TrimSpace(bearer) != "" { |
| 210 | + req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(bearer)) |
| 211 | + } |
| 212 | + resp, err := c.http.Do(req) |
| 213 | + if err != nil { |
| 214 | + return 0, fmt.Errorf("runner api: %s %s: %w", method, path, err) |
| 215 | + } |
| 216 | + defer resp.Body.Close() |
| 217 | + if resp.StatusCode == http.StatusNoContent { |
| 218 | + return resp.StatusCode, nil |
| 219 | + } |
| 220 | + if resp.StatusCode < 200 || resp.StatusCode > 299 { |
| 221 | + msg, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) |
| 222 | + return resp.StatusCode, fmt.Errorf("runner api: %s %s returned %d: %s", method, path, resp.StatusCode, strings.TrimSpace(string(msg))) |
| 223 | + } |
| 224 | + if out == nil { |
| 225 | + return resp.StatusCode, nil |
| 226 | + } |
| 227 | + if err := json.NewDecoder(resp.Body).Decode(out); err != nil { |
| 228 | + return resp.StatusCode, fmt.Errorf("runner api: decode %s %s: %w", method, path, err) |
| 229 | + } |
| 230 | + return resp.StatusCode, nil |
| 231 | +} |