Use nonce in data messages to de-dupe SendData API. (#3366)

* Use nonce in data messages to de-dupe SendData API.

With API retries, it is possible that some data messages are sent
multiple times. Check the nonce (if present) to de-dupe data messages
before forwarding it to the clients.

* add nonce to UserPacket

* defer unlock

* 128-bit UUID as nonce

* - UUID nonce
- make a UserPacketDeduper module for easier re-use.

* deps

* feedback
This commit is contained in:
Raja Subramanian
2025-01-27 15:35:37 +05:30
committed by GitHub
parent 30669722c3
commit db75092aa6
8 changed files with 184 additions and 26 deletions
+11
View File
@@ -142,6 +142,8 @@ type Room struct {
simulationLock sync.Mutex
disconnectSignalOnResumeParticipants map[livekit.ParticipantIdentity]time.Time
disconnectSignalOnResumeNoMessagesParticipants map[livekit.ParticipantIdentity]*disconnectSignalOnResumeNoMessages
userPacketDeduper *UserPacketDeduper
}
type ParticipantOptions struct {
@@ -270,6 +272,7 @@ func NewRoom(
trailer: []byte(utils.RandomSecret()),
disconnectSignalOnResumeParticipants: make(map[livekit.ParticipantIdentity]time.Time),
disconnectSignalOnResumeNoMessagesParticipants: make(map[livekit.ParticipantIdentity]*disconnectSignalOnResumeNoMessages),
userPacketDeduper: NewUserPacketDeduper(),
}
if r.protoRoom.EmptyTimeout == 0 {
@@ -1741,12 +1744,20 @@ func (r *Room) createAgentDispatchesFromRoomAgent() {
}
}
func (r *Room) IsDataMessageUserPacketDuplicate(up *livekit.UserPacket) bool {
return r.userPacketDeduper.IsDuplicate(up)
}
// ------------------------------------------------------------
func BroadcastDataPacketForRoom(r types.Room, source types.LocalParticipant, kind livekit.DataPacket_Kind, dp *livekit.DataPacket, logger logger.Logger) {
dp.Kind = kind // backward compatibility
dest := dp.GetUser().GetDestinationSids()
if u := dp.GetUser(); u != nil {
if r.IsDataMessageUserPacketDuplicate(u) {
logger.Infow("dropping duplicate data message", "nonce", u.Nonce)
return
}
if len(dp.DestinationIdentities) == 0 {
dp.DestinationIdentities = u.DestinationIdentities
} else {
+1
View File
@@ -478,6 +478,7 @@ type Room interface {
SimulateScenario(participant LocalParticipant, scenario *livekit.SimulateScenario) error
ResolveMediaTrackForSubscriber(sub LocalParticipant, trackID livekit.TrackID) MediaResolverResult
GetLocalParticipants() []LocalParticipant
IsDataMessageUserPacketDuplicate(ip *livekit.UserPacket) bool
}
// MediaTrack represents a media track
+74
View File
@@ -29,6 +29,17 @@ type FakeRoom struct {
iDReturnsOnCall map[int]struct {
result1 livekit.RoomID
}
IsDataMessageUserPacketDuplicateStub func(*livekit.UserPacket) bool
isDataMessageUserPacketDuplicateMutex sync.RWMutex
isDataMessageUserPacketDuplicateArgsForCall []struct {
arg1 *livekit.UserPacket
}
isDataMessageUserPacketDuplicateReturns struct {
result1 bool
}
isDataMessageUserPacketDuplicateReturnsOnCall map[int]struct {
result1 bool
}
NameStub func() livekit.RoomName
nameMutex sync.RWMutex
nameArgsForCall []struct {
@@ -212,6 +223,67 @@ func (fake *FakeRoom) IDReturnsOnCall(i int, result1 livekit.RoomID) {
}{result1}
}
func (fake *FakeRoom) IsDataMessageUserPacketDuplicate(arg1 *livekit.UserPacket) bool {
fake.isDataMessageUserPacketDuplicateMutex.Lock()
ret, specificReturn := fake.isDataMessageUserPacketDuplicateReturnsOnCall[len(fake.isDataMessageUserPacketDuplicateArgsForCall)]
fake.isDataMessageUserPacketDuplicateArgsForCall = append(fake.isDataMessageUserPacketDuplicateArgsForCall, struct {
arg1 *livekit.UserPacket
}{arg1})
stub := fake.IsDataMessageUserPacketDuplicateStub
fakeReturns := fake.isDataMessageUserPacketDuplicateReturns
fake.recordInvocation("IsDataMessageUserPacketDuplicate", []interface{}{arg1})
fake.isDataMessageUserPacketDuplicateMutex.Unlock()
if stub != nil {
return stub(arg1)
}
if specificReturn {
return ret.result1
}
return fakeReturns.result1
}
func (fake *FakeRoom) IsDataMessageUserPacketDuplicateCallCount() int {
fake.isDataMessageUserPacketDuplicateMutex.RLock()
defer fake.isDataMessageUserPacketDuplicateMutex.RUnlock()
return len(fake.isDataMessageUserPacketDuplicateArgsForCall)
}
func (fake *FakeRoom) IsDataMessageUserPacketDuplicateCalls(stub func(*livekit.UserPacket) bool) {
fake.isDataMessageUserPacketDuplicateMutex.Lock()
defer fake.isDataMessageUserPacketDuplicateMutex.Unlock()
fake.IsDataMessageUserPacketDuplicateStub = stub
}
func (fake *FakeRoom) IsDataMessageUserPacketDuplicateArgsForCall(i int) *livekit.UserPacket {
fake.isDataMessageUserPacketDuplicateMutex.RLock()
defer fake.isDataMessageUserPacketDuplicateMutex.RUnlock()
argsForCall := fake.isDataMessageUserPacketDuplicateArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeRoom) IsDataMessageUserPacketDuplicateReturns(result1 bool) {
fake.isDataMessageUserPacketDuplicateMutex.Lock()
defer fake.isDataMessageUserPacketDuplicateMutex.Unlock()
fake.IsDataMessageUserPacketDuplicateStub = nil
fake.isDataMessageUserPacketDuplicateReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeRoom) IsDataMessageUserPacketDuplicateReturnsOnCall(i int, result1 bool) {
fake.isDataMessageUserPacketDuplicateMutex.Lock()
defer fake.isDataMessageUserPacketDuplicateMutex.Unlock()
fake.IsDataMessageUserPacketDuplicateStub = nil
if fake.isDataMessageUserPacketDuplicateReturnsOnCall == nil {
fake.isDataMessageUserPacketDuplicateReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.isDataMessageUserPacketDuplicateReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeRoom) Name() livekit.RoomName {
fake.nameMutex.Lock()
ret, specificReturn := fake.nameReturnsOnCall[len(fake.nameArgsForCall)]
@@ -599,6 +671,8 @@ func (fake *FakeRoom) Invocations() map[string][][]interface{} {
defer fake.getLocalParticipantsMutex.RUnlock()
fake.iDMutex.RLock()
defer fake.iDMutex.RUnlock()
fake.isDataMessageUserPacketDuplicateMutex.RLock()
defer fake.isDataMessageUserPacketDuplicateMutex.RUnlock()
fake.nameMutex.RLock()
defer fake.nameMutex.RUnlock()
fake.removeParticipantMutex.RLock()
+66
View File
@@ -0,0 +1,66 @@
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rtc
import (
"sync"
"github.com/google/uuid"
"github.com/livekit/protocol/livekit"
)
const (
maxSize = 100
)
type UserPacketDeduper struct {
lock sync.Mutex
seen map[uuid.UUID]uuid.UUID
head uuid.UUID
tail uuid.UUID
}
func NewUserPacketDeduper() *UserPacketDeduper {
return &UserPacketDeduper{
seen: make(map[uuid.UUID]uuid.UUID),
}
}
func (u *UserPacketDeduper) IsDuplicate(up *livekit.UserPacket) bool {
id, err := uuid.FromBytes(up.Nonce)
if err != nil {
return false
}
u.lock.Lock()
defer u.lock.Unlock()
if u.head == id {
return true
}
if _, ok := u.seen[id]; ok {
return true
}
u.seen[u.head] = id
u.head = id
if len(u.seen) == maxSize {
tail := u.tail
u.tail = u.seen[tail]
delete(u.seen, tail)
}
return false
}
+1
View File
@@ -822,6 +822,7 @@ func (r *RoomManager) SendData(ctx context.Context, req *livekit.SendDataRequest
DestinationSids: req.DestinationSids,
DestinationIdentities: req.DestinationIdentities,
Topic: req.Topic,
Nonce: req.Nonce,
},
},
}, req.Kind)
+5
View File
@@ -234,6 +234,11 @@ func (s *RoomService) SendData(ctx context.Context, req *livekit.SendDataRequest
return nil, twirpAuthError(err)
}
// nonce is either absent or 128-bit UUID
if len(req.Nonce) != 8 && len(req.Nonce) != 16 {
return nil, twirp.NewError(twirp.InvalidArgument, fmt.Sprintf("nonce should be 16-bytes or not present, got: %d bytes", len(req.Nonce)))
}
return s.roomClient.SendData(ctx, s.topicFormatter.RoomTopic(ctx, livekit.RoomName(req.Room)), req)
}