-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient.go
More file actions
421 lines (366 loc) · 11.5 KB
/
client.go
File metadata and controls
421 lines (366 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package deploymentrecord
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"math"
"math/rand/v2"
"net/http"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/github/deployment-tracker/pkg/dtmetrics"
"golang.org/x/time/rate"
)
// ClientOption is a function that configures the Client.
type ClientOption func(*Client)
// validOrgPattern validates organization names (alphanumeric, hyphens,
// underscores).
var validOrgPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
// Client is an API client for posting deployment records.
type Client struct {
baseURL string
org string
httpClient *http.Client
retries int
apiToken string
transport *ghinstallation.Transport
requestThrottler *rate.Limiter
// rateLimitDeadline is a UnixNano timestamp shared across workers.
rateLimitDeadline atomic.Int64
}
// NewClient creates a new API client with the given base URL and
// organization. Returns an error if the base URL is not HTTPS for
// non-local hosts.
func NewClient(baseURL, org string, opts ...ClientOption) (*Client, error) {
// Check if URL is local (allowed to use HTTP)
isLocal := strings.HasPrefix(baseURL, "http://localhost") ||
strings.HasPrefix(baseURL, "http://127.0.0.1") ||
strings.Contains(baseURL, ".svc.cluster.local")
// Reject non-HTTPS URLs for non-local hosts
if strings.HasPrefix(baseURL, "http://") && !isLocal {
return nil, fmt.Errorf("insecure URL not allowed: %s (use HTTPS for non-local hosts)", baseURL)
}
// Add https:// prefix if no scheme is provided
if !strings.HasPrefix(baseURL, "https://") && !strings.HasPrefix(baseURL, "http://") {
baseURL = "https://" + baseURL
}
// Validate organization name to prevent URL injection
if !validOrgPattern.MatchString(org) {
return nil, fmt.Errorf("invalid organization name: %s (must be alphanumeric, hyphens, or underscores)", org)
}
c := &Client{
baseURL: baseURL,
org: org,
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
retries: 3,
// 3 req/sec (180 req/min) with burst of 20
requestThrottler: rate.NewLimiter(rate.Limit(3), 20),
}
for _, opt := range opts {
opt(c)
}
return c, nil
}
// WithTimeout sets the HTTP client timeout in seconds.
func WithTimeout(seconds int) ClientOption {
return func(c *Client) {
c.httpClient.Timeout = time.Duration(seconds) * time.Second
}
}
// WithRetries sets the number of retries for failed requests.
func WithRetries(retries int) ClientOption {
return func(c *Client) {
c.retries = retries
}
}
// WithAPIToken sets the API token for Bearer authentication.
func WithAPIToken(token string) ClientOption {
return func(c *Client) {
c.apiToken = token
}
}
// WithGHApp configures a GitHub app to use for authentication.
// If provided values are invalid, this will panic.
// If an API token is also set, the GitHub App will take precedence.
func WithGHApp(id, installID string, pkBytes []byte, pkPath string) ClientOption {
return func(c *Client) {
if len(pkBytes) > 0 && pkPath != "" {
panic("both GitHub App private key and private key path are set")
}
pid, err := strconv.Atoi(id)
if err != nil {
panic(err)
}
piid, err := strconv.Atoi(installID)
if err != nil {
panic(err)
}
if len(pkBytes) > 0 {
c.transport, err = ghinstallation.New(
http.DefaultTransport,
int64(pid),
int64(piid),
pkBytes)
} else {
c.transport, err = ghinstallation.NewKeyFromFile(
http.DefaultTransport,
int64(pid),
int64(piid),
pkPath)
}
if err != nil {
panic(err)
}
}
}
// WithRequestThrottler sets a custom rate limiter for API calls.
func WithRequestThrottler(rps float64, burst int) ClientOption {
return func(c *Client) {
c.requestThrottler = rate.NewLimiter(rate.Limit(rps), burst)
}
}
// ClientError represents a client error that can not be retried.
type ClientError struct {
err error
}
func (c *ClientError) Error() string {
return fmt.Sprintf("client_error: %s", c.err.Error())
}
func (c *ClientError) Unwrap() error {
return c.err
}
// NoArtifactError represents a 404 client response whose body indicates "no artifacts found".
type NoArtifactError struct {
err error
}
func (n *NoArtifactError) Error() string {
return fmt.Sprintf("no artifact found: %s", n.err.Error())
}
func (n *NoArtifactError) Unwrap() error {
return n.err
}
// PostOne posts a single deployment record to the GitHub deployment
// records API.
func (c *Client) PostOne(ctx context.Context, record *DeploymentRecord) error {
if record == nil {
return errors.New("record cannot be nil")
}
url := fmt.Sprintf("%s/orgs/%s/artifacts/metadata/deployment-record", c.baseURL, c.org)
body, err := json.Marshal(record)
if err != nil {
return fmt.Errorf("failed to marshal record: %w", err)
}
bodyReader := bytes.NewReader(body)
var lastErr error
// The first attempt is not a retry!
for attempt := range c.retries + 1 {
if err = waitForBackoff(ctx, attempt); err != nil {
return err
}
if err = c.waitForServerRateLimit(ctx); err != nil {
return err
}
if err = c.requestThrottler.Wait(ctx); err != nil {
return fmt.Errorf("request throttler wait failed: %w", err)
}
// Reset reader position for retries
bodyReader.Reset(body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bodyReader)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if c.transport != nil {
// Token is thread safe, so no need for external
// locking
tok, err := c.transport.Token(ctx)
if err != nil {
return fmt.Errorf("failed to get access token: %w", err)
}
req.Header.Set("Authorization", "Bearer "+tok)
} else if c.apiToken != "" {
req.Header.Set("Authorization", "Bearer "+c.apiToken)
}
req.Header.Set("User-Agent", "GitHub-Deployment-Tracker")
start := time.Now()
// nolint: gosec
resp, err := c.httpClient.Do(req)
dur := time.Since(start)
dtmetrics.PostDeploymentRecordTimer.Observe(dur.Seconds())
if err != nil {
lastErr = fmt.Errorf("post request failed: %w", err)
slog.Warn("recoverable error, re-trying",
"attempt", attempt,
"retries", c.retries,
"error", lastErr)
dtmetrics.PostDeploymentRecordSoftFail.Inc()
continue
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
// Drain and close response body to enable connection reuse
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
dtmetrics.PostDeploymentRecordOk.Inc()
return nil
}
// Drain and close response body to enable connection reuse by reading body for error logging
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
switch {
case resp.StatusCode == 404:
// No artifact found - do not retry
dtmetrics.PostDeploymentRecordNoAttestation.Inc()
slog.Debug("no artifact attestation found, no record created",
"attempt", attempt,
"status_code", resp.StatusCode,
"container_name", record.Name,
"resp_msg", string(respBody),
"digest", record.Digest,
)
return &NoArtifactError{err: fmt.Errorf("no attestation found for %s", record.Digest)}
case resp.StatusCode >= 400 && resp.StatusCode < 500:
// Check headers that indicate rate limiting
if resp.Header.Get("Retry-After") != "" || resp.Header.Get("X-Ratelimit-Remaining") == "0" {
retryDelay := parseRateLimitDelay(resp)
c.setRetryAfter(retryDelay)
dtmetrics.PostDeploymentRecordRateLimited.Inc()
slog.Warn("rate limited, retrying",
"attempt", attempt,
"status_code", resp.StatusCode,
"retry-after", resp.Header.Get("Retry-After"),
"x-ratelimit-remaining", resp.Header.Get("X-Ratelimit-Remaining"),
"retry_delay", retryDelay.Seconds(),
"container_name", record.Name,
"resp_msg", string(respBody),
)
lastErr = fmt.Errorf("rate limited, attempt %d", attempt)
continue
}
// Don't retry non rate limiting client errors
dtmetrics.PostDeploymentRecordClientError.Inc()
slog.Warn("client error, aborting",
"attempt", attempt,
"status_code", resp.StatusCode,
"container_name", record.Name,
"resp_msg", string(respBody),
)
return &ClientError{err: fmt.Errorf("unexpected client err with status code %d", resp.StatusCode)}
default:
// Retry with backoff
dtmetrics.PostDeploymentRecordSoftFail.Inc()
slog.Debug("retriable error",
"attempt", attempt,
"status_code", resp.StatusCode,
"container_name", record.Name,
"resp_msg", string(respBody),
)
lastErr = fmt.Errorf("server error, attempt %d", attempt)
}
}
dtmetrics.PostDeploymentRecordHardFail.Inc()
slog.Error("all retries exhausted",
"count", c.retries,
"error", lastErr,
"container_name", record.Name,
)
return fmt.Errorf("all retries exhausted: %w", lastErr)
}
// waitForServerRateLimit blocks until the global server rate limit backoff has elapsed.
// All workers sharing this client observe the same deadline.
func (c *Client) waitForServerRateLimit(ctx context.Context) error {
deadline := c.rateLimitDeadline.Load()
delay := time.Until(time.Unix(0, deadline))
if delay <= 0 {
return nil
}
slog.Info("waiting for server rate limit backoff",
"delay", delay.Round(time.Millisecond),
)
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return fmt.Errorf("context cancelled during server rate limit wait: %w", ctx.Err())
}
}
// setRetryAfter records a global backoff deadline.
// Ensures deadline can only be extended, not shortened.
func (c *Client) setRetryAfter(d time.Duration) {
newDeadline := time.Now().Add(d).UnixNano()
for {
current := c.rateLimitDeadline.Load()
if newDeadline <= current {
return
}
if c.rateLimitDeadline.CompareAndSwap(current, newDeadline) {
return
}
}
}
// parseRateLimitDelay extracts the backoff duration from a rate-limit response:
// Return largest delay from header options.
// If no headers are set, default to 1 minute.
func parseRateLimitDelay(resp *http.Response) time.Duration {
// GitHub docs show Retry-After header will always be an int
var retryAfterDelay *time.Duration
if ra := resp.Header.Get("Retry-After"); ra != "" {
if seconds, err := strconv.Atoi(ra); err == nil {
rad := time.Duration(seconds) * time.Second
retryAfterDelay = &rad
}
}
var rateLimitResetDelay *time.Duration
if resp.Header.Get("X-Ratelimit-Remaining") == "0" {
if resetStr := resp.Header.Get("X-Ratelimit-Reset"); resetStr != "" {
if epoch, err := strconv.ParseInt(resetStr, 10, 64); err == nil {
if d := time.Until(time.Unix(epoch, 0)); d > 0 {
rateLimitResetDelay = &d
}
}
}
}
switch {
case retryAfterDelay != nil && rateLimitResetDelay != nil:
return max(*retryAfterDelay, *rateLimitResetDelay)
case retryAfterDelay != nil:
return *retryAfterDelay
case rateLimitResetDelay != nil:
return *rateLimitResetDelay
default:
return time.Minute
}
}
func waitForBackoff(ctx context.Context, attempt int) error {
if attempt > 0 {
backoff := time.Duration(math.Pow(2,
float64(attempt))) * 100 * time.Millisecond
//nolint:gosec
jitter := time.Duration(rand.Int64N(50)) * time.Millisecond
delay := backoff + jitter
if delay > 5*time.Second {
delay = 5 * time.Second
}
// Wait with context cancellation support
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-timer.C:
case <-ctx.Done():
return fmt.Errorf("context cancelled during retry backoff: %w", ctx.Err())
}
}
return nil
}