use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use serde::de::DeserializeOwned;
use serde_json::value::RawValue;
use tokio::runtime::Handle;
use tokio::sync::oneshot;
use tokio::time::Instant;
use crate::client::{
Engine, RequestInfo, batch_body, command_bytes, decode_batch, decode_reply, is_error_reply,
};
use crate::error::TimeoutError;
use crate::{Client, Error};
pub(crate) struct Batcher {
max_in_flight: usize,
max_batch: usize,
handle: Handle,
state: Mutex<State>,
}
#[derive(Default)]
struct State {
in_flight: usize,
queue: VecDeque<Arc<Queued>>,
}
struct Queued {
command: Vec<u8>,
method: &'static str,
deadline: Instant,
taken: AtomicBool,
gone: AtomicBool,
reply: Mutex<Option<oneshot::Sender<Reply>>>,
}
struct Taken {
q: Arc<Queued>,
tx: oneshot::Sender<Reply>,
}
type Reply = Result<Box<RawValue>, Error>;
enum Turn {
Slot,
Queued(Arc<Queued>, oneshot::Receiver<Reply>),
Encode,
}
impl State {
fn drop_gone(&mut self) {
while self
.queue
.front()
.is_some_and(|q| q.gone.load(Ordering::Relaxed))
{
self.queue.pop_front();
}
}
}
impl Batcher {
pub(crate) fn new(max_in_flight: usize, max_batch: usize, handle: Handle) -> Self {
Self {
max_in_flight,
max_batch,
handle,
state: Mutex::new(State::default()),
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) async fn call<T: DeserializeOwned + Default>(
self: Arc<Self>,
client: &Client,
engine: &Arc<Engine>,
method: &'static str,
pro: bool,
body: Vec<u8>,
deadline: Instant,
) -> Result<T, Error> {
let mut command = None;
let (q, mut rx) = loop {
match self.turn(method, &mut command, deadline) {
Turn::Queued(q, rx) => break (q, rx),
Turn::Slot => {
let _slot = Slot {
batcher: Arc::clone(&self),
client: client.clone(),
engine: Arc::clone(engine),
};
return client.send_alone(engine, method, pro, body, deadline).await;
}
Turn::Encode => command = Some(command_bytes(method, &body)),
}
};
drop(body);
let _leave = Leave {
batcher: &self,
q: &q,
};
let reply = match tokio::time::timeout_at(deadline, &mut rx).await {
Ok(Ok(reply)) => reply,
Ok(Err(_)) => Err(Error::Network(crate::error::NetworkError::new(
method,
std::sync::Arc::from(crate::BoxError::from(
"the batch carrying the call was dropped before its reply",
)),
false,
))),
Err(_) => {
let taken = {
let _st = self.lock();
let taken = q.taken.load(Ordering::Relaxed);
if !taken {
q.gone.store(true, Ordering::Relaxed);
}
taken
};
match rx.try_recv() {
Ok(reply) => reply,
Err(_) => Err(Error::Timeout(TimeoutError {
method: Some(method),
unsent: !taken,
})),
}
}
};
decode_reply(&reply?, method)
}
fn turn(&self, method: &'static str, command: &mut Option<Vec<u8>>, deadline: Instant) -> Turn {
let mut st = self.lock();
st.drop_gone();
if st.in_flight < self.max_in_flight && st.queue.is_empty() {
st.in_flight += 1;
return Turn::Slot;
}
let Some(command) = command.take() else {
return Turn::Encode;
};
let (tx, rx) = oneshot::channel();
let q = Arc::new(Queued {
command,
method,
deadline,
taken: AtomicBool::new(false),
gone: AtomicBool::new(false),
reply: Mutex::new(Some(tx)),
});
st.queue.push_back(Arc::clone(&q));
Turn::Queued(q, rx)
}
fn release(self: &Arc<Self>, client: &Client, engine: &Arc<Engine>) {
let items = {
let mut st = self.lock();
st.drop_gone();
if st.queue.is_empty() {
st.in_flight -= 1;
return;
}
let now = Instant::now();
let mut items = Vec::with_capacity(st.queue.len().min(self.max_batch));
while items.len() < self.max_batch {
let Some(q) = st.queue.pop_front() else { break };
if q.deadline <= now {
q.gone.store(true, Ordering::Relaxed);
}
if q.gone.load(Ordering::Relaxed) {
continue;
}
let Some(tx) = q
.reply
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
else {
continue;
};
q.taken.store(true, Ordering::Relaxed);
items.push(Taken { q, tx });
}
items
};
let call = client.shared.add();
let slot = Slot {
batcher: Arc::clone(self),
client: client.clone(),
engine: Arc::clone(engine),
};
self.handle.spawn(async move {
let _call = call;
flush(&slot.client, &slot.engine, items).await;
drop(slot); });
}
}
struct Slot {
batcher: Arc<Batcher>,
client: Client,
engine: Arc<Engine>,
}
impl Drop for Slot {
fn drop(&mut self) {
self.batcher.release(&self.client, &self.engine);
}
}
struct Leave<'a> {
batcher: &'a Batcher,
q: &'a Queued,
}
impl Drop for Leave<'_> {
fn drop(&mut self) {
let _st = self.batcher.lock();
if !self.q.taken.load(Ordering::Relaxed) {
self.q.gone.store(true, Ordering::Relaxed);
}
}
}
async fn flush(client: &Client, engine: &Engine, items: Vec<Taken>) {
if items.is_empty() {
return;
}
let deadline = items.iter().map(|t| t.q.deadline).fold(
crate::client::after(client.shared.request_timeout),
Instant::max,
);
let body = batch_body(items.iter().map(|t| t.q.command.as_slice()), true);
let start = std::time::Instant::now();
let mut status = 0;
let replies = tokio::time::timeout_at(
deadline,
client.post(engine, "batch", false, body, &mut status),
)
.await
.unwrap_or_else(|_| Err(Error::timeout("batch")))
.and_then(|b| decode_batch(&b, items.len()));
let failed = replies
.as_ref()
.map_or(0, |r| r.iter().filter(|r| is_error_reply(r)).count());
client.shared.report(&RequestInfo {
method: "batch",
commands: items.len(),
failed,
auto_batch: true,
duration: start.elapsed(),
status,
error: replies.as_ref().err(),
});
match replies {
Ok(replies) => {
for (t, r) in items.into_iter().zip(replies) {
let _ = t.tx.send(Ok(r));
}
}
Err(e) => {
for t in items {
let e = match &e {
Error::Timeout(_) => Error::timeout(t.q.method),
e => e.clone(),
};
let _ = t.tx.send(Err(e));
}
}
}
}