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
//! When fetching a file from a web server via GET, it is possible to define a range of bytes to
//! receive per request. This allows the possibility of using multiple GET requests on the same
//! URL to increase the throughput of a transfer for that file. Once the parts have been fetched,
//! they are concatenated into a single file.
//!
//! Therefore, this crate will make it trivial to set up a parallel GET request, with an API that
//! provides a configurable number of threads and an optional callback to monitor the progress of
//! a transfer.
//!
//! ## Example
//!
//! ```rust,no_run
//! extern crate parallel_getter;
//!
//! use parallel_getter::ParallelGetter;
//! use std::fs::File;
//!
//! fn main() {
//!     let url = "http://apt.pop-os.org/proprietary/pool/bionic/main/\
//!         binary-amd64/a/atom/atom_1.31.1_amd64.deb";
//!     let mut file = File::create("atom_1.31.1_amd64.deb").unwrap();
//!     let result = ParallelGetter::new(url, &mut file)
//!         .threads(4)
//!         .callback(1000, Box::new(|p, t| {
//!             println!(
//!                 "{} of {} KiB downloaded",
//!                 p / 1024,
//!                 t / 1024);
//!         }))
//!         .get();
//!
//!     if let Err(why) = result {
//!         eprintln!("errored: {}", why);
//!     }
//! }
//! ```

extern crate crossbeam;
extern crate numtoa;
extern crate progress_streams;
extern crate reqwest;
extern crate tempfile;

mod range;

use crossbeam::thread::ScopedJoinHandle;
use numtoa::NumToA;
use progress_streams::ProgressWriter;
use reqwest::{Client, StatusCode, header::{
    CONTENT_LENGTH,
    CONTENT_RANGE,
    RANGE,
}};
use self::range::{calc_range, range_header, range_string};
use std::{fs, thread};
use std::io::{self, Cursor, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

trait PartWriter: Send + Seek + Read + Write {}
impl<T: Send + Seek + Read + Write> PartWriter for T {}

/// Type for constructing parallel GET requests.
///
/// # Example
///
/// ```rust,no_run
/// extern crate reqwest;
/// extern crate parallel_getter;
///
/// use reqwest::Client;
/// use parallel_getter::ParallelGetter;
/// use std::fs::File;
/// use std::path::PathBuf;
/// use std::sync::Arc;
///
/// let client = Arc::new(Client::new());
/// let mut file = File::create("new_file").unwrap();
/// ParallelGetter::new("url_here", &mut file)
///     // Additional mirrors that can be used.
///     .mirrors(&["mirror_a", "mirror_b"])
///     // Optional client to use for the request.
///     .client(client)
///     // Optional path to store the parts.
///     .cache_path(PathBuf::from("/a/path/here"))
///     // Number of theads to use.
///     .threads(5)
///     // threshold (length in bytes) to determine when multiple threads are required.
///     .threshold_parallel(1 * 1024 * 1024)
///     // threshold for defining when to store parts in memory or on disk.
///     .threshold_memory(10 * 1024 * 1024)
///     // Callback for monitoring progress.
///     .callback(16, Box::new(|progress, total| {
///         println!(
///             "{} of {} KiB downloaded",
///             progress / 1024,
///             total / 1024
///         );
///     }))
///     // Commit the parallel GET requests.
///     .get();
/// ```
pub struct ParallelGetter<'a, W: Write + 'a> {
    client: Option<Arc<Client>>,
    urls: Vec<&'a str>,
    dest: &'a mut W,
    threads: usize,
    threshold_parallel: Option<u64>,
    threshold_memory: Option<u64>,
    tries: u32,
    cache_path: Option<PathBuf>,
    progress_callback: Option<(Box<Fn(u64, u64)>, u64)>
}

impl<'a, W: Write> ParallelGetter<'a, W> {
    /// Initialize a new `ParallelGetter`
    ///
    /// # Notes
    /// - The `url` is the location which we will send a GET to.
    /// - The `dest` is where the completed file will be written to.
    /// - By default, 4 threads will be used.
    pub fn new(url: &'a str, dest: &'a mut W) -> Self {
        Self {
            client: None,
            urls: vec![url],
            dest,
            threads: 4,
            threshold_parallel: None,
            threshold_memory: None,
            tries: 3,
            cache_path: None,
            progress_callback: None,
        }
    }

    /// Submit the parallel GET request.
    pub fn get(mut self) -> io::Result<usize> {
        let client = self.client.take().unwrap_or_else(|| Arc::new(Client::new()));
        let length = match get_content_length(&client, self.urls[0]) {
            Ok(length) => {
                if let Some(threshold) = self.threshold_parallel {
                    if length < threshold {
                        self.threads = 1;
                    }
                }

                length
            },
            Err(_) => {
                self.threads = 1;
                0
            }
        };

        let result = self.parallel_get(client, length);

        // Ensure that the progress is completed when returning.
        if let Some((callback, _)) = self.progress_callback {
            callback(length, length);
        }

        result
    }

    /// If defined, downloads will be stored here instead of a temporary directory.
    ///
    /// # Notes
    /// This is required to enable resumable downloads (not yet implemented).
    pub fn cache_path(mut self, path: PathBuf) -> Self {
        self.cache_path = Some(path);
        self
    }

    /// Specify a callback for monitoring progress, to be polled at the given interval.
    pub fn callback(mut self, poll_ms: u64, func: Box<Fn(u64, u64)>) -> Self {
        self.progress_callback = Some((func, poll_ms));
        self
    }

    /// Allow the caller to provide their own `Client`.
    pub fn client(mut self, client: Arc<Client>) -> Self {
        self.client = Some(client);
        self
    }

    /// Specify additional URLs that point to the same content, to be used for boosted transfers.
    pub fn mirrors(mut self, mirrors: &'a [&'a str]) -> Self {
        self.urls.truncate(1);
        self.urls.extend_from_slice(mirrors);
        self
    }

    /// Number of attempts to make before giving up.
    pub fn retries(mut self, tries: u32) -> Self {
        self.tries = tries;
        self
    }

    /// If the length is less than this threshold, parts will be stored in memory.
    pub fn threshold_memory(mut self, length: u64) -> Self {
        self.threshold_memory = Some(length);
        self
    }

    /// If the length is less than this threshold, threads will not be used.
    pub fn threshold_parallel(mut self, bytes: u64) -> Self {
        self.threshold_parallel = Some(bytes);
        self
    }

    /// Number of threads to download a file with.
    pub fn threads(mut self, threads: usize) -> Self {
        self.threads = threads;
        self
    }

    fn create_parts(
        &self,
        cache_path: &Path,
        length: u64,
        nthreads: u64,
        url_hash: &str
    ) -> io::Result<Vec<Box<dyn PartWriter>>> {
        let mut parts = Vec::new();

        for part in 0u64..nthreads {
            let mut part: Box<dyn PartWriter> = match self.threshold_memory {
                Some(threshold) if threshold > length => {
                    Box::new(Cursor::new(
                        Vec::with_capacity((length / nthreads) as usize)
                    ))
                }
                _ => {
                    let mut array = [0u8; 20];
                    let name = [&url_hash, "-", part.numtoa_str(10, &mut array)].concat();
                    let tempfile = cache_path.join(&name);
                    Box::new(
                        fs::OpenOptions::new()
                            .read(true)
                            .write(true)
                            .truncate(true)
                            .create(true)
                            .open(tempfile)?
                    )
                }
            };

            parts.push(part);
        }

        Ok(parts)
    }

    fn parallel_get(&mut self, client: Arc<Client>, length: u64) -> io::Result<usize> {
        let progress = Arc::new(AtomicUsize::new(0));
        let nthreads = self.threads as u64;

        let has_callback = self.progress_callback.is_some();
        let progress_callback = self.progress_callback.take();
        let tries = self.tries;
        let urls = &self.urls;

        let tempdir;
        let cache_path = match self.cache_path {
            Some(ref path) => path.as_path(),
            None => {
                tempdir = tempfile::tempdir()?;
                tempdir.path()
            }
        };

        let url_hash = hash(urls[0]);
        let parts = self.create_parts(cache_path, length, nthreads, &url_hash)?;
        let dest = &mut self.dest;

        let result: io::Result<()> = {
            let progress = progress.clone();
            crossbeam::scope(move |scope| {
                let mut threads = Vec::new();
                for (part, mut part_file) in (0u64..nthreads).zip(parts.into_iter()) {
                    let client = client.clone();
                    let progress = progress.clone();

                    let local_progress = Arc::new(AtomicUsize::new(0));
                    let local = local_progress.clone();
                    let handle: ScopedJoinHandle<io::Result<_>> = scope.spawn(move || {
                        let range = calc_range(length, nthreads, part);

                        for tried in 0..tries {
                            let url = urls[((part as usize) + tried as usize) % urls.len()];
                            let result = attempt_get(
                                client.clone(), &mut part_file, url, &progress,
                                &local, length, range, has_callback
                            );

                            match result {
                                Ok(()) => break,
                                Err(why) => {
                                    progress.fetch_sub(local.load(Ordering::SeqCst), Ordering::SeqCst);
                                    local.store(0, Ordering::SeqCst);
                                    part_file.seek(SeekFrom::Start(0))?;
                                    if tried == tries-1 {
                                        return Err(why);
                                    }
                                }
                            }
                        }

                        part_file.seek(SeekFrom::Start(0))?;

                        Ok(part_file)
                    });

                    threads.push(handle);
                }

                if let Some((ref progress_callback, mut poll_ms)) = progress_callback {
                    // Poll for progress until all background threads have exited.
                    poll_ms = if poll_ms == 0 { 1 } else { poll_ms };
                    let poll_ms = Duration::from_millis(poll_ms);

                    let mut time_since_update = Instant::now();
                    while Arc::strong_count(&progress) != 1 {
                        let progress = progress.load(Ordering::SeqCst) as u64;
                        if time_since_update.elapsed() > poll_ms {
                            progress_callback(progress, length);
                            time_since_update = Instant::now();
                        }

                        if progress >= length { break }
                        thread::sleep(Duration::from_millis(1));
                    }
                }

                for handle in threads {
                    let mut file = handle.join().unwrap()?;
                    io::copy(&mut file, dest)?;
                }

                Ok(())
            })
        };

        result?;

        Ok(progress.load(Ordering::SeqCst))
    }
}

fn attempt_get(
    client: Arc<Client>,
    part: &mut Box<dyn PartWriter>,
    url: &str,
    progress: &AtomicUsize,
    local: &AtomicUsize,
    length: u64,
    range: Option<(u64, u64)>,
    has_callback: bool,
) -> io::Result<()> {
    if has_callback {
        let mut writer = ProgressWriter::new(part, |written| {
            progress.fetch_add(written, Ordering::SeqCst);
            local.fetch_add(written, Ordering::SeqCst);
        });

        send_get_request(client, &mut writer, url, length, range)?;
    } else {
        send_get_request(client, part, url, length, range)?;
    }

    Ok(())
}

fn send_get_request(
    client: Arc<Client>,
    writer: &mut impl Write,
    url: &str,
    length: u64,
    range: Option<(u64, u64)>
) -> io::Result<u64> {
    let mut client = client.get(url);

    if let Some((from, to)) = range {
        client = client.header(RANGE, range_string(from, to).as_str());
    }

    let mut response = client.send()
        .map_err(|why| io::Error::new(
            io::ErrorKind::Other,
            format!("reqwest get failed: {}", why))
        )?;

    if let Some((from, to)) = range {
        if response.status() != StatusCode::PARTIAL_CONTENT {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "server did not return a partial request"
            ));
        }

        match response.headers().get(CONTENT_RANGE) {
            Some(header) => range_header(header, from, to, length)?,
            None => return Err(io::Error::new(
                io::ErrorKind::Other,
                "server did not return a `content-range` header"
            ))
        }
    } else {
        let status = response.status();
        if status != StatusCode::OK {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("server returned an error: {}", status)
            ));
        }
    }

    response.copy_to(writer)
        .map_err(|why|
            io::Error::new(
                io::ErrorKind::Other,
                format!("reqwest copy failed: {}", why)
            )
        )
}

fn get_content_length(client: &Client, url: &str) -> io::Result<u64> {
    let resp = client.head(url).send()
        .map_err(|why| io::Error::new(
            io::ErrorKind::Other,
            format!("failed to send HEAD reqest: {}", why)
        ))?;

    resp.headers().get(CONTENT_LENGTH)
        .ok_or_else(|| io::Error::new(
            io::ErrorKind::NotFound,
            "content length not found"
        ))?
        .to_str()
        .map_err(|_| io::Error::new(
            io::ErrorKind::InvalidData,
            "Content-Length is not UTF-8"
        ))?
        .parse::<u64>()
        .map_err(|_| io::Error::new(
            io::ErrorKind::InvalidData,
            "Content-Length did not have a valid u64 integer"
        ))
}

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

fn hash(string: &str) -> String {
    let mut hasher = DefaultHasher::new();
    string.hash(&mut hasher);
    format!("{:x}", hasher.finish())
}