From 320a6c35bf0bcaa22f4c7d03880708549681af62 Mon Sep 17 00:00:00 2001 From: David Zhao Date: Sat, 30 Jan 2021 23:16:11 -0800 Subject: [PATCH] enable explicit reconnect to distinguish between WS disconnect vs PeerConnection disconnect --- pkg/routing/interfaces.go | 4 +-- pkg/routing/localrouter.go | 3 ++- pkg/routing/redisrouter.go | 33 +++++++++++++++-------- pkg/routing/routingfakes/fake_router.go | 18 +++++++------ pkg/rtc/participant.go | 11 +++----- pkg/service/roommanager.go | 32 +++++++++++++--------- pkg/service/rtcservice.go | 7 ++--- proto/internal.proto | 13 ++------- proto/livekit/internal.pb.go | 35 ++++++++++++++++--------- 9 files changed, 87 insertions(+), 69 deletions(-) diff --git a/pkg/routing/interfaces.go b/pkg/routing/interfaces.go index bd1f75c5..6d15cc0e 100644 --- a/pkg/routing/interfaces.go +++ b/pkg/routing/interfaces.go @@ -23,7 +23,7 @@ type MessageSource interface { ReadChan() <-chan proto.Message } -type ParticipantCallback func(roomName, identity string, requestSource MessageSource, responseSink MessageSink) +type ParticipantCallback func(roomName, identity string, reconnect bool, requestSource MessageSource, responseSink MessageSink) // Router allows multiple nodes to coordinate the participant session //counterfeiter:generate . Router @@ -37,7 +37,7 @@ type Router interface { ListNodes() ([]*livekit.Node, error) // participant signal connection is ready to start - StartParticipantSignal(roomName, identity string) (reqSink MessageSink, resSource MessageSource, err error) + StartParticipantSignal(roomName, identity string, reconnect bool) (reqSink MessageSink, resSource MessageSource, err error) // when a new participant's RTC connection is ready to start OnNewParticipantRTC(callback ParticipantCallback) diff --git a/pkg/routing/localrouter.go b/pkg/routing/localrouter.go index b7695fed..62ffd9a2 100644 --- a/pkg/routing/localrouter.go +++ b/pkg/routing/localrouter.go @@ -59,7 +59,7 @@ func (r *LocalRouter) ListNodes() ([]*livekit.Node, error) { }, nil } -func (r *LocalRouter) StartParticipantSignal(roomName, identity string) (reqSink MessageSink, resSource MessageSource, err error) { +func (r *LocalRouter) StartParticipantSignal(roomName, identity string, reconnect bool) (reqSink MessageSink, resSource MessageSource, err error) { // treat it as a new participant connecting if r.onNewParticipant == nil { return nil, nil, ErrHandlerNotDefined @@ -73,6 +73,7 @@ func (r *LocalRouter) StartParticipantSignal(roomName, identity string) (reqSink r.onNewParticipant( roomName, identity, + reconnect, // request source reqChan, // response sink diff --git a/pkg/routing/redisrouter.go b/pkg/routing/redisrouter.go index 06985b8f..3c9d7829 100644 --- a/pkg/routing/redisrouter.go +++ b/pkg/routing/redisrouter.go @@ -115,7 +115,7 @@ func (r *RedisRouter) ListNodes() ([]*livekit.Node, error) { } // signal connection sets up paths to the RTC node, and starts to route messages to that message queue -func (r *RedisRouter) StartParticipantSignal(roomName, identity string) (reqSink MessageSink, resSource MessageSource, err error) { +func (r *RedisRouter) StartParticipantSignal(roomName, identity string, reconnect bool) (reqSink MessageSink, resSource MessageSource, err error) { // find the node where the room is hosted at rtcNode, err := r.GetNodeForRoom(roomName) if err != nil { @@ -139,6 +139,7 @@ func (r *RedisRouter) StartParticipantSignal(roomName, identity string) (reqSink Identity: identity, // connection id is to allow the RTC node to identify where to route the message back to ConnectionId: connectionId, + Reconnect: reconnect, }) if err != nil { return @@ -177,11 +178,24 @@ func (r *RedisRouter) startParticipantRTC(ss *livekit.StartSession, participantK return ErrHandlerNotDefined } + if !ss.Reconnect { + // when it's not reconnecting, we do not want to re-use the same response sink + // the previous rtc worker thread is still consuming off of it. + // we'll want to sever the connection and switch to the new one + r.lock.Lock() + requestChan, ok := r.requestChannels[participantKey] + r.lock.Unlock() + if ok { + requestChan.Close() + } + } + reqChan := r.getOrCreateMessageChannel(r.requestChannels, participantKey) resSink := r.getOrCreateSignalSink(signalNode, ss.ConnectionId) r.onNewParticipant( ss.RoomName, ss.Identity, + ss.Reconnect, reqChan, resSink, ) @@ -317,17 +331,17 @@ func (r *RedisRouter) signalWorker() { } case *livekit.SignalNodeMessage_EndSession: - signalNode, err := r.getParticipantSignalNode(connectionId) + //signalNode, err := r.getParticipantSignalNode(connectionId) if err != nil { logger.Errorw("could not get participant RTC node", "error", err) continue } // EndSession can only be initiated on an RTC node, is handled on the signal node - if signalNode == r.currentNode.Id { - resSink := r.getOrCreateMessageChannel(r.responseChannels, connectionId) - resSink.Close() - } + //if signalNode == r.currentNode.Id { + resSink := r.getOrCreateMessageChannel(r.responseChannels, connectionId) + resSink.Close() + //} } } } @@ -363,8 +377,6 @@ func (r *RedisRouter) rtcWorker() { switch rmb := rm.Message.(type) { case *livekit.RTCNodeMessage_StartSession: - logger.Debugw("received router startSession", "node", r.currentNode.Id, - "participant", pKey) // RTC session should start on this node err = r.startParticipantRTC(rmb.StartSession, pKey) if err != nil { @@ -372,9 +384,8 @@ func (r *RedisRouter) rtcWorker() { } case *livekit.RTCNodeMessage_Request: - // in the event the current node is an RTC node, push to request channels - reqSink := r.getOrCreateMessageChannel(r.requestChannels, pKey) - err = reqSink.WriteMessage(rmb.Request) + requestChan := r.getOrCreateMessageChannel(r.requestChannels, pKey) + err = requestChan.WriteMessage(rmb.Request) if err != nil { logger.Errorw("could not write to request channel", "participant", pKey, diff --git a/pkg/routing/routingfakes/fake_router.go b/pkg/routing/routingfakes/fake_router.go index f9ff37f6..882bc3d2 100644 --- a/pkg/routing/routingfakes/fake_router.go +++ b/pkg/routing/routingfakes/fake_router.go @@ -95,11 +95,12 @@ type FakeRouter struct { startReturnsOnCall map[int]struct { result1 error } - StartParticipantSignalStub func(string, string) (routing.MessageSink, routing.MessageSource, error) + StartParticipantSignalStub func(string, string, bool) (routing.MessageSink, routing.MessageSource, error) startParticipantSignalMutex sync.RWMutex startParticipantSignalArgsForCall []struct { arg1 string arg2 string + arg3 bool } startParticipantSignalReturns struct { result1 routing.MessageSink @@ -574,19 +575,20 @@ func (fake *FakeRouter) StartReturnsOnCall(i int, result1 error) { }{result1} } -func (fake *FakeRouter) StartParticipantSignal(arg1 string, arg2 string) (routing.MessageSink, routing.MessageSource, error) { +func (fake *FakeRouter) StartParticipantSignal(arg1 string, arg2 string, arg3 bool) (routing.MessageSink, routing.MessageSource, error) { fake.startParticipantSignalMutex.Lock() ret, specificReturn := fake.startParticipantSignalReturnsOnCall[len(fake.startParticipantSignalArgsForCall)] fake.startParticipantSignalArgsForCall = append(fake.startParticipantSignalArgsForCall, struct { arg1 string arg2 string - }{arg1, arg2}) + arg3 bool + }{arg1, arg2, arg3}) stub := fake.StartParticipantSignalStub fakeReturns := fake.startParticipantSignalReturns - fake.recordInvocation("StartParticipantSignal", []interface{}{arg1, arg2}) + fake.recordInvocation("StartParticipantSignal", []interface{}{arg1, arg2, arg3}) fake.startParticipantSignalMutex.Unlock() if stub != nil { - return stub(arg1, arg2) + return stub(arg1, arg2, arg3) } if specificReturn { return ret.result1, ret.result2, ret.result3 @@ -600,17 +602,17 @@ func (fake *FakeRouter) StartParticipantSignalCallCount() int { return len(fake.startParticipantSignalArgsForCall) } -func (fake *FakeRouter) StartParticipantSignalCalls(stub func(string, string) (routing.MessageSink, routing.MessageSource, error)) { +func (fake *FakeRouter) StartParticipantSignalCalls(stub func(string, string, bool) (routing.MessageSink, routing.MessageSource, error)) { fake.startParticipantSignalMutex.Lock() defer fake.startParticipantSignalMutex.Unlock() fake.StartParticipantSignalStub = stub } -func (fake *FakeRouter) StartParticipantSignalArgsForCall(i int) (string, string) { +func (fake *FakeRouter) StartParticipantSignalArgsForCall(i int) (string, string, bool) { fake.startParticipantSignalMutex.RLock() defer fake.startParticipantSignalMutex.RUnlock() argsForCall := fake.startParticipantSignalArgsForCall[i] - return argsForCall.arg1, argsForCall.arg2 + return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeRouter) StartParticipantSignalReturns(result1 routing.MessageSink, result2 routing.MessageSource, result3 error) { diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index 2b174d0e..ef32ad2b 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -1,7 +1,6 @@ package rtc import ( - "context" "io" "sync" "sync/atomic" @@ -37,8 +36,7 @@ type ParticipantImpl struct { peerConn types.PeerConnection responseSink routing.MessageSink receiverConfig ReceiverConfig - ctx context.Context - cancel context.CancelFunc + isClosed utils.AtomicFlag mediaEngine *webrtc.MediaEngine identity string state atomic.Value // livekit.ParticipantInfo_State @@ -80,15 +78,12 @@ func NewParticipant(identity string, pc types.PeerConnection, rs routing.Message me := &webrtc.MediaEngine{} me.RegisterDefaultCodecs() - ctx, cancel := context.WithCancel(context.Background()) participant := &ParticipantImpl{ id: utils.NewGuid(utils.ParticipantPrefix), identity: identity, peerConn: pc, responseSink: rs, receiverConfig: receiverConfig, - ctx: ctx, - cancel: cancel, rtcpCh: utils.NewCalmChannel(50), subscribedTracks: make(map[string][]*sfu.DownTrack), lock: sync.RWMutex{}, @@ -215,6 +210,7 @@ func (p *ParticipantImpl) OnClose(callback func(types.Participant)) { // Answer an offer from remote participant, used when clients make the initial connection func (p *ParticipantImpl) Answer(sdp webrtc.SessionDescription) (answer webrtc.SessionDescription, err error) { + logger.Debugw("answering", "state", p.State().String()) if p.State() != livekit.ParticipantInfo_JOINING && p.negotiationState != negotiationStateClient { // not in a valid state to continue err = ErrUnexpectedNegotiation @@ -332,7 +328,7 @@ func (p *ParticipantImpl) Start() { } func (p *ParticipantImpl) Close() error { - if p.ctx.Err() != nil { + if !p.isClosed.TrySet(true) { // already closed return nil } @@ -346,7 +342,6 @@ func (p *ParticipantImpl) Close() error { if p.onClose != nil { p.onClose(p) } - p.cancel() p.peerConn.Close() p.rtcpCh.Close() return nil diff --git a/pkg/service/roommanager.go b/pkg/service/roommanager.go index e6ae438f..d22e607e 100644 --- a/pkg/service/roommanager.go +++ b/pkg/service/roommanager.go @@ -125,28 +125,34 @@ func (r *RoomManager) Cleanup() error { } // starts WebRTC session when a new participant is connected, takes place on RTC node -func (r *RoomManager) StartSession(roomName, identity string, requestSource routing.MessageSource, responseSink routing.MessageSink) { +func (r *RoomManager) StartSession(roomName, identity string, reconnect bool, requestSource routing.MessageSource, responseSink routing.MessageSink) { room, err := r.getOrCreateRoom(roomName) if err != nil { logger.Errorw("could not create room", "error", err) return } - // Use existing peer connection if it's already connected, perhaps from a different signal connection participant := room.GetParticipant(identity) if participant != nil { - logger.Debugw("resuming RTC session", - "room", roomName, - "node", r.currentNode.Id, - "participant", identity, - ) - // close previous sink, and link to new one - prevSink := participant.GetResponseSink() - if prevSink != nil { - prevSink.Close() + // When reconnecting, it means WS has interrupted by underlying peer connection is still ok + // in this mode, we'll keep the participant SID, and just swap the sink for the underlying connection + if reconnect { + logger.Debugw("resuming RTC session", + "room", roomName, + "node", r.currentNode.Id, + "participant", identity, + ) + // close previous sink, and link to new one + prevSink := participant.GetResponseSink() + if prevSink != nil { + prevSink.Close() + } + participant.SetResponseSink(responseSink) + return + } else { + // we need to clean up the existing participant, so a new one can join + room.RemoveParticipant(participant.Identity()) } - participant.SetResponseSink(responseSink) - return } logger.Debugw("starting RTC session", diff --git a/pkg/service/rtcservice.go b/pkg/service/rtcservice.go index 44c6043b..939da876 100644 --- a/pkg/service/rtcservice.go +++ b/pkg/service/rtcservice.go @@ -43,6 +43,8 @@ func NewRTCService(conf *config.Config, roomStore RoomStore, roomManager *RoomMa func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) { roomName := r.FormValue("room") + reconnectParam := r.FormValue("reconnect") + isReconnect := reconnectParam == "1" || reconnectParam == "true" claims := GetGrants(r.Context()) // require a claim if claims == nil || claims.Video == nil { @@ -68,12 +70,11 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // this needs to be started first *before* using router functions on this node - reqSink, resSource, err := s.router.StartParticipantSignal(roomName, identity) + reqSink, resSource, err := s.router.StartParticipantSignal(roomName, identity, isReconnect) if err != nil { handleError(w, http.StatusInternalServerError, "could not start session: "+err.Error()) return } - logger.Debugw("started participant signal", "sink", reqSink, "source", resSource) done := make(chan bool, 1) defer func() { @@ -93,7 +94,7 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) { } sigConn := NewWSSignalConnection(conn) - logger.Infow("new client connected", + logger.Infow("new client WS connected", "room", rm.Sid, "roomName", rm.Name, "name", identity, diff --git a/proto/internal.proto b/proto/internal.proto index f617f2df..c9ec4a7a 100644 --- a/proto/internal.proto +++ b/proto/internal.proto @@ -42,21 +42,12 @@ message SignalNodeMessage { } } -//message RouterMessage { -// oneof message { -// StartSession start_session = 1; -// SignalRequest request = 2; -// SignalResponse response = 3; -// EndSession end_session = 4; -// } -// // empty for start session -// string participant_key = 5; -//} - message StartSession { string room_name = 1; string identity = 2; string connection_id = 3; + // if a client is reconnecting (i.e. resume instead of restart) + bool reconnect = 4; } message EndSession { diff --git a/proto/livekit/internal.pb.go b/proto/livekit/internal.pb.go index 48320473..a80a23d0 100644 --- a/proto/livekit/internal.pb.go +++ b/proto/livekit/internal.pb.go @@ -371,6 +371,8 @@ type StartSession struct { RoomName string `protobuf:"bytes,1,opt,name=room_name,json=roomName,proto3" json:"room_name,omitempty"` Identity string `protobuf:"bytes,2,opt,name=identity,proto3" json:"identity,omitempty"` ConnectionId string `protobuf:"bytes,3,opt,name=connection_id,json=connectionId,proto3" json:"connection_id,omitempty"` + // if a client is reconnecting (i.e. resume instead of restart) + Reconnect bool `protobuf:"varint,4,opt,name=reconnect,proto3" json:"reconnect,omitempty"` } func (x *StartSession) Reset() { @@ -426,6 +428,13 @@ func (x *StartSession) GetConnectionId() string { return "" } +func (x *StartSession) GetReconnect() bool { + if x != nil { + return x.Reconnect + } + return false +} + type EndSession struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -512,18 +521,20 @@ var file_internal_proto_rawDesc = []byte{ 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x6c, 0x69, 0x76, 0x65, 0x6b, 0x69, 0x74, 0x2e, 0x45, 0x6e, 0x64, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x48, 0x00, 0x52, 0x0a, 0x65, 0x6e, 0x64, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x09, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, - 0x61, 0x67, 0x65, 0x22, 0x6c, 0x0a, 0x0c, 0x53, 0x74, 0x61, 0x72, 0x74, 0x53, 0x65, 0x73, 0x73, - 0x69, 0x6f, 0x6e, 0x12, 0x1b, 0x0a, 0x09, 0x72, 0x6f, 0x6f, 0x6d, 0x5f, 0x6e, 0x61, 0x6d, 0x65, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x6f, 0x6f, 0x6d, 0x4e, 0x61, 0x6d, 0x65, - 0x12, 0x1a, 0x0a, 0x08, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x08, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x12, 0x23, 0x0a, 0x0d, - 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, - 0x64, 0x22, 0x0c, 0x0a, 0x0a, 0x45, 0x6e, 0x64, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x42, - 0x31, 0x5a, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6c, 0x69, - 0x76, 0x65, 0x6b, 0x69, 0x74, 0x2f, 0x6c, 0x69, 0x76, 0x65, 0x6b, 0x69, 0x74, 0x2d, 0x73, 0x65, - 0x72, 0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6c, 0x69, 0x76, 0x65, 0x6b, - 0x69, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x61, 0x67, 0x65, 0x22, 0x8a, 0x01, 0x0a, 0x0c, 0x53, 0x74, 0x61, 0x72, 0x74, 0x53, 0x65, 0x73, + 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1b, 0x0a, 0x09, 0x72, 0x6f, 0x6f, 0x6d, 0x5f, 0x6e, 0x61, 0x6d, + 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x6f, 0x6f, 0x6d, 0x4e, 0x61, 0x6d, + 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x08, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x12, 0x23, 0x0a, + 0x0d, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x22, 0x0c, 0x0a, 0x0a, 0x45, 0x6e, 0x64, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x31, + 0x5a, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6c, 0x69, 0x76, + 0x65, 0x6b, 0x69, 0x74, 0x2f, 0x6c, 0x69, 0x76, 0x65, 0x6b, 0x69, 0x74, 0x2d, 0x73, 0x65, 0x72, + 0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6c, 0x69, 0x76, 0x65, 0x6b, 0x69, + 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var (