Shared Atlassian clients: atlassian/jira and atlassian/confluence
New library module yetano.dev/yetano/yetano-clients (owner decision 2026-11-01) replacing the three own Jira clients in yareco, yabaratla and yamcp: - atlassian: Options, Auth (api_token, basic, bearer/pat, cookie), Deployment (Cloud/Data Center), TLS, APIError and sentinel errors. - atlassian/internal/transport: retry with backoff on 5xx/connection errors, shared adaptive 429 throttle honouring Retry-After (from yabaratla/yareco), CA file, proxy, cross-host redirect hardening, response cap (from yamcp), startAt pagination, file downloads. - atlassian/jira: typed reads (projects, versions, fields, issues, comments, changelog, editmeta, transitions), JQL search on Cloud (/search/jql) and Data Center, classic search pages, issue writes, ADF/plain-text bodies per deployment, custom-field helpers. - atlassian/confluence: small content API client (CQL search, pages, spaces, current user, create/update page with version check, comment, label), taken over from yamcp. Standard library only; tests against httptest servers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
6a97dbd4c6
24 files changed
+3524
No files matched your search
@@ -0,0 +1,111 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errRateLimited = errors.New("rate limited (429)")
|
||||
|
||||
// DownloadFile streams fileURL -- absolute, or a path starting with "/"
|
||||
// resolved against BaseURL -- to dest, creating dest's directory. It
|
||||
// retries like Do (MaxRetries for errors, the separate budget for 429s)
|
||||
// and removes a partial file before every retry and after a failure.
|
||||
// Credentials go with the request itself -- the caller passes URLs the
|
||||
// API handed out (attachment "content" links) -- but, as everywhere, not
|
||||
// along a redirect to another host (e.g. a signed media URL).
|
||||
func (c *Client) DownloadFile(ctx context.Context, fileURL, dest string) error {
|
||||
full := fileURL
|
||||
if strings.HasPrefix(fileURL, "/") {
|
||||
full = c.baseURL + fileURL
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
rateLimited := 0
|
||||
for attempt := 1; attempt <= c.maxRetries; attempt++ {
|
||||
err := c.downloadOnce(ctx, full, dest, rateLimited+1)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
lastErr = err
|
||||
os.Remove(dest) //nolint:errcheck // best-effort cleanup of a partial download
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if errors.Is(err, errRateLimited) {
|
||||
if rateLimited++; rateLimited > maxRateLimitRetries {
|
||||
break
|
||||
}
|
||||
attempt-- // throttling doesn't use up MaxRetries, see Do
|
||||
continue
|
||||
}
|
||||
if attempt < c.maxRetries {
|
||||
c.log.Warn("atlassian download failed, retrying", "attempt", attempt, "max", c.maxRetries, "url", redactURL(full), "err", err)
|
||||
if err := c.sleep(ctx, backoff(attempt, 30)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("download failed after %d attempt(s): %w", c.maxRetries, lastErr)
|
||||
}
|
||||
|
||||
func (c *Client) downloadOnce(ctx context.Context, full, dest string, rateLimitAttempt int) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, full, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.auth.Apply(req)
|
||||
|
||||
if err := c.throttle.acquire(ctx, c.sleep); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.download.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusTooManyRequests && c.retry429 {
|
||||
c.throttle.rateLimited(retryAfter(resp.Header, rateLimitAttempt, time.Now()))
|
||||
return errRateLimited
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("GET %s: HTTP %d", redactURL(full), resp.StatusCode)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.Create(dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(f, resp.Body); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.throttle.succeeded()
|
||||
return nil
|
||||
}
|
||||
|
||||
// redactURL drops the query, which on signed media URLs is a credential.
|
||||
func redactURL(s string) string {
|
||||
u, err := url.Parse(s)
|
||||
if err != nil {
|
||||
return "(unparsable URL)"
|
||||
}
|
||||
u.RawQuery = ""
|
||||
u.User = nil
|
||||
return u.String()
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Adaptive throttling across all goroutines sharing one Client: a 429
|
||||
// pauses every request until Retry-After and widens a shared minimum gap
|
||||
// between request starts (multiplicative increase); each success narrows
|
||||
// it again (slow decrease) until it is back to zero, i.e. only APIDelay
|
||||
// applies. With parallel workers a 429 that only slept its own request
|
||||
// would leave the others hammering the API.
|
||||
const (
|
||||
minInterval = 100 * time.Millisecond
|
||||
maxInterval = 10 * time.Second
|
||||
recoverFactor = 0.95
|
||||
maxRateLimitRetries = 10
|
||||
)
|
||||
|
||||
type throttle struct {
|
||||
mu sync.Mutex
|
||||
interval time.Duration // shared minimum gap between request starts
|
||||
next time.Time // earliest start for the next request
|
||||
pauseUntil time.Time // global pause after a 429
|
||||
|
||||
now func() time.Time
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func newThrottle(log *slog.Logger) *throttle {
|
||||
return &throttle{now: time.Now, log: log}
|
||||
}
|
||||
|
||||
// acquire blocks until this request may start, or ctx ends.
|
||||
func (t *throttle) acquire(ctx context.Context, sleep func(context.Context, time.Duration) error) error {
|
||||
t.mu.Lock()
|
||||
at := t.now()
|
||||
if t.pauseUntil.After(at) {
|
||||
at = t.pauseUntil
|
||||
}
|
||||
if t.next.After(at) {
|
||||
at = t.next
|
||||
}
|
||||
t.next = at.Add(t.interval)
|
||||
wait := at.Sub(t.now())
|
||||
t.mu.Unlock()
|
||||
|
||||
if wait > 0 {
|
||||
return sleep(ctx, wait)
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// rateLimited records a 429: pause everyone for wait and slow down.
|
||||
// Requests that hit the same burst while the pause is already active
|
||||
// don't slow down any further, so N parallel 429s count as one signal.
|
||||
func (t *throttle) rateLimited(wait time.Duration) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
now := t.now()
|
||||
if now.Before(t.pauseUntil) {
|
||||
if until := now.Add(wait); until.After(t.pauseUntil) {
|
||||
t.pauseUntil = until
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
t.pauseUntil = now.Add(wait)
|
||||
t.interval = min(max(t.interval*2, minInterval), maxInterval)
|
||||
t.log.Warn("atlassian rate limited (429)", "pause", wait, "interval", t.interval)
|
||||
}
|
||||
|
||||
// succeeded narrows the gap again after a successful response.
|
||||
func (t *throttle) succeeded() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
if t.interval == 0 {
|
||||
return
|
||||
}
|
||||
t.interval = time.Duration(float64(t.interval) * recoverFactor)
|
||||
if t.interval < minInterval {
|
||||
t.interval = 0
|
||||
t.log.Info("atlassian rate limit recovered")
|
||||
}
|
||||
}
|
||||
|
||||
// retryAfter returns how long a 429 response asks us to wait: the
|
||||
// Retry-After header (seconds or HTTP date), else exponential backoff.
|
||||
func retryAfter(header http.Header, attempt int, now time.Time) time.Duration {
|
||||
if ra := header.Get("Retry-After"); ra != "" {
|
||||
if secs, err := strconv.Atoi(ra); err == nil && secs >= 0 {
|
||||
return time.Duration(secs) * time.Second
|
||||
}
|
||||
if t, err := http.ParseTime(ra); err == nil {
|
||||
if d := t.Sub(now); d > 0 {
|
||||
return d
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
return backoff(attempt, 60)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeClock drives the throttle without real waiting.
|
||||
type fakeClock struct {
|
||||
mu sync.Mutex
|
||||
t time.Time
|
||||
slept time.Duration
|
||||
}
|
||||
|
||||
func (c *fakeClock) now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.t
|
||||
}
|
||||
|
||||
func (c *fakeClock) sleep(_ context.Context, d time.Duration) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.t = c.t.Add(d)
|
||||
c.slept += d
|
||||
return nil
|
||||
}
|
||||
|
||||
func newFakeThrottle() (*throttle, *fakeClock) {
|
||||
clk := &fakeClock{t: time.Date(2026, 10, 14, 3, 0, 0, 0, time.UTC)}
|
||||
th := newThrottle(quietLogger())
|
||||
th.now = clk.now
|
||||
return th, clk
|
||||
}
|
||||
|
||||
func TestThrottleUnthrottledByDefault(t *testing.T) {
|
||||
th, clk := newFakeThrottle()
|
||||
for i := 0; i < 5; i++ {
|
||||
if err := th.acquire(context.Background(), clk.sleep); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if clk.slept != 0 {
|
||||
t.Errorf("slept %s without any 429, want 0", clk.slept)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThrottleRateLimitPausesAndSpacesRequests(t *testing.T) {
|
||||
th, clk := newFakeThrottle()
|
||||
th.rateLimited(5 * time.Second)
|
||||
if th.interval != minInterval {
|
||||
t.Fatalf("interval = %s, want %s", th.interval, minInterval)
|
||||
}
|
||||
_ = th.acquire(context.Background(), clk.sleep) // waits out the pause
|
||||
_ = th.acquire(context.Background(), clk.sleep) // then one interval later
|
||||
if want := 5*time.Second + minInterval; clk.slept != want {
|
||||
t.Errorf("slept %s, want %s", clk.slept, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThrottleConcurrent429sCountOnce(t *testing.T) {
|
||||
th, _ := newFakeThrottle()
|
||||
th.rateLimited(time.Second)
|
||||
th.rateLimited(time.Second)
|
||||
th.rateLimited(2 * time.Second)
|
||||
if th.interval != minInterval {
|
||||
t.Errorf("interval = %s, want %s (one slowdown per burst)", th.interval, minInterval)
|
||||
}
|
||||
if want := th.now().Add(2 * time.Second); !th.pauseUntil.Equal(want) {
|
||||
t.Errorf("pauseUntil = %s, want the longest Retry-After %s", th.pauseUntil, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThrottleBacksOffAndRecovers(t *testing.T) {
|
||||
th, clk := newFakeThrottle()
|
||||
for i := 0; i < 20; i++ {
|
||||
th.rateLimited(0)
|
||||
_ = clk.sleep(context.Background(), time.Millisecond) // next 429 arrives after the (zero) pause
|
||||
}
|
||||
if th.interval != maxInterval {
|
||||
t.Fatalf("interval = %s, want capped at %s", th.interval, maxInterval)
|
||||
}
|
||||
for i := 0; i < 1000 && th.interval > 0; i++ {
|
||||
th.succeeded()
|
||||
}
|
||||
if th.interval != 0 {
|
||||
t.Errorf("interval = %s after many successes, want 0", th.interval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThrottleRespectsCancel(t *testing.T) {
|
||||
th, _ := newFakeThrottle()
|
||||
th.rateLimited(time.Hour)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := th.acquire(ctx, sleepCtx); err == nil {
|
||||
t.Error("acquire must return the context error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryAfter(t *testing.T) {
|
||||
now := time.Date(2026, 10, 14, 3, 0, 0, 0, time.UTC)
|
||||
h := http.Header{}
|
||||
h.Set("Retry-After", "7")
|
||||
if got := retryAfter(h, 1, now); got != 7*time.Second {
|
||||
t.Errorf("seconds: got %s", got)
|
||||
}
|
||||
h.Set("Retry-After", now.Add(30*time.Second).Format(http.TimeFormat))
|
||||
if got := retryAfter(h, 1, now); got != 30*time.Second {
|
||||
t.Errorf("http date: got %s", got)
|
||||
}
|
||||
if got := retryAfter(http.Header{}, 2, now); got != 4*time.Second {
|
||||
t.Errorf("fallback backoff: got %s", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"yetano.dev/yetano/yetano-clients/atlassian"
|
||||
)
|
||||
|
||||
func quietLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
|
||||
|
||||
// testClient starts h and returns a client against it that records
|
||||
// (instead of doing) every wait.
|
||||
func testClient(t *testing.T, h http.HandlerFunc, mod func(*atlassian.Options)) (*Client, *[]time.Duration) {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(h)
|
||||
t.Cleanup(srv.Close)
|
||||
o := atlassian.Options{BaseURL: srv.URL + "/", MaxRetries: 3, Logger: quietLogger(),
|
||||
Auth: atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@example.com", Password: "secret-token"}}
|
||||
if mod != nil {
|
||||
mod(&o)
|
||||
}
|
||||
c, err := New(o)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var slept []time.Duration
|
||||
c.SetSleep(func(ctx context.Context, d time.Duration) error {
|
||||
if d > 0 {
|
||||
mu.Lock()
|
||||
slept = append(slept, d)
|
||||
mu.Unlock()
|
||||
}
|
||||
return ctx.Err()
|
||||
})
|
||||
return c, &slept
|
||||
}
|
||||
|
||||
func get(c *Client, path string) error {
|
||||
_, err := c.Do(context.Background(), http.MethodGet, path, nil, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestRetryOn5xxThenSuccess(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
c, slept := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if calls.Add(1) < 3 {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"displayName":"Ada"}`)
|
||||
}, nil)
|
||||
raw, err := c.Do(context.Background(), http.MethodGet, "/rest/api/3/myself", nil, nil)
|
||||
if err != nil || !strings.Contains(string(raw), "Ada") || calls.Load() != 3 {
|
||||
t.Fatalf("got %s, %v after %d calls", raw, err, calls.Load())
|
||||
}
|
||||
if len(*slept) != 2 || (*slept)[0] != 2*time.Second || (*slept)[1] != 4*time.Second {
|
||||
t.Errorf("backoff = %v, want [2s 4s]", *slept)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryExhaustedReturnsAPIError(t *testing.T) {
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
fmt.Fprint(w, "down")
|
||||
}, nil)
|
||||
err := get(c, "/x")
|
||||
if atlassian.StatusOf(err) != http.StatusServiceUnavailable {
|
||||
t.Fatalf("err = %v, want APIError 503", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusHandling(t *testing.T) {
|
||||
cases := []struct {
|
||||
status int
|
||||
body string
|
||||
wantErr bool
|
||||
want string
|
||||
}{
|
||||
{200, `{"a":1}`, false, `{"a":1}`},
|
||||
{201, `{"id":"1"}`, false, `{"id":"1"}`},
|
||||
{204, ``, false, `{}`},
|
||||
{200, ``, false, `{}`},
|
||||
{200, `<html>login</html>`, true, ""},
|
||||
{400, `{"errorMessages":["bad jql"]}`, true, ""},
|
||||
{404, ``, true, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
var calls atomic.Int32
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.WriteHeader(tc.status)
|
||||
fmt.Fprint(w, tc.body)
|
||||
}, nil)
|
||||
raw, err := c.Do(context.Background(), http.MethodGet, "/x", nil, nil)
|
||||
if (err != nil) != tc.wantErr || (!tc.wantErr && string(raw) != tc.want) {
|
||||
t.Errorf("HTTP %d %q: got %s, %v", tc.status, tc.body, raw, err)
|
||||
}
|
||||
if tc.status >= 400 && calls.Load() != 1 {
|
||||
t.Errorf("HTTP %d retried %d times", tc.status, calls.Load())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNonJSONSuccessIsAnError(t *testing.T) {
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
fmt.Fprint(w, "<html>SSO</html>")
|
||||
}, nil)
|
||||
if err := get(c, "/x"); !errors.Is(err, atlassian.ErrNotJSON) {
|
||||
t.Fatalf("err = %v, want ErrNotJSON", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIErrorMessage(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
`{"errorMessages":["Issue does not exist"]}`: "Issue does not exist",
|
||||
`{"message":"No space"}`: "No space",
|
||||
`{"errors":{"summary":"required"}}`: "summary: required",
|
||||
``: "no additional detail from upstream",
|
||||
`plain text`: "plain text",
|
||||
}
|
||||
for body, want := range cases {
|
||||
if got := (&atlassian.APIError{StatusCode: 400, Body: body}).Message(); got != want {
|
||||
t.Errorf("Message(%q) = %q, want %q", body, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimitDoesNotUseRetriesAndHonoursRetryAfter(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
c, slept := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
// four 429s in a row -- more than MaxRetries (3)
|
||||
if calls.Add(1) <= 4 {
|
||||
w.Header().Set("Retry-After", "7")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{}`)
|
||||
}, nil)
|
||||
if err := get(c, "/x"); err != nil {
|
||||
t.Fatalf("429s must not exhaust MaxRetries: %v", err)
|
||||
}
|
||||
if calls.Load() != 5 || len(*slept) == 0 || (*slept)[0] < 6*time.Second {
|
||||
t.Errorf("calls = %d, waits = %v; want 5 calls, first wait about 7s (Retry-After)", calls.Load(), *slept)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimitBudget(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.Header().Set("Retry-After", "0")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
}, nil)
|
||||
if err := get(c, "/x"); atlassian.StatusOf(err) != 429 {
|
||||
t.Fatalf("err = %v, want 429 after the budget", err)
|
||||
}
|
||||
if got := calls.Load(); got != maxRateLimitRetries+1 {
|
||||
t.Errorf("calls = %d, want %d", got, maxRateLimitRetries+1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisableRateLimitRetry(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
}, func(o *atlassian.Options) { o.DisableRateLimitRetry = true })
|
||||
if err := get(c, "/x"); atlassian.StatusOf(err) != 429 || calls.Load() != 1 {
|
||||
t.Fatalf("err = %v after %d calls, want one 429", err, calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthApplied(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
auth atlassian.Auth
|
||||
check func(r *http.Request) bool
|
||||
}{
|
||||
{"api token", atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@x", Password: "tok"}, func(r *http.Request) bool {
|
||||
u, p, ok := r.BasicAuth()
|
||||
return ok && u == "e@x" && p == "tok"
|
||||
}},
|
||||
{"basic", atlassian.Auth{Type: atlassian.AuthBasic, Username: "u", Password: "p"}, func(r *http.Request) bool {
|
||||
u, p, ok := r.BasicAuth()
|
||||
return ok && u == "u" && p == "p"
|
||||
}},
|
||||
{"pat", atlassian.Auth{Type: atlassian.AuthPAT, Token: "pat"}, func(r *http.Request) bool {
|
||||
return r.Header.Get("Authorization") == "Bearer pat"
|
||||
}},
|
||||
{"bearer", atlassian.Auth{Type: atlassian.AuthBearer, Token: "b"}, func(r *http.Request) bool {
|
||||
return r.Header.Get("Authorization") == "Bearer b"
|
||||
}},
|
||||
{"cookie", atlassian.Auth{Type: atlassian.AuthCookie, Cookie: "s=1"}, func(r *http.Request) bool {
|
||||
return r.Header.Get("Cookie") == "s=1" && r.Header.Get("Authorization") == ""
|
||||
}},
|
||||
{"auto prefers basic over cookie", atlassian.Auth{Username: "u", Password: "p", Cookie: "s=1"}, func(r *http.Request) bool {
|
||||
_, _, ok := r.BasicAuth()
|
||||
return ok && r.Header.Get("Cookie") == ""
|
||||
}},
|
||||
{"api token without e-mail sends nothing", atlassian.Auth{Type: atlassian.AuthAPIToken, Password: "tok"}, func(r *http.Request) bool {
|
||||
return r.Header.Get("Authorization") == ""
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !tc.check(r) {
|
||||
t.Errorf("headers = %v", r.Header)
|
||||
}
|
||||
fmt.Fprint(w, `{}`)
|
||||
}, func(o *atlassian.Options) { o.Auth = tc.auth })
|
||||
if err := get(c, "/x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossHostRedirectDropsCredentials(t *testing.T) {
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" {
|
||||
t.Error("credentials followed a cross-host redirect")
|
||||
}
|
||||
fmt.Fprint(w, `{}`)
|
||||
}))
|
||||
defer other.Close()
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, other.URL+"/elsewhere", http.StatusFound)
|
||||
}, nil)
|
||||
if err := get(c, "/x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRejectsBadCAFile(t *testing.T) {
|
||||
bad := filepath.Join(t.TempDir(), "ca.pem")
|
||||
if err := os.WriteFile(bad, []byte("not a certificate"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, f := range []string{bad, filepath.Join(t.TempDir(), "missing.pem")} {
|
||||
if _, err := New(atlassian.Options{TLS: atlassian.TLS{CAFile: f}}); !errors.Is(err, atlassian.ErrTLSConfig) {
|
||||
t.Errorf("CA file %s: err = %v, want ErrTLSConfig", f, err)
|
||||
}
|
||||
}
|
||||
if _, err := New(atlassian.Options{ProxyURL: "://bad"}); err == nil {
|
||||
t.Error("bad proxy URL must be an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxResponseBytes(t *testing.T) {
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"a":"`+strings.Repeat("x", 100)+`"}`)
|
||||
}, func(o *atlassian.Options) { o.MaxResponseBytes = 50 })
|
||||
if err := get(c, "/x"); !errors.Is(err, atlassian.ErrResponseTooLarge) {
|
||||
t.Fatalf("err = %v, want ErrResponseTooLarge", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenNeverInError(t *testing.T) {
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}, nil)
|
||||
err := get(c, "/x")
|
||||
if atlassian.StatusOf(err) != 401 || strings.Contains(err.Error(), "secret-token") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextCancelStopsBackoff(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
c, err := New(atlassian.Options{BaseURL: srv.URL, MaxRetries: 5, Logger: quietLogger()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
_, err = c.Do(ctx, http.MethodGet, "/x", nil, nil)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("err = %v, want deadline exceeded", err)
|
||||
}
|
||||
if time.Since(start) > 2*time.Second {
|
||||
t.Errorf("backoff ignored the context: %s", time.Since(start))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaginateAdvancesByItemsReturned(t *testing.T) {
|
||||
var starts []string
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
start := r.URL.Query().Get("startAt")
|
||||
starts = append(starts, start)
|
||||
switch start {
|
||||
case "0":
|
||||
fmt.Fprint(w, `{"total":3,"values":[{"key":"A"},{"key":"B"}]}`) // server capped at 2
|
||||
case "2":
|
||||
fmt.Fprint(w, `{"total":3,"values":[{"key":"C"}]}`)
|
||||
default:
|
||||
t.Errorf("unexpected startAt %s", start)
|
||||
}
|
||||
}, nil)
|
||||
items, err := c.Paginate(context.Background(), "/x", nil, "values", 50)
|
||||
if err != nil || len(items) != 3 {
|
||||
t.Fatalf("items = %d, err = %v", len(items), err)
|
||||
}
|
||||
if strings.Join(starts, ",") != "0,2" {
|
||||
t.Errorf("startAt sequence = %v", starts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaginateStopsOnIsLast(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if calls.Add(1) == 1 {
|
||||
fmt.Fprint(w, `{"isLast":false,"values":[{"id":"1"}]}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"isLast":true,"values":[{"id":"2"}]}`)
|
||||
}, nil)
|
||||
items, err := c.Paginate(context.Background(), "/x", nil, "values", 1)
|
||||
if err != nil || len(items) != 2 || calls.Load() != 2 {
|
||||
t.Fatalf("items = %d after %d calls, err = %v", len(items), calls.Load(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadFile(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
switch calls.Add(1) {
|
||||
case 1:
|
||||
w.Header().Set("Retry-After", "0")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
case 2:
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
default:
|
||||
if _, _, ok := r.BasicAuth(); !ok {
|
||||
t.Error("same-host download without credentials")
|
||||
}
|
||||
fmt.Fprint(w, "payload")
|
||||
}
|
||||
}, func(o *atlassian.Options) { o.MaxRetries = 2 })
|
||||
dest := filepath.Join(t.TempDir(), "sub", "f")
|
||||
if err := c.DownloadFile(context.Background(), "/att/1", dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(dest); string(b) != "payload" {
|
||||
t.Errorf("downloaded %q", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadFileRedirectToOtherHostDropsCredentials(t *testing.T) {
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "" {
|
||||
t.Error("credentials followed a redirect to a foreign host")
|
||||
}
|
||||
fmt.Fprint(w, "x")
|
||||
}))
|
||||
defer other.Close()
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, _, ok := r.BasicAuth(); !ok {
|
||||
t.Error("site request without credentials")
|
||||
}
|
||||
http.Redirect(w, r, other.URL+"/media?token=s", http.StatusFound)
|
||||
}, nil)
|
||||
dest := filepath.Join(t.TempDir(), "f")
|
||||
if err := c.DownloadFile(context.Background(), "/rest/api/3/attachment/content/1", dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(dest); string(b) != "x" {
|
||||
t.Errorf("downloaded %q", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadFileFailureRemovesPartial(t *testing.T) {
|
||||
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}, nil)
|
||||
dest := filepath.Join(t.TempDir(), "f")
|
||||
err := c.DownloadFile(context.Background(), "/att/1?sig=secret", dest)
|
||||
if err == nil || strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("err = %v (want an error without the query)", err)
|
||||
}
|
||||
if _, statErr := os.Stat(dest); !os.IsNotExist(statErr) {
|
||||
t.Error("partial file left behind")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user