WebDAV: survive rate limits on large shares
Nextcloud throttles bursty PROPFIND walks (429) and big trees exceeded the 3-minute sync budget — production's 1000+ file share failed intermittently with 'unexpected answer (429)' and 'context deadline exceeded'. propfind now retries 429/503 up to 3 times honoring Retry-After (capped 30s, ctx-bound, linear backoff without the header), the directory walk paces 100ms between PROPFINDs, and the engine sync budget grows to 6 minutes. Unit tests cover recover-after-429 and the bounded attempt count; truncation semantics are unchanged.
This commit is contained in:
@@ -26,6 +26,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -146,6 +147,13 @@ func List(ctx context.Context, conn Conn) (*ListResult, error) {
|
||||
if rel != "" {
|
||||
dirURL += "/"
|
||||
}
|
||||
if dials > 1 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(walkPace):
|
||||
}
|
||||
}
|
||||
entries, err := propfindEntries(ctx, conn, dirURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -218,18 +226,62 @@ type parsed struct {
|
||||
// propfind issues a PROPFIND with the given Depth and returns the raw
|
||||
// response (caller closes the body). Both Check and List build the same
|
||||
// request; only Depth differs.
|
||||
//
|
||||
// Rate limits (429/503 — Nextcloud throttles bursty PROPFIND walks) are
|
||||
// retried up to rateRetries times, honoring Retry-After (capped at
|
||||
// rateWaitCap so a hostile server cannot pin the sync); without the header
|
||||
// a short linear backoff applies. Every wait is ctx-bound.
|
||||
func propfind(ctx context.Context, conn Conn, target, depth string) (*http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "PROPFIND", target, strings.NewReader(propfindBody))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
for attempt := 0; ; attempt++ {
|
||||
req, err := http.NewRequestWithContext(ctx, "PROPFIND", target, strings.NewReader(propfindBody))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/xml")
|
||||
req.Header.Set("Depth", depth)
|
||||
res, err := httpClient(conn).Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not reach the WebDAV share: %w", err)
|
||||
}
|
||||
if (res.StatusCode == http.StatusTooManyRequests || res.StatusCode == http.StatusServiceUnavailable) && attempt < rateRetries {
|
||||
wait := rateLimitWait(res.Header.Get("Retry-After"), attempt)
|
||||
_ = res.Body.Close()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, fmt.Errorf("could not reach the WebDAV share: %w", ctx.Err())
|
||||
case <-time.After(wait):
|
||||
}
|
||||
continue
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/xml")
|
||||
req.Header.Set("Depth", depth)
|
||||
res, err := httpClient(conn).Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not reach the WebDAV share: %w", err)
|
||||
}
|
||||
|
||||
const (
|
||||
rateRetries = 3
|
||||
rateWaitCap = 30 * time.Second
|
||||
rateWaitDefault = 5 * time.Second
|
||||
// walkPace spaces directory PROPFINDs so a bounded walk stays under
|
||||
// common server rate limits instead of tripping them and paying
|
||||
// Retry-After waits on every request.
|
||||
walkPace = 100 * time.Millisecond
|
||||
)
|
||||
|
||||
// rateLimitWait parses Retry-After (delay-seconds form; the HTTP-date form
|
||||
// falls back to the default) and caps it. attempt is zero-based.
|
||||
func rateLimitWait(header string, attempt int) time.Duration {
|
||||
if secs, err := strconv.Atoi(strings.TrimSpace(header)); err == nil && secs >= 0 {
|
||||
d := time.Duration(secs) * time.Second
|
||||
if d > rateWaitCap {
|
||||
d = rateWaitCap
|
||||
}
|
||||
return d
|
||||
}
|
||||
return res, nil
|
||||
d := rateWaitDefault * time.Duration(attempt+1)
|
||||
if d > rateWaitCap {
|
||||
d = rateWaitCap
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
const propfindBody = `<?xml version="1.0" encoding="utf-8"?>` +
|
||||
|
||||
@@ -197,3 +197,52 @@ func TestNormalizeBasePercentSafety(t *testing.T) {
|
||||
t.Fatalf("double or missing encoding: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A 429 with Retry-After is retried, not fatal: the walk recovers once the
|
||||
// throttle window passes (Nextcloud rate-limits bursty PROPFIND walks).
|
||||
func TestListRetriesRateLimit(t *testing.T) {
|
||||
allowPrivate(t)
|
||||
hits := 0
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits++
|
||||
if hits == 1 {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
http.Error(w, "slow down", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.WriteHeader(http.StatusMultiStatus)
|
||||
_, _ = w.Write([]byte(`<multistatus xmlns="DAV:">` +
|
||||
`<response><href>/dav/</href><propstat><prop><resourcetype><collection/></resourcetype></prop></propstat></response>` +
|
||||
`<response><href>/dav/a.txt</href><propstat><prop><resourcetype/><getetag>"A1"</getetag></prop></propstat></response>` +
|
||||
`</multistatus>`))
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
res, err := List(context.Background(), Conn{BaseURL: ts.URL + "/dav", Username: davUser, Password: davPass})
|
||||
if err != nil {
|
||||
t.Fatalf("429 then 207 must recover: %v", err)
|
||||
}
|
||||
if len(res.Files) != 1 || res.Files[0].Path != "a.txt" || hits != 2 {
|
||||
t.Fatalf("retry walk wrong: files=%v hits=%d", res.Files, hits)
|
||||
}
|
||||
}
|
||||
|
||||
// Persistent 429s stay bounded: exactly rateRetries+1 attempts, then the
|
||||
// server's answer surfaces (no infinite retry loop pinning the sync tick).
|
||||
func TestListRateLimitBounded(t *testing.T) {
|
||||
allowPrivate(t)
|
||||
hits := 0
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits++
|
||||
w.Header().Set("Retry-After", "0")
|
||||
http.Error(w, "slow down", http.StatusTooManyRequests)
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
_, err := List(context.Background(), Conn{BaseURL: ts.URL + "/dav", Username: davUser, Password: davPass})
|
||||
if err == nil || !strings.Contains(err.Error(), "429") {
|
||||
t.Fatalf("persistent 429 must surface: %v", err)
|
||||
}
|
||||
if hits != rateRetries+1 {
|
||||
t.Fatalf("attempts = %d, want %d", hits, rateRetries+1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ const (
|
||||
tick = 5 * time.Minute // engine cadence
|
||||
syncEvery = 30 * time.Minute // per-connection freshness target
|
||||
perTick = 10 // connections claimed per tick
|
||||
syncTimeout = 3 * time.Minute // one full reconcile
|
||||
syncTimeout = 6 * time.Minute // one full reconcile (large walks pace + retry 429s)
|
||||
lastErrCap = 500
|
||||
dialBudget = 10 // outbound.Reserve window per owner (tests + syncs)
|
||||
dialWindow = time.Minute
|
||||
|
||||
Reference in New Issue
Block a user