Delete v2 signalling (#3835)

* Delete v2 signalling

* deps

* mage generate

* deelte unused file
This commit is contained in:
Raja Subramanian
2025-08-06 09:08:09 +05:30
committed by GitHub
parent 1fe337160a
commit 34a491309f
34 changed files with 156 additions and 2664 deletions
-236
View File
@@ -34,7 +34,6 @@ import (
"github.com/livekit/protocol/observability"
"github.com/livekit/protocol/observability/roomobs"
"github.com/livekit/protocol/rpc"
"github.com/livekit/protocol/signalling"
"github.com/livekit/protocol/utils"
"github.com/livekit/protocol/utils/guid"
"github.com/livekit/protocol/utils/must"
@@ -566,241 +565,6 @@ func (r *RoomManager) StartSession(
return nil
}
// SIGNALLING-V2-TODO: consolidate common parts beteen this and `StartSession`
func (r *RoomManager) HandleConnect(
ctx context.Context,
grants *auth.ClaimGrants,
createRoom *livekit.CreateRoomRequest,
wireMessage *livekit.Signalv2WireMessage, // contains livekit.ConnectRequest
) (*livekit.Signalv2WireMessage, error) {
sessionStartTime := time.Now()
// find connect request in wire message
connectRequest := signalling.GetConnectRequest(wireMessage)
if connectRequest == nil {
return nil, ErrNoConnectRequest
}
room, err := r.getOrCreateRoom(ctx, createRoom)
if err != nil {
return nil, err
}
defer room.Release()
protoRoom, roomInternal := room.ToProto(), room.Internal()
participantIdentity := livekit.ParticipantIdentity(grants.Identity)
// should not error out, error is logged in iceServersForParticipant even if it fails
// since this is used for TURN server credentials, we don't want to fail the request even if there's no TURN for the session
apiKey, _, _ := r.getFirstKeyPair()
/* SIGNALLING-V2-TODO - v2 should not have ICERestart, but leaving reminder here (similar location as `StartSession` code check on this path */
sid := livekit.ParticipantID(guid.New(utils.ParticipantPrefix))
pLogger := rtc.LoggerWithParticipant(
rtc.LoggerWithRoom(logger.GetLogger(), room.Name(), room.ID()),
participantIdentity,
sid,
false,
)
pLogger.Infow(
"starting RTC session",
"room", room.Name(),
"nodeID", r.currentNode.NodeID(),
"numParticipants", room.GetParticipantCount(),
"grants", grants,
"createRoom", logger.Proto(createRoom),
"wireMessage", logger.Proto(wireMessage),
)
clientInfo := connectRequest.ClientInfo
clientConf := r.clientConfManager.GetConfiguration(clientInfo)
rtcConf := *r.rtcConfig
rtcConf.SetBufferFactory(room.GetBufferFactory())
if connectRequest.ConnectionSettings.DisableIceLite {
rtcConf.SettingEngine.SetLite(false)
}
// default allow forceTCP
allowFallback := true
if r.config.RTC.AllowTCPFallback != nil {
allowFallback = *r.config.RTC.AllowTCPFallback
}
// default do not force full reconnect on a publication error
reconnectOnPublicationError := false
if r.config.RTC.ReconnectOnPublicationError != nil {
reconnectOnPublicationError = *r.config.RTC.ReconnectOnPublicationError
}
// default do not force full reconnect on a subscription error
reconnectOnSubscriptionError := false
if r.config.RTC.ReconnectOnSubscriptionError != nil {
reconnectOnSubscriptionError = *r.config.RTC.ReconnectOnSubscriptionError
}
// default do not force full reconnect on a data channel error
reconnectOnDataChannelError := false
if r.config.RTC.ReconnectOnDataChannelError != nil {
reconnectOnDataChannelError = *r.config.RTC.ReconnectOnDataChannelError
}
subscriberAllowPause := r.config.RTC.CongestionControl.AllowPause
if connectRequest.ConnectionSettings.SubscriberAllowPause != nil {
subscriberAllowPause = *connectRequest.ConnectionSettings.SubscriberAllowPause
}
participant, err := rtc.NewParticipant(rtc.ParticipantParams{
Identity: participantIdentity,
Name: livekit.ParticipantName(grants.Name),
SID: sid,
Config: &rtcConf,
AudioConfig: r.config.Audio,
VideoConfig: r.config.Video,
LimitConfig: r.config.Limit,
ProtocolVersion: types.ProtocolVersion(clientInfo.Protocol),
SessionStartTime: sessionStartTime,
Telemetry: r.telemetry,
Trailer: room.Trailer(),
PLIThrottleConfig: r.config.RTC.PLIThrottle,
CongestionControlConfig: r.config.RTC.CongestionControl,
PublishEnabledCodecs: protoRoom.EnabledCodecs,
SubscribeEnabledCodecs: protoRoom.EnabledCodecs,
Grants: grants,
Logger: pLogger,
Reporter: roomobs.NewNoopParticipantSessionReporter(),
ClientConf: clientConf,
ClientInfo: rtc.ClientInfo{ClientInfo: clientInfo},
// SIGNALLING-V@-TODO Region: pi.Region,
AdaptiveStream: connectRequest.ConnectionSettings.AdaptiveStream,
AllowTCPFallback: allowFallback,
TURNSEnabled: r.config.IsTURNSEnabled(),
ParticipantHelper: &roomManagerParticipantHelper{
room: room,
codecRegressionThreshold: r.config.Video.CodecRegressionThreshold,
},
ReconnectOnPublicationError: reconnectOnPublicationError,
ReconnectOnSubscriptionError: reconnectOnSubscriptionError,
ReconnectOnDataChannelError: reconnectOnDataChannelError,
VersionGenerator: r.versionGenerator,
SubscriberAllowPause: subscriberAllowPause,
SubscriptionLimitAudio: r.config.Limit.SubscriptionLimitAudio,
SubscriptionLimitVideo: r.config.Limit.SubscriptionLimitVideo,
PlayoutDelay: roomInternal.GetPlayoutDelay(),
SyncStreams: roomInternal.GetSyncStreams(),
ForwardStats: r.forwardStats,
MetricConfig: r.config.Metric,
DataChannelMaxBufferedAmount: r.config.RTC.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: r.config.RTC.DatachannelSlowThreshold,
FireOnTrackBySdp: true,
SynchronousLocalCandidatesMode: true,
})
if err != nil {
return nil, err
}
iceConfig := r.setIceConfig(room.Name(), participant)
// join room
opts := rtc.ParticipantOptions{
AutoSubscribe: connectRequest.ConnectionSettings.AutoSubscribe,
}
iceServers := r.iceServersForParticipant(
apiKey,
participant,
iceConfig.PreferenceSubscriber == livekit.ICECandidateType_ICT_TLS,
)
if err := room.Joinv2(participant, &opts, iceServers); err != nil {
pLogger.Errorw("could not join room", err)
_ = participant.Close(true, types.ParticipantCloseReasonJoinFailed, false)
return nil, err
}
// SIGNALLING-V2-TODO: process messages other than ConnecRequest in envelope.
var wireMessageResponse *livekit.Signalv2WireMessage
if pending := participant.SignalPendingMessages(); pending != nil {
var ok bool
if wireMessageResponse, ok = pending.(*livekit.Signalv2WireMessage); !ok {
pLogger.Errorw("could not join room", ErrInvalidMessageType)
_ = participant.Close(true, types.ParticipantCloseReasonJoinFailed, false)
return nil, ErrInvalidMessageType
}
}
if signalling.GetConnectResponse(wireMessageResponse) == nil {
pLogger.Errorw("could not join room", ErrNoConnectResponse)
_ = participant.Close(true, types.ParticipantCloseReasonJoinFailed, false)
return nil, ErrNoConnectResponse
}
var participantServerClosers utils.Closers
participantTopic := rpc.FormatParticipantTopic(room.Name(), participant.Identity())
participantServer := must.Get(rpc.NewTypedParticipantServer(r, r.bus))
participantServerClosers = append(participantServerClosers, utils.CloseFunc(r.participantServers.Replace(participantTopic, participantServer)))
if err := participantServer.RegisterAllParticipantTopics(participantTopic); err != nil {
participantServerClosers.Close()
pLogger.Errorw("could not join register participant topic", err)
_ = participant.Close(true, types.ParticipantCloseReasonMessageBusFailed, false)
return nil, err
}
httpSignalParticipantServer := must.Get(rpc.NewTypedSignalv2ParticipantServer(signalv2ParticipantService{r}, r.bus))
participantServerClosers = append(
participantServerClosers,
utils.CloseFunc(r.httpSignalParticipantServers.Replace(participantTopic, httpSignalParticipantServer)),
)
if err := httpSignalParticipantServer.RegisterAllCommonTopics(participantTopic); err != nil {
participantServerClosers.Close()
pLogger.Errorw("could not join register participant topic for http signalling", err)
_ = participant.Close(true, types.ParticipantCloseReasonMessageBusFailed, false)
return nil, err
}
if err = r.roomStore.StoreParticipant(ctx, room.Name(), participant.ToProto()); err != nil {
pLogger.Errorw("could not store participant", err)
}
persistRoomForParticipantCount := func(proto *livekit.Room) {
if !participant.Hidden() && !room.IsClosed() {
err = r.roomStore.StoreRoom(ctx, proto, room.Internal())
if err != nil {
logger.Errorw("could not store room", err)
}
}
}
// update room store with new numParticipants
persistRoomForParticipantCount(room.ToProto())
clientMeta := &livekit.AnalyticsClientMeta{
Region: r.currentNode.Region(),
Node: string(r.currentNode.NodeID()),
}
r.telemetry.ParticipantJoined(ctx, protoRoom, participant.ToProto(), clientInfo, clientMeta, true)
participant.OnClose(func(p types.LocalParticipant) {
if err := r.roomStore.DeleteParticipant(ctx, room.Name(), p.Identity()); err != nil {
pLogger.Errorw("could not delete participant", err)
}
// update room store with new numParticipants
proto := room.ToProto()
persistRoomForParticipantCount(proto)
r.telemetry.ParticipantLeft(ctx, proto, p.ToProto(), true)
})
participant.OnClaimsChanged(func(participant types.LocalParticipant) {
pLogger.Debugw("refreshing client token after claims change")
if err := r.refreshToken(participant); err != nil {
pLogger.Errorw("could not refresh token", err)
}
})
participant.OnICEConfigChanged(func(participant types.LocalParticipant, iceConfig *livekit.ICEConfig) {
r.iceConfigCache.Put(iceConfigCacheKey{room.Name(), participant.Identity()}, iceConfig)
})
return wireMessageResponse, nil
}
// create the actual room object, to be used on RTC node
func (r *RoomManager) getOrCreateRoom(ctx context.Context, createRoom *livekit.CreateRoomRequest) (*rtc.Room, error) {
roomName := livekit.RoomName(createRoom.Name)
-54
View File
@@ -194,57 +194,3 @@ func (r whipParticipantService) DeleteSession(ctx context.Context, req *rpc.WHIP
}
// --------------------------------
type signalv2ParticipantService struct {
*RoomManager
}
func (s signalv2ParticipantService) RelaySignalv2Participant(ctx context.Context, req *rpc.RelaySignalv2ParticipantRequest) (*rpc.RelaySignalv2ParticipantResponse, error) {
room := s.RoomManager.GetRoom(ctx, livekit.RoomName(req.Room))
if room == nil {
return nil, ErrRoomNotFound
}
lp := room.GetParticipantByID(livekit.ParticipantID(req.ParticipantId))
if lp == nil {
return nil, ErrParticipantNotFound
}
err := lp.HandleSignalMessage(req.WireMessage)
if err != nil {
return nil, err
}
var wireMessage *livekit.Signalv2WireMessage
if pending := lp.SignalPendingMessages(); pending != nil {
var ok bool
if wireMessage, ok = pending.(*livekit.Signalv2WireMessage); !ok {
return nil, ErrInvalidMessageType
}
}
return &rpc.RelaySignalv2ParticipantResponse{
WireMessage: wireMessage,
}, nil
}
func (s signalv2ParticipantService) RelaySignalv2ParticipantDeleteSession(
ctx context.Context,
req *rpc.RelaySignalv2ParticipantDeleteSessionRequest,
) (*emptypb.Empty, error) {
room := s.RoomManager.GetRoom(ctx, livekit.RoomName(req.Room))
if room == nil {
return nil, ErrRoomNotFound
}
lp := room.GetParticipantByID(livekit.ParticipantID(req.ParticipantId))
if lp != nil {
room.RemoveParticipant(
lp.Identity(),
lp.ID(),
types.ParticipantCloseReasonClientRequestLeave,
)
}
return &emptypb.Empty{}, nil
}
-361
View File
@@ -1,361 +0,0 @@
// 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 service
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/rpc"
"github.com/livekit/protocol/signalling"
"github.com/livekit/psrpc"
"google.golang.org/protobuf/proto"
)
var (
errFragmentsInHTTP = errors.New("should not get fragments via HTTP request")
errUnknownMessageType = errors.New("unknown message type")
)
const (
cRTCv2Path = "/rtc/v2"
cRTCv2ValidatePath = "/rtc/v2/validate"
cRTCv2ParticipantIDPath = "/rtc/v2/{participant_id}"
)
type RTCv2Service struct {
http.Handler
limits config.LimitConfig
roomAllocator RoomAllocator
router routing.MessageRouter
topicFormatter rpc.TopicFormatter
signalv2ParticipantClient rpc.TypedSignalv2ParticipantClient
}
func NewRTCv2Service(
config *config.Config,
roomAllocator RoomAllocator,
router routing.MessageRouter,
topicFormatter rpc.TopicFormatter,
signalv2ParticipantClient rpc.TypedSignalv2ParticipantClient,
) *RTCv2Service {
return &RTCv2Service{
limits: config.Limit,
router: router,
roomAllocator: roomAllocator,
topicFormatter: topicFormatter,
signalv2ParticipantClient: signalv2ParticipantClient,
}
}
func (s *RTCv2Service) SetupRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST "+cRTCv2Path, s.handlePost)
mux.HandleFunc("GET "+cRTCv2ValidatePath, s.validate)
mux.HandleFunc("PATCH "+cRTCv2ParticipantIDPath, s.handleParticipantPatch)
mux.HandleFunc("DELETE "+cRTCv2ParticipantIDPath, s.handleParticipantDelete)
}
func (s *RTCv2Service) validateInternal(
lgr logger.Logger,
r *http.Request,
wireMessage *livekit.Signalv2WireMessage,
) (livekit.RoomName, livekit.ParticipantIdentity, *rpc.RelaySignalv2ConnectRequest, int, error) {
connectRequest := signalling.GetConnectRequest(wireMessage)
if connectRequest == nil {
return "", "", nil, http.StatusBadRequest, ErrNoConnectRequest
}
params := ValidateConnectRequestParams{
metadata: connectRequest.Metadata,
attributes: connectRequest.ParticipantAttributes,
}
res, code, err := ValidateConnectRequest(
lgr,
r,
s.limits,
params,
s.router,
s.roomAllocator,
)
if err != nil {
return "", "", nil, code, err
}
grantsJson, err := json.Marshal(res.grants)
if err != nil {
return "", "", nil, http.StatusInternalServerError, err
}
AugmentClientInfo(connectRequest.ClientInfo, r)
return res.roomName,
livekit.ParticipantIdentity(res.grants.Identity),
&rpc.RelaySignalv2ConnectRequest{
GrantsJson: string(grantsJson),
CreateRoom: res.createRoomRequest,
WireMessage: wireMessage,
},
code,
err
}
func (s *RTCv2Service) handlePost(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") != "application/x-protobuf" {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
return
}
wireMessage, err := getWireMessage(r)
if err != nil {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("could not get wire message: %w", err))
return
}
// only connect requests should be coming in here and there should not be fragments
roomName, participantIdentity, rscr, code, err := s.validateInternal(
utils.GetLogger(r.Context()),
r,
wireMessage,
)
if err != nil {
HandleErrorJson(w, r, code, err)
return
}
if err := s.roomAllocator.SelectRoomNode(r.Context(), roomName, ""); err != nil {
HandleErrorJson(w, r, http.StatusInternalServerError, err)
return
}
resp, err := s.router.HandleParticipantConnectRequest(r.Context(), roomName, participantIdentity, rscr)
if err != nil {
HandleErrorJson(w, r, http.StatusInternalServerError, err)
return
}
connectResponse := signalling.GetConnectResponse(resp.WireMessage)
if connectResponse == nil {
HandleErrorJson(w, r, http.StatusInternalServerError, ErrNoConnectResponse)
return
}
marshalled, err := proto.Marshal(resp.WireMessage)
if err != nil {
HandleErrorJson(w, r, http.StatusInternalServerError, err)
return
}
w.Header().Add("Content-type", "application/x-protobuf")
w.Write(marshalled)
logger.Debugw(
"connect response",
"room", roomName,
"roomID", connectResponse.Room.Sid, // SIGNALLING-V2-TODO: roomID may not be resolved
"participant", participantIdentity,
"pID", connectResponse.Participant.Sid,
"wireMessage", logger.Proto(resp.WireMessage),
)
w.WriteHeader(http.StatusOK)
}
func (s *RTCv2Service) validate(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") != "application/x-protobuf" {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
return
}
wireMessage, err := getWireMessage(r)
if err != nil {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("could not get wire message: %w", err))
return
}
_, _, _, code, err := s.validateInternal(utils.GetLogger(r.Context()), r, wireMessage)
if err != nil {
HandleErrorJson(w, r, code, err)
return
}
_, _ = w.Write([]byte("success"))
w.WriteHeader(http.StatusOK)
}
func (s *RTCv2Service) handleParticipantPatch(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") != "application/x-protobuf" {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
return
}
roomName, participantIdentity, pID, code, err := getParams(r)
if err != nil {
HandleErrorJson(w, r, code, err)
return
}
wireMessage, err := getWireMessage(r)
if err != nil {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("could not get wire message: %w", err))
return
}
logger.Debugw(
"participant request",
"room", roomName,
"participant", participantIdentity,
"pID", pID,
"participantRequest", logger.Proto(wireMessage),
)
res, err := s.signalv2ParticipantClient.RelaySignalv2Participant(
r.Context(),
s.topicFormatter.ParticipantTopic(r.Context(), roomName, participantIdentity),
&rpc.RelaySignalv2ParticipantRequest{
Room: string(roomName),
ParticipantIdentity: string(participantIdentity),
ParticipantId: string(pID),
WireMessage: wireMessage,
},
)
if err != nil {
var pe psrpc.Error
if errors.As(err, &pe) {
switch pe.Code() {
case psrpc.NotFound:
HandleErrorJson(w, r, http.StatusNotFound, errors.New(pe.Error()))
case psrpc.InvalidArgument:
HandleErrorJson(w, r, http.StatusBadRequest, errors.New(pe.Error()))
default:
HandleErrorJson(w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
} else {
HandleErrorJson(w, r, http.StatusInternalServerError, nil)
}
return
}
logger.Debugw(
"participant response",
"room", roomName,
"participant", participantIdentity,
"pID", pID,
"participantResponse", logger.Proto(res.WireMessage),
)
marshalled, err := proto.Marshal(res.WireMessage)
if err != nil {
HandleErrorJson(w, r, http.StatusInternalServerError, err)
return
}
w.Header().Add("Content-type", "application/x-protobuf")
w.Write(marshalled)
w.WriteHeader(http.StatusOK)
}
func (s *RTCv2Service) handleParticipantDelete(w http.ResponseWriter, r *http.Request) {
claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil {
HandleErrorJson(w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
return
}
roomName, participantIdentity, pID, code, err := getParams(r)
if err != nil {
HandleErrorJson(w, r, code, err)
return
}
_, err = s.signalv2ParticipantClient.RelaySignalv2ParticipantDeleteSession(
r.Context(),
s.topicFormatter.ParticipantTopic(r.Context(), roomName, participantIdentity),
&rpc.RelaySignalv2ParticipantDeleteSessionRequest{
Room: string(roomName),
ParticipantIdentity: string(participantIdentity),
ParticipantId: string(pID),
},
)
if err != nil {
HandleErrorJson(w, r, http.StatusBadRequest, err)
return
}
logger.Debugw(
"participant deleted",
"room", roomName,
"participant", participantIdentity,
"pID", pID,
)
w.WriteHeader(http.StatusOK)
}
// ---------------------------------------
func getWireMessage(r *http.Request) (*livekit.Signalv2WireMessage, error) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
wireMessage := &livekit.Signalv2WireMessage{}
err = proto.Unmarshal(body, wireMessage)
if err != nil {
return nil, err
}
return wireMessage, nil
}
func getParams(r *http.Request) (livekit.RoomName, livekit.ParticipantIdentity, livekit.ParticipantID, int, error) {
claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil {
return "", "", "", http.StatusUnauthorized, rtc.ErrPermissionDenied
}
roomName, err := EnsureJoinPermission(r.Context())
if err != nil {
return "", "", "", http.StatusUnauthorized, err
}
if roomName == "" {
return "", "", "", http.StatusUnauthorized, ErrNoRoomName
}
participantIdentity := livekit.ParticipantIdentity(claims.Identity)
if participantIdentity == "" {
return "", "", "", http.StatusUnauthorized, ErrIdentityEmpty
}
pID := livekit.ParticipantID(r.PathValue("participant_id"))
if pID == "" {
return "", "", "", http.StatusBadRequest, ErrParticipantSidEmpty
}
return roomName, participantIdentity, pID, http.StatusOK, nil
}
+23 -34
View File
@@ -46,23 +46,21 @@ import (
)
type LivekitServer struct {
config *config.Config
ioService *IOInfoService
rtcService *RTCService
rtcv2Service *RTCv2Service
whipService *WHIPService
agentService *AgentService
httpServer *http.Server
promServer *http.Server
router routing.Router
roomManager *RoomManager
signalServer *SignalServer
signalv2Server *Signalv2Server
turnServer *turn.Server
currentNode routing.LocalNode
running atomic.Bool
doneChan chan struct{}
closedChan chan struct{}
config *config.Config
ioService *IOInfoService
rtcService *RTCService
whipService *WHIPService
agentService *AgentService
httpServer *http.Server
promServer *http.Server
router routing.Router
roomManager *RoomManager
signalServer *SignalServer
turnServer *turn.Server
currentNode routing.LocalNode
running atomic.Bool
doneChan chan struct{}
closedChan chan struct{}
}
func NewLivekitServer(conf *config.Config,
@@ -73,28 +71,24 @@ func NewLivekitServer(conf *config.Config,
sipService *SIPService,
ioService *IOInfoService,
rtcService *RTCService,
rtcv2Service *RTCv2Service,
whipService *WHIPService,
agentService *AgentService,
keyProvider auth.KeyProvider,
router routing.Router,
roomManager *RoomManager,
signalServer *SignalServer,
signalv2Server *Signalv2Server,
turnServer *turn.Server,
currentNode routing.LocalNode,
) (s *LivekitServer, err error) {
s = &LivekitServer{
config: conf,
ioService: ioService,
rtcService: rtcService,
rtcv2Service: rtcv2Service,
whipService: whipService,
agentService: agentService,
router: router,
roomManager: roomManager,
signalServer: signalServer,
signalv2Server: signalv2Server,
config: conf,
ioService: ioService,
rtcService: rtcService,
whipService: whipService,
agentService: agentService,
router: router,
roomManager: roomManager,
signalServer: signalServer,
// turn server starts automatically
turnServer: turnServer,
currentNode: currentNode,
@@ -150,7 +144,6 @@ func NewLivekitServer(conf *config.Config,
xtwirp.RegisterServer(mux, ingressServer)
xtwirp.RegisterServer(mux, sipServer)
rtcService.SetupRoutes(mux)
rtcv2Service.SetupRoutes(mux)
whipService.SetupRoutes(mux)
mux.Handle("/agent", agentService)
mux.HandleFunc("/", s.defaultHandler)
@@ -281,10 +274,6 @@ func (s *LivekitServer) Start() error {
return err
}
if err := s.signalv2Server.Start(); err != nil {
return err
}
httpGroup := &errgroup.Group{}
for _, ln := range listeners {
l := ln
@@ -1,200 +0,0 @@
// Code generated by counterfeiter. DO NOT EDIT.
package servicefakes
import (
"context"
"sync"
"github.com/livekit/livekit-server/pkg/service"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/rpc"
)
type FakeConnectHandler struct {
HandleConnectStub func(context.Context, logger.Logger, *auth.ClaimGrants, *rpc.RelaySignalv2ConnectRequest) (*rpc.RelaySignalv2ConnectResponse, error)
handleConnectMutex sync.RWMutex
handleConnectArgsForCall []struct {
arg1 context.Context
arg2 logger.Logger
arg3 *auth.ClaimGrants
arg4 *rpc.RelaySignalv2ConnectRequest
}
handleConnectReturns struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
}
handleConnectReturnsOnCall map[int]struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
}
LoggerStub func(context.Context) logger.Logger
loggerMutex sync.RWMutex
loggerArgsForCall []struct {
arg1 context.Context
}
loggerReturns struct {
result1 logger.Logger
}
loggerReturnsOnCall map[int]struct {
result1 logger.Logger
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeConnectHandler) HandleConnect(arg1 context.Context, arg2 logger.Logger, arg3 *auth.ClaimGrants, arg4 *rpc.RelaySignalv2ConnectRequest) (*rpc.RelaySignalv2ConnectResponse, error) {
fake.handleConnectMutex.Lock()
ret, specificReturn := fake.handleConnectReturnsOnCall[len(fake.handleConnectArgsForCall)]
fake.handleConnectArgsForCall = append(fake.handleConnectArgsForCall, struct {
arg1 context.Context
arg2 logger.Logger
arg3 *auth.ClaimGrants
arg4 *rpc.RelaySignalv2ConnectRequest
}{arg1, arg2, arg3, arg4})
stub := fake.HandleConnectStub
fakeReturns := fake.handleConnectReturns
fake.recordInvocation("HandleConnect", []interface{}{arg1, arg2, arg3, arg4})
fake.handleConnectMutex.Unlock()
if stub != nil {
return stub(arg1, arg2, arg3, arg4)
}
if specificReturn {
return ret.result1, ret.result2
}
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeConnectHandler) HandleConnectCallCount() int {
fake.handleConnectMutex.RLock()
defer fake.handleConnectMutex.RUnlock()
return len(fake.handleConnectArgsForCall)
}
func (fake *FakeConnectHandler) HandleConnectCalls(stub func(context.Context, logger.Logger, *auth.ClaimGrants, *rpc.RelaySignalv2ConnectRequest) (*rpc.RelaySignalv2ConnectResponse, error)) {
fake.handleConnectMutex.Lock()
defer fake.handleConnectMutex.Unlock()
fake.HandleConnectStub = stub
}
func (fake *FakeConnectHandler) HandleConnectArgsForCall(i int) (context.Context, logger.Logger, *auth.ClaimGrants, *rpc.RelaySignalv2ConnectRequest) {
fake.handleConnectMutex.RLock()
defer fake.handleConnectMutex.RUnlock()
argsForCall := fake.handleConnectArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4
}
func (fake *FakeConnectHandler) HandleConnectReturns(result1 *rpc.RelaySignalv2ConnectResponse, result2 error) {
fake.handleConnectMutex.Lock()
defer fake.handleConnectMutex.Unlock()
fake.HandleConnectStub = nil
fake.handleConnectReturns = struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
}{result1, result2}
}
func (fake *FakeConnectHandler) HandleConnectReturnsOnCall(i int, result1 *rpc.RelaySignalv2ConnectResponse, result2 error) {
fake.handleConnectMutex.Lock()
defer fake.handleConnectMutex.Unlock()
fake.HandleConnectStub = nil
if fake.handleConnectReturnsOnCall == nil {
fake.handleConnectReturnsOnCall = make(map[int]struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
})
}
fake.handleConnectReturnsOnCall[i] = struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
}{result1, result2}
}
func (fake *FakeConnectHandler) Logger(arg1 context.Context) logger.Logger {
fake.loggerMutex.Lock()
ret, specificReturn := fake.loggerReturnsOnCall[len(fake.loggerArgsForCall)]
fake.loggerArgsForCall = append(fake.loggerArgsForCall, struct {
arg1 context.Context
}{arg1})
stub := fake.LoggerStub
fakeReturns := fake.loggerReturns
fake.recordInvocation("Logger", []interface{}{arg1})
fake.loggerMutex.Unlock()
if stub != nil {
return stub(arg1)
}
if specificReturn {
return ret.result1
}
return fakeReturns.result1
}
func (fake *FakeConnectHandler) LoggerCallCount() int {
fake.loggerMutex.RLock()
defer fake.loggerMutex.RUnlock()
return len(fake.loggerArgsForCall)
}
func (fake *FakeConnectHandler) LoggerCalls(stub func(context.Context) logger.Logger) {
fake.loggerMutex.Lock()
defer fake.loggerMutex.Unlock()
fake.LoggerStub = stub
}
func (fake *FakeConnectHandler) LoggerArgsForCall(i int) context.Context {
fake.loggerMutex.RLock()
defer fake.loggerMutex.RUnlock()
argsForCall := fake.loggerArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeConnectHandler) LoggerReturns(result1 logger.Logger) {
fake.loggerMutex.Lock()
defer fake.loggerMutex.Unlock()
fake.LoggerStub = nil
fake.loggerReturns = struct {
result1 logger.Logger
}{result1}
}
func (fake *FakeConnectHandler) LoggerReturnsOnCall(i int, result1 logger.Logger) {
fake.loggerMutex.Lock()
defer fake.loggerMutex.Unlock()
fake.LoggerStub = nil
if fake.loggerReturnsOnCall == nil {
fake.loggerReturnsOnCall = make(map[int]struct {
result1 logger.Logger
})
}
fake.loggerReturnsOnCall[i] = struct {
result1 logger.Logger
}{result1}
}
func (fake *FakeConnectHandler) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.handleConnectMutex.RLock()
defer fake.handleConnectMutex.RUnlock()
fake.loggerMutex.RLock()
defer fake.loggerMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeConnectHandler) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ service.ConnectHandler = new(FakeConnectHandler)
-162
View File
@@ -1,162 +0,0 @@
// 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 service
import (
"context"
"encoding/json"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/rpc"
"github.com/livekit/psrpc"
"github.com/livekit/psrpc/pkg/middleware"
)
//counterfeiter:generate . ConnectHandler
type ConnectHandler interface {
Logger(ctx context.Context) logger.Logger
HandleConnect(
ctx context.Context,
lgr logger.Logger,
grants *auth.ClaimGrants,
rscr *rpc.RelaySignalv2ConnectRequest,
) (*rpc.RelaySignalv2ConnectResponse, error)
}
type Signalv2Server struct {
server rpc.TypedSignalv2Server
nodeID livekit.NodeID
}
func NewSignalv2Server(
nodeID livekit.NodeID,
region string,
bus psrpc.MessageBus,
connectHandler ConnectHandler,
) (*Signalv2Server, error) {
s, err := rpc.NewTypedSignalv2Server(
nodeID,
&signalv2Service{region, connectHandler},
bus,
middleware.WithServerMetrics(rpc.PSRPCMetricsObserver{}),
)
if err != nil {
return nil, err
}
return &Signalv2Server{s, nodeID}, nil
}
func (s *Signalv2Server) Start() error {
logger.Debugw("starting relay signal v2 server", "topic", s.nodeID)
return s.server.RegisterAllNodeTopics(s.nodeID)
}
func (r *Signalv2Server) Stop() {
r.server.Kill()
}
// -------------------------------------------------
func NewDefaultSignalv2Server(
currentNode routing.LocalNode,
bus psrpc.MessageBus,
router routing.Router,
roomManager *RoomManager,
) (*Signalv2Server, error) {
return NewSignalv2Server(
currentNode.NodeID(),
currentNode.Region(),
bus,
&defaultSignalv2Handler{currentNode, router, roomManager},
)
}
// -------------------------------------------------
type defaultSignalv2Handler struct {
currentNode routing.LocalNode
router routing.Router
roomManager *RoomManager
}
func (s *defaultSignalv2Handler) Logger(ctx context.Context) logger.Logger {
return utils.GetLogger(ctx)
}
func (s *defaultSignalv2Handler) HandleConnect(
ctx context.Context,
lgr logger.Logger,
grants *auth.ClaimGrants,
rscr *rpc.RelaySignalv2ConnectRequest,
) (*rpc.RelaySignalv2ConnectResponse, error) {
prometheus.IncrementParticipantRtcInit(1)
rtcNode, err := s.router.GetNodeForRoom(ctx, livekit.RoomName(rscr.CreateRoom.Name))
if err != nil {
return nil, err
}
if livekit.NodeID(rtcNode.Id) != s.currentNode.NodeID() {
err = routing.ErrIncorrectRTCNode
lgr.Errorw(
"called participant on incorrect node", err,
"rtcNode", rtcNode,
)
return nil, err
}
wireMessageResponse, err := s.roomManager.HandleConnect(ctx, grants, rscr.CreateRoom, rscr.WireMessage)
if err != nil {
return nil, err
}
return &rpc.RelaySignalv2ConnectResponse{
WireMessage: wireMessageResponse,
}, nil
}
// ------------------------------------------
type signalv2Service struct {
region string
connectHandler ConnectHandler
}
func (r *signalv2Service) RelaySignalv2Connect(ctx context.Context, rscr *rpc.RelaySignalv2ConnectRequest) (*rpc.RelaySignalv2ConnectResponse, error) {
grants := &auth.ClaimGrants{}
if err := json.Unmarshal([]byte(rscr.GrantsJson), grants); err != nil {
return nil, err
}
lgr := r.connectHandler.Logger(ctx).WithValues(
"room", grants.Video.Room,
"participant", grants.Identity,
// SIGNALLING-V2-TODO - maybe add a connection ID to rscr for tracking/debugging only
)
resp, err := r.connectHandler.HandleConnect(ctx, lgr, grants, rscr)
if err != nil {
lgr.Errorw("could not handle new participant", err)
}
return resp, err
}
// ------------------------------------------
-3
View File
@@ -77,7 +77,6 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
NewRoomAllocator,
NewRoomService,
NewRTCService,
NewRTCv2Service,
NewWHIPService,
NewAgentService,
NewAgentDispatchService,
@@ -85,7 +84,6 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
getAgentStore,
getSignalRelayConfig,
NewDefaultSignalServer,
NewDefaultSignalv2Server,
routing.NewSignalClient,
getRoomConfig,
routing.NewRoomManagerClient,
@@ -95,7 +93,6 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
rpc.NewTopicFormatter,
rpc.NewTypedRoomClient,
rpc.NewTypedParticipantClient,
rpc.NewTypedSignalv2ParticipantClient,
rpc.NewTypedWHIPParticipantClient,
rpc.NewTypedAgentDispatchInternalClient,
NewLocalRoomManager,
+8 -17
View File
@@ -89,23 +89,23 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
}
rtcEgressLauncher := NewEgressLauncher(egressClient, ioInfoService, objectStore)
topicFormatter := rpc.NewTopicFormatter()
roomClient, err := rpc.NewTypedRoomClient(clientParams)
v, err := rpc.NewTypedRoomClient(clientParams)
if err != nil {
return nil, err
}
participantClient, err := rpc.NewTypedParticipantClient(clientParams)
v2, err := rpc.NewTypedParticipantClient(clientParams)
if err != nil {
return nil, err
}
roomService, err := NewRoomService(limitConfig, apiConfig, router, roomAllocator, objectStore, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
roomService, err := NewRoomService(limitConfig, apiConfig, router, roomAllocator, objectStore, rtcEgressLauncher, topicFormatter, v, v2)
if err != nil {
return nil, err
}
agentDispatchInternalClient, err := rpc.NewTypedAgentDispatchInternalClient(clientParams)
v3, err := rpc.NewTypedAgentDispatchInternalClient(clientParams)
if err != nil {
return nil, err
}
agentDispatchService := NewAgentDispatchService(agentDispatchInternalClient, topicFormatter, roomAllocator, router)
agentDispatchService := NewAgentDispatchService(v3, topicFormatter, roomAllocator, router)
egressService := NewEgressService(egressClient, rtcEgressLauncher, ioInfoService, roomService)
ingressConfig := getIngressConfig(conf)
ingressClient, err := rpc.NewIngressClient(clientParams)
@@ -120,16 +120,11 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
}
sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService)
rtcService := NewRTCService(conf, roomAllocator, router, telemetryService)
signalv2ParticipantClient, err := rpc.NewTypedSignalv2ParticipantClient(clientParams)
v4, err := rpc.NewTypedWHIPParticipantClient(clientParams)
if err != nil {
return nil, err
}
rtCv2Service := NewRTCv2Service(conf, roomAllocator, router, topicFormatter, signalv2ParticipantClient)
whipParticipantClient, err := rpc.NewTypedWHIPParticipantClient(clientParams)
if err != nil {
return nil, err
}
serviceWHIPService, err := NewWHIPService(conf, router, roomAllocator, clientParams, topicFormatter, whipParticipantClient)
serviceWHIPService, err := NewWHIPService(conf, router, roomAllocator, clientParams, topicFormatter, v4)
if err != nil {
return nil, err
}
@@ -153,16 +148,12 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
if err != nil {
return nil, err
}
signalv2Server, err := NewDefaultSignalv2Server(currentNode, messageBus, router, roomManager)
if err != nil {
return nil, err
}
authHandler := getTURNAuthHandlerFunc(turnAuthHandler)
server, err := newInProcessTurnServer(conf, authHandler)
if err != nil {
return nil, err
}
livekitServer, err := NewLivekitServer(conf, roomService, agentDispatchService, egressService, ingressService, sipService, ioInfoService, rtcService, rtCv2Service, serviceWHIPService, agentService, keyProvider, router, roomManager, signalServer, signalv2Server, server, currentNode)
livekitServer, err := NewLivekitServer(conf, roomService, agentDispatchService, egressService, ingressService, sipService, ioInfoService, rtcService, serviceWHIPService, agentService, keyProvider, router, roomManager, signalServer, server, currentNode)
if err != nil {
return nil, err
}