Files
yetano-clients/atlassian/internal/transport/download.go
T

111 lines
2.9 KiB
Go
Raw Normal View History

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()
}