rill_protocol/flow/
core.rs

1use crate::encoding;
2use crate::io::provider::{PackedAction, PackedEvent, PackedState, ProviderReqId, StreamType};
3use anyhow::Error;
4use serde::{de::DeserializeOwned, Deserialize, Serialize};
5use std::fmt;
6
7// TODO: Move to the separate module
8/// Requirements for a data fraction in a data flow.
9pub trait DataFraction:
10    DeserializeOwned + Serialize + Clone + fmt::Debug + Sync + Send + 'static
11{
12}
13
14impl<T> DataFraction for T where
15    T: DeserializeOwned + Serialize + Clone + fmt::Debug + Sync + Send + 'static
16{
17}
18
19/// Immutable state of a data flow.
20pub trait Flow: DataFraction {
21    /// `ControlEvent` - that send from a client to a server
22    type Action: DataFraction;
23
24    /// `UpdateEvent` - that sent from a server to a client
25    type Event: DataFraction;
26
27    fn stream_type() -> StreamType;
28
29    fn apply(&mut self, event: Self::Event);
30
31    fn pack_state(&self) -> Result<PackedState, Error> {
32        encoding::pack(self)
33    }
34
35    fn unpack_state(data: &PackedState) -> Result<Self, Error> {
36        encoding::unpack(data)
37    }
38
39    fn pack_event(delta: &Self::Event) -> Result<PackedEvent, Error> {
40        encoding::pack(delta)
41    }
42
43    fn unpack_event(data: &PackedEvent) -> Result<Self::Event, Error> {
44        encoding::unpack(data)
45    }
46
47    fn pack_action(action: &Self::Action) -> Result<PackedAction, Error> {
48        encoding::pack(action)
49    }
50
51    fn unpack_action(data: &PackedAction) -> Result<Self::Action, Error> {
52        encoding::unpack(data)
53    }
54}
55
56/// Envelope for incoming actions that contains routing information.
57#[derive(Debug, Clone)]
58pub struct ActionEnvelope<T: Flow> {
59    /// Direction to a client.
60    pub origin: ProviderReqId,
61    /// The reason of sending an envelope.
62    pub activity: Activity,
63    /// An action sent to a clinet.
64    /// It's detached from activity to make it suitable for
65    /// third-party languages.
66    pub action: Option<T::Action>,
67}
68
69/// Variant of activity that send to tracers.
70///
71/// It doesn't include `Action` value to make this type
72/// compatible with languages that have no ADTs.
73#[derive(Debug, Clone)]
74pub enum Activity {
75    /// No one connected client
76    Suspend = 0, // 0b0000
77    /// At least one client connected
78    Awake = 1, // 0b0001
79
80    /// Listener disconnected
81    Disconnected = 2, // 0b0010
82    /// Listener connected
83    Connected = 3, // 0b0011
84
85    /// Forwards an action
86    Action = 4, // 0b010
87}
88
89impl Activity {
90    pub fn is_action(&self) -> bool {
91        matches!(self, Self::Action)
92    }
93}
94
95#[derive(Debug, Clone, Deserialize, Serialize)]
96pub enum FlowMode {
97    Realtime,
98    Throttle { ms: u64 },
99    FlushOnly,
100}
101
102impl Default for FlowMode {
103    fn default() -> Self {
104        Self::Realtime
105    }
106}