From 11fd2a88c017f977b9e6c471f40180ab81f4d0eb Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Wed, 18 Nov 2026 17:28:22 +0100 Subject: [PATCH] p2p: incremental sync with digests, inventory and fetch Peers compare a short digest of revocations, listings and messages on connect and transfer only what differs. Peers without digests are synced the old way. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- docs/PROTOCOL.md | 29 +++- internal/p2p/node.go | 1 + internal/p2p/p2p_test.go | 54 +++++++ internal/p2p/sync.go | 298 +++++++++++++++++++++++++++++++++-- internal/store/inventory.go | 249 +++++++++++++++++++++++++++++ internal/store/store_test.go | 91 +++++++++++ 6 files changed, 705 insertions(+), 17 deletions(-) create mode 100644 internal/store/inventory.go diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index c1ca103..460440e 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -120,11 +120,28 @@ within 30 days. tombstones are stored like any version so old copies cannot resurrect a deleted listing. - **Sync** (`/allmende/1/sync`): on every new connection to a peer a node - pulls revocations first, then each subscribed region, paged by a - `(created_at, author, id)` keyset cursor. Tombstones are included so - deletions propagate. Simultaneous connections to the same peer (e.g. TCP and - QUIC) share one running sync. Currently a full pull; a digest-based - incremental sync is future work. Gossip lost *while connected* is only + catches up incrementally. Simultaneous connections to the same peer (e.g. + TCP and QUIC) share one running sync. + 1. `digest` (no region) returns a digest `{n, root}` of the peer's + revocations; if it differs from ours, the revocations are pulled (they + are few). Revocations go first so listings of revoked devices are + refused. + 2. For each subscribed region, `digest` returns digests of the region's + listings and of its messages. A digest is the record count and a SHA-256 + over the sorted identities and versions (`author id hash` per listing, + `hash` per message; tombstones count, expired records do not). Equal + digests: nothing more is sent, which is the usual case. + 3. When listing digests differ, `inventory` pages through the peer's + `(author, id, seq, hash)` list (about 100 bytes per listing). The node + keeps the versions it lacks or that beat the one it holds (the conflict + rules above) and asks for them with `fetch` (up to 100 `author/id` keys + per request). Messages work the same way, keyed by hash. Listings are + synced before messages, since owner-bound messages are only accepted for + listings we hold. + A peer that answers `digest` with a reset (a node from before digests + existed) is caught up the original way: kinds `revocations`, `listings` and + `messages`, paged by `(created_at, author, id)` and `(created_at, hash)` + cursors, which servers still answer. Gossip lost *while connected* is only repaired by the next reconnect; periodic anti-entropy is future work. - **Reconnection**: bootstrap peers are redialed every 20 s when disconnected. - **Re-announce**: a running node re-gossips its own live listings and @@ -476,7 +493,7 @@ Proof-of-work per listing and per revocation, plus subscribable blocklists Abuse reporting for messages, reciprocity rules, anti- discrimination (AGG) content rules, blocklists, peer scoring and rate limits, -incremental sync and anti-entropy, a fallback bootstrap list inside the binary +periodic anti-entropy while connected, a fallback bootstrap list inside the binary for networks that block DNS, image hosting, recovering listings onto a fresh machine with an empty database, a helper to turn a place name into a region. diff --git a/internal/p2p/node.go b/internal/p2p/node.go index e0d0a9d..9e411c9 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -117,6 +117,7 @@ type Node struct { boot *bootstrapper dht *dht.IpfsDHT syncing map[peer.ID]bool + oldSync bool // tests: answer like a node from before digests existed revTopic *pubsub.Topic } diff --git a/internal/p2p/p2p_test.go b/internal/p2p/p2p_test.go index 6fd8dab..60a515a 100644 --- a/internal/p2p/p2p_test.go +++ b/internal/p2p/p2p_test.go @@ -438,3 +438,57 @@ func mustRoot(t *testing.T) *identity.Identity { } return root } + +// Reconnecting must transfer only what differs: b holds most of a's listings, +// a has since changed one and added another. +func TestIncrementalSyncFetchesOnlyTheDifference(t *testing.T) { + a := startNode(t, nil, "u1x") + b := startNode(t, nil, "u1x") + ctx := context.Background() + + var shared []*listing.Listing + for i := 0; i < 5; i++ { // page size is 3: two inventory pages + l := a.listing(t, "u1xjhx") + a.s.Put(ctx, l) + b.s.Put(ctx, l) + shared = append(shared, l) + } + update := &listing.Listing{ + Version: listing.Version, ID: shared[2].ID, Seq: 2, + CreatedAt: time.Now().Unix(), ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(), + Kind: "rent", Category: "apartment", Geohash: "u1xjhx", Title: "Neu", + Price: &listing.Price{AmountCents: 90000, Currency: "EUR", Period: "month"}, + } + if err := update.Seal(a.dev, difficulty); err != nil { + t.Fatal(err) + } + fresh := a.listing(t, "u1xjhx") + a.s.Put(ctx, update) + a.s.Put(ctx, fresh) + + connect(t, b, a) + eventually(t, "b has the update and the new listing", func() bool { + l, err := b.s.Get(ctx, shared[2].Author, shared[2].ID) + _, err2 := b.s.Get(ctx, fresh.Author, fresh.ID) + return err == nil && l.Title == "Neu" && err2 == nil + }) + da, _ := a.s.ListingDigest(ctx, "u1x") + db, _ := b.s.ListingDigest(ctx, "u1x") + if da != db { + t.Fatal("digests differ after sync") + } +} + +// The bootstrap node deployed today does not know digests: syncing with it +// must still work, the old way. +func TestSyncWithANodeThatKnowsNoDigests(t *testing.T) { + a := startNode(t, nil, "u1x") + a.oldSync = true + ctx := context.Background() + for i := 0; i < 4; i++ { + a.s.Put(ctx, a.listing(t, "u1xjhx")) + } + b := startNode(t, nil, "u1x") + connect(t, b, a) + eventually(t, "b caught up from an old node", func() bool { return count(b) == 4 }) +} diff --git a/internal/p2p/sync.go b/internal/p2p/sync.go index 5be6c99..4d096dd 100644 --- a/internal/p2p/sync.go +++ b/internal/p2p/sync.go @@ -29,16 +29,29 @@ const ( syncTimeout = 2 * time.Minute maxSyncPages = 200 // bounds work per region against a misbehaving peer maxRevocations = 5000 + maxFetch = 100 // records asked for in one fetch ) +// digestReply is the answer to a "digest" request. Listings and Messages are +// left empty when no region was asked about. +type digestReply struct { + Revocations store.Digest `json:"revocations"` + Listings store.Digest `json:"listings"` + Messages store.Digest `json:"messages"` +} + type syncRequest struct { - Kind string `json:"kind"` // "listings", "messages" or "revocations" - Region string `json:"region,omitempty"` - AfterCreated int64 `json:"after_created,omitempty"` - AfterAuthor string `json:"after_author,omitempty"` // listings - AfterID string `json:"after_id,omitempty"` // listings - AfterHash string `json:"after_hash,omitempty"` // messages - Limit int `json:"limit,omitempty"` + // Kind is "listings", "messages" or "revocations" (everything, paged: the + // original catch-up), or "digest", "inventory" and "fetch" (incremental). + Kind string `json:"kind"` + Of string `json:"of,omitempty"` // inventory, fetch: "listings" or "messages" + Keys []string `json:"keys,omitempty"` // fetch: "author/id" of listings, or message hashes + Region string `json:"region,omitempty"` + AfterCreated int64 `json:"after_created,omitempty"` + AfterAuthor string `json:"after_author,omitempty"` // listings + AfterID string `json:"after_id,omitempty"` // listings + AfterHash string `json:"after_hash,omitempty"` // messages + Limit int `json:"limit,omitempty"` } // --- server --------------------------------------------------------------- @@ -48,7 +61,11 @@ func (n *Node) handleSync(s network.Stream) { _ = s.SetDeadline(time.Now().Add(syncTimeout)) var req syncRequest - if err := json.NewDecoder(io.LimitReader(s, 4096)).Decode(&req); err != nil { + if err := json.NewDecoder(io.LimitReader(s, 64<<10)).Decode(&req); err != nil { + _ = s.Reset() + return + } + if n.oldSync && (req.Kind == "digest" || req.Kind == "inventory" || req.Kind == "fetch") { _ = s.Reset() return } @@ -120,6 +137,101 @@ func (n *Node) handleSync(s network.Stream) { return } } + case "digest": + var d digestReply + var err error + if d.Revocations, err = n.cfg.Store.RevocationDigest(n.ctx); err != nil { + _ = s.Reset() + return + } + if req.Region != "" { + if !listing.ValidRegion(req.Region) { + _ = s.Reset() + return + } + if d.Listings, err = n.cfg.Store.ListingDigest(n.ctx, req.Region); err != nil { + _ = s.Reset() + return + } + if d.Messages, err = n.cfg.Store.MessageDigest(n.ctx, req.Region); err != nil { + _ = s.Reset() + return + } + } + if !write(json.Marshal(d)) { + _ = s.Reset() + return + } + case "inventory": + if !listing.ValidRegion(req.Region) { + _ = s.Reset() + return + } + limit := req.Limit + if limit <= 0 || limit > n.cfg.SyncPageSize { + limit = n.cfg.SyncPageSize + } + var items []store.Item + var err error + switch req.Of { + case "listings": + items, err = n.cfg.Store.Inventory(n.ctx, req.Region, req.AfterAuthor, req.AfterID, limit) + case "messages": + var hashes []string + hashes, err = n.cfg.Store.MessageHashes(n.ctx, req.Region, req.AfterHash, limit) + for _, h := range hashes { + items = append(items, store.Item{Hash: h}) + } + default: + err = errors.New("unknown inventory") + } + if err != nil { + _ = s.Reset() + return + } + for _, it := range items { + if !write(json.Marshal(it)) { + _ = s.Reset() + return + } + } + case "fetch": + if !listing.ValidRegion(req.Region) || len(req.Keys) > maxFetch { + _ = s.Reset() + return + } + switch req.Of { + case "listings": + ls, err := n.cfg.Store.ListingsByKey(n.ctx, req.Keys) + if err != nil { + _ = s.Reset() + return + } + for _, l := range ls { + if listing.Region(l.Geohash) != req.Region { + continue + } + if !write(l.Bytes()) { + _ = s.Reset() + return + } + } + case "messages": + es, err := n.cfg.Store.MessagesByHash(n.ctx, req.Region, req.Keys) + if err != nil { + _ = s.Reset() + return + } + for _, e := range es { + if !write(e.Bytes()) { + _ = s.Reset() + return + } + } + default: + _ = s.Reset() + return + } default: _ = s.Reset() return @@ -160,13 +272,177 @@ func (n *Node) syncSoon(p peer.ID) { // SyncFrom pulls revocations and then every subscribed region from p. // Revocations go first so listings from revoked devices are refused. +// +// It compares digests first and transfers only what differs. A peer that +// 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 { - if err := n.syncRevocations(ctx, p); err != nil { - return err - } n.mu.Lock() regions := append([]string(nil), n.subscribed...) n.mu.Unlock() + + var theirs digestReply + if err := n.digest(ctx, p, "", &theirs); err != nil { + return n.syncEverything(ctx, p, regions) + } + ours, err := n.cfg.Store.RevocationDigest(ctx) + if err != nil { + return err + } + if ours != theirs.Revocations { + if err := n.syncRevocations(ctx, p); err != nil { + return err + } + } + for _, region := range regions { + if err := n.digest(ctx, p, region, &theirs); err != nil { + return err + } + if err := n.syncRegionIncremental(ctx, p, region, theirs); err != nil { + return err + } + } + return nil +} + +func (n *Node) digest(ctx context.Context, p peer.ID, region string, out *digestReply) error { + got := false + err := n.request(ctx, p, syncRequest{Kind: "digest", Region: region}, func(line []byte) { + got = json.Unmarshal(line, out) == nil + }) + if err == nil && !got { + err = errors.New("no digest") + } + return err +} + +func (n *Node) syncRegionIncremental(ctx context.Context, p peer.ID, region string, theirs digestReply) error { + ours, err := n.cfg.Store.ListingDigest(ctx, region) + if err != nil { + return err + } + if ours != theirs.Listings { + if err := n.pullListings(ctx, p, region); err != nil { + return err + } + } + // After the listings: owner-bound messages are only accepted for + // listings we already hold. + ourMsgs, err := n.cfg.Store.MessageDigest(ctx, region) + if err != nil { + return err + } + if ourMsgs != theirs.Messages { + return n.pullMessages(ctx, p, region) + } + return nil +} + +// pullListings lists what p holds in region, page by page, and fetches the +// versions this node lacks or holds an older version of. +func (n *Node) pullListings(ctx context.Context, p peer.ID, region string) error { + var afterAuthor, afterID string + for page := 0; page < maxSyncPages; page++ { + var items []store.Item + err := n.request(ctx, p, syncRequest{ + Kind: "inventory", Of: "listings", Region: region, Limit: n.cfg.SyncPageSize, + AfterAuthor: afterAuthor, AfterID: afterID, + }, func(line []byte) { + var it store.Item + if json.Unmarshal(line, &it) == nil { + if _, _, ok := store.SplitKey(it.Key()); ok { + items = append(items, it) + } + } + }) + if err != nil { + return err + } + want, err := n.cfg.Store.Wanted(ctx, items) + if err != nil { + return err + } + for len(want) > 0 { + batch := want[:min(len(want), maxFetch)] + want = want[len(batch):] + keys := make([]string, len(batch)) + for i, it := range batch { + keys[i] = it.Key() + } + err := n.request(ctx, p, syncRequest{Kind: "fetch", Of: "listings", Region: region, Keys: keys}, func(line []byte) { + var l listing.Listing + if json.Unmarshal(line, &l) != nil || listing.Region(l.Geohash) != region { + return + } + if _, err := n.cfg.Store.Put(ctx, &l); err != nil { + n.log.Debug("sync: listing rejected", "peer", p, "err", err) + } + }) + if err != nil { + return err + } + } + if len(items) < n.cfg.SyncPageSize { + return nil + } + last := items[len(items)-1] + afterAuthor, afterID = last.Author, last.ID + } + return nil +} + +// pullMessages is pullListings for the envelopes of a region. +func (n *Node) pullMessages(ctx context.Context, p peer.ID, region string) error { + var after string + for page := 0; page < maxSyncPages; page++ { + var hashes []string + err := n.request(ctx, p, syncRequest{ + Kind: "inventory", Of: "messages", Region: region, Limit: n.cfg.SyncPageSize, AfterHash: after, + }, func(line []byte) { + var it store.Item + if json.Unmarshal(line, &it) == nil && it.Hash != "" { + hashes = append(hashes, it.Hash) + } + }) + if err != nil { + return err + } + want, err := n.cfg.Store.MissingMessages(ctx, hashes) + if err != nil { + return err + } + for len(want) > 0 { + batch := want[:min(len(want), maxFetch)] + want = want[len(batch):] + err := n.request(ctx, p, syncRequest{Kind: "fetch", Of: "messages", Region: region, Keys: batch}, func(line []byte) { + var e message.Envelope + if json.Unmarshal(line, &e) != nil { + return + } + switch _, err := n.cfg.Store.PutMessage(ctx, region, &e); { + case err == nil, errors.Is(err, store.ErrNoListing), errors.Is(err, store.ErrQueueFull): + default: + n.log.Debug("sync: message rejected", "peer", p, "err", err) + } + }) + if err != nil { + return err + } + } + if len(hashes) < n.cfg.SyncPageSize { + return nil + } + after = hashes[len(hashes)-1] + } + return nil +} + +// syncEverything is the original catch-up: page through all of a peer's +// revocations, listings and messages. Used for peers without digests. +func (n *Node) syncEverything(ctx context.Context, p peer.ID, regions []string) error { + if err := n.syncRevocations(ctx, p); err != nil { + return err + } for _, region := range regions { if err := n.syncRegion(ctx, p, region); err != nil { return err diff --git a/internal/store/inventory.go b/internal/store/inventory.go new file mode 100644 index 0000000..2130530 --- /dev/null +++ b/internal/store/inventory.go @@ -0,0 +1,249 @@ +package store + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "fmt" + "strings" + + "git.stinnesbeck.com/nils/allmende/internal/listing" + "git.stinnesbeck.com/nils/allmende/internal/message" +) + +// This file backs incremental sync. Instead of sending every record again on +// every reconnect, a node first compares a short digest of what each side +// holds. When they match nothing more is sent. When they differ it lists the +// keys and versions (about 100 bytes per record, not kilobytes) and fetches +// only what it lacks or holds an older version of. + +// Digest summarises a set of records: how many, and a hash over their sorted +// identities and versions. Equal digests mean equal sets. +type Digest struct { + Count int `json:"n"` + Root string `json:"root"` +} + +// Item names one version of a listing, without its content. +type Item struct { + Author string `json:"a"` + ID string `json:"i"` + Seq int64 `json:"s"` + Hash string `json:"h"` +} + +// Key is the stable identity of a listing, "author/id" (both are hex). +func (i Item) Key() string { return i.Author + "/" + i.ID } + +// SplitKey is the inverse of Item.Key. +func SplitKey(key string) (author, id string, ok bool) { + author, id, ok = strings.Cut(key, "/") + return author, id, ok && author != "" && id != "" && !strings.Contains(id, "/") +} + +func digestOf(rows *sql.Rows, cols int) (Digest, error) { + defer rows.Close() + h := sha256.New() + var d Digest + for rows.Next() { + parts := make([]string, cols) + ptrs := make([]any, cols) + for i := range parts { + ptrs[i] = &parts[i] + } + if err := rows.Scan(ptrs...); err != nil { + return d, err + } + h.Write([]byte(strings.Join(parts, " "))) + h.Write([]byte{'\n'}) + d.Count++ + } + d.Root = hex.EncodeToString(h.Sum(nil)) + return d, rows.Err() +} + +// ListingDigest digests the unexpired listings (tombstones included) of a +// region, the same set Since and Inventory serve. +func (s *Store) ListingDigest(ctx context.Context, region string) (Digest, error) { + if !listing.ValidGeohashPrefix(region) { + return Digest{}, fmt.Errorf("store: invalid geohash prefix %q", region) + } + rows, err := s.db.QueryContext(ctx, ` + SELECT author, id, hash FROM listings + WHERE geohash >= ? AND geohash <= ? AND expires_at > ? + ORDER BY author, id`, region, region+"~", s.clock().Unix()) + if err != nil { + return Digest{}, err + } + return digestOf(rows, 3) +} + +// Inventory returns up to limit unexpired listing versions of a region after +// (afterAuthor, afterID), ordered by that key. +func (s *Store) Inventory(ctx context.Context, region, afterAuthor, afterID string, limit int) ([]Item, error) { + if !listing.ValidGeohashPrefix(region) { + return nil, fmt.Errorf("store: invalid geohash prefix %q", region) + } + rows, err := s.db.QueryContext(ctx, ` + SELECT author, id, seq, hash FROM listings + WHERE geohash >= ? AND geohash <= ? AND expires_at > ? + AND (author, id) > (?, ?) + ORDER BY author, id LIMIT ?`, + region, region+"~", s.clock().Unix(), afterAuthor, afterID, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Item + for rows.Next() { + var it Item + if err := rows.Scan(&it.Author, &it.ID, &it.Seq, &it.Hash); err != nil { + return nil, err + } + out = append(out, it) + } + return out, rows.Err() +} + +// Wanted reports which of the offered versions this store would accept: the +// listing is unknown, or the offered version beats the one held (higher seq; +// on equal seq the smaller hash, as in Put). +func (s *Store) Wanted(ctx context.Context, offered []Item) ([]Item, error) { + var out []Item + for _, it := range offered { + var seq int64 + var hash string + err := s.db.QueryRowContext(ctx, + `SELECT seq, hash FROM listings WHERE author = ? AND id = ?`, it.Author, it.ID).Scan(&seq, &hash) + switch { + case err == sql.ErrNoRows: + out = append(out, it) + case err != nil: + return nil, err + case it.Seq > seq || (it.Seq == seq && it.Hash < hash): + out = append(out, it) + } + } + return out, nil +} + +// ListingsByKey returns the stored versions (tombstones included) for the +// given "author/id" keys. Unknown keys are skipped. +func (s *Store) ListingsByKey(ctx context.Context, keys []string) ([]*listing.Listing, error) { + var out []*listing.Listing + for _, k := range keys { + author, id, ok := SplitKey(k) + if !ok { + continue + } + var data []byte + err := s.db.QueryRowContext(ctx, + `SELECT data FROM listings WHERE author = ? AND id = ? AND expires_at > ?`, + author, id, s.clock().Unix()).Scan(&data) + if err == sql.ErrNoRows { + continue + } + if err != nil { + return nil, err + } + l, err := decode(data) + if err != nil { + return nil, err + } + out = append(out, l) + } + return out, nil +} + +// RevocationDigest digests the relevant revocations (see Revocations). +func (s *Store) RevocationDigest(ctx context.Context) (Digest, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT author, device, revoked_at FROM revocations + WHERE cert_expires_at > ? ORDER BY author, device`, s.clock().Unix()) + if err != nil { + return Digest{}, err + } + return digestOf(rows, 3) +} + +// MessageDigest digests the live envelopes of a region by hash. +func (s *Store) MessageDigest(ctx context.Context, region string) (Digest, error) { + if !listing.ValidRegion(region) { + return Digest{}, fmt.Errorf("store: invalid region %q", region) + } + rows, err := s.db.QueryContext(ctx, ` + SELECT hash FROM messages WHERE region = ? AND expires_at > ? ORDER BY hash`, + region, s.clock().Unix()) + if err != nil { + return Digest{}, err + } + return digestOf(rows, 1) +} + +// MessageHashes returns up to limit hashes of a region's live envelopes after +// hash `after`, in hash order. +func (s *Store) MessageHashes(ctx context.Context, region, after string, limit int) ([]string, error) { + if !listing.ValidRegion(region) { + return nil, fmt.Errorf("store: invalid region %q", region) + } + rows, err := s.db.QueryContext(ctx, ` + SELECT hash FROM messages + WHERE region = ? AND expires_at > ? AND hash > ? ORDER BY hash LIMIT ?`, + region, s.clock().Unix(), after, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var h string + if err := rows.Scan(&h); err != nil { + return nil, err + } + out = append(out, h) + } + return out, rows.Err() +} + +// MissingMessages returns those of hashes this store does not hold. +func (s *Store) MissingMessages(ctx context.Context, hashes []string) ([]string, error) { + var out []string + for _, h := range hashes { + var one int + err := s.db.QueryRowContext(ctx, `SELECT 1 FROM messages WHERE hash = ?`, h).Scan(&one) + if err == sql.ErrNoRows { + out = append(out, h) + } else if err != nil { + return nil, err + } + } + return out, nil +} + +// MessagesByHash returns the live envelopes of a region with the given hashes. +func (s *Store) MessagesByHash(ctx context.Context, region string, hashes []string) ([]*message.Envelope, error) { + if !listing.ValidRegion(region) { + return nil, fmt.Errorf("store: invalid region %q", region) + } + var out []*message.Envelope + for _, h := range hashes { + var data []byte + err := s.db.QueryRowContext(ctx, + `SELECT data FROM messages WHERE hash = ? AND region = ? AND expires_at > ?`, + h, region, s.clock().Unix()).Scan(&data) + if err == sql.ErrNoRows { + continue + } + if err != nil { + return nil, err + } + var e message.Envelope + if err := json.Unmarshal(data, &e); err != nil { + return nil, fmt.Errorf("store: corrupt message row: %w", err) + } + out = append(out, &e) + } + return out, nil +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 6e4e7ad..570e899 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -527,3 +527,94 @@ func TestRevokeAllRecovery(t *testing.T) { t.Fatalf("someone else's listing blocked: %v", o) } } + +func TestDigestsTellEqualSetsFromDifferentOnes(t *testing.T) { + a, b := newEnv(t), newEnv(t) + l1, l2 := a.listing(t, nil), a.listing(t, nil) + a.put(t, l1) + a.put(t, l2) + b.put(t, l2) // insertion order must not matter + b.put(t, l1) + + da, _ := a.s.ListingDigest(ctx, "u1x") + db, _ := b.s.ListingDigest(ctx, "u1x") + if da != db || da.Count != 2 { + t.Fatalf("equal sets, different digests: %+v vs %+v", da, db) + } + // Another version of one listing changes the digest. + a.put(t, a.listing(t, func(l *listing.Listing) { l.ID, l.Seq = l1.ID, 2 })) + da2, _ := a.s.ListingDigest(ctx, "u1x") + if da2 == db { + t.Fatal("a newer version did not change the digest") + } + // A listing outside the region does not. + a.put(t, a.listing(t, func(l *listing.Listing) { l.Geohash = "u30000" })) + if d, _ := a.s.ListingDigest(ctx, "u1x"); d != da2 { + t.Fatal("a listing of another region changed the digest") + } +} + +func TestInventoryWantedAndFetch(t *testing.T) { + a, b := newEnv(t), newEnv(t) + var ls []*listing.Listing + for i := 0; i < 5; i++ { + l := a.listing(t, nil) + a.put(t, l) + ls = append(ls, l) + } + // b holds ls[0], but a is about to get a newer version of it. + b.put(t, ls[0]) + newer := a.listing(t, func(l *listing.Listing) { l.ID, l.Seq = ls[0].ID, 2 }) + a.put(t, newer) + + var all []Item + var after Item + for pages := 0; pages < 10; pages++ { + page, err := a.s.Inventory(ctx, "u1x", after.Author, after.ID, 2) + if err != nil { + t.Fatal(err) + } + if len(page) == 0 { + break + } + all = append(all, page...) + after = page[len(page)-1] + } + if len(all) != 5 { + t.Fatalf("inventory lists %d listings, want 5", len(all)) + } + want, err := b.s.Wanted(ctx, all) + if err != nil { + t.Fatal(err) + } + // b lacks four listings and holds an older version of the fifth. + if len(want) != 5 { + t.Fatalf("wanted %d, want 5", len(want)) + } + b.put(t, ls[2]) + if want, _ = b.s.Wanted(ctx, all); len(want) != 4 { + t.Fatalf("wanted %d after storing one, want 4", len(want)) + } + + var keys []string + for _, it := range want { + keys = append(keys, it.Key()) + } + got, err := a.s.ListingsByKey(ctx, append(keys, "garbage", "x/y/z", "ab/cd")) + if err != nil { + t.Fatal(err) + } + if len(got) != 4 { + t.Fatalf("fetched %d, want 4", len(got)) + } + for _, l := range got { + b.put(t, l) + } + if want, _ = b.s.Wanted(ctx, all); len(want) != 0 { + t.Fatalf("b still wants %d after fetching", len(want)) + } + da, _ := a.s.ListingDigest(ctx, "u1x") + if db, _ := b.s.ListingDigest(ctx, "u1x"); da != db { + t.Fatal("digests differ after the transfer") + } +}