340 lines
10 KiB
Go
340 lines
10 KiB
Go
// Package transport is the HTTP client behind atlassian/jira and
|
|||
|
|
// atlassian/confluence: authentication, TLS/proxy setup, redirect
|
||
|
|
// hardening, retry with exponential backoff on 5xx and connection errors,
|
||
|
|
// 429 handling through a shared adaptive throttle that honours
|
||
|
|
// Retry-After, a fixed pause after every response, startAt/maxResults
|
||
|
|
// pagination and streamed file downloads. It knows nothing about Jira or
|
||
|
|
// Confluence payloads.
|
||
|
|
//
|
||
|
|
// It merges the three clients that existed before (yabaratla's and
|
||
|
|
// yareco's internal/jira, yamcp's atlassian/httpclient); see the
|
||
|
|
// repository's README for which behaviour came from where.
|
||
|
|
package transport
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"context"
|
||
|
|
"crypto/tls"
|
||
|
|
"crypto/x509"
|
||
|
|
"encoding/json"
|
||
|
|
"errors"
|
||
|
|
"fmt"
|
||
|
|
"io"
|
||
|
|
"log/slog"
|
||
|
|
"net/http"
|
||
|
|
"net/url"
|
||
|
|
"os"
|
||
|
|
"strconv"
|
||
|
|
"strings"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"yetano.dev/yetano/yetano-clients/atlassian"
|
||
|
|
)
|
||
|
|
|
||
|
|
// retryableStatus lists transient HTTP status codes worth retrying.
|
||
|
|
var retryableStatus = map[int]bool{500: true, 502: true, 503: true, 504: true}
|
||
|
|
|
||
|
|
// Client is safe for concurrent use; all goroutines share one throttle.
|
||
|
|
type Client struct {
|
||
|
|
http *http.Client
|
||
|
|
download *http.Client
|
||
|
|
baseURL string
|
||
|
|
auth atlassian.Auth
|
||
|
|
maxRetries int
|
||
|
|
retry429 bool
|
||
|
|
apiDelay time.Duration
|
||
|
|
maxBody int64
|
||
|
|
throttle *throttle
|
||
|
|
log *slog.Logger
|
||
|
|
sleep func(ctx context.Context, d time.Duration) error
|
||
|
|
}
|
||
|
|
|
||
|
|
// New builds a Client. It fails only on a bad CA file or proxy URL; it
|
||
|
|
// never sends a request.
|
||
|
|
func New(o atlassian.Options) (*Client, error) {
|
||
|
|
tlsConfig := &tls.Config{InsecureSkipVerify: o.TLS.InsecureSkipVerify} //nolint:gosec // explicit, caller-controlled opt-in
|
||
|
|
if o.TLS.CAFile != "" {
|
||
|
|
pemData, err := os.ReadFile(o.TLS.CAFile)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("%w: reading CA file %s: %w", atlassian.ErrTLSConfig, o.TLS.CAFile, err)
|
||
|
|
}
|
||
|
|
pool := x509.NewCertPool()
|
||
|
|
if !pool.AppendCertsFromPEM(pemData) {
|
||
|
|
return nil, fmt.Errorf("%w: CA file %s contains no valid PEM certificates", atlassian.ErrTLSConfig, o.TLS.CAFile)
|
||
|
|
}
|
||
|
|
tlsConfig.RootCAs = pool
|
||
|
|
}
|
||
|
|
|
||
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||
|
|
transport.TLSClientConfig = tlsConfig
|
||
|
|
if o.ProxyURL != "" {
|
||
|
|
proxyURL, err := url.Parse(o.ProxyURL)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("parsing proxy URL: %w", err)
|
||
|
|
}
|
||
|
|
transport.Proxy = http.ProxyURL(proxyURL)
|
||
|
|
}
|
||
|
|
|
||
|
|
if o.MaxRetries < 1 {
|
||
|
|
o.MaxRetries = 1
|
||
|
|
}
|
||
|
|
if o.Logger == nil {
|
||
|
|
o.Logger = slog.Default()
|
||
|
|
}
|
||
|
|
base := strings.TrimRight(o.BaseURL, "/")
|
||
|
|
|
||
|
|
return &Client{
|
||
|
|
http: &http.Client{Transport: transport, Timeout: o.Timeout, CheckRedirect: checkRedirect},
|
||
|
|
download: &http.Client{Transport: transport, Timeout: o.DownloadTimeout, CheckRedirect: checkRedirect},
|
||
|
|
baseURL: base,
|
||
|
|
auth: o.Auth,
|
||
|
|
maxRetries: o.MaxRetries,
|
||
|
|
retry429: !o.DisableRateLimitRetry,
|
||
|
|
apiDelay: o.APIDelay,
|
||
|
|
maxBody: o.MaxResponseBytes,
|
||
|
|
throttle: newThrottle(o.Logger),
|
||
|
|
log: o.Logger,
|
||
|
|
sleep: sleepCtx,
|
||
|
|
}, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// checkRedirect drops credentials on any redirect to another host, so a
|
||
|
|
// misconfigured or malicious redirect can never carry them to a third
|
||
|
|
// party (net/http alone keeps them for subdomains). Same-host redirects,
|
||
|
|
// e.g. http -> https, keep them.
|
||
|
|
func checkRedirect(req *http.Request, via []*http.Request) error {
|
||
|
|
if len(via) >= 10 {
|
||
|
|
return errors.New("stopped after 10 redirects")
|
||
|
|
}
|
||
|
|
if req.URL.Host != via[0].URL.Host {
|
||
|
|
req.Header.Del("Authorization")
|
||
|
|
req.Header.Del("Cookie")
|
||
|
|
}
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// SetSleep replaces the wait function (backoff, Retry-After, throttle,
|
||
|
|
// APIDelay) -- for tests that must not really wait.
|
||
|
|
func (c *Client) SetSleep(f func(ctx context.Context, d time.Duration) error) { c.sleep = f }
|
||
|
|
|
||
|
|
// BaseURL is the site root without trailing slash.
|
||
|
|
func (c *Client) BaseURL() string { return c.baseURL }
|
||
|
|
|
||
|
|
// HasCredentials reports whether any credentials are configured.
|
||
|
|
func (c *Client) HasCredentials() bool { return c.auth.IsSet() }
|
||
|
|
|
||
|
|
// Close releases idle connections.
|
||
|
|
func (c *Client) Close() {
|
||
|
|
c.http.CloseIdleConnections()
|
||
|
|
c.download.CloseIdleConnections()
|
||
|
|
}
|
||
|
|
|
||
|
|
// Do executes one logical request against BaseURL+path and returns the
|
||
|
|
// JSON response body ("{}" for an empty one). body, if non-nil, is sent
|
||
|
|
// as JSON.
|
||
|
|
func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body any) (json.RawMessage, error) {
|
||
|
|
fullURL := c.baseURL + path
|
||
|
|
if len(query) > 0 {
|
||
|
|
fullURL += "?" + query.Encode()
|
||
|
|
}
|
||
|
|
|
||
|
|
var bodyBytes []byte
|
||
|
|
if body != nil {
|
||
|
|
b, err := json.Marshal(body)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("%w: encoding request body: %v", atlassian.ErrInvalidArgument, err)
|
||
|
|
}
|
||
|
|
bodyBytes = b
|
||
|
|
}
|
||
|
|
|
||
|
|
var lastErr error
|
||
|
|
rateLimited := 0
|
||
|
|
for attempt := 1; attempt <= c.maxRetries; attempt++ {
|
||
|
|
var reader io.Reader
|
||
|
|
if bodyBytes != nil {
|
||
|
|
reader = bytes.NewReader(bodyBytes)
|
||
|
|
}
|
||
|
|
req, err := http.NewRequestWithContext(ctx, method, fullURL, reader)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("%w: %v", atlassian.ErrInvalidArgument, err)
|
||
|
|
}
|
||
|
|
req.Header.Set("Accept", "application/json")
|
||
|
|
if bodyBytes != nil {
|
||
|
|
req.Header.Set("Content-Type", "application/json")
|
||
|
|
}
|
||
|
|
c.auth.Apply(req)
|
||
|
|
|
||
|
|
if err := c.throttle.acquire(ctx, c.sleep); err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
resp, err := c.http.Do(req)
|
||
|
|
if err != nil {
|
||
|
|
if ctx.Err() != nil {
|
||
|
|
return nil, ctx.Err()
|
||
|
|
}
|
||
|
|
lastErr = fmt.Errorf("%s %s: %w", method, path, err)
|
||
|
|
if attempt == c.maxRetries {
|
||
|
|
return nil, lastErr
|
||
|
|
}
|
||
|
|
c.log.Warn("atlassian connection error, retrying", "attempt", attempt, "max", c.maxRetries, "method", method, "path", path, "err", err)
|
||
|
|
if err := c.sleep(ctx, backoff(attempt, 30)); err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
data, readErr := c.readBody(resp.Body)
|
||
|
|
resp.Body.Close()
|
||
|
|
if errors.Is(readErr, atlassian.ErrResponseTooLarge) {
|
||
|
|
return nil, fmt.Errorf("%s %s: %w (limit %d bytes)", method, path, readErr, c.maxBody)
|
||
|
|
}
|
||
|
|
if err := c.sleep(ctx, c.apiDelay); err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
if readErr != nil {
|
||
|
|
lastErr = fmt.Errorf("%s %s: reading response: %w", method, path, readErr)
|
||
|
|
if attempt == c.maxRetries {
|
||
|
|
return nil, lastErr
|
||
|
|
}
|
||
|
|
if err := c.sleep(ctx, backoff(attempt, 30)); err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
switch {
|
||
|
|
case resp.StatusCode >= 200 && resp.StatusCode < 300:
|
||
|
|
c.throttle.succeeded()
|
||
|
|
if len(bytes.TrimSpace(data)) == 0 {
|
||
|
|
return json.RawMessage("{}"), nil
|
||
|
|
}
|
||
|
|
if !json.Valid(data) {
|
||
|
|
return nil, fmt.Errorf("%s %s: HTTP %d, Content-Type %q: %w", method, path, resp.StatusCode, resp.Header.Get("Content-Type"), atlassian.ErrNotJSON)
|
||
|
|
}
|
||
|
|
return json.RawMessage(data), nil
|
||
|
|
|
||
|
|
case resp.StatusCode == http.StatusTooManyRequests && c.retry429:
|
||
|
|
// Being throttled is not a failure: it doesn't use up
|
||
|
|
// MaxRetries, only the separate maxRateLimitRetries budget.
|
||
|
|
rateLimited++
|
||
|
|
if rateLimited > maxRateLimitRetries {
|
||
|
|
return nil, &atlassian.APIError{StatusCode: resp.StatusCode, Method: method, Path: path, Body: fmt.Sprintf("still rate limited after %d retries", maxRateLimitRetries)}
|
||
|
|
}
|
||
|
|
c.throttle.rateLimited(retryAfter(resp.Header, rateLimited, time.Now()))
|
||
|
|
attempt--
|
||
|
|
continue
|
||
|
|
|
||
|
|
case retryableStatus[resp.StatusCode]:
|
||
|
|
lastErr = &atlassian.APIError{StatusCode: resp.StatusCode, Method: method, Path: path, Body: string(data)}
|
||
|
|
if attempt == c.maxRetries {
|
||
|
|
return nil, lastErr
|
||
|
|
}
|
||
|
|
c.log.Warn("atlassian server error, retrying", "attempt", attempt, "max", c.maxRetries, "method", method, "path", path, "status", resp.StatusCode)
|
||
|
|
if err := c.sleep(ctx, backoff(attempt, 30)); err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
continue
|
||
|
|
|
||
|
|
default:
|
||
|
|
return nil, &atlassian.APIError{StatusCode: resp.StatusCode, Method: method, Path: path, Body: string(data)}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if lastErr != nil {
|
||
|
|
return nil, lastErr
|
||
|
|
}
|
||
|
|
return nil, fmt.Errorf("%s %s: max retries exceeded", method, path)
|
||
|
|
}
|
||
|
|
|
||
|
|
func (c *Client) readBody(r io.Reader) ([]byte, error) {
|
||
|
|
if c.maxBody <= 0 {
|
||
|
|
return io.ReadAll(r)
|
||
|
|
}
|
||
|
|
data, err := io.ReadAll(io.LimitReader(r, c.maxBody+1))
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
if int64(len(data)) > c.maxBody {
|
||
|
|
return nil, atlassian.ErrResponseTooLarge
|
||
|
|
}
|
||
|
|
return data, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// backoff returns min(2^attempt, capSeconds) seconds.
|
||
|
|
func backoff(attempt, capSeconds int) time.Duration {
|
||
|
|
d := time.Duration(1) << uint(attempt) * time.Second
|
||
|
|
if limit := time.Duration(capSeconds) * time.Second; d > limit {
|
||
|
|
d = limit
|
||
|
|
}
|
||
|
|
return d
|
||
|
|
}
|
||
|
|
|
||
|
|
func sleepCtx(ctx context.Context, d time.Duration) error {
|
||
|
|
if d <= 0 {
|
||
|
|
return ctx.Err()
|
||
|
|
}
|
||
|
|
t := time.NewTimer(d)
|
||
|
|
defer t.Stop()
|
||
|
|
select {
|
||
|
|
case <-ctx.Done():
|
||
|
|
return ctx.Err()
|
||
|
|
case <-t.C:
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Paginate walks a classic startAt/maxResults/{isLast|total} listing and
|
||
|
|
// returns every element of the itemsKey array ("values" for most
|
||
|
|
// endpoints, "comments" for issue comments) across all pages. It advances
|
||
|
|
// by the number of items actually returned, because Jira may cap
|
||
|
|
// maxResults below what was asked for.
|
||
|
|
func (c *Client) Paginate(ctx context.Context, path string, params url.Values, itemsKey string, pageSize int) ([]json.RawMessage, error) {
|
||
|
|
var all []json.RawMessage
|
||
|
|
start := 0
|
||
|
|
for {
|
||
|
|
p := CloneValues(params)
|
||
|
|
p.Set("startAt", strconv.Itoa(start))
|
||
|
|
p.Set("maxResults", strconv.Itoa(pageSize))
|
||
|
|
|
||
|
|
raw, err := c.Do(ctx, http.MethodGet, path, p, nil)
|
||
|
|
if err != nil {
|
||
|
|
return all, err
|
||
|
|
}
|
||
|
|
var page map[string]json.RawMessage
|
||
|
|
if err := json.Unmarshal(raw, &page); err != nil {
|
||
|
|
return all, fmt.Errorf("GET %s: %w", path, err)
|
||
|
|
}
|
||
|
|
var items []json.RawMessage
|
||
|
|
if v, ok := page[itemsKey]; ok {
|
||
|
|
if err := json.Unmarshal(v, &items); err != nil {
|
||
|
|
return all, fmt.Errorf("GET %s: %s: %w", path, itemsKey, err)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
all = append(all, items...)
|
||
|
|
|
||
|
|
var isLast *bool
|
||
|
|
var total *int
|
||
|
|
if v, ok := page["isLast"]; ok {
|
||
|
|
_ = json.Unmarshal(v, &isLast)
|
||
|
|
}
|
||
|
|
if v, ok := page["total"]; ok {
|
||
|
|
_ = json.Unmarshal(v, &total)
|
||
|
|
}
|
||
|
|
if isLast != nil && *isLast {
|
||
|
|
return all, nil
|
||
|
|
}
|
||
|
|
start += len(items)
|
||
|
|
if (total != nil && start >= *total) || len(items) == 0 {
|
||
|
|
return all, nil
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// CloneValues deep-copies v (nil gives an empty map).
|
||
|
|
func CloneValues(v url.Values) url.Values {
|
||
|
|
out := url.Values{}
|
||
|
|
for k, vs := range v {
|
||
|
|
out[k] = append([]string(nil), vs...)
|
||
|
|
}
|
||
|
|
return out
|
||
|
|
}
|