Re-establish WebRTC connection if stalled
Sometimes, the WebRTC connection might be lost during an initial sync, in which case we'd like to re-establish the connection over the signalling channel.
At the beginning of a Sync, both ends create a SignalTransport (the sender when creating the QR code, the receiver when scanning the QR code): https://github.com/WorldBrain/storex-sync/blob/develop/ts/integration/initial-sync.ts#L69
This SignalTransport can send and receive signalling messages, which is used to set up a SimplePeer, which is a wrapper around WebRTC: https://github.com/WorldBrain/storex-sync/blob/develop/ts/integration/initial-sync.ts#L314 https://github.com/WorldBrain/simple-signalling/blob/master/ts/simple-peer.ts#L18
The SignalTransport is Firebase and in case we lose the WebRTC connection, it could be we can still send messages over there. So, if one side detects we don't have a connection anymore, it should:
- try to send a message over there to tell the other side we're going to re-establish the connection
- wait for a confirmation (another message being sent from the other side)\
- call signalSimplePeer() again with a new SimplePeer instance.
When you call signalSimplePeer(), it immediately starts to listen for new signal messages and send new signal messages. You need to be careful for a race condition there, were one peer might start sending messages before the other one is listening. This might be solved by a buffer at both ends, so signals do not get lost if nobody's listening.
The WebRTCFastSyncChannnel now takes a SimplePeer in it's constructor and uses that one for the entire sync: https://github.com/WorldBrain/storex-sync/blob/develop/ts/fast-sync/channels.ts#L157
You could make it accept an additional parameter, reEstablishConnection: () => Promise<SimplePeer> which it can call to replace the SimplePeer it's using.
About detecting when the connection is down, you can use either the stalled event we already detect, or look into this:
https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/oniceconnectionstatechange