use super::StorageZone;
use crate::client::Client;
use crate::error::{APIResult, error_from_response, Error as APIError};
use crate::files::{file_content, checksum, Error as FileError, urlencode_path};
use std::path::Path;
use reqwest::Method;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
File(#[from] FileError),
#[error("expected SHA256 checksum {expected}, got {received}")]
MismatchedSha256 {
expected: String,
received: String,
}
}
fn get_url(storage_zone: StorageZone, zone_name: &str, dest: &str) -> String {
let dest = dest.strip_prefix('/').unwrap_or(dest);
let dest = urlencode_path(dest);
format!("https://{}/{}/{}", storage_zone.url(), zone_name, dest)
}
async fn upload_data(client: &Client, url: String, content: Vec<u8>, expected_sha256: Option<String>) -> APIResult<(), Error> {
#[cfg(feature = "tracing")]
tracing::debug!("hashing file contents");
let hash = checksum(&content);
if let Some(expected) = expected_sha256 {
let expected = expected.to_uppercase();
#[cfg(feature = "tracing")]
tracing::debug!(%expected, %hash, "checking that hash matches expected value");
if expected != hash {
return Err(APIError::new(
Method::PUT,
url,
Error::MismatchedSha256 { expected, received: hash }
));
}
}
let request = client
.put(&url)
.header("Checksum", hash)
.header("content-type", "application/octet-stream")
.body(content)
.build()
.map_err(crate::Error::map_request_err(
Method::PUT,
url.clone(),
))?;
let resp = client
.send_logged(request)
.await
.map_err(crate::Error::map_request_err(
Method::PUT,
url.clone(),
))?;
error_from_response(resp)
.await
.map(|_| ())
.map_err(crate::Error::map_response_err(Method::PUT, url))
}
#[allow(clippy::module_name_repetitions)]
pub async fn upload_file_by_path(client: &Client, storage_zone: StorageZone, zone_name: &str, dest: &str, file: &Path, expected_sha256: Option<String>) -> APIResult<(), Error> {
let url = get_url(storage_zone, zone_name, dest);
let content = file_content(file).await
.map_err(Error::from)
.map_err(crate::Error::map_err(
Method::PUT,
url.clone(),
))?;
upload_data(client, url, content, expected_sha256).await
}
#[allow(clippy::module_name_repetitions)]
pub async fn upload_file_data(client: &Client, storage_zone: StorageZone, zone_name: &str, dest: &str, content: Vec<u8>, expected_sha256: Option<String>) -> APIResult<(), Error> {
let url = get_url(storage_zone, zone_name, dest);
upload_data(client, url, content, expected_sha256).await
}