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