12 "github.com/anacrolix/missinggo/v2/filecache"
13 "github.com/anacrolix/torrent"
14 "github.com/anacrolix/torrent/internal/testutil"
15 "github.com/anacrolix/torrent/storage"
16 "golang.org/x/time/rate"
18 "github.com/stretchr/testify/assert"
19 "github.com/stretchr/testify/require"
22 type testClientTransferParams struct {
26 ExportClientStatus bool
27 LeecherStorage func(string) storage.ClientImplCloser
28 SeederStorage func(string) storage.ClientImplCloser
29 SeederUploadRateLimiter *rate.Limiter
30 LeecherDownloadRateLimiter *rate.Limiter
31 ConfigureSeeder ConfigureClient
32 ConfigureLeecher ConfigureClient
35 func assertReadAllGreeting(t *testing.T, r io.ReadSeeker) {
36 pos, err := r.Seek(0, io.SeekStart)
37 assert.NoError(t, err)
38 assert.EqualValues(t, 0, pos)
39 _greeting, err := ioutil.ReadAll(r)
40 assert.NoError(t, err)
41 assert.EqualValues(t, testutil.GreetingFileContents, string(_greeting))
44 // Creates a seeder and a leecher, and ensures the data transfers when a read
45 // is attempted on the leecher.
46 func testClientTransfer(t *testing.T, ps testClientTransferParams) {
47 greetingTempDir, mi := testutil.GreetingTestTorrent()
48 defer os.RemoveAll(greetingTempDir)
49 // Create seeder and a Torrent.
50 cfg := torrent.TestingConfig()
52 if ps.SeederUploadRateLimiter != nil {
53 cfg.UploadRateLimiter = ps.SeederUploadRateLimiter
55 // cfg.ListenAddr = "localhost:4000"
56 if ps.SeederStorage != nil {
57 storage := ps.SeederStorage(greetingTempDir)
59 cfg.DefaultStorage = storage
61 cfg.DataDir = greetingTempDir
63 if ps.ConfigureSeeder.Config != nil {
64 ps.ConfigureSeeder.Config(cfg)
66 seeder, err := torrent.NewClient(cfg)
67 require.NoError(t, err)
68 if ps.ConfigureSeeder.Client != nil {
69 ps.ConfigureSeeder.Client(seeder)
71 if ps.ExportClientStatus {
72 defer testutil.ExportStatusWriter(seeder, "s")()
74 seederTorrent, _, _ := seeder.AddTorrentSpec(torrent.TorrentSpecFromMetaInfo(mi))
75 // Run a Stats right after Closing the Client. This will trigger the Stats
76 // panic in #214 caused by RemoteAddr on Closed uTP sockets.
77 defer seederTorrent.Stats()
79 seederTorrent.VerifyData()
80 // Create leecher and a Torrent.
81 leecherDataDir, err := ioutil.TempDir("", "")
82 require.NoError(t, err)
83 defer os.RemoveAll(leecherDataDir)
84 cfg = torrent.TestingConfig()
85 if ps.LeecherStorage == nil {
86 cfg.DataDir = leecherDataDir
88 storage := ps.LeecherStorage(leecherDataDir)
90 cfg.DefaultStorage = storage
92 if ps.LeecherDownloadRateLimiter != nil {
93 cfg.DownloadRateLimiter = ps.LeecherDownloadRateLimiter
96 if ps.ConfigureLeecher.Config != nil {
97 ps.ConfigureLeecher.Config(cfg)
99 leecher, err := torrent.NewClient(cfg)
100 require.NoError(t, err)
101 defer leecher.Close()
102 if ps.ConfigureLeecher.Client != nil {
103 ps.ConfigureLeecher.Client(leecher)
105 if ps.ExportClientStatus {
106 defer testutil.ExportStatusWriter(leecher, "l")()
108 leecherTorrent, new, err := leecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
109 ret = torrent.TorrentSpecFromMetaInfo(mi)
113 require.NoError(t, err)
116 //// This was used when observing coalescing of piece state changes.
117 //logPieceStateChanges(leecherTorrent)
119 // Now do some things with leecher and seeder.
120 added := leecherTorrent.AddClientPeer(seeder)
121 // The Torrent should not be interested in obtaining peers, so the one we
122 // just added should be the only one.
123 assert.False(t, leecherTorrent.Seeding())
124 assert.EqualValues(t, added, leecherTorrent.Stats().PendingPeers)
125 r := leecherTorrent.NewReader()
131 r.SetReadahead(ps.Readahead)
133 assertReadAllGreeting(t, r)
134 assert.NotEmpty(t, seederTorrent.PeerConns())
135 leecherPeerConns := leecherTorrent.PeerConns()
136 assert.NotEmpty(t, leecherPeerConns)
137 for _, pc := range leecherPeerConns {
138 assert.EqualValues(t, leecherTorrent.Info().NumPieces(), pc.PeerPieces().Len())
141 seederStats := seederTorrent.Stats()
142 assert.True(t, 13 <= seederStats.BytesWrittenData.Int64())
143 assert.True(t, 8 <= seederStats.ChunksWritten.Int64())
145 leecherStats := leecherTorrent.Stats()
146 assert.True(t, 13 <= leecherStats.BytesReadData.Int64())
147 assert.True(t, 8 <= leecherStats.ChunksRead.Int64())
149 // Try reading through again for the cases where the torrent data size
150 // exceeds the size of the cache.
151 assertReadAllGreeting(t, r)
154 type fileCacheClientStorageFactoryParams struct {
157 Wrapper func(*filecache.Cache) storage.ClientImplCloser
160 func newFileCacheClientStorageFactory(ps fileCacheClientStorageFactoryParams) storageFactory {
161 return func(dataDir string) storage.ClientImplCloser {
162 fc, err := filecache.NewCache(dataDir)
167 fc.SetCapacity(ps.Capacity)
169 return ps.Wrapper(fc)
173 type storageFactory func(string) storage.ClientImplCloser
175 func TestClientTransferDefault(t *testing.T) {
176 testClientTransfer(t, testClientTransferParams{
177 ExportClientStatus: true,
178 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
179 Wrapper: fileCachePieceResourceStorage,
184 func TestClientTransferRateLimitedUpload(t *testing.T) {
185 started := time.Now()
186 testClientTransfer(t, testClientTransferParams{
187 // We are uploading 13 bytes (the length of the greeting torrent). The
188 // chunks are 2 bytes in length. Then the smallest burst we can run
189 // with is 2. Time taken is (13-burst)/rate.
190 SeederUploadRateLimiter: rate.NewLimiter(11, 2),
191 ExportClientStatus: true,
193 require.True(t, time.Since(started) > time.Second)
196 func TestClientTransferRateLimitedDownload(t *testing.T) {
197 testClientTransfer(t, testClientTransferParams{
198 LeecherDownloadRateLimiter: rate.NewLimiter(512, 512),
202 func fileCachePieceResourceStorage(fc *filecache.Cache) storage.ClientImplCloser {
203 return storage.NewResourcePieces(fc.AsResourceProvider())
206 func testClientTransferSmallCache(t *testing.T, setReadahead bool, readahead int64) {
207 testClientTransfer(t, testClientTransferParams{
208 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
210 // Going below the piece length means it can't complete a piece so
211 // that it can be hashed.
213 Wrapper: fileCachePieceResourceStorage,
215 SetReadahead: setReadahead,
216 // Can't readahead too far or the cache will thrash and drop data we
218 Readahead: readahead,
219 ExportClientStatus: true,
221 // These tests don't work well with more than 1 connection to the seeder.
222 ConfigureLeecher: ConfigureClient{
223 Config: func(cfg *torrent.ClientConfig) {
224 cfg.DropDuplicatePeerIds = true
225 //cfg.DisableIPv6 = true
226 //cfg.DisableUTP = true
232 func TestClientTransferSmallCachePieceSizedReadahead(t *testing.T) {
233 testClientTransferSmallCache(t, true, 5)
236 func TestClientTransferSmallCacheLargeReadahead(t *testing.T) {
237 testClientTransferSmallCache(t, true, 15)
240 func TestClientTransferSmallCacheDefaultReadahead(t *testing.T) {
241 testClientTransferSmallCache(t, false, -1)
244 func TestClientTransferVarious(t *testing.T) {
246 for _, ls := range []struct {
250 {"Filecache", newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
251 Wrapper: fileCachePieceResourceStorage,
253 {"Boltdb", storage.NewBoltDB},
255 t.Run(fmt.Sprintf("LeecherStorage=%s", ls.name), func(t *testing.T) {
257 for _, ss := range []struct {
259 f func(string) storage.ClientImplCloser
261 {"File", storage.NewFile},
262 {"Mmap", storage.NewMMap},
264 t.Run(fmt.Sprintf("%sSeederStorage", ss.name), func(t *testing.T) {
265 for _, responsive := range []bool{false, true} {
266 t.Run(fmt.Sprintf("Responsive=%v", responsive), func(t *testing.T) {
267 t.Run("NoReadahead", func(t *testing.T) {
268 testClientTransfer(t, testClientTransferParams{
269 Responsive: responsive,
271 LeecherStorage: ls.f,
274 for _, readahead := range []int64{-1, 0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 20} {
275 t.Run(fmt.Sprintf("readahead=%v", readahead), func(t *testing.T) {
276 testClientTransfer(t, testClientTransferParams{
278 Responsive: responsive,
280 Readahead: readahead,
281 LeecherStorage: ls.f,
293 // Check that after completing leeching, a leecher transitions to a seeding
294 // correctly. Connected in a chain like so: Seeder <-> Leecher <-> LeecherLeecher.
295 func TestSeedAfterDownloading(t *testing.T) {
296 greetingTempDir, mi := testutil.GreetingTestTorrent()
297 defer os.RemoveAll(greetingTempDir)
299 cfg := torrent.TestingConfig()
301 cfg.DataDir = greetingTempDir
302 seeder, err := torrent.NewClient(cfg)
303 require.NoError(t, err)
305 defer testutil.ExportStatusWriter(seeder, "s")()
306 seederTorrent, ok, err := seeder.AddTorrentSpec(torrent.TorrentSpecFromMetaInfo(mi))
307 require.NoError(t, err)
309 seederTorrent.VerifyData()
311 cfg = torrent.TestingConfig()
313 cfg.DataDir, err = ioutil.TempDir("", "")
314 require.NoError(t, err)
315 defer os.RemoveAll(cfg.DataDir)
316 leecher, err := torrent.NewClient(cfg)
317 require.NoError(t, err)
318 defer leecher.Close()
319 defer testutil.ExportStatusWriter(leecher, "l")()
321 cfg = torrent.TestingConfig()
323 cfg.DataDir, err = ioutil.TempDir("", "")
324 require.NoError(t, err)
325 defer os.RemoveAll(cfg.DataDir)
326 leecherLeecher, _ := torrent.NewClient(cfg)
327 require.NoError(t, err)
328 defer leecherLeecher.Close()
329 defer testutil.ExportStatusWriter(leecherLeecher, "ll")()
330 leecherGreeting, ok, err := leecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
331 ret = torrent.TorrentSpecFromMetaInfo(mi)
335 require.NoError(t, err)
337 llg, ok, err := leecherLeecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
338 ret = torrent.TorrentSpecFromMetaInfo(mi)
342 require.NoError(t, err)
344 // Simultaneously DownloadAll in Leecher, and read the contents
345 // consecutively in LeecherLeecher. This non-deterministically triggered a
346 // case where the leecher wouldn't unchoke the LeecherLeecher.
347 var wg sync.WaitGroup
353 b, err := ioutil.ReadAll(r)
354 require.NoError(t, err)
355 assert.EqualValues(t, testutil.GreetingFileContents, b)
357 done := make(chan struct{})
359 go leecherGreeting.AddClientPeer(seeder)
360 go leecherGreeting.AddClientPeer(leecherLeecher)
364 leecherGreeting.DownloadAll()
370 type ConfigureClient struct {
371 Config func(*torrent.ClientConfig)
372 Client func(*torrent.Client)