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
This commit is contained in:
+31
-15
@@ -41,15 +41,28 @@ func (n *Node) startDiscovery() error {
|
||||
}
|
||||
n.dht = d
|
||||
rd := drouting.NewRoutingDiscovery(d)
|
||||
for _, r := range n.cfg.Regions {
|
||||
ns := regionNamespace + r
|
||||
n.wg.Add(2)
|
||||
go n.advertise(rd, ns)
|
||||
go n.findPeers(rd, r, ns)
|
||||
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
|
||||
@@ -58,11 +71,14 @@ func (n *Node) discoverInterval() time.Duration {
|
||||
}
|
||||
|
||||
// sleep waits for d or until the node stops; false means it stopped.
|
||||
func (n *Node) sleep(d time.Duration) bool {
|
||||
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 <-n.ctx.Done():
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
@@ -71,16 +87,16 @@ func (n *Node) sleep(d time.Duration) bool {
|
||||
|
||||
// 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(rd *drouting.RoutingDiscovery, ns string) {
|
||||
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(n.ctx, 30*time.Second)
|
||||
ctx, cancel := context.WithTimeout(rctx, 30*time.Second)
|
||||
ttl, err := rd.Advertise(ctx, ns)
|
||||
cancel()
|
||||
switch {
|
||||
case n.ctx.Err() != nil:
|
||||
case rctx.Err() != nil:
|
||||
return
|
||||
case err != nil:
|
||||
n.log.Debug("advertise", "ns", ns, "err", err) // retried soon, then less often
|
||||
@@ -89,7 +105,7 @@ func (n *Node) advertise(rd *drouting.RoutingDiscovery, ns string) {
|
||||
wait = ttl * 3 / 4 // refresh before the record lapses
|
||||
back.reset()
|
||||
}
|
||||
if !n.sleep(wait) {
|
||||
if !sleepCtx(rctx, wait) {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -120,22 +136,22 @@ func (b *backoff) bump() {
|
||||
}
|
||||
|
||||
// findPeers connects to other nodes of the region that the DHT knows.
|
||||
func (n *Node) findPeers(rd *drouting.RoutingDiscovery, region, ns string) {
|
||||
func (n *Node) findPeers(rctx context.Context, rd *drouting.RoutingDiscovery, region, ns string) {
|
||||
defer n.wg.Done()
|
||||
back := n.backoff()
|
||||
for {
|
||||
if !n.sleep(back.next()) {
|
||||
if !sleepCtx(rctx, back.next()) {
|
||||
return
|
||||
}
|
||||
back.bump()
|
||||
if len(n.RegionPeers(region)) >= enoughRegionPeers {
|
||||
continue
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(n.ctx, 30*time.Second)
|
||||
ctx, cancel := context.WithTimeout(rctx, 30*time.Second)
|
||||
found, err := rd.FindPeers(ctx, ns, discovery.Limit(findLimit))
|
||||
if err != nil {
|
||||
cancel()
|
||||
if n.ctx.Err() == nil {
|
||||
if rctx.Err() == nil {
|
||||
n.log.Debug("find peers", "ns", ns, "err", err)
|
||||
}
|
||||
continue
|
||||
|
||||
+105
-5
@@ -17,6 +17,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -28,6 +29,7 @@ import (
|
||||
"github.com/libp2p/go-libp2p/core/network"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/p2p/discovery/mdns"
|
||||
drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing"
|
||||
"github.com/libp2p/go-libp2p/p2p/host/autorelay"
|
||||
madns "github.com/multiformats/go-multiaddr-dns"
|
||||
|
||||
@@ -104,6 +106,8 @@ type Node struct {
|
||||
topics map[string]*pubsub.Topic
|
||||
msgTopics map[string]*pubsub.Topic
|
||||
subscribed []string
|
||||
regions map[string]*regionRun
|
||||
rd *drouting.RoutingDiscovery // nil without a DHT
|
||||
boot *bootstrapper
|
||||
dht *dht.IpfsDHT
|
||||
syncing map[peer.ID]bool
|
||||
@@ -184,6 +188,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
|
||||
cancel: cancel,
|
||||
topics: map[string]*pubsub.Topic{},
|
||||
msgTopics: map[string]*pubsub.Topic{},
|
||||
regions: map[string]*regionRun{},
|
||||
syncing: map[peer.ID]bool{},
|
||||
boot: boot,
|
||||
}
|
||||
@@ -356,7 +361,7 @@ func (n *Node) startRevocations() error {
|
||||
n.wg.Add(1)
|
||||
go func() {
|
||||
defer n.wg.Done()
|
||||
n.consume(sub, func(msg *pubsub.Message) {
|
||||
n.consume(n.ctx, sub, func(msg *pubsub.Message) {
|
||||
r, ok := msg.ValidatorData.(*identity.Revocation)
|
||||
if !ok {
|
||||
return
|
||||
@@ -369,6 +374,90 @@ func (n *Node) startRevocations() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// regionRun is what a followed region keeps running; dropping the region stops it.
|
||||
type regionRun struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
subs []*pubsub.Subscription
|
||||
}
|
||||
|
||||
// Regions lists the regions this node follows now, in the order they were added.
|
||||
func (n *Node) Regions() []string {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return append([]string(nil), n.subscribed...)
|
||||
}
|
||||
|
||||
// SetRegions makes the node follow exactly these regions, without a restart:
|
||||
// new ones are joined (and peers looked for), dropped ones are left. Listings
|
||||
// already stored stay stored. Nothing changes if a region is invalid.
|
||||
func (n *Node) SetRegions(regions []string) error {
|
||||
want := make([]string, 0, len(regions))
|
||||
for _, r := range regions {
|
||||
if !listing.ValidRegion(r) {
|
||||
return fmt.Errorf("p2p: invalid region %q (want %d geohash characters)", r, listing.RegionPrecision)
|
||||
}
|
||||
if !slices.Contains(want, r) {
|
||||
want = append(want, r)
|
||||
}
|
||||
}
|
||||
have := n.Regions()
|
||||
added := false
|
||||
for _, r := range want {
|
||||
if !slices.Contains(have, r) {
|
||||
if err := n.subscribeRegion(r); err != nil {
|
||||
return err
|
||||
}
|
||||
added = true
|
||||
}
|
||||
}
|
||||
if added {
|
||||
// What was published before is not gossiped again: ask the peers we
|
||||
// already know for what they hold in the new regions.
|
||||
for _, p := range n.host.Network().Peers() {
|
||||
n.syncSoon(p)
|
||||
}
|
||||
}
|
||||
for _, r := range have {
|
||||
if !slices.Contains(want, r) {
|
||||
n.unsubscribeRegion(r)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *Node) unsubscribeRegion(region string) {
|
||||
n.mu.Lock()
|
||||
run := n.regions[region]
|
||||
delete(n.regions, region)
|
||||
n.subscribed = slices.DeleteFunc(n.subscribed, func(r string) bool { return r == region })
|
||||
listings, messages := n.topics[region], n.msgTopics[region]
|
||||
delete(n.topics, region)
|
||||
delete(n.msgTopics, region)
|
||||
n.mu.Unlock()
|
||||
if run == nil {
|
||||
return
|
||||
}
|
||||
run.cancel()
|
||||
for _, s := range run.subs {
|
||||
s.Cancel()
|
||||
}
|
||||
for name, t := range map[string]*pubsub.Topic{
|
||||
listingTopicPrefix + region: listings,
|
||||
messageTopicPrefix + region: messages,
|
||||
} {
|
||||
if t == nil {
|
||||
continue
|
||||
}
|
||||
if err := t.Close(); err != nil {
|
||||
n.log.Debug("leave topic", "topic", name, "err", err)
|
||||
}
|
||||
if err := n.ps.UnregisterTopicValidator(name); err != nil {
|
||||
n.log.Debug("remove validator", "topic", name, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) subscribeRegion(region string) error {
|
||||
t, err := n.regionTopic(region)
|
||||
if err != nil {
|
||||
@@ -378,13 +467,20 @@ func (n *Node) subscribeRegion(region string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rctx, cancel := context.WithCancel(n.ctx)
|
||||
run := ®ionRun{ctx: rctx, cancel: cancel, subs: []*pubsub.Subscription{sub}}
|
||||
n.mu.Lock()
|
||||
n.subscribed = append(n.subscribed, region)
|
||||
n.regions[region] = run
|
||||
rd := n.rd
|
||||
n.mu.Unlock()
|
||||
if rd != nil {
|
||||
n.discoverRegion(rctx, rd, region)
|
||||
}
|
||||
n.wg.Add(1)
|
||||
go func() {
|
||||
defer n.wg.Done()
|
||||
n.consume(sub, func(msg *pubsub.Message) {
|
||||
n.consume(rctx, sub, func(msg *pubsub.Message) {
|
||||
l, ok := msg.ValidatorData.(*listing.Listing)
|
||||
if !ok {
|
||||
return
|
||||
@@ -405,10 +501,13 @@ func (n *Node) subscribeRegion(region string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n.mu.Lock()
|
||||
run.subs = append(run.subs, msub)
|
||||
n.mu.Unlock()
|
||||
n.wg.Add(1)
|
||||
go func() {
|
||||
defer n.wg.Done()
|
||||
n.consume(msub, func(msg *pubsub.Message) {
|
||||
n.consume(rctx, msub, func(msg *pubsub.Message) {
|
||||
e, ok := msg.ValidatorData.(*message.Envelope)
|
||||
if !ok {
|
||||
return
|
||||
@@ -469,9 +568,10 @@ func (n *Node) regionTopic(region string) (*pubsub.Topic, error) {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (n *Node) consume(sub *pubsub.Subscription, handle func(*pubsub.Message)) {
|
||||
// consume handles what arrives on sub until ctx ends or the subscription is cancelled.
|
||||
func (n *Node) consume(ctx context.Context, sub *pubsub.Subscription, handle func(*pubsub.Message)) {
|
||||
for {
|
||||
msg, err := sub.Next(n.ctx)
|
||||
msg, err := sub.Next(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -324,3 +324,64 @@ func TestBadBootstrapAddressRejectedUpFront(t *testing.T) {
|
||||
t.Fatal("malformed bootstrap address accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegionsChangeWhileRunning(t *testing.T) {
|
||||
a := startNode(t, nil, "u1x")
|
||||
b := startNode(t, nil, "u30")
|
||||
connect(t, b, a)
|
||||
|
||||
first := a.listing(t, "u1xjhx")
|
||||
if err := a.Publish(context.Background(), first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
if count(b) != 0 {
|
||||
t.Fatal("b received a listing of a region it does not follow")
|
||||
}
|
||||
|
||||
// Following u1x as well: what was published before arrives by sync, what
|
||||
// is published from now on by gossip.
|
||||
if err := b.SetRegions([]string{"u30", "u1x", "u1x"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := b.Regions(); len(got) != 2 || got[0] != "u30" || got[1] != "u1x" {
|
||||
t.Fatalf("regions = %v", got)
|
||||
}
|
||||
eventually(t, "b catches up on u1x", func() bool { return count(b) == 1 })
|
||||
eventually(t, "a sees b on the u1x topic", func() bool { return len(a.RegionPeers("u1x")) == 1 })
|
||||
if err := a.Publish(context.Background(), a.listing(t, "u1xjhy")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, "b receives gossip of the new region", func() bool { return count(b) == 2 })
|
||||
|
||||
// Dropping it again: b leaves the topic, nothing more arrives, and what
|
||||
// was stored stays.
|
||||
if err := b.SetRegions([]string{"u30"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := b.Regions(); len(got) != 1 || got[0] != "u30" {
|
||||
t.Fatalf("regions = %v", got)
|
||||
}
|
||||
eventually(t, "a no longer sees b on u1x", func() bool { return len(a.RegionPeers("u1x")) == 0 })
|
||||
if err := a.Publish(context.Background(), a.listing(t, "u1xjhz")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
if count(b) != 2 {
|
||||
t.Fatalf("b has %d listings, want the 2 it had", count(b))
|
||||
}
|
||||
|
||||
// And back: the region can be followed again.
|
||||
if err := b.SetRegions([]string{"u30", "u1x"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, "b follows u1x again and catches up", func() bool { return count(b) == 3 })
|
||||
|
||||
// Nothing changes on a bad region.
|
||||
if err := b.SetRegions([]string{"u1x", "no"}); err == nil {
|
||||
t.Fatal("an invalid region was accepted")
|
||||
}
|
||||
if got := b.Regions(); len(got) != 2 {
|
||||
t.Fatalf("regions changed to %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user