Add lock around ackMap

This commit is contained in:
Tulir Asokan 2023-07-15 15:57:07 +03:00
parent 605d84c485
commit e086846574

View file

@ -2,6 +2,7 @@ package libgm
import ( import (
"fmt" "fmt"
"sync"
"time" "time"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
@ -32,8 +33,9 @@ type SessionHandler struct {
client *Client client *Client
requests map[string]map[binary.ActionType]*ResponseChan requests map[string]map[binary.ActionType]*ResponseChan
ackMap []string ackMapLock sync.Mutex
ackTicker *time.Ticker ackMap []string
ackTicker *time.Ticker
sessionId string sessionId string
@ -101,6 +103,8 @@ func (s *SessionHandler) buildMessage(actionType binary.ActionType, encryptedDat
func (s *SessionHandler) addResponseAck(responseId string) { func (s *SessionHandler) addResponseAck(responseId string) {
s.client.Logger.Debug().Any("responseId", responseId).Msg("Added to ack map") s.client.Logger.Debug().Any("responseId", responseId).Msg("Added to ack map")
s.ackMapLock.Lock()
defer s.ackMapLock.Unlock()
hasResponseId := slices.Contains(s.ackMap, responseId) hasResponseId := slices.Contains(s.ackMap, responseId)
if !hasResponseId { if !hasResponseId {
s.ackMap = append(s.ackMap, responseId) s.ackMap = append(s.ackMap, responseId)
@ -121,11 +125,13 @@ func (s *SessionHandler) startAckInterval() {
} }
func (s *SessionHandler) sendAckRequest() { func (s *SessionHandler) sendAckRequest() {
if len(s.ackMap) <= 0 { s.ackMapLock.Lock()
return
}
dataToAck := s.ackMap dataToAck := s.ackMap
s.ackMap = nil s.ackMap = nil
s.ackMapLock.Unlock()
if len(dataToAck) == 0 {
return
}
ackMessages := make([]*binary.AckMessageData, len(dataToAck)) ackMessages := make([]*binary.AckMessageData, len(dataToAck))
for i, reqID := range dataToAck { for i, reqID := range dataToAck {
ackMessages[i] = &binary.AckMessageData{ ackMessages[i] = &binary.AckMessageData{