Skip to content
17 changes: 14 additions & 3 deletions internal/cli/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,11 @@ type listEntry struct {
DownloadRateBps float64 `json:"download_rate_bps"`
ActivePeers int `json:"active_peers"`
TotalPeers int `json:"total_peers"`
Error string `json:"error,omitempty"`
// PortEphemeral is true if this torrent is running on an OS-assigned
// fallback port because the configured port range was exhausted -- see
// store.TorrentConfig.PortEphemeral.
PortEphemeral bool `json:"port_ephemeral,omitempty"`
Error string `json:"error,omitempty"`
}

func loadListEntries() ([]listEntry, error) {
Expand All @@ -66,7 +70,7 @@ func loadListEntries() ([]listEntry, error) {
}
_ = store.ReconcileLiveness(tc)

e := listEntry{ID: tc.ID, Name: tc.Name, Status: string(tc.Status)}
e := listEntry{ID: tc.ID, Name: tc.Name, Status: string(tc.Status), PortEphemeral: tc.PortEphemeral}
if st, err := store.LoadState(id); err == nil {
e.Percent = st.Percent
e.DownloadRateBps = st.DownloadRateBps
Expand Down Expand Up @@ -117,7 +121,14 @@ func runListTable(cmd *cobra.Command) error {
percent := fmt.Sprintf("%.1f%%", e.Percent)
rate := humanize.Rate(e.DownloadRateBps)
peers := fmt.Sprintf("%d/%d", e.ActivePeers, e.TotalPeers)
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", e.ID, e.Name, e.Status, percent, rate, peers)
status := e.Status
if e.PortEphemeral {
// Visible here, not just logged to log.txt: an unreachable
// inbound listener silently degrading a running torrent is
// exactly the failure mode this needs to surface, not hide.
status += " (ephemeral port)"
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", e.ID, e.Name, status, percent, rate, peers)
}
return w.Flush()
}
Expand Down
31 changes: 31 additions & 0 deletions internal/cli/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cli
import (
"bytes"
"os/exec"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -72,6 +73,36 @@ func TestList_SelfCorrectsCrashedStatus(t *testing.T) {
}
}

// TestList_SurfacesEphemeralPortFallback confirms a torrent running on an
// OS-assigned fallback port (store.TorrentConfig.PortEphemeral) is visibly
// flagged in `list --plain` output, not just recorded silently -- the
// whole point of persisting this rather than only logging it.
func TestList_SurfacesEphemeralPortFallback(t *testing.T) {
t.Setenv("HOME", t.TempDir())

id := "ephemeral1"
if err := store.InitTorrentDir(id); err != nil {
t.Fatalf("init torrent dir: %v", err)
}
tc := &store.TorrentConfig{ID: id, Name: "port-exhausted", Status: store.StatusRunning, PortEphemeral: true}
if err := store.SaveTorrentConfig(tc); err != nil {
t.Fatalf("save torrent config: %v", err)
}

out := new(bytes.Buffer)
root := NewRootCmd("test")
root.SetArgs([]string{"list", "--plain"})
root.SetOut(out)
if err := root.Execute(); err != nil {
t.Fatalf("run list: %v", err)
}

got := out.String()
if !strings.Contains(got, "ephemeral1") || !strings.Contains(got, "ephemeral port") {
t.Fatalf("list output missing an ephemeral-port note for a torrent with PortEphemeral=true:\n%s", got)
}
}

// TestPause_AlreadyCrashedReportsCleanly ensures pausing a torrent whose
// process has already died reports a sensible status instead of trying (and
// failing) to signal a dead pid.
Expand Down
36 changes: 35 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ const fileName = "config.toml"

// Config holds the global defaults applied to every torrent unless
// overridden per-torrent in a later pass. Zero values for the speed limits
// mean "unlimited"; zero for the port range means "let the OS pick".
// mean "unlimited". PortRangeStart/PortRangeEnd both zero means "let the OS
// pick" a port for every torrent, with no coordination between them at all.
// When set, each concurrently-running torrent claims a distinct,
// lowest-available port from [PortRangeStart, PortRangeEnd] -- see
// internal/portpool.Claim -- falling back to an OS-assigned port (recorded
// and surfaced as such, not just logged -- see
// store.TorrentConfig.PortEphemeral) once the range is exhausted.
type Config struct {
BaseDownloadDir string `toml:"base_download_dir"`
MaxUploadBps int64 `toml:"max_upload_bps"`
Expand Down Expand Up @@ -75,9 +81,37 @@ func Load() (*Config, error) {
if err := toml.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse config %s: %w", p, err)
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("invalid config %s: %w", p, err)
}
return &cfg, nil
}

// Validate reports whether cfg's fields are internally consistent. Load
// calls this after decoding config.toml, so a malformed port range (the
// only field pair with a relationship to check today) fails loudly at
// startup instead of producing undefined behavior later when
// internal/portpool tries to use it.
func (c Config) Validate() error {
if c.PortRangeStart < 0 || c.PortRangeEnd < 0 {
return fmt.Errorf("port_range_start and port_range_end must not be negative")
}
switch {
case c.PortRangeStart == 0 && c.PortRangeEnd == 0:
// Both unset: "let the OS pick", the documented zero-value
// convention. Nothing to validate.
return nil
case c.PortRangeStart == 0:
return fmt.Errorf("port_range_start must be set when port_range_end (%d) is set", c.PortRangeEnd)
case c.PortRangeEnd == 0:
return fmt.Errorf("port_range_end must be set when port_range_start (%d) is set", c.PortRangeStart)
case c.PortRangeStart > c.PortRangeEnd:
return fmt.Errorf("port_range_end (%d) must be >= port_range_start (%d)", c.PortRangeEnd, c.PortRangeStart)
default:
return nil
}
}

// Save writes cfg to ~/.tocli/config.toml.
func Save(cfg *Config) error {
p, err := path()
Expand Down
54 changes: 54 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package config

import "testing"

// TestConfig_Validate covers the port-range checks Load now enforces: a
// malformed range (inverted, or half-specified) must be rejected clearly
// rather than left to produce undefined behavior later in
// internal/portpool.
func TestConfig_Validate(t *testing.T) {
tests := []struct {
name string
cfg Config
wantErr bool
}{
{"both zero (let the OS pick)", Config{}, false},
{"valid single-port range", Config{PortRangeStart: 42069, PortRangeEnd: 42069}, false},
{"valid multi-port range", Config{PortRangeStart: 6000, PortRangeEnd: 6010}, false},
{"inverted range", Config{PortRangeStart: 6010, PortRangeEnd: 6000}, true},
{"start set, end zero", Config{PortRangeStart: 6000}, true},
{"end set, start zero", Config{PortRangeEnd: 6000}, true},
{"negative start", Config{PortRangeStart: -1, PortRangeEnd: 6000}, true},
{"negative end", Config{PortRangeStart: 6000, PortRangeEnd: -1}, true},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.cfg.Validate()
if tt.wantErr && err == nil {
t.Fatalf("Validate() = nil, want an error for %+v", tt.cfg)
}
if !tt.wantErr && err != nil {
t.Fatalf("Validate() = %v, want nil for %+v", err, tt.cfg)
}
})
}
}

// TestLoad_RejectsInvertedPortRange confirms the check is actually wired
// into Load, not just Validate in isolation: a config.toml with
// port_range_start > port_range_end must fail to load with a clear error.
func TestLoad_RejectsInvertedPortRange(t *testing.T) {
t.Setenv("HOME", t.TempDir())

cfg := Default()
cfg.PortRangeStart = 6010
cfg.PortRangeEnd = 6000
if err := Save(&cfg); err != nil {
t.Fatalf("save invalid config: %v", err)
}

if _, err := Load(); err == nil {
t.Fatal("Load() succeeded on a config with port_range_start > port_range_end, want an error")
}
}
Loading
Loading