Room closed fix (#370)

* Room closed fix

* switch to uber/atomic

* release after err check
This commit is contained in:
David Colburn
2022-01-25 09:23:22 -07:00
committed by GitHub
parent bb26109096
commit c92e0e38d5
3 changed files with 60 additions and 41 deletions
+38 -26
View File
@@ -4,12 +4,12 @@ import (
"math"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/go-logr/logr"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"go.uber.org/atomic"
"google.golang.org/protobuf/proto"
"github.com/livekit/livekit-server/pkg/config"
@@ -42,9 +42,10 @@ type Room struct {
bufferFactory *buffer.Factory
// time the first participant joined the room
joinedAt atomic.Value
joinedAt atomic.Int64
holds atomic.Int32
// time that the last participant left the room
leftAt atomic.Value
leftAt atomic.Int64
closed chan struct{}
closeOnce sync.Once
@@ -145,30 +146,38 @@ func (r *Room) GetBufferFactory() *buffer.Factory {
}
func (r *Room) FirstJoinedAt() int64 {
j := r.joinedAt.Load()
if t, ok := j.(int64); ok {
return t
}
return 0
return r.joinedAt.Load()
}
func (r *Room) LastLeftAt() int64 {
l := r.leftAt.Load()
if t, ok := l.(int64); ok {
return t
return r.leftAt.Load()
}
func (r *Room) Hold() bool {
r.lock.Lock()
defer r.lock.Unlock()
if r.IsClosed() {
return false
}
return 0
r.holds.Inc()
return true
}
func (r *Room) Release() {
r.holds.Dec()
}
func (r *Room) Join(participant types.LocalParticipant, opts *ParticipantOptions, iceServers []*livekit.ICEServer) error {
r.lock.Lock()
defer r.lock.Unlock()
if r.IsClosed() {
prometheus.ServiceOperationCounter.WithLabelValues("participant_join", "error", "room_closed").Add(1)
return ErrRoomClosed
}
r.lock.Lock()
defer r.lock.Unlock()
if r.participants[participant.Identity()] != nil {
prometheus.ServiceOperationCounter.WithLabelValues("participant_join", "error", "already_joined").Add(1)
return ErrAlreadyJoined
@@ -416,22 +425,18 @@ func (r *Room) IsClosed() bool {
// CloseIfEmpty closes the room if all participants had left, or it's still empty past timeout
func (r *Room) CloseIfEmpty() {
if r.IsClosed() {
r.lock.Lock()
defer r.lock.Unlock()
if r.IsClosed() || r.holds.Load() > 0 {
return
}
r.lock.RLock()
visibleParticipants := 0
for _, p := range r.participants {
if !p.Hidden() {
visibleParticipants++
return
}
}
r.lock.RUnlock()
if visibleParticipants > 0 {
return
}
timeout := r.Room.EmptyTimeout
var elapsed int64
@@ -446,17 +451,24 @@ func (r *Room) CloseIfEmpty() {
}
if elapsed >= int64(timeout) {
r.Close()
r.closeLocked()
}
}
func (r *Room) Close() {
r.lock.Lock()
defer r.lock.Unlock()
r.closeLocked()
}
func (r *Room) closeLocked() {
r.closeOnce.Do(func() {
close(r.closed)
r.Logger.Infow("closing room")
if r.onClose != nil {
r.onClose()
}
close(r.closed)
})
}