anacrolix / torrent

Full-featured BitTorrent client package and utilities
Mozilla Public License 2.0
5.39k stars 615 forks source link

Support passing context to `torrent.Reader` #878

Open igorcafe opened 8 months ago

igorcafe commented 8 months ago

I'm building a server that streams torrents through HTTP. I just found out that we had the same idea of creating a "ContextReader", but I saw that here you pass a fixed context.Background(), so there is no way for me to pass a context and cancel it.

What I ended up doing was:

func streamChunk(ctx context.Context, start int64, end int64, dst io.Writer, src io.ReadSeekCloser) error {
    _, err := src.Seek(start, io.SeekStart)
    if err != nil {
        return err
    }

    _, err = io.CopyN(dst, NewContextReader(ctx, src), end-start+1)
    if err != nil {
        return err
    }

    return nil
}

Where the context is the http.Request.Context(), src is the torrent.Reader and dst is the http.ResponseWriter.

anacrolix commented 8 months ago

Could you link to the implementation of NewContextReader that you are using? I'm guessing there that Read is directed to ReadContext instead. I'm not sure it's possible to do any better than that. I'm sure I have an implementation of that somewhere, but I'm on my mobile.

For wrapping torrents in HTTP, check out anacrolix/confluence and anacrolix/webtorrent-public. Both are used in very mature projects that do streaming BitTorrent over HTTP.