Skip to content

Commit 37c9bd9

Browse files
Danielius1922Daniel Adam
authored andcommitted
Fix issues reported by golangsci-lint
1 parent d54e225 commit 37c9bd9

File tree

9 files changed

+57
-31
lines changed

9 files changed

+57
-31
lines changed

.github/workflows/test-with-cfg.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ jobs:
7878
uses: actions/upload-artifact@v4
7979
with:
8080
name: ${{ steps.coverage.outputs.directory }}
81+
# match bridge.coverage.txt, bridge.unit.coverage.txt, coverage.txt, pkg.unit.coverage.txt and schema.unit.coverage.txt
8182
path: .tmp/*coverage.txt
83+
include-hidden-files: true
8284
if-no-files-found: error
8385
retention-days: 1

.golangci.yml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ linters:
2727
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
2828
- bidichk # Checks for dangerous unicode character sequences
2929
- bodyclose # Checks whether HTTP response body is closed successfully
30-
# - copyloopvar # Detects places where loop variables are copied
30+
- copyloopvar # Detects places where loop variables are copied
3131
- decorder # Check declaration order and count of types, constants, variables and functions
3232
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
3333
- dupl # Tool for code clone detection
@@ -37,7 +37,6 @@ linters:
3737
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted.
3838
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
3939
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
40-
- exportloopref # checks for pointers to enclosing loop variables
4140
- forcetypeassert # finds forced type assertions
4241
- gci # Gci control golang package import order and make it always deterministic.
4342
- gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid.

client/client.go

Lines changed: 32 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import (
2828
"github.com/pion/dtls/v2"
2929
"github.com/plgd-dev/device/v2/client/core"
3030
"github.com/plgd-dev/device/v2/client/core/otm"
31+
"github.com/plgd-dev/device/v2/internal/math"
3132
"github.com/plgd-dev/device/v2/pkg/log"
3233
"github.com/plgd-dev/device/v2/pkg/net/coap"
3334
"github.com/plgd-dev/go-coap/v3/net/blockwise"
@@ -51,7 +52,7 @@ type subscription = interface {
5152
}
5253

5354
type Config struct {
54-
DeviceCacheExpirationSeconds int64
55+
DeviceCacheExpirationSeconds uint64
5556
ObserverPollingIntervalSeconds uint64 // 0 means 3 seconds
5657
ObserverFailureThreshold uint8 // 0 means 3
5758

@@ -67,16 +68,27 @@ type Config struct {
6768
DeviceOwnershipBackend *DeviceOwnershipBackendConfig `yaml:",omitempty"`
6869
}
6970

71+
func toDuration(seconds uint64, def time.Duration) (time.Duration, error) {
72+
if seconds == 0 {
73+
return def, nil
74+
}
75+
const maxDurationSeconds uint64 = (1<<63 - 1) / uint64(time.Second)
76+
if seconds > maxDurationSeconds {
77+
return 0, errors.New("invalid value: interval overflows maximal duration")
78+
}
79+
return math.CastTo[time.Duration](seconds * uint64(time.Second)), nil
80+
}
81+
7082
// NewClientFromConfig constructs a new local client from the proto configuration.
7183
func NewClientFromConfig(cfg *Config, app ApplicationCallback, logger core.Logger) (*Client, error) {
72-
var cacheExpiration time.Duration
73-
if cfg.DeviceCacheExpirationSeconds > 0 {
74-
cacheExpiration = time.Second * time.Duration(cfg.DeviceCacheExpirationSeconds)
84+
cacheExpiration, err := toDuration(cfg.DeviceCacheExpirationSeconds, 0)
85+
if err != nil {
86+
return nil, errors.New("invalid DeviceCacheExpirationSeconds value")
7587
}
7688

77-
observerPollingInterval := time.Second * 3
78-
if cfg.ObserverPollingIntervalSeconds > 0 {
79-
observerPollingInterval = time.Second * time.Duration(cfg.ObserverPollingIntervalSeconds)
89+
observerPollingInterval, err := toDuration(cfg.ObserverPollingIntervalSeconds, time.Second*3)
90+
if err != nil {
91+
return nil, errors.New("invalid ObserverPollingIntervalSeconds value")
8092
}
8193

8294
tcpDialOpts := make([]tcp.Option, 0, 5)
@@ -93,20 +105,20 @@ func NewClientFromConfig(cfg *Config, app ApplicationCallback, logger core.Logge
93105
tcpDialOpts = append(tcpDialOpts, options.WithErrors(errFn))
94106
udpDialOpts = append(udpDialOpts, options.WithErrors(errFn))
95107

96-
keepAliveConnectionTimeout := time.Second * 60
97-
if cfg.KeepAliveConnectionTimeoutSeconds > 0 {
98-
keepAliveConnectionTimeout = time.Second * time.Duration(cfg.KeepAliveConnectionTimeoutSeconds)
108+
keepAliveConnectionTimeout, err := toDuration(cfg.KeepAliveConnectionTimeoutSeconds, time.Second*60)
109+
if err != nil {
110+
return nil, errors.New("invalid KeepAliveConnectionTimeoutSeconds value")
99111
}
100112
tcpDialOpts = append(tcpDialOpts, options.WithKeepAlive(3, keepAliveConnectionTimeout/3, func(cc *tcpClient.Conn) {
101-
errFn(fmt.Errorf("keepalive failed for tcp: %v", cc.RemoteAddr()))
102-
if err := cc.Close(); err != nil {
103-
errFn(fmt.Errorf("failed to close tcp connection: %v", cc.RemoteAddr()))
113+
errFn(fmt.Errorf("keepalive failed for tcp %v", cc.RemoteAddr()))
114+
if errC := cc.Close(); errC != nil {
115+
errFn(fmt.Errorf("failed to close tcp connection %v: %w", cc.RemoteAddr(), errC))
104116
}
105117
}))
106118
udpDialOpts = append(udpDialOpts, options.WithKeepAlive(3, keepAliveConnectionTimeout/3, func(cc *udpClient.Conn) {
107-
errFn(fmt.Errorf("keepalive failed for udp: %v", cc.RemoteAddr()))
108-
if err := cc.Close(); err != nil {
109-
errFn(fmt.Errorf("failed to close udp connection: %v", cc.RemoteAddr()))
119+
errFn(fmt.Errorf("keepalive failed for udp %v", cc.RemoteAddr()))
120+
if errC := cc.Close(); errC != nil {
121+
errFn(fmt.Errorf("failed to close udp connection %v: %w", cc.RemoteAddr(), errC))
110122
}
111123
}))
112124

@@ -121,10 +133,11 @@ func NewClientFromConfig(cfg *Config, app ApplicationCallback, logger core.Logge
121133
tcpDialOpts = append(tcpDialOpts, options.WithDisablePeerTCPSignalMessageCSMs())
122134
}
123135

124-
defaultTransferDuration := time.Second * 15
125-
if cfg.DefaultTransferDurationSeconds > 0 {
126-
defaultTransferDuration = time.Second * time.Duration(cfg.DefaultTransferDurationSeconds)
136+
defaultTransferDuration, err := toDuration(cfg.DefaultTransferDurationSeconds, time.Second*15)
137+
if err != nil {
138+
return nil, errors.New("invalid DefaultTransferDurationSeconds value")
127139
}
140+
128141
tcpDialOpts = append(tcpDialOpts, options.WithBlockwise(true, blockwise.SZX1024, defaultTransferDuration))
129142
udpDialOpts = append(udpDialOpts, options.WithBlockwise(true, blockwise.SZX1024, defaultTransferDuration))
130143

client/core/discover.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"sync"
2424
"time"
2525

26+
"github.com/plgd-dev/device/v2/internal/math"
2627
"github.com/plgd-dev/device/v2/pkg/net/coap"
2728
"github.com/plgd-dev/go-coap/v3/message"
2829
"github.com/plgd-dev/go-coap/v3/message/pool"
@@ -128,7 +129,7 @@ func DialDiscoveryAddresses(ctx context.Context, cfg DiscoveryConfiguration, err
128129
// We need to separate messageIDs for upd4 and udp6, because if any docker container has isolated network
129130
// iotivity-lite gets error EINVAL(22) for sendmsg with UDP6 for some interfaces. If it happens, the device is
130131
// not discovered and msgid is cached so all other multicast messages from another interfaces are dropped for deduplication.
131-
msgIDudp4 := uint16(message.GetMID())
132+
msgIDudp4 := math.CastTo[uint16](message.GetMID())
132133
msgIDudp6 := msgIDudp4 + ^uint16(0)/2
133134

134135
for _, address := range cfg.MulticastAddressUDP4 {

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ require (
2222
github.com/ugorji/go/codec v1.2.12
2323
github.com/web-of-things-open-source/thingdescription-go v0.0.0-20240513190706-79b5f39190eb
2424
go.uber.org/atomic v1.11.0
25+
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56
2526
golang.org/x/sync v0.8.0
2627
google.golang.org/grpc v1.65.0
2728
gopkg.in/yaml.v3 v3.0.1
@@ -36,7 +37,6 @@ require (
3637
github.com/pmezard/go-difflib v1.0.0 // indirect
3738
github.com/x448/float16 v0.8.4 // indirect
3839
golang.org/x/crypto v0.25.0 // indirect
39-
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect
4040
golang.org/x/net v0.27.0 // indirect
4141
golang.org/x/sys v0.23.0 // indirect
4242
google.golang.org/genproto/googleapis/rpc v0.0.0-20240730163845-b1a4ccb954bf // indirect

internal/math/cast.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package math
2+
3+
import "golang.org/x/exp/constraints"
4+
5+
func CastTo[T, F constraints.Integer](from F) T {
6+
return T(from)
7+
}

schema/credential/credential.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ func (c CredentialType) String() string {
8686
c &^= CredentialType_ASYMMETRIC_ENCRYPTION_KEY
8787
}
8888
if c != 0 {
89-
res = append(res, fmt.Sprintf("unknown(%v)", int(c)))
89+
res = append(res, fmt.Sprintf("unknown(%v)", uint8(c)))
9090
}
9191
return strings.Join(res, "|")
9292
}

schema/platform/platform.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@
1818
// https://github.com/openconnectivityfoundation/core/blob/master/swagger2.0/oic.wk.p.swagger.json
1919
package platform
2020

21-
import "fmt"
21+
import (
22+
"fmt"
23+
24+
"github.com/plgd-dev/device/v2/internal/math"
25+
)
2226

2327
const (
2428
ResourceType = "oic.wk.p"
@@ -42,10 +46,10 @@ type Platform struct {
4246
}
4347

4448
func (p Platform) GetVersion() (uint8, uint8, uint8, uint8) {
45-
major := uint8((p.Version >> 24) & 0xFF)
46-
minor := uint8((p.Version >> 16) & 0xFF)
47-
patch := uint8((p.Version >> 8) & 0xFF)
48-
bugfix := uint8(p.Version & 0xFF)
49+
major := math.CastTo[uint8]((p.Version >> 24) & 0xFF)
50+
minor := math.CastTo[uint8]((p.Version >> 16) & 0xFF)
51+
patch := math.CastTo[uint8]((p.Version >> 8) & 0xFF)
52+
bugfix := math.CastTo[uint8](p.Version & 0xFF)
4953
return major, minor, patch, bugfix
5054
}
5155

schema/pstat/pstat.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ func (m OperationalMode) String() string {
115115
m &^= OperationalMode_CLIENT_DIRECTED
116116
}
117117
if m != 0 {
118-
res = append(res, fmt.Sprintf("unknown(%v)", int(m)))
118+
res = append(res, fmt.Sprintf("unknown(%v)", uint8(m)))
119119
}
120120
return strings.Join(res, "|")
121121
}
@@ -145,7 +145,7 @@ func (m ProvisioningMode) String() string {
145145
m &^= ProvisioningMode_INIT_SEC_SOFT_UPDATE
146146
}
147147
if m != 0 {
148-
res = append(res, fmt.Sprintf("unknown(%v)", int(m)))
148+
res = append(res, fmt.Sprintf("unknown(%v)", uint16(m)))
149149
}
150150
return strings.Join(res, "|")
151151
}

0 commit comments

Comments
 (0)