Repository navigation
Claim a distinct listen port per concurrently-running torrent - #17
Merged
Merged
Conversation
port_range_start > port_range_end (or one set without the other) was previously undefined behavior -- nothing checked it. Config.Validate rejects it clearly at config load time instead, ahead of internal/portpool depending on the range actually being well-formed.
Refactors the shared flock/open/release logic out of AcquireLock into a private acquireLock(path, flags) so the two variants share it rather than duplicating it. AcquireLock's non-blocking semantics fit its existing use (the per-torrent spawn lock: contention there means another process already owns this one, give up). A different, upcoming use -- coordinating access to a shared port registry file (internal/portpool) -- needs the opposite: brief, expected contention where waiting a moment is the right response, not failing immediately. Unused until that lands.
~/.tocli/ports.json records which port in the configured range is currently claimed and by which torrent id; ~/.tocli/ports.lock guards read-check-claim-write access to it. Root-level, not per-torrent, since it's shared across every torrent rather than scoped to one -- contrast store.LockPath. Pure storage, following this package's existing convention (it owns all of ~/.tocli's on-disk state and serialization); the claim/release decision logic that will use this lands separately in internal/portpool. Unused until that lands.
…cesses Claim assigns a torrent id the lowest available port in [PortRangeStart, PortRangeEnd], recording it in store.PortRegistry under process.AcquireLockBlocking so two concurrently-starting torrents can never claim the same one. Assignment is always lowest-available, not an arbitrary free port, so a range a user has forwarded on their router gets used predictably from the bottom up. No range configured (PortRangeStart <= 0) short-circuits before touching the registry at all, matching existing behavior exactly. Range exhaustion returns (0, ephemeral=true, nil) rather than an error, so the caller can fall back to an OS-assigned port instead of failing to start. Release frees a claimed port so a later torrent can reclaim it; safe to call for an id that never held one. Covered by unit tests in isolation (sequential assignment, exhaustion, release-then-reclaim, the no-range-configured short circuit); not yet wired into anything that calls it.
…to one Every internal/engine.Run process previously pinned its BitTorrent listen port to config.PortRangeStart unconditionally, so only the first concurrently-running torrent could ever actually bind it -- every one after it silently fell back to outbound-only (no inbound peer connections), with no visible symptom in list/logs, and defeating any router port-forwarding the user had set up for the range. port_range_end was pure dead config as a result. Run now claims a port via internal/portpool.Claim before creating the torrent.Client, using it as the listener port when one was actually claimed, and logging a clear warning when the configured range is exhausted and it falls back to an OS-assigned port instead (still starts normally -- exhaustion is not a failure to start). The claimed port is released via internal/portpool.Release as part of the same paths that already release the per-torrent lock: normal completion, the SIGTERM/pause handler, and (via defer) any early failure in between. Nothing is deferred at all for a torrent that never actually claimed a port (no range configured, or the ephemeral fallback), so the registry/lock file is never touched in that case. Tests spawn real, separate "tocli __run" processes (not goroutines) against a small configured range: concurrent torrents land on distinct ports with no collision, a freed port (previous holder exits via SIGTERM) is reclaimed by the next spawn rather than staying marked claimed, and range exhaustion falls back to an ephemeral port with the expected warning rather than failing to start. Manually verified end-to-end against the real binary: three concurrent "tocli __run" processes against a configured [49500-49502] range, confirmed via lsof to each be listening (TCP+UDP) on a distinct port matching the port registry exactly. Out of scope, tracked separately (see the pool/queue GitHub issue): no limit on concurrent torrents, no queueing when the range is exhausted -- it still starts immediately on an ephemeral port.
…avior Not stale (it never described the old single-port-pinning bug), just silent on what a configured port range actually does now that internal/portpool exists. This is the only place in the repo that documents these two fields, so it's worth it actually saying so.
The exhaustion warning portpool.Claim's caller logs was only ever reaching log.txt -- invisible during normal use unless someone already suspects something's wrong and goes looking. That undercuts the whole point of this fix: the original bug's defining symptom was "no visible symptom anywhere in list or logs". store.TorrentConfig gets a new PortEphemeral field, set by Run alongside the existing PID/status bookkeeping whenever it falls back to an OS-assigned port, and cleared once the torrent stops actively running (paused/completed) since the claim -- or lack of one -- no longer applies once released. Surfaced in both places a user actually looks: `list`/`list --json` (a new port_ephemeral field, and "(ephemeral port)" appended to the STATUS column in `list --plain`) and the dashboard's STATUS column (widened from 12 to 20 to fit "running (ephemeral)" without truncating). Tests: the existing real-subprocess exhaustion test now also confirms the persisted config actually records PortEphemeral=true, and a new `list --plain` test confirms it renders visibly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The bug
tocli's process-per-torrent architecture means every running torrent is a separate OS process, and every one of them previously tried to bind the same configured port (
PortRangeStart) for inbound peer connections. Only the first process to bind won; every other concurrently-running torrent silently fell back to outbound-only -- it could still find and connect out to peers via DHT/trackers/PEX, but nothing could connect in to it. This degraded seeding/upload contribution and defeated any router port-forwarding the user had set up, with no visible symptom anywhere inlistor logs.port_range_endinconfig.tomldid nothing at all.What changed
Five layered commits (each independently buildable -- verified by checking out and building every one in sequence):
Validate the configured port range at load time--Config.Validate()rejectsport_range_start > port_range_end, or one set without the other, atLoad()time instead of leaving it undefined.Add AcquireLockBlocking alongside the existing non-blocking AcquireLock-- sharedflocklogic factored out; the new blocking variant fits the port registry's contention (wait a moment) differently from the existing per-torrent spawn lock's (give up immediately).Add store.PortRegistry--~/.tocli/ports.json(which port is claimed by which torrent id) plus~/.tocli/ports.lockguarding it, following this package's existing convention of owning all on-disk state/serialization.Add internal/portpool--Claim(id, cfg)assigns the lowest available port in[PortRangeStart, PortRangeEnd];Release(id)frees it. No range configured short-circuits before touching the registry; exhaustion returnsephemeral=true(not an error) so the caller can fall back rather than fail to start.Claim a distinct listen port per torrent instead of pinning them all to one-- wiresportpool.Claim/Releaseintointernal/engine.Run, replacing the old pin-to-PortRangeStartblock, released via the same paths that already release the per-torrent lock (completion, SIGTERM/pause, and any earlier failure viadefer).Plus two follow-up commits from review of this PR's own scope, done before opening it:
Expand Config's doc comment-- the struct comment wasn't wrong, just silent on the new per-torrent behavior; it's the only place in the repo documenting these two fields, so it's worth actually saying what they do now. (Searched the rest of the repo -- README, CONTRIBUTING.md,.github/workflows/*.yml, other doc comments -- for anything describing the old single-port-pinning behavior or claimingport_range_endis unused: nothing else needed changing. Both workflow files' only port-adjacent text is the unrelated Windows/build-matrix comment.)Surface the ephemeral-port fallback in list/dashboard, not just log.txt-- the exhaustion warning was originally logged only tolog.txt, which nobody looks at unless they already suspect something's wrong -- the exact "no visible symptom" problem this whole PR exists to fix, just moved one layer down.store.TorrentConfiggets a newPortEphemeralfield (set/cleared alongside the existing PID/status bookkeeping), surfaced inlist/list --json(port_ephemeral),list --plain(STATUScolumn:running (ephemeral port)), and the dashboard (STATUScolumn widened 12→20 to fitrunning (ephemeral)).Verification
go build ./...,go vet ./...,gofmt -l .,go mod tidy(no diff),go test ./... -race,govulncheck ./...-- all clean.tocli __runprocesses, not goroutines, matching the existinglock_concurrency_test.gopattern): concurrent torrents land on distinct ports with no collision (verified via the shared registry), a freed port is reclaimed by the next spawn rather than staying marked claimed, and range exhaustion falls back to an ephemeral port with the expected warning logged and persisted (PortEphemeral=true) while still reachingrunning.internal/portpool(sequential/lowest-available assignment, exhaustion, release-then-reclaim) andinternal/config(range validation).tocli __runprocesses against a configured[49500-49502]range, confirmed vialsofthat each bound a distinct TCP+UDP port matching the port registry exactly.Out of scope (tracked separately)
No limit on concurrent torrents, no queueing when the range is exhausted -- it still starts immediately on an ephemeral port either way. See the pool/queue GitHub issue for that.