Skip to content

Commit

Permalink
fix: add rwlock for file to ensure thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
rfyiamcool committed May 7, 2023
1 parent 2e91846 commit 1838665
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
26 changes: 19 additions & 7 deletions file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,21 @@ func (f *file) read(key string) (*fileContent, error) {
return content, nil
}

if content.Duration <= time.Now().Unix() {
_ = f.Delete(key)
return nil, errors.New("cache expired")
}

return content, nil
}

// Contains checks if the cached key exists into the File storage
func (f *file) Contains(key string) bool {
_, err := f.read(key)
return err == nil
content, err := f.read(key)
if err != nil {
return false
}

if f.isExpired(content) {
_ = f.Delete(key)
return false
}
return true
}

// Delete the cached key from File storage
Expand All @@ -95,9 +98,18 @@ func (f *file) Fetch(key string) (string, error) {
return "", err
}

if f.isExpired(content) {
_ = f.Delete(key)
return "", errors.New("cache expired")
}

return content.Data, nil
}

func (f *file) isExpired(content *fileContent) bool {
return content.Duration > 0 && content.Duration <= time.Now().Unix()
}

// FetchMulti retrieve multiple cached values from keys of the File storage
func (f *file) FetchMulti(keys []string) map[string]string {
result := make(map[string]string)
Expand Down
2 changes: 1 addition & 1 deletion file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func TestFile(t *testing.T) {

_ = c.Save("bar", testValue, 0)

if values := c.FetchMulti([]string{testKey, "bar"}); len(values) == 0 {
if values := c.FetchMulti([]string{testKey, "bar"}); len(values) != 2 {
t.Errorf("fetch multi failed: expected %d, got %d", 2, len(values))
}

Expand Down

0 comments on commit 1838665

Please sign in to comment.