use std::fmt;
use std::sync::{Arc, OnceLock};
use serde::de::DeserializeOwned;
use serde_json::value::RawValue;
use crate::broadcast::{BroadcastWire, write_failures};
use crate::client::{
RequestInfo, batch_body, command_bytes, decode_batch, decode_reply, is_error_reply,
};
use crate::error::InvalidRequestError;
use crate::{BroadcastRequest, BroadcastResult, Client, Error, Request};
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct BatchOptions {
pub parallel: bool,
}
impl BatchOptions {
#[must_use]
pub fn parallel(mut self, parallel: bool) -> Self {
self.parallel = parallel;
self
}
}
type Slot<T> = Arc<OnceLock<Result<T, Error>>>;
trait Deliver: Send + Sync {
fn reply(&self, reply: &RawValue) -> Option<Error>;
fn fail(&self, err: &Error);
}
type Decode<T> = Box<dyn Fn(&RawValue) -> Result<T, Error> + Send + Sync>;
struct Delivery<T> {
slot: Slot<T>,
decode: Decode<T>,
}
impl<T: Send + Sync> Deliver for Delivery<T> {
fn reply(&self, reply: &RawValue) -> Option<Error> {
let outcome = (self.decode)(reply);
let err = outcome.as_ref().err().cloned();
let _ = self.slot.set(outcome);
err
}
fn fail(&self, err: &Error) {
let _ = self.slot.set(Err(err.clone()));
}
}
pub struct Batch {
client: Client,
options: BatchOptions,
commands: Vec<Command>,
}
struct Command {
method: &'static str,
encoded: Result<Vec<u8>, InvalidRequestError>,
deliver: Box<dyn Deliver>,
}
impl fmt::Debug for Batch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Batch")
.field("options", &self.options)
.field(
"commands",
&self.commands.iter().map(|c| c.method).collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}
impl Client {
#[must_use]
pub fn new_batch(&self, options: BatchOptions) -> Batch {
Batch {
client: self.clone(),
options,
commands: Vec::new(),
}
}
}
impl Batch {
#[must_use]
pub fn len(&self) -> usize {
self.commands.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.commands.is_empty()
}
#[allow(clippy::needless_pass_by_value)]
pub(crate) fn add<R: Request, T: DeserializeOwned + Default + Send + Sync + 'static>(
&mut self,
request: R,
) -> Pending<T> {
let method = R::METHOD;
self.push(
&request,
Box::new(move |raw| decode_reply::<T>(raw, method)),
)
}
fn push<R: Request, T: Send + Sync + 'static>(
&mut self,
request: &R,
decode: Decode<T>,
) -> Pending<T> {
let encoded = match request.validate() {
Err(Error::InvalidRequest(e)) => Err(e),
Err(e) => Err(InvalidRequestError::new(R::METHOD, e.to_string())),
Ok(()) => serde_json::to_vec(request)
.map(|r| command_bytes(R::METHOD, &r))
.map_err(|e| {
InvalidRequestError::new(R::METHOD, format!("cannot be encoded: {e}"))
}),
};
let slot = Slot::default();
let deliver = Box::new(Delivery {
slot: Arc::clone(&slot),
decode,
});
self.commands.push(Command {
method: R::METHOD,
encoded,
deliver,
});
Pending {
source: Source::Batch(slot),
}
}
#[allow(clippy::needless_pass_by_value)] pub fn broadcast(&mut self, request: BroadcastRequest) -> Pending<BroadcastResult> {
let channels = request.channels.clone();
let key = request.idempotency_key.clone();
self.push(
&request,
Box::new(move |raw| {
decode_reply::<BroadcastWire>(raw, "broadcast")
.and_then(|w| w.into_result(&channels, &key))
}),
)
}
pub async fn send(self) -> Result<BatchResult, Error> {
let total = self.commands.len();
match self.send_replies().await {
Ok((commands, replies)) => {
let mut failed = Vec::new();
for (i, (c, raw)) in commands.iter().zip(&replies).enumerate() {
if let Some(error) = c.deliver.reply(raw) {
failed.push(FailedCommand {
index: i,
method: c.method,
error,
});
}
}
let result = BatchResult {
replied: true,
failed,
};
if result.failed.is_empty() {
Ok(result)
} else {
Err(Error::BatchFailedCommands(Box::new(
BatchFailedCommandsError::new(result, total),
)))
}
}
Err((commands, e)) => {
for c in &commands {
c.deliver.fail(&e);
}
Err(e)
}
}
}
#[allow(clippy::type_complexity)]
async fn send_replies(
self,
) -> Result<(Vec<Command>, Vec<Box<RawValue>>), (Vec<Command>, Error)> {
let Batch {
client,
options,
commands,
} = self;
let _call = match client.shared.enter() {
Ok(c) => c,
Err(e) => return Err((commands, e)),
};
if commands.is_empty() {
return Ok((commands, Vec::new()));
}
let mut encoded = Vec::with_capacity(commands.len());
for (i, c) in commands.iter().enumerate() {
match &c.encoded {
Ok(e) => encoded.push(e.as_slice()),
Err(e) => {
let e = Error::InvalidRequest(e.clone().in_command(i));
return Err((commands, e));
}
}
}
let body = batch_body(encoded, options.parallel);
let engine = match client.engine() {
Ok(e) => e,
Err(e) => return Err((commands, e)),
};
let deadline = client.deadline();
if tokio::time::Instant::now() >= deadline {
let e = Error::Timeout(crate::error::TimeoutError {
method: Some("batch"),
unsent: true,
});
return Err((commands, e));
}
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, commands.len()));
client.shared.report(&RequestInfo {
method: "batch",
commands: commands.len(),
failed: replies
.as_ref()
.map_or(0, |r| r.iter().filter(|r| is_error_reply(r)).count()),
auto_batch: false,
duration: start.elapsed(),
status,
error: replies.as_ref().err(),
});
match replies {
Ok(r) => Ok((commands, r)),
Err(e) => Err((commands, e)),
}
}
}
pub struct Pending<T> {
source: Source<T>,
}
enum Source<T> {
Batch(Slot<T>),
Fixed(Result<T, Error>),
}
impl<T> fmt::Debug for Pending<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let state = match &self.source {
Source::Batch(slot) => match slot.get() {
None => "not sent",
Some(Ok(_)) => "succeeded",
Some(Err(_)) => "failed",
},
Source::Fixed(Ok(_)) => "succeeded",
Source::Fixed(Err(_)) => "failed",
};
f.debug_struct("Pending").field("state", &state).finish()
}
}
impl<T: Clone> Pending<T> {
#[must_use]
pub fn new(outcome: Result<T, Error>) -> Self {
Self {
source: Source::Fixed(outcome),
}
}
pub fn result(&self) -> Result<T, Error> {
match &self.source {
Source::Fixed(r) => r.clone(),
Source::Batch(slot) => slot.get().cloned().unwrap_or(Err(Error::BatchNotSent)),
}
}
}
#[derive(Debug, Clone, Default, serde::Serialize)]
#[non_exhaustive]
pub struct BatchResult {
pub replied: bool,
pub failed: Vec<FailedCommand>,
}
impl BatchResult {
#[must_use]
pub fn new(replied: bool, failed: Vec<FailedCommand>) -> Self {
Self { replied, failed }
}
}
#[derive(Debug, Clone, serde::Serialize)]
#[non_exhaustive]
pub struct FailedCommand {
pub index: usize,
pub method: &'static str,
pub error: Error,
}
impl FailedCommand {
#[must_use]
pub fn new(index: usize, method: &'static str, error: Error) -> Self {
Self {
index,
method,
error,
}
}
}
#[derive(Debug, Clone)]
pub struct BatchFailedCommandsError {
result: BatchResult,
total: usize,
}
impl BatchFailedCommandsError {
#[must_use]
pub fn new(result: BatchResult, total: usize) -> Self {
Self { result, total }
}
#[must_use]
pub fn result(&self) -> &BatchResult {
&self.result
}
#[must_use]
pub fn failed(&self) -> &[FailedCommand] {
&self.result.failed
}
#[must_use]
pub fn total(&self) -> usize {
self.total
}
}
impl fmt::Display for BatchFailedCommandsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let items = self.failed().iter().map(|c| {
let msg = c.error.to_string();
let msg = msg
.strip_prefix(&format!("{}: ", c.method))
.map_or(msg.clone(), str::to_owned);
(format_args!("#{} {}", c.index, c.method).to_string(), msg)
});
write_failures(
f,
"batch",
"commands",
"succeeded",
self.failed().len(),
self.total,
items,
)
}
}
impl std::error::Error for BatchFailedCommandsError {}