devbox/internal/transport/ratelimit.go
shoemoney 6532c510f5 feat(M4) + harden: bandwidth cap + M3 review fixes 🔒🛡️
Bandwidth cap (M4):
- transport rate-limited blob up/download (golang.org/x/time/rate); config.toml
  [transfer].max_kbps; daemon applies it per mount; [secrets].extra_patterns too

M3 ponytail review fixes (data-loss + resilience):
- C1: conflict-copy names use nanoseconds + collision probe — second-granularity
  timestamps could collide and os.Rename would overwrite a copy (lost edit)
- C3: pull resilience — a filesystem clash (file<->dir) skips that path instead of
  aborting the whole batch; network errors still abort+retry. PullResult.Skipped
- C2(partial): manifest skips .devbox-tmp-* (atomic-write temp files never sync).
  Kept conflict-copy propagation (design + Dropbox: losing edit survives device death)
- dedup: manifest.SameContent shared (was duplicated in pull)
- tests: file<->dir clash skips one path not the mount; rate-limit throttles
2026-06-23 00:29:50 -05:00

45 lines
965 B
Go

package transport
import (
"context"
"io"
"golang.org/x/time/rate"
)
// rlBurst caps a single throttled Read. It equals one max chunk so WaitN(n) is
// always called with n <= burst (rate.Limiter.WaitN errors if n > burst).
const rlBurst = 64 * 1024
// SetRateLimit caps blob transfer (up and down) to bytesPerSec. 0 = unlimited.
func (c *Client) SetRateLimit(bytesPerSec int) {
if bytesPerSec <= 0 {
c.limiter = nil
return
}
c.limiter = rate.NewLimiter(rate.Limit(bytesPerSec), rlBurst)
}
// limit wraps r so reads are paced by the client's limiter (no-op if unset).
func (c *Client) limit(r io.Reader) io.Reader {
if c.limiter == nil {
return r
}
return &rlReader{r: r, lim: c.limiter}
}
type rlReader struct {
r io.Reader
lim *rate.Limiter
}
func (rr *rlReader) Read(p []byte) (int, error) {
if len(p) > rlBurst {
p = p[:rlBurst]
}
n, err := rr.r.Read(p)
if n > 0 {
_ = rr.lim.WaitN(context.Background(), n)
}
return n, err
}