-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdetect-sync.js
53 lines (46 loc) · 1.38 KB
/
detect-sync.js
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
module.exports = function detectSync (peerId, upto, toSend, peerHas, onSync) {
// HACK: createHistoryStream does not emit sync event, so we don't
// know when it switches to live. Do it manually!
let sync = false
let last = (upto.sequence || upto.seq || 0)
// check sync after 500ms, hopefully we have the info from the peer by then
setTimeout(function () {
if (peerHas[peerId] && peerHas[peerId][upto.id] != null) {
checkSync()
} else {
// if we get here, the peer hasn't yet asked for this feed, or is not responding
// we can assume it doesn't have the feed, so lets call sync
broadcastSync()
}
}, 500)
return function (msg) {
if (!msg) {
// throw new Error("wat")
return false
}
if (msg.sync) {
// surprise! This peer actually has a sync event!
broadcastSync()
return false
}
last = msg.sequence
checkSync()
return true
}
function checkSync () {
if (!sync) {
const availableSeq = peerHas[peerId] && peerHas[peerId][upto.id]
if (availableSeq === last || availableSeq < toSend[upto.id]) {
// we've reached the maximum sequence this server has told us it knows about
// or we don't need anything from this server
broadcastSync()
}
}
}
function broadcastSync () {
if (!sync) {
sync = true
onSync && onSync()
}
}
}