use std::sync::{Arc, Mutex, PoisonError};
use super::FrameContainer;
use crate::{app::Envelope, response::Response};
pub(super) type DeferredBody = Arc<Mutex<Option<Response<Envelope, ()>>>>;
#[derive(Default)]
pub struct ServiceResponse {
inner: FrameContainer<Vec<u8>>,
correlation_id: Option<u64>,
deferred: Option<DeferredBody>,
}
impl Clone for ServiceResponse {
fn clone(&self) -> Self {
Self {
inner: FrameContainer::new(self.inner.frame().clone()),
correlation_id: self.correlation_id,
deferred: self.deferred.clone(),
}
}
}
impl PartialEq for ServiceResponse {
fn eq(&self, other: &Self) -> bool {
self.inner.frame() == other.inner.frame() && self.correlation_id == other.correlation_id
}
}
impl std::fmt::Debug for ServiceResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServiceResponse")
.field("frame", &self.inner.frame())
.field("correlation_id", &self.correlation_id)
.field("has_deferred_body", &self.deferred.is_some())
.finish()
}
}
impl ServiceResponse {
#[must_use]
pub const fn new(frame: Vec<u8>, correlation_id: Option<u64>) -> Self {
Self {
inner: FrameContainer::new(frame),
correlation_id,
deferred: None,
}
}
#[must_use]
pub(crate) const fn with_deferred(
frame: Vec<u8>,
correlation_id: Option<u64>,
deferred: DeferredBody,
) -> Self {
Self {
inner: FrameContainer::new(frame),
correlation_id,
deferred: Some(deferred),
}
}
pub(crate) fn take_deferred(&self) -> Option<Response<Envelope, ()>> {
let slot = self.deferred.as_ref()?;
slot.lock().unwrap_or_else(PoisonError::into_inner).take()
}
#[must_use]
pub const fn frame(&self) -> &[u8] { self.inner.frame().as_slice() }
#[must_use]
pub const fn frame_mut(&mut self) -> &mut Vec<u8> { self.inner.frame_mut() }
#[must_use]
pub const fn correlation_id(&self) -> Option<u64> { self.correlation_id }
#[must_use]
pub const fn set_correlation_id(&mut self, correlation_id: Option<u64>) -> &mut Self {
self.correlation_id = correlation_id;
self
}
#[must_use]
pub fn into_inner(self) -> Vec<u8> { self.inner.into_inner() }
}