feat: server rpc apis (#3904)
* feat: server rpc apis * fix: cleanup * fix: move rpc impl to participant * cleanup * cleanup, psrpc errors * remove TODO comment * update protocol, handle participant disconnect case * add ephemeral participant identity to rpc data packet * fix: panic * chore(deps): bump proto
This commit is contained in:
+153
-1
@@ -25,6 +25,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/frostbyte73/core"
|
||||
"github.com/google/uuid"
|
||||
lru "github.com/hashicorp/golang-lru/v2"
|
||||
"github.com/pion/rtcp"
|
||||
"github.com/pion/sdp/v3"
|
||||
@@ -46,6 +47,7 @@ import (
|
||||
"github.com/livekit/protocol/utils"
|
||||
"github.com/livekit/protocol/utils/guid"
|
||||
"github.com/livekit/protocol/utils/pointer"
|
||||
"github.com/livekit/psrpc"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/metric"
|
||||
@@ -328,6 +330,10 @@ type ParticipantImpl struct {
|
||||
// loggers for publisher and subscriber
|
||||
pubLogger logger.Logger
|
||||
subLogger logger.Logger
|
||||
|
||||
rpcLock sync.Mutex
|
||||
rpcPendingAcks map[string]*utils.DataChannelRpcPendingAckHandler
|
||||
rpcPendingResponses map[string]*utils.DataChannelRpcPendingResponseHandler
|
||||
}
|
||||
|
||||
func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
|
||||
@@ -360,7 +366,9 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
|
||||
joiningMessageFirstSeqs: make(map[livekit.ParticipantID]uint32),
|
||||
joiningMessageLastWrittenSeqs: make(map[livekit.ParticipantID]uint32),
|
||||
},
|
||||
onClose: make(map[string]func(types.LocalParticipant)),
|
||||
rpcPendingAcks: make(map[string]*utils.DataChannelRpcPendingAckHandler),
|
||||
rpcPendingResponses: make(map[string]*utils.DataChannelRpcPendingResponseHandler),
|
||||
onClose: make(map[string]func(types.LocalParticipant)),
|
||||
}
|
||||
p.setupSignalling()
|
||||
|
||||
@@ -1506,6 +1514,14 @@ func (p *ParticipantImpl) Close(sendLeave bool, reason types.ParticipantCloseRea
|
||||
|
||||
p.UpTrackManager.Close(isExpectedToResume)
|
||||
|
||||
p.rpcLock.Lock()
|
||||
clear(p.rpcPendingAcks)
|
||||
for _, handler := range p.rpcPendingResponses {
|
||||
handler.Resolve("", utils.DataChannelRpcErrorFromBuiltInCodes(utils.DataChannelRpcRecipientDisconnected, ""))
|
||||
}
|
||||
p.rpcPendingResponses = make(map[string]*utils.DataChannelRpcPendingResponseHandler)
|
||||
p.rpcLock.Unlock()
|
||||
|
||||
p.updateState(livekit.ParticipantInfo_DISCONNECTED)
|
||||
close(p.disconnected)
|
||||
|
||||
@@ -2492,10 +2508,24 @@ func (p *ParticipantImpl) handleReceivedDataMessage(kind livekit.DataPacket_Kind
|
||||
if payload.RpcResponse == nil {
|
||||
return
|
||||
}
|
||||
|
||||
rpcResponse := payload.RpcResponse
|
||||
switch res := rpcResponse.Value.(type) {
|
||||
case *livekit.RpcResponse_Payload:
|
||||
shouldForwardData = !p.handleIncomingRpcResponse(payload.RpcResponse.GetRequestId(), res.Payload, nil)
|
||||
case *livekit.RpcResponse_Error:
|
||||
shouldForwardData = !p.handleIncomingRpcResponse(payload.RpcResponse.GetRequestId(), "", &utils.DataChannelRpcError{
|
||||
Code: utils.DataChannelRpcErrorCode(res.Error.GetCode()),
|
||||
Message: res.Error.GetMessage(),
|
||||
Data: res.Error.GetData(),
|
||||
})
|
||||
}
|
||||
case *livekit.DataPacket_RpcAck:
|
||||
if payload.RpcAck == nil {
|
||||
return
|
||||
}
|
||||
|
||||
shouldForwardData = !p.handleIncomingRpcAck(payload.RpcAck.GetRequestId())
|
||||
case *livekit.DataPacket_StreamHeader:
|
||||
if payload.StreamHeader == nil {
|
||||
return
|
||||
@@ -4170,3 +4200,125 @@ func (p *ParticipantImpl) AddTransceiverFromTrackLocal(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ParticipantImpl) handleIncomingRpcAck(requestId string) bool {
|
||||
p.rpcLock.Lock()
|
||||
defer p.rpcLock.Unlock()
|
||||
|
||||
handler, ok := p.rpcPendingAcks[requestId]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
handler.Resolve()
|
||||
delete(p.rpcPendingAcks, requestId)
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *ParticipantImpl) handleIncomingRpcResponse(requestId string, payload string, err *utils.DataChannelRpcError) bool {
|
||||
p.rpcLock.Lock()
|
||||
defer p.rpcLock.Unlock()
|
||||
|
||||
handler, ok := p.rpcPendingResponses[requestId]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
handler.Resolve(payload, err)
|
||||
delete(p.rpcPendingResponses, requestId)
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *ParticipantImpl) PerformRpc(req *livekit.PerformRpcRequest, resultCh chan string, errorCh chan error) {
|
||||
responseTimeout := req.GetResponseTimeoutMs()
|
||||
if responseTimeout <= 0 {
|
||||
responseTimeout = uint32(utils.DataChannelRpcDefaultResponseTimeout.Milliseconds())
|
||||
}
|
||||
|
||||
go func() {
|
||||
if len([]byte(req.GetPayload())) > utils.DataChannelRpcMaxPayloadBytes {
|
||||
errorCh <- utils.DataChannelRpcErrorFromBuiltInCodes(utils.DataChannelRpcRequestPayloadTooLarge, "").PsrpcError()
|
||||
return
|
||||
}
|
||||
|
||||
id := uuid.NewString()
|
||||
|
||||
responseTimer := time.AfterFunc(time.Duration(responseTimeout)*time.Millisecond, func() {
|
||||
p.rpcLock.Lock()
|
||||
delete(p.rpcPendingResponses, id)
|
||||
p.rpcLock.Unlock()
|
||||
|
||||
select {
|
||||
case errorCh <- utils.DataChannelRpcErrorFromBuiltInCodes(utils.DataChannelRpcResponseTimeout, "").PsrpcError():
|
||||
default:
|
||||
}
|
||||
})
|
||||
ackTimer := time.AfterFunc(utils.DataChannelRpcMaxRoundTripLatency, func() {
|
||||
p.rpcLock.Lock()
|
||||
delete(p.rpcPendingAcks, id)
|
||||
delete(p.rpcPendingResponses, id)
|
||||
p.rpcLock.Unlock()
|
||||
responseTimer.Stop()
|
||||
|
||||
select {
|
||||
case errorCh <- utils.DataChannelRpcErrorFromBuiltInCodes(utils.DataChannelRpcConnectionTimeout, "").PsrpcError():
|
||||
default:
|
||||
}
|
||||
})
|
||||
|
||||
rpcRequest := &livekit.DataPacket{
|
||||
Kind: livekit.DataPacket_RELIABLE,
|
||||
ParticipantIdentity: id,
|
||||
Value: &livekit.DataPacket_RpcRequest{
|
||||
RpcRequest: &livekit.RpcRequest{
|
||||
Id: id,
|
||||
Method: req.GetMethod(),
|
||||
Payload: req.GetPayload(),
|
||||
ResponseTimeoutMs: responseTimeout - p.lastRTT,
|
||||
Version: 1,
|
||||
},
|
||||
},
|
||||
}
|
||||
data, err := proto.Marshal(rpcRequest)
|
||||
if err != nil {
|
||||
ackTimer.Stop()
|
||||
responseTimer.Stop()
|
||||
errorCh <- psrpc.NewError(psrpc.Internal, err)
|
||||
return
|
||||
}
|
||||
|
||||
// using RPC ID as the unique ID for server to identify the response
|
||||
err = p.SendDataMessage(livekit.DataPacket_RELIABLE, data, livekit.ParticipantID(id), 0)
|
||||
if err != nil {
|
||||
ackTimer.Stop()
|
||||
responseTimer.Stop()
|
||||
errorCh <- psrpc.NewError(psrpc.Internal, err)
|
||||
return
|
||||
}
|
||||
|
||||
p.rpcLock.Lock()
|
||||
p.rpcPendingAcks[id] = &utils.DataChannelRpcPendingAckHandler{
|
||||
Resolve: func() {
|
||||
ackTimer.Stop()
|
||||
},
|
||||
ParticipantIdentity: req.GetDestinationIdentity(),
|
||||
}
|
||||
p.rpcPendingResponses[id] = &utils.DataChannelRpcPendingResponseHandler{
|
||||
Resolve: func(payload string, error *utils.DataChannelRpcError) {
|
||||
responseTimer.Stop()
|
||||
if _, ok := p.rpcPendingAcks[id]; ok {
|
||||
p.rpcPendingAcks[id].Resolve()
|
||||
ackTimer.Stop()
|
||||
}
|
||||
|
||||
if error != nil {
|
||||
errorCh <- error.PsrpcError()
|
||||
} else {
|
||||
resultCh <- payload
|
||||
}
|
||||
},
|
||||
ParticipantIdentity: req.GetDestinationIdentity(),
|
||||
}
|
||||
p.rpcLock.Unlock()
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -541,6 +541,8 @@ type LocalParticipant interface {
|
||||
HandleLeaveRequest(reason ParticipantCloseReason)
|
||||
|
||||
HandleSignalMessage(msg proto.Message) error
|
||||
|
||||
PerformRpc(req *livekit.PerformRpcRequest, resultCh chan string, errorCh chan error)
|
||||
}
|
||||
|
||||
// Room is a container of participants, and can provide room-level actions
|
||||
|
||||
@@ -940,6 +940,13 @@ type FakeLocalParticipant struct {
|
||||
onUpdateSubscriptionsArgsForCall []struct {
|
||||
arg1 func(types.LocalParticipant, []livekit.TrackID, []*livekit.ParticipantTracks, bool)
|
||||
}
|
||||
PerformRpcStub func(*livekit.PerformRpcRequest, chan string, chan error)
|
||||
performRpcMutex sync.RWMutex
|
||||
performRpcArgsForCall []struct {
|
||||
arg1 *livekit.PerformRpcRequest
|
||||
arg2 chan string
|
||||
arg3 chan error
|
||||
}
|
||||
ProtocolVersionStub func() types.ProtocolVersion
|
||||
protocolVersionMutex sync.RWMutex
|
||||
protocolVersionArgsForCall []struct {
|
||||
@@ -6413,6 +6420,40 @@ func (fake *FakeLocalParticipant) OnUpdateSubscriptionsArgsForCall(i int) func(t
|
||||
return argsForCall.arg1
|
||||
}
|
||||
|
||||
func (fake *FakeLocalParticipant) PerformRpc(arg1 *livekit.PerformRpcRequest, arg2 chan string, arg3 chan error) {
|
||||
fake.performRpcMutex.Lock()
|
||||
fake.performRpcArgsForCall = append(fake.performRpcArgsForCall, struct {
|
||||
arg1 *livekit.PerformRpcRequest
|
||||
arg2 chan string
|
||||
arg3 chan error
|
||||
}{arg1, arg2, arg3})
|
||||
stub := fake.PerformRpcStub
|
||||
fake.recordInvocation("PerformRpc", []interface{}{arg1, arg2, arg3})
|
||||
fake.performRpcMutex.Unlock()
|
||||
if stub != nil {
|
||||
fake.PerformRpcStub(arg1, arg2, arg3)
|
||||
}
|
||||
}
|
||||
|
||||
func (fake *FakeLocalParticipant) PerformRpcCallCount() int {
|
||||
fake.performRpcMutex.RLock()
|
||||
defer fake.performRpcMutex.RUnlock()
|
||||
return len(fake.performRpcArgsForCall)
|
||||
}
|
||||
|
||||
func (fake *FakeLocalParticipant) PerformRpcCalls(stub func(*livekit.PerformRpcRequest, chan string, chan error)) {
|
||||
fake.performRpcMutex.Lock()
|
||||
defer fake.performRpcMutex.Unlock()
|
||||
fake.PerformRpcStub = stub
|
||||
}
|
||||
|
||||
func (fake *FakeLocalParticipant) PerformRpcArgsForCall(i int) (*livekit.PerformRpcRequest, chan string, chan error) {
|
||||
fake.performRpcMutex.RLock()
|
||||
defer fake.performRpcMutex.RUnlock()
|
||||
argsForCall := fake.performRpcArgsForCall[i]
|
||||
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
|
||||
}
|
||||
|
||||
func (fake *FakeLocalParticipant) ProtocolVersion() types.ProtocolVersion {
|
||||
fake.protocolVersionMutex.Lock()
|
||||
ret, specificReturn := fake.protocolVersionReturnsOnCall[len(fake.protocolVersionArgsForCall)]
|
||||
|
||||
@@ -48,4 +48,5 @@ var (
|
||||
ErrInvalidMessageType = psrpc.NewErrorf(psrpc.Internal, "invalid message type")
|
||||
ErrNoConnectRequest = psrpc.NewErrorf(psrpc.InvalidArgument, "no connect request")
|
||||
ErrNoConnectResponse = psrpc.NewErrorf(psrpc.InvalidArgument, "no connect response")
|
||||
ErrDestinationIdentityRequired = psrpc.NewErrorf(psrpc.InvalidArgument, "destination identity is required")
|
||||
)
|
||||
|
||||
@@ -825,6 +825,30 @@ func (r *RoomManager) MoveParticipant(ctx context.Context, req *livekit.MovePart
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (r *RoomManager) PerformRpc(ctx context.Context, req *livekit.PerformRpcRequest) (*livekit.PerformRpcResponse, error) {
|
||||
room := r.GetRoom(ctx, livekit.RoomName(req.GetRoom()))
|
||||
if room == nil {
|
||||
return nil, ErrRoomNotFound
|
||||
}
|
||||
|
||||
participant := room.GetParticipant(livekit.ParticipantIdentity(req.GetDestinationIdentity()))
|
||||
if participant == nil {
|
||||
return nil, ErrParticipantNotFound
|
||||
}
|
||||
|
||||
resultChan := make(chan string, 1)
|
||||
errorChan := make(chan error, 1)
|
||||
|
||||
participant.PerformRpc(req, resultChan, errorChan)
|
||||
|
||||
select {
|
||||
case result := <-resultChan:
|
||||
return &livekit.PerformRpcResponse{Payload: result}, nil
|
||||
case err := <-errorChan:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RoomManager) DeleteRoom(ctx context.Context, req *livekit.DeleteRoomRequest) (*livekit.DeleteRoomResponse, error) {
|
||||
room := r.GetRoom(ctx, livekit.RoomName(req.Room))
|
||||
if room == nil {
|
||||
|
||||
@@ -355,6 +355,24 @@ func (s *RoomService) MoveParticipant(ctx context.Context, req *livekit.MovePart
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (s *RoomService) PerformRpc(ctx context.Context, req *livekit.PerformRpcRequest) (*livekit.PerformRpcResponse, error) {
|
||||
RecordRequest(ctx, req)
|
||||
|
||||
roomName := livekit.RoomName(req.Room)
|
||||
AppendLogFields(ctx, "room", roomName, "participant", req.DestinationIdentity)
|
||||
|
||||
if err := EnsureAdminPermission(ctx, roomName); err != nil {
|
||||
return nil, twirpAuthError(err)
|
||||
}
|
||||
if req.DestinationIdentity == "" {
|
||||
return nil, ErrDestinationIdentityRequired
|
||||
}
|
||||
|
||||
res, err := s.participantClient.PerformRpc(ctx, s.topicFormatter.ParticipantTopic(ctx, roomName, livekit.ParticipantIdentity(req.DestinationIdentity)), req)
|
||||
RecordResponse(ctx, res)
|
||||
return res, err
|
||||
}
|
||||
|
||||
func redactCreateRoomRequest(req *livekit.CreateRoomRequest) *livekit.CreateRoomRequest {
|
||||
if req.Egress == nil && req.Metadata == "" {
|
||||
// nothing to redact
|
||||
|
||||
Reference in New Issue
Block a user