goat_cli/report/
fetch.rs

1use anyhow::{bail, Result};
2use futures::StreamExt;
3use reqwest;
4use reqwest::header::ACCEPT;
5
6use crate::report::report::{Report, ReportType};
7
8/// CLI entry point to get the Newick file from the GoaT API.
9pub async fn fetch_report(
10    matches: &clap::ArgMatches,
11    unique_ids: Vec<String>,
12    report_type: ReportType,
13) -> Result<()> {
14    let report = Report::new(matches, report_type)?;
15    let url = report.make_url(unique_ids)?;
16
17    let print_url = *matches.get_one::<bool>("url").expect("cli default false");
18    if print_url {
19        println!("GoaT lookup API URL:\t{}", url);
20        std::process::exit(0);
21    }
22
23    // otherwise we get schema errors.
24    // more schemas could be defined here.
25    let header_value = match report_type {
26        ReportType::Newick => "text/x-nh",
27        _ => "text/tab-separated-values",
28    };
29
30    // for now, you can only submit a single request at once.
31    let concurrent_requests = 1;
32
33    // but for future work, might be useful to have concurrent requests
34    // for now this is a bit of extra work for a single request.
35    // but whatever!
36    let url_vector_api = vec![url];
37
38    let fetches = futures::stream::iter(url_vector_api.into_iter().map(|path| async move {
39        // possibly make a again::RetryPolicy
40        // to catch all the values in a *very* large request.
41        let client = reqwest::Client::new();
42
43        match again::retry(|| client.get(&path).header(ACCEPT, header_value).send()).await {
44            Ok(resp) => match resp.text().await {
45                Ok(body) => Ok(body),
46                Err(_) => bail!("ERROR reading {}", path),
47            },
48            Err(_) => bail!("ERROR downloading {}", path),
49        }
50    }))
51    .buffered(concurrent_requests)
52    .collect::<Vec<_>>();
53
54    let awaited_fetches = fetches.await;
55
56    let newick = &awaited_fetches[0];
57
58    match newick {
59        Ok(s) => print!("{}", s),
60        Err(e) => bail!("{}", e),
61    }
62
63    Ok(())
64}