use crate::client::InnerClient;
use crate::{Client, Connection, Error};
use std::cell::Cell;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Wake, Waker};
use tokio::io::{AsyncRead, AsyncWrite};
thread_local! {
static QUEUING: Cell<u8> = const { Cell::new(IDLE) };
}
const IDLE: u8 = 0;
const SUPPRESS: u8 = 1;
const SUPPRESSED: u8 = 2;
pub(crate) struct Gate {
task: Mutex<Option<Waker>>,
}
impl Gate {
fn task(&self) -> MutexGuard<'_, Option<Waker>> {
self.task.lock().unwrap_or_else(PoisonError::into_inner)
}
fn wake_task(&self) {
let waker = self.task().clone();
if let Some(waker) = waker {
waker.wake();
}
}
}
impl Wake for Gate {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
if QUEUING.get() == IDLE {
self.wake_task();
} else {
QUEUING.set(SUPPRESSED);
}
}
}
pub(crate) trait Drive: Send + Sync {
fn queue_and_drive(&self, queue: &mut dyn FnMut() -> Result<(), Error>) -> Result<(), Error>;
}
#[allow(clippy::large_enum_variant)]
enum State<S, T> {
Running(Connection<S, T>),
Ended(Option<Result<(), Error>>),
}
struct Shared<S, T> {
state: Mutex<State<S, T>>,
gate: Arc<Gate>,
}
impl<S, T> Drive for Shared<S, T>
where
S: AsyncRead + AsyncWrite + Unpin + Send,
T: AsyncRead + AsyncWrite + Unpin + Send,
{
fn queue_and_drive(&self, queue: &mut dyn FnMut() -> Result<(), Error>) -> Result<(), Error> {
QUEUING.set(SUPPRESS);
let queued = queue();
let suppressed = QUEUING.replace(IDLE) == SUPPRESSED;
queued?;
let driven = match self.state.try_lock() {
Ok(mut state) => {
let task = self.gate.task().clone();
match (&mut *state, task) {
(State::Running(connection), Some(task)) => {
let mut cx = Context::from_waker(&task);
if let Poll::Ready(result) = Pin::new(connection).poll(&mut cx) {
*state = State::Ended(Some(result));
drop(state);
task.wake();
}
true
}
_ => false,
}
}
Err(_) => false,
};
if suppressed && !driven {
self.gate.wake_task();
}
Ok(())
}
}
#[must_use = "futures do nothing unless polled"]
pub struct DrivenConnection<S, T> {
shared: Arc<Shared<S, T>>,
}
impl<S, T> Connection<S, T>
where
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
pub fn driven_by(mut self, client: &Client) -> DrivenConnection<S, T> {
let gate = Arc::new(Gate {
task: Mutex::new(None),
});
self.set_request_waker(Waker::from(gate.clone()));
let shared = Arc::new(Shared {
state: Mutex::new(State::Running(self)),
gate,
});
InnerClient::set_driver(client.inner(), shared.clone());
DrivenConnection { shared }
}
}
impl<S, T> Future for DrivenConnection<S, T>
where
S: AsyncRead + AsyncWrite + Unpin,
T: AsyncRead + AsyncWrite + Unpin,
{
type Output = Result<(), Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
let mut state = self
.shared
.state
.lock()
.unwrap_or_else(PoisonError::into_inner);
let connection = match &mut *state {
State::Running(connection) => connection,
State::Ended(result) => return Poll::Ready(result.take().unwrap_or(Ok(()))),
};
{
let mut task = self.shared.gate.task();
if !task.as_ref().is_some_and(|w| w.will_wake(cx.waker())) {
*task = Some(cx.waker().clone());
}
}
let result = std::task::ready!(Pin::new(connection).poll(cx));
*state = State::Ended(None);
Poll::Ready(result)
}
}
impl<S, T> Drop for DrivenConnection<S, T> {
fn drop(&mut self) {
let ended = std::mem::replace(
&mut *self
.shared
.state
.lock()
.unwrap_or_else(PoisonError::into_inner),
State::Ended(None),
);
*self.shared.gate.task() = None;
drop(ended);
}
}