From d9ca26dabb4c552802fd161b6d115e472cdf7269 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Sat, 9 Jul 2022 17:54:08 +1000 Subject: [PATCH] Close detached data channel and end span on webrtc conn close --- webtorrent/otel.go | 1 + webtorrent/transport.go | 14 ++++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/webtorrent/otel.go b/webtorrent/otel.go index 3c40b32a..d939c3f8 100644 --- a/webtorrent/otel.go +++ b/webtorrent/otel.go @@ -13,6 +13,7 @@ const ( ) func dataChannelStarted(peerConnectionCtx context.Context, dc *webrtc.DataChannel) (dataChannelCtx context.Context, span trace.Span) { + trace.SpanFromContext(peerConnectionCtx).AddEvent("starting data channel") dataChannelCtx, span = otel.Tracer(tracerName).Start(peerConnectionCtx, "DataChannel") dc.OnClose(func() { span.End() diff --git a/webtorrent/transport.go b/webtorrent/transport.go index 9cff003e..561a6b9f 100644 --- a/webtorrent/transport.go +++ b/webtorrent/transport.go @@ -169,25 +169,31 @@ func setDataChannelOnOpen( onOpen func(closer datachannel.ReadWriteCloser), ) { dc.OnOpen(func() { - trace.SpanFromContext(ctx).AddEvent("opened") + dataChannelSpan := trace.SpanFromContext(ctx) + dataChannelSpan.AddEvent("opened") raw, err := dc.Detach() if err != nil { // This shouldn't happen if the API is configured correctly, and we call from OnOpen. panic(err) } //dc.OnClose() - onOpen(hookDataChannelCloser(raw, pc)) + onOpen(hookDataChannelCloser(raw, pc, dataChannelSpan)) }) } // Hooks the datachannel's Close to Close the owning PeerConnection. The datachannel takes ownership // and responsibility for the PeerConnection. -func hookDataChannelCloser(dcrwc datachannel.ReadWriteCloser, pc *wrappedPeerConnection) datachannel.ReadWriteCloser { +func hookDataChannelCloser(dcrwc datachannel.ReadWriteCloser, pc *wrappedPeerConnection, dataChannelSpan trace.Span) datachannel.ReadWriteCloser { return struct { datachannelReadWriter io.Closer }{ dcrwc, - ioCloserFunc(pc.Close), + ioCloserFunc(func() error { + dcrwc.Close() + pc.Close() + dataChannelSpan.End() + return nil + }), } } -- 2.48.1