Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enable gomnd linter #1048

Merged
merged 14 commits into from
Apr 10, 2024
4 changes: 3 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,6 @@ linters:
- godot
- goerr113
- golint
- gomnd
- ifshort
- interfacebloat
- ireturn
Expand Down Expand Up @@ -304,6 +303,9 @@ issues:
- staticcheck
- path: _test\.go
text: "ydb.Connection is deprecated"
- path: examples
linters:
- gomnd

# Allow underscore and capital camel case for readability
# Examples: Type_PRIMITIVE_TYPE_ID_UNSPECIFIED, Ydb_Discovery_V1, _voidValue
Expand Down
2 changes: 1 addition & 1 deletion internal/allocator/allocator.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ type structAllocator struct {
func (a *structAllocator) Struct() (v *Ydb.StructType) {
v = structPool.Get()
if cap(v.GetMembers()) <= 0 {
v.Members = make([]*Ydb.StructMember, 0, 10)
v.Members = make([]*Ydb.StructMember, 0, 10) //nolint:gomnd
}
a.allocations = append(a.allocations, v)

Expand Down
4 changes: 2 additions & 2 deletions internal/backoff/backoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ const (
var (
Fast = New(
WithSlotDuration(fastSlot),
WithCeiling(6),
WithCeiling(6), //nolint:gomnd
)
Slow = New(
WithSlotDuration(slowSlot),
WithCeiling(6),
WithCeiling(6), //nolint:gomnd
)
)

Expand Down
2 changes: 1 addition & 1 deletion internal/balancer/local_dc.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func detectFastestEndpoint(ctx context.Context, endpoints []endpoint.Endpoint) (

var lastErr error
// common is 2 ip address for every fqdn: ipv4 + ipv6
initialAddressToEndpointCapacity := len(endpoints) * 2
initialAddressToEndpointCapacity := len(endpoints) * 2 //nolint:gomnd
addressToEndpoint := make(map[string]endpoint.Endpoint, initialAddressToEndpointCapacity)
for _, ep := range endpoints {
host, port, err := extractHostPort(ep.Address())
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/gtrace/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func main() {
f, err = os.OpenFile(
filepath.Join(workDir, filepath.Clean(name)),
os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
0o600,
0o600, //nolint:gomnd
)
if err != nil {
log.Fatal(err)
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/gtrace/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -1028,7 +1028,7 @@ func (s *scope) set(v string) bool {
if _, has := s.vars[v]; has {
return false
}
_, file, line, _ := runtime.Caller(2)
_, file, line, _ := runtime.Caller(2) //nolint:gomnd
s.vars[v] = decl{
where: fmt.Sprintf("%s:%d", file, line),
}
Expand Down
2 changes: 1 addition & 1 deletion internal/conn/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ func NewPool(ctx context.Context, config Config) *Pool {
}

if ttl := config.ConnectionTTL(); ttl > 0 {
go p.connParker(xcontext.ValueOnly(ctx), ttl, ttl/2)
go p.connParker(xcontext.ValueOnly(ctx), ttl, ttl/2) //nolint:gomnd
}

return p
Expand Down
6 changes: 3 additions & 3 deletions internal/coordination/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,11 @@ func (c *Client) closeSessions(ctx context.Context) {
func defaultCreateSessionConfig() *options.CreateSessionOptions {
return &options.CreateSessionOptions{
Description: "YDB Go SDK",
SessionTimeout: time.Second * 5,
SessionTimeout: time.Second * 5, //nolint:gomnd
SessionStartTimeout: time.Second * 1,
SessionStopTimeout: time.Second * 1,
SessionKeepAliveTimeout: time.Second * 10,
SessionReconnectDelay: time.Millisecond * 500,
SessionKeepAliveTimeout: time.Second * 10, //nolint:gomnd
SessionReconnectDelay: time.Millisecond * 500, //nolint:gomnd
}
}

Expand Down
6 changes: 3 additions & 3 deletions internal/coordination/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func createSession(
}

func newProtectionKey() []byte {
key := make([]byte, 8)
key := make([]byte, 8) //nolint:gomnd
binary.LittleEndian.PutUint64(key, rand.Uint64()) //nolint:gosec

return key
Expand Down Expand Up @@ -120,7 +120,7 @@ func (s *session) newStream(
deadline = s.getLastGoodResponseTime().Add(s.options.SessionTimeout)
} else {
// Large enough to make the loop infinite, small enough to allow the maximum duration value (~290 years).
deadline = time.Now().Add(time.Hour * 24 * 365 * 100)
deadline = time.Now().Add(time.Hour * 24 * 365 * 100) //nolint:gomnd
}

lastChance := false
Expand Down Expand Up @@ -230,7 +230,7 @@ func (s *session) mainLoop(path string, sessionStartedChan chan struct{}) {

// Start the loops.
wg := sync.WaitGroup{}
wg.Add(2)
wg.Add(2) //nolint:gomnd
sessionStarted := make(chan *Ydb_Coordination.SessionResponse_SessionStarted, 1)
sessionStopped := make(chan *Ydb_Coordination.SessionResponse_SessionStopped, 1)
startSending := make(chan struct{})
Expand Down
4 changes: 3 additions & 1 deletion internal/credentials/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (
"github.com/ydb-platform/ydb-go-sdk/v3/internal/xstring"
)

const TokenRefreshDivisor = 10

var (
_ Credentials = (*Static)(nil)
_ fmt.Stringer = (*Static)(nil)
Expand Down Expand Up @@ -133,7 +135,7 @@ func (c *Static) Token(ctx context.Context) (token string, err error) {
return "", xerrors.WithStackTrace(err)
}

c.requestAt = time.Now().Add(time.Until(expiresAt) / 10)
c.requestAt = time.Now().Add(time.Until(expiresAt) / TokenRefreshDivisor)
c.token = result.GetToken()

return c.token, nil
Expand Down
16 changes: 10 additions & 6 deletions internal/decimal/decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,19 @@ import (
"github.com/ydb-platform/ydb-go-sdk/v3/internal/xstring"
)

const wordSize = bits.UintSize / 8
const (
wordSize = bits.UintSize / 8
bufferSize = 40
negMask = 0x80
)

var (
ten = big.NewInt(10)
ten = big.NewInt(10) //nolint:gomnd
zero = big.NewInt(0)
one = big.NewInt(1)
inf = big.NewInt(0).Mul(
big.NewInt(100000000000000000),
big.NewInt(1000000000000000000),
big.NewInt(100000000000000000), //nolint:gomnd
big.NewInt(1000000000000000000), //nolint:gomnd
)
nan = big.NewInt(0).Add(inf, one)
err = big.NewInt(0).Add(nan, one)
Expand Down Expand Up @@ -58,7 +62,7 @@ func FromBytes(bts []byte, precision, scale uint32) *big.Int {

v.SetBytes(bts)

neg := bts[0]&0x80 != 0
neg := bts[0]&negMask != 0
if neg {
// Given bytes contains negative value.
// Interpret is as two's complement.
Expand Down Expand Up @@ -216,7 +220,7 @@ func Format(x *big.Int, precision, scale uint32) string {

// log_{10}(2^120) ~= 36.12, 37 decimal places
// plus dot, zero before dot, sign.
bts := make([]byte, 40)
bts := make([]byte, bufferSize)
pos := len(bts)

var digit big.Int
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ func sendWriteRequest(send sendFunc, req *Ydb_Topic.StreamWriteMessage_FromClien
return sendErr
}

//nolint:gomnd
splitIndex := len(grpcMessages) / 2
firstMessages, lastMessages := grpcMessages[:splitIndex], grpcMessages[splitIndex:]
defer func() {
Expand Down
2 changes: 1 addition & 1 deletion internal/meta/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func WithRequestType(ctx context.Context, requestType string) context.Context {

// WithAllowFeatures returns a copy of parent context with allowed client feature
func WithAllowFeatures(ctx context.Context, features ...string) context.Context {
kv := make([]string, 0, len(features)*2)
kv := make([]string, 0, len(features)*2) //nolint:gomnd
for _, feature := range features {
kv = append(kv, HeaderClientCapabilities, feature)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/repeater/repeater.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,8 @@ func (r *repeater) worker(ctx context.Context, tick clockwork.Ticker) {

// force returns backoff with delays [500ms...32s]
force := backoff.New(
backoff.WithSlotDuration(500*time.Millisecond),
backoff.WithCeiling(6),
backoff.WithSlotDuration(500*time.Millisecond), //nolint:gomnd
backoff.WithCeiling(6), //nolint:gomnd
backoff.WithJitterLimit(1),
)

Expand Down
4 changes: 3 additions & 1 deletion internal/secret/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import (
"hash/crc32"
)

const minTokenLength = 16

func Token(token string) string {
var mask bytes.Buffer
if len(token) > 16 {
if len(token) > minTokenLength {
mask.WriteString(token[:4])
mask.WriteString("****")
mask.WriteString(token[len(token)-4:])
Expand Down
2 changes: 1 addition & 1 deletion internal/stack/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func (c call) Record(opts ...recordOption) string {
if len(split) > 1 {
funcName = split[len(split)-1]
}
if len(split) > 2 {
if len(split) > 2 { //nolint:gomnd
structName = split[1]
}

Expand Down
2 changes: 1 addition & 1 deletion internal/table/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ func (c *Client) internalPoolGC(ctx context.Context, idleThreshold time.Duration

case <-timer.Chan():
c.internalPoolGCTick(ctx, idleThreshold)
timer.Reset(idleThreshold / 2)
timer.Reset(idleThreshold / 2) //nolint:gomnd
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion internal/table/scanner/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ func (r *unaryResult) NextResultSet(ctx context.Context, columns ...string) bool

func (r *streamResult) nextResultSetErr(ctx context.Context, columns ...string) (err error) {
// skipping second recv because first call of recv is from New Stream(), second call is from user
if r.nextResultSetCounter.Add(1) == 2 {
if r.nextResultSetCounter.Add(1) == 2 { //nolint:gomnd
r.setColumnIndexes(columns)

return ctx.Err()
Expand Down
12 changes: 6 additions & 6 deletions internal/table/scanner/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -1174,7 +1174,7 @@ func (s *valueScanner) errorf(depth int, f string, args ...interface{}) error {

func (s *valueScanner) typeError(act, exp interface{}) {
_ = s.errorf(
2,
2, //nolint:gomnd
"unexpected types during scan at %q %s: %s; want %s",
s.path(),
s.getType(),
Expand All @@ -1186,7 +1186,7 @@ func (s *valueScanner) typeError(act, exp interface{}) {
func (s *valueScanner) valueTypeError(act, exp interface{}) {
// unexpected value during scan at \"migration_status\" Int64: NullFlag; want Int64
_ = s.errorf(
2,
2, //nolint:gomnd
"unexpected value during scan at %q %s: %s; want %s",
s.path(),
s.getType(),
Expand All @@ -1197,31 +1197,31 @@ func (s *valueScanner) valueTypeError(act, exp interface{}) {

func (s *valueScanner) notFoundColumnByIndex(idx int) error {
return s.errorf(
2,
2, //nolint:gomnd
"not found %d column",
idx,
)
}

func (s *valueScanner) notFoundColumnName(name string) error {
return s.errorf(
2,
2, //nolint:gomnd
"not found column '%s'",
name,
)
}

func (s *valueScanner) noColumnError(name string) error {
return s.errorf(
2,
2, //nolint:gomnd
"no column %q",
name,
)
}

func (s *valueScanner) overflowError(i, n interface{}) error {
return s.errorf(
2,
2, //nolint:gomnd
"overflow error: %d overflows capacity of %t",
i,
n,
Expand Down
2 changes: 1 addition & 1 deletion internal/topic/retriable_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ type PublicCheckRetryResult struct {
var (
PublicRetryDecisionDefault = PublicCheckRetryResult{val: 0}
PublicRetryDecisionRetry = PublicCheckRetryResult{val: 1}
PublicRetryDecisionStop = PublicCheckRetryResult{val: 2}
PublicRetryDecisionStop = PublicCheckRetryResult{val: 2} //nolint:gomnd
)

func CheckResetReconnectionCounters(lastTry, now time.Time, connectionTimeout time.Duration) bool {
Expand Down
2 changes: 1 addition & 1 deletion internal/topic/topicreaderinternal/committer.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (c *committer) pushCommitsLoop(ctx context.Context) {
var commits CommitRanges
c.m.WithLock(func() {
commits = c.commits
c.commits = NewCommitRangesWithCapacity(commits.len() * 2)
c.commits = NewCommitRangesWithCapacity(commits.len() * 2) //nolint:gomnd
})

if commits.len() == 0 && c.backgroundWorker.Context().Err() != nil {
Expand Down
4 changes: 3 additions & 1 deletion internal/topic/topicreaderinternal/stream_reader_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import (
"github.com/ydb-platform/ydb-go-sdk/v3/trace"
)

const defaultBufferSize = 1024 * 1024

var (
PublicErrCommitSessionToExpiredSession = xerrors.Wrap(errors.New("ydb: commit to expired session"))

Expand Down Expand Up @@ -73,7 +75,7 @@ type topicStreamReaderConfig struct {
func newTopicStreamReaderConfig() topicStreamReaderConfig {
return topicStreamReaderConfig{
BaseContext: context.Background(),
BufferSizeProtoBytes: 1024 * 1024,
BufferSizeProtoBytes: defaultBufferSize,
Cred: credentials.NewAnonymousCredentials(),
CredUpdateInterval: time.Hour,
CommitMode: CommitModeAsync,
Expand Down
2 changes: 1 addition & 1 deletion internal/topic/topicwriterinternal/encoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ func cacheMessages(messages []messageWithDataContent, codec rawtopiccommon.Codec
}

// no need goroutines and synchronization for zero or one worker
if workerCount < 2 {
if workerCount < 2 { //nolint:gomnd
for i := range messages {
if _, err := messages[i].GetEncodedBytes(codec); err != nil {
return err
Expand Down
1 change: 1 addition & 0 deletions internal/topic/topicwriterinternal/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ var (
)

const (
//nolint:gomnd
intSize = 32 << (^uint(0) >> 63) // copy from math package for use in go <= 1.16
maxInt = 1<<(intSize-1) - 1 // copy from math package for use in go <= 1.16
minInt = -1 << (intSize - 1) // copy from math package for use in go <= 1.16
Expand Down
4 changes: 2 additions & 2 deletions internal/topic/topicwriterinternal/writer_reconnector.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ func newWriterReconnectorConfig(options ...PublicWriterOption) WriterReconnector
},
AutoSetSeqNo: true,
AutoSetCreatedTime: true,
MaxMessageSize: 50 * 1024 * 1024,
MaxQueueLen: 1000,
MaxMessageSize: 50 * 1024 * 1024, //nolint:gomnd
MaxQueueLen: 1000, //nolint:gomnd
RetrySettings: topic.RetrySettings{
StartTimeout: topic.DefaultStartTimeout,
},
Expand Down
Loading
Loading