feat: SubscriptionManager to consolidate subscription handling (#1317)

Added a new manager to handle all subscription needs. Implemented using reconciler pattern. The goals are:

improve subscription resilience by separating desired state and current state
reduce complexity of synchronous processing
better detect failures with the ability to trigger full reconnect
This commit is contained in:
David Zhao
2023-01-24 23:06:16 -08:00
committed by GitHub
parent c696626fe8
commit cd6b8b80b9
31 changed files with 2625 additions and 2208 deletions
+54 -360
View File
@@ -50,20 +50,6 @@ type downTrackState struct {
downTrack sfu.DownTrackState
}
type SubscribeRequestType int
const (
SubscribeRequestTypeRemove SubscribeRequestType = iota
SubscribeRequestTypeAdd
)
type SubscribeRequest struct {
requestType SubscribeRequestType
willBeResumed bool
addCb func(sub types.LocalParticipant) error
removeCb func(subscriberID livekit.ParticipantID, willBeResumed bool) error
}
type ParticipantParams struct {
Identity livekit.ParticipantIdentity
Name livekit.ParticipantName
@@ -92,6 +78,7 @@ type ParticipantParams struct {
ReconnectOnPublicationError bool
ReconnectOnSubscriptionError bool
VersionGenerator utils2.TimedVersionGenerator
TrackResolver types.MediaTrackResolver
DisableDynacast bool
}
@@ -124,15 +111,10 @@ type ParticipantImpl struct {
*TransportManager
*UpTrackManager
*SubscriptionManager
// tracks the current participant is subscribed to
subscribedTracks map[livekit.TrackID]types.SubscribedTrack
// track settings of tracks the current participant is subscribed to
subscribedTracksSettings map[livekit.TrackID]*livekit.UpdateTrackSettings
// keeps track of disallowed tracks
// tracks and participants that this participant isn't allowed to subscribe to
disallowedSubscriptions map[livekit.TrackID]livekit.ParticipantID // trackID -> publisherID
// keeps track of other publishers ids that we are subscribed to
subscribedTo map[livekit.ParticipantID]struct{}
// keeps track of unpublished tracks in order to reuse trackID
unpublishedTracks []*livekit.TrackInfo
@@ -159,7 +141,6 @@ type ParticipantImpl struct {
onStateChange func(p types.LocalParticipant, oldState livekit.ParticipantInfo_State)
onParticipantUpdate func(types.LocalParticipant)
onDataPacket func(types.LocalParticipant, *livekit.DataPacket)
onSubscribedTo func(types.LocalParticipant, livekit.ParticipantID)
migrateState atomic.Value // types.MigrateState
@@ -169,10 +150,6 @@ type ParticipantImpl struct {
cachedDownTracks map[livekit.TrackID]*downTrackState
subscriptionInProgress map[livekit.TrackID]bool
subscriptionRequestsQueue map[livekit.TrackID][]SubscribeRequest
trackPublisherVersion map[livekit.TrackID]uint32
supervisor *supervisor.ParticipantSupervisor
}
@@ -187,19 +164,13 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
return nil, ErrMissingGrants
}
p := &ParticipantImpl{
params: params,
rtcpCh: make(chan []rtcp.Packet, 100),
pendingTracks: make(map[string]*pendingTrackInfo),
subscribedTracks: make(map[livekit.TrackID]types.SubscribedTrack),
subscribedTracksSettings: make(map[livekit.TrackID]*livekit.UpdateTrackSettings),
disallowedSubscriptions: make(map[livekit.TrackID]livekit.ParticipantID),
subscribedTo: make(map[livekit.ParticipantID]struct{}),
connectedAt: time.Now(),
rttUpdatedAt: time.Now(),
cachedDownTracks: make(map[livekit.TrackID]*downTrackState),
subscriptionInProgress: make(map[livekit.TrackID]bool),
subscriptionRequestsQueue: make(map[livekit.TrackID][]SubscribeRequest),
trackPublisherVersion: make(map[livekit.TrackID]uint32),
params: params,
rtcpCh: make(chan []rtcp.Packet, 100),
pendingTracks: make(map[string]*pendingTrackInfo),
disallowedSubscriptions: make(map[livekit.TrackID]livekit.ParticipantID),
connectedAt: time.Now(),
rttUpdatedAt: time.Now(),
cachedDownTracks: make(map[livekit.TrackID]*downTrackState),
dataChannelStats: telemetry.NewBytesTrackStats(
telemetry.BytesTrackIDForParticipantID(telemetry.BytesTrackTypeData, params.SID),
params.SID,
@@ -213,7 +184,6 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
p.SetResponseSink(params.Sink)
p.supervisor.OnPublicationError(p.onPublicationError)
p.supervisor.OnSubscriptionError(p.onSubscriptionError)
var err error
// keep last participants and when updates were sent
@@ -227,6 +197,7 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
}
p.setupUpTrackManager()
p.setupSubscriptionManager()
return p, nil
}
@@ -275,18 +246,12 @@ func (p *ParticipantImpl) IsDisconnected() bool {
func (p *ParticipantImpl) IsIdle() bool {
// check if there are any published tracks that are subscribed
for _, t := range p.GetPublishedTracks() {
if t.IsSubscribed() {
if t.GetNumSubscribers() > 0 {
return false
}
}
p.lock.RLock()
defer p.lock.RUnlock()
// check if participant is subscribed to any tracks
if len(p.subscribedTracks) != 0 || len(p.subscriptionInProgress) != 0 || len(p.subscriptionRequestsQueue) != 0 {
return false
}
return true
return !p.SubscriptionManager.HasSubscriptions()
}
func (p *ParticipantImpl) ConnectedAt() time.Time {
@@ -380,6 +345,7 @@ func (p *ParticipantImpl) SetPermission(permission *livekit.ParticipantPermissio
video.Recorder = permission.Recorder
canPublish := video.GetCanPublish()
canSubscribe := video.GetCanSubscribe()
onParticipantUpdate := p.onParticipantUpdate
onClaimsChanged := p.onClaimsChanged
p.lock.Unlock()
@@ -396,6 +362,16 @@ func (p *ParticipantImpl) SetPermission(permission *livekit.ParticipantPermissio
}
}
}
if canSubscribe {
// reconcile everything
p.SubscriptionManager.queueReconcile("")
} else {
// revoke all subscriptions
for _, st := range p.GetSubscribedTracks() {
st.MediaTrack().RemoveSubscriber(p.ID(), false)
}
}
// update isPublisher attribute
p.isPublisher.Store(canPublish && p.TransportManager.IsPublisherEstablished())
@@ -460,12 +436,6 @@ func (p *ParticipantImpl) OnDataPacket(callback func(types.LocalParticipant, *li
p.lock.Unlock()
}
func (p *ParticipantImpl) OnSubscribedTo(callback func(types.LocalParticipant, livekit.ParticipantID)) {
p.lock.Lock()
p.onSubscribedTo = callback
p.lock.Unlock()
}
func (p *ParticipantImpl) OnClose(callback func(types.LocalParticipant, map[livekit.TrackID]livekit.ParticipantID)) {
p.lock.Lock()
p.onClose = callback
@@ -665,12 +635,6 @@ func (p *ParticipantImpl) Close(sendLeave bool, reason types.ParticipantCloseRea
for trackID, publisherID := range p.disallowedSubscriptions {
disallowedSubscriptions[trackID] = publisherID
}
// remove all down tracks
downTracksToClose := make([]*sfu.DownTrack, 0, len(p.subscribedTracks))
for _, st := range p.subscribedTracks {
downTracksToClose = append(downTracksToClose, st.DownTrack())
}
p.lock.Unlock()
p.updateState(livekit.ParticipantInfo_DISCONNECTED)
@@ -684,13 +648,10 @@ func (p *ParticipantImpl) Close(sendLeave bool, reason types.ParticipantCloseRea
onClose(p, disallowedSubscriptions)
}
// Close peer connections without blocking participant close. If peer connections are gathering candidates
// Close peer connections without blocking participant Close. If peer connections are gathering candidates
// Close will block.
go func() {
for _, dt := range downTracksToClose {
dt.CloseWithFlush(sendLeave)
}
p.SubscriptionManager.Close(!sendLeave)
p.TransportManager.Close()
}()
@@ -698,6 +659,10 @@ func (p *ParticipantImpl) Close(sendLeave bool, reason types.ParticipantCloseRea
return nil
}
func (p *ParticipantImpl) IsClosed() bool {
return p.isClosed.Load()
}
// Negotiate subscriber SDP with client, if force is true, will cencel pending
// negotiate task and negotiate immediately
func (p *ParticipantImpl) Negotiate(force bool) {
@@ -755,16 +720,7 @@ func (p *ParticipantImpl) MaybeStartMigration(force bool, onStart func()) bool {
// DownTrack close has checks to handle the case of closing before bind.
// So, an `Unbind` before close would bypass that logic.
//
p.lock.Lock()
downTracksToClose := make([]*sfu.DownTrack, 0, len(p.subscribedTracks))
for _, st := range p.subscribedTracks {
downTracksToClose = append(downTracksToClose, st.DownTrack())
}
p.lock.Unlock()
for _, dt := range downTracksToClose {
dt.CloseWithFlush(false)
}
p.SubscriptionManager.Close(true)
p.TransportManager.SubscriberClose()
})
@@ -847,9 +803,9 @@ func (p *ParticipantImpl) GetConnectionQuality() *livekit.ConnectionQualityInfo
totalScore += score
}
p.lock.RLock()
subscriberScores := make(map[livekit.TrackID]float32, len(p.subscribedTracks))
for _, subTrack := range p.subscribedTracks {
subscribedTracks := p.SubscriptionManager.GetSubscribedTracks()
subscriberScores := make(map[livekit.TrackID]float32, len(subscribedTracks))
for _, subTrack := range subscribedTracks {
if subTrack.IsMuted() || subTrack.MediaTrack().IsMuted() {
continue
}
@@ -858,7 +814,6 @@ func (p *ParticipantImpl) GetConnectionQuality() *livekit.ConnectionQualityInfo
totalScore += score
numTracks++
}
p.lock.RUnlock()
avgScore := float32(5.0)
if numTracks > 0 {
@@ -872,25 +827,6 @@ func (p *ParticipantImpl) GetConnectionQuality() *livekit.ConnectionQualityInfo
}
}
func (p *ParticipantImpl) GetSubscribedParticipants() []livekit.ParticipantID {
p.lock.RLock()
defer p.lock.RUnlock()
var participantIDs []livekit.ParticipantID
for pID := range p.subscribedTo {
participantIDs = append(participantIDs, pID)
}
return participantIDs
}
func (p *ParticipantImpl) IsSubscribedTo(participantID livekit.ParticipantID) bool {
p.lock.RLock()
defer p.lock.RUnlock()
_, ok := p.subscribedTo[participantID]
return ok
}
func (p *ParticipantImpl) IsPublisher() bool {
return p.isPublisher.Load()
}
@@ -930,23 +866,6 @@ func (p *ParticipantImpl) IsRecorder() bool {
return p.grants.Video.Recorder
}
func (p *ParticipantImpl) UpdateSubscribedTrackSettings(trackID livekit.TrackID, settings *livekit.UpdateTrackSettings) error {
p.lock.Lock()
p.subscribedTracksSettings[trackID] = settings
subTrack := p.subscribedTracks[trackID]
if subTrack == nil {
// will get set when subscribed track is added
p.lock.Unlock()
p.params.Logger.Infow("could not find subscribed track", "trackID", trackID)
return nil
}
p.lock.Unlock()
subTrack.UpdateSubscriberSettings(settings)
return nil
}
func (p *ParticipantImpl) VerifySubscribeParticipantInfo(pID livekit.ParticipantID, version uint32) {
if !p.IsReady() {
// we have not sent a JoinResponse yet. metadata would be covered in JoinResponse
@@ -963,133 +882,23 @@ func (p *ParticipantImpl) VerifySubscribeParticipantInfo(pID livekit.Participant
}
}
// AddSubscribedTrack adds a track to the participant's subscribed list
func (p *ParticipantImpl) AddSubscribedTrack(subTrack types.SubscribedTrack, sourceTrack types.MediaTrack) {
p.lock.Lock()
if v, ok := p.trackPublisherVersion[subTrack.ID()]; ok && v > subTrack.PublisherVersion() {
p.supervisor.SetSubscribedTrack(subTrack.ID(), subTrack, sourceTrack)
p.lock.Unlock()
p.params.Logger.Debugw("ignoring add subscribedTrack from older version",
"current", v,
"requesting", subTrack.PublisherVersion(),
"trackID", subTrack.ID(),
)
return
}
p.params.Logger.Debugw("added subscribedTrack",
"publisherID", subTrack.PublisherID(),
"publisherIdentity", subTrack.PublisherIdentity(),
"trackID", subTrack.ID())
p.trackPublisherVersion[subTrack.ID()] = subTrack.PublisherVersion()
onSubscribedTo := p.onSubscribedTo
p.subscribedTracks[subTrack.ID()] = subTrack
// TODO: I believe we have yet to negotiate with the subscriber, so it's a bit early to consider the track been
// successfully subscribed to
// ideally we consider it's successful after the participant has answered that offer OR we've received the
// first receiver report
// will move the telemetry options when this is implemented
p.supervisor.SetSubscribedTrack(subTrack.ID(), subTrack, sourceTrack)
p.params.Telemetry.TrackSubscribed(context.Background(), p.ID(), sourceTrack.ToProto(), &livekit.ParticipantInfo{
Identity: string(subTrack.PublisherIdentity()),
Sid: string(subTrack.PublisherID()),
})
settings := p.subscribedTracksSettings[subTrack.ID()]
p.lock.Unlock()
// onTrackSubscribed handles post-processing after a track is subscribed
func (p *ParticipantImpl) onTrackSubscribed(subTrack types.SubscribedTrack) {
if p.params.ClientInfo.FireTrackByRTPPacket() {
subTrack.DownTrack().SetActivePaddingOnMuteUpTrack()
}
subTrack.OnBind(func() {
subTrack.AddOnBind(func() {
if p.TransportManager.HasSubscriberEverConnected() {
subTrack.DownTrack().SetConnected()
}
p.TransportManager.AddSubscribedTrack(subTrack)
})
if settings != nil {
subTrack.UpdateSubscriberSettings(settings)
}
publisherID := subTrack.PublisherID()
p.lock.Lock()
_, isAlreadySubscribed := p.subscribedTo[publisherID]
p.subscribedTo[publisherID] = struct{}{}
p.lock.Unlock()
if !isAlreadySubscribed && onSubscribedTo != nil {
onSubscribedTo(p, publisherID)
}
}
// RemoveSubscribedTrack removes a track to the participant's subscribed list
func (p *ParticipantImpl) RemoveSubscribedTrack(subTrack types.SubscribedTrack, sourceTrack types.MediaTrack) {
p.lock.Lock()
if v, ok := p.trackPublisherVersion[subTrack.ID()]; ok && v > subTrack.PublisherVersion() {
p.supervisor.ClearSubscribedTrack(subTrack.ID(), subTrack, sourceTrack)
p.lock.Unlock()
p.params.Logger.Debugw("ignoring remove subscribedTrack from older version",
"current", v,
"requesting", subTrack.PublisherVersion(),
"trackID", subTrack.ID(),
)
return
}
p.params.Logger.Debugw("removed subscribedTrack",
"publisherID", subTrack.PublisherID(),
"publisherIdentity", subTrack.PublisherIdentity(),
"trackID", subTrack.ID(), "kind", subTrack.DownTrack().Kind())
p.trackPublisherVersion[subTrack.ID()] = subTrack.PublisherVersion()
delete(p.subscribedTracks, subTrack.ID())
p.supervisor.ClearSubscribedTrack(subTrack.ID(), subTrack, sourceTrack)
// remove from subscribed map
numRemaining := 0
for _, st := range p.subscribedTracks {
if st.PublisherID() == subTrack.PublisherID() {
numRemaining++
}
}
//
// NOTE
// subscribedTracksSettings should not be deleted on removal as it is needed if corresponding publisher migrated
// LK-TODO: find a way to clean these up
//
if numRemaining == 0 {
delete(p.subscribedTo, subTrack.PublisherID())
}
p.lock.Unlock()
// onTrackUnsubscribed handles post-processing after a track is unsubscribed
func (p *ParticipantImpl) onTrackUnsubscribed(subTrack types.SubscribedTrack) {
p.TransportManager.RemoveSubscribedTrack(subTrack)
if numRemaining == 0 {
//
// When a participant leaves OR
// this participant unsubscribes from all tracks of another participant,
// have to send speaker update indicating that the participant speaker is no long active
// so that clients can clean up their speaker state for the leaving/unsubscribed participant
//
if p.ProtocolVersion().SupportsSpeakerChanged() {
_ = p.writeMessage(&livekit.SignalResponse{
Message: &livekit.SignalResponse_SpeakersChanged{
SpeakersChanged: &livekit.SpeakersChanged{
Speakers: []*livekit.SpeakerInfo{
{
Sid: string(subTrack.PublisherID()),
Level: 0,
Active: false,
},
},
},
},
})
}
}
}
func (p *ParticipantImpl) SubscriptionPermissionUpdate(publisherID livekit.ParticipantID, trackID livekit.TrackID, allowed bool) {
@@ -1224,6 +1033,18 @@ func (p *ParticipantImpl) setupUpTrackManager() {
p.UpTrackManager.OnUpTrackManagerClose(p.onUpTrackManagerClose)
}
func (p *ParticipantImpl) setupSubscriptionManager() {
p.SubscriptionManager = NewSubscriptionManager(SubscriptionManagerParams{
Participant: p,
Logger: p.params.Logger,
TrackResolver: p.params.TrackResolver,
Telemetry: p.params.Telemetry,
OnTrackSubscribed: p.onTrackSubscribed,
OnTrackUnsubscribed: p.onTrackUnsubscribed,
OnSubcriptionError: p.onSubscriptionError,
})
}
func (p *ParticipantImpl) updateState(state livekit.ParticipantInfo_State) {
oldState := p.State()
if state == oldState {
@@ -1399,8 +1220,9 @@ func (p *ParticipantImpl) subscriberRTCPWorker() {
var srs []rtcp.Packet
var sd []rtcp.SourceDescriptionChunk
subscribedTracks := p.SubscriptionManager.GetSubscribedTracks()
p.lock.RLock()
for _, subTrack := range p.subscribedTracks {
for _, subTrack := range subscribedTracks {
sr := subTrack.DownTrack().CreateSenderReport()
chunks := subTrack.DownTrack().CreateSourceDescriptionChunks()
if sr == nil || chunks == nil {
@@ -2010,30 +1832,9 @@ func (p *ParticipantImpl) DebugInfo() map[string]interface{} {
info["UpTrackManager"] = p.UpTrackManager.DebugInfo()
subscribedTrackInfo := make(map[livekit.TrackID]interface{})
p.lock.RLock()
for _, track := range p.subscribedTracks {
dt := track.DownTrack().DebugInfo()
dt["SubMuted"] = track.IsMuted()
subscribedTrackInfo[track.ID()] = dt
}
p.lock.RUnlock()
info["SubscribedTracks"] = subscribedTrackInfo
return info
}
func (p *ParticipantImpl) GetSubscribedTracks() []types.SubscribedTrack {
p.lock.RLock()
defer p.lock.RUnlock()
tracks := make([]types.SubscribedTrack, 0, len(p.subscribedTracks))
for _, t := range p.subscribedTracks {
tracks = append(tracks, t)
}
return tracks
}
func (p *ParticipantImpl) postRtcp(pkts []rtcp.Packet) {
select {
case p.rtcpCh <- pkts:
@@ -2043,10 +1844,7 @@ func (p *ParticipantImpl) postRtcp(pkts []rtcp.Packet) {
}
func (p *ParticipantImpl) setDowntracksConnected() {
p.lock.RLock()
defer p.lock.RUnlock()
for _, t := range p.subscribedTracks {
for _, t := range p.GetSubscribedTracks() {
if dt := t.DownTrack(); dt != nil {
dt.SetConnected()
}
@@ -2119,110 +1917,6 @@ func (p *ParticipantImpl) onAnyTransportNegotiationFailed() {
p.issueFullReconnect(types.ParticipantCloseReasonNegotiateFailed)
}
func (p *ParticipantImpl) EnqueueSubscribeTrack(trackID livekit.TrackID, sourceTrack types.MediaTrack, isRelayed bool, f func(sub types.LocalParticipant) error) bool {
// do not queue subscription is participant is already closed/disconnected
if p.isClosed.Load() || p.IsDisconnected() {
return false
}
p.params.Logger.Debugw("queuing subscribe", "trackID", trackID, "relayed", isRelayed)
p.supervisor.UpdateSubscription(trackID, true, sourceTrack)
p.params.Telemetry.TrackSubscribeRequested(
context.Background(),
p.ID(),
sourceTrack.ToProto(),
&livekit.ParticipantInfo{
Sid: string(sourceTrack.PublisherID()),
Identity: string(sourceTrack.PublisherIdentity()),
},
)
p.lock.Lock()
p.subscriptionRequestsQueue[trackID] = append(p.subscriptionRequestsQueue[trackID], SubscribeRequest{
requestType: SubscribeRequestTypeAdd,
addCb: f,
})
p.lock.Unlock()
go p.ProcessSubscriptionRequestsQueue(trackID)
return true
}
func (p *ParticipantImpl) EnqueueUnsubscribeTrack(
trackID livekit.TrackID,
sourceTrack types.MediaTrack,
isRelayed bool,
willBeResumed bool,
f func(subscriberID livekit.ParticipantID, willBeResumed bool) error,
) bool {
p.params.Logger.Debugw("queuing unsubscribe", "trackID", trackID, "relayed", isRelayed)
p.supervisor.UpdateSubscription(trackID, false, sourceTrack)
p.lock.Lock()
p.subscriptionRequestsQueue[trackID] = append(p.subscriptionRequestsQueue[trackID], SubscribeRequest{
requestType: SubscribeRequestTypeRemove,
willBeResumed: willBeResumed,
removeCb: f,
})
p.lock.Unlock()
go p.ProcessSubscriptionRequestsQueue(trackID)
return true
}
func (p *ParticipantImpl) ProcessSubscriptionRequestsQueue(trackID livekit.TrackID) {
p.lock.Lock()
if p.subscriptionInProgress[trackID] || len(p.subscriptionRequestsQueue[trackID]) == 0 {
p.lock.Unlock()
return
}
request := p.subscriptionRequestsQueue[trackID][0]
p.subscriptionRequestsQueue[trackID] = p.subscriptionRequestsQueue[trackID][1:]
if len(p.subscriptionRequestsQueue[trackID]) == 0 {
delete(p.subscriptionRequestsQueue, trackID)
}
p.subscriptionInProgress[trackID] = true
p.lock.Unlock()
switch request.requestType {
case SubscribeRequestTypeAdd:
err := request.addCb(p)
if err != nil {
if err != errAlreadySubscribed {
p.params.Logger.Errorw("error adding subscriber", err, "trackID", trackID)
}
// process pending request even if adding errors out
p.ClearInProgressAndProcessSubscriptionRequestsQueue(trackID)
}
case SubscribeRequestTypeRemove:
err := request.removeCb(p.ID(), request.willBeResumed)
if err != nil {
p.ClearInProgressAndProcessSubscriptionRequestsQueue(trackID)
}
default:
p.params.Logger.Warnw("unknown request type", nil,
"requestType", request.requestType)
// let the queue move forward
p.ClearInProgressAndProcessSubscriptionRequestsQueue(trackID)
}
}
func (p *ParticipantImpl) ClearInProgressAndProcessSubscriptionRequestsQueue(trackID livekit.TrackID) {
p.lock.Lock()
delete(p.subscriptionInProgress, trackID)
p.lock.Unlock()
go p.ProcessSubscriptionRequestsQueue(trackID)
}
func (p *ParticipantImpl) UpdateSubscribedQuality(nodeID livekit.NodeID, trackID livekit.TrackID, maxQualities []types.SubscribedCodecQuality) error {
track := p.GetPublishedTrack(trackID)
if track == nil {