Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 3 additions & 84 deletions clients/cli/cmd/internal/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"path/filepath"
"reflect"
"strings"
"sync"
"time"

"github.com/phrase/phrase-cli/cmd/internal/paths"
Expand All @@ -31,13 +30,9 @@ const (

const maxParallelDownloads = 4 // Phrase API allows max 4 concurrent requests

const maxDownloadAttempts = 3

var (
Config *phrase.Config
errNotModified = errors.New("not modified")

downloadRetrySleep = time.Sleep
)

type PullCommand struct {
Expand Down Expand Up @@ -138,6 +133,7 @@ func newClient() *phrase.APIClient {
if Config.Credentials.Host != "" {
cfg.BasePath = Config.Credentials.Host
}
cfg.HTTPClient = &http.Client{Transport: rateLimitTransport{http.DefaultTransport}}
return phrase.NewAPIClient(cfg)
}

Expand Down Expand Up @@ -234,7 +230,6 @@ func (target *Target) PullParallel(client *phrase.APIClient, cache *DownloadCach
}

results := make([]downloadResult, len(localeFiles))
var rateMu sync.RWMutex

ctx, cancel := context.WithTimeout(context.Background(), timeoutInMinutes)
defer cancel()
Expand All @@ -260,7 +255,7 @@ func (target *Target) PullParallel(client *phrase.APIClient, cache *DownloadCach
applyCacheHeaders(cache, cacheKey, &opts)
}

file, response, dlErr := target.downloadWithRateGate(client, lf, opts, &rateMu)
file, response, dlErr := downloadLocale(client, target.ProjectID, lf.ID, &opts)

if response != nil && response.StatusCode == 304 {
debugFprintln("Not modified (304), skipping", lf.Path)
Expand Down Expand Up @@ -312,38 +307,6 @@ func (target *Target) PullParallel(client *phrase.APIClient, cache *DownloadCach
return waitErr
}

// downloadWithRateGate downloads a locale file with rate-limit coordination.
// Uses RWMutex as a broadcast gate: workers take a read lock (cheap, concurrent),
// and a rate-limited worker takes the write lock to pause everyone until reset.
func (target *Target) downloadWithRateGate(client *phrase.APIClient, localeFile *LocaleFile, opts phrase.LocaleDownloadOpts, gate *sync.RWMutex) (*os.File, *phrase.APIResponse, error) {
waitForGate := func() { gate.RLock(); gate.RUnlock() }
waitForGate()

file, response, err := downloadLocale(client, target.ProjectID, localeFile.ID, &opts)
if err != nil {
if response != nil && response.StatusCode == 304 {
return nil, response, nil
}
if response != nil && response.Rate.Remaining == 0 {
if gate.TryLock() {
waitForRateLimit(response.Rate)
gate.Unlock()
} else {
waitForGate()
}
opts.IfNoneMatch = optional.String{}
opts.IfModifiedSince = optional.String{}
file, response, err = downloadLocale(client, target.ProjectID, localeFile.ID, &opts)
if err != nil {
return nil, response, err
}
} else {
return nil, response, err
}
}
return file, response, nil
}

// downloadLocale calls the locale download endpoint and retries transport
// errors, e.g. an HTTP/2 stream reset by an intermediary while reading the
// body. API errors, including 304 and rate limiting, are returned to the
Expand All @@ -360,20 +323,6 @@ func downloadLocale(client *phrase.APIClient, projectID string, localeID string,
return file, response, err
}

// retryTransient calls fn up to maxDownloadAttempts times for as long as it
// fails with an error it reports as transient.
func retryTransient(fn func() (transient bool, err error)) error {
for attempt := 1; ; attempt++ {
transient, err := fn()
if err == nil || !transient || attempt >= maxDownloadAttempts {
return err
}
delay := time.Second << (attempt - 1) // 1s, 2s
debugFprintln(fmt.Sprintf("Download attempt %d/%d failed: %s, retrying in %s", attempt, maxDownloadAttempts, err, delay))
downloadRetrySleep(delay)
}
}

// buildDownloadOpts prepares the LocaleDownloadOpts for a locale file download.
func (target *Target) buildDownloadOpts(localeFile *LocaleFile) (phrase.LocaleDownloadOpts, error) {
opts := phrase.LocaleDownloadOpts{}
Expand Down Expand Up @@ -465,18 +414,7 @@ func (target *Target) downloadSynchronously(client *phrase.APIClient, localeFile
debugFprintln("Not modified (304), skipping", localeFile.Path)
return errNotModified
}
if response != nil && response.Rate.Remaining == 0 {
waitForRateLimit(response.Rate)
// Strip conditional headers on retry to get a full response
downloadOpts.IfNoneMatch = optional.String{}
downloadOpts.IfModifiedSince = optional.String{}
file, response, err = downloadLocale(client, target.ProjectID, localeFile.ID, &downloadOpts)
if err != nil {
return err
}
} else {
return err
}
return err
}

if err := copyToDestination(file, localeFile.Path); err != nil {
Expand Down Expand Up @@ -637,25 +575,6 @@ func (target *Target) createLocaleFiles(remoteLocale *phrase.Locale) (LocaleFile
return files, nil
}

func waitForRateLimit(rate phrase.Rate) {
endTime := rate.Reset.Time.Add(5 * time.Second)
duration := time.Until(endTime)
message := "Rate limit exceeded. Download will resume in %d seconds"
seconds := int64(time.Until(endTime).Seconds())
print.Warn(message, seconds)
counter := int64(1)
ticker := time.NewTicker(1 * time.Second)
for range ticker.C {
counter++
seconds = int64(time.Until(endTime).Seconds())
print.Warn(message, seconds)
if counter > int64(duration/time.Second) {
ticker.Stop()
break
}
}
}

func createLocaleFile(target *Target, remoteLocale *phrase.Locale, tag string) (*LocaleFile, error) {
localeFile := &LocaleFile{
Name: remoteLocale.Name,
Expand Down
6 changes: 3 additions & 3 deletions clients/cli/cmd/internal/pull_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ func TestDownloadRetries(t *testing.T) {
{"does not retry API errors", 0, http.StatusServiceUnavailable, true, 1},
}

prevAuth, prevConfig, prevSleep := Auth, Config, downloadRetrySleep
Auth, Config, downloadRetrySleep = context.Background(), &phrase.Config{}, func(time.Duration) {}
t.Cleanup(func() { Auth, Config, downloadRetrySleep = prevAuth, prevConfig, prevSleep })
prevAuth, prevConfig, prevSleep := Auth, Config, retrySleep
Auth, Config, retrySleep = context.Background(), &phrase.Config{}, func(context.Context, time.Duration) error { return nil }
t.Cleanup(func() { Auth, Config, retrySleep = prevAuth, prevConfig, prevSleep })

for name, download := range downloads {
for _, c := range cases {
Expand Down
112 changes: 112 additions & 0 deletions clients/cli/cmd/internal/retry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package internal

import (
"context"
"fmt"
"io"
"math/rand/v2"
"net/http"
"strconv"
"time"

"github.com/phrase/phrase-cli/cmd/internal/print"
)

const (
maxDownloadAttempts = 3
maxRateLimitRetries = 20
maxRateLimitWait = 10 * time.Minute // total wait per request, then the 429 is returned
concurrencyDelay = 250 * time.Millisecond
maxConcurrencyDelay = 5 * time.Second
)

var (
retrySleep = sleepContext
rateLimitNow = time.Now
)

// sleepContext waits for d or until ctx is done, whichever comes first.
func sleepContext(ctx context.Context, d time.Duration) error {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}

// retryTransient calls fn up to maxDownloadAttempts times for as long as it
// fails with an error it reports as transient.
func retryTransient(fn func() (transient bool, err error)) error {
for attempt := 1; ; attempt++ {
transient, err := fn()
if err == nil || !transient || attempt >= maxDownloadAttempts {
return err
}
delay := time.Second << (attempt - 1) // 1s, 2s
debugFprintln(fmt.Sprintf("Download attempt %d/%d failed: %s, retrying in %s", attempt, maxDownloadAttempts, err, delay))
retrySleep(context.Background(), delay)
}
}

// rateLimitTransport retries requests rejected with 429. Rate limit
// rejections are retried once the window resets (X-Rate-Limit-Reset), anything
// else, e.g. the global concurrency limit, with exponential backoff.
type rateLimitTransport struct {
next http.RoundTripper
}

func (t rateLimitTransport) RoundTrip(req *http.Request) (*http.Response, error) {
var waited time.Duration
for attempt := 1; ; attempt++ {
resp, err := t.next.RoundTrip(req)
if err != nil || resp.StatusCode != http.StatusTooManyRequests || attempt > maxRateLimitRetries {
return resp, err
}
delay, untilReset := rateLimitDelay(resp, attempt)
if waited += delay; waited > maxRateLimitWait {
return resp, nil
}

// the body is needed to replay the request
retry := req.Clone(req.Context())
if req.Body != nil && req.Body != http.NoBody {
if req.GetBody == nil {
return resp, nil
}
if retry.Body, err = req.GetBody(); err != nil {
return resp, nil
}
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()

if untilReset {
print.Warn("Rate limit exceeded. Retrying in %s", delay.Round(time.Second))
} else {
debugFprintln(fmt.Sprintf("Concurrency limit exceeded, retrying in %s", delay))
}
if err := retrySleep(req.Context(), delay); err != nil {
if retry.Body != nil {
retry.Body.Close()
}
return nil, err
}
req = retry
}
}

// rateLimitDelay returns how long to wait before retrying a 429, and whether
// that is the time until the rate limit window resets.
func rateLimitDelay(resp *http.Response, attempt int) (time.Duration, bool) {
if resp.Header.Get("X-Rate-Limit-Reason") != "global-concurrency" {
// X-Rate-Limit-Remaining is 0 here; X-Rate-Limit-Reset is the unix time the window ends.
if reset, err := strconv.ParseInt(resp.Header.Get("X-Rate-Limit-Reset"), 10, 64); err == nil {
return max(time.Unix(reset, 0).Sub(rateLimitNow())+time.Second, concurrencyDelay), true
}
}
delay := min(concurrencyDelay<<(attempt-1), maxConcurrencyDelay)
return delay + rand.N(delay/2), false // jitter, so parallel workers don't retry in lockstep
}
Loading
Loading