mod last_value;
mod reducer;
pub use last_value::LastValue;
pub use reducer::{Reducer, ReducerFn, ReducerType};
use crate::error::{RegulaError, Result};
use serde::{de::DeserializeOwned, Serialize};
use std::fmt::Debug;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChannelSpec {
LastValue,
Reducer(ReducerType),
Ephemeral,
AnyValue,
}
impl Default for ChannelSpec {
fn default() -> Self {
Self::LastValue
}
}
pub trait Channel: Send + Sync + Debug {
type Value: Clone + Send + Sync + Serialize + DeserializeOwned;
fn update(&mut self, values: Vec<Self::Value>) -> Result<bool>;
fn get(&self) -> Result<Self::Value>;
fn is_set(&self) -> bool;
fn reset(&mut self);
fn spec(&self) -> ChannelSpec;
fn checkpoint(&self) -> Result<Option<serde_json::Value>>;
fn restore(&mut self, value: Option<serde_json::Value>) -> Result<()>;
}
pub type BoxedChannel<V> = Box<dyn Channel<Value = V>>;
#[derive(Debug, Clone)]
pub struct DynChannel {
pub spec: ChannelSpec,
value: Option<serde_json::Value>,
modified: bool,
}
impl DynChannel {
pub fn new(spec: ChannelSpec) -> Self {
Self {
spec,
value: None,
modified: false,
}
}
pub fn with_value<V: Serialize>(spec: ChannelSpec, value: V) -> Result<Self> {
Ok(Self {
spec,
value: Some(serde_json::to_value(value)?),
modified: false,
})
}
pub fn is_set(&self) -> bool {
self.value.is_some()
}
pub fn get<V: DeserializeOwned>(&self) -> Result<V> {
match &self.value {
Some(v) => Ok(serde_json::from_value(v.clone())?),
None => Err(RegulaError::EmptyChannel("unknown".to_string())),
}
}
pub fn set<V: Serialize>(&mut self, value: V) -> Result<()> {
self.value = Some(serde_json::to_value(value)?);
self.modified = true;
Ok(())
}
pub fn update(&mut self, value: serde_json::Value) -> Result<bool> {
match self.spec {
ChannelSpec::LastValue => {
if self.modified {
return Err(RegulaError::ChannelTypeMismatch {
channel: "unknown".to_string(),
expected: "single write".to_string(),
actual: "multiple writes".to_string(),
});
}
self.value = Some(value);
self.modified = true;
Ok(true)
}
ChannelSpec::AnyValue | ChannelSpec::Ephemeral => {
self.value = Some(value);
self.modified = true;
Ok(true)
}
ChannelSpec::Reducer(ref reducer_type) => {
let new_value = match (&self.value, reducer_type) {
(Some(current), ReducerType::Append) => {
let mut arr = current
.as_array()
.cloned()
.unwrap_or_default();
if let Some(new_arr) = value.as_array() {
arr.extend(new_arr.iter().cloned());
} else {
arr.push(value);
}
serde_json::Value::Array(arr)
}
(None, ReducerType::Append) => {
if value.is_array() {
value
} else {
serde_json::Value::Array(vec![value])
}
}
(Some(current), ReducerType::Add) => {
let c = current.as_f64().unwrap_or(0.0);
let v = value.as_f64().unwrap_or(0.0);
serde_json::Value::from(c + v)
}
(None, ReducerType::Add) => value,
(_, ReducerType::Custom(_)) => {
value
}
};
self.value = Some(new_value);
self.modified = true;
Ok(true)
}
}
}
pub fn clear_modified(&mut self) {
self.modified = false;
if self.spec == ChannelSpec::Ephemeral {
self.value = None;
}
}
pub fn raw_value(&self) -> Option<&serde_json::Value> {
self.value.as_ref()
}
pub fn checkpoint(&self) -> Option<serde_json::Value> {
if self.spec == ChannelSpec::Ephemeral {
None
} else {
self.value.clone()
}
}
pub fn restore(&mut self, value: Option<serde_json::Value>) {
self.value = value;
self.modified = false;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_channel_spec_default() {
assert_eq!(ChannelSpec::default(), ChannelSpec::LastValue);
}
#[test]
fn test_dyn_channel_last_value() {
let mut channel = DynChannel::new(ChannelSpec::LastValue);
assert!(!channel.is_set());
channel.update(serde_json::json!("hello")).unwrap();
assert!(channel.is_set());
let value: String = channel.get().unwrap();
assert_eq!(value, "hello");
}
#[test]
fn test_dyn_channel_reducer_append() {
let mut channel = DynChannel::new(ChannelSpec::Reducer(ReducerType::Append));
channel.update(serde_json::json!(["a"])).unwrap();
channel.update(serde_json::json!(["b", "c"])).unwrap();
let value: Vec<String> = channel.get().unwrap();
assert_eq!(value, vec!["a", "b", "c"]);
}
#[test]
fn test_dyn_channel_ephemeral() {
let mut channel = DynChannel::new(ChannelSpec::Ephemeral);
channel.update(serde_json::json!("temp")).unwrap();
assert!(channel.is_set());
channel.clear_modified();
assert!(!channel.is_set()); }
}