feat(transfer): harden the WAN sync path — timeouts, retry, parallel I/O, download gzip 🌐⚡

Now the hub is WAN-reachable, the transfer path needed real hardening:

- ⏱️  request timeout fix: replaced the 30s TOTAL http.Client.Timeout (which
  killed a 256MiB blob mid-transfer over a slow link) with granular dial / TLS /
  response-header timeouts + TCP keepalive. Body transfer is no longer wall-clocked.
- 🔁 retry + exponential backoff on transient blob transfers (network / 5xx),
  3 attempts; 4xx fails fast. Blob GET/PUT are content-addressed (idempotent),
  so retry is safe; control calls are left alone.
- 🚀 parallel blob uploads (push) and parallel chunk downloads (pull reassembly),
  bounded pools (8), sharing the existing rate limiter. WAN is RTT-bound — this
  keeps the pipe full instead of one-blob-at-a-time.
- 🗜️ download (response) gzip: round 1 compressed only uploads, but a clone is
  download-heavy. Client negotiates gzip explicitly (so the rate limiter counts
  wire bytes), hub streams the response through gzip, client decompresses
  bomb-safely. Gated by the same settings.transfer.compress flag.

Tests: retry transient-then-success + 4xx-no-retry, gzip download round-trip.
All existing push/pull round-trips green under -race (refactors behavior-preserving).
This commit is contained in:
shoemoney 2026-06-30 13:15:17 -05:00
parent 4168b2109f
commit 963ece58b0
5 changed files with 317 additions and 60 deletions

View file

@ -14,6 +14,7 @@ import (
"io" "io"
"net/http" "net/http"
"strconv" "strconv"
"strings"
"sync" "sync"
"time" "time"
@ -392,6 +393,18 @@ func (s *Server) handleGetBlob(w http.ResponseWriter, r *http.Request, _ string)
return return
} }
w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Type", "application/octet-stream")
// Gzip the response when the client negotiated it (settings.transfer.compress on
// the device → WAN). The blob is already in memory, so this just streams it
// through a gzip.Writer. ponytail: no shrink-check — the client only asks when it
// expects a win; a tiny incompressible chunk may inflate a few bytes, which is
// noise next to the WAN round-trip it's trying to save.
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
gz.Write(b)
return
}
w.Write(b) w.Write(b)
} }

View file

@ -5,6 +5,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
"github.com/shoemoney/devbox/internal/hooks" "github.com/shoemoney/devbox/internal/hooks"
"github.com/shoemoney/devbox/internal/ignore" "github.com/shoemoney/devbox/internal/ignore"
@ -360,14 +361,65 @@ func unionKeys(maps ...map[string]manifest.Entry) map[string]struct{} {
// error returns fsErr=false (the caller should abort and retry the whole sync); // error returns fsErr=false (the caller should abort and retry the whole sync);
// a filesystem error — e.g. the path is currently a directory — returns // a filesystem error — e.g. the path is currently a directory — returns
// fsErr=true so the caller can skip just that path instead of wedging the mount. // fsErr=true so the caller can skip just that path instead of wedging the mount.
func writeEntry(c *transport.Client, root string, e manifest.Entry) (fsErr bool, err error) { // downloadConcurrency bounds parallel chunk fetches when reassembling one file.
var buf []byte const downloadConcurrency = 8
for _, h := range e.Chunks {
b, gerr := c.GetBlob(h) // fetchChunks downloads a file's chunks (up to downloadConcurrency in flight) and
if gerr != nil { // concatenates them IN ORDER. Memory is bounded to this one file's content — the
return false, gerr // network // same as the old sequential append. ponytail: parallelism is within-file; a
// many-tiny-files clone is still one file at a time — a cross-file prefetch
// window is the upgrade path if that ever dominates.
func fetchChunks(c *transport.Client, hashes []string) ([]byte, error) {
if len(hashes) == 0 {
return nil, nil
}
if len(hashes) == 1 {
return c.GetBlob(hashes[0])
}
parts := make([][]byte, len(hashes))
sem := make(chan struct{}, downloadConcurrency)
var wg sync.WaitGroup
var mu sync.Mutex
var firstErr error
for i, h := range hashes {
mu.Lock()
stop := firstErr != nil
mu.Unlock()
if stop {
break
} }
buf = append(buf, b...) sem <- struct{}{}
wg.Add(1)
go func(i int, h string) {
defer wg.Done()
defer func() { <-sem }()
b, err := c.GetBlob(h)
if err != nil {
mu.Lock()
if firstErr == nil {
firstErr = err
}
mu.Unlock()
return
}
parts[i] = b
}(i, h)
}
wg.Wait()
if firstErr != nil {
return nil, firstErr
}
var buf []byte
for _, p := range parts {
buf = append(buf, p...)
}
return buf, nil
}
func writeEntry(c *transport.Client, root string, e manifest.Entry) (fsErr bool, err error) {
buf, gerr := fetchChunks(c, e.Chunks)
if gerr != nil {
return false, gerr // network
} }
dst, serr := safeJoin(root, e.Path) dst, serr := safeJoin(root, e.Path)
if serr != nil { if serr != nil {

View file

@ -8,6 +8,7 @@ import (
"path/filepath" "path/filepath"
"sort" "sort"
"strings" "strings"
"sync"
"github.com/shoemoney/devbox/internal/chunk" "github.com/shoemoney/devbox/internal/chunk"
"github.com/shoemoney/devbox/internal/hooks" "github.com/shoemoney/devbox/internal/hooks"
@ -90,10 +91,8 @@ func Push(c *transport.Client, root, share, subpath string, ig *ignore.Matcher,
if err != nil { if err != nil {
return Result{}, err return Result{}, err
} }
for _, h := range missing { if err := uploadBlobs(c, missing, blobs); err != nil {
if err := c.PutBlob(h, blobs[h]); err != nil { return Result{}, err
return Result{}, err
}
} }
// Declare every distinct chunk the full manifest references so the hub's // Declare every distinct chunk the full manifest references so the hub's
@ -161,6 +160,44 @@ func splice(c *transport.Client, localM manifest.Manifest, subpath, parent strin
return manifest.Manifest{Entries: entries}, nil return manifest.Manifest{Entries: entries}, nil
} }
// uploadConcurrency bounds parallel blob uploads. WAN round-trip latency, not
// bandwidth, dominates a push of many small chunks; a small pool keeps the pipe
// full while the shared rate limiter still caps total throughput.
const uploadConcurrency = 8
// uploadBlobs PUTs every missing blob, up to uploadConcurrency in flight, and
// returns the first error (cancelling further starts). Order doesn't matter —
// blobs are content-addressed and independent.
func uploadBlobs(c *transport.Client, missing []string, blobs map[string][]byte) error {
sem := make(chan struct{}, uploadConcurrency)
var wg sync.WaitGroup
var mu sync.Mutex
var firstErr error
for _, h := range missing {
mu.Lock()
stop := firstErr != nil
mu.Unlock()
if stop {
break
}
sem <- struct{}{}
wg.Add(1)
go func(h string) {
defer wg.Done()
defer func() { <-sem }()
if err := c.PutBlob(h, blobs[h]); err != nil {
mu.Lock()
if firstErr == nil {
firstErr = err
}
mu.Unlock()
}
}(h)
}
wg.Wait()
return firstErr
}
// LoadIgnore compiles root/.devignore (an empty matcher if the file is absent). // LoadIgnore compiles root/.devignore (an empty matcher if the file is absent).
func LoadIgnore(root string) (*ignore.Matcher, error) { func LoadIgnore(root string) (*ignore.Matcher, error) {
return LoadIgnoreWith(root, nil) return LoadIgnoreWith(root, nil)

View file

@ -15,6 +15,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"net"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
@ -35,14 +36,62 @@ type Client struct {
compress bool // gzip blob uploads when it shrinks them (settings.transfer.compress) compress bool // gzip blob uploads when it shrinks them (settings.transfer.compress)
} }
// maxBlobBytes mirrors the hub's per-blob cap; used to bound a gzip-decoded
// download so a malicious/buggy hub can't bomb the client.
const maxBlobBytes = 256 << 20
// blobRetries is how many times a transient blob transfer is attempted before
// giving up (the daemon retries the whole sync on its next trigger regardless).
const blobRetries = 3
// New returns a Client for the hub at base (e.g. "http://host:8080"). // New returns a Client for the hub at base (e.g. "http://host:8080").
func New(base string) *Client { func New(base string) *Client {
return &Client{ return &Client{
base: strings.TrimRight(base, "/"), base: strings.TrimRight(base, "/"),
hc: &http.Client{Timeout: 30 * time.Second}, // No total client Timeout: a 256MiB blob over a slow WAN link can legitimately
// take minutes, and a wall-clock total would kill it mid-transfer. Bound the
// phases that SHOULD be fast instead (connect, TLS, time-to-first-byte) and let
// TCP keepalive reap a dead peer. ponytail: a mid-body stall isn't bounded here;
// add a stall-timeout reader if a flaky link ever hangs transfers.
hc: &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
DisableCompression: true, // we negotiate gzip explicitly so the rate limiter sees wire bytes
MaxIdleConnsPerHost: 16, // reuse connections for parallel blob transfers
},
},
} }
} }
// transient reports whether a failed attempt is worth retrying: a network error
// (code 0) or a 5xx. A 4xx is a definite client/auth error — retrying just hammers.
func transient(code int) bool { return code < 400 || code >= 500 }
// retry runs attempt up to blobRetries times with exponential backoff, retrying
// only transient failures. attempt returns the HTTP status (0 on a pre-response
// error) and the error. Blob GET/PUT are idempotent (content-addressed), so this
// is safe; it is NOT used for the non-idempotent control calls.
func (c *Client) retry(attempt func() (int, error)) error {
delay := 200 * time.Millisecond
var err error
for i := 0; i < blobRetries; i++ {
var code int
if code, err = attempt(); err == nil {
return nil
}
if !transient(code) {
return err
}
if i < blobRetries-1 {
time.Sleep(delay)
delay *= 2
}
}
return err
}
// SetBearer sets the device bearer token used for authenticated requests. // SetBearer sets the device bearer token used for authenticated requests.
func (c *Client) SetBearer(b string) { c.bearer = b } func (c *Client) SetBearer(b string) { c.bearer = b }
@ -139,32 +188,55 @@ func (c *Client) Events(ctx context.Context, share string, onEvent func(proto.Ev
return sc.Err() return sc.Err()
} }
// GetBlob downloads one blob's raw bytes by content hash (used by pull). // GetBlob downloads one blob's raw bytes by content hash (used by pull). When
// compression is on it negotiates gzip explicitly (so the rate limiter counts
// wire bytes) and decompresses bomb-safely. Transient failures are retried.
func (c *Client) GetBlob(hash string) ([]byte, error) { func (c *Client) GetBlob(hash string) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, c.base+proto.PathBlob+hash, nil) var out []byte
if err != nil { err := c.retry(func() (int, error) {
return nil, err req, err := http.NewRequest(http.MethodGet, c.base+proto.PathBlob+hash, nil)
} if err != nil {
req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer) return 0, err
resp, err := c.hc.Do(req) }
if err != nil { req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer)
return nil, err if c.compress {
} req.Header.Set("Accept-Encoding", "gzip")
defer resp.Body.Close() }
body, err := io.ReadAll(c.limit(resp.Body)) resp, err := c.hc.Do(req)
if err != nil { if err != nil {
return nil, err return 0, err // network: code 0 → retryable
} }
if resp.StatusCode < 200 || resp.StatusCode >= 300 { defer resp.Body.Close()
return nil, apiError(resp.StatusCode, body) reader := c.limit(resp.Body) // count compressed wire bytes against the cap
} if resp.StatusCode < 200 || resp.StatusCode >= 300 {
// Blobs (chunks and manifests) are content-addressed: the key is BLAKE3 of the b, _ := io.ReadAll(reader)
// bytes. Verify it so a corrupt/truncated transfer or a buggy/malicious hub return resp.StatusCode, apiError(resp.StatusCode, b)
// can't write wrong content into the user's tree undetected. }
if chunk.Hash(body) != hash { if resp.Header.Get("Content-Encoding") == "gzip" {
return nil, fmt.Errorf("devbox: blob %s failed integrity check (got %s)", hash, chunk.Hash(body)) gz, gerr := gzip.NewReader(reader)
} if gerr != nil {
return body, nil return resp.StatusCode, gerr
}
defer gz.Close()
reader = io.LimitReader(gz, maxBlobBytes+1) // bomb guard
}
body, err := io.ReadAll(reader)
if err != nil {
return resp.StatusCode, err // truncated mid-body → retryable (code 200 is < 400)
}
if int64(len(body)) > maxBlobBytes {
return resp.StatusCode, fmt.Errorf("devbox: blob %s exceeds %d bytes decompressed", hash, maxBlobBytes)
}
// Blobs (chunks and manifests) are content-addressed: the key is BLAKE3 of the
// bytes. Verify it so a corrupt/truncated transfer or a buggy/malicious hub
// can't write wrong content into the user's tree undetected.
if chunk.Hash(body) != hash {
return resp.StatusCode, fmt.Errorf("devbox: blob %s failed integrity check (got %s)", hash, chunk.Hash(body))
}
out = body
return resp.StatusCode, nil
})
return out, err
} }
// Push commits a snapshot. Its manifest and chunk blobs must already be uploaded. // Push commits a snapshot. Its manifest and chunk blobs must already be uploaded.
@ -268,29 +340,33 @@ func (c *Client) raw(method, path string, data []byte) error {
data, enc = gz, "gzip" data, enc = gz, "gzip"
} }
} }
req, err := http.NewRequest(method, c.base+path, c.limit(bytes.NewReader(data))) // Retry transient failures — a blob PUT is idempotent (content-addressed), and
if err != nil { // the body reader is rebuilt each attempt since c.limit consumes it.
return err return c.retry(func() (int, error) {
} req, err := http.NewRequest(method, c.base+path, c.limit(bytes.NewReader(data)))
req.ContentLength = int64(len(data)) // body is a custom reader; set length explicitly if err != nil {
req.Header.Set("Content-Type", "application/octet-stream") return 0, err
if enc != "" { }
req.Header.Set("Content-Encoding", enc) req.ContentLength = int64(len(data)) // body is a custom reader; set length explicitly
} req.Header.Set("Content-Type", "application/octet-stream")
req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer) if enc != "" {
resp, err := c.hc.Do(req) req.Header.Set("Content-Encoding", enc)
if err != nil { }
return err req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer)
} resp, err := c.hc.Do(req)
defer resp.Body.Close() if err != nil {
body, err := io.ReadAll(resp.Body) return 0, err
if err != nil { }
return err defer resp.Body.Close()
} body, err := io.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 { if err != nil {
return apiError(resp.StatusCode, body) return resp.StatusCode, err
} }
return nil if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return resp.StatusCode, apiError(resp.StatusCode, body)
}
return resp.StatusCode, nil
})
} }
// apiError turns a non-2xx body into an error, preferring proto.Error's message. // apiError turns a non-2xx body into an error, preferring proto.Error's message.

View file

@ -10,8 +10,10 @@ import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
"sync"
"testing" "testing"
"github.com/shoemoney/devbox/internal/chunk"
"github.com/shoemoney/devbox/pkg/proto" "github.com/shoemoney/devbox/pkg/proto"
) )
@ -203,6 +205,83 @@ func TestPutBlobCompress(t *testing.T) {
} }
} }
// TestPutBlobRetry proves transient failures (5xx) are retried and a 4xx is not.
func TestPutBlobRetry(t *testing.T) {
var attempts int
var always400 bool
var mu sync.Mutex
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
attempts++
n := attempts
bad := always400
mu.Unlock()
switch {
case bad:
w.WriteHeader(http.StatusBadRequest)
case n < 2:
w.WriteHeader(http.StatusServiceUnavailable) // fail first attempt
default:
w.WriteHeader(http.StatusOK) // succeed on retry
}
}))
defer srv.Close()
c := New(srv.URL)
c.SetBearer("t")
if err := c.PutBlob("h", []byte("data")); err != nil {
t.Fatalf("PutBlob should succeed after one 503 retry: %v", err)
}
mu.Lock()
got := attempts
mu.Unlock()
if got != 2 {
t.Fatalf("expected 2 attempts (503 then 200), got %d", got)
}
// A 4xx must NOT be retried.
mu.Lock()
attempts, always400 = 0, true
mu.Unlock()
if err := c.PutBlob("h", []byte("data")); err == nil {
t.Fatal("PutBlob should fail on 400")
}
mu.Lock()
got = attempts
mu.Unlock()
if got != 1 {
t.Fatalf("4xx must not retry: got %d attempts, want 1", got)
}
}
// TestGetBlobGzipDownload proves the client decodes a gzip-encoded blob response
// (download-side compression) and the integrity check passes on the decoded bytes.
func TestGetBlobGzipDownload(t *testing.T) {
original := bytes.Repeat([]byte("pull me over the WAN "), 512)
hash := chunk.Hash(original)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
t.Errorf("client did not request gzip; Accept-Encoding=%q", r.Header.Get("Accept-Encoding"))
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
gz.Write(original)
gz.Close()
}))
defer srv.Close()
c := New(srv.URL)
c.SetBearer("t")
c.SetCompress(true)
got, err := c.GetBlob(hash)
if err != nil {
t.Fatalf("GetBlob: %v", err)
}
if !bytes.Equal(got, original) {
t.Fatalf("gzip download mismatch: %d bytes, want %d", len(got), len(original))
}
}
func TestPush(t *testing.T) { func TestPush(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != proto.PathPush { if r.Method != http.MethodPost || r.URL.Path != proto.PathPush {