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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
+17
-5
@@ -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)
|
||||
}
|
||||
|
||||
+11
-2
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user