From 3878dddaa754162102443b217808bf333ad86609 Mon Sep 17 00:00:00 2001 From: Andrew S Erwin Date: Tue, 24 Nov 2026 11:35:06 -0600 Subject: [PATCH] WebDAV: survive rate limits on large shares MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- API.md | 5 ++- internal/webdav/client.go | 70 +++++++++++++++++++++++++++++----- internal/webdav/client_test.go | 49 ++++++++++++++++++++++++ internal/webdav/sync.go | 2 +- 4 files changed, 115 insertions(+), 11 deletions(-) diff --git a/API.md b/API.md index db34c3a..24a2965 100644 --- a/API.md +++ b/API.md @@ -158,7 +158,10 @@ deleted it, FK SET NULL) re-links every still-tracked file. A truncated listing (200 dirs / 1000 files / depth 12 caps) creates new members but never reconciles deletions. Dials are netguard-pinned (ports 80/443 outside tests), credentials travel only in a Basic `Authorization` header (never the -URL), and redirects are refused outright. Creation AND every sync re-check +URL), and redirects are refused outright. Rate-limited answers (429/503) are +retried up to 3 times honoring `Retry-After` (capped at 30s), directory walks +are paced 100ms apart, and the engine's per-sync budget is 6 minutes — large +shares throttle instead of failing. Creation AND every sync re-check `AllowConnector("webdav")` from the entitlement catalog; a downgrade suppresses syncs instead of deleting anything. diff --git a/internal/webdav/client.go b/internal/webdav/client.go index 50dab41..2da6d5c 100644 --- a/internal/webdav/client.go +++ b/internal/webdav/client.go @@ -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 = `` + diff --git a/internal/webdav/client_test.go b/internal/webdav/client_test.go index 6457d71..5edd977 100644 --- a/internal/webdav/client_test.go +++ b/internal/webdav/client_test.go @@ -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(`` + + `/dav/` + + `/dav/a.txt"A1"` + + ``)) + })) + 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) + } +} diff --git a/internal/webdav/sync.go b/internal/webdav/sync.go index e7deffd..842ab56 100644 --- a/internal/webdav/sync.go +++ b/internal/webdav/sync.go @@ -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