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:
2026-11-18 10:28:16 +01:00
co-authored by Claude Sonnet 5.5
parent e7bec4fb63
commit fd439710df
24 changed files with 70080 additions and 42 deletions
+60 -1
View File
@@ -14,6 +14,7 @@ import (
"fmt"
"io"
"net/http"
"slices"
"strconv"
"strings"
"time"
@@ -49,6 +50,26 @@ type Config struct {
// Inbox is the owner's conversations. Without it the owner endpoints are
// absent; relaying messages for buyers still works.
Inbox *inbox.Inbox
// RegionKeeper lets the owner change the regions the node follows while it
// runs. Without it Regions is fixed and the endpoint is absent.
RegionKeeper RegionKeeper
}
// RegionKeeper holds the regions a node follows: it applies and remembers a change.
type RegionKeeper interface {
Regions() []string
SetRegions([]string) error
}
// MaxRegions is how many regions one node may follow: it replicates everything
// in them, so this keeps "follow the world" from being one click.
const MaxRegions = 20
func (s *server) regions() []string {
if s.RegionKeeper != nil {
return s.RegionKeeper.Regions()
}
return s.Regions
}
type server struct {
@@ -72,6 +93,9 @@ func New(cfg Config) http.Handler {
mux.HandleFunc("POST /api/v1/listings", s.admin(s.create))
mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update))
mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove))
if cfg.RegionKeeper != nil {
mux.HandleFunc("PUT /api/v1/regions", s.admin(s.putRegions))
}
// Messaging: public relay endpoints for buyers' browsers...
mux.HandleFunc("POST /api/v1/messages", s.postMessage)
@@ -131,7 +155,7 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
"addrs": s.Node.Addrs(),
"author": s.Device.Cert.Author,
"device": s.Device.Cert.Device,
"regions": s.Regions,
"regions": s.regions(),
"peers": s.Node.PeerCount(),
"listings": n,
// Lets the browser report how much anti-spam work a listing carries.
@@ -266,6 +290,41 @@ func (s *server) admin(next http.HandlerFunc) http.HandlerFunc {
}
}
// putRegions changes the regions the node follows, at once and for good.
func (s *server) putRegions(w http.ResponseWriter, r *http.Request) {
var body struct {
Regions []string `json:"regions"`
}
if !decodeBody(w, r, &body) {
return
}
var regions []string
for _, raw := range body.Regions {
region := strings.ToLower(strings.TrimSpace(raw))
if !listing.ValidRegion(region) {
fail(w, http.StatusBadRequest, fmt.Sprintf(
"%q is not a region: use %d geohash characters, e.g. u1j for Bonn", raw, listing.RegionPrecision))
return
}
if !slices.Contains(regions, region) {
regions = append(regions, region)
}
}
switch {
case len(regions) == 0:
fail(w, http.StatusBadRequest, "choose at least one region")
return
case len(regions) > MaxRegions:
fail(w, http.StatusBadRequest, fmt.Sprintf("that is too many regions (at most %d)", MaxRegions))
return
}
if err := s.RegionKeeper.SetRegions(regions); err != nil {
fail(w, http.StatusInternalServerError, "could not change the regions: "+err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"regions": s.RegionKeeper.Regions()})
}
func (s *server) readDraft(w http.ResponseWriter, r *http.Request) (*draft, bool) {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody))
dec.DisallowUnknownFields()
+73
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
@@ -300,3 +301,75 @@ func TestStatus(t *testing.T) {
t.Fatal("status must never expose the admin token")
}
}
// keeper is a RegionKeeper that follows the node's real regions.
type keeper struct {
node *p2p.Node
fail error
}
func (k *keeper) Regions() []string { return k.node.Regions() }
func (k *keeper) SetRegions(r []string) error {
if k.fail != nil {
return k.fail
}
return k.node.SetRegions(r)
}
func TestOwnerChangesTheRegions(t *testing.T) {
k := &keeper{}
f := newFixture(t, token, func(c *Config) {
k.node = c.Node
c.RegionKeeper = k
})
regions := func() []string {
_, body := f.do(t, "GET", "/api/v1/status", "", false)
var st struct {
Regions []string `json:"regions"`
}
_ = json.Unmarshal(body, &st)
return st.Regions
}
if got := regions(); len(got) != 1 || got[0] != "u1x" {
t.Fatalf("regions = %v", got)
}
if code, _ := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, false); code != 401 {
t.Fatalf("without the token: %d, want 401", code)
}
code, body := f.do(t, "PUT", "/api/v1/regions", `{"regions":[" U1J ","u1x","u1j"]}`, true)
if code != 200 {
t.Fatalf("PUT: %d %s", code, body)
}
if got := regions(); len(got) != 2 || got[0] != "u1x" || got[1] != "u1j" {
t.Fatalf("regions after the change (case and repeats tidied) = %v", got)
}
for name, tc := range map[string]struct{ body, want string }{
"not a region": {`{"regions":["u1j","nope"]}`, "not a region"},
"none": {`{"regions":[]}`, "at least one"},
"unknown field": {`{"regions":["u1j"],"x":1}`, "invalid JSON"},
"too many": {`{"regions":["u00","u01","u02","u03","u04","u05","u06","u07","u08","u09","u0b",` +
`"u0c","u0d","u0e","u0f","u0g","u0h","u0j","u0k","u0m","u0n"]}`, "too many"},
} {
code, body := f.do(t, "PUT", "/api/v1/regions", tc.body, true)
if code != 400 || !strings.Contains(string(body), tc.want) {
t.Errorf("%s: %d %s, want 400 containing %q", name, code, body, tc.want)
}
}
if got := regions(); len(got) != 2 {
t.Fatalf("a refused change must change nothing, regions = %v", got)
}
k.fail = errors.New("disk full")
if code, body := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, true); code != 500 || !strings.Contains(string(body), "disk full") {
t.Fatalf("a failing keeper: %d %s", code, body)
}
}
func TestRegionsCannotBeChangedWithoutAKeeper(t *testing.T) {
f := newFixture(t, token)
if code, _ := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, true); code == 200 {
t.Fatal("regions changed on a node that has no keeper")
}
}
+31 -15
View File
@@ -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
View File
@@ -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 := &regionRun{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
}
+61
View File
@@ -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)
}
}