This repository has been archived by the owner on Jun 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
maconn.ts
85 lines (70 loc) · 2.32 KB
/
maconn.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { logger } from '@libp2p/logger'
import { nopSink, nopSource } from './util.js'
import type { MultiaddrConnection, MultiaddrConnectionTimeline } from '@libp2p/interface-connection'
import type { CounterGroup } from '@libp2p/interface-metrics'
import type { Multiaddr } from '@multiformats/multiaddr'
import type { Source, Sink } from 'it-stream-types'
const log = logger('libp2p:webrtc:connection')
interface WebRTCMultiaddrConnectionInit {
/**
* WebRTC Peer Connection
*/
peerConnection: RTCPeerConnection
/**
* The multiaddr address used to communicate with the remote peer
*/
remoteAddr: Multiaddr
/**
* Holds the relevant events timestamps of the connection
*/
timeline: MultiaddrConnectionTimeline
/**
* Optional metrics counter group for this connection
*/
metrics?: CounterGroup
}
export class WebRTCMultiaddrConnection implements MultiaddrConnection {
/**
* WebRTC Peer Connection
*/
readonly peerConnection: RTCPeerConnection
/**
* The multiaddr address used to communicate with the remote peer
*/
remoteAddr: Multiaddr
/**
* Holds the lifecycle times of the connection
*/
timeline: MultiaddrConnectionTimeline
/**
* Optional metrics counter group for this connection
*/
metrics?: CounterGroup
/**
* The stream source, a no-op as the transport natively supports multiplexing
*/
source: AsyncGenerator<Uint8Array, any, unknown> = nopSource()
/**
* The stream destination, a no-op as the transport natively supports multiplexing
*/
sink: Sink<Source<Uint8Array>, Promise<void>> = nopSink
constructor (init: WebRTCMultiaddrConnectionInit) {
this.remoteAddr = init.remoteAddr
this.timeline = init.timeline
this.peerConnection = init.peerConnection
this.peerConnection.onconnectionstatechange = () => {
if (this.peerConnection.connectionState === 'closed' || this.peerConnection.connectionState === 'disconnected' || this.peerConnection.connectionState === 'failed') {
this.timeline.close = Date.now()
}
}
}
async close (err?: Error | undefined): Promise<void> {
if (err !== undefined) {
log.error('error closing connection', err)
}
log.trace('closing connection')
this.timeline.close = Date.now()
this.peerConnection.close()
this.metrics?.increment({ close: true })
}
}