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,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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user