Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lexi: add KV argument type #3199

Merged
merged 1 commit into from
Mar 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions dex/lexi/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package lexi

import (
"bytes"
"encoding"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -66,11 +65,11 @@ func (v *tValue) MarshalBinary() ([]byte, error) {
return v.v, nil
}

func valueIndex(k, v encoding.BinaryMarshaler) ([]byte, error) {
func valueIndex(k, v KV) ([]byte, error) {
return v.(*tValue).idx, nil
}

func valueKey(k, v encoding.BinaryMarshaler) ([]byte, error) {
func valueKey(k, v KV) ([]byte, error) {
return v.(*tValue).k, nil
}

Expand Down Expand Up @@ -109,7 +108,7 @@ func TestIndex(t *testing.T) {
indexKey = append(prefix, indexKey...)
v := &tValue{k: indexKey, v: encode.RandomBytes(10), idx: []byte{byte(i)}}
vs[i] = v
if err := tbl.Set(B(k), v); err != nil {
if err := tbl.Set(k, v); err != nil {
t.Fatalf("Error setting table entry: %v", err)
}
}
Expand Down
37 changes: 6 additions & 31 deletions dex/lexi/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@ package lexi

import (
"bytes"
"encoding"
"encoding/binary"
"errors"
"fmt"
"time"

"decred.org/dcrdex/dex"
"github.com/dgraph-io/badger"
Expand All @@ -29,13 +26,13 @@ type Index struct {
name string
table *Table
prefix keyPrefix
f func(k, v encoding.BinaryMarshaler) ([]byte, error)
f func(k, v KV) ([]byte, error)
defaultIterationOptions iteratorOpts
}

// AddIndex adds an index to a Table. Once an Index is added, every datum
// Set in the Table will generate an entry in the Index too.
func (t *Table) AddIndex(name string, f func(k, v encoding.BinaryMarshaler) ([]byte, error)) (*Index, error) {
func (t *Table) AddIndex(name string, f func(k, v KV) ([]byte, error)) (*Index, error) {
p, err := t.prefixForName(t.name + "__idx__" + name)
if err != nil {
return nil, err
Expand All @@ -51,7 +48,7 @@ func (t *Table) AddIndex(name string, f func(k, v encoding.BinaryMarshaler) ([]b
return idx, nil
}

func (idx *Index) add(txn *badger.Txn, k, v encoding.BinaryMarshaler, dbID DBID) ([]byte, error) {
func (idx *Index) add(txn *badger.Txn, k, v KV, dbID DBID) ([]byte, error) {
idxB, err := idx.f(k, v)
if err != nil {
return nil, fmt.Errorf("error getting index value: %w", err)
Expand Down Expand Up @@ -172,37 +169,15 @@ func (i *Iter) Delete() error {
return i.table.deleteDatum(i.txn, i.dbID, d)
}

// IndexBucket is any one of a number of common types whose binary encoding is
// straight-forward. An IndexBucket restricts Iterate to the entries in the
// index that have the bytes decoded from the IndexBucket as the prefix.
type IndexBucket interface{}

func parseIndexBucket(i IndexBucket) (b []byte, err error) {
switch it := i.(type) {
case []byte:
b = it
case uint32:
b = make([]byte, 4)
binary.BigEndian.PutUint32(b[:], it)
case time.Time:
b = make([]byte, 8)
binary.BigEndian.PutUint64(b[:], uint64(it.UnixMilli()))
case nil:
default:
err = fmt.Errorf("unknown IndexBucket type %T", it)
}
return
}

// Iterate iterates the index, providing access to the index entry, datum, and
// datum key via the Iter.
func (idx *Index) Iterate(prefixI IndexBucket, f func(*Iter) error, iterOpts ...IterationOption) error {
func (idx *Index) Iterate(prefixI KV, f func(*Iter) error, iterOpts ...IterationOption) error {
return idx.iterate(idx.prefix, idx.table, idx.defaultIterationOptions, true, prefixI, f, iterOpts...)
}

// iterate iterates a table or index.
func (db *DB) iterate(keyPfix keyPrefix, table *Table, io iteratorOpts, isIndex bool, prefixI IndexBucket, f func(*Iter) error, iterOpts ...IterationOption) error {
prefix, err := parseIndexBucket(prefixI)
func (db *DB) iterate(keyPfix keyPrefix, table *Table, io iteratorOpts, isIndex bool, prefixI KV, f func(*Iter) error, iterOpts ...IterationOption) error {
prefix, err := parseKV(prefixI)
if err != nil {
return err
}
Expand Down
29 changes: 21 additions & 8 deletions dex/lexi/lexi.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,25 @@ func (db *DB) deleteDBID(txn *badger.Txn, dbID DBID) error {
return nil
}

// B is a byte slice that implements encoding.BinaryMarshaler.
type B []byte

var _ encoding.BinaryMarshaler = B{}

// MarshalBinary implements encoding.BinaryMarshaler for the B.
func (b B) MarshalBinary() ([]byte, error) {
return b, nil
// KV is any one of a number of common types whose binary encoding is
// straight-forward.
type KV interface{}

func parseKV(i KV) (b []byte, err error) {
switch it := i.(type) {
case []byte:
b = it
case uint32:
b = make([]byte, 4)
binary.BigEndian.PutUint32(b[:], it)
case time.Time:
b = make([]byte, 8)
binary.BigEndian.PutUint64(b[:], uint64(it.UnixMilli()))
case encoding.BinaryMarshaler:
b, err = it.MarshalBinary()
case nil:
default:
err = fmt.Errorf("unknown IndexBucket type %T", it)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
err = fmt.Errorf("unknown IndexBucket type %T", it)
err = fmt.Errorf("unknown KV type %T", it)

}
return
}
14 changes: 7 additions & 7 deletions dex/lexi/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ func (db *DB) Table(name string) (*Table, error) {
}

// GetRaw retrieves a value from the Table as raw bytes.
func (t *Table) GetRaw(k encoding.BinaryMarshaler) (b []byte, err error) {
kB, err := k.MarshalBinary()
func (t *Table) GetRaw(k KV) (b []byte, err error) {
kB, err := parseKV(k)
if err != nil {
return nil, fmt.Errorf("error marshaling key: %w", err)
}
Expand All @@ -58,7 +58,7 @@ func (t *Table) GetRaw(k encoding.BinaryMarshaler) (b []byte, err error) {
}

// Get retrieves a value from the Table.
func (t *Table) Get(k encoding.BinaryMarshaler, thing encoding.BinaryUnmarshaler) error {
func (t *Table) Get(k KV, thing encoding.BinaryUnmarshaler) error {
b, err := t.GetRaw(k)
if err != nil {
return err
Expand Down Expand Up @@ -114,8 +114,8 @@ func (t *Table) UseDefaultSetOptions(setOpts ...SetOption) {
}

// Set inserts a new value for the key, and creates index entries.
func (t *Table) Set(k, v encoding.BinaryMarshaler, setOpts ...SetOption) error {
kB, err := k.MarshalBinary()
func (t *Table) Set(k, v KV, setOpts ...SetOption) error {
kB, err := parseKV(k)
if err != nil {
return fmt.Errorf("error marshaling key: %w", err)
}
Expand All @@ -124,7 +124,7 @@ func (t *Table) Set(k, v encoding.BinaryMarshaler, setOpts ...SetOption) error {
if len(kB) == 0 {
return errors.New("no zero-length keys allowed")
}
vB, err := v.MarshalBinary()
vB, err := parseKV(v)
if err != nil {
return fmt.Errorf("error marshaling value: %w", err)
}
Expand Down Expand Up @@ -210,6 +210,6 @@ func (t *Table) UseDefaultIterationOptions(optss ...IterationOption) {
}

// Iterate iterates the table.
func (t *Table) Iterate(prefixI IndexBucket, f func(*Iter) error, iterOpts ...IterationOption) error {
func (t *Table) Iterate(prefixI KV, f func(*Iter) error, iterOpts ...IterationOption) error {
return t.iterate(t.prefix, t, t.defaultIterationOptions, false, prefixI, f, iterOpts...)
}
2 changes: 1 addition & 1 deletion tatanka/client/mesh/mesh.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ func (m *Mesh) SubscribeToFiatRates() error {
// PostBond stores the bond in the database and sends it to the mesh.
func (m *Mesh) PostBond(bond *tanka.Bond) error {
k := bond.ID()
if err := m.bondTable.Set(lexi.B(k[:]), lexi.JSON(bond)); err != nil {
if err := m.bondTable.Set(k[:], lexi.JSON(bond)); err != nil {
return fmt.Errorf("error storing bond in DB: %w", err)
}
req := mj.MustRequest(mj.RoutePostBond, []*tanka.Bond{bond})
Expand Down
2 changes: 1 addition & 1 deletion tatanka/db/bonds.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (bond *dbBond) UnmarshalBinary(b []byte) error {
}

func (d *DB) StoreBond(newBond *tanka.Bond) error {
return d.bonds.Set(lexi.B(newBond.CoinID), &dbBond{newBond}, lexi.WithReplace())
return d.bonds.Set(newBond.CoinID[:], &dbBond{newBond}, lexi.WithReplace())
}

func (d *DB) GetBonds(peerID tanka.PeerID) ([]*tanka.Bond, error) {
Expand Down
11 changes: 5 additions & 6 deletions tatanka/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package db

import (
"context"
"encoding"
"encoding/binary"
"errors"
"fmt"
Expand Down Expand Up @@ -51,12 +50,12 @@ func New(dir string, log dex.Logger) (*DB, error) {
if err != nil {
return nil, fmt.Errorf("error initializing meta table: %w", err)
}
verB, err := metaTable.GetRaw(lexi.B(versionKey))
verB, err := metaTable.GetRaw(versionKey)
if err != nil {
if errors.Is(err, lexi.ErrKeyNotFound) {
// fresh install
verB = []byte{DBVersion}
metaTable.Set(lexi.B(versionKey), lexi.B(verB))
metaTable.Set(versionKey, verB)
} else {
return nil, fmt.Errorf("error getting version")
}
Expand All @@ -78,7 +77,7 @@ func New(dir string, log dex.Logger) (*DB, error) {
return nil, fmt.Errorf("error constructing reputation table: %w", err)
}
// Scored peer index with timestamp sorting.
scoredIdx, err := scoreTable.AddIndex("scored-stamp", func(_, v encoding.BinaryMarshaler) ([]byte, error) {
scoredIdx, err := scoreTable.AddIndex("scored-stamp", func(_, v lexi.KV) ([]byte, error) {
s, is := v.(*dbScore)
if !is {
return nil, fmt.Errorf("wrong type %T", v)
Expand All @@ -98,7 +97,7 @@ func New(dir string, log dex.Logger) (*DB, error) {
return nil, fmt.Errorf("error initializing bonds table: %w", err)
}
// Retrieve bonds by peer ID.
bonderIdx, err := bondsTable.AddIndex("bonder", func(_, v encoding.BinaryMarshaler) ([]byte, error) {
bonderIdx, err := bondsTable.AddIndex("bonder", func(_, v lexi.KV) ([]byte, error) {
b, is := v.(*dbBond)
if !is {
return nil, fmt.Errorf("wrong type %T", v)
Expand All @@ -109,7 +108,7 @@ func New(dir string, log dex.Logger) (*DB, error) {
return nil, fmt.Errorf("error initializing bonder index: %w", err)
}
// We'll periodically prune expired bonds.
bondStampIdx, err := bondsTable.AddIndex("bond-stamp", func(_, v encoding.BinaryMarshaler) ([]byte, error) {
bondStampIdx, err := bondsTable.AddIndex("bond-stamp", func(_, v lexi.KV) ([]byte, error) {
b, is := v.(*dbBond)
if !is {
return nil, fmt.Errorf("wrong type %T", v)
Expand Down
2 changes: 1 addition & 1 deletion tatanka/db/reputation.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (d *DB) SetScore(scored, scorer tanka.PeerID, score int8, stamp time.Time)
score: score,
stamp: stamp,
}
return d.scores.Set(lexi.B(k), s, lexi.WithReplace())
return d.scores.Set(k, s, lexi.WithReplace())
}

func (d *DB) Reputation(scored tanka.PeerID) (*tanka.Reputation, error) {
Expand Down
Loading