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
use chrono::{DateTime, Utc};
use reqwest::{header::HeaderValue, Url};
use serde::{Deserialize, Serialize};
use snafu::ResultExt;

mod errors {
    use snafu::{Backtrace, Snafu};

    #[derive(Snafu, Debug)]
    #[snafu(visibility = "pub")]
    pub enum Error {
        //#[snafu(display("Could not build request"))]
        Build {
            source: reqwest::header::InvalidHeaderValue,
            backtrace: Backtrace,
        },
        //#[snafu(display("Invalid URL: {}", path))]
        InvalidUrl {
            path: String,
            source: url::ParseError,
            backtrace: Backtrace,
        },
        //#[snafu(display("Failed to access http"))]
        Http {
            source: reqwest::Error,
            backtrace: Backtrace,
        },
        //#[snafu(display("invalid JSON"))]
        Json {
            source: serde_json::Error,
            backtrace: Backtrace,
        },
    }
}

#[derive(Default)]
pub struct HerokuruBuilder {
    token: String,
    base_url: Option<Url>,
}

impl HerokuruBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn base_url(mut self, base_url: impl Into<Option<Url>>) -> Self {
        self.base_url = base_url.into();
        self
    }

    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = token.into();
        self
    }

    pub fn build(self) -> Result<Herokuru, crate::errors::Error> {
        let mut hmap = reqwest::header::HeaderMap::new();
        hmap.append(
            reqwest::header::AUTHORIZATION,
            format!("Bearer {}", self.token)
                .parse()
                .context(errors::Build)?,
        );
        hmap.append(
            reqwest::header::ACCEPT,
            "application/vnd.heroku+json; version=3"
                .parse()
                .context(errors::Build)?,
        );

        let client = reqwest::Client::builder()
            .user_agent("Reqwest/herokuru version 0.1.0")
            .default_headers(hmap)
            .build()
            .context(errors::Http)?;

        Ok(Herokuru {
            client,
            base_url: self
                .base_url
                .unwrap_or_else(|| Url::parse("https://api.heroku.com/").unwrap()),
        })
    }
}

#[derive(Debug, Clone, Default)]
pub struct Page {
    pub key: String,
    pub order: String,
    pub per_page: u32,

    pub range_format: String,
}

impl Page {
    pub fn first_releases() -> Self {
        Self {
            key: "version".to_string(),
            order: "desc".to_string(),
            per_page: 1000u32,
            ..Default::default()
        }
        .gen_range_format()
    }

    fn gen_range_format(mut self) -> Self {
        self.range_format = format!(
            "{} ; order={},max={}",
            &self.key, &self.order, &self.per_page
        );
        self
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Release {
    pub id: String, // is UUID
    pub addon_plan_names: Vec<String>,
    pub app: App,
    pub created_at: DateTime<Utc>,
    pub description: String,
    pub status: String,
    pub slug: Option<Slug>,
    pub updated_at: DateTime<Utc>,
    pub user: User,
    pub version: i32,
    pub current: bool,
    pub output_stream_url: Option<Url>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct App {
    pub id: String,
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Slug {
    pub id: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct User {
    pub id: String,
    pub email: String,
}

#[derive(Debug, Clone)]
pub struct Herokuru {
    client: reqwest::Client,
    pub base_url: Url,
}

impl Herokuru {
    pub fn builder() -> HerokuruBuilder {
        HerokuruBuilder::new()
    }

    pub fn releases(&self, app_name: impl Into<String>) -> ReleasesRequest {
        ReleasesRequest {
            heroku: &self,
            app_name: app_name.into(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ReleasesResponse {
    pub releases: Vec<Release>,
    pub next: Option<Page>,
}

#[derive(Debug, Clone)]
pub struct ReleasesRequest<'a> {
    heroku: &'a Herokuru,
    pub app_name: String,
}

impl ReleasesRequest<'_> {
    pub async fn list(
        &self,
        page: Option<Page>,
    ) -> Result<Option<ReleasesResponse>, crate::errors::Error> {
        match page {
            None => Ok(None),
            Some(page) => {
                let path = format!("apps/{}/releases", self.app_name);
                let url = self
                    .heroku
                    .base_url
                    .join(&path)
                    .context(errors::InvalidUrl { path })?;

                let res = self
                    .heroku
                    .client
                    .get(url)
                    .header("Range", page.range_format.parse::<HeaderValue>().unwrap())
                    .send()
                    .await
                    .context(errors::Http)?;
                let headers = res.headers();

                let next = headers.get("next-range").map(|range_format| Page {
                    range_format: range_format.to_str().unwrap().into(),
                    ..Default::default()
                });
                let json: serde_json::Value = res.json().await.context(errors::Http)?;
                let releases: Vec<Release> = serde_json::from_value(json).context(errors::Json)?;

                Ok(ReleasesResponse { releases, next }.into())
            }
        }
    }

    pub async fn first_list(&self) -> Result<Option<ReleasesResponse>, crate::errors::Error> {
        self.list(Page::first_releases().into()).await
    }
}