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
This commit is contained in:
parent
1712bb26f3
commit
6532c510f5
10 changed files with 264 additions and 60 deletions
1
go.mod
1
go.mod
|
|
@ -8,6 +8,7 @@ require (
|
|||
github.com/jotfs/fastcdc-go v0.2.0
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/zeebo/blake3 v0.2.4
|
||||
golang.org/x/time v0.15.0
|
||||
modernc.org/sqlite v1.53.0
|
||||
)
|
||||
|
||||
|
|
|
|||
2
go.sum
2
go.sum
|
|
@ -42,6 +42,8 @@ golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
|||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
||||
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
|
||||
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
|
|
|||
|
|
@ -88,6 +88,29 @@ func SaveDaemon(dir string, d Daemon) error {
|
|||
return os.Rename(tmp, daemonPath(dir))
|
||||
}
|
||||
|
||||
// Settings is config.toml: per-machine tunables (separate from daemon.toml).
|
||||
type Settings struct {
|
||||
Transfer struct {
|
||||
MaxKbps int `toml:"max_kbps"` // blob transfer cap; 0 = unlimited
|
||||
} `toml:"transfer"`
|
||||
Secrets struct {
|
||||
ExtraPatterns []string `toml:"extra_patterns"`
|
||||
} `toml:"secrets"`
|
||||
}
|
||||
|
||||
// LoadSettings reads config.toml from dir (zero Settings if absent).
|
||||
func LoadSettings(dir string) (Settings, error) {
|
||||
var s Settings
|
||||
b, err := os.ReadFile(filepath.Join(dir, "config.toml"))
|
||||
if os.IsNotExist(err) {
|
||||
return s, nil
|
||||
}
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, toml.Unmarshal(b, &s)
|
||||
}
|
||||
|
||||
func statePath(dir string) string { return filepath.Join(dir, "state.json") }
|
||||
|
||||
// LoadState reads the per-mount last-applied snapshot map (mountKey -> snapshot).
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ type Daemon struct {
|
|||
cfg config.Daemon
|
||||
host string
|
||||
guard *secret.Guard
|
||||
maxBytesPerSec int
|
||||
logf func(string, ...any)
|
||||
|
||||
mu sync.Mutex
|
||||
|
|
@ -32,7 +33,11 @@ type Daemon struct {
|
|||
|
||||
// New builds a daemon from a loaded config. logf may be nil (defaults to log.Printf).
|
||||
func New(dir string, cfg config.Daemon, host string, logf func(string, ...any)) (*Daemon, error) {
|
||||
guard, err := secret.New(nil)
|
||||
settings, err := config.LoadSettings(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
guard, err := secret.New(settings.Secrets.ExtraPatterns)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -43,7 +48,11 @@ func New(dir string, cfg config.Daemon, host string, logf func(string, ...any))
|
|||
if logf == nil {
|
||||
logf = log.Printf
|
||||
}
|
||||
return &Daemon{dir: dir, cfg: cfg, host: host, guard: guard, logf: logf, state: state}, nil
|
||||
return &Daemon{
|
||||
dir: dir, cfg: cfg, host: host, guard: guard,
|
||||
maxBytesPerSec: settings.Transfer.MaxKbps * 1024,
|
||||
logf: logf, state: state,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Run syncs every mount until ctx is cancelled.
|
||||
|
|
@ -82,6 +91,9 @@ func (d *Daemon) setBase(m config.Mount, base string) {
|
|||
func (d *Daemon) runMount(ctx context.Context, m config.Mount) {
|
||||
c := transport.New(m.Hub)
|
||||
c.SetBearer(d.cfg.Bearer)
|
||||
if d.maxBytesPerSec > 0 {
|
||||
c.SetRateLimit(d.maxBytesPerSec)
|
||||
}
|
||||
|
||||
trigger := make(chan struct{}, 1)
|
||||
nudge := func() {
|
||||
|
|
@ -142,7 +154,7 @@ func (d *Daemon) syncMount(c *transport.Client, m config.Mount) {
|
|||
return
|
||||
}
|
||||
base := d.getBase(m)
|
||||
now := time.Now().Unix()
|
||||
now := time.Now().UnixNano() // nanoseconds so conflict-copy names don't collide
|
||||
|
||||
if m.ReadOnly {
|
||||
pr, err := syncer.Pull(c, m.Local, m.Share, base, d.host, now, ig, d.guard)
|
||||
|
|
@ -165,11 +177,15 @@ func (d *Daemon) syncMount(c *transport.Client, m config.Mount) {
|
|||
}
|
||||
|
||||
func (d *Daemon) report(m config.Mount, pr syncer.PullResult) {
|
||||
if len(pr.Written)+len(pr.Deleted)+len(pr.Conflicts) == 0 {
|
||||
if len(pr.Written)+len(pr.Deleted)+len(pr.Conflicts)+len(pr.Skipped) == 0 {
|
||||
return
|
||||
}
|
||||
d.logf("📥 %s: %d written, %d deleted, %d conflicts", m.Share, len(pr.Written), len(pr.Deleted), len(pr.Conflicts))
|
||||
d.logf("📥 %s: %d written, %d deleted, %d conflicts, %d skipped",
|
||||
m.Share, len(pr.Written), len(pr.Deleted), len(pr.Conflicts), len(pr.Skipped))
|
||||
for _, cf := range pr.Conflicts {
|
||||
d.logf(" 💥 conflict copy: %s", cf)
|
||||
}
|
||||
for _, sk := range pr.Skipped {
|
||||
d.logf(" ⚠️ skipped (filesystem clash): %s", sk)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/chunk"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/ignore"
|
||||
|
|
@ -58,6 +59,9 @@ func Build(root string, ig *ignore.Matcher, guard *secret.Guard) (Manifest, []st
|
|||
if !d.Type().IsRegular() {
|
||||
return nil // ponytail: symlinks/specials unsupported in v1
|
||||
}
|
||||
if strings.HasPrefix(d.Name(), ".devbox-tmp-") {
|
||||
return nil // transient atomic-write temp file; never sync
|
||||
}
|
||||
if ig != nil && ig.Match(rel, false) {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -140,7 +144,7 @@ func Diff(old, cur Manifest) Changes {
|
|||
oe, ok := om[path]
|
||||
if !ok {
|
||||
ch.Added = append(ch.Added, path)
|
||||
} else if !sameContent(oe, ce) {
|
||||
} else if !SameContent(oe, ce) {
|
||||
ch.Modified = append(ch.Modified, path)
|
||||
}
|
||||
}
|
||||
|
|
@ -163,7 +167,9 @@ func index(m Manifest) map[string]Entry {
|
|||
return idx
|
||||
}
|
||||
|
||||
func sameContent(a, b Entry) bool {
|
||||
// SameContent reports whether two entries have identical size, mode, and chunk
|
||||
// list (i.e. the same file content + permissions).
|
||||
func SameContent(a, b Entry) bool {
|
||||
if a.Size != b.Size || a.Mode != b.Mode || len(a.Chunks) != len(b.Chunks) {
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ type PullResult struct {
|
|||
Written []string // files written/updated from the hub
|
||||
Deleted []string // files deleted to match the hub
|
||||
Conflicts []string // conflict copies created (local edits preserved beside canonical)
|
||||
Skipped []string // paths a filesystem error skipped (e.g. file<->dir clash)
|
||||
}
|
||||
|
||||
// Pull fetches the hub head manifest for share, three-way merges it against the
|
||||
|
|
@ -60,8 +61,8 @@ func Pull(c *transport.Client, root, share, base, host string, now int64, ig *ig
|
|||
oe, oOK := oi[p]
|
||||
te, tOK := ti[p]
|
||||
|
||||
oursCh := oOK != bOK || (oOK && bOK && !sameEntry(oe, be))
|
||||
theirsCh := tOK != bOK || (tOK && bOK && !sameEntry(te, be))
|
||||
oursCh := oOK != bOK || (oOK && bOK && !manifest.SameContent(oe, be))
|
||||
theirsCh := tOK != bOK || (tOK && bOK && !manifest.SameContent(te, be))
|
||||
if !theirsCh {
|
||||
continue // hub didn't touch p; local state (changed or not) stands
|
||||
}
|
||||
|
|
@ -70,38 +71,50 @@ func Pull(c *transport.Client, root, share, base, host string, now int64, ig *ig
|
|||
case !oursCh:
|
||||
// Hub-only change: apply it verbatim.
|
||||
if tOK {
|
||||
if err := writeFileFromChunks(c, root, te); err != nil {
|
||||
return PullResult{}, err
|
||||
if fsErr, err := writeEntry(c, root, te); err != nil {
|
||||
if !fsErr {
|
||||
return PullResult{}, err // network error: abort, retry whole sync
|
||||
}
|
||||
res.Written = append(res.Written, p)
|
||||
res.Skipped = append(res.Skipped, p) // e.g. path is now a directory
|
||||
} else {
|
||||
if err := deleteFile(root, p); err != nil {
|
||||
return PullResult{}, err
|
||||
res.Written = append(res.Written, p)
|
||||
}
|
||||
} else if err := deleteFile(root, p); err != nil {
|
||||
res.Skipped = append(res.Skipped, p)
|
||||
} else {
|
||||
res.Deleted = append(res.Deleted, p)
|
||||
}
|
||||
|
||||
case tOK && oOK && sameEntry(te, oe):
|
||||
case tOK && oOK && manifest.SameContent(te, oe):
|
||||
// Both made the identical change — already in agreement.
|
||||
|
||||
case tOK && oOK:
|
||||
// Both edited differently: preserve ours as a conflict copy, hub canonical.
|
||||
cp, err := preserveAsConflict(root, p, host, now)
|
||||
if err != nil {
|
||||
return PullResult{}, err
|
||||
}
|
||||
if err := writeFileFromChunks(c, root, te); err != nil {
|
||||
cp, cerr := preserveAsConflict(root, p, host, now)
|
||||
if cerr != nil {
|
||||
res.Skipped = append(res.Skipped, p) // couldn't preserve ours; never clobber
|
||||
continue
|
||||
}
|
||||
if fsErr, err := writeEntry(c, root, te); err != nil {
|
||||
if !fsErr {
|
||||
return PullResult{}, err
|
||||
}
|
||||
res.Skipped = append(res.Skipped, p)
|
||||
} else {
|
||||
res.Conflicts = append(res.Conflicts, cp)
|
||||
res.Written = append(res.Written, p)
|
||||
}
|
||||
|
||||
case tOK && !oOK:
|
||||
// Ours deleted, hub edited: hub wins (a delete has no bytes to keep).
|
||||
if err := writeFileFromChunks(c, root, te); err != nil {
|
||||
if fsErr, err := writeEntry(c, root, te); err != nil {
|
||||
if !fsErr {
|
||||
return PullResult{}, err
|
||||
}
|
||||
res.Skipped = append(res.Skipped, p)
|
||||
} else {
|
||||
res.Written = append(res.Written, p)
|
||||
}
|
||||
|
||||
default:
|
||||
// Hub deleted, ours edited (!tOK && oOK): the edit wins — keep ours,
|
||||
|
|
@ -162,36 +175,31 @@ func unionKeys(maps ...map[string]manifest.Entry) map[string]struct{} {
|
|||
return u
|
||||
}
|
||||
|
||||
func sameEntry(a, b manifest.Entry) bool {
|
||||
if a.Size != b.Size || a.Mode != b.Mode || len(a.Chunks) != len(b.Chunks) {
|
||||
return false
|
||||
}
|
||||
for i := range a.Chunks {
|
||||
if a.Chunks[i] != b.Chunks[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeFileFromChunks(c *transport.Client, root string, e manifest.Entry) error {
|
||||
// writeEntry downloads e's content and writes it atomically. A network/download
|
||||
// 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, err := c.GetBlob(h)
|
||||
if err != nil {
|
||||
return err
|
||||
b, gerr := c.GetBlob(h)
|
||||
if gerr != nil {
|
||||
return false, gerr // network
|
||||
}
|
||||
buf = append(buf, b...)
|
||||
}
|
||||
dst := filepath.Join(root, filepath.FromSlash(e.Path))
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return err
|
||||
if merr := os.MkdirAll(filepath.Dir(dst), 0o755); merr != nil {
|
||||
return true, merr
|
||||
}
|
||||
mode := os.FileMode(e.Mode)
|
||||
if mode == 0 {
|
||||
mode = 0o644
|
||||
}
|
||||
return atomicWrite(dst, buf, mode)
|
||||
if werr := atomicWrite(dst, buf, mode); werr != nil {
|
||||
return true, werr
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func deleteFile(root, relPath string) error {
|
||||
|
|
@ -207,13 +215,25 @@ func deleteFile(root, relPath string) error {
|
|||
func preserveAsConflict(root, relPath, host string, ts int64) (string, error) {
|
||||
ext := filepath.Ext(relPath)
|
||||
stem := strings.TrimSuffix(relPath, ext)
|
||||
cp := fmt.Sprintf("%s.conflict-%s-%d%s", stem, host, ts, ext)
|
||||
src := filepath.Join(root, filepath.FromSlash(relPath))
|
||||
// Probe for a free name (ts is nanoseconds, so collisions are already rare;
|
||||
// the counter is belt-and-suspenders against ever overwriting a prior copy).
|
||||
for n := 0; ; n++ {
|
||||
cp := fmt.Sprintf("%s.conflict-%s-%d%s", stem, host, ts, ext)
|
||||
if n > 0 {
|
||||
cp = fmt.Sprintf("%s.conflict-%s-%d-%d%s", stem, host, ts, n, ext)
|
||||
}
|
||||
dst := filepath.Join(root, filepath.FromSlash(cp))
|
||||
if _, err := os.Stat(dst); err == nil {
|
||||
continue // taken
|
||||
} else if !os.IsNotExist(err) {
|
||||
return "", err
|
||||
}
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return cp, nil
|
||||
}
|
||||
}
|
||||
|
||||
// atomicWrite writes data to path via a temp file + rename (atomic on POSIX and
|
||||
|
|
|
|||
|
|
@ -139,3 +139,43 @@ func TestPullDeleteAndEditBeatsDelete(t *testing.T) {
|
|||
t.Fatal("hub delete did not propagate to B")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPullSkipsFileDirClash: a hub file whose local path is a directory must be
|
||||
// skipped (recorded), not abort the whole pull (C3 resilience).
|
||||
func TestPullSkipsFileDirClash(t *testing.T) {
|
||||
db, _ := meta.Open(":memory:")
|
||||
defer db.Close()
|
||||
store, _ := blobstore.NewDisk(t.TempDir())
|
||||
srv := httptest.NewServer(hub.NewServer(db, store).Handler())
|
||||
defer srv.Close()
|
||||
guard, _ := secret.New(nil)
|
||||
ig, _ := LoadIgnore(t.TempDir())
|
||||
|
||||
A := joinDevice(t, db, srv.URL, "alice")
|
||||
B := joinDevice(t, db, srv.URL, "bob")
|
||||
_ = A.Publish("s")
|
||||
|
||||
rootA := t.TempDir()
|
||||
writeFile(t, rootA, "data", "hello\n")
|
||||
writeFile(t, rootA, "ok.txt", "fine\n")
|
||||
if _, _, err := Sync(A, rootA, "s", "", "alice", 1, ig, guard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Bob's mount has a DIRECTORY where the hub has a file "data".
|
||||
rootB := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(rootB, "data", "child"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pr, err := Pull(B, rootB, "s", "", "bob", 2, ig, guard)
|
||||
if err != nil {
|
||||
t.Fatalf("pull must not abort on a file/dir clash: %v", err)
|
||||
}
|
||||
if len(pr.Skipped) != 1 || pr.Skipped[0] != "data" {
|
||||
t.Fatalf("Skipped = %v, want [data]", pr.Skipped)
|
||||
}
|
||||
// The non-clashing file still applied.
|
||||
if !exists(rootB, "ok.txt") {
|
||||
t.Fatal("ok.txt should have been written despite the data/ clash")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
|
|
@ -26,6 +28,7 @@ type Client struct {
|
|||
base string // hub base URL, e.g. "http://host:8080"
|
||||
bearer string // device bearer token; empty until Join
|
||||
hc *http.Client
|
||||
limiter *rate.Limiter // optional blob-transfer rate cap; nil = unlimited
|
||||
}
|
||||
|
||||
// New returns a Client for the hub at base (e.g. "http://host:8080").
|
||||
|
|
@ -124,7 +127,7 @@ func (c *Client) GetBlob(hash string) ([]byte, error) {
|
|||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
body, err := io.ReadAll(c.limit(resp.Body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -194,10 +197,11 @@ func (c *Client) do(method, path string, auth bool, body, out any) error {
|
|||
|
||||
// raw sends raw bytes (used for blob uploads) with the bearer header set.
|
||||
func (c *Client) raw(method, path string, data []byte) error {
|
||||
req, err := http.NewRequest(method, c.base+path, bytes.NewReader(data))
|
||||
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")
|
||||
req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer)
|
||||
resp, err := c.hc.Do(req)
|
||||
|
|
|
|||
45
internal/transport/ratelimit.go
Normal file
45
internal/transport/ratelimit.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
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
|
||||
}
|
||||
47
internal/transport/ratelimit_test.go
Normal file
47
internal/transport/ratelimit_test.go
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestRateLimitThrottles checks the limiter can't transfer faster than its cap
|
||||
// (a reliable lower bound — it may be slower, never faster).
|
||||
func TestRateLimitThrottles(t *testing.T) {
|
||||
c := New("http://x")
|
||||
c.SetRateLimit(100 * 1024) // 100 KiB/s
|
||||
|
||||
const n = 250 * 1024 // 250 KiB -> ~2.5s at the cap
|
||||
start := time.Now()
|
||||
got, err := io.Copy(io.Discard, c.limit(bytes.NewReader(make([]byte, n))))
|
||||
elapsed := time.Since(start)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != n {
|
||||
t.Fatalf("copied %d bytes, want %d", got, n)
|
||||
}
|
||||
// Allow generous slack but ensure it actually throttled (burst lets the first
|
||||
// 64 KiB through free, so expect at least ~1.5s for the remaining ~186 KiB).
|
||||
if elapsed < 1200*time.Millisecond {
|
||||
t.Fatalf("transfer took %v, expected the 100 KiB/s cap to slow it down", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimitUnlimitedByDefault(t *testing.T) {
|
||||
c := New("http://x")
|
||||
if c.limiter != nil {
|
||||
t.Fatal("new client should be unlimited")
|
||||
}
|
||||
c.SetRateLimit(0)
|
||||
if c.limiter != nil {
|
||||
t.Fatal("SetRateLimit(0) should clear the limiter")
|
||||
}
|
||||
// limit() is a pass-through when unset.
|
||||
r := bytes.NewReader([]byte("hi"))
|
||||
if c.limit(r) != r {
|
||||
t.Fatal("limit() should return the reader unchanged when unlimited")
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue