Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(@libp2p/webrtc): delay closing datachannels #2048

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/transport-webrtc/src/muxer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createStream } from './stream.js'
import { nopSink, nopSource } from './util.js'
import { drainAndClose, nopSink, nopSource } from './util.js'
import type { DataChannelOpts } from './stream.js'
import type { Stream } from '@libp2p/interface/connection'
import type { CounterGroup } from '@libp2p/interface/metrics'
Expand All @@ -9,6 +9,7 @@ import type { Source, Sink } from 'it-stream-types'
import type { Uint8ArrayList } from 'uint8arraylist'

const PROTOCOL = '/webrtc'
const DEFAULT_CHANNEL_CLOSE_DELAY = 30000
maschad marked this conversation as resolved.
Show resolved Hide resolved

export interface DataChannelMuxerFactoryInit {
/**
Expand Down Expand Up @@ -131,6 +132,7 @@ export class DataChannelMuxer implements StreamMuxer {
direction: 'inbound',
dataChannelOptions: this.dataChannelOptions,
onEnd: () => {
drainAndClose(channel, this.dataChannelOptions?.closeDelay ?? DEFAULT_CHANNEL_CLOSE_DELAY)
this.streams = this.streams.filter(s => s.id !== stream.id)
this.metrics?.increment({ stream_end: true })
init?.onStreamEnd?.(stream)
Expand Down Expand Up @@ -158,7 +160,7 @@ export class DataChannelMuxer implements StreamMuxer {
direction: 'outbound',
dataChannelOptions: this.dataChannelOptions,
onEnd: () => {
channel.close() // Stream initiator is responsible for closing the channel
drainAndClose(channel, this.dataChannelOptions?.closeDelay ?? DEFAULT_CHANNEL_CLOSE_DELAY)
this.streams = this.streams.filter(s => s.id !== stream.id)
this.metrics?.increment({ stream_end: true })
this.init?.onStreamEnd?.(stream)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export class WebRTCTransport implements Transport, Startable {
* <relay address>/p2p/<relay-peer>/p2p-circuit/webrtc/p2p/<destination-peer>
*/
async dial (ma: Multiaddr, options: DialOptions): Promise<Connection> {
log.trace('dialing address: ', ma)
log.trace('dialing address: %a', ma)
const { baseAddr, peerId } = splitAddr(ma)

if (options.signal == null) {
Expand Down
3 changes: 2 additions & 1 deletion packages/transport-webrtc/src/private-to-public/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export interface WebRTCMetrics {

export interface WebRTCTransportDirectInit {
dataChannel?: Partial<DataChannelOpts>
dataChannelCloseDelay?: number
}

export class WebRTCDirectTransport implements Transport {
Expand All @@ -80,7 +81,7 @@ export class WebRTCDirectTransport implements Transport {
*/
async dial (ma: Multiaddr, options: WebRTCDialOptions): Promise<Connection> {
const rawConn = await this._connect(ma, options)
log(`dialing address - ${ma.toString()}`)
log.trace('dialing address: %a', ma)
return rawConn
}

Expand Down
1 change: 1 addition & 0 deletions packages/transport-webrtc/src/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface DataChannelOpts {
maxMessageSize: number
maxBufferedAmount: number
bufferedAmountLowEventTimeout: number
closeDelay?: number
}

export interface WebRTCStreamInit extends AbstractStreamInit {
Expand Down
51 changes: 51 additions & 0 deletions packages/transport-webrtc/src/util.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,59 @@
import { logger } from '@libp2p/logger'
import { detect } from 'detect-browser'
import pDefer from 'p-defer'

const log = logger('libp2p:webrtc:utils')

const browser = detect()
export const isFirefox = ((browser != null) && browser.name === 'firefox')

export const nopSource = async function * nop (): AsyncGenerator<Uint8Array, any, unknown> {}

export const nopSink = async (_: any): Promise<void> => {}

export function drainAndClose (channel: RTCDataChannel, channelCloseDelay: number): void {
if (channel.readyState !== 'open') {
return
}

void Promise.resolve()
.then(async () => {
// wait for bufferedAmount to become zero
if (channel.bufferedAmount > 0) {
const deferred = pDefer()

channel.bufferedAmountLowThreshold = 0
channel.addEventListener('bufferedamountlow', () => {
deferred.resolve()
})

await deferred.promise
}
})
.then(async () => {
const deferred = pDefer()

// event if bufferedAmount is zero there can still be unsent bytes
const timeout = setTimeout(() => {
try {
// only close if the channel is still open
if (channel.readyState === 'open') {
channel.close()
}

deferred.resolve()
} catch (err: any) {
deferred.reject(err)
}
}, channelCloseDelay)

if (timeout.unref != null) {
timeout.unref()
}

await deferred.promise
})
.catch(err => {
log.error('error closing outbound stream', err)
maschad marked this conversation as resolved.
Show resolved Hide resolved
})
}