use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::mpsc::{Receiver, RecvError, TryRecvError};
use super::{PortalChannel, PortalOutcome, SaveChannel, SaveOutcome};
#[derive(Clone)]
pub struct SaveDestination {
name: String,
target: Target,
reference: Option<PathBuf>,
}
type Writer = Arc<dyn Fn(Vec<u8>) -> SaveChannel + Send + Sync>;
#[derive(Clone)]
enum Target {
Path(PathBuf),
Kept(Writer),
}
impl std::fmt::Debug for SaveDestination {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let target = match &self.target {
Target::Path(path) => format!("{}", path.display()),
Target::Kept(_) => "kept by the host".to_owned(),
};
f.debug_struct("SaveDestination")
.field("name", &self.name)
.field("target", &target)
.field("reference", &self.reference)
.finish()
}
}
impl SaveDestination {
pub fn at(path: impl Into<PathBuf>) -> Self {
let path = path.into();
Self {
name: super::file_name_of(&path),
target: Target::Path(path),
reference: None,
}
}
pub fn kept(
name: impl Into<String>,
write: impl Fn(Vec<u8>) -> SaveChannel + Send + Sync + 'static,
) -> Self {
Self {
name: name.into(),
target: Target::Kept(Arc::new(write)),
reference: None,
}
}
pub fn kept_at(
name: impl Into<String>,
reference: PathBuf,
write: impl Fn(Vec<u8>) -> SaveChannel + Send + Sync + 'static,
) -> Self {
Self {
name: name.into(),
target: Target::Kept(Arc::new(write)),
reference: Some(reference),
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn location(&self) -> Option<&Path> {
match &self.target {
Target::Path(path) => Some(path),
Target::Kept(_) => None,
}
}
pub fn reference(&self) -> Option<&Path> {
self.reference.as_deref()
}
#[doc(hidden)]
pub fn write(&self, bytes: Vec<u8>) -> SaveChannel {
match &self.target {
Target::Path(path) => write_path(path.clone(), bytes),
Target::Kept(write) => write(bytes),
}
}
}
fn answered<T>(outcome: T) -> Receiver<T> {
let (tx, rx) = std::sync::mpsc::channel();
let _ = tx.send(outcome);
rx
}
fn write_path(path: PathBuf, bytes: Vec<u8>) -> SaveChannel {
let (tx, rx) = std::sync::mpsc::channel();
let refused = tx.clone();
let spawned =
tilo_rt::background::Background::current().spawn("tilo-portal-write", move || {
let _ = tx.send(match super::replace_saved(&path, &bytes) {
Ok(()) => SaveOutcome::Saved,
Err(error) => SaveOutcome::Failed(format!("{}: {error}", path.display())),
});
});
if spawned.is_err() {
let _ = refused.send(SaveOutcome::Failed(
"this host runs no background work".to_owned(),
));
}
rx
}
#[derive(Debug)]
pub enum DestinationOutcome {
Chosen(SaveDestination),
Cancelled,
Failed(String),
}
#[derive(Debug)]
pub struct DestinationChannel(Pending);
#[derive(Debug)]
enum Pending {
Path(PortalChannel),
Direct(Receiver<DestinationOutcome>),
}
impl DestinationChannel {
pub fn from_path(channel: PortalChannel) -> Self {
Self(Pending::Path(channel))
}
pub fn from_outcomes(channel: Receiver<DestinationOutcome>) -> Self {
Self(Pending::Direct(channel))
}
pub fn answered(outcome: DestinationOutcome) -> Self {
Self::from_outcomes(answered(outcome))
}
pub fn try_recv(&self) -> Result<DestinationOutcome, TryRecvError> {
match &self.0 {
Pending::Path(channel) => channel.try_recv().map(from_path),
Pending::Direct(channel) => channel.try_recv(),
}
}
pub fn recv(&self) -> Result<DestinationOutcome, RecvError> {
match &self.0 {
Pending::Path(channel) => channel.recv().map(from_path),
Pending::Direct(channel) => channel.recv(),
}
}
}
fn from_path(outcome: PortalOutcome) -> DestinationOutcome {
match outcome {
PortalOutcome::Opened(path) => DestinationOutcome::Chosen(SaveDestination::at(path)),
PortalOutcome::Cancelled => DestinationOutcome::Cancelled,
PortalOutcome::Failed(reason) => DestinationOutcome::Failed(reason),
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
tilo_test_env::scenario! {
fn a_save_destination_is_a_chosen_path_or_the_hosts_keeping_or_nothing;
phase a_chosen_path_is_written_in_place_and_named_by_its_file;
{
let dir = std::env::temp_dir().join(format!("tilo-dest-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("report.pdf");
let (tx, rx) = std::sync::mpsc::channel();
tx.send(PortalOutcome::Opened(path.clone())).unwrap();
let DestinationOutcome::Chosen(destination) =
DestinationChannel::from_path(rx).try_recv().unwrap()
else {
panic!("a path was chosen");
};
assert_eq!(destination.name(), "report.pdf");
assert_eq!(destination.location(), Some(path.as_path()));
let work = tilo_rt::background::Pumped::new();
let _work = work.background().enter();
let saved = destination.write(b"%PDF".to_vec());
work.run_pending();
assert_eq!(saved.recv().unwrap(), SaveOutcome::Saved);
assert_eq!(std::fs::read(&path).unwrap(), b"%PDF");
std::fs::remove_dir_all(dir).unwrap();
}
phase a_kept_destination_hands_its_bytes_to_the_host;
{
let written = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let into = std::sync::Arc::clone(&written);
let destination = SaveDestination::kept("notes.pdf", move |bytes| {
into.lock().unwrap().extend(bytes);
answered(SaveOutcome::Saved)
});
assert_eq!(destination.name(), "notes.pdf");
assert_eq!(destination.location(), None, "no path to save in place");
assert_eq!(
destination.write(b"%PDF".to_vec()).recv().unwrap(),
SaveOutcome::Saved
);
assert_eq!(*written.lock().unwrap(), b"%PDF");
assert_eq!(
destination.write(b"!".to_vec()).recv().unwrap(),
SaveOutcome::Saved,
"a kept destination takes the next save too"
);
assert_eq!(*written.lock().unwrap(), b"%PDF!");
}
phase cancelling_or_failing_the_chooser_chooses_nothing;
{
for (outcome, cancelled) in [
(PortalOutcome::Cancelled, true),
(PortalOutcome::Failed("gone".into()), false),
] {
let (tx, rx) = std::sync::mpsc::channel();
tx.send(outcome).unwrap();
match DestinationChannel::from_path(rx).recv().unwrap() {
DestinationOutcome::Cancelled => assert!(cancelled),
DestinationOutcome::Failed(reason) => assert_eq!(reason, "gone"),
DestinationOutcome::Chosen(_) => panic!("nothing was chosen"),
}
}
}
}
}