Skip to content

Commit

Permalink
Merge pull request #7 from mobile-health/last-access-time
Browse files Browse the repository at this point in the history
Update mod time whenever reading a file
  • Loading branch information
canhlinh authored Mar 16, 2023
2 parents 128b18e + fb7643f commit 28a84af
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
6 changes: 5 additions & 1 deletion filecache.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ func (f *FileCache) Read(key string) (io.ReadCloser, error) {
return nil, err
}

if err := f.touch(key, time.Now()); err != nil {
return nil, err
}

file, err := os.Open(absFilePath)
if err != nil {
return nil, err
Expand Down Expand Up @@ -215,7 +219,7 @@ func (f *FileCache) Empty() error {
return nil
}

func (fc FileCache) Touch(key string, ts time.Time) error {
func (fc FileCache) touch(key string, ts time.Time) error {
if ts.IsZero() {
ts = time.Now()
}
Expand Down
41 changes: 39 additions & 2 deletions filecache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,43 @@ func TestWrite(t *testing.T) {
}
}

func getModTime(path string) (time.Time, error) {
fs, err := os.Stat(path)
if err != nil {
return time.Time{}, err
}
return fs.ModTime(), nil
}

func TestRead(t *testing.T) {
fc := New(Config{TempDir: "tmp"}, nil)
defer fc.Empty()

if err := fc.Write("key", sampleReader("ABC")); err != nil {
t.Fatal(err)
}

if r, err := fc.Read("key"); err != nil {
t.Fatal(err)
} else {
var buf bytes.Buffer
io.Copy(&buf, r)
if buf.String() != "ABC" {
t.Fatal("file not matched")
}
}
mt1, err := getModTime(fc.absFilePath("key"))
if err != nil {
t.Fatal(err)
}
time.Sleep(time.Second)
fc.Read("key")
mt2, _ := getModTime(fc.absFilePath("key"))
if mt2.Unix() <= mt1.Unix() {
t.Fatal("mod time must be changed")
}
}

func TestFiles(t *testing.T) {
fc := New(Config{TempDir: "tmp"}, nil)
defer fc.Empty()
Expand Down Expand Up @@ -205,8 +242,8 @@ func TestCleanCachedFileByLRU(t *testing.T) {
if err := fc.Write("key3", sampleReader(data)); err != nil {
t.Fatal(err)
}
fc.Touch("key1", time.Now().Add(-time.Minute))
fc.Touch("key3", time.Now().Add(-time.Minute))
fc.touch("key1", time.Now().Add(-time.Minute))
fc.touch("key3", time.Now().Add(-time.Minute))

if err := fc.cleanCachedFileByLRU(); err != nil {
t.Fatal(err)
Expand Down

0 comments on commit 28a84af

Please sign in to comment.