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
pub enum DownloadCliError {
    RequestFailure(reqwest::Error),
    InvalidHeaderValue(reqwest::header::InvalidHeaderValue),
    UnexpectedStatus(reqwest::StatusCode),
    Status400(crate::model::ComponentEndpointError),
}

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,
}

#[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.set_path(&format!("v1/{account_id}/golem-cli"));
        if let Some(value) = version {
            url.query_pairs_mut().append_pair("version", &format!("{value}"));
        }
        let result = reqwest::Client::builder()
            .build()?
            .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::ComponentEndpointError>().await?;
                Err(DownloadCliError::Status400(body))
            }
            _ => Err(DownloadCliError::UnexpectedStatus(result.status()))
        }
    }
}