diff --git a/internal/hub/server.go b/internal/hub/server.go index 3587c07..8bd0d18 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -14,6 +14,7 @@ import ( "io" "net/http" "strconv" + "strings" "sync" "time" @@ -392,6 +393,18 @@ func (s *Server) handleGetBlob(w http.ResponseWriter, r *http.Request, _ string) return } 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) } diff --git a/internal/syncer/pull.go b/internal/syncer/pull.go index ee7b051..a1ae455 100644 --- a/internal/syncer/pull.go +++ b/internal/syncer/pull.go @@ -5,6 +5,7 @@ import ( "os" "path/filepath" "strings" + "sync" "github.com/shoemoney/devbox/internal/hooks" "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); // 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. -func writeEntry(c *transport.Client, root string, e manifest.Entry) (fsErr bool, err error) { - var buf []byte - for _, h := range e.Chunks { - b, gerr := c.GetBlob(h) - if gerr != nil { - return false, gerr // network +// downloadConcurrency bounds parallel chunk fetches when reassembling one file. +const downloadConcurrency = 8 + +// fetchChunks downloads a file's chunks (up to downloadConcurrency in flight) and +// concatenates them IN ORDER. Memory is bounded to this one file's content — the +// 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) if serr != nil { diff --git a/internal/syncer/syncer.go b/internal/syncer/syncer.go index e25bea6..f5db79f 100644 --- a/internal/syncer/syncer.go +++ b/internal/syncer/syncer.go @@ -8,6 +8,7 @@ import ( "path/filepath" "sort" "strings" + "sync" "github.com/shoemoney/devbox/internal/chunk" "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 { return Result{}, err } - for _, h := range missing { - if err := c.PutBlob(h, blobs[h]); err != nil { - return Result{}, err - } + if err := uploadBlobs(c, missing, blobs); err != nil { + return Result{}, err } // 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 } +// 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). func LoadIgnore(root string) (*ignore.Matcher, error) { return LoadIgnoreWith(root, nil) diff --git a/internal/transport/client.go b/internal/transport/client.go index 2a19913..a66d4c7 100644 --- a/internal/transport/client.go +++ b/internal/transport/client.go @@ -15,6 +15,7 @@ import ( "encoding/json" "fmt" "io" + "net" "net/http" "net/url" "strings" @@ -35,14 +36,62 @@ type Client struct { 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"). func New(base string) *Client { return &Client{ 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. 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() } -// 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) { - req, err := http.NewRequest(http.MethodGet, c.base+proto.PathBlob+hash, nil) - if err != nil { - return nil, err - } - req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer) - resp, err := c.hc.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := io.ReadAll(c.limit(resp.Body)) - if err != nil { - return nil, err - } - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return nil, apiError(resp.StatusCode, body) - } - // 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 nil, fmt.Errorf("devbox: blob %s failed integrity check (got %s)", hash, chunk.Hash(body)) - } - return body, nil + var out []byte + err := c.retry(func() (int, error) { + req, err := http.NewRequest(http.MethodGet, c.base+proto.PathBlob+hash, nil) + if err != nil { + return 0, err + } + req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer) + if c.compress { + req.Header.Set("Accept-Encoding", "gzip") + } + resp, err := c.hc.Do(req) + if err != nil { + return 0, err // network: code 0 → retryable + } + defer resp.Body.Close() + reader := c.limit(resp.Body) // count compressed wire bytes against the cap + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + b, _ := io.ReadAll(reader) + return resp.StatusCode, apiError(resp.StatusCode, b) + } + if resp.Header.Get("Content-Encoding") == "gzip" { + gz, gerr := gzip.NewReader(reader) + if gerr != 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. @@ -268,29 +340,33 @@ func (c *Client) raw(method, path string, data []byte) error { data, enc = gz, "gzip" } } - req, err := http.NewRequest(method, c.base+path, c.limit(bytes.NewReader(data))) - if err != nil { - return err - } - req.ContentLength = int64(len(data)) // body is a custom reader; set length explicitly - req.Header.Set("Content-Type", "application/octet-stream") - if enc != "" { - req.Header.Set("Content-Encoding", enc) - } - req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer) - resp, err := c.hc.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) - if err != nil { - return err - } - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return apiError(resp.StatusCode, body) - } - return nil + // Retry transient failures — a blob PUT is idempotent (content-addressed), and + // the body reader is rebuilt each attempt since c.limit consumes it. + return c.retry(func() (int, error) { + req, err := http.NewRequest(method, c.base+path, c.limit(bytes.NewReader(data))) + if err != nil { + return 0, err + } + req.ContentLength = int64(len(data)) // body is a custom reader; set length explicitly + req.Header.Set("Content-Type", "application/octet-stream") + if enc != "" { + req.Header.Set("Content-Encoding", enc) + } + req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer) + resp, err := c.hc.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return resp.StatusCode, err + } + 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. diff --git a/internal/transport/client_test.go b/internal/transport/client_test.go index 9819f19..f2b4895 100644 --- a/internal/transport/client_test.go +++ b/internal/transport/client_test.go @@ -10,8 +10,10 @@ import ( "net/http" "net/http/httptest" "strings" + "sync" "testing" + "github.com/shoemoney/devbox/internal/chunk" "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) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost || r.URL.Path != proto.PathPush {