use std::io;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use super::{Holder, Serve};
use crate::Store;
use crate::pipe::{Connect, Pipe};
use crate::store::WeakStore;
pub(crate) const MOST: usize = 4;
const LEAVING: Duration = Duration::from_secs(2);
const HELLO_TIME: Duration = Duration::from_secs(5);
const DRAIN: Duration = Duration::from_secs(10);
const TICK: Duration = Duration::from_millis(20);
#[cfg(windows)]
const ACCEPT_TICK: Duration = Duration::from_millis(100);
const AGAIN: Duration = Duration::from_millis(10);
const READ_ROOM: usize = 64 << 10;
const WRITE_ROOM: usize = 256 << 10;
pub(crate) struct Endpoint {
shared: Arc<Shared>,
accepting: Option<JoinHandle<()>>,
server: PathBuf,
#[cfg(unix)]
socket: PathBuf,
}
#[derive(Default)]
struct Shared {
closing: AtomicBool,
cut: AtomicBool,
held: AtomicUsize,
connections: Mutex<Vec<JoinHandle<()>>>,
}
impl Shared {
fn closing(&self) -> bool {
self.closing.load(Ordering::Acquire)
}
fn cut(&self) -> bool {
self.cut.load(Ordering::Acquire)
}
}
impl Endpoint {
pub(crate) fn start(store: &Store) -> io::Result<Endpoint> {
let server = super::server_dir(store.dir())?;
super::unpublish(&server)?;
let (listener, endpoint) = Listener::bind(store.dir(), &server)?;
let serve = Serve::new(vec![endpoint], Holder::Embedded)?;
let connect = Connect { prove: Some(serve.prove()), ..Connect::default() };
super::publish(&server, &serve)?;
let shared = Arc::new(Shared::default());
#[cfg(unix)]
let socket = listener.path.clone();
let accepting = {
let (shared, store) = (Arc::clone(&shared), store.downgrade());
thread::Builder::new()
.name("tinystore-cli".to_owned())
.spawn(move || accept_all(listener, &store, &connect, &shared))
};
let mut endpoint = Endpoint {
shared,
accepting: None,
server,
#[cfg(unix)]
socket,
};
endpoint.accepting = Some(accepting?);
Ok(endpoint)
}
pub(crate) fn stop(&mut self) {
if self.shared.closing.swap(true, Ordering::AcqRel) {
return;
}
#[cfg(unix)]
let woken = std::os::unix::net::UnixStream::connect(&self.socket).is_ok();
#[cfg(windows)]
let woken = true;
let accepting = self.accepting.take();
if woken {
joined(accepting);
}
let deadline = Instant::now() + LEAVING;
while self.shared.held.load(Ordering::Acquire) > 0 && Instant::now() < deadline {
thread::sleep(TICK);
}
self.shared.cut.store(true, Ordering::Release);
let connections = std::mem::take(&mut *self.shared.connections.lock().unwrap_or_else(PoisonError::into_inner));
for connection in connections {
joined(Some(connection));
}
if let Err(error) = super::unpublish(&self.server) {
tracing::warn!(target: "tinystore", %error, "a store's SERVE for the command line was not removed");
}
#[cfg(unix)]
let _ = std::fs::remove_file(&self.socket);
}
}
impl Drop for Endpoint {
fn drop(&mut self) {
self.stop();
}
}
fn joined(handle: Option<JoinHandle<()>>) {
if let Some(handle) = handle.filter(|handle| handle.thread().id() != thread::current().id()) {
let _ = handle.join();
}
}
fn accept_all(mut listener: Listener, store: &WeakStore, connect: &Connect, shared: &Arc<Shared>) {
loop {
let stream = match listener.accept(&|| shared.closing()) {
Ok(Some(stream)) => stream,
Ok(None) => return,
Err(error) => {
tracing::debug!(target: "tinystore", %error, "a command line client did not connect");
thread::sleep(AGAIN);
continue;
}
};
if shared.closing() {
return;
}
let Some(store) = store.upgrade() else { return };
serve(stream, store, connect, shared);
}
}
fn serve(stream: Stream, store: Store, connect: &Connect, shared: &Arc<Shared>) {
let mut connections = shared.connections.lock().unwrap_or_else(PoisonError::into_inner);
connections.retain(|connection| !connection.is_finished());
let (connect, held) = if shared.held.load(Ordering::Acquire) >= MOST {
let why = format!("the program that holds this store takes {MOST} command line connections at once: try again");
(Connect { turned_away: Some(why), ..connect.clone() }, None)
} else {
shared.held.fetch_add(1, Ordering::AcqRel);
(connect.clone(), Some(Held(Arc::clone(shared))))
};
let shared = Arc::clone(shared);
let started = thread::Builder::new().name("tinystore-cli-read".to_owned()).spawn(move || {
let _held = held;
connected(&stream, &store, connect, &shared);
});
match started {
Ok(connection) => connections.push(connection),
Err(error) => tracing::debug!(target: "tinystore", %error, "a command line client was not served"),
}
}
struct Held(Arc<Shared>);
impl Drop for Held {
fn drop(&mut self) {
self.0.held.fetch_sub(1, Ordering::AcqRel);
}
}
#[derive(Default)]
struct Ending {
done: AtomicBool,
gone: AtomicBool,
}
fn connected(stream: &Arc<StreamEnd>, store: &Store, connect: Connect, shared: &Arc<Shared>) {
let pipe = match Pipe::connect(store, connect) {
Ok(pipe) => Arc::new(pipe),
Err(error) => return tracing::warn!(target: "tinystore", %error, "a command line connection did not open"),
};
let ending = Arc::new(Ending::default());
let writer = {
let (stream, pipe, ending, shared) =
(Arc::clone(stream), Arc::clone(&pipe), Arc::clone(&ending), Arc::clone(shared));
thread::Builder::new()
.name("tinystore-cli-write".to_owned())
.spawn(move || write_frames(&stream, &pipe, &ending, &shared))
};
let Ok(writer) = writer else { return };
read_frames(stream, &pipe, &ending, shared);
pipe.client_closed();
drain(&pipe, &ending, shared);
ending.done.store(true, Ordering::Release);
let _ = writer.join();
stream.close();
}
fn read_frames(stream: &StreamEnd, pipe: &Pipe, ending: &Ending, shared: &Shared) {
let mut buffer = vec![0; READ_ROOM];
let hello_by = Instant::now() + HELLO_TIME;
let mut going_away = false;
loop {
if !going_away && shared.closing() {
going_away = true;
pipe.go_away();
}
let over = || {
pipe.finished()
|| ending.gone.load(Ordering::Acquire)
|| shared.cut()
|| (going_away && pipe.streams() == 0)
|| (!pipe.welcomed() && Instant::now() >= hello_by)
};
if over() {
return;
}
if pipe.full() {
thread::sleep(TICK);
continue;
}
match stream.read(&mut buffer, &|| over() || (!going_away && shared.closing())) {
Ok(Some(0)) | Err(_) => return,
Ok(Some(read)) => pipe.push(&buffer[..read]),
Ok(None) => {}
}
}
}
fn drain(pipe: &Pipe, ending: &Ending, shared: &Shared) {
let deadline = Instant::now() + DRAIN;
while pipe.streams() > 0
&& !pipe.finished()
&& !ending.gone.load(Ordering::Acquire)
&& !shared.cut()
&& Instant::now() < deadline
{
thread::sleep(TICK);
}
}
fn write_frames(stream: &StreamEnd, pipe: &Pipe, ending: &Ending, shared: &Shared) {
let mut room = vec![0; WRITE_ROOM];
'writing: loop {
let last = ending.done.load(Ordering::Acquire) || pipe.finished();
let mut wait = TICK;
loop {
let taken = pipe.recv_into(wait, &mut room);
wait = Duration::ZERO;
if taken > 0 && write_all(stream, &room[..taken], shared).is_err() {
break 'writing;
}
if taken < room.len() {
break;
}
}
if last || shared.cut() {
break;
}
}
ending.gone.store(true, Ordering::Release);
}
fn write_all(stream: &StreamEnd, mut bytes: &[u8], shared: &Shared) -> io::Result<()> {
while !bytes.is_empty() {
match stream.write(bytes, &|| shared.cut())? {
Some(0) => return Err(io::ErrorKind::WriteZero.into()),
Some(written) => bytes = &bytes[written..],
None => return Err(io::Error::other("the store closed")),
}
}
Ok(())
}
type Stream = Arc<StreamEnd>;
#[cfg(unix)]
use unix::{Listener, StreamEnd};
#[cfg(windows)]
use windows::{Listener, StreamEnd};
#[cfg(unix)]
mod unix {
use std::io::{self, Read as _, Write as _};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use super::TICK;
pub(super) struct Listener {
listener: UnixListener,
pub(super) path: PathBuf,
}
impl Listener {
pub(super) fn bind(store: &Path, server: &Path) -> io::Result<(Listener, String)> {
let socket = crate::local::bind_socket(store, server)?;
Ok((Listener { listener: socket.listener, path: socket.path }, socket.endpoint))
}
pub(super) fn accept(&mut self, stop: &dyn Fn() -> bool) -> io::Result<Option<Arc<StreamEnd>>> {
let (stream, _) = self.listener.accept()?;
if stop() {
return Ok(None);
}
stream.set_read_timeout(Some(TICK))?;
stream.set_write_timeout(Some(TICK))?;
Ok(Some(Arc::new(StreamEnd(stream))))
}
}
pub(super) struct StreamEnd(UnixStream);
impl StreamEnd {
pub(super) fn read(&self, into: &mut [u8], stop: &dyn Fn() -> bool) -> io::Result<Option<usize>> {
loop {
match (&self.0).read(into) {
Ok(read) => return Ok(Some(read)),
Err(error) if waited(&error) => {
if stop() {
return Ok(None);
}
}
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
}
}
pub(super) fn write(&self, bytes: &[u8], stop: &dyn Fn() -> bool) -> io::Result<Option<usize>> {
loop {
match (&self.0).write(bytes) {
Ok(written) => return Ok(Some(written)),
Err(error) if waited(&error) => {
if stop() {
return Ok(None);
}
}
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
}
}
pub(super) fn close(&self) {
let _ = self.0.shutdown(std::net::Shutdown::Both);
}
}
fn waited(error: &io::Error) -> bool {
matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut)
}
}
#[cfg(windows)]
mod windows {
use std::io;
use std::path::Path;
use std::sync::Arc;
use super::{ACCEPT_TICK, TICK};
use crate::local::windows::PipeEnd;
pub(super) struct Listener {
name: String,
waiting: Option<PipeEnd>,
}
impl Listener {
pub(super) fn bind(store: &Path, _server: &Path) -> io::Result<(Listener, String)> {
let (name, endpoint) = crate::local::pipe_names(store);
let first = PipeEnd::new(crate::local::pipe_instance(&name, true)?);
Ok((Listener { name, waiting: Some(first) }, endpoint))
}
pub(super) fn accept(&mut self, stop: &dyn Fn() -> bool) -> io::Result<Option<Arc<StreamEnd>>> {
let pipe = match self.waiting.take() {
Some(pipe) => pipe,
None => PipeEnd::new(crate::local::pipe_instance(&self.name, false)?),
};
if !pipe.connect(ACCEPT_TICK, stop)? {
return Ok(None);
}
match crate::local::pipe_instance(&self.name, false) {
Ok(next) => self.waiting = Some(PipeEnd::new(next)),
Err(error) => tracing::debug!(target: "tinystore", %error, "a pipe instance was not made"),
}
Ok(Some(Arc::new(StreamEnd(pipe))))
}
}
pub(super) struct StreamEnd(PipeEnd);
impl StreamEnd {
pub(super) fn read(&self, into: &mut [u8], stop: &dyn Fn() -> bool) -> io::Result<Option<usize>> {
self.0.read(into, TICK, stop)
}
pub(super) fn write(&self, bytes: &[u8], stop: &dyn Fn() -> bool) -> io::Result<Option<usize>> {
self.0.write(bytes, TICK, stop)
}
pub(super) fn close(&self) {}
}
}
#[cfg(all(test, feature = "client"))]
#[path = "endpoint_tests.rs"]
mod tests;