use std::ops::Deref;
use std::sync::Arc;
use chrono::{DateTime, Utc};
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use uuid::Uuid;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SharedJson(Arc<serde_json::Value>);
impl SharedJson {
#[must_use]
pub fn new(value: serde_json::Value) -> Self {
Self(Arc::new(value))
}
#[must_use]
pub fn as_value(&self) -> &serde_json::Value {
self.0.as_ref()
}
pub fn make_mut(&mut self) -> &mut serde_json::Value {
Arc::make_mut(&mut self.0)
}
#[must_use]
pub fn into_inner(self) -> serde_json::Value {
match Arc::try_unwrap(self.0) {
Ok(value) => value,
Err(value) => value.as_ref().clone(),
}
}
}
impl Deref for SharedJson {
type Target = serde_json::Value;
fn deref(&self) -> &Self::Target {
self.as_value()
}
}
impl AsRef<serde_json::Value> for SharedJson {
fn as_ref(&self) -> &serde_json::Value {
self.as_value()
}
}
impl From<serde_json::Value> for SharedJson {
fn from(value: serde_json::Value) -> Self {
Self::new(value)
}
}
impl From<SharedJson> for serde_json::Value {
fn from(value: SharedJson) -> Self {
value.into_inner()
}
}
impl PartialEq<serde_json::Value> for SharedJson {
fn eq(&self, other: &serde_json::Value) -> bool {
self.as_value() == other
}
}
#[cfg(feature = "serde")]
impl Serialize for SharedJson {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_value().serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for SharedJson {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
serde_json::Value::deserialize(deserializer).map(Self::new)
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FoldContext {
pub as_of: DateTime<Utc>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub correlation_id: Option<Uuid>,
#[cfg_attr(feature = "serde", serde(default))]
pub extra: SharedJson,
}
impl FoldContext {
pub fn new() -> Self {
Self::default()
}
pub fn at(as_of: DateTime<Utc>) -> Self {
Self {
as_of,
..Default::default()
}
}
pub fn with_correlation_id(mut self, id: Uuid) -> Self {
self.correlation_id = Some(id);
self
}
pub fn with_extra(mut self, extra: impl Into<SharedJson>) -> Self {
self.extra = extra.into();
self
}
#[must_use]
pub fn extra(&self) -> &serde_json::Value {
self.extra.as_value()
}
pub fn extra_mut(&mut self) -> &mut serde_json::Value {
self.extra.make_mut()
}
}
#[cfg(test)]
#[path = "context_tests.rs"]
mod tests;