fuel_streams_core/stream/
stream_encoding.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::fmt::Debug;

use async_trait::async_trait;
use fuel_data_parser::{DataParseable, DataParser};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamData<T> {
    pub subject: String,
    pub timestamp: String,
    /// The payload published for the subject
    pub payload: T,
}

impl<T> StreamData<T>
where
    T: serde::de::DeserializeOwned + Clone,
{
    pub fn new(subject: &str, payload: T) -> Self {
        let now: chrono::DateTime<chrono::Utc> = chrono::Utc::now();
        // Formatting the datetime as an ISO 8601 string
        let timestamp = now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
        Self {
            subject: subject.to_string(),
            timestamp,
            payload,
        }
    }

    #[cfg(feature = "bench-helpers")]
    pub fn ts_as_millis(&self) -> u128 {
        use chrono::{DateTime, Utc};

        DateTime::parse_from_rfc3339(&self.timestamp)
            .ok()
            .map(|ts| ts.timestamp_millis() as u128)
            .unwrap_or_else(|| Utc::now().timestamp_millis() as u128)
    }
}

#[async_trait]
pub trait StreamEncoder: DataParseable {
    async fn encode(&self, subject: &str) -> Vec<u8> {
        let data = StreamData::new(subject, self.clone());

        Self::data_parser()
            .encode(&data)
            .await
            .expect("Streamable must encode correctly")
    }

    async fn decode(encoded: Vec<u8>) -> Self {
        Self::decode_raw(encoded).await.payload
    }

    async fn decode_raw(encoded: Vec<u8>) -> StreamData<Self> {
        Self::data_parser()
            .decode(&encoded)
            .await
            .expect("Streamable must decode correctly")
    }

    fn data_parser() -> DataParser {
        DataParser::default()
    }
}