MCPcopy Create free account
hub / github.com/ambianic/peerfetch / _setPeerConnectionHandlers

Method _setPeerConnectionHandlers

javascript/src/peerfetch.ts:211–331  ·  view source on GitHub ↗
(peerConnection: Peer.DataConnection, setupResolve: Function, setupReject: Function)

Source from the content-addressed store, hash-verified

209 }
210
211 private _setPeerConnectionHandlers (peerConnection: Peer.DataConnection, setupResolve: Function, setupReject: Function) {
212 // isSetupResolved indicates whether the setupReady promise has been resolved or rejected
213 // to ensure that we resolve/reject the promise only once.
214 let isSetupResolved = false
215
216 // setup connection progress callbacks
217 peerConnection.on('open', () => {
218 this._peerConnectionStatus = ConnectionStatus.CONNECTED
219 this._dataConnection = peerConnection
220 // Map of pending requests awaiting responses
221 this._requestMap = new Map()
222 // incrementing counter to the next available
223 // unused ticket number
224 // Each request is assigned a ticket
225 // which can be used to claim the response
226 this._nextAvailableTicket = 0
227 // points to the next ticket assigned to a pending request
228 // Requests are processed in FIFO order.
229 this._nextTicketInLine = 0
230 console.debug('Peer DataConnection is now open.', { peerConnection })
231 // Now that a peer connection is established,
232 // we can resolve the PeerFetch setup() promise
233 isSetupResolved = true
234 // Add artificial delay as a workaround for a timing issue with dataconnection open.
235 // It needs a moment to be come available after is signals 'open' state.
236 setTimeout( () => {
237 setupResolve()
238 // schedule keepalive pings to prevent
239 // routers from closing the NAT holes during persiod of inactivity
240 // between peerfetch requests.
241 this._schedulePing()
242 }, 1000)
243 })
244
245 peerConnection.on('close', () => {
246 this._peerConnectionStatus = ConnectionStatus.DISCONNECTED
247 const msg = 'Peer DataConnection closed.'
248 console.debug(msg)
249 // if PeerFetch setup() promise has not been resolved yet,
250 // then throw an exception to notify any app code awaiting resolution.
251 if (!isSetupResolved) {
252 isSetupResolved = true
253 setupReject(new Error(msg))
254 }
255 console.debug('Peer connection is now closed.')
256 this._stopPing()
257 })
258
259 peerConnection.on('error', (err) => {
260 this._peerConnectionStatus = ConnectionStatus.ERROR
261 const msg = 'Error in connection to remote peer ID: ' + peerConnection.peer
262 console.debug(msg)
263 if (!isSetupResolved) {
264 isSetupResolved = true
265 setupReject(new Error(msg))
266 }
267 })
268

Calls 4

_schedulePingMethod · 0.95
_stopPingMethod · 0.95
jsonifyMethod · 0.95
getMethod · 0.80

Tested by

no test coverage detected