// 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 }