Skip to content

Commit

Permalink
Merge pull request #362 from dunglas/fix/linters
Browse files Browse the repository at this point in the history
fix: errors raised by golangci-lint
  • Loading branch information
dunglas committed Aug 19, 2020
2 parents 3a42289 + 475ce6f commit c99be1b
Show file tree
Hide file tree
Showing 15 changed files with 48 additions and 12 deletions.
3 changes: 1 addition & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ package cmd
import (
"fmt"

log "github.com/sirupsen/logrus"

"github.com/dunglas/mercure/common"
"github.com/dunglas/mercure/hub"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand Down
1 change: 1 addition & 0 deletions hub/authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ func canDispatch(s *TopicSelectorStore, topics, topicSelectors []string) bool {

if s.match(topic, topicSelector, false) {
matched = true

break
}
}
Expand Down
3 changes: 1 addition & 2 deletions hub/authorization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import (
"net/http"
"testing"

"github.com/dgrijalva/jwt-go"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"

"github.com/dgrijalva/jwt-go"
)

const (
Expand Down
9 changes: 6 additions & 3 deletions hub/bolt_transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ import (
"strconv"
"sync"

bolt "go.etcd.io/bbolt"

log "github.com/sirupsen/logrus"
bolt "go.etcd.io/bbolt"
)

const defaultBoltBucketName = "updates"
Expand Down Expand Up @@ -202,6 +201,7 @@ func (t *BoltTransport) dispatchHistory(s *Subscriber, toSeq uint64) {
b := tx.Bucket([]byte(t.bucketName))
if b == nil {
s.HistoryDispatched(EarliestLastEventID)

return nil // No data
}

Expand All @@ -222,11 +222,13 @@ func (t *BoltTransport) dispatchHistory(s *Subscriber, toSeq uint64) {
if err := json.Unmarshal(v, &update); err != nil {
s.HistoryDispatched(responseLastEventID)
log.Error(fmt.Errorf("bolt history: %w", err))

return err
}

if !s.Dispatch(update, true) || (toSeq > 0 && binary.BigEndian.Uint64(k[:8]) >= toSeq) {
s.HistoryDispatched(responseLastEventID)

return nil
}
}
Expand All @@ -250,6 +252,7 @@ func (t *BoltTransport) Close() (err error) {

err = t.db.Close()
})

return err
}

Expand All @@ -258,7 +261,7 @@ func (t *BoltTransport) cleanup(bucket *bolt.Bucket, lastID uint64) error {
if t.size == 0 ||
t.cleanupFrequency == 0 ||
t.size >= lastID ||
(t.cleanupFrequency != 1 && rand.Float64() < t.cleanupFrequency) {
(t.cleanupFrequency != 1 && rand.Float64() < t.cleanupFrequency) { // nolint:gosec
return nil
}

Expand Down
1 change: 1 addition & 0 deletions hub/bolt_transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ func TestBoltLastEventID(t *testing.T) {

// The DB is append only
bucket.FillPercent = 1

return bucket.Put(key, []byte("invalid"))
})
require.Nil(t, db.Close())
Expand Down
1 change: 1 addition & 0 deletions hub/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func ValidateConfig(v *viper.Viper) error {
return fmt.Errorf(`%w: if the "metrics_password" configuration parameter is defined, "metrics_login" must be defined too`, ErrInvalidConfig)
}
}

return nil
}

Expand Down
2 changes: 2 additions & 0 deletions hub/hub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func TestNewHubTransportValidationError(t *testing.T) {
func TestStartCrash(t *testing.T) {
if os.Getenv("BE_START_CRASH") == "1" {
Start()

return
}
cmd := exec.Command(os.Args[0], "-test.run=TestStartCrash") // nolint:gosec
Expand Down Expand Up @@ -110,6 +111,7 @@ func createDummyAuthorizedJWT(h *Hub, r role, topics []string) string {
}

tokenString, _ := token.SignedString(key)

return tokenString
}

Expand Down
20 changes: 15 additions & 5 deletions hub/publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,35 @@ import (
log "github.com/sirupsen/logrus"
)

func logAccessError(r *http.Request, err error) {
if err == nil {
log.WithFields(log.Fields{"remote_addr": r.RemoteAddr}).Info("topic selectors not matched or not provided")

return
}
log.WithFields(log.Fields{"remote_addr": r.RemoteAddr}).Info(err)
}

// PublishHandler allows publisher to broadcast updates to all subscribers.
func (h *Hub) PublishHandler(w http.ResponseWriter, r *http.Request) {
claims, err := authorize(r, h.getJWTKey(rolePublisher), h.getJWTAlgorithm(rolePublisher), h.config.GetStringSlice("publish_allowed_origins"))
if err != nil || claims == nil || claims.Mercure.Publish == nil {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
if err == nil {
log.WithFields(log.Fields{"remote_addr": r.RemoteAddr}).Info("topic selectors not matched or not provided")
} else {
log.WithFields(log.Fields{"remote_addr": r.RemoteAddr}).Info(err)
}
logAccessError(r, err)

return
}

if r.ParseForm() != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)

return
}

topics := r.PostForm["topic"]
if len(topics) == 0 {
http.Error(w, "Missing \"topic\" parameter", http.StatusBadRequest)

return
}

Expand All @@ -38,13 +46,15 @@ func (h *Hub) PublishHandler(w http.ResponseWriter, r *http.Request) {
retry, err = strconv.ParseUint(retryString, 10, 64)
if err != nil {
http.Error(w, "Invalid \"retry\" parameter", http.StatusBadRequest)

return
}
}

private := len(r.PostForm["private"]) != 0
if private && !canDispatch(h.topicSelectorStore, topics, claims.Mercure.Publish) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)

return
}

Expand Down
1 change: 1 addition & 0 deletions hub/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ func basicAuthMiddleware(expectedLogin, expectedPassword string) func(next http.
if !ok || login != expectedLogin || password != expectedPassword {
w.Header().Add("WWW-Authenticate", `Basic realm="Mercure"`)
w.WriteHeader(http.StatusUnauthorized)

return
}

Expand Down
1 change: 1 addition & 0 deletions hub/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ func TestClientClosesThenReconnects(t *testing.T) {
receivedBody += string(buf)
if strings.Contains(receivedBody, "data: "+expectedBodyData+"\n") {
cancel()

break
}
}
Expand Down
5 changes: 5 additions & 0 deletions hub/subscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,14 @@ func (h *Hub) registerSubscriber(w http.ResponseWriter, r *http.Request, debug b
if err != nil || (claims == nil && !h.config.GetBool("allow_anonymous")) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
log.WithFields(s.LogFields).Info(err)

return nil
}

s.Topics = r.URL.Query()["topic"]
if len(s.Topics) == 0 {
http.Error(w, "Missing \"topic\" parameter.", http.StatusBadRequest)

return nil
}
s.LogFields["subscriber_topics"] = s.Topics
Expand All @@ -102,6 +104,7 @@ func (h *Hub) registerSubscriber(w http.ResponseWriter, r *http.Request, debug b
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
h.dispatchSubscriptionUpdate(s, false)
log.WithFields(s.LogFields).Error(err)

return nil
}

Expand Down Expand Up @@ -155,6 +158,7 @@ func (h *Hub) write(w io.Writer, s *Subscriber, data string, d time.Duration) bo
if d == time.Duration(0) {
fmt.Fprint(w, data)
w.(http.Flusher).Flush()

return true
}

Expand All @@ -170,6 +174,7 @@ func (h *Hub) write(w io.Writer, s *Subscriber, data string, d time.Duration) bo
return true
case <-time.After(d):
log.WithFields(s.LogFields).Warn("Dispatch timeout reached")

return false
}
}
Expand Down
1 change: 1 addition & 0 deletions hub/subscribe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ func TestSubscribePrivate(t *testing.T) {
Event: Event{Data: "Great", ID: "c", Retry: 1},
Private: true,
})

return
}
}()
Expand Down
8 changes: 8 additions & 0 deletions hub/subscriber.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ func (s *Subscriber) start() {
case u, ok := <-s.history.in:
if !ok {
s.history.in = nil

break
}
if s.CanDispatch(u) {
Expand All @@ -85,6 +86,7 @@ func (s *Subscriber) start() {
case s.outChan() <- s.nextUpdate():
if len(s.history.buffer) > 0 {
s.history.buffer = s.history.buffer[1:]

break
}

Expand All @@ -105,6 +107,7 @@ func (s *Subscriber) outChan() chan<- *Update {
if len(s.live.buffer) > 0 || len(s.history.buffer) > 0 {
return s.out
}

return nil
}

Expand All @@ -116,6 +119,7 @@ func (s *Subscriber) nextUpdate() *Update {
if len(s.history.buffer) > 0 {
return s.history.buffer[0]
}

return nil
}

Expand All @@ -138,6 +142,7 @@ func (s *Subscriber) Dispatch(u *Update, fromHistory bool) bool {
select {
case <-s.disconnected:
close(s.live.in)

return false

default:
Expand All @@ -146,6 +151,7 @@ func (s *Subscriber) Dispatch(u *Update, fromHistory bool) bool {
select {
case <-s.disconnected:
close(s.live.in)

return false

case in <- u:
Expand Down Expand Up @@ -176,11 +182,13 @@ func (s *Subscriber) Disconnect() {
func (s *Subscriber) CanDispatch(u *Update) bool {
if !canReceive(s.topicSelectorStore, u.Topics, s.Topics, true) {
log.WithFields(createFields(u, s)).Debug("Subscriber has not subscribed to this update")

return false
}

if u.Private && (s.Claims == nil || s.Claims.Mercure.Subscribe == nil || !canReceive(s.topicSelectorStore, u.Topics, s.Claims.Mercure.Subscribe, true)) {
log.WithFields(createFields(u, s)).Debug("Subscriber not authorized to receive this update")

return false
}

Expand Down
3 changes: 3 additions & 0 deletions hub/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ func (h *Hub) SubscriptionHandler(w http.ResponseWriter, r *http.Request) {
}

w.Write(json)

return
}
}
Expand All @@ -110,6 +111,7 @@ func (h *Hub) initSubscription(currentURL string, w http.ResponseWriter, r *http
} else {
log.WithFields(log.Fields{"remote_addr": r.RemoteAddr}).Info(err)
}

return "", nil, false
}

Expand All @@ -121,6 +123,7 @@ func (h *Hub) initSubscription(currentURL string, w http.ResponseWriter, r *http
lastEventID, subscribers = transport.GetSubscribers()
if r.Header.Get("If-None-Match") == lastEventID {
w.WriteHeader(http.StatusNotModified)

return "", nil, false
}

Expand Down
1 change: 1 addition & 0 deletions hub/topic_selector.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ func (tss *TopicSelectorStore) cleanup(topics []string) {
if tc, ok := tss.m[topic]; ok {
if tc.counter == 0 {
delete(tss.m, topic)

continue
}

Expand Down

0 comments on commit c99be1b

Please sign in to comment.