use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tinystore::ErrorKind;
use tinystore::client::Client;
use crate::asked::{Refused, failed};
use crate::client::{self, Connection, Stream};
const START_WAIT: Duration = Duration::from_secs(15);
const RIVAL_WAIT: Duration = Duration::from_secs(2);
const HELD: i32 = 3;
const LOOK: Duration = Duration::from_millis(20);
const ATTEMPTS: usize = 3;
const SAID: usize = 8 << 10;
pub(crate) fn write<T: Send + 'static>(
dir: &Path,
command: &'static str,
call: impl Fn(&mut Client<Box<dyn Stream>>) -> tinystore::Result<T> + Send + Sync + 'static,
) -> Result<T, Refused> {
Writer::new(dir, command).write(call)
}
pub(crate) fn write_by_id<T: Send + 'static>(
dir: &Path,
command: &'static str,
id: Option<&str>,
call: impl Fn(&mut Client<Box<dyn Stream>>) -> tinystore::Result<T> + Send + Sync + 'static,
) -> Result<T, Refused> {
Writer { again: Again::of_id(id), ..Writer::new(dir, command) }.write(call)
}
pub(crate) fn write_once<T: Send + 'static>(
dir: &Path,
command: &'static str,
call: impl FnOnce(&mut Client<Box<dyn Stream>>) -> tinystore::Result<T> + Send + 'static,
) -> Result<T, Refused> {
let (_, answer) = connected(dir, command)?.call(command, call);
answer.map_err(failed)
}
pub(crate) struct Writer {
dir: PathBuf,
command: &'static str,
connection: Option<Connection>,
again: Again,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Again {
Harmless,
Twice,
}
impl Again {
fn of_id(id: Option<&str>) -> Again {
if id.is_some() { Again::Harmless } else { Again::Twice }
}
fn after(self, kind: ErrorKind) -> bool {
match kind {
ErrorKind::Unavailable => true,
ErrorKind::OutcomeUnknown => self == Again::Harmless,
_ => false,
}
}
}
impl Writer {
pub(crate) fn new(dir: &Path, command: &'static str) -> Writer {
Writer { dir: dir.to_owned(), command, connection: None, again: Again::Harmless }
}
pub(crate) fn reach(&mut self) -> Result<(), Refused> {
if self.connection.is_none() {
self.connection = Some(connected(&self.dir, self.command)?);
}
Ok(())
}
pub(crate) fn write<T: Send + 'static>(
&mut self,
call: impl Fn(&mut Client<Box<dyn Stream>>) -> tinystore::Result<T> + Send + Sync + 'static,
) -> Result<T, Refused> {
self.try_write(call)?.map_err(failed)
}
pub(crate) fn try_write<T: Send + 'static>(
&mut self,
call: impl Fn(&mut Client<Box<dyn Stream>>) -> tinystore::Result<T> + Send + Sync + 'static,
) -> Result<tinystore::Result<T>, Refused> {
let call = Arc::new(call);
let mut attempt = 0;
loop {
attempt += 1;
let connection = match self.connection.take() {
Some(connection) => connection,
None => connected(&self.dir, self.command)?,
};
let sent = Arc::clone(&call);
let (kept, answer) = connection.call(self.command, move |client| sent(client));
self.connection = kept;
match answer {
Err(error) if self.again.after(error.kind()) && attempt < ATTEMPTS => continue,
answer => return Ok(answer),
}
}
}
}
pub(crate) fn stream<T>(
dir: &Path,
command: &str,
call: impl FnOnce(&mut Client<Box<dyn Stream>>) -> tinystore::Result<T>,
) -> Result<T, Refused> {
connected(dir, command)?.run(call).map_err(failed)
}
pub(crate) fn store_at(dir: &Path) -> Result<(), Refused> {
if dir.join("LOCK").is_file() {
return Ok(());
}
let shown = dir.display();
Err(failed(format!("{shown}: no store is there; a program, or `tinystore serve {shown}`, makes one")))
}
pub(crate) fn connected(dir: &Path, command: &str) -> Result<Connection, Refused> {
store_at(dir)?;
if let Some(connection) = served(dir)? {
return Ok(connection);
}
started(dir, command)
}
fn served(dir: &Path) -> Result<Option<Connection>, Refused> {
let Some(found) = client::found(dir).map_err(failed)? else {
return Ok(None);
};
Ok(found.connect().ok())
}
fn started(dir: &Path, command: &str) -> Result<Connection, Refused> {
let mut sidecar = Sidecar::start(&std::path::absolute(dir).unwrap_or_else(|_| dir.to_owned()))?;
let began = Instant::now();
let mut stopped_at = None;
loop {
if let Some(found) = client::found(dir).map_err(failed)?
&& let Ok(connection) = found.connect()
{
if found.pid == u64::from(sidecar.child.id()) {
crate::asked::say(
command,
format!("started a server for {}; it stops 30 s after the last client", dir.display()),
);
}
return Ok(connection);
}
if stopped_at.is_none()
&& let Ok(Some(exit)) = sidecar.child.try_wait()
{
stopped_at = Some((Instant::now(), exit.code()));
}
match stopped_at {
Some((at, code)) if at.elapsed() > RIVAL_WAIT => return Err(sidecar.refusal(dir, code)),
None if began.elapsed() > START_WAIT => {
return Err(failed(format!(
"no server listened for {} within {} s",
dir.display(),
START_WAIT.as_secs()
)));
}
_ => std::thread::sleep(LOOK),
}
}
}
struct Sidecar {
child: Child,
said: Arc<Mutex<String>>,
}
impl Sidecar {
fn start(dir: &Path) -> Result<Sidecar, Refused> {
let binary = std::env::current_exe().map_err(|error| failed(format!("this command's own path: {error}")))?;
let log: PathBuf = dir.join("server").join("serve.log");
let mut serve = Command::new(binary);
serve
.arg("serve")
.arg("--dir")
.arg(dir)
.args(["--local", "--quiet", "--log-file"])
.arg(&log)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped());
detached(&mut serve);
#[cfg(windows)]
crate::own_handles::keep();
let mut child = serve.spawn().map_err(|error| failed(format!("a server for {}: {error}", dir.display())))?;
let said = Arc::new(Mutex::new(String::new()));
if let Some(mut stderr) = child.stderr.take() {
let kept = Arc::clone(&said);
std::thread::spawn(move || {
let mut read = [0; 4096];
while let Ok(count @ 1..) = stderr.read(&mut read) {
let mut said = kept.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if said.len() < SAID {
said.push_str(&String::from_utf8_lossy(&read[..count]));
}
}
});
}
Ok(Sidecar { child, said })
}
fn refusal(&self, dir: &Path, code: Option<i32>) -> Refused {
if code == Some(HELD) {
return failed(format!(
"a program holds {} inside its own process, so no other process can write to it\n open it in that \
program with a sidecar, or let `tinystore serve {}` hold it",
dir.display(),
dir.display()
));
}
let said = self.said.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).trim().to_owned();
let why = said.lines().last().unwrap_or("it said nothing");
failed(format!("the server started for {} stopped: {why}", dir.display()))
}
}
#[cfg(unix)]
fn detached(serve: &mut Command) {
use std::os::unix::process::CommandExt as _;
serve.process_group(0);
}
#[cfg(windows)]
fn detached(serve: &mut Command) {
use std::os::windows::process::CommandExt as _;
const DETACHED_PROCESS: u32 = 0x0000_0008;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
serve.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_write_whose_outcome_is_unknown_goes_again_only_when_a_second_send_writes_nothing_more() {
let unnamed = Again::of_id(None);
assert_eq!(unnamed, Again::Twice, "a job or an event without an id");
assert!(!unnamed.after(ErrorKind::OutcomeUnknown), "its caller hears the outcome is unknown");
assert!(unnamed.after(ErrorKind::Unavailable), "the server never ran it");
let named = Again::of_id(Some("welcome-42"));
assert!(named.after(ErrorKind::OutcomeUnknown), "a second add finds the id taken and adds nothing");
assert!(!named.after(ErrorKind::Conflict) && !unnamed.after(ErrorKind::Invalid), "a refusal is the answer");
assert!(Writer::new(Path::new("data"), "kv set").again.after(ErrorKind::OutcomeUnknown), "a key set");
}
}