Flush pending signal responses before closing the web socket. (#4776)

* Flush pending signal responses before closing the web socket.

When the request direction of a signalling connection goes away, the
web socket was closed right away. Responses that the participant had
already sent were dropped.

This loses the leave request on migration. The media node writes
leave(RESUME) and closes the signalling connection just after. The
close won the race, so the client saw a plain web socket close with
code 1000 and never got the leave. It then did a full reconnect
instead of a resume.

Now the response pump is signalled first and drains what is pending,
then the web socket is closed. The producer closes the response
source after its last write, so draining till the source is closed is
a complete flush. A deadline bounds the case where the source stays
open.

The web socket is still closed on all paths, so the ping worker does
not leak.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Give the response pump a margin over the drain deadline.

Both waits used the same timeout and started at about the same time.
So when the drain ran to its deadline, the outer wait could give up at
the same moment and close the web socket while the pump was still
writing. That write failed and the message was lost. It also logged a
timeout even though nothing was stuck.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Raja Subramanian
2026-08-20 01:13:50 +05:30
committed by GitHub
co-authored by Claude Opus 5
parent 0ef7ee440c
commit c52b1b2a30
2 changed files with 251 additions and 62 deletions
+142 -62
View File
@@ -44,6 +44,17 @@ import (
"github.com/livekit/livekit-server/pkg/utils"
)
const (
// how long the response source is drained after the request direction is gone,
// applies only when the source is not closed by the relay, i. e. when there is
// no way to tell that everything pending has been read
responseFlushTimeout = 250 * time.Millisecond
// how long the response pump is given to stop, a bit more than the drain deadline
// so that it can finish the write it is in when that deadline expires
responsePumpDoneTimeout = 2 * responseFlushTimeout
)
type RTCService struct {
router routing.MessageRouter
roomAllocator RoomAllocator
@@ -428,13 +439,34 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
closedByClient := atomic.NewBool(false)
done := make(chan struct{})
// closed by the response pump when it has stopped writing to the web socket
responsePumpDone := make(chan struct{})
responsePumpStarted := false
var sigConn *WSSignalConnection
// function exits when websocket terminates, it'll close the event reading off of request sink and response source as well
defer func() {
resolveLogger(true)
pLogger.Debugw("finishing WS connection", "closedByClient", closedByClient.Load())
cr.ResponseSource.Close()
cr.RequestSink.Close()
// signal the response pump before anything else so that it can flush responses
// the participant queued on its way out, a leave request sent just before the
// signalling connection was closed (on migration for example) is dropped otherwise
close(done)
cr.RequestSink.Close()
if responsePumpStarted {
select {
case <-responsePumpDone:
case <-time.After(responsePumpDoneTimeout):
pLogger.Debugw("timed out waiting for response pump to finish")
}
}
cr.ResponseSource.Close()
// close the web socket on all paths, even when the response pump is wedged
// writing to an unresponsive client
if sigConn != nil {
sigConn.CloseWithReason("")
}
signalStats.Stop()
}()
@@ -466,8 +498,7 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
}()
// websocket established
sigConn := NewWSSignalConnection(conn, s.limits.SignalMessageSizeLimit)
defer sigConn.CloseWithReason("")
sigConn = NewWSSignalConnection(conn, s.limits.SignalMessageSizeLimit)
pLogger.Debugw("sending initial response", "response", logger.Proto(initialResponse))
count, err := sigConn.WriteResponse(initialResponse)
if err != nil {
@@ -491,9 +522,79 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
"nodeSelectionReason", cr.NodeSelectionReason,
)
// writes one response from the response source to the web socket,
// returns false if the response pump should stop
writeResponse := func(msg proto.Message) bool {
res, ok := msg.(*livekit.SignalResponse)
if !ok {
pLogger.Errorw(
"unexpected message type", nil,
"type", fmt.Sprintf("%T", msg),
)
return true
}
switch m := res.Message.(type) {
case *livekit.SignalResponse_Offer:
pLogger.Debugw("sending offer", "offer", logger.Proto(res))
case *livekit.SignalResponse_Answer:
pLogger.Debugw("sending answer", "answer", logger.Proto(res))
case *livekit.SignalResponse_Join:
pLogger.Debugw("sending join", "join", logger.Proto(res))
signalStats.ResolveRoom(m.Join.GetRoom())
signalStats.ResolveParticipant(m.Join.GetParticipant())
case *livekit.SignalResponse_RoomUpdate:
updateRoomID := livekit.RoomID(m.RoomUpdate.GetRoom().GetSid())
if updateRoomID != "" {
roomID = updateRoomID
resolveLogger(false)
}
pLogger.Debugw("sending room update", "roomUpdate", logger.Proto(res))
signalStats.ResolveRoom(m.RoomUpdate.GetRoom())
case *livekit.SignalResponse_Update:
pLogger.Debugw("sending participant update", "participantUpdate", logger.Proto(res))
case *livekit.SignalResponse_RoomMoved:
resetLogger()
signalStats.Reset()
roomName = livekit.RoomName(m.RoomMoved.GetRoom().GetName())
moveRoomID := livekit.RoomID(m.RoomMoved.GetRoom().GetSid())
if moveRoomID != "" {
roomID = moveRoomID
}
participantIdentity = livekit.ParticipantIdentity(m.RoomMoved.GetParticipant().GetIdentity())
pID = livekit.ParticipantID(m.RoomMoved.GetParticipant().GetSid())
resolveLogger(false)
signalStats.ResolveRoom(m.RoomMoved.GetRoom())
signalStats.ResolveParticipant(m.RoomMoved.GetParticipant())
pLogger.Debugw("sending room moved", "roomMoved", logger.Proto(res))
default:
pLogger.Debugw("sending signal response", "response", logger.Proto(res))
}
if count, err := sigConn.WriteResponse(res); err != nil {
pLogger.Warnw("error writing to websocket", err)
return false
} else {
signalStats.AddBytes(uint64(count), true)
}
return true
}
// handle responses
responsePumpStarted = true
go func() {
defer func() {
close(responsePumpDone)
// when the source is terminated, this means Participant.Close had been called and RTC connection is done
// we would terminate the signal connection as well
sigConn.CloseWithReason("")
@@ -506,72 +607,23 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
for {
select {
case <-done:
// the request direction is gone, flush what the participant queued on its
// way out unless the client is the one that went away
if !closedByClient.Load() {
if !drainMessageSource(cr.ResponseSource, responseFlushTimeout, writeResponse) {
pLogger.Debugw("could not drain response source fully")
}
}
return
case msg := <-cr.ResponseSource.ReadChan():
if msg == nil {
resolveLogger(true)
pLogger.Debugw("nothing to read from response source")
return
}
res, ok := msg.(*livekit.SignalResponse)
if !ok {
pLogger.Errorw(
"unexpected message type", nil,
"type", fmt.Sprintf("%T", msg),
)
continue
}
switch m := res.Message.(type) {
case *livekit.SignalResponse_Offer:
pLogger.Debugw("sending offer", "offer", logger.Proto(res))
case *livekit.SignalResponse_Answer:
pLogger.Debugw("sending answer", "answer", logger.Proto(res))
case *livekit.SignalResponse_Join:
pLogger.Debugw("sending join", "join", logger.Proto(res))
signalStats.ResolveRoom(m.Join.GetRoom())
signalStats.ResolveParticipant(m.Join.GetParticipant())
case *livekit.SignalResponse_RoomUpdate:
updateRoomID := livekit.RoomID(m.RoomUpdate.GetRoom().GetSid())
if updateRoomID != "" {
roomID = updateRoomID
resolveLogger(false)
}
pLogger.Debugw("sending room update", "roomUpdate", logger.Proto(res))
signalStats.ResolveRoom(m.RoomUpdate.GetRoom())
case *livekit.SignalResponse_Update:
pLogger.Debugw("sending participant update", "participantUpdate", logger.Proto(res))
case *livekit.SignalResponse_RoomMoved:
resetLogger()
signalStats.Reset()
roomName = livekit.RoomName(m.RoomMoved.GetRoom().GetName())
moveRoomID := livekit.RoomID(m.RoomMoved.GetRoom().GetSid())
if moveRoomID != "" {
roomID = moveRoomID
}
participantIdentity = livekit.ParticipantIdentity(m.RoomMoved.GetParticipant().GetIdentity())
pID = livekit.ParticipantID(m.RoomMoved.GetParticipant().GetSid())
resolveLogger(false)
signalStats.ResolveRoom(m.RoomMoved.GetRoom())
signalStats.ResolveParticipant(m.RoomMoved.GetParticipant())
pLogger.Debugw("sending room moved", "roomMoved", logger.Proto(res))
default:
pLogger.Debugw("sending signal response", "response", logger.Proto(res))
}
if count, err := sigConn.WriteResponse(res); err != nil {
pLogger.Warnw("error writing to websocket", err)
if !writeResponse(msg) {
return
} else {
signalStats.AddBytes(uint64(count), true)
}
}
}
@@ -634,6 +686,34 @@ func (s *RTCService) serve(w http.ResponseWriter, r *http.Request, needsJoinRequ
}
}
// drainMessageSource writes messages that are still queued in source using write.
// It is used when tearing a signalling connection down, responses the participant queued
// on its way out, a leave request on migration for example, would be dropped otherwise.
//
// The producer writes all pending messages into the source before closing it, so draining
// till the source is closed is a complete flush. The deadline is a backstop for the cases
// where the source is not closed, i. e. when there is no way to tell that everything
// pending has been read. Returns true if the source was drained fully.
func drainMessageSource(source routing.MessageSource, timeout time.Duration, write func(proto.Message) bool) bool {
deadline := time.NewTimer(timeout)
defer deadline.Stop()
for {
select {
case msg := <-source.ReadChan():
if msg == nil {
return true
}
if !write(msg) {
return false
}
case <-deadline.C:
return false
}
}
}
func (s *RTCService) DrainConnections(interval time.Duration, force bool) {
s.mu.Lock()
conns := maps.Clone(s.connections)
+109
View File
@@ -0,0 +1,109 @@
// Copyright 2026 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 (
"testing"
"time"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"github.com/livekit/protocol/livekit"
"github.com/livekit/livekit-server/pkg/routing"
)
func leaveResponse(action livekit.LeaveRequest_Action) *livekit.SignalResponse {
return &livekit.SignalResponse{
Message: &livekit.SignalResponse_Leave{
Leave: &livekit.LeaveRequest{
Action: action,
Reason: livekit.DisconnectReason_MIGRATION,
},
},
}
}
func TestDrainMessageSource(t *testing.T) {
collect := func(msgs *[]proto.Message) func(proto.Message) bool {
return func(msg proto.Message) bool {
*msgs = append(*msgs, msg)
return true
}
}
t.Run("drains queued messages of a closed source", func(t *testing.T) {
source := routing.NewDefaultMessageChannel("CO_test")
require.NoError(t, source.WriteMessage(leaveResponse(livekit.LeaveRequest_RESUME)))
require.NoError(t, source.WriteMessage(leaveResponse(livekit.LeaveRequest_RECONNECT)))
source.Close()
var got []proto.Message
require.True(t, drainMessageSource(source, time.Second, collect(&got)))
require.Len(t, got, 2)
require.Equal(
t,
livekit.LeaveRequest_RESUME,
got[0].(*livekit.SignalResponse).GetLeave().GetAction(),
)
require.Equal(
t,
livekit.LeaveRequest_RECONNECT,
got[1].(*livekit.SignalResponse).GetLeave().GetAction(),
)
})
t.Run("drains messages written while draining", func(t *testing.T) {
source := routing.NewDefaultMessageChannel("CO_test")
// mimics the relay pushing a message that was still in flight when the
// request direction went away, and closing the source right after
go func() {
time.Sleep(20 * time.Millisecond)
_ = source.WriteMessage(leaveResponse(livekit.LeaveRequest_RESUME))
source.Close()
}()
var got []proto.Message
require.True(t, drainMessageSource(source, time.Second, collect(&got)))
require.Len(t, got, 1)
})
t.Run("gives up on the deadline when the source stays open", func(t *testing.T) {
source := routing.NewDefaultMessageChannel("CO_test")
require.NoError(t, source.WriteMessage(leaveResponse(livekit.LeaveRequest_RESUME)))
var got []proto.Message
start := time.Now()
require.False(t, drainMessageSource(source, 50*time.Millisecond, collect(&got)))
require.GreaterOrEqual(t, time.Since(start), 50*time.Millisecond)
// what was queued is still flushed
require.Len(t, got, 1)
})
t.Run("stops when the write fails", func(t *testing.T) {
source := routing.NewDefaultMessageChannel("CO_test")
require.NoError(t, source.WriteMessage(leaveResponse(livekit.LeaveRequest_RESUME)))
require.NoError(t, source.WriteMessage(leaveResponse(livekit.LeaveRequest_RECONNECT)))
source.Close()
var got []proto.Message
require.False(t, drainMessageSource(source, time.Second, func(msg proto.Message) bool {
got = append(got, msg)
return false
}))
require.Len(t, got, 1)
})
}