Skip to content

Commit

Permalink
wal: fix panic when decoder not set
Browse files Browse the repository at this point in the history
Handle the related panic and clarify doc.
  • Loading branch information
spzala committed Jun 21, 2020
1 parent 91b1a91 commit 7d1cf64
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
8 changes: 7 additions & 1 deletion wal/wal.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ var (
ErrCRCMismatch = errors.New("wal: crc mismatch")
ErrSnapshotMismatch = errors.New("wal: snapshot mismatch")
ErrSnapshotNotFound = errors.New("wal: snapshot not found")
ErrDecoderNotFound = errors.New("wal: decoder not found")
crcTable = crc32.MakeTable(crc32.Castagnoli)
)

Expand Down Expand Up @@ -95,7 +96,8 @@ type WAL struct {
}

// Create creates a WAL ready for appending records. The given metadata is
// recorded at the head of each WAL file, and can be retrieved with ReadAll.
// recorded at the head of each WAL file, and can be retrieved with ReadAll
// after the file is Open.
func Create(lg *zap.Logger, dirpath string, metadata []byte) (*WAL, error) {
if Exist(dirpath) {
return nil, os.ErrExist
Expand Down Expand Up @@ -434,6 +436,10 @@ func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.
defer w.mu.Unlock()

rec := &walpb.Record{}

if w.decoder == nil {
return nil, state, nil, ErrDecoderNotFound
}
decoder := w.decoder

var match bool
Expand Down
21 changes: 21 additions & 0 deletions wal/wal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1059,3 +1059,24 @@ func TestValidSnapshotEntriesAfterPurgeWal(t *testing.T) {
t.Fatal(err)
}
}

// TestReadAllFail ensure ReadAll error if used without opening the WAL
func TestReadAllFail(t *testing.T) {
dir, err := ioutil.TempDir(os.TempDir(), "waltest")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)

// create initial WAL
f, err := Create(zap.NewExample(), dir, []byte("metadata"))
if err != nil {
t.Fatal(err)
}
f.Close()
// try to read without opening the WAL
_, _, _, err = f.ReadAll()
if err == nil || err != ErrDecoderNotFound {
t.Fatalf("err = %v, want ErrDecoderNotFound", err)
}
}

0 comments on commit 7d1cf64

Please sign in to comment.