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

feat(engine): websocket - rand.New only once #6729

Merged
merged 3 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions engine/api/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package api
import (
"context"
"fmt"
"math/rand"
"net/http"
"strings"
"sync"
Expand Down Expand Up @@ -296,10 +295,7 @@ func (a *API) websocketOnMessage(e sdk.Event) {
return
}

// Randomize the order of client to prevent the old client to always received new events in priority
clientIDs := a.WSServer.server.ClientIDs()
r := rand.New(rand.NewSource(time.Now().UnixNano()))
r.Shuffle(len(clientIDs), func(i, j int) { clientIDs[i], clientIDs[j] = clientIDs[j], clientIDs[i] })

for _, id := range clientIDs {
// Copy idx for goroutine
Expand Down
9 changes: 8 additions & 1 deletion engine/websocket/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package websocket
import (
"context"
"fmt"
"math/rand"
"net/http"
"sync"
"time"

"github.com/gorilla/websocket"
"github.com/rockbears/log"
Expand All @@ -17,12 +19,16 @@ var Upgrader = websocket.Upgrader{
}

func NewServer() *Server {
return &Server{clients: make(map[string]Client)}
return &Server{
clients: make(map[string]Client),
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}

type Server struct {
mutex sync.RWMutex
clients map[string]Client
rand *rand.Rand
}

func (s *Server) AddClient(c Client) {
Expand Down Expand Up @@ -51,6 +57,7 @@ func (s *Server) ClientIDs() []string {
for k := range s.clients {
ids = append(ids, k)
}
s.rand.Shuffle(len(ids), func(i, j int) { ids[i], ids[j] = ids[j], ids[i] })
return ids
}

Expand Down