Skip to main content

zero_client/ivm/
change.rs

1//! Nodes and the changes pushed through a pipeline
2//! (`packages/zql/src/ivm/data.ts`, `change.ts`, and `source.ts`).
3
4use super::{NodeStream, Row};
5use std::rc::Rc;
6
7/// A relationship of a node: a stream of its child nodes, made each time it
8/// is read.
9pub type RelationshipStream = Rc<dyn Fn() -> NodeStream>;
10
11/// A row flowing through a pipeline, plus its relationships. Relationships
12/// are generated lazily as they are read.
13#[derive(Clone)]
14pub struct Node {
15    pub row: Row,
16    pub relationships: Relationships,
17}
18
19impl Node {
20    pub fn new(row: Row) -> Self {
21        Node {
22            row,
23            relationships: Relationships::default(),
24        }
25    }
26
27    /// This node with `stream` as its relationship `name`.
28    pub fn with(mut self, name: &str, stream: RelationshipStream) -> Self {
29        self.relationships.set(name, Some(stream));
30        self
31    }
32}
33
34impl std::fmt::Debug for Node {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("Node")
37            .field("row", &self.row)
38            .field("relationships", &self.relationships.names())
39            .finish()
40    }
41}
42
43/// A node's relationships, in insertion order like a JS object's keys. Nodes
44/// carry a handful at most, so lookups are linear.
45#[derive(Clone, Default)]
46pub struct Relationships {
47    entries: Vec<(String, RelationshipStream)>,
48}
49
50impl Relationships {
51    pub fn is_empty(&self) -> bool {
52        self.entries.is_empty()
53    }
54
55    pub fn len(&self) -> usize {
56        self.entries.len()
57    }
58
59    pub fn names(&self) -> Vec<&str> {
60        self.entries.iter().map(|(n, _)| n.as_str()).collect()
61    }
62
63    pub fn get(&self, name: &str) -> Option<&RelationshipStream> {
64        self.entries.iter().find(|(n, _)| n == name).map(|(_, s)| s)
65    }
66
67    /// Sets, replaces (keeping its position), or with `None` removes the
68    /// relationship `name`.
69    pub fn set(&mut self, name: &str, stream: Option<RelationshipStream>) {
70        let i = self.entries.iter().position(|(n, _)| n == name);
71        match (i, stream) {
72            (Some(i), Some(s)) => self.entries[i].1 = s,
73            (Some(i), None) => {
74                self.entries.remove(i);
75            }
76            (None, Some(s)) => self.entries.push((name.to_owned(), s)),
77            (None, None) => {}
78        }
79    }
80
81    /// `{...self, ...other}`: `other` wins, keys keep their first position.
82    pub fn merging(&self, other: &Relationships) -> Relationships {
83        let mut result = self.clone();
84        for (name, stream) in &other.entries {
85            result.set(name, Some(stream.clone()));
86        }
87        result
88    }
89
90    pub fn iter(&self) -> impl Iterator<Item = (&str, &RelationshipStream)> {
91        self.entries.iter().map(|(n, s)| (n.as_str(), s))
92    }
93}
94
95/// The kinds of change (`change-type-enum.ts`).
96#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
97pub enum ChangeType {
98    Add = 0,
99    Remove = 1,
100    Edit = 2,
101    Child = 3,
102}
103
104/// A change to a child relationship of a node.
105#[derive(Clone, Debug)]
106pub struct ChildChange {
107    pub relationship_name: String,
108    pub change: Change,
109}
110
111/// A change pushed through a pipeline (`change.ts`).
112#[derive(Clone, Debug)]
113pub enum Change {
114    Add(Node),
115    Remove(Node),
116    Child(Node, Box<ChildChange>),
117    Edit { node: Node, old_node: Node },
118}
119
120impl Change {
121    pub fn change_type(&self) -> ChangeType {
122        match self {
123            Change::Add(_) => ChangeType::Add,
124            Change::Remove(_) => ChangeType::Remove,
125            Change::Child(..) => ChangeType::Child,
126            Change::Edit { .. } => ChangeType::Edit,
127        }
128    }
129
130    /// The node, or the new node of an edit.
131    pub fn node(&self) -> &Node {
132        match self {
133            Change::Add(n) | Change::Remove(n) | Change::Child(n, _) => n,
134            Change::Edit { node, .. } => node,
135        }
136    }
137
138    /// A child change of `node`.
139    pub fn child(node: Node, relationship_name: impl Into<String>, change: Change) -> Change {
140        Change::Child(
141            node,
142            Box::new(ChildChange {
143                relationship_name: relationship_name.into(),
144                change,
145            }),
146        )
147    }
148}
149
150/// A change to a source's rows (`source.ts`).
151#[derive(Clone, Debug, PartialEq)]
152pub enum SourceChange {
153    Add(Row),
154    Remove(Row),
155    Edit { row: Row, old_row: Row },
156}
157
158impl SourceChange {
159    pub fn change_type(&self) -> ChangeType {
160        match self {
161            SourceChange::Add(_) => ChangeType::Add,
162            SourceChange::Remove(_) => ChangeType::Remove,
163            SourceChange::Edit { .. } => ChangeType::Edit,
164        }
165    }
166
167    /// The row, or the new row of an edit.
168    pub fn row(&self) -> &Row {
169        match self {
170            SourceChange::Add(r) | SourceChange::Remove(r) => r,
171            SourceChange::Edit { row, .. } => row,
172        }
173    }
174}