Skip to content

Commit

Permalink
cmd/torrent download: Propagate write errors
Browse files Browse the repository at this point in the history
  • Loading branch information
anacrolix committed Feb 28, 2024
1 parent 3d92cca commit b8e03eb
Showing 1 changed file with 33 additions and 7 deletions.
40 changes: 33 additions & 7 deletions cmd/torrent/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,13 @@ func resolveTestPeers(addrs []string) (ret []torrent.PeerInfo) {
return
}

func addTorrents(ctx context.Context, client *torrent.Client, flags downloadFlags, wg *sync.WaitGroup) error {
func addTorrents(
ctx context.Context,
client *torrent.Client,
flags downloadFlags,
wg *sync.WaitGroup,
fatalErr func(err error),
) error {
testPeers := resolveTestPeers(flags.TestPeer)
for _, arg := range flags.Torrent {
t, err := func() (*torrent.Torrent, error) {
Expand Down Expand Up @@ -133,6 +139,10 @@ func addTorrents(ctx context.Context, client *torrent.Client, flags downloadFlag
if err != nil {
return fmt.Errorf("adding torrent for %q: %w", arg, err)
}
t.SetOnWriteChunkError(func(err error) {
err = fmt.Errorf("error writing chunk for %v: %w", t, err)
fatalErr(err)
})
if flags.Progress {
torrentBar(t, flags.PieceStates)
}
Expand Down Expand Up @@ -344,17 +354,33 @@ func downloadErr(flags downloadFlags) error {
client.WriteStatus(w)
})
var wg sync.WaitGroup
err = addTorrents(ctx, client, flags, &wg)
fatalErr := make(chan error, 1)
err = addTorrents(ctx, client, flags, &wg,
func(err error) {
select {
case fatalErr <- err:
default:
panic(err)
}
})
if err != nil {
return fmt.Errorf("adding torrents: %w", err)
}
started := time.Now()
defer outputStats(client, flags)
wg.Wait()
if ctx.Err() == nil {
log.Print("downloaded ALL the torrents")
} else {
err = ctx.Err()
wgWaited := make(chan struct{})
go func() {
defer close(wgWaited)
wg.Wait()
}()
select {
case <-wgWaited:
if ctx.Err() == nil {
log.Print("downloaded ALL the torrents")
} else {
err = ctx.Err()
}
case err = <-fatalErr:
}
clientConnStats := client.ConnStats()
log.Printf(
Expand Down

0 comments on commit b8e03eb

Please sign in to comment.