Skip to content

Commit

Permalink
fix: handle defers properly when loading data from file
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianLoch committed Feb 3, 2025
1 parent cc86c0a commit 15e58bd
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,15 +192,28 @@ func (f *fsStorage) LoadETag(key string) (string, error) {
}

func (f *fsStorage) LoadData(key string) (io.ReadCloser, error) {
callerWillCleanupResources := false

key = strings.ToUpper(key)

unlockFileFn := f.lockFile(key, read)
defer func() {
if !callerWillCleanupResources {
unlockFileFn()
}
}()

file, err := os.Open(f.filePath(key))
if err != nil {
return nil, fmt.Errorf("opening file %q: %w", f.filePath(key), err)
}

defer func() {
if !callerWillCleanupResources {
_ = file.Close()
}
}()

var (
r io.Reader = file
dec *zstd.Decoder
Expand All @@ -212,6 +225,12 @@ func (f *fsStorage) LoadData(key string) (io.ReadCloser, error) {
return nil, fmt.Errorf("creating zstd reader: %w", err)
}

defer func() {
if !callerWillCleanupResources {
dec.Close()
}
}()

r = dec
}

Expand All @@ -220,14 +239,11 @@ func (f *fsStorage) LoadData(key string) (io.ReadCloser, error) {

// Skip the first line containing the etag
if _, _, err := bufReader.ReadLine(); err != nil && !errors.Is(err, io.EOF) {
defer file.Close()
if dec != nil {
defer dec.Close()
}

return nil, fmt.Errorf("skipping etag line in file %q: %w", f.filePath(key), err)
}

callerWillCleanupResources = true

return &closableReader{
Reader: bufReader,
closeFn: func() error {
Expand Down

0 comments on commit 15e58bd

Please sign in to comment.