Skip to content

Commit

Permalink
fix: validate format in index file
Browse files Browse the repository at this point in the history
  • Loading branch information
kevmo314 committed Feb 16, 2024
1 parent 3a7a86b commit d862446
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pkg/appendable/index_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,21 @@ func NewIndexFile(f io.ReadWriteSeeker, dataHandler DataHandler) (*IndexFile, er
} else if i > 1 {
panic("expected to only reset the first page once")
} else {
// validate the metadata
buf, err := tree.Metadata()
if err != nil {
return nil, fmt.Errorf("failed to read metadata: %w", err)
}
metadata := &FileMeta{}
if err := metadata.UnmarshalBinary(buf); err != nil {
return nil, fmt.Errorf("failed to unmarshal metadata: %w", err)
}
if metadata.Version != CurrentVersion {
return nil, fmt.Errorf("unsupported version: %d", metadata.Version)
}
if metadata.Format != dataHandler.Format() {
return nil, fmt.Errorf("unsupported format: %x", metadata.Format)
}
return &IndexFile{tree: tree, dataHandler: dataHandler}, nil
}
}
Expand Down
36 changes: 36 additions & 0 deletions pkg/appendable/index_file_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package appendable

import (
"testing"

"github.com/kevmo314/appendable/pkg/buftest"
)

type FormatHandler struct{ ReturnsFormat Format }

func (f FormatHandler) Format() Format {
return f.ReturnsFormat
}

func (f FormatHandler) Synchronize(f1 *IndexFile, df []byte) error {
return nil
}

func (f FormatHandler) Parse(data []byte) []byte {
return nil
}

func TestIndexFile(t *testing.T) {
t.Run("validate metadata throws error if format doesn't match on second read", func(t *testing.T) {
f := buftest.NewSeekableBuffer()

if _, err := NewIndexFile(f, &FormatHandler{ReturnsFormat: Format(1)}); err != nil {
t.Fatal(err)
}

// try creating a new index file with a different format
if _, err := NewIndexFile(f, &FormatHandler{ReturnsFormat: Format(2)}); err == nil {
t.Fatal("expected error")
}
})
}

0 comments on commit d862446

Please sign in to comment.