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
#[derive(Debug)]
pub enum DownloadCliError {
    RequestFailure(reqwest::Error),
    InvalidHeaderValue(reqwest::header::InvalidHeaderValue),
    UnexpectedStatus(reqwest::StatusCode),
    Status400(crate::model::TemplateEndpointError),
}

impl From<reqwest::Error> for DownloadCliError {
    fn from(error: reqwest::Error) -> DownloadCliError {
        DownloadCliError::RequestFailure(error)
    }
}

impl From<reqwest::header::InvalidHeaderValue> for DownloadCliError {
    fn from(error: reqwest::header::InvalidHeaderValue) -> DownloadCliError {
        DownloadCliError::InvalidHeaderValue(error)
    }
}

#[async_trait::async_trait]
pub trait DownloadCli {
    async fn download_cli(&self, account_id: &str, version: Option<&str>) -> Result<Box<dyn futures_core::Stream<Item = reqwest::Result<bytes::Bytes>> + Send + Sync + Unpin>, DownloadCliError>;
}

#[derive(Clone, Debug)]
pub struct DownloadCliLive {
    pub base_url: reqwest::Url,
    pub allow_insecure: bool,
}

#[async_trait::async_trait]
impl DownloadCli for DownloadCliLive {
    async fn download_cli(&self, account_id: &str, version: Option<&str>) -> Result<Box<dyn futures_core::Stream<Item = reqwest::Result<bytes::Bytes>> + Send + Sync + Unpin>, DownloadCliError> {
        let mut url = self.base_url.clone();
        url.path_segments_mut().unwrap()
            .push("v1")
            .push(account_id)
            .push("golem-cli");
        if let Some(value) = version {
            url.query_pairs_mut().append_pair("version", &format!("{value}"));
        }
        {
            let headers_vec: Vec<(&str, String)> = vec![];            tracing::info!(method="get", url=url.to_string(), headers=?headers_vec, body="<no_body>", "download_cli");
        }
        let mut builder = reqwest::Client::builder();
        if self.allow_insecure {
            builder = builder.danger_accept_invalid_certs(true);
        }
        let client = builder.build()?;
        let result = client
            .get(url)
            .send()
            .await?;
        match result.status().as_u16() {
            200 => {
                let body = Box::new(result.bytes_stream());
                Ok(body)
            }
            400 => {
                let body = result.json::<crate::model::TemplateEndpointError>().await?;
                Err(DownloadCliError::Status400(body))
            }
            _ => Err(DownloadCliError::UnexpectedStatus(result.status()))
        }
    }
}