scientific-workflow 0.17.1

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
//! Workflow Object API v1. An ordinary read-only HTTP file server is insufficient.
use super::Backend;
use reqwest::{
    StatusCode, Url,
    blocking::{Client, Response},
};
use serde::Deserialize;
use std::{
    fs::File,
    io::{self, Read},
    path::Path,
    time::Duration,
};

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Profile {
    bearer_token: String,
    #[serde(default)]
    ca_certificate: Option<std::path::PathBuf>,
}
pub(super) struct Https {
    client: Client,
    base: Url,
    profile: std::path::PathBuf,
}
pub(super) fn client() -> io::Result<Client> {
    Client::builder()
        .connect_timeout(Duration::from_secs(15))
        .timeout(Duration::from_secs(120))
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .map_err(io::Error::other)
}
pub(super) fn response(response: Response) -> io::Result<Response> {
    let status = response.status();
    if status.is_success() {
        return Ok(response);
    }
    let kind = match status {
        StatusCode::NOT_FOUND => io::ErrorKind::NotFound,
        StatusCode::CONFLICT | StatusCode::PRECONDITION_FAILED => io::ErrorKind::AlreadyExists,
        StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => io::ErrorKind::PermissionDenied,
        _ => io::ErrorKind::Other,
    };
    Err(io::Error::new(
        kind,
        format!("storage request returned HTTP {}", status.as_u16()),
    ))
}
impl Https {
    pub(super) fn new(endpoint: &str, profile: &Path) -> io::Result<Self> {
        let base = Url::parse(&format!("{}/", endpoint.trim_end_matches('/')))
            .map_err(io::Error::other)?;
        if base.scheme() != "https"
            || base.username() != ""
            || base.password().is_some()
            || base.query().is_some()
            || base.fragment().is_some()
        {
            return Err(io::Error::other(
                "storage requires an HTTPS API URL without inline credentials",
            ));
        }
        let credentials: Profile = serde_json::from_reader(File::open(profile)?)
            .map_err(|_| io::Error::other("invalid HTTPS credential profile"))?;
        let client = if let Some(path) = credentials.ca_certificate {
            let pem = std::fs::read(path)?;
            Client::builder()
                .connect_timeout(Duration::from_secs(15))
                .timeout(Duration::from_secs(120))
                .redirect(reqwest::redirect::Policy::none())
                .add_root_certificate(
                    reqwest::Certificate::from_pem(&pem).map_err(io::Error::other)?,
                )
                .build()
                .map_err(io::Error::other)?
        } else {
            client()?
        };
        let this = Self {
            client,
            base,
            profile: profile.into(),
        };
        let capabilities: serde_json::Value = response(
            this.client
                .get(this.url("v1/capabilities")?)
                .bearer_auth(this.token()?)
                .send()
                .map_err(io::Error::other)?,
        )?
        .json()
        .map_err(io::Error::other)?;
        if capabilities["protocol"] != "scientific-workflow-object.v1"
            || ["create_only", "replace", "read", "delete", "list"]
                .iter()
                .any(|k| capabilities[*k] != true)
        {
            return Err(io::Error::other(
                "destination lacks required Workflow Object API v1 capabilities",
            ));
        }
        Ok(this)
    }
    fn token(&self) -> io::Result<String> {
        let profile: Profile = serde_json::from_reader(File::open(&self.profile)?)
            .map_err(|_| io::Error::other("invalid HTTPS credential profile"))?;
        Ok(profile.bearer_token)
    }
    fn url(&self, key: &str) -> io::Result<Url> {
        crate::artifact::validate_key(key)?;
        let mut url = self.base.clone();
        url.path_segments_mut()
            .map_err(|_| io::Error::other("invalid API base"))?
            .pop_if_empty()
            .extend(key.split('/'));
        Ok(url)
    }
}
impl Backend for Https {
    fn read(&self, key: &str) -> io::Result<Box<dyn Read + Send>> {
        Ok(Box::new(response(
            self.client
                .get(self.url(&format!("v1/objects/{key}"))?)
                .bearer_auth(self.token()?)
                .send()
                .map_err(io::Error::other)?,
        )?))
    }
    fn write(&self, key: &str, path: &Path, create: bool) -> io::Result<()> {
        self.write_stream(
            key,
            Box::new(File::open(path)?),
            path.metadata()?.len(),
            create,
        )
    }
    fn write_stream(
        &self,
        key: &str,
        reader: Box<dyn Read + Send>,
        bytes: u64,
        create: bool,
    ) -> io::Result<()> {
        let mut request = self
            .client
            .put(self.url(&format!("v1/objects/{key}"))?)
            .bearer_auth(self.token()?)
            .header("Content-Type", "application/octet-stream")
            .body(reqwest::blocking::Body::sized(reader, bytes));
        if create {
            request = request.header("If-None-Match", "*");
        }
        response(request.send().map_err(io::Error::other)?)?;
        Ok(())
    }
    fn remove(&self, key: &str) -> io::Result<()> {
        match response(
            self.client
                .delete(self.url(&format!("v1/objects/{key}"))?)
                .bearer_auth(self.token()?)
                .send()
                .map_err(io::Error::other)?,
        ) {
            Ok(_) => Ok(()),
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(e),
        }
    }
    fn list(&self, prefix: &str) -> io::Result<Vec<String>> {
        let values: Vec<String> = response(
            self.client
                .get(self.url("v1/objects")?)
                .query(&[("prefix", prefix)])
                .bearer_auth(self.token()?)
                .send()
                .map_err(io::Error::other)?,
        )?
        .json()
        .map_err(io::Error::other)?;
        for key in &values {
            crate::artifact::validate_key(key)?;
        }
        Ok(values)
    }
}