add drain function to rtc service

This commit is contained in:
paulwe
2023-06-15 11:56:41 -07:00
parent 12db469297
commit 0dab55556d
+34
View File
@@ -5,14 +5,17 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"math/rand"
"net/http" "net/http"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/ua-parser/uap-go/uaparser" "github.com/ua-parser/uap-go/uaparser"
"golang.org/x/exp/maps"
"github.com/livekit/livekit-server/pkg/utils" "github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
@@ -37,6 +40,9 @@ type RTCService struct {
limits config.LimitConfig limits config.LimitConfig
parser *uaparser.Parser parser *uaparser.Parser
telemetry telemetry.TelemetryService telemetry telemetry.TelemetryService
mu sync.Mutex
connections map[*websocket.Conn]struct{}
} }
func NewRTCService( func NewRTCService(
@@ -58,6 +64,7 @@ func NewRTCService(
limits: conf.Limit, limits: conf.Limit,
parser: uaparser.NewFromSaved(), parser: uaparser.NewFromSaved(),
telemetry: telemetry, telemetry: telemetry,
connections: map[*websocket.Conn]struct{}{},
} }
// allow connections from any origin, since script may be hosted anywhere // allow connections from any origin, since script may be hosted anywhere
@@ -250,6 +257,16 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return return
} }
s.mu.Lock()
s.connections[conn] = struct{}{}
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.connections, conn)
s.mu.Unlock()
}()
// websocket established // websocket established
sigConn := NewWSSignalConnection(conn) sigConn := NewWSSignalConnection(conn)
if count, err := sigConn.WriteResponse(initialResponse); err != nil { if count, err := sigConn.WriteResponse(initialResponse); err != nil {
@@ -442,6 +459,23 @@ func (s *RTCService) ParseClientInfo(r *http.Request) *livekit.ClientInfo {
return ci return ci
} }
func (s *RTCService) DrainConnections(interval time.Duration) {
s.mu.Lock()
conns := maps.Clone(s.connections)
s.mu.Unlock()
// jitter drain start
time.Sleep(time.Duration(rand.Int63n(int64(interval))))
t := time.NewTicker(interval)
defer t.Stop()
for c := range conns {
c.Close()
<-t.C
}
}
type connectionResult struct { type connectionResult struct {
Room *livekit.Room Room *livekit.Room
ConnectionID livekit.ConnectionID ConnectionID livekit.ConnectionID