Skip to content

Commit bfd392b

Browse files
authored
fix: use int64 in publisher delay (#19457)
1 parent baf3067 commit bfd392b

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

cryptorand/numbers.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,12 @@ func Int63() (int64, error) {
4747
return rng.Int63(), cs.err
4848
}
4949

50+
// Int63n returns a non-negative integer in [0,maxVal) as an int64.
51+
func Int63n(maxVal int64) (int64, error) {
52+
rng, cs := secureRand()
53+
return rng.Int63n(maxVal), cs.err
54+
}
55+
5056
// Intn returns a non-negative integer in [0,maxVal) as an int.
5157
func Intn(maxVal int) (int, error) {
5258
rng, cs := secureRand()

cryptorand/numbers_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,27 @@ func TestInt63(t *testing.T) {
1919
}
2020
}
2121

22+
func TestInt63n(t *testing.T) {
23+
t.Parallel()
24+
25+
for i := 0; i < 20; i++ {
26+
v, err := cryptorand.Int63n(100)
27+
require.NoError(t, err, "unexpected error from Int63n")
28+
t.Logf("value: %v <- random?", v)
29+
require.GreaterOrEqual(t, v, int64(0), "values must be positive")
30+
require.Less(t, v, int64(100), "values must be less than 100")
31+
}
32+
33+
// Ensure Int63n works for int larger than 32 bits
34+
_, err := cryptorand.Int63n(1 << 35)
35+
require.NoError(t, err, "expected Int63n to work for 64-bit int")
36+
37+
// Expect a panic if max is negative
38+
require.PanicsWithValue(t, "invalid argument to Int63n", func() {
39+
cryptorand.Int63n(0)
40+
})
41+
}
42+
2243
func TestIntn(t *testing.T) {
2344
t.Parallel()
2445

enterprise/coderd/usage/publisher.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,8 @@ func (p *tallymanPublisher) Start() error {
136136
if p.initialDelay <= 0 {
137137
// Pick a random time between tallymanPublishInitialMinimumDelay and
138138
// tallymanPublishInterval.
139-
maxPlusDelay := int(tallymanPublishInterval - tallymanPublishInitialMinimumDelay)
140-
plusDelay, err := cryptorand.Intn(maxPlusDelay)
139+
maxPlusDelay := tallymanPublishInterval - tallymanPublishInitialMinimumDelay
140+
plusDelay, err := cryptorand.Int63n(int64(maxPlusDelay))
141141
if err != nil {
142142
return xerrors.Errorf("could not generate random start delay: %w", err)
143143
}

0 commit comments

Comments
 (0)