Skip to content

Commit dff7387

Browse files
Replace fastrand with rand/v2 package
Signed-off-by: Amirali Amirifar <amirali.amirifar@gmail.com>
1 parent 6f3d85d commit dff7387

9 files changed

Lines changed: 145 additions & 298 deletions

File tree

internal/fastrand/LICENSE

Lines changed: 0 additions & 27 deletions
This file was deleted.

internal/fastrand/fastrand.go

Lines changed: 0 additions & 23 deletions
This file was deleted.

internal/fastrand/fastrand_test.go

Lines changed: 0 additions & 72 deletions
This file was deleted.

server/accounts.go

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import (
2222
"io"
2323
"io/fs"
2424
"math"
25-
"math/rand"
25+
"math/rand/v2"
2626
"net/http"
2727
"net/textproto"
2828
"reflect"
@@ -34,7 +34,6 @@ import (
3434
"time"
3535

3636
"github.com/nats-io/jwt/v2"
37-
"github.com/nats-io/nats-server/v2/internal/fastrand"
3837
"github.com/nats-io/nkeys"
3938
"github.com/nats-io/nuid"
4039
)
@@ -802,7 +801,7 @@ func (a *Account) AddWeightedMappings(src string, dests ...*MapDest) error {
802801
m := &mapping{src: src, wc: subjectHasWildcard(src), dests: make([]*destination, 0, len(dests)+1)}
803802
seen := make(map[string]struct{})
804803

805-
var tw = make(map[string]uint8)
804+
tw := make(map[string]uint8)
806805
for _, d := range dests {
807806
if _, ok := seen[d.Subject]; ok {
808807
return fmt.Errorf("duplicate entry for %q", d.Subject)
@@ -1006,7 +1005,7 @@ func (a *Account) selectMappedSubject(dest string) (string, bool) {
10061005
if len(dests) == 1 && dests[0].weight == 100 {
10071006
d = dests[0]
10081007
} else {
1009-
w := uint8(fastrand.Uint32n(100))
1008+
w := uint8(rand.Uint32N(100))
10101009
for _, rm := range dests {
10111010
if w < rm.weight {
10121011
d = rm
@@ -1217,7 +1216,8 @@ func (a *Account) AddServiceExportWithResponse(subject string, respType ServiceR
12171216

12181217
// AddServiceExportWithresponse will configure the account with the defined export and response type.
12191218
func (a *Account) addServiceExportWithResponseAndAccountPos(
1220-
subject string, respType ServiceRespType, accounts []*Account, accountPos uint) error {
1219+
subject string, respType ServiceRespType, accounts []*Account, accountPos uint,
1220+
) error {
12211221
if a == nil {
12221222
return ErrMissingAccount
12231223
}
@@ -2388,7 +2388,7 @@ func shouldSample(l *serviceLatency, c *client) (bool, http.Header) {
23882388
if l.sampling >= 100 {
23892389
return true, nil
23902390
}
2391-
if l.sampling > 0 && rand.Int31n(100) <= int32(l.sampling) {
2391+
if l.sampling > 0 && rand.Int32N(100) <= int32(l.sampling) {
23922392
return true, nil
23932393
}
23942394
h := c.parseState.getHeader()
@@ -2480,8 +2480,8 @@ func (a *Account) processServiceImportResponse(sub *subscription, c *client, _ *
24802480
// for all service replies, unless we are bound to a leafnode.
24812481
// Lock should be held.
24822482
func (a *Account) createRespWildcard() {
2483-
var b = [baseServerLen]byte{'_', 'R', '_', '.'}
2484-
rn := fastrand.Uint64()
2483+
b := [baseServerLen]byte{'_', 'R', '_', '.'}
2484+
rn := rand.Uint64()
24852485
for i, l := replyPrefixLen, rn; i < len(b); i++ {
24862486
b[i] = digits[l%base]
24872487
l /= base
@@ -2500,7 +2500,7 @@ func isTrackedReply(reply []byte) bool {
25002500
func (a *Account) newServiceReply(tracking bool) []byte {
25012501
a.mu.Lock()
25022502
s := a.srv
2503-
rn := fastrand.Uint64()
2503+
rn := rand.Uint64()
25042504

25052505
// Check if we need to create the reply here.
25062506
var createdSiReply bool
@@ -3609,7 +3609,8 @@ func (s *Server) updateAccountClaimsWithRefresh(a *Account, ac *jwt.AccountClaim
36093609
case jwt.Stream:
36103610
s.Debugf("Adding stream export %q for %s", e.Subject, tl)
36113611
if err := a.addStreamExportWithAccountPos(
3612-
string(e.Subject), authAccounts(e.TokenReq), e.AccountTokenPosition); err != nil {
3612+
string(e.Subject), authAccounts(e.TokenReq), e.AccountTokenPosition,
3613+
); err != nil {
36133614
s.Debugf("Error adding stream export to account [%s]: %v", tl, err.Error())
36143615
}
36153616
case jwt.Service:
@@ -3622,7 +3623,8 @@ func (s *Server) updateAccountClaimsWithRefresh(a *Account, ac *jwt.AccountClaim
36223623
rt = Chunked
36233624
}
36243625
if err := a.addServiceExportWithResponseAndAccountPos(
3625-
string(e.Subject), rt, authAccounts(e.TokenReq), e.AccountTokenPosition); err != nil {
3626+
string(e.Subject), rt, authAccounts(e.TokenReq), e.AccountTokenPosition,
3627+
); err != nil {
36263628
s.Debugf("Error adding service export to account [%s]: %v", tl, err)
36273629
continue
36283630
}
@@ -4133,7 +4135,7 @@ func buildInternalNkeyUser(uc *jwt.UserClaims, acts map[string]struct{}, acc *Ac
41334135
}
41344136

41354137
// Now check for permissions.
4136-
var p = buildPermissionsFromJwt(&uc.Permissions)
4138+
p := buildPermissionsFromJwt(&uc.Permissions)
41374139
if p == nil {
41384140
nu.defaultPerms = true
41394141
acc.mu.RLock()

server/client.go

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import (
2424
"fmt"
2525
"io"
2626
"math"
27-
"math/rand"
27+
"math/rand/v2"
2828
"net"
2929
"net/http"
3030
"net/url"
@@ -39,7 +39,6 @@ import (
3939

4040
"github.com/klauspost/compress/s2"
4141
"github.com/nats-io/jwt/v2"
42-
"github.com/nats-io/nats-server/v2/internal/fastrand"
4342
)
4443

4544
// Type of client connection.
@@ -229,6 +228,7 @@ const (
229228

230229
// Some flags passed to processMsgResults
231230
const pmrNoFlag int = 0
231+
232232
const (
233233
pmrCollectQueueNames int = 1 << iota
234234
pmrIgnoreEmptyQueueFilter
@@ -362,9 +362,11 @@ type outbound struct {
362362

363363
const nbMaxVectorSize = 1024 // == IOV_MAX on Linux/Darwin and most other Unices (except Solaris/AIX)
364364

365-
const nbPoolSizeSmall = 512 // Underlying array size of small buffer
366-
const nbPoolSizeMedium = 4096 // Underlying array size of medium buffer
367-
const nbPoolSizeLarge = 65536 // Underlying array size of large buffer
365+
const (
366+
nbPoolSizeSmall = 512 // Underlying array size of small buffer
367+
nbPoolSizeMedium = 4096 // Underlying array size of medium buffer
368+
nbPoolSizeLarge = 65536 // Underlying array size of large buffer
369+
)
368370

369371
var nbPoolSmall = &sync.Pool{
370372
New: func() any {
@@ -703,8 +705,10 @@ type ClientOpts struct {
703705
ProxySig string `json:"proxy_sig,omitempty"`
704706
}
705707

706-
var defaultOpts = ClientOpts{Verbose: true, Pedantic: true, Echo: true}
707-
var internalOpts = ClientOpts{Verbose: false, Pedantic: false, Echo: false}
708+
var (
709+
defaultOpts = ClientOpts{Verbose: true, Pedantic: true, Echo: true}
710+
internalOpts = ClientOpts{Verbose: false, Pedantic: false, Echo: false}
711+
)
708712

709713
func (c *client) setTraceLevel() {
710714
if c.kind == SYSTEM && !(atomic.LoadInt32(&c.srv.logging.traceSysAcc) != 0) {
@@ -720,7 +724,7 @@ func (c *client) initClient() {
720724
c.cid = atomic.AddUint64(&s.gcid, 1)
721725

722726
// Outbound data structure setup
723-
c.out.sg = sync.NewCond(&(c.mu))
727+
c.out.sg = sync.NewCond(&c.mu)
724728
opts := s.getOpts()
725729
// Snapshots to avoid mutex access in fast paths.
726730
c.out.wdl = opts.WriteDeadline
@@ -1691,7 +1695,7 @@ func (c *client) readLoop(pre []byte) {
16911695
return
16921696
}
16931697

1694-
if cpacc && (c.in.start.Sub(lpacc)) >= closedSubsCheckInterval {
1698+
if cpacc && c.in.start.Sub(lpacc) >= closedSubsCheckInterval {
16951699
c.pruneClosedSubFromPerAccountCache()
16961700
lpacc = time.Now()
16971701
}
@@ -5239,7 +5243,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
52395243
}
52405244

52415245
var rplyHasGWPrefix bool
5242-
var creply = reply
5246+
creply := reply
52435247

52445248
// If the reply subject is a GW routed reply, we will perform some
52455249
// tracking in deliverMsg(). We also want to send to the user the
@@ -5513,7 +5517,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
55135517
// We already have a LEAF and this is another one.
55145518
// Flip a coin to see if we swap it or not.
55155519
// See https://github.com/nats-io/nats-server/issues/6040
5516-
if fastrand.Uint32()%2 == 1 {
5520+
if rand.Uint32()%2 == 1 {
55175521
rsub = sub
55185522
}
55195523
}
@@ -5527,7 +5531,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
55275531
sindex := 0
55285532
lqs := len(qsubs)
55295533
if lqs > 1 {
5530-
sindex = int(fastrand.Uint32() % uint32(lqs))
5534+
sindex = int(rand.Uint32() % uint32(lqs))
55315535
}
55325536

55335537
// Find a subscription that is able to deliver this message starting at a random index.
@@ -6326,12 +6330,12 @@ func (c *client) clearAccountSubs(close bool) {
63266330
// Process any qsubs here.
63276331
for _, esub := range qsubs {
63286332
if !spoke {
6329-
srv.updateRouteSubscriptionMap(acc, esub.sub, -(esub.n))
6333+
srv.updateRouteSubscriptionMap(acc, esub.sub, -esub.n)
63306334
if srv.gateway.enabled {
6331-
srv.gatewayUpdateSubInterest(acc.Name, esub.sub, -(esub.n))
6335+
srv.gatewayUpdateSubInterest(acc.Name, esub.sub, -esub.n)
63326336
}
63336337
}
6334-
acc.updateLeafNodes(esub.sub, -(esub.n))
6338+
acc.updateLeafNodes(esub.sub, -esub.n)
63356339
}
63366340
}
63376341

@@ -7030,7 +7034,7 @@ func (c *client) setFirstPingTimer() {
70307034
}
70317035
}
70327036
// We randomize the first one by an offset up to 20%, e.g. 2m ~= max 24s.
7033-
addDelay := rand.Int63n(int64(d / 5))
7037+
addDelay := rand.Int64N(int64(d / 5))
70347038
d += time.Duration(addDelay)
70357039
// In the case of ROUTER/LEAF and when compression is configured, it is possible
70367040
// that this timer was already set, but just to detect a stale connection

0 commit comments

Comments
 (0)