scsys_agents/core/states/
state.rs

1/*
2    Appellation: actors <module>
3    Contributors: FL03 <jo3mccain@icloud.com> (https://github.com)
4    Description:
5        ... Summary ...
6*/
7use crate::{messages::Message, states::Stateful};
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use std::fmt::Display;
11
12/// Implement the standard structure of a state
13#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
14pub struct State<T: Display> {
15    pub events: Vec<String>,
16    pub message: Message<T>,
17    pub metadata: Value,
18    pub timestamp: i64,
19}
20
21impl<T: Display> State<T> {
22    pub fn new(events: Vec<String>, message: Message<T>) -> Self {
23        let metadata = Value::default();
24        let timestamp = chrono::Utc::now().timestamp();
25        Self {
26            events,
27            message,
28            metadata,
29            timestamp,
30        }
31    }
32}
33
34impl<T: Clone + Default + Display + Serialize> Stateful for State<T> {
35    type Data = T;
36
37    fn message(&self) -> &Message<Self::Data> {
38        &self.message
39    }
40
41    fn timestamp(&self) -> i64 {
42        self.timestamp
43    }
44}
45
46impl<T: Default + std::fmt::Display> Default for State<T> {
47    fn default() -> Self {
48        Self::new(Default::default(), Default::default())
49    }
50}
51
52impl<T: Display> std::convert::From<T> for State<T> {
53    fn from(data: T) -> Self {
54        Self::new(Default::default(), Message::from(data))
55    }
56}
57
58impl<T: Display + Serialize> std::fmt::Display for State<T> {
59    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
60        write!(
61            f,
62            "{}",
63            serde_json::to_string_pretty(&self).unwrap().to_lowercase()
64        )
65    }
66}