use bytes::Bytes;
use std::{
any::Any,
collections::HashMap,
os::unix::fs::MetadataExt,
path::{Path, PathBuf},
sync::Arc,
};
use thiserror::Error;
use tokio::sync::mpsc::{self, Receiver, Sender};
use crate::update_workflow::UpdateError;
#[derive(Debug, Error)]
pub enum UpdateSourceError {
#[error("configuration error: {0}")]
ConfigurationError(String),
#[error("connection error: {0}")]
ConnectionError(String),
#[error("fetch error: {0}")]
FetchError(String),
#[error("Consent required")]
ConsentRequired,
#[error("Invalid state")]
InvalidState,
}
impl From<StreamError> for UpdateError {
fn from(e: StreamError) -> Self {
UpdateError::UpdateSourceError(UpdateSourceError::FetchError(format!(
"stream error: {}",
e
)))
}
}
pub trait UpdateInfo {
fn needs_consent(&self) -> bool;
fn metadata(&self) -> HashMap<String, String>;
fn version(&self) -> String;
fn give_consent(&mut self)
-> impl std::future::Future<Output = Result<(), UpdateError>> + Send;
fn update(&self) -> Result<impl Update, UpdateError>;
}
#[derive(Debug, Error)]
pub enum StreamError {
#[error("streaming unsupported")]
Unsupported,
#[error(transparent)]
IOError(#[from] std::io::Error),
#[error("{0}")]
ReceiveError(String),
#[error("{0}")]
SendError(String),
}
impl From<tokio::sync::mpsc::error::SendError<Result<Bytes, StreamError>>> for StreamError {
fn from(e: tokio::sync::mpsc::error::SendError<Result<Bytes, StreamError>>) -> Self {
StreamError::SendError(format!("send error: {}", e))
}
}
pub type StreamSender = Sender<Result<Bytes, StreamError>>;
pub type StreamReceiver = Receiver<Result<Bytes, StreamError>>;
pub trait Update: Send + Sync + Clone + 'static {
fn as_any(&self) -> &dyn Any;
fn version(&self) -> &str;
fn size(&self) -> u64;
fn save_to_disk(
&self,
path_hint: Option<PathBuf>,
) -> impl std::future::Future<Output = Result<Vec<UpdateFile<impl Update>>, UpdateError>>
+ std::marker::Send {
async move {
if let Some(path_hint) = &path_hint {
tokio::fs::create_dir_all(path_hint).await?
}
let mut target_files = Vec::new();
for file in self.files() {
target_files.push(self.save_to_disk_by_name(file, path_hint.clone()).await?);
}
Ok(target_files)
}
}
fn stream(&self) -> Result<StreamReceiver, UpdateError> {
let (tx, rx) = mpsc::channel::<Result<Bytes, StreamError>>(1);
let update = self.clone();
tokio::spawn(async move {
let tx = tx;
for file in update.files() {
update.stream_by_name(file, &tx).await;
}
});
Ok(rx)
}
fn save_to_disk_by_name(
&self,
artifact: String,
save_dir: Option<PathBuf>,
) -> impl std::future::Future<Output = Result<UpdateFile<impl Update>, UpdateError>>
+ std::marker::Send;
fn stream_by_name(
&self,
artifact: String,
stream: &StreamSender,
) -> impl std::future::Future<Output = ()> + std::marker::Send;
fn files(&self) -> Vec<String>;
}
#[derive(Clone)]
pub struct UpdateFile<U: Update> {
pub filename: PathBuf,
pub version: String,
pub size: u64,
pub parent_update: Arc<U>,
}
impl<U: Update> UpdateFile<U> {
pub async fn new(filename: &Path, parent: &U) -> Result<UpdateFile<U>, UpdateError> {
let size = tokio::fs::metadata(filename).await?.size();
Ok(UpdateFile {
filename: PathBuf::from(filename),
version: parent.version().to_string(),
size,
parent_update: Arc::new(parent.clone()),
})
}
}
impl<U: Update> Update for UpdateFile<U> {
fn as_any(&self) -> &dyn Any {
self.parent_update.as_any()
}
fn version(&self) -> &str {
&self.version
}
fn size(&self) -> u64 {
self.size
}
async fn save_to_disk_by_name(
&self,
artifact: String,
save_dir: Option<PathBuf>,
) -> Result<UpdateFile<impl Update>, UpdateError> {
if let Some(save_dir) = save_dir {
let filename = Path::new(&artifact).file_name();
if let Some(filename) = filename {
let mut target_file = save_dir;
target_file.push(filename);
if self.filename != target_file {
tokio::fs::copy(artifact, &target_file).await?;
}
Ok(UpdateFile::new(&target_file, &*self.parent_update).await?)
} else {
Err(UpdateSourceError::FetchError(format!("{artifact} is not a filename")).into())
}
} else {
Ok(self.clone())
}
}
async fn stream_by_name(&self, _artifact: String, stream: &StreamSender) {
stream.send(Err(StreamError::Unsupported)).await.ok();
}
fn files(&self) -> Vec<String> {
vec![self.filename.to_string_lossy().to_string()]
}
}
pub trait UpdateSource {
fn check_for_updates(
&mut self,
) -> impl std::future::Future<Output = Result<impl UpdateInfo, UpdateError>>;
}