Sync kind 'author': everything a peer holds from one author key, any region. A node asks the first 3 peers it syncs with per run. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
264 lines
7.9 KiB
Go
264 lines
7.9 KiB
Go
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
|
|
}
|
|
|
|
// AuthorListings returns up to limit unexpired records (deletions included)
|
|
// signed by author, in id order, after afterID. A node that lost its database
|
|
// asks its peers for these to get its own listings back.
|
|
func (s *Store) AuthorListings(ctx context.Context, author, afterID string, limit int) ([]*listing.Listing, error) {
|
|
rows, err := s.db.QueryContext(ctx, `
|
|
SELECT data FROM listings
|
|
WHERE author = ? AND id > ? AND expires_at > ?
|
|
ORDER BY id LIMIT ?`, author, afterID, s.clock().Unix(), limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return collect(rows)
|
|
}
|
|
|
|
// 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
|
|
}
|