Skip to content

Commit 6ac4b71

Browse files
committed
Fix concurrent pc.GracefulClose
1 parent a49914b commit 6ac4b71

File tree

2 files changed

+155
-35
lines changed

2 files changed

+155
-35
lines changed

peerconnection.go

+72-34
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,9 @@ type PeerConnection struct {
5656
idpLoginURL *string
5757

5858
isClosed *atomicBool
59-
isGracefulClosed *atomicBool
60-
isGracefulClosedDone chan struct{}
59+
isGracefullyClosingOrClosed bool
60+
isCloseDone chan struct{}
61+
isGracefulCloseDone chan struct{}
6162
isNegotiationNeeded *atomicBool
6263
updateNegotiationNeededFlagOnEmptyChain *atomicBool
6364

@@ -130,8 +131,8 @@ func (api *API) NewPeerConnection(configuration Configuration) (*PeerConnection,
130131
ICECandidatePoolSize: 0,
131132
},
132133
isClosed: &atomicBool{},
133-
isGracefulClosed: &atomicBool{},
134-
isGracefulClosedDone: make(chan struct{}),
134+
isCloseDone: make(chan struct{}),
135+
isGracefulCloseDone: make(chan struct{}),
135136
isNegotiationNeeded: &atomicBool{},
136137
updateNegotiationNeededFlagOnEmptyChain: &atomicBool{},
137138
lastOffer: "",
@@ -2101,22 +2102,44 @@ func (pc *PeerConnection) GracefulClose() error {
21012102
func (pc *PeerConnection) close(shouldGracefullyClose bool) error {
21022103
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #1)
21032104
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #2)
2104-
alreadyGracefullyClosed := shouldGracefullyClose && pc.isGracefulClosed.swap(true)
2105-
if pc.isClosed.swap(true) {
2106-
if alreadyGracefullyClosed {
2107-
// similar but distinct condition where we may be waiting for some
2108-
// other graceful close to finish. Incorrectly using isClosed may
2109-
// leak a goroutine.
2110-
<-pc.isGracefulClosedDone
2111-
}
2112-
return nil
2105+
2106+
pc.mu.Lock()
2107+
// A lock in this critical section is needed because pc.isClosed and
2108+
// pc.isGracefullyClosingOrClosed are related to each other in that we
2109+
// want to make graceful and normal closure one time operations in order
2110+
// to avoid any double closure errors from cropping up. However, there are
2111+
// some overlapping close cases when both normal and graceful close are used
2112+
// that should be idempotent, but be cautioned when writing new close behavior
2113+
// to preserve this property.
2114+
isAlreadyClosingOrClosed := pc.isClosed.swap(true)
2115+
isAlreadyGracefullyClosingOrClosed := pc.isGracefullyClosingOrClosed
2116+
if shouldGracefullyClose && !isAlreadyGracefullyClosingOrClosed {
2117+
pc.isGracefullyClosingOrClosed = true
21132118
}
2114-
if shouldGracefullyClose && !alreadyGracefullyClosed {
2115-
defer close(pc.isGracefulClosedDone)
2119+
pc.mu.Unlock()
2120+
2121+
if isAlreadyClosingOrClosed {
2122+
if !shouldGracefullyClose {
2123+
return nil
2124+
}
2125+
// Even if we're already closing, it may not be graceful:
2126+
// If we are not the ones doing the closing, we just wait for the graceful close
2127+
// to happen and then return.
2128+
if isAlreadyGracefullyClosingOrClosed {
2129+
<-pc.isGracefulCloseDone
2130+
return nil
2131+
}
2132+
// Otherwise we need to go through the graceful closure flow once the
2133+
// normal closure is done since there are extra steps to take with a
2134+
// graceful close.
2135+
<-pc.isCloseDone
2136+
} else {
2137+
defer close(pc.isCloseDone)
21162138
}
21172139

2118-
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #3)
2119-
pc.signalingState.Set(SignalingStateClosed)
2140+
if shouldGracefullyClose {
2141+
defer close(pc.isGracefulCloseDone)
2142+
}
21202143

21212144
// Try closing everything and collect the errors
21222145
// Shutdown strategy:
@@ -2126,6 +2149,34 @@ func (pc *PeerConnection) close(shouldGracefullyClose bool) error {
21262149
// continue the chain the Mux has to be closed.
21272150
closeErrs := make([]error, 4)
21282151

2152+
doGracefulCloseOps := func() []error {
2153+
if !shouldGracefullyClose {
2154+
return nil
2155+
}
2156+
2157+
// these are all non-canon steps
2158+
var gracefulCloseErrors []error
2159+
if pc.iceTransport != nil {
2160+
gracefulCloseErrors = append(gracefulCloseErrors, pc.iceTransport.GracefulStop())
2161+
}
2162+
2163+
pc.ops.GracefulClose()
2164+
2165+
pc.sctpTransport.lock.Lock()
2166+
for _, d := range pc.sctpTransport.dataChannels {
2167+
gracefulCloseErrors = append(gracefulCloseErrors, d.GracefulClose())
2168+
}
2169+
pc.sctpTransport.lock.Unlock()
2170+
return gracefulCloseErrors
2171+
}
2172+
2173+
if isAlreadyClosingOrClosed {
2174+
return util.FlattenErrs(doGracefulCloseOps())
2175+
}
2176+
2177+
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #3)
2178+
pc.signalingState.Set(SignalingStateClosed)
2179+
21292180
closeErrs = append(closeErrs, pc.api.interceptor.Close())
21302181

21312182
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #4)
@@ -2156,28 +2207,15 @@ func (pc *PeerConnection) close(shouldGracefullyClose bool) error {
21562207
closeErrs = append(closeErrs, pc.dtlsTransport.Stop())
21572208

21582209
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #8, #9, #10)
2159-
if pc.iceTransport != nil {
2160-
if shouldGracefullyClose {
2161-
// note that it isn't canon to stop gracefully
2162-
closeErrs = append(closeErrs, pc.iceTransport.GracefulStop())
2163-
} else {
2164-
closeErrs = append(closeErrs, pc.iceTransport.Stop())
2165-
}
2210+
if pc.iceTransport != nil && !shouldGracefullyClose {
2211+
// we will stop gracefully in doGracefulCloseOps
2212+
closeErrs = append(closeErrs, pc.iceTransport.Stop())
21662213
}
21672214

21682215
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #11)
21692216
pc.updateConnectionState(pc.ICEConnectionState(), pc.dtlsTransport.State())
21702217

2171-
if shouldGracefullyClose {
2172-
pc.ops.GracefulClose()
2173-
2174-
// note that it isn't canon to stop gracefully
2175-
pc.sctpTransport.lock.Lock()
2176-
for _, d := range pc.sctpTransport.dataChannels {
2177-
closeErrs = append(closeErrs, d.GracefulClose())
2178-
}
2179-
pc.sctpTransport.lock.Unlock()
2180-
}
2218+
closeErrs = append(closeErrs, doGracefulCloseOps()...)
21812219

21822220
return util.FlattenErrs(closeErrs)
21832221
}

peerconnection_close_test.go

+83-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
package webrtc
88

99
import (
10+
"fmt"
11+
"sync"
1012
"testing"
1113
"time"
1214

@@ -180,7 +182,7 @@ func TestPeerConnection_Close_DuringICE(t *testing.T) {
180182
}
181183
}
182184

183-
func TestPeerConnection_CloseWithIncomingMessages(t *testing.T) {
185+
func TestPeerConnection_GracefulCloseWithIncomingMessages(t *testing.T) {
184186
// Limit runtime in case of deadlocks
185187
lim := test.TimeOut(time.Second * 20)
186188
defer lim.Stop()
@@ -245,3 +247,83 @@ func TestPeerConnection_CloseWithIncomingMessages(t *testing.T) {
245247
t.Fatal(err)
246248
}
247249
}
250+
251+
func TestPeerConnection_GracefulCloseWhileOpening(t *testing.T) {
252+
// Limit runtime in case of deadlocks
253+
lim := test.TimeOut(time.Second * 5)
254+
defer lim.Stop()
255+
256+
report := test.CheckRoutinesStrict(t)
257+
defer report()
258+
259+
pcOffer, pcAnswer, err := newPair()
260+
if err != nil {
261+
t.Fatal(err)
262+
}
263+
264+
if _, err = pcOffer.CreateDataChannel("initial_data_channel", nil); err != nil {
265+
t.Fatal(err)
266+
}
267+
268+
offer, err := pcOffer.CreateOffer(nil)
269+
if err != nil {
270+
t.Fatal(err)
271+
}
272+
offerGatheringComplete := GatheringCompletePromise(pcOffer)
273+
if err = pcOffer.SetLocalDescription(offer); err != nil {
274+
t.Fatal(err)
275+
}
276+
<-offerGatheringComplete
277+
278+
err = pcOffer.GracefulClose()
279+
if err != nil {
280+
t.Fatal(err)
281+
}
282+
283+
if err = pcAnswer.SetRemoteDescription(offer); err != nil {
284+
t.Fatal(err)
285+
}
286+
287+
err = pcAnswer.GracefulClose()
288+
if err != nil {
289+
t.Fatal(err)
290+
}
291+
}
292+
293+
func TestPeerConnection_GracefulCloseConcurrent(t *testing.T) {
294+
// Limit runtime in case of deadlocks
295+
lim := test.TimeOut(time.Second * 10)
296+
defer lim.Stop()
297+
298+
for _, mixed := range []bool{false, true} {
299+
t.Run(fmt.Sprintf("mixed_graceful=%t", mixed), func(t *testing.T) {
300+
report := test.CheckRoutinesStrict(t)
301+
defer report()
302+
303+
pc, err := NewPeerConnection(Configuration{})
304+
if err != nil {
305+
t.Fatal(err)
306+
}
307+
308+
const gracefulCloseConcurrency = 50
309+
var wg sync.WaitGroup
310+
wg.Add(gracefulCloseConcurrency)
311+
for i := 0; i < gracefulCloseConcurrency; i++ {
312+
go func() {
313+
defer wg.Done()
314+
assert.NoError(t, pc.GracefulClose())
315+
}()
316+
}
317+
if !mixed {
318+
if err := pc.Close(); err != nil {
319+
t.Fatal(err)
320+
}
321+
} else {
322+
if err := pc.GracefulClose(); err != nil {
323+
t.Fatal(err)
324+
}
325+
}
326+
wg.Wait()
327+
})
328+
}
329+
}

0 commit comments

Comments
 (0)