datahugger 0.6.1

Tool for fetching data and metadata from DOI or URL.
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
use async_trait::async_trait;
use exn::{Exn, OptionExt, ResultExt};
use futures_core::stream::BoxStream;
use futures_util::{StreamExt, TryStreamExt};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

use reqwest::Client;

use crate::{
    crawl,
    crawler::{CrawlerError, ProgressManager},
    error::ErrorStatus,
    filter::FileFilter,
    Dataset, Entry,
};

use bytes::Buf;
use digest::Digest;
use std::{fs, path::Path};
use tokio::{fs::OpenOptions, io::AsyncWriteExt};
use tracing::{debug, instrument, warn};

use crate::{Checksum, Hasher};

impl Dataset {
    /// crawling and print the metadata of dirs and files
    /// # Errors
    /// when crawl fails
    pub async fn print_meta(
        &self,
        client: &Client,
        mp: MultiProgress,
        limit: usize,
        filter: Option<&FileFilter>,
    ) -> Result<usize, Exn<CrawlerError>> {
        let root_dir = self.root_dir();
        let file_count = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&file_count);
        crawl(client.clone(), Arc::clone(&self.backend), root_dir, mp)
            .try_filter(move |entry| {
                let pass = match entry {
                    Entry::Dir(_) => true,
                    Entry::File(file_meta) => match filter {
                        Some(filter) => filter.matches(file_meta.relative().as_str()),
                        None => true,
                    },
                };
                futures_util::future::ready(pass)
            })
            .try_for_each_concurrent(limit, |entry| {
                let counter = Arc::clone(&counter);
                async move {
                    match entry {
                        Entry::Dir(dir_meta) => {
                            println!("{dir_meta}");
                        }
                        Entry::File(file_meta) => {
                            counter.fetch_add(1, Ordering::Relaxed);
                            println!("{file_meta}");
                        }
                    }
                    Ok(())
                }
            })
            .await
            .or_raise(|| CrawlerError {
                message: "crawl, download and validation failed".to_string(),
                status: ErrorStatus::Permanent,
            })?;
        Ok(file_count.load(Ordering::Relaxed))
    }
}

#[allow(clippy::too_many_lines)]
#[instrument(skip(client, mp))]
async fn download_crawled_file_with_validation<P>(
    client: &Client,
    src: Entry,
    dst: P,
    mp: impl ProgressManager,
) -> Result<(), Exn<CrawlerError>>
where
    P: AsRef<Path> + std::fmt::Debug,
{
    debug!("downloading with validating");
    // dbg!(&src);
    match src {
        Entry::Dir(dir_meta) => {
            let path = dst.as_ref().join(dir_meta.relative());
            // TODO: create_dir to be more strict on stream order
            fs::create_dir_all(path.as_path()).or_raise(|| CrawlerError {
                message: format!("cannot create dir {}", path.display()),
                status: ErrorStatus::Permanent,
            })?;
            Ok(())
        }
        Entry::File(file_meta) => {
            // prepare stream src
            let pb = mp.insert(0, ProgressBar::new_spinner());
            pb.set_style(
                ProgressStyle::with_template("{spinner:.green} {msg}")
                    .expect("indicatif template error"),
            );
            pb.enable_steady_tick(std::time::Duration::from_millis(100));
            pb.set_message(format!(
                "Connecting... {}",
                file_meta.download_url().as_str()
            ));

            if !file_meta.is_downloadable() {
                pb.set_message(format!(
                    "{} is not downloadable",
                    file_meta.download_url().as_str()
                ));
                return Ok(());
            }

            let resp = client
                .get(file_meta.download_url())
                .send()
                .await
                .or_raise(|| CrawlerError {
                    message: format!("fail to send http GET to {}", file_meta.download_url()),
                    status: ErrorStatus::Temporary,
                })?
                .error_for_status()
                .or_raise(|| CrawlerError {
                    message: format!("fail to send http GET to {}", file_meta.download_url()),
                    // Temporary??
                    status: ErrorStatus::Temporary,
                })?;
            pb.finish_and_clear();
            let mut stream = resp.bytes_stream();
            // prepare file dst
            // NOTE: like in zenodo, the file path can exist without its parent dir as Dir entity
            // being created first. To cover that case, the folder of the path will be created no
            // matter it existed or not using `create_dir_all`.
            // See issue #54.
            let path = dst.as_ref().join(file_meta.relative());
            let parent_dir = path.parent().ok_or_raise(|| CrawlerError {
                message: format!("connot get parent dir for '{}'", path.display()),
                status: ErrorStatus::Permanent,
            })?;
            fs::create_dir_all(parent_dir).or_raise(|| CrawlerError {
                message: format!("connot create folder dir of '{}'", parent_dir.display()),
                status: ErrorStatus::Permanent,
            })?;
            let mut fh = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(path.as_path())
                .await
                .or_raise(|| CrawlerError {
                    message: format!("fail on create file at {}", path.display()),
                    status: ErrorStatus::Permanent,
                })?;

            let checksum = file_meta
                .checksum()
                .iter()
                .find(|c| matches!(c, Checksum::Sha256(_)))
                .or_else(|| file_meta.checksum().first());
            let expected_size = file_meta.size();
            let (mut hasher, expected_checksum) = if let Some(checksum) = checksum {
                match checksum {
                    Checksum::Sha256(value) => {
                        (Some(Hasher::Sha256(sha2::Sha256::new())), Some(value))
                    }
                    Checksum::Md5(value) => (Some(Hasher::Md5(md5::Md5::new())), Some(value)),
                    Checksum::Sha1(value) => (Some(Hasher::Sha1(sha1::Sha1::new())), Some(value)),
                }
            } else {
                warn!("unable to find expected checksum to verify");
                (None, None)
            };

            let style = ProgressStyle::with_template(
                "{msg:<60} [{bar:40.cyan/blue}] \
                 {decimal_bytes:>8}/{decimal_total_bytes:>8} \
                 ({decimal_bytes_per_sec:>12}, {eta:>3})",
            )
            .unwrap()
            .progress_chars("=>-");
            let pb = if let Some(expected_size) = expected_size {
                mp.insert_from_back(0, ProgressBar::new(expected_size))
            } else {
                mp.insert_from_back(0, ProgressBar::no_length())
            };
            pb.set_style(style);
            pb.enable_steady_tick(std::time::Duration::from_millis(100));
            pb.set_message(compact_path(file_meta.relative().as_str()));

            let mut got_size = 0;
            while let Some(item) = stream.next().await {
                let mut bytes = item.or_raise(|| CrawlerError {
                    message: "reqwest error stream".to_string(),
                    status: ErrorStatus::Permanent,
                })?;
                let chunk = bytes.chunk();
                if let Some(ref mut hasher) = hasher {
                    hasher.update(chunk);
                }
                let bytes_len = bytes.len() as u64;
                got_size += bytes_len;
                fh.write_all_buf(&mut bytes)
                    .await
                    .or_raise(|| CrawlerError {
                        message: "fail at writing to fs".to_string(),
                        status: ErrorStatus::Permanent,
                    })?;
                pb.inc(bytes_len);
            }

            pb.finish_and_clear();

            if let (Some(expected_size), Some(expected_checksum)) =
                (expected_size, expected_checksum)
            {
                if got_size != expected_size {
                    exn::bail!(CrawlerError {
                        message: format!("size wrong, expect {expected_size}, got {got_size}"),
                        status: ErrorStatus::Permanent
                    })
                }

                let checksum = hex::encode(hasher.expect("hasher is not none").finalize());

                if checksum != *expected_checksum {
                    exn::bail!(CrawlerError {
                        message: format!(
                            "checksum wrong, expect {expected_checksum}, got {checksum}"
                        ),
                        status: ErrorStatus::Permanent
                    })
                }
            }
            Ok(())
        }
    }
}

fn compact_path(full_path: &str) -> String {
    let path = Path::new(full_path);

    // Get components
    let mut comps: Vec<String> = path
        .parent() // everything except the file name
        .map(|p| {
            p.components()
                .map(|c| {
                    let s = c.as_os_str().to_string_lossy();
                    if s.is_empty() {
                        String::new()
                    } else {
                        s.chars().next().unwrap().to_string()
                    }
                })
                .collect()
        })
        .unwrap_or_default();

    // Add base file name
    if let Some(file_name) = path.file_name() {
        comps.push(file_name.to_string_lossy().to_string());
    }

    // Join with slashes
    comps.join("/")
}

#[async_trait]
pub trait DownloadExt {
    async fn download_with_validation<P>(
        self,
        client: &Client,
        dst_dir: P,
        mp: impl ProgressManager,
        limit: usize,
        filter: Option<&FileFilter>,
    ) -> Result<usize, Exn<CrawlerError>>
    where
        P: AsRef<Path> + Sync + Send;
}

#[async_trait]
impl DownloadExt for Dataset {
    /// Downloads all files reachable from a repository root URL into a local directory,
    /// validating both checksum and file size for each downloaded file.
    ///
    /// The repository is crawled recursively starting from its root, and all resolved
    /// files are downloaded concurrently (with a bounded level of parallelism).
    /// Each file is written into `dst_dir` at local fs, preserving its relative path, and is verified
    /// after download to ensure data integrity.
    ///
    /// # Validation
    ///
    /// For every file, this function verifies:
    /// - The downloaded file size matches the expected size.
    /// - The computed checksum matches the checksum provided by the repository metadata.
    ///
    /// A validation failure for any file causes the entire operation to fail.
    ///
    /// # Concurrency
    ///
    /// Downloads are performed concurrently with a fixed upper limit to avoid overwhelming
    /// the network or filesystem.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Dataset crawling fails (e.g. invalid URLs or metadata).
    /// - A file cannot be downloaded due to network or I/O errors.
    /// - The destination directory cannot be created or written to.
    /// - File size or checksum validation fails for any file.
    /// - Any underlying repository or HTTP client operation fails.
    ///
    ///
    /// * `P` is A path-like type specifying the destination directory.
    async fn download_with_validation<P>(
        self,
        client: &Client,
        dst_dir: P,
        mp: impl ProgressManager,
        limit: usize,
        filter: Option<&FileFilter>,
    ) -> Result<usize, Exn<CrawlerError>>
    where
        P: AsRef<Path> + Sync + Send,
    {
        // TODO: deal with zip differently according to input instruction

        let root_dir = self.root_dir();
        let path = dst_dir.as_ref().join(root_dir.relative());
        fs::create_dir_all(path.as_path()).or_raise(|| CrawlerError {
            message: format!("cannot create dir at '{}'", path.display()),
            status: ErrorStatus::Permanent,
        })?;
        let file_count = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&file_count);
        crawl(
            client.clone(),
            Arc::clone(&self.backend),
            root_dir,
            mp.clone(),
        )
        .try_filter(move |entry| {
            let pass = match entry {
                Entry::Dir(_) => true,
                Entry::File(file_meta) => match &filter {
                    Some(filter) => filter.matches(file_meta.relative().as_str()),
                    None => true,
                },
            };
            futures_util::future::ready(pass)
        })
        // NOTE: limit set to 0 as default for cli download,
        // should set to 20 for polite crawling for every dataset, it limit the stream consumer rate.
        .try_for_each_concurrent(limit, |entry| {
            let dst_dir = dst_dir.as_ref().to_path_buf();
            let mp = mp.clone();
            let counter = Arc::clone(&counter);
            async move {
                if matches!(&entry, Entry::File(_)) {
                    counter.fetch_add(1, Ordering::Relaxed);
                }
                download_crawled_file_with_validation(client, entry, &dst_dir, mp).await?;
                Ok(())
            }
        })
        .await
        .or_raise(|| CrawlerError {
            message: "crawl, download and validation failed".to_string(),
            status: ErrorStatus::Permanent,
        })?;
        Ok(file_count.load(Ordering::Relaxed))
    }
}

pub trait CrawlExt {
    fn crawl(
        self,
        client: &Client,
        mp: impl ProgressManager,
    ) -> BoxStream<'static, Result<Entry, Exn<CrawlerError>>>;
}

impl CrawlExt for Dataset {
    fn crawl(
        self,
        client: &Client,
        mp: impl ProgressManager,
    ) -> BoxStream<'static, Result<Entry, Exn<CrawlerError>>> {
        let root_dir = self.root_dir();
        crawl(
            client.clone(),
            Arc::clone(&self.backend),
            root_dir,
            mp.clone(),
        )
    }
}