use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tinystore::Store;
use tinystore::pipe::{Connect, Pipe};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::{Notify, watch};
use tokio::time::Instant;
const DRAIN: Duration = Duration::from_secs(10);
const HELLO_TIME: Duration = Duration::from_secs(5);
const DRAIN_TICK: Duration = Duration::from_millis(10);
pub(crate) async fn serve<R, W>(reader: R, writer: W, store: &Store, connect: Connect, closing: watch::Receiver<bool>)
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin + Send + 'static,
{
let ready = Arc::new(Notify::new());
let woken = Arc::clone(&ready);
let connect = Connect { wake: Some(Arc::new(move || woken.notify_one())), ..connect };
let pipe = match Pipe::connect(store, connect) {
Ok(pipe) => Arc::new(pipe),
Err(error) => return tracing::warn!(target: "tinystore", %error, "a connection did not open"),
};
let done = Arc::new(AtomicBool::new(false));
let writing = tokio::spawn(write_frames(Arc::clone(&pipe), writer, Arc::clone(&ready), Arc::clone(&done)));
read_frames(reader, &pipe, closing).await;
drain(&pipe).await;
done.store(true, Ordering::Release);
ready.notify_one();
let _ = writing.await;
}
async fn read_frames<R: AsyncRead + Unpin>(mut reader: R, pipe: &Pipe, mut closing: watch::Receiver<bool>) {
let mut buffer = vec![0; 64 << 10];
let hello_by = Instant::now() + HELLO_TIME;
let mut going_away = *closing.borrow();
if going_away {
pipe.go_away();
}
loop {
if pipe.finished() || (going_away && pipe.streams() == 0) {
return;
}
tokio::select! {
read = reader.read(&mut buffer) => match read {
Ok(0) | Err(_) => return,
Ok(read) => pipe.push(&buffer[..read]),
},
changed = closing.changed(), if !going_away => {
going_away = true;
if changed.is_ok() {
pipe.go_away();
}
}
() = tokio::time::sleep(DRAIN_TICK), if going_away => {}
() = tokio::time::sleep_until(hello_by), if !pipe.welcomed() => return,
}
}
}
async fn drain(pipe: &Pipe) {
let deadline = Instant::now() + DRAIN;
while pipe.streams() > 0 && !pipe.finished() && Instant::now() < deadline {
tokio::time::sleep(DRAIN_TICK).await;
}
}
async fn write_frames<W: AsyncWrite + Unpin>(
pipe: Arc<Pipe>,
mut writer: W,
ready: Arc<Notify>,
done: Arc<AtomicBool>,
) {
loop {
ready.notified().await;
let last = done.load(Ordering::Acquire) || pipe.finished();
let owed = pipe.recv(Duration::ZERO);
if !owed.is_empty() && (writer.write_all(&owed).await.is_err() || writer.flush().await.is_err()) {
break;
}
if last {
break;
}
}
let _ = writer.flush().await;
let _ = writer.shutdown().await;
}