Files
allmende/internal/p2p/peercache.go
T
nilsandClaude Sonnet 5.5 59973cbf43 p2p: peer exchange to find a region without the DHT, region-tagged peer cache, faster anti-entropy
A node with too few peers in a followed region asks its connected peers who they know there (sync kind "peers"); a peer answers even from another region, since gossip tells it which topics its connections subscribe to. Peers of the region are dialed, others only while the region has none. The peer cache records the regions a peer was seen in and a restart redials those first. Anti-entropy now runs every 10 minutes (plus or minus a fifth) with 3 peers per round instead of every 30 with one. Simulator: a newcomer whose remembered peers were all in another region got 0 of 114 listings with the seeds down, now 56 of 56; repair median at the same interval 25.9 s to 5.7 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-19 00:54:48 +01:00

230 lines
5.6 KiB
Go

package p2p
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
// The peer cache remembers who this node met, so after the first successful
// start it can find the network again without any bootstrap node.
const (
maxCachedPeers = 100
cachedPeerTTL = 30 * 24 * time.Hour
dialCachedMax = 10
rememberEvery = 5 * time.Minute
)
type cachedPeer struct {
ID string `json:"id"`
Addrs []string `json:"addrs"`
Seen int64 `json:"seen"` // unix seconds
// Regions are the regions this node followed when it saw that the peer
// subscribed to them, so a restart can redial the peers of its own regions
// first instead of only the most recent ones.
Regions []string `json:"regions,omitempty"`
}
// maxCachedRegions bounds the regions remembered per peer.
const maxCachedRegions = 8
type peerFile struct {
Peers []cachedPeer `json:"peers"`
}
// readPeerCache returns the usable entries, newest first. A missing, damaged or
// stale file is simply an empty cache: it is a convenience, never a requirement.
func readPeerCache(path string, now time.Time) []cachedPeer {
data, err := os.ReadFile(path)
if err != nil {
return nil
}
var f peerFile
if json.Unmarshal(data, &f) != nil {
return nil
}
var out []cachedPeer
for _, p := range f.Peers {
if _, err := peer.Decode(p.ID); err != nil || len(p.Addrs) == 0 {
continue
}
if now.Sub(time.Unix(p.Seen, 0)) > cachedPeerTTL {
continue
}
out = append(out, p)
}
sort.Slice(out, func(i, j int) bool { return out[i].Seen > out[j].Seen })
return out
}
func writePeerCache(path string, peers []cachedPeer) error {
sort.Slice(peers, func(i, j int) bool { return peers[i].Seen > peers[j].Seen })
if len(peers) > maxCachedPeers {
peers = peers[:maxCachedPeers]
}
data, err := json.MarshalIndent(peerFile{Peers: peers}, "", " ")
if err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(path), ".peers-*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
// orderForRedial puts the peers seen in one of regions first, keeping the
// order (newest first) within each group.
func orderForRedial(peers []cachedPeer, regions []string) {
slices.SortStableFunc(peers, func(a, b cachedPeer) int {
return boolInt(sharesRegion(b, regions)) - boolInt(sharesRegion(a, regions))
})
}
func sharesRegion(p cachedPeer, regions []string) bool {
for _, r := range p.Regions {
if slices.Contains(regions, r) {
return true
}
}
return false
}
func boolInt(b bool) int {
if b {
return 1
}
return 0
}
// directAddrs keeps the addresses worth remembering: not relayed, which only
// work while that relay does, and not unspecified.
func directAddrs(addrs []ma.Multiaddr) []string {
var out []string
for _, a := range addrs {
if strings.Contains(a.String(), "/p2p-circuit") {
continue
}
out = append(out, a.String())
}
return out
}
// rememberPeers records the currently connected peers in the cache file.
func (n *Node) rememberPeers() {
if n.cfg.PeerCache == "" {
return
}
now := n.clock()
byID := map[string]cachedPeer{}
for _, p := range readPeerCache(n.cfg.PeerCache, now) {
byID[p.ID] = p
}
inRegion := map[peer.ID][]string{}
for _, r := range n.Regions() {
for _, p := range n.RegionPeers(r) {
inRegion[p] = append(inRegion[p], r)
}
}
for _, id := range n.host.Network().Peers() {
addrs := directAddrs(n.host.Peerstore().Addrs(id))
if len(addrs) == 0 {
continue
}
regions := byID[id.String()].Regions
for _, r := range inRegion[id] {
if !slices.Contains(regions, r) {
regions = append(regions, r)
}
}
if len(regions) > maxCachedRegions {
regions = regions[len(regions)-maxCachedRegions:]
}
byID[id.String()] = cachedPeer{ID: id.String(), Addrs: addrs, Seen: now.Unix(), Regions: regions}
}
list := make([]cachedPeer, 0, len(byID))
for _, p := range byID {
list = append(list, p)
}
if err := writePeerCache(n.cfg.PeerCache, list); err != nil {
n.log.Warn("could not save known peers", "err", err)
}
}
// remember saves the known peers now and then, and once more on the way out.
func (n *Node) remember() {
defer n.wg.Done()
if n.cfg.PeerCache == "" {
return
}
t := time.NewTicker(rememberEvery)
defer t.Stop()
for {
select {
case <-n.ctx.Done():
n.rememberPeers()
return
case <-t.C:
n.rememberPeers()
}
}
}
// dialCached reconnects to the peers met on earlier runs.
func (n *Node) dialCached() {
if n.cfg.PeerCache == "" {
return
}
var wg sync.WaitGroup
dialed := 0
cached := readPeerCache(n.cfg.PeerCache, n.clock())
// Peers seen in a region we follow come first (the newest of each group first,
// as the file is sorted), then the rest.
orderForRedial(cached, n.Regions())
for _, p := range cached {
if dialed == dialCachedMax {
break
}
id, err := peer.Decode(p.ID)
if err != nil || id == n.host.ID() || n.host.Network().Connectedness(id) == network.Connected {
continue
}
ai := peer.AddrInfo{ID: id}
for _, a := range p.Addrs {
if m, err := ma.NewMultiaddr(a); err == nil {
ai.Addrs = append(ai.Addrs, m)
}
}
dialed++
wg.Add(1)
go func() {
defer wg.Done()
ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second)
defer cancel()
if err := n.host.Connect(ctx, ai); err != nil && !errors.Is(err, context.Canceled) {
n.log.Debug("remembered peer unreachable", "peer", ai.ID, "err", err)
}
}()
}
wg.Wait()
}