From: Sergey Matveev <stargrave@stargrave.org>
Date: Mon, 28 Nov 2022 14:42:49 +0000 (+0300)
Subject: Delete only expired entries from fdCache
X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=e3b6cad4ae12cc43cb1d65e551292647a2f51e91;p=btrtrc.git

Delete only expired entries from fdCache
---

diff --git a/storage/file.go b/storage/file.go
index 7a5bc33d..aa67df15 100644
--- a/storage/file.go
+++ b/storage/file.go
@@ -15,8 +15,11 @@ import (
 	"github.com/anacrolix/torrent/segments"
 )
 
+const fdCacheAliveTime = 10
+
 type fdCacheEntry struct {
-	fd *os.File
+	last int64
+	fd   *os.File
 	sync.Mutex
 }
 
@@ -30,20 +33,24 @@ var (
 )
 
 func fdCacheCleaner() {
-	cleaner := func(c *map[string]*fdCacheEntry, m *sync.Mutex) {
+	cleaner := func(c map[string]*fdCacheEntry, m *sync.Mutex) {
+		now := time.Now().Unix()
 		m.Lock()
-		prev := fdRCache
-		*c = make(map[string]*fdCacheEntry)
-		m.Unlock()
-		for _, v := range prev {
-			v.Lock()
-			v.fd.Close()
-			v.Unlock()
+		for k, v := range c {
+			if now-v.last > fdCacheAliveTime {
+				go func() {
+					v.Lock()
+					v.fd.Close()
+					v.Unlock()
+				}()
+			}
+			delete(c, k)
 		}
+		m.Unlock()
 	}
-	for range time.Tick(10 * time.Second) {
-		cleaner(&fdRCache, &fdRCacheM)
-		cleaner(&fdWCache, &fdWCacheM)
+	for range time.Tick(fdCacheAliveTime * time.Second) {
+		cleaner(fdRCache, &fdRCacheM)
+		cleaner(fdWCache, &fdWCacheM)
 	}
 }
 
@@ -199,6 +206,7 @@ func (fst *fileTorrentImplIO) readFileAt(file file, b []byte, off int64) (n int,
 		b = b[:file.length-off]
 	}
 	centry.Lock()
+	centry.last = time.Now().Unix()
 	n, err = centry.fd.ReadAt(b, off)
 	centry.Unlock()
 	return
@@ -242,6 +250,7 @@ func (fst fileTorrentImplIO) WriteAt(p []byte, off int64) (n int, err error) {
 		fdWCacheM.Unlock()
 		var n1 int
 		centry.Lock()
+		centry.last = time.Now().Unix()
 		n1, err = centry.fd.WriteAt(p[:e.Length], e.Start)
 		centry.Unlock()
 		n += n1