Files
bt/design.md
2016-12-14 15:12:16 -05:00

28 lines
1.6 KiB
Markdown

The `Session` is the main object to download torrents. It manages multiple
threads. When a torrent is added to it, the tracker is contacted to get a
list of peers. Then, a thread is spawned for each peer, and a connection to
the peer is opened.
The connections read packets and send them to the network thread via a channel.
The network thread manages the choking and unchoking of connections and the
scheduling of fragments. Fragments are 16KiB blocks that form a
piece. For instance if a piece is of 512KiB, there are 32 fragments for that
piece. When a connection is unchoked, the network thread will schedule
fragments on this connection. When the fragment is received back, the
network thread assembles the piece from the various fragments. When a piece
is complete, it writes it to disk.
The scheduling algorithm is very simple at the moment. It tries to minimize
the number of pieces that are being downloaded. Every fragment is kept
track of. It has a status, Available (no peer connection is downloading
this fragment), Taken(a peer is downloading this fragment) or Complete (this
fragment has been received). The Taken status also has a timestamp. When
looking for a fragment to schedule, the algorithm looks for fragments that
are available or that have been taken, but ran out of time (5s). It also
takes into account the peer's bitfield to find a piece the peer has. If no
fragment matches these criterias, a new piece is fragmented.
_Note that there could be an explosion in the number of pieces that are being
downloaded if the peers have very incomplete bitfields. In the future the
algorithm will limit the number of pieces that are being downloaded._