Skip to content

Commit 38e30a1

Browse files
committed
Implement new setting OneCacheForAll
Implement storage.cleanPieces which is used when option OneCacheForAll is enabled. It cleans pieces in caches starting with least recently modified
1 parent 36c6268 commit 38e30a1

File tree

2 files changed

+63
-2
lines changed

2 files changed

+63
-2
lines changed

server/torr/storage/torrstor/cache.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ func (c *Cache) GetState() *state.CacheState {
184184
return cState
185185
}
186186

187-
func (c *Cache) cleanPieces() {
187+
func (c *Cache) doCleanPieces() {
188188
if c.isRemove || c.isClosed {
189189
return
190190
}
@@ -211,6 +211,14 @@ func (c *Cache) cleanPieces() {
211211
}
212212
}
213213

214+
func (c *Cache) cleanPieces() {
215+
if settings.BTsets.OneCacheForAll {
216+
c.storage.cleanPieces()
217+
} else {
218+
c.doCleanPieces()
219+
}
220+
}
221+
214222
func (c *Cache) getRemPieces() []*Piece {
215223
piecesRemove := make([]*Piece, 0)
216224
fill := int64(0)

server/torr/storage/torrstor/storage.go

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,12 @@ package torrstor
22

33
import (
44
"sync"
5-
5+
"slices"
6+
"os"
7+
"path/filepath"
8+
"server/log"
69
"server/torr/storage"
10+
"server/settings"
711

812
"github.com/anacrolix/torrent/metainfo"
913
ts "github.com/anacrolix/torrent/storage"
@@ -70,3 +74,52 @@ func (s *Storage) GetCache(hash metainfo.Hash) *Cache {
7074
}
7175
return nil
7276
}
77+
78+
func (s *Storage) cleanPieces() {
79+
s.mu.Lock()
80+
defer s.mu.Unlock()
81+
var filled int64 = 0
82+
for _, ch := range s.caches {
83+
filled += ch.filled
84+
}
85+
overfill := filled - s.capacity
86+
if overfill < 0 {
87+
return
88+
}
89+
sortCachesByModifiedDate := func(a, b *Cache) int {
90+
aname := filepath.Join(settings.BTsets.TorrentsSavePath, a.hash.HexString())
91+
bname := filepath.Join(settings.BTsets.TorrentsSavePath, b.hash.HexString())
92+
ainfo, err := os.Stat(aname)
93+
if err != nil {
94+
return -1
95+
}
96+
binfo, err := os.Stat(bname)
97+
if err != nil {
98+
return 1
99+
}
100+
return ainfo.ModTime().Compare(binfo.ModTime())
101+
}
102+
nonempty := slices.Values(slices.Collect(func(yield func(*Cache) bool) {
103+
for _, c := range s.caches {
104+
if c.filled > 0 {
105+
if !yield(c) {
106+
return
107+
}
108+
}
109+
}
110+
}))
111+
// fill sortedcaches with refs to non-empty caches sorted by respective
112+
// folder modified date in descending order (older first)
113+
sortedcaches := slices.SortedFunc(nonempty, sortCachesByModifiedDate)
114+
for _, c := range sortedcaches {
115+
_cap := c.capacity
116+
c.capacity = max(c.filled - overfill, 0)
117+
overfill -= c.filled
118+
c.doCleanPieces()
119+
overfill += c.filled
120+
c.capacity = _cap
121+
if overfill <= 0 {
122+
return
123+
}
124+
}
125+
}

0 commit comments

Comments
 (0)