Files: 1802ce94b0eb0903cc5f9dd7e00aed245b4f124b / lib / detect-sync.js
1335 bytesRaw
1 | module.exports = function detectSync (peerId, upto, toSend, peerHas, onSync) { |
2 | // HACK: createHistoryStream does not emit sync event, so we don't |
3 | // know when it switches to live. Do it manually! |
4 | |
5 | var sync = false |
6 | var last = (upto.sequence || upto.seq || 0) |
7 | |
8 | // check sync after 500ms, hopefully we have the info from the peer by then |
9 | setTimeout(function () { |
10 | if (peerHas[peerId] && peerHas[peerId][upto.id] != null) { |
11 | checkSync() |
12 | } else { |
13 | // if we get here, the peer hasn't yet asked for this feed, or is not responding |
14 | // we can assume it doesn't have the feed, so lets call sync |
15 | broadcastSync() |
16 | } |
17 | }, 500) |
18 | |
19 | return function (msg) { |
20 | if (msg.sync) { |
21 | // surprise! This peer actually has a sync event! |
22 | broadcastSync() |
23 | return false |
24 | } |
25 | |
26 | last = msg.sequence |
27 | checkSync() |
28 | return true |
29 | } |
30 | |
31 | function checkSync () { |
32 | if (!sync) { |
33 | var availableSeq = peerHas[peerId] && peerHas[peerId][upto.id] |
34 | if (availableSeq === last || availableSeq < toSend[upto.id]) { |
35 | // we've reached the maximum sequence this server has told us it knows about |
36 | // or we don't need anything from this server |
37 | broadcastSync() |
38 | } |
39 | } |
40 | } |
41 | |
42 | function broadcastSync () { |
43 | if (!sync) { |
44 | sync = true |
45 | onSync && onSync() |
46 | } |
47 | } |
48 | } |
49 |
Built with git-ssb-web