rill_view/flow/data/
table.rs1use derive_more::{From, Into};
2use rill_protocol::flow::core::{Flow, TimedEvent};
3use rill_protocol::io::provider::StreamType;
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6use std::convert::{TryFrom, TryInto};
7use std::fmt;
8
9#[derive(
11 Debug, Clone, Copy, Serialize, Deserialize, From, Into, PartialEq, Eq, PartialOrd, Ord, Hash,
12)]
13pub struct Col(pub u64);
14
15impl fmt::Display for Col {
16 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
17 self.0.fmt(f)
18 }
19}
20
21impl TryFrom<usize> for Col {
22 type Error = <u64 as TryFrom<usize>>::Error;
23
24 fn try_from(value: usize) -> Result<Self, Self::Error> {
25 value.try_into().map(Self)
26 }
27}
28
29#[derive(
31 Debug, Clone, Copy, Serialize, Deserialize, From, Into, PartialEq, Eq, PartialOrd, Ord, Hash,
32)]
33pub struct Row(pub u64);
34
35impl fmt::Display for Row {
36 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 self.0.fmt(f)
38 }
39}
40
41impl TryFrom<usize> for Row {
42 type Error = <u64 as TryFrom<usize>>::Error;
43
44 fn try_from(value: usize) -> Result<Self, Self::Error> {
45 value.try_into().map(Self)
46 }
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct TableState {
51 #[serde(with = "vectorize")]
53 pub columns: BTreeMap<Col, ColRecord>,
54
55 #[serde(with = "vectorize")]
57 pub rows: BTreeMap<Row, RowRecord>,
58}
59
60impl TableState {
61 pub fn new(columns: BTreeMap<Col, ColRecord>) -> Self {
62 Self {
63 columns,
64 rows: BTreeMap::new(),
65 }
66 }
67}
68
69impl Flow for TableState {
70 type Action = ();
71 type Event = TableEvent;
72
73 fn stream_type() -> StreamType {
74 StreamType::from("rillrate.data.table.v0")
75 }
76
77 fn apply(&mut self, event: TimedEvent<Self::Event>) {
78 match event.event {
79 TableEvent::AddRow { row } => {
80 let record = RowRecord {
81 cols: BTreeMap::new(),
82 };
83 self.rows.insert(row, record);
84 }
85 TableEvent::DelRow { row } => {
86 self.rows.remove(&row);
87 }
88 TableEvent::SetCell { row, col, value } => {
89 if let Some(record) = self.rows.get_mut(&row) {
90 if self.columns.contains_key(&col) {
91 record.cols.insert(col, value);
92 }
93 }
94 }
95 }
96 }
97}
98
99pub type TableDelta = Vec<TimedEvent<TableEvent>>;
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
102pub enum TableEvent {
103 AddRow { row: Row },
104 DelRow { row: Row },
105 SetCell { row: Row, col: Col, value: String },
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
109pub struct ColRecord {
110 pub title: String,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
114pub struct RowRecord {
115 #[serde(with = "vectorize")]
116 pub cols: BTreeMap<Col, String>,
117}