Add SQLite listing store with deterministic conflict rules
- Put verifies listings and keeps only the newest version per (author, id); equal seq resolves to the smaller hash so replicas converge - Tombstones are stored so old versions cannot be resurrected - Search by geohash prefix, kind, category, price, area, rooms - Expire removes listings and tombstones past their lifetime Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,306 @@
|
||||
// Package store persists verified listings in SQLite and answers search
|
||||
// queries. It is the single place that decides which version of a listing
|
||||
// wins, so every node converges on the same state regardless of the order in
|
||||
// which versions arrive.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalid wraps any failure of listing.Check.
|
||||
ErrInvalid = errors.New("store: invalid listing")
|
||||
// ErrNotFound is returned when a listing is absent, expired or deleted.
|
||||
ErrNotFound = errors.New("store: not found")
|
||||
)
|
||||
|
||||
// Outcome tells the caller what Put did, so the p2p layer knows whether a
|
||||
// listing is new information worth re-gossiping.
|
||||
type Outcome int
|
||||
|
||||
const (
|
||||
Ignored Outcome = iota // duplicate, or older than what we hold
|
||||
Inserted // first version we have seen
|
||||
Replaced // superseded a stored version
|
||||
)
|
||||
|
||||
func (o Outcome) String() string {
|
||||
return [...]string{"ignored", "inserted", "replaced"}[o]
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Difficulty int // required proof-of-work bits
|
||||
Clock func() time.Time // defaults to time.Now
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
difficulty int
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
const schema = `
|
||||
CREATE TABLE IF NOT EXISTS listings (
|
||||
author TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
tombstone INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
geohash TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
price_cents INTEGER NOT NULL,
|
||||
area_m2 INTEGER NOT NULL,
|
||||
rooms_x2 INTEGER NOT NULL,
|
||||
data BLOB NOT NULL,
|
||||
PRIMARY KEY (author, id)
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS listings_geohash ON listings (geohash);
|
||||
CREATE INDEX IF NOT EXISTS listings_expires ON listings (expires_at);
|
||||
`
|
||||
|
||||
// Open opens (creating if needed) the database at path. Use ":memory:" for
|
||||
// an ephemeral store.
|
||||
func Open(path string, opt Options) (*Store, error) {
|
||||
dsn := "file:" + path + "?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)"
|
||||
if path == ":memory:" {
|
||||
dsn = "file::memory:?_pragma=busy_timeout(5000)"
|
||||
}
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// One connection: serializes writers and keeps :memory: coherent.
|
||||
db.SetMaxOpenConns(1)
|
||||
if _, err := db.Exec(schema); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock}
|
||||
if s.clock == nil {
|
||||
s.clock = time.Now
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
|
||||
// Put verifies l and stores it if it is the newest version known.
|
||||
//
|
||||
// Conflict rules (identical on every node, so replicas converge):
|
||||
// - listings are keyed by (author, id): nobody can squat another author's id;
|
||||
// - a higher seq wins;
|
||||
// - on equal seq (an author signing two versions), the smaller hash wins;
|
||||
// - tombstones are stored like any other version, so a late-arriving older
|
||||
// version cannot resurrect a deleted listing.
|
||||
func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
|
||||
if err := l.Check(s.clock(), s.difficulty); err != nil {
|
||||
return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err)
|
||||
}
|
||||
data, err := l.Bytes()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
hash, err := l.Hash()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var curSeq int64
|
||||
var curHash string
|
||||
err = tx.QueryRowContext(ctx,
|
||||
`SELECT seq, hash FROM listings WHERE author = ? AND id = ?`, l.Author, l.ID).
|
||||
Scan(&curSeq, &curHash)
|
||||
outcome := Inserted
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
case err != nil:
|
||||
return Ignored, err
|
||||
default:
|
||||
seq := int64(l.Seq)
|
||||
if seq < curSeq || (seq == curSeq && hash >= curHash) {
|
||||
return Ignored, nil
|
||||
}
|
||||
outcome = Replaced
|
||||
}
|
||||
|
||||
var price int64
|
||||
if l.Price != nil {
|
||||
price = l.Price.AmountCents
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT OR REPLACE INTO listings
|
||||
(author, id, seq, hash, tombstone, created_at, expires_at, geohash,
|
||||
kind, category, price_cents, area_m2, rooms_x2, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
l.Author, l.ID, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt,
|
||||
l.Geohash, l.Kind, l.Category, price, l.AreaM2, l.RoomsX2, data)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
return outcome, nil
|
||||
}
|
||||
|
||||
// Get returns the live (not deleted, not expired) listing.
|
||||
func (s *Store) Get(ctx context.Context, author, id string) (*listing.Listing, error) {
|
||||
var data []byte
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT data FROM listings
|
||||
WHERE author = ? AND id = ? AND tombstone = 0 AND expires_at > ?`,
|
||||
author, id, s.clock().Unix()).Scan(&data)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decode(data)
|
||||
}
|
||||
|
||||
// Query selects live listings. Zero values mean "no constraint".
|
||||
type Query struct {
|
||||
Geohashes []string // prefixes; a listing matches if it starts with any
|
||||
Kind string
|
||||
Category string
|
||||
MinPriceCents int64
|
||||
MaxPriceCents int64
|
||||
MinAreaM2 int
|
||||
MinRoomsX2 int
|
||||
Limit int // default 50, max 200
|
||||
Offset int
|
||||
}
|
||||
|
||||
// Search returns live listings, newest first.
|
||||
func (s *Store) Search(ctx context.Context, q Query) ([]*listing.Listing, error) {
|
||||
where := []string{"tombstone = 0", "expires_at > ?"}
|
||||
args := []any{s.clock().Unix()}
|
||||
|
||||
if len(q.Geohashes) > 0 {
|
||||
var ors []string
|
||||
for _, p := range q.Geohashes {
|
||||
if !listing.ValidGeohashPrefix(p) {
|
||||
return nil, fmt.Errorf("store: invalid geohash prefix %q", p)
|
||||
}
|
||||
ors = append(ors, "(geohash >= ? AND geohash <= ?)")
|
||||
// '~' sorts after every geohash character.
|
||||
args = append(args, p, p+"~")
|
||||
}
|
||||
where = append(where, "("+strings.Join(ors, " OR ")+")")
|
||||
}
|
||||
if q.Kind != "" {
|
||||
where = append(where, "kind = ?")
|
||||
args = append(args, q.Kind)
|
||||
}
|
||||
if q.Category != "" {
|
||||
where = append(where, "category = ?")
|
||||
args = append(args, q.Category)
|
||||
}
|
||||
if q.MinPriceCents > 0 {
|
||||
where = append(where, "price_cents >= ?")
|
||||
args = append(args, q.MinPriceCents)
|
||||
}
|
||||
if q.MaxPriceCents > 0 {
|
||||
where = append(where, "price_cents <= ?")
|
||||
args = append(args, q.MaxPriceCents)
|
||||
}
|
||||
if q.MinAreaM2 > 0 {
|
||||
where = append(where, "area_m2 >= ?")
|
||||
args = append(args, q.MinAreaM2)
|
||||
}
|
||||
if q.MinRoomsX2 > 0 {
|
||||
where = append(where, "rooms_x2 >= ?")
|
||||
args = append(args, q.MinRoomsX2)
|
||||
}
|
||||
|
||||
limit := q.Limit
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
offset := q.Offset
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
args = append(args, limit, offset)
|
||||
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT data FROM listings WHERE `+strings.Join(where, " AND ")+
|
||||
` ORDER BY created_at DESC, author, id LIMIT ? OFFSET ?`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []*listing.Listing
|
||||
for rows.Next() {
|
||||
var data []byte
|
||||
if err := rows.Scan(&data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l, err := decode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, l)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Expire deletes everything whose lifetime has ended, tombstones included,
|
||||
// and returns how many rows were removed. A tombstone outlives any version it
|
||||
// supersedes because listings live at most 30 days from creation.
|
||||
func (s *Store) Expire(ctx context.Context) (int64, error) {
|
||||
res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, s.clock().Unix())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// Count returns the number of live listings.
|
||||
func (s *Store) Count(ctx context.Context) (int, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM listings WHERE tombstone = 0 AND expires_at > ?`,
|
||||
s.clock().Unix()).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func decode(data []byte) (*listing.Listing, error) {
|
||||
var l listing.Listing
|
||||
if err := json.Unmarshal(data, &l); err != nil {
|
||||
return nil, fmt.Errorf("store: corrupt row: %w", err)
|
||||
}
|
||||
return &l, nil
|
||||
}
|
||||
|
||||
func boolInt(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
const difficulty = 8
|
||||
|
||||
var (
|
||||
ctx = context.Background()
|
||||
t0 = time.Unix(1_800_000_000, 0)
|
||||
)
|
||||
|
||||
type env struct {
|
||||
s *Store
|
||||
now time.Time
|
||||
key *identity.Identity
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T) *env {
|
||||
t.Helper()
|
||||
e := &env{now: t0}
|
||||
e.key, _ = identity.Generate()
|
||||
s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
e.s = s
|
||||
return e
|
||||
}
|
||||
|
||||
func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.Listing {
|
||||
t.Helper()
|
||||
id, _ := listing.NewID()
|
||||
l := &listing.Listing{
|
||||
Version: listing.Version,
|
||||
ID: id,
|
||||
Seq: 1,
|
||||
CreatedAt: e.now.Unix(),
|
||||
ExpiresAt: e.now.Add(7 * 24 * time.Hour).Unix(),
|
||||
Kind: "rent",
|
||||
Category: "apartment",
|
||||
Geohash: "u1xjhx",
|
||||
Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"},
|
||||
AreaM2: 50,
|
||||
RoomsX2: 4,
|
||||
Title: "Wohnung",
|
||||
Endpoint: "12D3KooWExamplePeerID",
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(l)
|
||||
}
|
||||
if err := l.Seal(e.key, difficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func (e *env) put(t *testing.T, l *listing.Listing) Outcome {
|
||||
t.Helper()
|
||||
o, err := e.s.Put(ctx, l)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func TestPutGet(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
l := e.listing(t, nil)
|
||||
if o := e.put(t, l); o != Inserted {
|
||||
t.Fatalf("got %v want inserted", o)
|
||||
}
|
||||
got, err := e.s.Get(ctx, l.Author, l.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, _ := l.Bytes()
|
||||
b, _ := got.Bytes()
|
||||
if string(a) != string(b) {
|
||||
t.Fatal("stored listing differs from original")
|
||||
}
|
||||
if o := e.put(t, l); o != Ignored {
|
||||
t.Fatalf("duplicate: got %v want ignored", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectsInvalid(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
l := e.listing(t, nil)
|
||||
l.Price.AmountCents = 1 // breaks signature
|
||||
_, err := e.s.Put(ctx, l)
|
||||
if !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("got %v, want ErrInvalid", err)
|
||||
}
|
||||
if n, _ := e.s.Count(ctx); n != 0 {
|
||||
t.Fatal("invalid listing was stored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHigherSeqWinsInAnyOrder(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
v1 := e.listing(t, nil)
|
||||
v2 := *v1
|
||||
v2.Seq = 2
|
||||
v2.Title = "Neuer Titel"
|
||||
if err := v2.Seal(e.key, difficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Newer first, older second: older must be ignored.
|
||||
if o := e.put(t, &v2); o != Inserted {
|
||||
t.Fatalf("v2: %v", o)
|
||||
}
|
||||
if o := e.put(t, v1); o != Ignored {
|
||||
t.Fatalf("v1 after v2: got %v want ignored", o)
|
||||
}
|
||||
got, _ := e.s.Get(ctx, v1.Author, v1.ID)
|
||||
if got.Title != "Neuer Titel" {
|
||||
t.Fatalf("got %q", got.Title)
|
||||
}
|
||||
|
||||
// Fresh store, natural order: second is a replacement.
|
||||
e2 := newEnv(t)
|
||||
e2.key = e.key
|
||||
e2.put(t, v1)
|
||||
if o := e2.put(t, &v2); o != Replaced {
|
||||
t.Fatalf("got %v want replaced", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
a := e.listing(t, nil)
|
||||
b := *a
|
||||
b.Title = "Anderer Titel"
|
||||
if err := b.Seal(e.key, difficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ha, _ := a.Hash()
|
||||
hb, _ := b.Hash()
|
||||
winner, loser := a, &b
|
||||
if hb < ha {
|
||||
winner, loser = &b, a
|
||||
}
|
||||
|
||||
for name, order := range map[string][]*listing.Listing{
|
||||
"winner first": {winner, loser},
|
||||
"loser first": {loser, winner},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
e2 := newEnv(t)
|
||||
e2.key = e.key
|
||||
for _, l := range order {
|
||||
e2.put(t, l)
|
||||
}
|
||||
got, _ := e2.s.Get(ctx, a.Author, a.ID)
|
||||
if got.Title != winner.Title {
|
||||
t.Fatalf("converged on %q, want %q", got.Title, winner.Title)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
ts := &listing.Listing{
|
||||
Version: listing.Version, ID: l.ID, Seq: l.Seq + 1,
|
||||
CreatedAt: e.now.Unix(), ExpiresAt: e.now.Add(30 * 24 * time.Hour).Unix(),
|
||||
Tombstone: true, Geohash: l.Geohash,
|
||||
}
|
||||
if err := ts.Seal(e.key, difficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if o := e.put(t, ts); o != Replaced {
|
||||
t.Fatalf("got %v want replaced", o)
|
||||
}
|
||||
if _, err := e.s.Get(ctx, l.Author, l.ID); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("deleted listing still readable: %v", err)
|
||||
}
|
||||
if o := e.put(t, l); o != Ignored {
|
||||
t.Fatalf("old version resurrected: %v", o)
|
||||
}
|
||||
if n, _ := e.s.Count(ctx); n != 0 {
|
||||
t.Fatalf("count %d, want 0", n)
|
||||
}
|
||||
|
||||
// A tombstone arriving before the listing it deletes still wins.
|
||||
e2 := newEnv(t)
|
||||
e2.key = e.key
|
||||
e2.put(t, ts)
|
||||
if o := e2.put(t, l); o != Ignored {
|
||||
t.Fatalf("listing after tombstone: %v", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
victim := e.listing(t, nil)
|
||||
e.put(t, victim)
|
||||
|
||||
other, _ := identity.Generate()
|
||||
squat := *victim
|
||||
squat.Seq = 99
|
||||
squat.Title = "Betrug"
|
||||
if err := squat.Seal(other, difficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.put(t, &squat)
|
||||
|
||||
got, err := e.s.Get(ctx, victim.Author, victim.ID)
|
||||
if err != nil || got.Title != "Wohnung" {
|
||||
t.Fatalf("victim listing disturbed: %v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearch(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
mk := func(geo, kind string, cents int64, area, rooms int) {
|
||||
period := map[string]string{"rent": "month", "sale": "once"}[kind]
|
||||
e.put(t, e.listing(t, func(l *listing.Listing) {
|
||||
l.Geohash, l.Kind = geo, kind
|
||||
l.Price = &listing.Price{AmountCents: cents, Currency: "EUR", Period: period}
|
||||
l.AreaM2, l.RoomsX2 = area, rooms
|
||||
}))
|
||||
}
|
||||
mk("u1xjhx", "rent", 90000, 40, 3)
|
||||
mk("u1xjhz", "rent", 150000, 80, 6)
|
||||
mk("u1xkbb", "rent", 120000, 60, 4)
|
||||
mk("u1xjhx", "sale", 30000000, 90, 6)
|
||||
mk("u30000", "rent", 100000, 50, 4) // different region
|
||||
|
||||
count := func(q Query) int {
|
||||
t.Helper()
|
||||
got, err := e.s.Search(ctx, q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return len(got)
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
q Query
|
||||
want int
|
||||
}{
|
||||
{"all", Query{}, 5},
|
||||
{"region prefix", Query{Geohashes: []string{"u1x"}}, 4},
|
||||
{"narrow prefix", Query{Geohashes: []string{"u1xjh"}}, 3},
|
||||
{"two prefixes", Query{Geohashes: []string{"u1xk", "u3"}}, 2},
|
||||
{"rent in region", Query{Geohashes: []string{"u1x"}, Kind: "rent"}, 3},
|
||||
{"price range", Query{Kind: "rent", MinPriceCents: 95000, MaxPriceCents: 130000}, 2},
|
||||
{"min area", Query{Kind: "rent", MinAreaM2: 55}, 2},
|
||||
{"min rooms", Query{MinRoomsX2: 6}, 2},
|
||||
{"limit", Query{Limit: 2}, 2},
|
||||
{"offset", Query{Offset: 4}, 1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := count(tc.q); got != tc.want {
|
||||
t.Fatalf("got %d want %d", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if _, err := e.s.Search(ctx, Query{Geohashes: []string{"u1x' OR 1=1 --"}}); err == nil {
|
||||
t.Fatal("invalid geohash prefix accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiry(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
e.now = e.now.Add(8 * 24 * time.Hour)
|
||||
if _, err := e.s.Get(ctx, l.Author, l.ID); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatal("expired listing still readable")
|
||||
}
|
||||
if got, _ := e.s.Search(ctx, Query{}); len(got) != 0 {
|
||||
t.Fatal("expired listing in search results")
|
||||
}
|
||||
n, err := e.s.Expire(ctx)
|
||||
if err != nil || n != 1 {
|
||||
t.Fatalf("Expire = %d, %v; want 1", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistence(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "allmende.db")
|
||||
key, _ := identity.Generate()
|
||||
opt := Options{Difficulty: difficulty, Clock: func() time.Time { return t0 }}
|
||||
|
||||
s, err := Open(path, opt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e := &env{s: s, now: t0, key: key}
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
s.Close()
|
||||
|
||||
s, err = Open(path, opt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err := s.Get(ctx, l.Author, l.ID); err != nil {
|
||||
t.Fatalf("listing lost after reopen: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user