Skip to content

Commit fdb47d9

Browse files
authored
add jitter to sync interval to avoid multiple sync at same time (#27)
1 parent 82553df commit fdb47d9

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

pkg/mirror/helper.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,3 +228,8 @@ func runGitCommand(ctx context.Context, log *slog.Logger, envs []string, cwd str
228228

229229
return stdout, nil
230230
}
231+
232+
// jitter returns a time.Duration between duration and duration + maxFactor * duration.
233+
func jitter(duration time.Duration, maxFactor float64) time.Duration {
234+
return duration + time.Duration(rand.Float64()*maxFactor*float64(duration))
235+
}

pkg/mirror/helper_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"os"
66
"path/filepath"
77
"testing"
8+
"time"
89

910
"github.com/google/go-cmp/cmp"
1011
)
@@ -375,3 +376,37 @@ t1643d7874890dca5982facfba9c4f24da53876e9 4c286e182bc4d1832a8739b18c19ecaf9262c3
375376
})
376377
}
377378
}
379+
380+
func TestJitter(t *testing.T) {
381+
type args struct {
382+
duration time.Duration
383+
maxFactor float64
384+
}
385+
tests := []struct {
386+
name string
387+
args args
388+
minWant time.Duration
389+
maxWant time.Duration
390+
}{
391+
{"1", args{10 * time.Second, 0.1}, 10 * time.Second, 11 * time.Second},
392+
{"2", args{10 * time.Second, 0.5}, 10 * time.Second, 15 * time.Second},
393+
{"3", args{10 * time.Second, 0.0}, 10 * time.Second, 10 * time.Second},
394+
{"4", args{30 * time.Second, 0.1}, 30 * time.Second, 33 * time.Second},
395+
{"5", args{30 * time.Second, 0.5}, 30 * time.Second, 45 * time.Second},
396+
{"6", args{30 * time.Second, 0.0}, 30 * time.Second, 30 * time.Second},
397+
}
398+
for _, tt := range tests {
399+
t.Run(tt.name, func(t *testing.T) {
400+
// since we are using rand test values 10 times
401+
for i := 0; i < 10; i++ {
402+
got := jitter(tt.args.duration, tt.args.maxFactor)
403+
if got < tt.minWant {
404+
t.Errorf("jitter() = %v, min-want %v", got, tt.minWant)
405+
}
406+
if got > tt.maxWant {
407+
t.Errorf("jitter() = %v, max-want %v", got, tt.maxWant)
408+
}
409+
}
410+
})
411+
}
412+
}

pkg/mirror/repository.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,7 @@ func (r *Repository) StartLoop(ctx context.Context) {
408408
}
409409
recordGitMirror(r.gitURL.Repo, err == nil)
410410

411-
t := time.NewTimer(r.interval)
411+
t := time.NewTimer(jitter(r.interval, 0.2))
412412
select {
413413
case <-t.C:
414414
case <-ctx.Done():

0 commit comments

Comments
 (0)