Skip to content

Commit

Permalink
LogStore must also expose FirstIndex(), add to LevelDB
Browse files Browse the repository at this point in the history
  • Loading branch information
armon committed Nov 15, 2013
1 parent 85fd685 commit b6e3b23
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
19 changes: 19 additions & 0 deletions leveldb_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,25 @@ func NewLevelDBLogStore(base string) (*LevelDBLogStore, error) {
return ldb, nil
}

func (l *LevelDBLogStore) FirstIndex() (uint64, error) {
// Get an iterator
it := l.db.NewIterator(nil)
defer it.Release()

// Seek to the first value
it.First()

// Check if there is a key
key := it.Key()
if key == nil {
// Nothing written yet
return 0, it.Error()
}

// Convert the key to the index
return bytesToUint64(key), it.Error()
}

func (l *LevelDBLogStore) LastIndex() (uint64, error) {
// Get an iterator
it := l.db.NewIterator(nil)
Expand Down
36 changes: 35 additions & 1 deletion leveldb_store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,17 @@ func TestLevelDB_Logs(t *testing.T) {
}
defer l.Close()

// Should be no first index
idx, err := l.FirstIndex()
if err != nil {
t.Fatalf("err: %v ", err)
}
if idx != 0 {
t.Fatalf("bad idx: %d", idx)
}

// Should be no last index
idx, err := l.LastIndex()
idx, err = l.LastIndex()
if err != nil {
t.Fatalf("err: %v ", err)
}
Expand All @@ -151,6 +160,15 @@ func TestLevelDB_Logs(t *testing.T) {

// Write out a log
log := Log{
Index: 1,
Term: 1,
Type: LogCommand,
Data: []byte("first"),
}
if err := l.StoreLog(&log); err != nil {
t.Fatalf("err: %v", err)
}
log = Log{
Index: 10,
Term: 3,
Type: LogCommand,
Expand All @@ -165,6 +183,15 @@ func TestLevelDB_Logs(t *testing.T) {
t.Fatalf("err: %v ", err)
}

// Check the lowest index
idx, err = l.FirstIndex()
if err != nil {
t.Fatalf("err: %v ", err)
}
if idx != 1 {
t.Fatalf("bad idx: %d", idx)
}

// Check the highest index
idx, err = l.LastIndex()
if err != nil {
Expand All @@ -180,6 +207,13 @@ func TestLevelDB_Logs(t *testing.T) {
}

// Index should be zero again
idx, err = l.FirstIndex()
if err != nil {
t.Fatalf("err: %v ", err)
}
if idx != 0 {
t.Fatalf("bad idx: %d", idx)
}
idx, err = l.LastIndex()
if err != nil {
t.Fatalf("err: %v ", err)
Expand Down
3 changes: 3 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ type Log struct {
// LogStore is used to provide an interface for storing
// and retrieving logs in a durable fashion
type LogStore interface {
// Returns the first index written. 0 for no entries.
FirstIndex() (uint64, error)

// Returns the last index written. 0 for no entries.
LastIndex() (uint64, error)

Expand Down

0 comments on commit b6e3b23

Please sign in to comment.