Files
nilsandClaude Sonnet 5.5 fd439710df Let the owner change regions by place name, without a restart
The p2p node can now add and drop regions while running (SetRegions):
topics, validators, subscriptions and per-region peer discovery start and
stop with them, and a newly followed region catches up by sync.

PUT /api/v1/regions (owner token) applies a change and the node saves it in
regions.json, which wins over --region from then on. The owner's browser
gets a "Regions" page: search a place by name (GeoNames cities, offline,
CC BY 4.0), follow its cell plus any cell within about 40 km.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-18 10:28:16 +01:00

180 lines
4.9 KiB
Go

package p2p
import (
"context"
"errors"
"sync"
"time"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p/core/discovery"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing"
)
const (
// dhtProtocolPrefix keeps this network's DHT apart from every other one
// (the IPFS DHT included): the protocol is /allmende/kad/1.0.0.
dhtProtocolPrefix = "/allmende"
// regionNamespace is what nodes advertise and look up, one per region.
regionNamespace = "allmende/region/"
defaultDiscoverInterval = time.Minute
// enoughRegionPeers: with this many peers on a region's topic there is no
// need to look for more.
enoughRegionPeers = 8
findLimit = 20
)
// startDiscovery joins the DHT and, for every region this node follows,
// advertises the node and looks for others. Bootstrap nodes only seed the
// routing table; once a node knows a few peers it no longer depends on them.
func (n *Node) startDiscovery() error {
mode := dht.ModeAuto // a server once AutoNAT finds this node publicly reachable
if n.cfg.Public {
mode = dht.ModeServer
}
d, err := dht.New(n.host, dht.ProtocolPrefix(dhtProtocolPrefix), dht.Mode(mode))
if err != nil {
return err
}
n.dht = d
rd := drouting.NewRoutingDiscovery(d)
n.mu.Lock()
n.rd = rd
runs := make(map[string]*regionRun, len(n.regions))
for r, run := range n.regions {
runs[r] = run
}
n.mu.Unlock()
for r, run := range runs {
n.discoverRegion(run.ctx, rd, r)
}
return nil
}
// discoverRegion advertises this node under the region and looks for others,
// until ctx ends (the region is dropped or the node stops).
func (n *Node) discoverRegion(ctx context.Context, rd *drouting.RoutingDiscovery, region string) {
ns := regionNamespace + region
n.wg.Add(2)
go n.advertise(ctx, rd, ns)
go n.findPeers(ctx, rd, region, ns)
}
func (n *Node) discoverInterval() time.Duration {
if n.cfg.DiscoverInterval > 0 {
return n.cfg.DiscoverInterval
}
return defaultDiscoverInterval
}
// sleep waits for d or until the node stops; false means it stopped.
func (n *Node) sleep(d time.Duration) bool { return sleepCtx(n.ctx, d) }
// sleepCtx waits for d or until ctx ends; false means it ended.
func sleepCtx(ctx context.Context, d time.Duration) bool {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return false
case <-t.C:
return true
}
}
// advertise keeps this node findable under the region's name. Until the
// routing table has a peer in it there is nowhere to publish, so it retries.
func (n *Node) advertise(rctx context.Context, rd *drouting.RoutingDiscovery, ns string) {
defer n.wg.Done()
back := n.backoff()
for {
wait := back.next()
ctx, cancel := context.WithTimeout(rctx, 30*time.Second)
ttl, err := rd.Advertise(ctx, ns)
cancel()
switch {
case rctx.Err() != nil:
return
case err != nil:
n.log.Debug("advertise", "ns", ns, "err", err) // retried soon, then less often
back.bump()
case ttl > 0:
wait = ttl * 3 / 4 // refresh before the record lapses
back.reset()
}
if !sleepCtx(rctx, wait) {
return
}
}
}
// backoff paces retries: quick at first, because a fresh node needs its first
// peers now, then settling on the regular interval.
type backoff struct{ cur, max time.Duration }
func (n *Node) backoff() *backoff {
max := n.discoverInterval()
first := 2 * time.Second
if first > max {
first = max
}
return &backoff{cur: first, max: max}
}
func (b *backoff) next() time.Duration { return b.cur }
func (b *backoff) reset() { b.cur = b.max }
// bump doubles the wait up to the limit.
func (b *backoff) bump() {
if b.cur *= 2; b.cur > b.max {
b.cur = b.max
}
}
// findPeers connects to other nodes of the region that the DHT knows.
func (n *Node) findPeers(rctx context.Context, rd *drouting.RoutingDiscovery, region, ns string) {
defer n.wg.Done()
back := n.backoff()
for {
if !sleepCtx(rctx, back.next()) {
return
}
back.bump()
if len(n.RegionPeers(region)) >= enoughRegionPeers {
continue
}
ctx, cancel := context.WithTimeout(rctx, 30*time.Second)
found, err := rd.FindPeers(ctx, ns, discovery.Limit(findLimit))
if err != nil {
cancel()
if rctx.Err() == nil {
n.log.Debug("find peers", "ns", ns, "err", err)
}
continue
}
var wg sync.WaitGroup
for ai := range found {
if ai.ID == n.host.ID() || len(ai.Addrs) == 0 || n.host.Network().Connectedness(ai.ID) == network.Connected {
continue
}
wg.Add(1)
go func(ai peer.AddrInfo) {
defer wg.Done()
cctx, ccancel := context.WithTimeout(ctx, 10*time.Second)
defer ccancel()
if err := n.host.Connect(cctx, ai); err != nil && !errors.Is(err, context.Canceled) {
n.log.Debug("discovered peer unreachable", "peer", ai.ID, "err", err)
} else if err == nil {
n.log.Debug("found a peer through the DHT", "peer", ai.ID, "region", region)
}
}(ai)
}
wg.Wait()
cancel()
}
}