fx-torrent 0.10.3

FX Torrent is a feature rich Bittorrent protocol implementation written in rust supporting Linux, MacOS and Windows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
use crate::channel::{ChannelSender, Reply};
use crate::storage::Storage;
use crate::torrent_data::DataPool;
use crate::{File, PiecePriority, Result, TorrentCommand, TorrentError, TorrentEvent};
use futures::future::BoxFuture;
use futures::task::AtomicWaker;
use futures::{ready, FutureExt, Stream};
use fx_callback::Subscription;
use log::trace;
use std::cmp::min;
use std::fmt::Debug;
use std::io;
use std::ops::Range;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::select;
use tokio_util::sync::CancellationToken;

/// The internal stream buffer type.
type Buffer = Range<usize>;

/// Streams the contents of a single torrent file.
///
/// # Example Usage
///
/// ```rust
/// # use futures::StreamExt;
/// # use fx_torrent::Torrent;
///
/// # async fn example() {
///     let torrent = Torrent::request()
///         .build()
///         .unwrap();
///     let file = torrent.file(&0).await.unwrap();
///
///     let mut stream = torrent.stream(&file).await.unwrap();
///     while let Some(bytes) = stream.next().await {
///         // use the bytes here
///     }
/// # }
/// ```
#[derive(Debug)]
pub struct FileStream {
    file: File,
    storage: Storage,
    data_pool: DataPool,
    command_sender: ChannelSender<TorrentCommand>,
    cursor: usize,
    stream_buffer_len: usize,
    piece_len: usize,
    waker: Arc<AtomicWaker>,
    state: StreamState,
    cancellation_token: CancellationToken,
}

impl FileStream {
    pub(crate) fn new(
        file: File,
        piece_len: usize,
        stream_buffer_len: usize,
        storage: Storage,
        data_pool: DataPool,
        command_sender: ChannelSender<TorrentCommand>,
        receiver: Subscription<TorrentEvent>,
    ) -> Self {
        let waker = Arc::new(AtomicWaker::new());
        let cancellation_token = CancellationToken::new();

        let event_waker = waker.clone();
        let event_cancellation_token = cancellation_token.clone();
        tokio::spawn(async move {
            Self::run_event_loop(receiver, event_waker, event_cancellation_token).await;
        });

        Self {
            file,
            storage,
            data_pool,
            command_sender,
            cursor: 0,
            stream_buffer_len,
            piece_len,
            waker,
            state: StreamState::Idle,
            cancellation_token,
        }
    }

    /// Returns the total number of bytes in the stream.
    pub fn len(&self) -> usize {
        self.file.len()
    }

    /// Reset the stream progress back to the start.
    pub fn reset(&mut self) {
        self.cursor = 0;
        self.state = StreamState::Idle;
    }

    /// Seek the given offset within the stream.
    pub fn seek(&mut self, offset: usize) -> Result<()> {
        if offset > self.file.len() {
            return Err(TorrentError::Io(io::Error::new(
                io::ErrorKind::InvalidInput,
                "offset exceeds file length",
            )));
        }

        self.cursor = offset;
        self.state = StreamState::Idle;
        Ok(())
    }

    /// Returns the current byte range of the stream.
    pub fn range(&self) -> Range<usize> {
        self.cursor..self.file.len()
    }

    /// Returns the [Content-Range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Range)
    /// information in bytes for the stream.
    pub fn content_range(&self) -> String {
        format!(
            "bytes {}-{}/{}",
            self.cursor,
            self.file.len() - 1,
            self.file.len()
        )
    }

    fn next_buffer(&self) -> Buffer {
        let buffer_end_byte = min(self.cursor + self.stream_buffer_len, self.file.len());
        self.file.torrent_offset + self.cursor..self.file.torrent_offset + buffer_end_byte
    }

    fn prioritize_buffer(&self, bytes: Buffer) {
        let command_sender = self.command_sender.clone();
        let waker = self.waker.clone();

        // execute the prioritization on a separate task
        tokio::spawn(async move {
            command_sender
                .fire_and_forget(TorrentCommand::PrioritizeBytes {
                    bytes,
                    priority: PiecePriority::Now,
                    response: Reply::empty(),
                })
                .await;

            waker.wake();
        });
    }

    async fn run_event_loop(
        mut receiver: Subscription<TorrentEvent>,
        waker: Arc<AtomicWaker>,
        cancellation_token: CancellationToken,
    ) {
        loop {
            select! {
                _ = cancellation_token.cancelled() => break,
                event = receiver.recv() => {
                    match event {
                        Err(_) => break,
                        Ok(event) => {
                            match &*event {
                                TorrentEvent::PieceCompleted(_) | TorrentEvent::StateChanged(_) => {
                                    waker.wake()
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
        }
    }
}

impl Stream for FileStream {
    type Item = Result<Vec<u8>>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // early exit if the end of the file has been reached
        if self.cursor >= self.file.len() {
            return Poll::Ready(None);
        }

        self.waker.register(cx.waker());
        loop {
            match &mut self.state {
                StreamState::Idle => {
                    let buffer = self.next_buffer();
                    let data_pool = self.data_pool.clone();

                    let future = {
                        let buffer = buffer.clone();
                        async move { data_pool.has_bytes(buffer).await }
                    }
                    .boxed();
                    trace!("Streaming buffer {:?}", buffer);
                    self.state = StreamState::Checking {
                        buffer,
                        future,
                        is_prioritized: false,
                    };
                }
                StreamState::Checking {
                    buffer,
                    future,
                    is_prioritized,
                } => {
                    let buffer = buffer.clone();
                    let is_available = ready!(future.as_mut().poll(cx));

                    if !is_available {
                        if !*is_prioritized {
                            let buffer = buffer.clone();
                            self.prioritize_buffer(buffer);
                        }

                        self.state = StreamState::Waiting { buffer };
                        return Poll::Pending;
                    }

                    let storage = self.storage.clone();
                    let starting_piece = self.cursor / self.piece_len;
                    let starting_offset = self.cursor % self.piece_len;
                    let stream_buffer_len = self.stream_buffer_len;
                    let future = async move {
                        let mut buffer = vec![0u8; stream_buffer_len];

                        match storage
                            .read(&mut buffer, &starting_piece, starting_offset)
                            .await
                        {
                            Err(e) => Err(TorrentError::Io(e)),
                            Ok(bytes_read) => {
                                if bytes_read != buffer.len() {
                                    Err(TorrentError::Io(io::Error::new(
                                        io::ErrorKind::UnexpectedEof,
                                        format!(
                                            "wanted {} bytes, but got {:?} instead",
                                            stream_buffer_len, bytes_read
                                        ),
                                    )))
                                } else {
                                    Ok(buffer)
                                }
                            }
                        }
                    }
                    .boxed();
                    self.state = StreamState::Reading { future };
                }
                StreamState::Waiting { buffer } => {
                    let buffer = buffer.clone();
                    let data_pool = self.data_pool.clone();

                    let future = {
                        let buffer = buffer.clone();
                        async move { data_pool.has_bytes(buffer).await }.boxed()
                    };
                    self.state = StreamState::Checking {
                        buffer,
                        future,
                        is_prioritized: true,
                    };
                }
                StreamState::Reading { future } => {
                    let result = ready!(future.as_mut().poll(cx));
                    if let Ok(bytes) = &result {
                        self.cursor += bytes.len();
                    }

                    self.state = StreamState::Idle;
                    return Poll::Ready(Some(result));
                }
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.stream_buffer_len == 0 || self.len() == 0 {
            return (0, Some(0));
        }

        let upper_bound = self.len().div_ceil(self.stream_buffer_len);
        (0, Some(upper_bound))
    }
}

impl Drop for FileStream {
    fn drop(&mut self) {
        self.cancellation_token.cancel();
    }
}

enum StreamState {
    Idle,
    Checking {
        buffer: Buffer,
        future: BoxFuture<'static, bool>,
        is_prioritized: bool,
    },
    Waiting {
        buffer: Buffer,
    },
    Reading {
        future: BoxFuture<'static, Result<Vec<u8>>>,
    },
}

impl Debug for StreamState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StreamState::Idle => f.write_str("StreamState::Idle"),
            StreamState::Checking { .. } => f.write_str("StreamState::Checking"),
            StreamState::Waiting { .. } => f.write_str("StreamState::Waiting"),
            StreamState::Reading { .. } => f.write_str("StreamState::Reading"),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::operation::CreatePiecesAndFilesOperation;
    use crate::storage::DiskStorage;
    use crate::tests::copy_test_file;
    use crate::tests::helpers::wait_for_torrent_pieces;
    use futures::{Stream, StreamExt};
    use std::time::Duration;
    use tempfile::tempdir;
    use tokio::time::timeout;

    #[tokio::test]
    async fn test_stream_next() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        copy_test_file(
            temp_path,
            "piece-1_30.iso",
            Some("debian-12.4.0-amd64-DVD-1.iso"),
        );
        let torrent = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![CreatePiecesAndFilesOperation::new().into(),],
            vec![],
            |params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
            None
        );
        let data_pool = torrent.inner.data_pool().await.unwrap();
        let (peer, _peer2) = tcp_peer_pair!(&torrent, vec![]);
        torrent.inner.peer_connected(peer.clone().into()).await;

        // wait for the pieces to be created
        wait_for_torrent_pieces(&torrent).await;

        // create the stream
        let file = torrent.file(&0).await.unwrap();
        let mut stream = torrent.stream(&file).await.unwrap();

        // set piece 0 as completed
        mark_piece_completed!(&stream.command_sender, 0, peer.addr(), "piece-1_30.iso");
        assert_timeout!(
            Duration::from_secs(2), // TODO: improve test performance
            data_pool.is_piece_completed(&0).await
        );

        // get the next buffer, which should complete instantly
        let result =
            timeout!(Duration::from_millis(500), stream.next()).expect("expected buffer data");
        match result {
            Ok(_) => {
                assert_eq!(
                    stream.stream_buffer_len, stream.cursor,
                    "expected the stream cursor to be updated"
                );
            }
            _ => assert!(false, "expected Ok(), but got {:?}", result),
        }

        // try to get the next buffer, which should be blocked
        let command_sender = stream.command_sender.clone();
        let mut future = stream.next();
        let result = timeout(Duration::from_millis(250), &mut future).await;
        match result {
            Err(_) => {}
            _ => assert!(false, "expected Err(Elapsed), but got {:?}", result),
        }

        // complete the piece
        mark_piece_completed!(&command_sender, 1, peer.addr(), "piece-1_30.iso");
        assert_timeout!(
            Duration::from_secs(2), // TODO: improve test performance
            data_pool.is_piece_completed(&1).await
        );

        // try to complete the previous future instantly
        let result = timeout!(Duration::from_millis(500), future).unwrap();
        match result {
            Ok(_) => {}
            _ => assert!(false, "expected Ok(), but got {:?}", result),
        }
    }

    #[tokio::test]
    async fn test_len() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        copy_test_file(
            temp_path,
            "piece-1_30.iso",
            Some("debian-12.4.0-amd64-DVD-1.iso"),
        );
        let torrent = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![CreatePiecesAndFilesOperation::new().into(),],
            vec![],
            |params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
            None
        );

        // wait for the pieces to be created
        wait_for_torrent_pieces(&torrent).await;

        // create the stream
        let file = torrent.file(&0).await.unwrap();
        let stream = torrent.stream(&file).await.unwrap();

        let result = stream.len();
        assert_eq!(file.len(), result, "expected the file length to match");
    }

    #[tokio::test]
    async fn test_reset() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        copy_test_file(
            temp_path,
            "piece-1_30.iso",
            Some("debian-12.4.0-amd64-DVD-1.iso"),
        );
        let torrent = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![CreatePiecesAndFilesOperation::new().into(),],
            vec![],
            |params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
            None
        );
        let data_pool = torrent.inner.data_pool().await.unwrap();
        let (peer, _peer2) = tcp_peer_pair!(&torrent, vec![]);
        torrent.inner.peer_connected(peer.clone().into()).await;

        // wait for the pieces to be created
        wait_for_torrent_pieces(&torrent).await;

        // create the stream
        let file = torrent.file(&0).await.unwrap();
        let mut stream = torrent.stream(&file).await.unwrap();

        // set the next piece as completed
        mark_piece_completed!(&stream.command_sender, 0, peer.addr(), "piece-1_30.iso");
        assert_timeout!(
            Duration::from_secs(2), // TODO: improve test performance
            data_pool.is_piece_completed(&0).await
        );

        // read the next stream buffer
        let result = timeout!(Duration::from_millis(750), stream.next());
        match result {
            Some(Ok(_)) => {
                assert_eq!(
                    stream.stream_buffer_len, stream.cursor,
                    "expected the stream cursor to be updated"
                );
            }
            _ => assert!(false, "expected Some(Ok()), but got {:?}", result),
        }

        // reset the stream back to the start
        stream.reset();
        assert_eq!(0, stream.cursor, "expected the cursor to have been reset");
    }

    #[tokio::test]
    async fn test_seek() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        copy_test_file(
            temp_path,
            "piece-1_30.iso",
            Some("debian-12.4.0-amd64-DVD-1.iso"),
        );
        let torrent = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![CreatePiecesAndFilesOperation::new().into(),],
            vec![],
            |params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
            None
        );
        let data_pool = torrent.inner.data_pool().await.unwrap();
        let (peer, _peer2) = tcp_peer_pair!(&torrent, vec![]);
        torrent.inner.peer_connected(peer.clone().into()).await;

        // wait for the pieces to be created
        wait_for_torrent_pieces(&torrent).await;

        // create the stream
        let file = torrent.file(&0).await.unwrap();
        let mut stream = torrent.stream(&file).await.unwrap();

        // set the next piece as completed
        mark_piece_completed!(&stream.command_sender, 0, peer.addr(), "piece-1_30.iso");
        assert_timeout!(
            Duration::from_secs(2), // TODO: improve test performance
            data_pool.is_piece_completed(&0).await
        );

        // read the next stream buffer
        let result = timeout!(Duration::from_millis(750), stream.next());
        match result {
            Some(Ok(_)) => {
                assert_eq!(
                    stream.stream_buffer_len, stream.cursor,
                    "expected the stream cursor to be updated"
                );
            }
            _ => assert!(false, "expected Some(Ok()), but got {:?}", result),
        }

        // seek an offset within the stream
        stream.seek(stream.stream_buffer_len * 3).unwrap();
        assert_eq!(
            stream.stream_buffer_len * 3,
            stream.cursor,
            "expected the cursor to have been reset"
        );
    }

    #[tokio::test]
    async fn test_range() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        copy_test_file(
            temp_path,
            "piece-1_30.iso",
            Some("debian-12.4.0-amd64-DVD-1.iso"),
        );
        let torrent = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![CreatePiecesAndFilesOperation::new().into(),],
            vec![],
            |params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
            None
        );

        // wait for the pieces to be created
        wait_for_torrent_pieces(&torrent).await;

        // create the stream
        let file = torrent.file(&0).await.unwrap();
        let mut stream = torrent.stream(&file).await.unwrap();

        // seek an offset within the stream
        let offset = stream.stream_buffer_len * 5;
        stream.seek(offset).unwrap();
        let result = stream.range();
        assert_eq!(
            offset..file.len(),
            result,
            "expected the stream range to match"
        );

        // reset the stream
        stream.reset();
        let result = stream.range();
        assert_eq!(0..file.len(), result, "expected the stream range to match");
    }

    #[tokio::test]
    async fn test_content_range() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        copy_test_file(
            temp_path,
            "piece-1_30.iso",
            Some("debian-12.4.0-amd64-DVD-1.iso"),
        );
        let torrent = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![CreatePiecesAndFilesOperation::new().into(),],
            vec![],
            |params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
            None
        );

        // wait for the pieces to be created
        wait_for_torrent_pieces(&torrent).await;

        // create the stream
        let file = torrent.file(&0).await.unwrap();
        let mut stream = torrent.stream(&file).await.unwrap();

        // seek an offset within the stream
        let offset = stream.stream_buffer_len * 9;
        stream.seek(offset).unwrap();
        let result = stream.content_range();
        assert_eq!(
            format!("bytes {}-{}/{}", offset, file.len() - 1, file.len()),
            result,
            "expected the stream range to match"
        );

        // reset the stream
        stream.reset();
        let result = stream.content_range();
        assert_eq!(
            format!("bytes 0-{}/{}", file.len() - 1, file.len()),
            result,
            "expected the stream range to match"
        );
    }

    #[tokio::test]
    async fn test_size_hint() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        copy_test_file(
            temp_path,
            "piece-1_30.iso",
            Some("debian-12.4.0-amd64-DVD-1.iso"),
        );
        let torrent = torrent!(
            "debian-udp.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![CreatePiecesAndFilesOperation::new().into(),],
            vec![],
            |params| DiskStorage::new(params.info_hash, params.path, params.data_pool).into(),
            None
        );

        // wait for the pieces to be created
        wait_for_torrent_pieces(&torrent).await;

        // create the stream
        let file = torrent.file(&0).await.unwrap();
        let stream = torrent.stream(&file).await.unwrap();

        let result = stream.size_hint();
        assert_eq!((0, Some(15237)), result, "expected the size hint to match");
    }
}