summaryrefslogtreecommitdiffstats
path: root/taskcluster/docker/image_builder/build-image/src/taskcluster.rs
blob: 3b39d669f08a58f69399864a8378b634460359bf (plain)
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use anyhow::{Context, Result};

pub struct TaskCluster {
    root_url: url::Url,
    client: reqwest::blocking::Client,
}

impl TaskCluster {
    pub fn from_env() -> Result<Self> {
        std::env::var("TASKCLUSTER_ROOT_URL")
            .context("TASKCLUSTER_ROOT_URL not set.")
            .and_then(|var| var.parse().context("Couldn't parse TASKCLUSTER_ROOT_URL."))
            .map(|root_url| TaskCluster {
                root_url,
                client: reqwest::blocking::Client::new(),
            })
    }

    /// Return the root URL as suitable for passing to other processes.
    ///
    /// In particular, any trailing slashes are removed.
    pub fn root_url(&self) -> String {
        self.root_url.as_str().trim_end_matches("/").to_string()
    }

    pub fn task_artifact_url(&self, task_id: &str, path: &str) -> url::Url {
        let mut url = self.root_url.clone();
        url.set_path(&format!("api/queue/v1/task/{}/artifacts/{}", task_id, path));
        url
    }

    pub fn stream_artifact(&self, task_id: &str, path: &str) -> Result<impl std::io::Read> {
        let url = self.task_artifact_url(task_id, path);
        Ok(self.client.get(url).send()?.error_for_status()?)
    }
}

#[cfg(test)]
mod test {
    #[test]
    fn test_url() {
        let cluster = super::TaskCluster {
            root_url: url::Url::parse("http://taskcluster.example").unwrap(),
            client: reqwest::blocking::Client::new(),
        };
        assert_eq!(
            cluster.task_artifact_url("QzDLgP4YRwanIvgPt6ClfA","public/docker-contexts/decision.tar.gz"),
            url::Url::parse("http://taskcluster.example/api/queue/v1/task/QzDLgP4YRwanIvgPt6ClfA/artifacts/public/docker-contexts/decision.tar.gz").unwrap(),
        );
    }
}