From 1177754daf77bf87695bb4bbf6a61cad717b74a3 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Wed, 18 Nov 2026 23:44:55 +0100 Subject: [PATCH] log what arrives: one line per sync and per minute of gossip, every listing at debug; --log-level A sync with a peer logs one info line when it brought something new (new and updated counts, per region). Listings that arrive by gossip are summed up once a minute. At debug level every stored listing gets a line with its id, region, outcome and the peer it came from. A duplicate is not news and logs nothing. --log-level takes debug, info, warn or error. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- README.md | 8 ++ cmd/allmende/loglevel.go | 24 ++++ cmd/allmende/loglevel_test.go | 28 +++++ cmd/allmende/run.go | 8 +- internal/p2p/intake.go | 103 +++++++++++++++ internal/p2p/intake_test.go | 228 ++++++++++++++++++++++++++++++++++ internal/p2p/node.go | 22 +++- internal/p2p/sync.go | 13 +- 8 files changed, 426 insertions(+), 8 deletions(-) create mode 100644 cmd/allmende/loglevel.go create mode 100644 cmd/allmende/loglevel_test.go create mode 100644 internal/p2p/intake.go create mode 100644 internal/p2p/intake_test.go diff --git a/README.md b/README.md index 6fe6746..bfaea2e 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,14 @@ know its own public address (router, container) is told one with `--announce /dns4//tcp/4001`. Where the terminal is a log (containers), `--no-login-link` keeps the sign-in link, which holds the admin token, out of it. +**What the node logs.** At the default level it says when something new arrived: +one line per sync with a peer (`synced listings peer=… new=101 updated=0 +regions="u0u=67 u1h=34"`, only when something was new) and one line a minute +for listings that came by gossip (`received listings by gossip`). A node with +nothing new stays quiet. `--log-level debug` adds a line for every single +listing stored, with its ID, region, whether it was new or an update, and which +peer it came from; `warn` and `error` show less. + ## Running a node for real A node needs to stay up to receive messages and keep your listings alive. Make diff --git a/cmd/allmende/loglevel.go b/cmd/allmende/loglevel.go new file mode 100644 index 0000000..e81ea66 --- /dev/null +++ b/cmd/allmende/loglevel.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "log/slog" + "strings" +) + +// parseLogLevel reads --log-level. Only the four names are accepted (slog's +// own parser also takes offsets like "info+2", which nobody should have to +// know about). +func parseLogLevel(s string) (slog.Level, error) { + switch strings.ToLower(strings.TrimSpace(s)) { + case "debug": + return slog.LevelDebug, nil + case "info", "": + return slog.LevelInfo, nil + case "warn", "warning": + return slog.LevelWarn, nil + case "error": + return slog.LevelError, nil + } + return 0, fmt.Errorf("--log-level %q: use debug, info, warn or error", s) +} diff --git a/cmd/allmende/loglevel_test.go b/cmd/allmende/loglevel_test.go new file mode 100644 index 0000000..f5b5f21 --- /dev/null +++ b/cmd/allmende/loglevel_test.go @@ -0,0 +1,28 @@ +package main + +import ( + "log/slog" + "strings" + "testing" +) + +func TestLogLevelNames(t *testing.T) { + for in, want := range map[string]slog.Level{ + "debug": slog.LevelDebug, "DEBUG": slog.LevelDebug, " info ": slog.LevelInfo, "": slog.LevelInfo, + "warn": slog.LevelWarn, "warning": slog.LevelWarn, "error": slog.LevelError, + } { + got, err := parseLogLevel(in) + if err != nil || got != want { + t.Errorf("parseLogLevel(%q) = %v, %v; want %v", in, got, err, want) + } + } +} + +func TestLogLevelRefusesAnythingElseAndSaysWhatIsAllowed(t *testing.T) { + for _, in := range []string{"verbose", "info+2", "trace", "3"} { + _, err := parseLogLevel(in) + if err == nil || !strings.Contains(err.Error(), "debug, info, warn or error") { + t.Errorf("parseLogLevel(%q): err = %v, want one naming the allowed levels", in, err) + } + } +} diff --git a/cmd/allmende/run.go b/cmd/allmende/run.go index 0e14f79..a8cb5ab 100644 --- a/cmd/allmende/run.go +++ b/cmd/allmende/run.go @@ -41,6 +41,8 @@ func cmdRun(args []string) error { fs.Var(&bootstrap, "bootstrap", "extra bootstrap peer: …/p2p/ or /dnsaddr/; repeatable") noDefaultBootstrap := fs.Bool("no-default-bootstrap", false, "do not use the built-in bootstrap name "+p2p.DefaultBootstrap) + logLevel := fs.String("log-level", "info", + "how much to log: debug (every listing that arrives and where from), info, warn or error") noDHT := fs.Bool("no-dht", false, "do not look for peers through the DHT") public := fs.Bool("public", false, "this node is reachable from the internet: serve the DHT and relay for nodes behind a NAT (for bootstrap nodes)") @@ -123,7 +125,11 @@ func cmdRun(args []string) error { if until <= 0 { return errors.New("this device's certificate has expired; " + renewExpired) } - log := slog.New(slog.NewTextHandler(os.Stderr, nil)) + level, err := parseLogLevel(*logLevel) + if err != nil { + return err + } + log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})) if until < certWarnBefore { log.Warn("device certificate expires soon; "+renewSoon, "expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02")) diff --git a/internal/p2p/intake.go b/internal/p2p/intake.go new file mode 100644 index 0000000..9a15bfc --- /dev/null +++ b/internal/p2p/intake.go @@ -0,0 +1,103 @@ +package p2p + +import ( + "context" + "fmt" + "log/slog" + "slices" + "strings" + "sync" + "time" + + "github.com/libp2p/go-libp2p/core/peer" + + "git.stinnesbeck.com/nils/allmende/internal/listing" + "git.stinnesbeck.com/nils/allmende/internal/store" +) + +// defaultIntakeSummary is how often a node sums up the listings that reached +// it by gossip. +const defaultIntakeSummary = time.Minute + +// tally counts the listings a node newly stored, so that one line can say so +// instead of one line per listing: a catch-up can bring in hundreds. +type tally struct { + mu sync.Mutex + inserted int + replaced int + regions map[string]int +} + +func (t *tally) add(region string, out store.Outcome) { + t.mu.Lock() + defer t.mu.Unlock() + if t.regions == nil { + t.regions = map[string]int{} + } + t.regions[region]++ + if out == store.Replaced { + t.replaced++ + } else { + t.inserted++ + } +} + +// log writes one info line with what was counted since the last call, and +// nothing when nothing new arrived, so a quiet node stays quiet. +func (t *tally) log(l *slog.Logger, msg string, attrs ...any) { + t.mu.Lock() + inserted, replaced, regions := t.inserted, t.replaced, t.regions + t.inserted, t.replaced, t.regions = 0, 0, nil + t.mu.Unlock() + if inserted+replaced == 0 { + return + } + cells := make([]string, 0, len(regions)) + for region, n := range regions { + cells = append(cells, fmt.Sprintf("%s=%d", region, n)) + } + slices.Sort(cells) + l.Info(msg, append(attrs, "new", inserted, "updated", replaced, "regions", strings.Join(cells, " "))...) +} + +type tallyKey struct{} + +// withTally makes the listings stored under ctx count into t (one sync). +func withTally(ctx context.Context, t *tally) context.Context { + return context.WithValue(ctx, tallyKey{}, t) +} + +// noteListing records a listing that was just stored. Debug level says what +// it was and where it came from; the count is summed up by whoever owns the +// tally: a sync with one peer, or the gossip summary. A duplicate or older +// version (Ignored) is not news and is not counted. +func (n *Node) noteListing(ctx context.Context, l *listing.Listing, out store.Outcome, via string, from peer.ID) { + if out == store.Ignored { + return + } + region := listing.Region(l.Geohash) + n.log.Debug("listing stored", "id", l.ID, "author", l.Author[:12], "region", region, + "kind", l.Kind, "tombstone", l.Tombstone, "outcome", out.String(), "via", via, "from", from) + t, ok := ctx.Value(tallyKey{}).(*tally) + if !ok { + t = &n.gossipIn + } + t.add(region, out) +} + +// summarizeIntake logs the listings that reached this node by gossip, once per +// interval, and once more when the node stops. +func (n *Node) summarizeIntake() { + defer n.wg.Done() + t := time.NewTicker(n.cfg.IntakeSummaryEvery) + defer t.Stop() + for { + select { + case <-n.ctx.Done(): + n.gossipIn.log(n.log, "received listings by gossip") + return + case <-t.C: + n.gossipIn.log(n.log, "received listings by gossip") + } + } +} diff --git a/internal/p2p/intake_test.go b/internal/p2p/intake_test.go new file mode 100644 index 0000000..9fa0239 --- /dev/null +++ b/internal/p2p/intake_test.go @@ -0,0 +1,228 @@ +package p2p + +import ( + "bytes" + "context" + "log/slog" + "regexp" + "strconv" + "strings" + "sync" + "testing" + "time" + + "git.stinnesbeck.com/nils/allmende/internal/store" +) + +// logBuffer collects a node's log at debug level so a test can read it back. +type logBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *logBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *logBuffer) logger() *slog.Logger { + return slog.New(slog.NewTextHandler(b, &slog.HandlerOptions{Level: slog.LevelDebug})) +} + +// lines are the log lines that contain every one of parts. +func (b *logBuffer) lines(parts ...string) []string { + b.mu.Lock() + defer b.mu.Unlock() + var out []string + for _, l := range strings.Split(b.buf.String(), "\n") { + ok := l != "" + for _, p := range parts { + ok = ok && strings.Contains(l, p) + } + if ok { + out = append(out, l) + } + } + return out +} + +// field reads key=value from a text-handler line (values here have no spaces +// unless quoted, which the regions field is). +func field(line, key string) string { + m := regexp.MustCompile(`\b` + key + `=("[^"]*"|\S+)`).FindStringSubmatch(line) + if m == nil { + return "" + } + return strings.Trim(m[1], `"`) +} + +func sumOf(lines []string, key string) int { + total := 0 + for _, l := range lines { + n, _ := strconv.Atoi(field(l, key)) + total += n + } + return total +} + +func TestACatchUpIsSummedUpInOneInfoLineAndListedAtDebugLevel(t *testing.T) { + a := startNode(t, nil, "u1x") + var bLog logBuffer + var ids []string + for i := 0; i < 5; i++ { // page size is 3: two pages + l := a.listing(t, "u1xjhx") + a.store(t, l) + ids = append(ids, l.ID) + } + b := startNodeWith(t, nil, func(c *Config) { c.Logger = bLog.logger() }, "u1x") + connect(t, b, a) + eventually(t, "b has caught up", func() bool { return count(b) == 5 }) + eventually(t, "b sums the catch-up up", func() bool { return len(bLog.lines(`msg="synced listings"`)) > 0 }) + + sums := bLog.lines(`msg="synced listings"`) + if len(sums) != 1 { + t.Fatalf("%d summary lines, want exactly one for one sync:\n%s", len(sums), strings.Join(sums, "\n")) + } + s := sums[0] + if !strings.Contains(s, "level=INFO") || field(s, "new") != "5" || field(s, "updated") != "0" || field(s, "regions") != "u1x=5" { + t.Fatalf("summary says the wrong thing: %s", s) + } + if field(s, "peer") != a.ID().String() { + t.Fatalf("summary names peer %q, want %s", field(s, "peer"), a.ID()) + } + + stored := bLog.lines(`msg="listing stored"`) + if len(stored) != 5 { + t.Fatalf("%d 'listing stored' lines, want one per listing:\n%s", len(stored), strings.Join(stored, "\n")) + } + for _, line := range stored { + if !strings.Contains(line, "level=DEBUG") { + t.Errorf("a single listing must not be logged above debug level: %s", line) + } + if field(line, "via") != "sync" || field(line, "from") != a.ID().String() || field(line, "region") != "u1x" || field(line, "outcome") != "inserted" { + t.Errorf("line does not say where the listing came from: %s", line) + } + } + for _, id := range ids { + if len(bLog.lines(`msg="listing stored"`, "id="+id)) != 1 { + t.Errorf("listing %s is not logged exactly once", id) + } + } +} + +func TestASyncThatBringsNothingNewLogsNothing(t *testing.T) { + a := startNode(t, nil, "u1x") + var bLog logBuffer + a.store(t, a.listing(t, "u1xjhx")) + b := startNodeWith(t, nil, func(c *Config) { c.Logger = bLog.logger() }, "u1x") + connect(t, b, a) + eventually(t, "the first summary", func() bool { return len(bLog.lines(`msg="synced listings"`)) == 1 }) + + if err := b.SyncFrom(context.Background(), a.ID()); err != nil { + t.Fatal(err) + } + if err := b.SyncFrom(context.Background(), a.ID()); err != nil { + t.Fatal(err) + } + if n := len(bLog.lines(`msg="synced listings"`)); n != 1 { + t.Fatalf("%d summaries after two syncs that changed nothing, want still 1", n) + } + if n := len(bLog.lines(`msg="listing stored"`)); n != 1 { + t.Fatalf("%d 'listing stored' lines, want 1: a duplicate is not news", n) + } +} + +func TestAnEditedListingCountsAsUpdatedNotNew(t *testing.T) { + a := startNode(t, nil, "u1x") + var bLog logBuffer + l := a.listing(t, "u1xjhx") + a.store(t, l) + b := startNodeWith(t, nil, func(c *Config) { c.Logger = bLog.logger() }, "u1x") + connect(t, b, a) + eventually(t, "b has the listing", func() bool { return count(b) == 1 }) + eventually(t, "the first summary", func() bool { return len(bLog.lines(`msg="synced listings"`)) == 1 }) + + edited := *l + edited.Seq = l.Seq + 1 + edited.Title = "Wohnung, jetzt günstiger" + if err := edited.Seal(a.dev, difficulty); err != nil { + t.Fatal(err) + } + a.store(t, &edited) + if err := b.SyncFrom(context.Background(), a.ID()); err != nil { + t.Fatal(err) + } + sums := bLog.lines(`msg="synced listings"`) + if len(sums) != 2 || field(sums[1], "new") != "0" || field(sums[1], "updated") != "1" { + t.Fatalf("the edit must be one updated listing, not a new one:\n%s", strings.Join(sums, "\n")) + } +} + +func TestListingsThatArriveByGossipAreSummedUpOncePerInterval(t *testing.T) { + a := startNode(t, nil, "u1x") + var bLog logBuffer + b := startNodeWith(t, nil, func(c *Config) { + c.Logger = bLog.logger() + c.IntakeSummaryEvery = 150 * time.Millisecond + }, "u1x") + connect(t, b, a) + eventually(t, "a sees b on the region topic", func() bool { return len(a.RegionPeers("u1x")) == 1 }) + + const sent = 4 + for i := 0; i < sent; i++ { + if err := a.Publish(context.Background(), a.listing(t, "u1xjhx")); err != nil { + t.Fatal(err) + } + } + eventually(t, "b has them all", func() bool { return count(b) == sent }) + eventually(t, "b sums them up", func() bool { return sumOf(bLog.lines(`msg="received listings by gossip"`), "new") == sent }) + + for _, line := range bLog.lines(`msg="received listings by gossip"`) { + if !strings.Contains(line, "level=INFO") || field(line, "regions") == "" { + t.Errorf("the gossip summary must be an info line naming the regions: %s", line) + } + } + stored := bLog.lines(`msg="listing stored"`) + if len(stored) != sent { + t.Fatalf("%d 'listing stored' lines, want %d", len(stored), sent) + } + for _, line := range stored { + if field(line, "via") != "gossip" || field(line, "from") != a.ID().String() || !strings.Contains(line, "level=DEBUG") { + t.Errorf("a gossip arrival must be a debug line naming its sender: %s", line) + } + } + + // Quiet again: no news, no line. + before := len(bLog.lines(`msg="received listings by gossip"`)) + time.Sleep(500 * time.Millisecond) + if after := len(bLog.lines(`msg="received listings by gossip"`)); after != before { + t.Fatalf("a node that received nothing logged %d more summaries", after-before) + } + // And the sync that happened when they connected found nothing to count. + if n := len(bLog.lines(`msg="synced listings"`)); n != 0 { + t.Fatalf("%d sync summaries, want none: there was nothing to catch up on", n) + } +} + +func TestTheTallyNamesRegionsInOrderAndResetsWhenRead(t *testing.T) { + var out logBuffer + var tl tally + tl.log(out.logger(), "nothing yet") + if len(out.lines("nothing yet")) != 0 { + t.Fatal("an empty tally must log nothing") + } + for _, r := range []string{"u1x", "u0u", "u1x"} { + tl.add(r, store.Inserted) + } + tl.add("u0u", store.Replaced) + tl.log(out.logger(), "got", "peer", "p") + line := out.lines("msg=got")[0] + if field(line, "new") != "3" || field(line, "updated") != "1" || field(line, "regions") != "u0u=2 u1x=2" { + t.Fatalf("tally line: %s", line) + } + tl.log(out.logger(), "again") + if len(out.lines("msg=again")) != 0 { + t.Fatal("reading the tally must reset it") + } +} diff --git a/internal/p2p/node.go b/internal/p2p/node.go index d0f392c..3c4143e 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -102,8 +102,12 @@ type Config struct { // it shares a region with, to repair what gossip lost while connected // (default 30 min). AntiEntropyInterval time.Duration - Clock func() time.Time // default time.Now - Logger *slog.Logger + // IntakeSummaryEvery is how often the node logs how many listings reached + // it by gossip since the last time (default 1 min; nothing is logged when + // none did). + IntakeSummaryEvery time.Duration + Clock func() time.Time // default time.Now + Logger *slog.Logger // Bandwidth, if set, counts the bytes this node sends and receives (the // simulator uses it; a real node leaves it nil). Bandwidth metrics.Reporter @@ -124,6 +128,8 @@ type Node struct { ps *pubsub.PubSub clock func() time.Time log *slog.Logger + // gossipIn counts listings that arrived by gossip since the last summary. + gossipIn tally ctx context.Context cancel context.CancelFunc @@ -166,6 +172,9 @@ func New(ctx context.Context, cfg Config) (*Node, error) { if cfg.AntiEntropyInterval <= 0 { cfg.AntiEntropyInterval = 30 * time.Minute } + if cfg.IntakeSummaryEvery <= 0 { + cfg.IntakeSummaryEvery = defaultIntakeSummary + } if cfg.RelayBootDelay <= 0 { cfg.RelayBootDelay = 10 * time.Second } @@ -301,12 +310,13 @@ func New(ctx context.Context, cfg Config) (*Node, error) { // Finding the first peers can take a while (DNS, unreachable servers), so it // does not hold up starting the node. - n.wg.Add(5) + n.wg.Add(6) go func() { defer n.wg.Done() n.dialBootstrap() n.dialCached() }() + go n.summarizeIntake() go n.maintain() go n.redial() go n.antiEntropy() @@ -591,8 +601,10 @@ func (n *Node) subscribeRegion(region string) error { if !ok { return } - switch _, err := n.cfg.Store.Put(n.ctx, l); { - case err == nil, errors.Is(err, store.ErrRevoked): + switch out, err := n.cfg.Store.Put(n.ctx, l); { + case err == nil: + n.noteListing(n.ctx, l, out, "gossip", msg.ReceivedFrom) + case errors.Is(err, store.ErrRevoked): default: n.log.Warn("store listing", "err", err) } diff --git a/internal/p2p/sync.go b/internal/p2p/sync.go index b51d6d6..8b4ca9b 100644 --- a/internal/p2p/sync.go +++ b/internal/p2p/sync.go @@ -296,6 +296,11 @@ func (n *Node) syncSoon(p peer.ID) { // does not know digests (an older node) is caught up the original way, by // paging through everything it holds. func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error { + // One info line says what this sync brought in, however it ends. + got := &tally{} + ctx = withTally(ctx, got) + defer got.log(n.log, "synced listings", "peer", p) + n.mu.Lock() regions := append([]string(nil), n.subscribed...) n.mu.Unlock() @@ -403,8 +408,10 @@ func (n *Node) pullListings(ctx context.Context, p peer.ID, region string) error if json.Unmarshal(line, &l) != nil || listing.Region(l.Geohash) != region { return } - if _, err := n.cfg.Store.Put(ctx, &l); err != nil { + if out, err := n.cfg.Store.Put(ctx, &l); err != nil { n.log.Debug("sync: listing rejected", "peer", p, "err", err) + } else { + n.noteListing(ctx, &l, out, "sync", p) } }) if err != nil { @@ -565,8 +572,10 @@ func (n *Node) syncRegion(ctx context.Context, p peer.ID, region string) error { if listing.Region(l.Geohash) != region { return // peer sent something we did not ask for } - if _, err := n.cfg.Store.Put(ctx, &l); err != nil { + if out, err := n.cfg.Store.Put(ctx, &l); err != nil { n.log.Debug("sync: listing rejected", "peer", p, "err", err) + } else { + n.noteListing(ctx, &l, out, "sync", p) } }) if err != nil {