summaryrefslogtreecommitdiff
path: root/crdt/src/lib.rs
blob: df8425deede20c8ec8974de37aeda90fc6db51ab (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
mod vector_clock;

use uuid::Uuid;

use crate::vector_clock::VectorClock;

#[derive(Default)]
pub struct Doc {
    ops: Vec<Op>,
}

impl Doc {
    pub fn append_op(&mut self, actor_id: &Uuid, payload: OpPayload) {
        // Increment the last clock for the provided actor
        let clock = self
            .ops
            .last()
            .map(|Op { clock, .. }| clock.inc(actor_id))
            // For an empty document, initialize a new clock
            .unwrap_or_else(|| VectorClock::default().inc(actor_id));

        self.ops.push(Op {
            id: Uuid::now_v7(),
            clock,
            payload,
        });
    }

    pub fn realize(&self) -> RealizedDoc<'_> {
        let mut realized = RealizedDoc::default();

        for op in &self.ops {
            op.apply(&mut realized);
        }

        realized
    }
}

pub struct Op {
    id: Uuid,
    payload: OpPayload,
    clock: VectorClock,
}

impl Op {
    fn apply<'a>(&'a self, realized: &mut RealizedDoc<'a>) {
        match &self.payload {
            OpPayload::CreateGrid {
                id: grid_id,
                rows,
                base_cells_per_row,
            } => {
                let rows = (0..*rows)
                    .map(|row_idx| {
                        let cells = (0..*base_cells_per_row)
                            .map(|cell_idx| Cell {
                                id: DerivedId::new(grid_id, "cell", cell_idx),
                            })
                            .collect();

                        Row {
                            id: DerivedId::new(grid_id, "row", row_idx),
                            cells,
                        }
                    })
                    .collect();

                realized.grids.push(Grid { id: grid_id, rows });
            }
        }
    }
}

pub enum OpPayload {
    CreateGrid {
        id: Uuid,
        rows: usize,
        base_cells_per_row: usize,
    },
}

#[derive(Default)]
pub struct RealizedDoc<'a> {
    grids: Vec<Grid<'a>>,
}

pub struct Grid<'a> {
    id: &'a Uuid,
    rows: Vec<Row<'a>>,
}

pub struct Row<'a> {
    id: DerivedId<'a>,
    cells: Vec<Cell<'a>>,
}

pub struct Cell<'a> {
    id: DerivedId<'a>,
}

pub struct DerivedId<'a> {
    id: &'a Uuid,
    tag: &'static str,
    index: usize,
}

impl<'a> DerivedId<'a> {
    pub fn new(id: &'a Uuid, tag: &'static str, index: usize) -> Self {
        Self { id, tag, index }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn realize_doc() {
        let actor_id = Uuid::now_v7();

        let mut doc = Doc::default();

        doc.append_op(
            &actor_id,
            OpPayload::CreateGrid {
                id: Uuid::now_v7(),
                rows: 4,
                base_cells_per_row: 16,
            },
        );

        let realized = doc.realize();

        assert!(realized.grids.len() == 1);

        let grid = realized.grids.first().unwrap();

        assert!(grid.rows.len() == 4);

        let row = grid.rows.first().unwrap();

        assert!(row.cells.len() == 16);
    }
}