use std::io::{self, Read, Write};
use std::path::Path;
use std::time::{Duration, SystemTime};
use tinystore::client::Client;
use tinystore::{Error, ErrorKind};
const ANSWER_WAIT: Duration = if cfg!(test) { Duration::from_secs(1) } else { Duration::from_secs(10) };
#[derive(Debug)]
pub(crate) struct Found {
pub(crate) pid: u64,
pub(crate) endpoints: Vec<String>,
pub(crate) since: SystemTime,
pub(crate) embedded: bool,
secret: Vec<u8>,
}
pub(crate) fn found(dir: &Path) -> Result<Option<Found>, String> {
let path = dir.join("server").join("SERVE");
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(format!("{}: {error}", path.display())),
};
let unreadable = |why: &str| format!("{}: {why}", path.display());
let serve: serde_json::Value = serde_json::from_str(&text).map_err(|error| unreadable(&error.to_string()))?;
let field = |name: &str| serve.get(name).ok_or_else(|| unreadable(&format!("no {name}")));
let endpoints = field("endpoints")?.as_array().ok_or_else(|| unreadable("endpoints that are no list"))?;
let since = std::fs::metadata(&path).and_then(|metadata| metadata.modified()).unwrap_or_else(|_| SystemTime::now());
Ok(Some(Found {
pid: field("pid")?.as_u64().unwrap_or_default(),
endpoints: endpoints.iter().filter_map(|endpoint| endpoint.as_str().map(str::to_owned)).collect(),
since,
embedded: serve["embedded"] == true,
secret: tinystore::local::from_base64url(field("secret")?.as_str().unwrap_or_default())
.ok_or_else(|| unreadable("a secret that is no base64url"))?,
}))
}
pub(crate) trait Stream: Read + Write + Send {}
impl<T: Read + Write + Send> Stream for T {}
pub(crate) struct Connection {
client: Client<Box<dyn Stream>>,
pub(crate) server: String,
pub(crate) durability: Option<String>,
}
impl Found {
pub(crate) fn connect(&self) -> Result<Connection, String> {
let endpoint = self.endpoints.first().ok_or("SERVE names no endpoint")?.clone();
let secret = self.secret.clone();
answered_within(&endpoint.clone(), move || hello(&endpoint, &secret))
}
}
fn hello(endpoint: &str, secret: &[u8]) -> Result<Connection, String> {
let stream = dial(endpoint).map_err(|error| format!("{endpoint}: {error}"))?;
let mut challenge = [0; 16];
getrandom::fill(&mut challenge).map_err(|error| error.to_string())?;
let name = format!("tinystore-cli/{}", env!("CARGO_PKG_VERSION"));
let (client, welcome) =
Client::hello(stream, &name, Some(challenge)).map_err(|error| format!("{endpoint}: {error}"))?;
let proof = welcome.proof.ok_or("the server gave no proof")?;
if !tinystore::local::proven(secret, &challenge, &proof) {
return Err("a process on the endpoint did not prove it is the store's server".to_owned());
}
Ok(Connection { client, server: welcome.server, durability: welcome.durability })
}
impl Connection {
pub(crate) fn stop(self) -> Result<(), String> {
let mut connection = self;
answered_within("server.stop", move || connection.client.stop().map_err(|error| error.to_string()))
}
pub(crate) fn into_client(self) -> Client<Box<dyn Stream>> {
self.client
}
pub(crate) fn run<T>(
self,
call: impl FnOnce(&mut Client<Box<dyn Stream>>) -> tinystore::Result<T>,
) -> tinystore::Result<T> {
let mut connection = self;
call(&mut connection.client)
}
pub(crate) fn call<T: Send + 'static>(
self,
what: &str,
call: impl FnOnce(&mut Client<Box<dyn Stream>>) -> tinystore::Result<T> + Send + 'static,
) -> (Option<Connection>, tinystore::Result<T>) {
let mut connection = self;
let timed_out = |why: String| Error::new(ErrorKind::OutcomeUnknown, why);
let answered = within(what, timed_out, move || {
let answer = call(&mut connection.client);
let lost = answer.as_ref().is_err_and(|error| {
matches!(error.kind(), ErrorKind::OutcomeUnknown | ErrorKind::Unavailable | ErrorKind::Corrupt)
});
Ok((if lost { None } else { Some(connection) }, answer))
});
answered.unwrap_or_else(|error| (None, Err(error)))
}
}
fn answered_within<T: Send + 'static>(
what: &str,
exchange: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, String> {
within(what, |why| why, exchange)
}
fn within<T: Send + 'static, E: Send + 'static>(
what: &str,
timed_out: impl FnOnce(String) -> E,
exchange: impl FnOnce() -> Result<T, E> + Send + 'static,
) -> Result<T, E> {
let (done, answer) = std::sync::mpsc::channel();
std::thread::spawn(move || drop(done.send(exchange())));
answer.recv_timeout(ANSWER_WAIT).unwrap_or_else(|_| {
Err(timed_out(format!("{what}: the server did not answer within {} s", ANSWER_WAIT.as_secs())))
})
}
#[cfg(unix)]
fn dial(endpoint: &str) -> io::Result<Box<dyn Stream>> {
let path = endpoint.strip_prefix("unix://").ok_or_else(|| io::Error::other("not a local socket"))?;
Ok(Box::new(std::os::unix::net::UnixStream::connect(path)?))
}
#[cfg(windows)]
fn dial(endpoint: &str) -> io::Result<Box<dyn Stream>> {
let name = endpoint.strip_prefix("pipe:").ok_or_else(|| io::Error::other("not a named pipe"))?;
let path = format!(r"\\.\pipe\{name}");
let mut tries = 0;
loop {
match std::fs::OpenOptions::new().read(true).write(true).open(&path) {
Ok(pipe) => return Ok(Box::new(pipe)),
Err(error) if error.raw_os_error() == Some(231) && tries < 50 => {
tries += 1;
std::thread::sleep(Duration::from_millis(20));
}
Err(error) => return Err(error),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_server_that_takes_the_connection_and_never_answers_is_said_within_the_wait() {
let (endpoint, _listening) = silent_endpoint();
let found =
Found { pid: 0, endpoints: vec![endpoint], since: SystemTime::now(), embedded: false, secret: vec![1] };
let began = std::time::Instant::now();
let refused = found.connect().err().expect("no answer came");
assert!(refused.contains("did not answer within"), "{refused}");
assert!(began.elapsed() < ANSWER_WAIT * 5, "{:?}", began.elapsed());
}
#[cfg(unix)]
fn silent_endpoint() -> (String, Box<dyn std::any::Any>) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("silent.sock");
let listener = std::os::unix::net::UnixListener::bind(&path).unwrap();
(format!("unix://{}", path.display()), Box::new((dir, listener)))
}
#[cfg(windows)]
fn silent_endpoint() -> (String, Box<dyn std::any::Any>) {
let name = format!("tinystore-silent-{}", std::process::id());
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
let pipe = runtime.block_on(async {
tokio::net::windows::named_pipe::ServerOptions::new().create(format!(r"\\.\pipe\{name}"))
});
(format!("pipe:{name}"), Box::new((pipe.unwrap(), runtime)))
}
}