Skip to content

Commit

Permalink
Update CI configs to v0.4.7
Browse files Browse the repository at this point in the history
Update lint scripts and CI configs.
  • Loading branch information
Sean-Der committed Sep 30, 2020
1 parent 0786371 commit 804a12f
Show file tree
Hide file tree
Showing 74 changed files with 518 additions and 346 deletions.
74 changes: 74 additions & 0 deletions .golangci.yml
Expand Up @@ -3,6 +3,80 @@ linters-settings:
check-shadowing: true
misspell:
locale: US
exhaustive:
default-signifies-exhaustive: true

linters:
enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bodyclose # checks whether HTTP response body is closed successfully
- deadcode # Finds unused code
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- exhaustive # check exhaustiveness of enum switch statements
- exportloopref # checks for pointers to enclosing loop variables
- gci # Gci control golang package import order and make it always deterministic.
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- godox # Tool for detection of FIXME, TODO and other comment keywords
- goerr113 # Golang linter to check the errors handling expressions
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- ineffassign # Detects when assignments to existing variables are not used
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- noctx # noctx finds sending http request without context.Context
- scopelint # Scopelint checks for unpinned variables in go programs
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- structcheck # Finds unused struct fields
- stylecheck # Stylecheck is a replacement for golint
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- varcheck # Finds unused global variables and constants
- whitespace # Tool for detection of leading and trailing whitespace
disable:
- funlen # Tool for detection of long functions
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- gomnd # An analyzer to detect magic numbers.
- lll # Reports long lines
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
- nestif # Reports deeply nested if statements
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- nolintlint # Reports ill-formed or insufficient nolint directives
- prealloc # Finds slice declarations that could potentially be preallocated
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- testpackage # linter that makes you use a separate _test package
- wsl # Whitespace Linter - Forces you to use empty lines!

issues:
exclude-rules:
# Allow complex tests, better to be self contained
- path: _test\.go
linters:
- gocognit

# Allow complex main function in examples
- path: examples
text: "of func `main` is high"
linters:
- gocognit

run:
skip-dirs-use-default: false
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -203,6 +203,7 @@ Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contribu
* [Joshua Obasaju](https://github.com/obasajujoshua31)
* [Mission Liao](https://github.com/mission-liao)
* [Hanjun Kim](https://github.com/hallazzang)
* [ZHENK](https://github.com/scorpionknifes)

### License
MIT License - see [LICENSE](LICENSE) for full text
6 changes: 3 additions & 3 deletions certificate.go
Expand Up @@ -103,11 +103,11 @@ func (c Certificate) GetFingerprints() ([]DTLSFingerprint, error) {
for _, algo := range fingerprintAlgorithms {
name, err := fingerprint.StringFromHash(algo)
if err != nil {
return nil, fmt.Errorf("failed to create fingerprint: %v", err)
return nil, fmt.Errorf("%w: %v", ErrFailedToGenerateCertificateFingerprint, err)
}
value, err := fingerprint.Fingerprint(c.x509Cert, algo)
if err != nil {
return nil, fmt.Errorf("failed to create fingerprint: %v", err)
return nil, fmt.Errorf("%w: %v", ErrFailedToGenerateCertificateFingerprint, err)
}
res[i] = DTLSFingerprint{
Algorithm: name,
Expand Down Expand Up @@ -164,7 +164,7 @@ func (c Certificate) collectStats(report *statsReportCollector) error {
report.Collecting()

fingerPrintAlgo, err := c.GetFingerprints()
if err != nil {
if err != nil {
return err
}

Expand Down
6 changes: 3 additions & 3 deletions datachannel.go
Expand Up @@ -15,7 +15,7 @@ import (
"github.com/pion/webrtc/v3/pkg/rtcerr"
)

const dataChannelBufferSize = math.MaxUint16 //message size limit for Chromium
const dataChannelBufferSize = math.MaxUint16 // message size limit for Chromium
var errSCTPNotEstablished = errors.New("SCTP not established")

// DataChannel represents a WebRTC DataChannel
Expand Down Expand Up @@ -372,11 +372,11 @@ func (d *DataChannel) Detach() (datachannel.ReadWriteCloser, error) {
defer d.mu.Unlock()

if !d.api.settingEngine.detach.DataChannels {
return nil, fmt.Errorf("enable detaching by calling webrtc.DetachDataChannels()")
return nil, errDetachNotEnabled
}

if d.dataChannel == nil {
return nil, fmt.Errorf("datachannel not opened yet, try calling Detach from OnOpen")
return nil, errDetachBeforeOpened
}

d.detachCalled = true
Expand Down
20 changes: 6 additions & 14 deletions datachannel_go_test.go
Expand Up @@ -67,8 +67,7 @@ func TestDataChannel_MessagesAreOrdered(t *testing.T) {
// math/rand a weak RNG, but this does not need to be secure. Ignore with #nosec
/* #nosec */
randInt, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
/* #nosec */
if err != nil {
/* #nosec */ if err != nil {
t.Fatalf("Failed to get random sleep duration: %s", err)
}
time.Sleep(time.Duration(randInt.Int64()) * time.Microsecond)
Expand Down Expand Up @@ -117,7 +116,7 @@ func TestDataChannelParamters_Go(t *testing.T) {
defer report()

t.Run("MaxPacketLifeTime exchange", func(t *testing.T) {
var ordered = true
ordered := true
var maxPacketLifeTime uint16 = 3
options := &DataChannelInit{
Ordered: &ordered,
Expand Down Expand Up @@ -218,8 +217,7 @@ func TestDataChannelBufferedAmount(t *testing.T) {
t.Fatalf("Failed to send string on data channel")
}
assert.Equal(t, uint64(1500), dc.BufferedAmountLowThreshold(), "value mismatch")

//assert.Equal(t, (i+1)*len(buf), int(dc.BufferedAmount()), "unexpected bufferedAmount")
// assert.Equal(t, (i+1)*len(buf), int(dc.BufferedAmount()), "unexpected bufferedAmount")
}
})

Expand Down Expand Up @@ -300,8 +298,7 @@ func TestDataChannelBufferedAmount(t *testing.T) {
t.Fatalf("Failed to send string on data channel")
}
assert.Equal(t, uint64(1500), dc.BufferedAmountLowThreshold(), "value mismatch")

//assert.Equal(t, (i+1)*len(buf), int(dc.BufferedAmount()), "unexpected bufferedAmount")
// assert.Equal(t, (i+1)*len(buf), int(dc.BufferedAmount()), "unexpected bufferedAmount")
}
})

Expand Down Expand Up @@ -436,18 +433,13 @@ func TestEOF(t *testing.T) {
lim := test.TimeOut(time.Second * 5)
defer lim.Stop()

// Use Detach data channels mode
s := SettingEngine{}
//s.DetachDataChannels()
api := NewAPI(WithSettingEngine(s))

// Set up two peer connections.
config := Configuration{}
pca, err := api.NewPeerConnection(config)
pca, err := NewPeerConnection(config)
if err != nil {
t.Fatal(err)
}
pcb, err := api.NewPeerConnection(config)
pcb, err := NewPeerConnection(config)
if err != nil {
t.Fatal(err)
}
Expand Down
2 changes: 1 addition & 1 deletion datachannel_ortc_test.go
Expand Up @@ -3,13 +3,13 @@
package webrtc

import (
"github.com/stretchr/testify/assert"
"io"
"testing"
"time"

"github.com/pion/transport/test"
"github.com/pion/webrtc/v3/internal/util"
"github.com/stretchr/testify/assert"
)

func TestDataChannel_ORTCE2E(t *testing.T) {
Expand Down
7 changes: 2 additions & 5 deletions datachannel_test.go
Expand Up @@ -203,11 +203,8 @@ func TestDataChannel_Send(t *testing.T) {
dc.OnMessage(func(msg DataChannelMessage) {
done <- true
})
// TODO: currently there is no way of properly subscribing to OnOpen with the js binding,
// because CreateDataChannel might return an already open data channel
//
e := dc.SendText("Ping")
if e != nil {

if e := dc.SendText("Ping"); e != nil {
// wasm binding doesn't fire OnOpen (we probably already missed it)
dc.OnOpen(func() {
e = dc.SendText("Ping")
Expand Down
23 changes: 13 additions & 10 deletions dtlstransport.go
Expand Up @@ -151,7 +151,7 @@ func (t *DTLSTransport) startSRTP() error {
if t.srtpSession.Load() != nil && t.srtcpSession.Load() != nil {
return nil
} else if t.conn == nil {
return fmt.Errorf("the DTLS transport has not started yet")
return errDtlsTransportNotStarted
}

srtpConfig := &srtp.Config{
Expand Down Expand Up @@ -189,17 +189,17 @@ func (t *DTLSTransport) startSRTP() error {
connState := t.conn.ConnectionState()
err := srtpConfig.ExtractSessionKeysFromDTLS(&connState, t.role() == DTLSRoleClient)
if err != nil {
return fmt.Errorf("failed to extract sctp session keys: %v", err)
return fmt.Errorf("%w: %v", errDtlsKeyExtractionFailed, err)
}

srtpSession, err := srtp.NewSessionSRTP(t.srtpEndpoint, srtpConfig)
if err != nil {
return fmt.Errorf("failed to start srtp: %v", err)
return fmt.Errorf("%w: %v", errFailedToStartSRTP, err)
}

srtcpSession, err := srtp.NewSessionSRTCP(t.srtcpEndpoint, srtpConfig)
if err != nil {
return fmt.Errorf("failed to start srtp: %v", err)
return fmt.Errorf("%w: %v", errFailedToStartSRTCP, err)
}

t.srtpSession.Store(srtpSession)
Expand Down Expand Up @@ -237,6 +237,7 @@ func (t *DTLSTransport) role() DTLSRole {
return DTLSRoleServer
case DTLSRoleServer:
return DTLSRoleClient
default:
}

// If SettingEngine has an explicit role
Expand All @@ -245,6 +246,7 @@ func (t *DTLSTransport) role() DTLSRole {
return DTLSRoleServer
case DTLSRoleClient:
return DTLSRoleClient
default:
}

// Remote was auto and no explicit role was configured via SettingEngine
Expand All @@ -267,7 +269,7 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error {
}

if t.state != DTLSTransportStateNew {
return DTLSRole(0), nil, &rtcerr.InvalidStateError{Err: fmt.Errorf("attempted to start DTLSTransport that is not in new state: %s", t.state)}
return DTLSRole(0), nil, &rtcerr.InvalidStateError{Err: fmt.Errorf("%w: %s", errInvalidDTLSStart, t.state)}
}

t.srtpEndpoint = t.iceTransport.NewEndpoint(mux.MatchSRTP)
Expand All @@ -282,7 +284,8 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error {
{
Certificate: [][]byte{cert.x509Cert.Raw},
PrivateKey: cert.privateKey,
}},
},
},
SRTPProtectionProfiles: []dtls.SRTPProtectionProfile{dtls.SRTP_AEAD_AES_128_GCM, dtls.SRTP_AES128_CM_HMAC_SHA1_80},
ClientAuth: dtls.RequireAnyClientCert,
LoggerFactory: t.api.settingEngine.LoggerFactory,
Expand Down Expand Up @@ -345,7 +348,7 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error {
remoteCerts := t.conn.ConnectionState().PeerCertificates
if len(remoteCerts) == 0 {
t.onStateChange(DTLSTransportStateFailed)
return fmt.Errorf("peer didn't provide certificate via DTLS")
return errNoRemoteCertificate
}
t.remoteCertificate = remoteCerts[0]

Expand Down Expand Up @@ -386,7 +389,7 @@ func (t *DTLSTransport) Stop() error {

if t.conn != nil {
// dtls connection may be closed on sctp close.
if err := t.conn.Close(); err != nil && err != dtls.ErrConnClosed {
if err := t.conn.Close(); err != nil && !errors.Is(err, dtls.ErrConnClosed) {
closeErrs = append(closeErrs, err)
}
}
Expand All @@ -411,12 +414,12 @@ func (t *DTLSTransport) validateFingerPrint(remoteCert *x509.Certificate) error
}
}

return errors.New("no matching fingerprint")
return errNoMatchingCertificateFingerprint
}

func (t *DTLSTransport) ensureICEConn() error {
if t.iceTransport == nil || t.iceTransport.State() == ICETransportStateNew {
return errors.New("ICE connection not started")
return errICEConnectionNotStarted
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions e2e/e2e_test.go
Expand Up @@ -7,7 +7,6 @@ import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
Expand All @@ -16,6 +15,7 @@ import (

"github.com/sclevine/agouti"

"github.com/pion/randutil"
"github.com/pion/webrtc/v3"
"github.com/pion/webrtc/v3/pkg/media"
)
Expand Down Expand Up @@ -351,7 +351,7 @@ func createTrack(offer webrtc.SessionDescription) (*webrtc.PeerConnection, *webr
return nil, nil, nil, errPc
}

track, errTrack := pc.NewTrack(payloadType, rand.Uint32(), "video", "pion")
track, errTrack := pc.NewTrack(payloadType, randutil.NewMathRandomGenerator().Uint32(), "video", "pion")
if errTrack != nil {
return nil, nil, nil, errTrack
}
Expand Down

0 comments on commit 804a12f

Please sign in to comment.