Skip to content

Commit

Permalink
chore(api): update protocol to allow specifying ranges in sync
Browse files Browse the repository at this point in the history
  • Loading branch information
heapwolf committed Jul 18, 2024
1 parent 0b9cb74 commit 8c35d17
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
5 changes: 3 additions & 2 deletions api/latica/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,8 @@ async function api (options = {}, events, dgram) {
ee._peer = peer

sub.peers.set(peer.peerId, ee)
if (!oldPeer || change) sub._emit('#join', ee, packet)
const isStateChange = !oldPeer || change
sub._emit('#join', ee, packet, isStateChange)
})

const handlePacket = async (packet, peer, port, address) => {
Expand All @@ -378,7 +379,7 @@ async function api (options = {}, events, dgram) {
bus._on('#packet', handlePacket)

bus._on('#disconnection', peer => {
for (const sub of bus.subclusters) {
for (const sub of [...bus.subclusters.values()]) {
sub._emit('#leave', peer)
sub.peers.delete(peer.peerId)
}
Expand Down
13 changes: 10 additions & 3 deletions api/latica/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1106,7 +1106,8 @@ export class Peer {

// if we are out of sync send our cache summary
const data = await Packet.encode(new PacketSync({
message: Cache.encodeSummary(summary)
message: Cache.encodeSummary(summary),
usr4: Buffer.from(String(Date.now()))
}))

this.send(data, rinfo.port, rinfo.address, peer.socket)
Expand Down Expand Up @@ -1157,7 +1158,12 @@ export class Peer {
*
*/
cachePredicate (packet) {
return packet.version === VERSION && packet.timestamp > Date.now() - Packet.ttl
if (packet.usr4.byteLength < 8 || packet.usr4.byteLength > 16) return

const timestamp = parseInt(Buffer.from(packet.usr4).toString(), 10)
const ts = Math.min(Packet.ttl, timestamp)

return packet.version === VERSION && ts > Date.now() - Packet.ttl
}

/**
Expand Down Expand Up @@ -1285,7 +1291,8 @@ export class Peer {
//
const nextLevel = await this.cache.summarize(local.prefix + i.toString(16), this.cachePredicate)
const data = await Packet.encode(new PacketSync({
message: Cache.encodeSummary(nextLevel)
message: Cache.encodeSummary(nextLevel),
usr4: Buffer.from(String(Date.now()))
}))
this.send(data, port, address)
}
Expand Down

0 comments on commit 8c35d17

Please sign in to comment.