use std::fmt;
#[cfg(feature = "client")]
use serde::Deserialize;
use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
#[cfg(feature = "client")]
use crate::error::ApiError;
use crate::{Error, PublishResult};
#[derive(Debug, Clone, Default, Serialize)]
#[non_exhaustive]
pub struct BroadcastResult {
pub channels: Vec<ChannelResult>,
pub idempotency_key: String,
pub attempts: u32,
pub replied: bool,
}
impl BroadcastResult {
#[must_use]
pub fn new(channels: Vec<ChannelResult>) -> Self {
Self {
channels,
idempotency_key: String::new(),
attempts: 1,
replied: true,
}
}
#[must_use]
pub fn failed(&self) -> Vec<&ChannelResult> {
self.channels
.iter()
.filter(|ch| ch.result.is_err())
.collect()
}
pub fn errors(&self) -> impl Iterator<Item = (&str, &Error)> {
self.channels
.iter()
.filter_map(|ch| Some((ch.channel.as_str(), ch.error()?)))
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ChannelResult {
pub channel: String,
pub result: Result<PublishResult, Error>,
pub attempts: u32,
}
impl ChannelResult {
#[must_use]
pub fn new(channel: impl Into<String>, result: Result<PublishResult, Error>) -> Self {
Self {
channel: channel.into(),
result,
attempts: 1,
}
}
#[must_use]
pub fn error(&self) -> Option<&Error> {
self.result.as_ref().err()
}
}
impl Serialize for ChannelResult {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(Some(3))?;
map.serialize_entry("channel", &self.channel)?;
match &self.result {
Ok(r) => map.serialize_entry("result", r)?,
Err(e) => map.serialize_entry("error", e)?,
}
map.serialize_entry("attempts", &self.attempts)?;
map.end()
}
}
#[derive(Debug, Clone)]
pub struct BroadcastFailedChannelsError {
result: BroadcastResult,
}
impl BroadcastFailedChannelsError {
#[must_use]
pub fn new(result: BroadcastResult) -> Self {
Self { result }
}
#[must_use]
pub fn result(&self) -> &BroadcastResult {
&self.result
}
#[must_use]
pub fn into_result(self) -> BroadcastResult {
self.result
}
#[must_use]
pub fn failed(&self) -> Vec<&ChannelResult> {
self.result.failed()
}
pub fn errors(&self) -> impl Iterator<Item = (&str, &Error)> {
self.result.errors()
}
#[must_use]
pub fn total(&self) -> usize {
self.result.channels.len()
}
#[must_use]
pub fn retryable_channels(&self) -> Vec<String> {
self.errors()
.filter(|(_, e)| crate::retryable(e))
.map(|(ch, _)| ch.to_owned())
.collect()
}
}
impl fmt::Display for BroadcastFailedChannelsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let items = self.errors().map(|(ch, e)| (ch, e.to_string()));
write_failures(
f,
"broadcast",
"channels",
"got the publication",
self.errors().count(),
self.total(),
items,
)?;
if !self.retryable_channels().is_empty() {
f.write_str(" (retry only retryable_channels(), with the same idempotency_key)")?;
}
Ok(())
}
}
impl std::error::Error for BroadcastFailedChannelsError {}
const MAX_ERROR_ITEMS: usize = 3;
pub(crate) fn write_failures(
f: &mut fmt::Formatter<'_>,
op: &str,
parts: &str,
rest: &str,
failed: usize,
total: usize,
items: impl Iterator<Item = (impl fmt::Display, String)>,
) -> fmt::Result {
write!(f, "{op}: {failed} of {total} {parts} failed")?;
if failed < total {
write!(f, ", {} {rest}", total - failed)?;
}
for (i, (label, err)) in items.enumerate() {
if i == MAX_ERROR_ITEMS {
write!(f, "; and {} more", failed - i)?;
break;
}
f.write_str(if i == 0 { ": " } else { "; " })?;
write!(f, "{label}: {err}")?;
}
Ok(())
}
#[cfg(feature = "client")]
#[derive(Debug, Default, Deserialize)]
pub(crate) struct BroadcastWire {
#[serde(default, deserialize_with = "crate::wire::nullable")]
responses: Vec<ChannelResponse>,
}
#[cfg(feature = "client")]
#[derive(Debug, Default, Deserialize)]
struct ChannelResponse {
#[serde(default)]
error: Option<ApiErrorWire>,
#[serde(default)]
result: Option<PublishResult>,
}
#[cfg(feature = "client")]
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ApiErrorWire {
#[serde(default)]
pub(crate) code: u32,
#[serde(default, deserialize_with = "crate::wire::nullable")]
pub(crate) message: String,
#[serde(default, deserialize_with = "crate::wire::nullable")]
pub(crate) temporary: bool,
}
#[cfg(feature = "client")]
impl From<ApiErrorWire> for ApiError {
fn from(w: ApiErrorWire) -> Self {
ApiError::new(w.code, w.message).temporary(w.temporary)
}
}
#[cfg(feature = "client")]
impl BroadcastWire {
pub(crate) fn into_result(
self,
channels: &[String],
key: &str,
) -> Result<BroadcastResult, Error> {
if self.responses.len() != channels.len() {
return Err(Error::Decode(crate::error::DecodeError::message(format!(
"got {} replies for {} channels",
self.responses.len(),
channels.len()
))));
}
let mut failed = false;
let channels = self
.responses
.into_iter()
.zip(channels)
.map(|(r, ch)| {
let result = match r.error {
Some(e) => {
failed = true;
Err(Error::Api(e.into()))
}
None => Ok(r.result.unwrap_or_default()),
};
ChannelResult::new(ch.clone(), result)
})
.collect();
let result = BroadcastResult {
channels,
idempotency_key: key.to_owned(),
attempts: 1,
replied: true,
};
if failed {
return Err(Error::BroadcastFailedChannels(Box::new(
BroadcastFailedChannelsError::new(result),
)));
}
Ok(result)
}
}