@libp2p/webrtc 3.2.11 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +1 -1
  2. package/dist/index.min.js +12 -12
  3. package/dist/src/error.d.ts +2 -2
  4. package/dist/src/error.d.ts.map +1 -1
  5. package/dist/src/error.js +1 -1
  6. package/dist/src/error.js.map +1 -1
  7. package/dist/src/index.d.ts +33 -3
  8. package/dist/src/index.d.ts.map +1 -1
  9. package/dist/src/index.js.map +1 -1
  10. package/dist/src/maconn.d.ts +8 -4
  11. package/dist/src/maconn.d.ts.map +1 -1
  12. package/dist/src/maconn.js +6 -6
  13. package/dist/src/maconn.js.map +1 -1
  14. package/dist/src/muxer.d.ts +13 -5
  15. package/dist/src/muxer.d.ts.map +1 -1
  16. package/dist/src/muxer.js +36 -7
  17. package/dist/src/muxer.js.map +1 -1
  18. package/dist/src/pb/message.js.map +1 -1
  19. package/dist/src/private-to-private/initiate-connection.d.ts +4 -5
  20. package/dist/src/private-to-private/initiate-connection.d.ts.map +1 -1
  21. package/dist/src/private-to-private/initiate-connection.js +4 -5
  22. package/dist/src/private-to-private/initiate-connection.js.map +1 -1
  23. package/dist/src/private-to-private/listener.d.ts +3 -4
  24. package/dist/src/private-to-private/listener.d.ts.map +1 -1
  25. package/dist/src/private-to-private/listener.js +1 -1
  26. package/dist/src/private-to-private/listener.js.map +1 -1
  27. package/dist/src/private-to-private/pb/message.js.map +1 -1
  28. package/dist/src/private-to-private/signaling-stream-handler.d.ts +4 -2
  29. package/dist/src/private-to-private/signaling-stream-handler.d.ts.map +1 -1
  30. package/dist/src/private-to-private/signaling-stream-handler.js +4 -5
  31. package/dist/src/private-to-private/signaling-stream-handler.js.map +1 -1
  32. package/dist/src/private-to-private/transport.d.ts +6 -27
  33. package/dist/src/private-to-private/transport.d.ts.map +1 -1
  34. package/dist/src/private-to-private/transport.js +15 -14
  35. package/dist/src/private-to-private/transport.js.map +1 -1
  36. package/dist/src/private-to-private/util.d.ts +2 -2
  37. package/dist/src/private-to-private/util.d.ts.map +1 -1
  38. package/dist/src/private-to-private/util.js +26 -41
  39. package/dist/src/private-to-private/util.js.map +1 -1
  40. package/dist/src/private-to-public/options.d.ts +1 -1
  41. package/dist/src/private-to-public/options.d.ts.map +1 -1
  42. package/dist/src/private-to-public/sdp.d.ts +2 -1
  43. package/dist/src/private-to-public/sdp.d.ts.map +1 -1
  44. package/dist/src/private-to-public/sdp.js +3 -6
  45. package/dist/src/private-to-public/sdp.js.map +1 -1
  46. package/dist/src/private-to-public/transport.d.ts +5 -16
  47. package/dist/src/private-to-public/transport.d.ts.map +1 -1
  48. package/dist/src/private-to-public/transport.js +28 -17
  49. package/dist/src/private-to-public/transport.js.map +1 -1
  50. package/dist/src/stream.d.ts +10 -4
  51. package/dist/src/stream.d.ts.map +1 -1
  52. package/dist/src/stream.js +19 -33
  53. package/dist/src/stream.js.map +1 -1
  54. package/dist/src/util.d.ts +2 -1
  55. package/dist/src/util.d.ts.map +1 -1
  56. package/dist/src/util.js +4 -6
  57. package/dist/src/util.js.map +1 -1
  58. package/dist/src/webrtc/rtc-data-channel.js.map +1 -1
  59. package/dist/src/webrtc/rtc-ice-candidate.js.map +1 -1
  60. package/dist/src/webrtc/rtc-peer-connection.js.map +1 -1
  61. package/dist/typedoc-urls.json +8 -0
  62. package/package.json +25 -20
  63. package/src/error.ts +2 -2
  64. package/src/index.ts +40 -3
  65. package/src/maconn.ts +14 -10
  66. package/src/muxer.ts +57 -11
  67. package/src/private-to-private/initiate-connection.ts +7 -11
  68. package/src/private-to-private/listener.ts +3 -4
  69. package/src/private-to-private/signaling-stream-handler.ts +7 -7
  70. package/src/private-to-private/transport.ts +18 -43
  71. package/src/private-to-private/util.ts +30 -46
  72. package/src/private-to-public/options.ts +1 -1
  73. package/src/private-to-public/sdp.ts +4 -8
  74. package/src/private-to-public/transport.ts +30 -34
  75. package/src/stream.ts +27 -39
  76. package/src/util.ts +5 -7
@@ -1,19 +1,14 @@
1
- import { CodeError } from '@libp2p/interface/errors'
2
- import { logger } from '@libp2p/logger'
3
- import { abortableSource } from 'abortable-iterator'
1
+ import { CodeError } from '@libp2p/interface'
2
+ import { closeSource } from '@libp2p/utils/close-source'
4
3
  import { anySignal } from 'any-signal'
5
- import * as lp from 'it-length-prefixed'
6
- import { AbortError, raceSignal } from 'race-signal'
7
4
  import { isFirefox } from '../util.js'
8
5
  import { RTCIceCandidate } from '../webrtc/index.js'
9
6
  import { Message } from './pb/message.js'
10
- import type { Stream } from '@libp2p/interface/connection'
7
+ import type { LoggerOptions, Stream } from '@libp2p/interface'
11
8
  import type { AbortOptions, MessageStream } from 'it-protobuf-stream'
12
9
  import type { DeferredPromise } from 'p-defer'
13
10
 
14
- const log = logger('libp2p:webrtc:peer:util')
15
-
16
- export interface ReadCandidatesOptions extends AbortOptions {
11
+ export interface ReadCandidatesOptions extends AbortOptions, LoggerOptions {
17
12
  direction: string
18
13
  }
19
14
 
@@ -31,71 +26,60 @@ export const readCandidatesUntilConnected = async (connectedPromise: DeferredPro
31
26
  options.signal
32
27
  ])
33
28
 
34
- const source = abortableSource(stream.unwrap().unwrap().source, signal, {
35
- returnOnAbort: true
36
- })
29
+ const abortListener = (): void => {
30
+ closeSource(stream.unwrap().unwrap().source, options.log)
31
+ }
32
+
33
+ signal.addEventListener('abort', abortListener)
37
34
 
38
35
  try {
39
36
  // read candidates until we are connected or we reach the end of the stream
40
- for await (const buf of lp.decode(source)) {
41
- const message = Message.decode(buf)
37
+ while (true) {
38
+ const message = await Promise.race([
39
+ connectedPromise.promise,
40
+ stream.read()
41
+ ])
42
+
43
+ // stream ended or we became connected
44
+ if (message == null) {
45
+ break
46
+ }
42
47
 
43
48
  if (message.type !== Message.Type.ICE_CANDIDATE) {
44
49
  throw new CodeError('ICE candidate message expected', 'ERR_NOT_ICE_CANDIDATE')
45
50
  }
46
51
 
47
- let candidateInit = JSON.parse(message.data ?? 'null')
52
+ const candidateInit = JSON.parse(message.data ?? 'null')
48
53
 
49
- if (candidateInit === '') {
50
- log.trace('end-of-candidates for this generation received')
51
- candidateInit = {
52
- candidate: '',
53
- sdpMid: '0',
54
- sdpMLineIndex: 0
55
- }
56
- }
54
+ // an empty string means this generation of candidates is complete, a null
55
+ // candidate means candidate gathering has finished
56
+ // see - https://www.w3.org/TR/webrtc/#rtcpeerconnectioniceevent
57
+ if (candidateInit === '' || candidateInit === null) {
58
+ options.log.trace('end-of-candidates received')
57
59
 
58
- if (candidateInit === null) {
59
- log.trace('end-of-candidates received')
60
- candidateInit = {
61
- candidate: null,
62
- sdpMid: '0',
63
- sdpMLineIndex: 0
64
- }
60
+ continue
65
61
  }
66
62
 
67
- // a null candidate means end-of-candidates
68
- // see - https://www.w3.org/TR/webrtc/#rtcpeerconnectioniceevent
69
63
  const candidate = new RTCIceCandidate(candidateInit)
70
64
 
71
- log.trace('%s received new ICE candidate', options.direction, candidate)
65
+ options.log.trace('%s received new ICE candidate', options.direction, candidate)
72
66
 
73
67
  try {
74
68
  await pc.addIceCandidate(candidate)
75
69
  } catch (err) {
76
- log.error('%s bad candidate received', options.direction, err)
70
+ options.log.error('%s bad candidate received', options.direction, candidateInit, err)
77
71
  }
78
72
  }
79
73
  } catch (err) {
80
- log.error('%s error parsing ICE candidate', options.direction, err)
74
+ options.log.error('%s error parsing ICE candidate', options.direction, err)
81
75
  } finally {
76
+ signal.removeEventListener('abort', abortListener)
82
77
  signal.clear()
83
78
  }
84
-
85
- if (options.signal?.aborted === true) {
86
- throw new AbortError('Aborted while reading ICE candidates', 'ERR_ICE_CANDIDATES_READ_ABORTED')
87
- }
88
-
89
- // read all available ICE candidates, wait for connection state change
90
- await raceSignal(connectedPromise.promise, options.signal, {
91
- errorMessage: 'Aborted before connected',
92
- errorCode: 'ERR_ABORTED_BEFORE_CONNECTED'
93
- })
94
79
  }
95
80
 
96
81
  export function resolveOnConnected (pc: RTCPeerConnection, promise: DeferredPromise<void>): void {
97
82
  pc[isFirefox ? 'oniceconnectionstatechange' : 'onconnectionstatechange'] = (_) => {
98
- log.trace('receiver peerConnectionState state change: %s', pc.connectionState)
99
83
  switch (isFirefox ? pc.iceConnectionState : pc.connectionState) {
100
84
  case 'connected':
101
85
  promise.resolve()
@@ -1,4 +1,4 @@
1
- import type { CreateListenerOptions, DialOptions } from '@libp2p/interface/transport'
1
+ import type { CreateListenerOptions, DialOptions } from '@libp2p/interface'
2
2
 
3
3
  export interface WebRTCListenerOptions extends CreateListenerOptions {}
4
4
  export interface WebRTCDialOptions extends DialOptions {}
@@ -1,24 +1,22 @@
1
- import { logger } from '@libp2p/logger'
2
1
  import { bases } from 'multiformats/basics'
3
2
  import * as multihashes from 'multihashes'
4
3
  import { inappropriateMultiaddr, invalidArgument, invalidFingerprint, unsupportedHashAlgorithm } from '../error.js'
5
4
  import { CERTHASH_CODE } from './transport.js'
5
+ import type { LoggerOptions } from '@libp2p/interface'
6
6
  import type { Multiaddr } from '@multiformats/multiaddr'
7
7
  import type { HashCode, HashName } from 'multihashes'
8
8
 
9
- const log = logger('libp2p:webrtc:sdp')
10
-
11
9
  /**
12
10
  * Get base2 | identity decoders
13
11
  */
14
12
  // @ts-expect-error - Not easy to combine these types.
15
13
  export const mbdecoder: any = Object.values(bases).map(b => b.decoder).reduce((d, b) => d.or(b))
16
14
 
17
- export function getLocalFingerprint (pc: RTCPeerConnection): string | undefined {
15
+ export function getLocalFingerprint (pc: RTCPeerConnection, options: LoggerOptions): string | undefined {
18
16
  // try to fetch fingerprint from local certificate
19
17
  const localCert = pc.getConfiguration().certificates?.at(0)
20
18
  if (localCert == null || localCert.getFingerprints == null) {
21
- log.trace('fetching fingerprint from local SDP')
19
+ options.log.trace('fetching fingerprint from local SDP')
22
20
  const localDescription = pc.localDescription
23
21
  if (localDescription == null) {
24
22
  return undefined
@@ -26,7 +24,7 @@ export function getLocalFingerprint (pc: RTCPeerConnection): string | undefined
26
24
  return getFingerprintFromSdp(localDescription.sdp)
27
25
  }
28
26
 
29
- log.trace('fetching fingerprint from local certificate')
27
+ options.log.trace('fetching fingerprint from local certificate')
30
28
 
31
29
  if (localCert.getFingerprints().length === 0) {
32
30
  return undefined
@@ -55,8 +53,6 @@ function ipv (ma: Multiaddr): string {
55
53
  }
56
54
  }
57
55
 
58
- log('Warning: multiaddr does not appear to contain IP4 or IP6, defaulting to IP6', ma)
59
-
60
56
  return 'IP6'
61
57
  }
62
58
 
@@ -1,7 +1,6 @@
1
- import { noise as Noise } from '@chainsafe/libp2p-noise'
2
- import { type CreateListenerOptions, symbol, type Transport, type Listener } from '@libp2p/interface/transport'
3
- import { logger } from '@libp2p/logger'
4
- import * as p from '@libp2p/peer-id'
1
+ import { noise } from '@chainsafe/libp2p-noise'
2
+ import { transportSymbol } from '@libp2p/interface'
3
+ import { peerIdFromString } from '@libp2p/peer-id'
5
4
  import { protocols } from '@multiformats/multiaddr'
6
5
  import { WebRTCDirect } from '@multiformats/multiaddr-matcher'
7
6
  import * as multihashes from 'multihashes'
@@ -16,14 +15,10 @@ import { RTCPeerConnection } from '../webrtc/index.js'
16
15
  import * as sdp from './sdp.js'
17
16
  import { genUfrag } from './util.js'
18
17
  import type { WebRTCDialOptions } from './options.js'
19
- import type { DataChannelOptions } from '../index.js'
20
- import type { Connection } from '@libp2p/interface/connection'
21
- import type { CounterGroup, Metrics } from '@libp2p/interface/metrics'
22
- import type { PeerId } from '@libp2p/interface/peer-id'
18
+ import type { WebRTCDirectTransportComponents, WebRTCTransportDirectInit } from '../index.js'
19
+ import type { Logger, Connection, CounterGroup, CreateListenerOptions, Transport, Listener } from '@libp2p/interface'
23
20
  import type { Multiaddr } from '@multiformats/multiaddr'
24
21
 
25
- const log = logger('libp2p:webrtc:transport')
26
-
27
22
  /**
28
23
  * The time to wait, in milliseconds, for the data channel handshake to complete
29
24
  */
@@ -43,27 +38,17 @@ export const WEBRTC_CODE: number = protocols('webrtc-direct').code
43
38
  */
44
39
  export const CERTHASH_CODE: number = protocols('certhash').code
45
40
 
46
- /**
47
- * The peer for this transport
48
- */
49
- export interface WebRTCDirectTransportComponents {
50
- peerId: PeerId
51
- metrics?: Metrics
52
- }
53
-
54
41
  export interface WebRTCMetrics {
55
42
  dialerEvents: CounterGroup
56
43
  }
57
44
 
58
- export interface WebRTCTransportDirectInit {
59
- dataChannel?: DataChannelOptions
60
- }
61
-
62
45
  export class WebRTCDirectTransport implements Transport {
46
+ private readonly log: Logger
63
47
  private readonly metrics?: WebRTCMetrics
64
48
  private readonly components: WebRTCDirectTransportComponents
65
49
  private readonly init: WebRTCTransportDirectInit
66
50
  constructor (components: WebRTCDirectTransportComponents, init: WebRTCTransportDirectInit = {}) {
51
+ this.log = components.logger.forComponent('libp2p:webrtc-direct')
67
52
  this.components = components
68
53
  this.init = init
69
54
  if (components.metrics != null) {
@@ -81,7 +66,7 @@ export class WebRTCDirectTransport implements Transport {
81
66
  */
82
67
  async dial (ma: Multiaddr, options: WebRTCDialOptions): Promise<Connection> {
83
68
  const rawConn = await this._connect(ma, options)
84
- log('dialing address: %a', ma)
69
+ this.log('dialing address: %a', ma)
85
70
  return rawConn
86
71
  }
87
72
 
@@ -107,7 +92,7 @@ export class WebRTCDirectTransport implements Transport {
107
92
  /**
108
93
  * Symbol.for('@libp2p/transport')
109
94
  */
110
- readonly [symbol] = true
95
+ readonly [transportSymbol] = true
111
96
 
112
97
  /**
113
98
  * Connect to a peer using a multiaddr
@@ -120,7 +105,7 @@ export class WebRTCDirectTransport implements Transport {
120
105
  if (remotePeerString === null) {
121
106
  throw inappropriateMultiaddr("we need to have the remote's PeerId")
122
107
  }
123
- const theirPeerId = p.peerIdFromString(remotePeerString)
108
+ const theirPeerId = peerIdFromString(remotePeerString)
124
109
 
125
110
  const remoteCerthash = sdp.decodeCerthash(sdp.certhash(ma))
126
111
 
@@ -144,7 +129,7 @@ export class WebRTCDirectTransport implements Transport {
144
129
  const handshakeDataChannel = peerConnection.createDataChannel('', { negotiated: true, id: 0 })
145
130
  const handshakeTimeout = setTimeout(() => {
146
131
  const error = `Data channel was never opened: state: ${handshakeDataChannel.readyState}`
147
- log.error(error)
132
+ this.log.error(error)
148
133
  this.metrics?.dialerEvents.increment({ open_error: true })
149
134
  reject(dataChannelError('data', error))
150
135
  }, HANDSHAKE_TIMEOUT_MS)
@@ -159,7 +144,7 @@ export class WebRTCDirectTransport implements Transport {
159
144
  clearTimeout(handshakeTimeout)
160
145
  const errorTarget = event.target?.toString() ?? 'not specified'
161
146
  const error = `Error opening a data channel for handshaking: ${errorTarget}`
162
- log.error(error)
147
+ this.log.error(error)
163
148
  // NOTE: We use unknown error here but this could potentially be considered a reset by some standards.
164
149
  this.metrics?.dialerEvents.increment({ unknown_error: true })
165
150
  reject(dataChannelError('data', error))
@@ -192,9 +177,14 @@ export class WebRTCDirectTransport implements Transport {
192
177
 
193
178
  // Since we use the default crypto interface and do not use a static key or early data,
194
179
  // we pass in undefined for these parameters.
195
- const noise = Noise({ prologueBytes: fingerprintsPrologue })()
180
+ const encrypter = noise({ prologueBytes: fingerprintsPrologue })()
196
181
 
197
- const wrappedChannel = createStream({ channel: handshakeDataChannel, direction: 'inbound', ...(this.init.dataChannel ?? {}) })
182
+ const wrappedChannel = createStream({
183
+ channel: handshakeDataChannel,
184
+ direction: 'inbound',
185
+ logger: this.components.logger,
186
+ ...(this.init.dataChannel ?? {})
187
+ })
198
188
  const wrappedDuplex = {
199
189
  ...wrappedChannel,
200
190
  sink: wrappedChannel.sink.bind(wrappedChannel),
@@ -209,7 +199,7 @@ export class WebRTCDirectTransport implements Transport {
209
199
 
210
200
  // Creating the connection before completion of the noise
211
201
  // handshake ensures that the stream opening callback is set up
212
- const maConn = new WebRTCMultiaddrConnection({
202
+ const maConn = new WebRTCMultiaddrConnection(this.components, {
213
203
  peerConnection,
214
204
  remoteAddr: ma,
215
205
  timeline: {
@@ -226,7 +216,7 @@ export class WebRTCDirectTransport implements Transport {
226
216
  case 'disconnected':
227
217
  case 'closed':
228
218
  maConn.close().catch((err) => {
229
- log.error('error closing connection', err)
219
+ this.log.error('error closing connection', err)
230
220
  }).finally(() => {
231
221
  // Remove the event listener once the connection is closed
232
222
  controller.abort()
@@ -240,11 +230,15 @@ export class WebRTCDirectTransport implements Transport {
240
230
  // Track opened peer connection
241
231
  this.metrics?.dialerEvents.increment({ peer_connection: true })
242
232
 
243
- const muxerFactory = new DataChannelMuxerFactory({ peerConnection, metrics: this.metrics?.dialerEvents, dataChannelOptions: this.init.dataChannel })
233
+ const muxerFactory = new DataChannelMuxerFactory(this.components, {
234
+ peerConnection,
235
+ metrics: this.metrics?.dialerEvents,
236
+ dataChannelOptions: this.init.dataChannel
237
+ })
244
238
 
245
239
  // For outbound connections, the remote is expected to start the noise handshake.
246
240
  // Therefore, we need to secure an inbound noise connection from the remote.
247
- await noise.secureInbound(myPeerId, wrappedDuplex, theirPeerId)
241
+ await encrypter.secureInbound(myPeerId, wrappedDuplex, theirPeerId)
248
242
 
249
243
  return await options.upgrader.upgradeOutbound(maConn, { skipProtection: true, skipEncryption: true, muxerFactory })
250
244
  } catch (err) {
@@ -262,7 +256,9 @@ export class WebRTCDirectTransport implements Transport {
262
256
  throw invalidArgument('no local certificate')
263
257
  }
264
258
 
265
- const localFingerprint = sdp.getLocalFingerprint(pc)
259
+ const localFingerprint = sdp.getLocalFingerprint(pc, {
260
+ log: this.log
261
+ })
266
262
  if (localFingerprint == null) {
267
263
  throw invalidArgument('no local fingerprint found')
268
264
  }
package/src/stream.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { CodeError } from '@libp2p/interface/errors'
2
- import { AbstractStream, type AbstractStreamInit } from '@libp2p/interface/stream-muxer/stream'
3
- import { logger } from '@libp2p/logger'
1
+ import { CodeError } from '@libp2p/interface'
2
+ import { AbstractStream, type AbstractStreamInit } from '@libp2p/utils/abstract-stream'
4
3
  import * as lengthPrefixed from 'it-length-prefixed'
5
4
  import { type Pushable, pushable } from 'it-pushable'
6
5
  import pDefer from 'p-defer'
@@ -10,8 +9,7 @@ import { raceSignal } from 'race-signal'
10
9
  import { Uint8ArrayList } from 'uint8arraylist'
11
10
  import { Message } from './pb/message.js'
12
11
  import type { DataChannelOptions } from './index.js'
13
- import type { AbortOptions } from '@libp2p/interface'
14
- import type { Direction } from '@libp2p/interface/connection'
12
+ import type { AbortOptions, ComponentLogger, Direction } from '@libp2p/interface'
15
13
  import type { DeferredPromise } from 'p-defer'
16
14
 
17
15
  export interface WebRTCStreamInit extends AbstractStreamInit, DataChannelOptions {
@@ -22,6 +20,8 @@ export interface WebRTCStreamInit extends AbstractStreamInit, DataChannelOptions
22
20
  * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel}
23
21
  */
24
22
  channel: RTCDataChannel
23
+
24
+ logger: ComponentLogger
25
25
  }
26
26
 
27
27
  /**
@@ -56,6 +56,12 @@ export const MAX_MESSAGE_SIZE = 16 * 1024
56
56
  */
57
57
  export const FIN_ACK_TIMEOUT = 5000
58
58
 
59
+ /**
60
+ * When sending data messages, if the channel is not in the "open" state, wait
61
+ * this long for the "open" event to fire.
62
+ */
63
+ export const OPEN_TIMEOUT = 5000
64
+
59
65
  export class WebRTCStream extends AbstractStream {
60
66
  /**
61
67
  * The data channel used to send and receive data
@@ -68,8 +74,6 @@ export class WebRTCStream extends AbstractStream {
68
74
  */
69
75
  private readonly incomingData: Pushable<Uint8Array>
70
76
 
71
- private messageQueue?: Uint8ArrayList
72
-
73
77
  private readonly maxBufferedAmount: number
74
78
 
75
79
  private readonly bufferedAmountLowEventTimeout: number
@@ -84,6 +88,7 @@ export class WebRTCStream extends AbstractStream {
84
88
  */
85
89
  private readonly receiveFinAck: DeferredPromise<void>
86
90
  private readonly finAckTimeout: number
91
+ private readonly openTimeout: number
87
92
 
88
93
  constructor (init: WebRTCStreamInit) {
89
94
  // override onEnd to send/receive FIN_ACK before closing the stream
@@ -121,17 +126,18 @@ export class WebRTCStream extends AbstractStream {
121
126
 
122
127
  this.channel = init.channel
123
128
  this.channel.binaryType = 'arraybuffer'
124
- this.incomingData = pushable()
125
- this.messageQueue = new Uint8ArrayList()
129
+ this.incomingData = pushable<Uint8Array>()
126
130
  this.bufferedAmountLowEventTimeout = init.bufferedAmountLowEventTimeout ?? BUFFERED_AMOUNT_LOW_TIMEOUT
127
131
  this.maxBufferedAmount = init.maxBufferedAmount ?? MAX_BUFFERED_AMOUNT
128
132
  this.maxMessageSize = (init.maxMessageSize ?? MAX_MESSAGE_SIZE) - PROTOBUF_OVERHEAD - VARINT_LENGTH
129
133
  this.receiveFinAck = pDefer()
130
134
  this.finAckTimeout = init.closeTimeout ?? FIN_ACK_TIMEOUT
135
+ this.openTimeout = init.openTimeout ?? OPEN_TIMEOUT
131
136
 
132
137
  // set up initial state
133
138
  switch (this.channel.readyState) {
134
139
  case 'open':
140
+ this.timeline.open = new Date().getTime()
135
141
  break
136
142
 
137
143
  case 'closed':
@@ -152,19 +158,6 @@ export class WebRTCStream extends AbstractStream {
152
158
  // handle RTCDataChannel events
153
159
  this.channel.onopen = (_evt) => {
154
160
  this.timeline.open = new Date().getTime()
155
-
156
- if (this.messageQueue != null && this.messageQueue.byteLength > 0) {
157
- this.log.trace('dataChannel opened, sending queued messages', this.messageQueue.byteLength, this.channel.readyState)
158
-
159
- // send any queued messages
160
- this._sendMessage(this.messageQueue)
161
- .catch(err => {
162
- this.log.error('error sending queued messages', err)
163
- this.abort(err)
164
- })
165
- }
166
-
167
- this.messageQueue = undefined
168
161
  }
169
162
 
170
163
  this.channel.onclose = (_evt) => {
@@ -217,6 +210,7 @@ export class WebRTCStream extends AbstractStream {
217
210
  async _sendMessage (data: Uint8ArrayList, checkBuffer: boolean = true): Promise<void> {
218
211
  if (checkBuffer && this.channel.bufferedAmount > this.maxBufferedAmount) {
219
212
  try {
213
+ this.log('channel buffer is %d, wait for "bufferedamountlow" event', this.channel.bufferedAmount)
220
214
  await pEvent(this.channel, 'bufferedamountlow', { timeout: this.bufferedAmountLowEventTimeout })
221
215
  } catch (err: any) {
222
216
  if (err instanceof TimeoutError) {
@@ -231,22 +225,14 @@ export class WebRTCStream extends AbstractStream {
231
225
  throw new CodeError(`Invalid datachannel state - ${this.channel.readyState}`, 'ERR_INVALID_STATE')
232
226
  }
233
227
 
234
- if (this.channel.readyState === 'open') {
235
- // send message without copying data
236
- for (const buf of data) {
237
- this.channel.send(buf)
238
- }
239
- } else if (this.channel.readyState === 'connecting') {
240
- // queue message for when we are open
241
- if (this.messageQueue == null) {
242
- this.messageQueue = new Uint8ArrayList()
243
- }
244
-
245
- this.messageQueue.append(data)
246
- } else {
247
- this.log.error('unknown datachannel state %s', this.channel.readyState)
248
- throw new CodeError('Unknown datachannel state', 'ERR_INVALID_STATE')
228
+ if (this.channel.readyState !== 'open') {
229
+ this.log('channel state is "%s" and not "open", waiting for "open" event before sending data', this.channel.readyState)
230
+ await pEvent(this.channel, 'open', { timeout: this.openTimeout })
231
+ this.log('channel state is now "%s", sending data', this.channel.readyState)
249
232
  }
233
+
234
+ // send message without copying data
235
+ this.channel.send(data.subarray())
250
236
  }
251
237
 
252
238
  async sendData (data: Uint8ArrayList): Promise<void> {
@@ -341,7 +327,7 @@ export class WebRTCStream extends AbstractStream {
341
327
  // flags can be sent while we or the remote are closing the datachannel so
342
328
  // if the channel isn't open, don't try to send it but return false to let
343
329
  // the caller know and act if they need to
344
- this.log.trace('not sending flag %s because channel is not open', flag.toString())
330
+ this.log.trace('not sending flag %s because channel is "%s" and not "open"', this.channel.readyState, flag.toString())
345
331
  return false
346
332
  }
347
333
 
@@ -379,6 +365,8 @@ export interface WebRTCStreamOptions extends DataChannelOptions {
379
365
  * A callback invoked when the channel ends
380
366
  */
381
367
  onEnd?(err?: Error | undefined): void
368
+
369
+ logger: ComponentLogger
382
370
  }
383
371
 
384
372
  export function createStream (options: WebRTCStreamOptions): WebRTCStream {
@@ -386,7 +374,7 @@ export function createStream (options: WebRTCStreamOptions): WebRTCStream {
386
374
 
387
375
  return new WebRTCStream({
388
376
  id: direction === 'inbound' ? (`i${channel.id}`) : `r${channel.id}`,
389
- log: logger(`libp2p:webrtc:stream:${direction}:${channel.id}`),
377
+ log: options.logger.forComponent(`libp2p:webrtc:stream:${direction}:${channel.id}`),
390
378
  ...options
391
379
  })
392
380
  }
package/src/util.ts CHANGED
@@ -1,9 +1,7 @@
1
- import { logger } from '@libp2p/logger'
2
1
  import { detect } from 'detect-browser'
3
2
  import pDefer from 'p-defer'
4
3
  import pTimeout from 'p-timeout'
5
-
6
- const log = logger('libp2p:webrtc:utils')
4
+ import type { LoggerOptions } from '@libp2p/interface'
7
5
 
8
6
  const browser = detect()
9
7
  export const isFirefox = ((browser != null) && browser.name === 'firefox')
@@ -14,7 +12,7 @@ export const nopSink = async (_: any): Promise<void> => {}
14
12
 
15
13
  export const DATA_CHANNEL_DRAIN_TIMEOUT = 30 * 1000
16
14
 
17
- export function drainAndClose (channel: RTCDataChannel, direction: string, drainTimeout: number = DATA_CHANNEL_DRAIN_TIMEOUT): void {
15
+ export function drainAndClose (channel: RTCDataChannel, direction: string, drainTimeout: number = DATA_CHANNEL_DRAIN_TIMEOUT, options: LoggerOptions): void {
18
16
  if (channel.readyState !== 'open') {
19
17
  return
20
18
  }
@@ -23,7 +21,7 @@ export function drainAndClose (channel: RTCDataChannel, direction: string, drain
23
21
  .then(async () => {
24
22
  // wait for bufferedAmount to become zero
25
23
  if (channel.bufferedAmount > 0) {
26
- log('%s drain channel with %d buffered bytes', direction, channel.bufferedAmount)
24
+ options.log('%s drain channel with %d buffered bytes', direction, channel.bufferedAmount)
27
25
  const deferred = pDefer()
28
26
  let drained = false
29
27
 
@@ -31,7 +29,7 @@ export function drainAndClose (channel: RTCDataChannel, direction: string, drain
31
29
 
32
30
  const closeListener = (): void => {
33
31
  if (!drained) {
34
- log('%s drain channel closed before drain', direction)
32
+ options.log('%s drain channel closed before drain', direction)
35
33
  deferred.resolve()
36
34
  }
37
35
  }
@@ -58,7 +56,7 @@ export function drainAndClose (channel: RTCDataChannel, direction: string, drain
58
56
  }
59
57
  })
60
58
  .catch(err => {
61
- log.error('error closing outbound stream', err)
59
+ options.log.error('error closing outbound stream', err)
62
60
  })
63
61
  }
64
62