Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,26 @@ environment:
> Going public? Always put it behind **TLS** (a reverse proxy) so the session cookie is
> `Secure`, and prefer a **VPN** when you can. See [Security](#security).

### Disk cleanup (disk mode)

In **RAM mode** nothing is written to disk, so there's nothing to clean. In **disk mode**
FluxTorrent frees space automatically so `/downloads` never fills up. Tune it in the
**Settings → Disk cleanup** screen:

| Setting | Default | What it does |
|---|---|---|
| **Disk limit (GB)** | `0` = off | Hard cap for the download folder. When exceeded, the **oldest unused** content is deleted first until back under the cap. |
| **Safety window (min)** | `60` | After content is no longer needed it's kept this long before deletion, so replaying it **resumes without re-downloading**. |
| **Delete after sharing** | `on` | Free the files once a torrent meets its seed **ratio/time** target. |
| **Delete after watching** | `on` | Remove leftover files after you finish watching or a torrent goes idle. |

**What is kept:** anything **being watched right now** or **still seeding toward a live
target** is never touched. **Private torrents** manage their own ratio/time window, so they're
deleted **immediately** when it's met (no safety window). Everything else is retired: dropped
from the active set, kept for the safety window (so a returning viewer resumes instantly), then
deleted. The disk cap is a hard guarantee — under pressure it evicts the oldest content first,
overriding the safety window.

### Per-source rules

Rules are evaluated **in order, first match wins** (edit them in the **Rules** screen):
Expand Down
21 changes: 21 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,23 @@ type Compressed struct {
Reject bool `json:"reject"`
}

// Disk retention: auto-free space in disk mode by removing content once it is no
// longer needed, and cap the disk-cache directory so it can never fill up.
type Disk struct {
MaxGB int `json:"maxGB"` // hard cap for the disk-cache dir; 0 = no cap
GraceMinutes int `json:"graceMinutes"` // safety window before deleting public content (0 = immediate)
DeleteAfterSeed bool `json:"deleteAfterSeed"` // delete files once a seed ratio/time target is met
DeleteAfterPlayback bool `json:"deleteAfterPlayback"` // disk mode: delete leftover files after playback / idle timeout
}

// Settings is the full config object persisted in bbolt.
type Settings struct {
Cache Cache `json:"cache"`
Seed Seed `json:"seed"`
Net Net `json:"net"`
Limits Limits `json:"limits"`
Compressed Compressed `json:"compressed"`
Disk Disk `json:"disk"`
NoPeersTimeoutSec int `json:"noPeersTimeoutSec"`
APIToken string `json:"apiToken"`
}
Expand Down Expand Up @@ -100,6 +110,7 @@ func Defaults() Settings {
Net: Net{ListenHost: "0.0.0.0", ListenPort: 7001, BTPort: 42069, DHT: true, MaxConns: 200, DownKbps: 0, UpKbps: 0, EncryptHeaders: false, IPv6: true, UTP: true, DisconnectTimeoutSec: 0},
Limits: Limits{MaxActiveTorrents: 8},
Compressed: Compressed{Reject: true},
Disk: Disk{MaxGB: 0, GraceMinutes: 60, DeleteAfterSeed: true, DeleteAfterPlayback: true},
NoPeersTimeoutSec: 60,
APIToken: "",
}
Expand All @@ -126,6 +137,10 @@ type TorrentRecord struct {
SeedUntilRatio float64 `json:"seedUntilRatio"`
SeedUntilMinutes int `json:"seedUntilMinutes"`
SeedStartedAt int64 `json:"seedStartedAt"`
// PendingDeleteAt marks public disk content slated for deletion once the
// grace window elapses (unix seconds; 0 = not pending). Re-adding the torrent
// clears it (the returning viewer resumes from the retained files).
PendingDeleteAt int64 `json:"pendingDeleteAt"`
}

// Store is the bbolt-backed config + state store. Safe for concurrent use.
Expand Down Expand Up @@ -302,6 +317,12 @@ func normalize(cfg *Settings) {
if cfg.NoPeersTimeoutSec < 1 {
cfg.NoPeersTimeoutSec = 60
}
if cfg.Disk.MaxGB < 0 {
cfg.Disk.MaxGB = 0
}
if cfg.Disk.GraceMinutes < 0 {
cfg.Disk.GraceMinutes = 0
}
}

// applyEnv overlays FT_* environment variables onto the config (boot only).
Expand Down
6 changes: 4 additions & 2 deletions internal/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ func New(store *config.Store) (*Engine, error) {
}
e.ApplyRateLimits(cfg.Net)
e.startSeedEnforcer() // keepSeed ratio/time enforcement (SPEC §6.4)
e.startJanitor() // disk retention: auto-free space + cap (SPEC §6.1)
return e, nil
}

Expand Down Expand Up @@ -756,8 +757,9 @@ func (e *Engine) Delete(hash string, withFiles bool) error {
_ = e.store.DeleteTorrent(hash)

if withFiles && found && rec.StorageMode == "disk" {
cfg := e.store.Get()
_ = os.RemoveAll(filepath.Join(cfg.Cache.Path, rec.Name))
if path, ok := e.safeDataPath(rec.Name); ok {
_ = os.RemoveAll(path)
}
}
return nil
}
Expand Down
200 changes: 200 additions & 0 deletions internal/engine/janitor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
package engine

// Disk retention (SPEC §6.1 disk mode).
//
// Goal: keep only what is in use or seeding toward a live target, and free
// everything else — while guaranteeing the disk-cache dir never exceeds
// Disk.MaxGB (the disk analogue of the RAM ring-buffer cap).
//
// Two phases keep it safe:
// - retire(): a torrent that is no longer needed. Private torrents are deleted
// immediately (their tracker ratio/time already served as the retention
// window); public torrents are dropped from the active set but kept on disk
// and marked PendingDeleteAt = now + grace, so a returning viewer resumes
// instantly from the retained files.
// - the janitor loop: deletes pending content once its grace window elapses,
// and, if the dir is over the cap, evicts the oldest inactive content first
// (the hard cap overrides the grace window).

import (
"log"
"os"
"path/filepath"
"sort"
"strings"
"time"

"github.com/jodacame/fluxtorrent/internal/config"
)

const janitorInterval = 30 * time.Second

// startJanitor launches the periodic disk-retention loop.
func (e *Engine) startJanitor() {
go func() {
t := time.NewTicker(janitorInterval)
defer t.Stop()
for range t.C {
e.sweepPending()
e.enforceDiskCap()
}
}()
}

// retire disposes of a torrent that is no longer needed (see file header).
func (e *Engine) retire(hash string, private bool) {
if private {
_ = e.Delete(hash, true) // immediate: private manages its own window
return
}
grace := time.Duration(e.store.Get().Disk.GraceMinutes) * time.Minute
_ = e.Drop(hash) // stop sharing/downloading, keep the files on disk
rec, ok := e.store.GetTorrent(hash)
if !ok {
return
}
rec.PendingDeleteAt = time.Now().Add(grace).Unix()
if rec.LastPlayedAt == 0 {
rec.LastPlayedAt = time.Now().Unix()
}
_ = e.store.SaveTorrent(rec)
log.Printf("retire: %s kept ~%dm before deletion", shortHash(hash), e.store.Get().Disk.GraceMinutes)
}

// sweepPending deletes public records whose grace window has elapsed and that
// are not currently active (an active torrent means a viewer rescued it).
func (e *Engine) sweepPending() {
now := time.Now().Unix()
recs, _ := e.store.Torrents()
for _, r := range recs {
if r.PendingDeleteAt == 0 || r.PendingDeleteAt > now {
continue
}
if e.isActive(r.Hash) {
continue // rescued
}
if freed := e.deleteRecordFiles(r); freed >= 0 {
log.Printf("janitor: deleted %s (%s)", shortHash(r.Hash), r.Name)
}
}
}

// enforceDiskCap evicts the oldest inactive pending content until the disk-cache
// dir is back under Disk.MaxGB. The hard cap overrides the grace window.
func (e *Engine) enforceDiskCap() {
cfg := e.store.Get()
if cfg.Disk.MaxGB <= 0 {
return
}
limit := int64(cfg.Disk.MaxGB) << 30
used := dirSize(cfg.Cache.Path)
if used <= limit {
return
}

recs, _ := e.store.Torrents()
cand := make([]config.TorrentRecord, 0, len(recs))
for _, r := range recs {
if r.PendingDeleteAt == 0 || e.isActive(r.Hash) {
continue // only inactive, already-retired content is evictable
}
cand = append(cand, r)
}
// Oldest first: by last use, falling back to when it was added.
sort.Slice(cand, func(i, j int) bool { return evictKey(cand[i]) < evictKey(cand[j]) })

for _, r := range cand {
if used <= limit {
break
}
freed := e.deleteRecordFiles(r)
if freed > 0 {
used -= freed
}
log.Printf("disk cap: evicted %s (%s), freed %dMB", shortHash(r.Hash), r.Name, freed>>20)
}
if used > limit {
// Everything evictable is gone but active/seeding content still exceeds
// the cap — surface it rather than silently over-run.
log.Printf("disk cap: still over budget (%dMB > %dMB) — only active/seeding content remains",
used>>20, limit>>20)
}
}

// deleteRecordFiles removes a record's on-disk files (guarded) and the record
// itself, returning the bytes freed. Only disk-mode records with a path that
// stays strictly inside the cache dir are touched.
func (e *Engine) deleteRecordFiles(r config.TorrentRecord) int64 {
defer func() { _ = e.store.DeleteTorrent(r.Hash) }()
if r.StorageMode != "disk" {
return 0
}
path, ok := e.safeDataPath(r.Name)
if !ok {
log.Printf("janitor: refusing unsafe delete path for %s (name=%q)", shortHash(r.Hash), r.Name)
return 0
}
size := dirSize(path)
if err := os.RemoveAll(path); err != nil {
log.Printf("janitor: remove %s: %v", path, err)
return 0
}
return size
}

// safeDataPath resolves a torrent's on-disk root and verifies it stays strictly
// inside the disk-cache dir — guarding against an empty name (which would target
// the whole dir) and path traversal via a crafted torrent name.
func (e *Engine) safeDataPath(name string) (string, bool) {
name = strings.TrimSpace(name)
if name == "" {
return "", false
}
root := filepath.Clean(e.store.Get().Cache.Path)
p := filepath.Clean(filepath.Join(root, name))
if p == root || !strings.HasPrefix(p, root+string(os.PathSeparator)) {
return "", false
}
return p, true
}

// isActive reports whether the hash is currently a managed (running) torrent.
func (e *Engine) isActive(hash string) bool {
e.mu.Lock()
_, ok := e.managed[hash]
e.mu.Unlock()
return ok
}

// evictKey is the eviction ordering: least-recently-used first (fall back to
// add time for never-played content).
func evictKey(r config.TorrentRecord) int64 {
if r.LastPlayedAt > 0 {
return r.LastPlayedAt
}
return r.AddedAt
}

// dirSize sums the byte size of every file under path (0 if it doesn't exist).
func dirSize(path string) int64 {
var total int64
_ = filepath.WalkDir(path, func(_ string, d os.DirEntry, err error) error {
if err != nil {
return nil
}
if !d.IsDir() {
if info, ierr := d.Info(); ierr == nil {
total += info.Size()
}
}
return nil
})
return total
}

func shortHash(h string) string {
if len(h) >= 8 {
return h[:8]
}
return h
}
Loading
Loading