From 433f5016e22a9667b3d845a1b1dfe7c08538a5fb Mon Sep 17 00:00:00 2001 From: Philip O'Toole Date: Thu, 4 Jan 2024 20:35:25 -0500 Subject: [PATCH] Add function to test if log is "empty" --- log/log.go | 16 ++++++++++++++++ log/log_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/log/log.go b/log/log.go index 612499e1..5e8d7781 100644 --- a/log/log.go +++ b/log/log.go @@ -71,6 +71,22 @@ func (l *Log) LastCommandIndex(fi, li uint64) (uint64, error) { return 0, nil } +// HasCommand returns whether the Raft log contains any Command log entries. +func (l *Log) HasCommand() (bool, error) { + fi, li, err := l.Indexes() + if err != nil { + return false, err + } + if fi == 0 || li == 0 { + return false, nil + } + i, err := l.LastCommandIndex(fi, li) + if err != nil { + return false, err + } + return i != 0, nil +} + // SetAppliedIndex sets the AppliedIndex value. func (l *Log) SetAppliedIndex(index uint64) error { return l.SetUint64([]byte(rqliteAppliedIndex), index) diff --git a/log/log_test.go b/log/log_test.go index 203f34c3..20cc09de 100644 --- a/log/log_test.go +++ b/log/log_test.go @@ -40,6 +40,14 @@ func Test_LogNewEmpty(t *testing.T) { if lci != 0 { t.Fatalf("got wrong value for last command index of not empty log: %d", lci) } + + f, err := l.HasCommand() + if err != nil { + t.Fatalf("failed to get has command: %s", err) + } + if f { + t.Fatalf("got wrong value for has command of empty log: %v", f) + } } func Test_LogNewExistNotEmpty(t *testing.T) { @@ -91,6 +99,14 @@ func Test_LogNewExistNotEmpty(t *testing.T) { t.Fatalf("got wrong value for last command index of not empty log: %d", lci) } + f, err := l.HasCommand() + if err != nil { + t.Fatalf("failed to get has command: %s", err) + } + if !f { + t.Fatalf("got wrong value for has command of non-empty log: %v", f) + } + if err := l.Close(); err != nil { t.Fatalf("failed to close log: %s", err) } @@ -311,6 +327,14 @@ func Test_LogDeleteAll(t *testing.T) { if li != 0 { t.Fatalf("got wrong value for last index of empty log: %d", li) } + + f, err := l.HasCommand() + if err != nil { + t.Fatalf("failed to get has command: %s", err) + } + if f { + t.Fatalf("got wrong value for has command of empty log: %v", f) + } } func Test_LogLastCommandIndexNotExist(t *testing.T) {