diff options
Diffstat (limited to 'crdt/src/lib.rs')
| -rw-r--r-- | crdt/src/lib.rs | 58 |
1 files changed, 39 insertions, 19 deletions
diff --git a/crdt/src/lib.rs b/crdt/src/lib.rs index 977763f..3c89ce9 100644 --- a/crdt/src/lib.rs +++ b/crdt/src/lib.rs @@ -1,13 +1,10 @@ -//! This crate defines the distributed state management system for -//! Notive. The state is an operation-based CRDT, which given the same -//! set of operations on any client, will realize the same state. - use thiserror::Error; use uuid::Uuid; +use wasm_bindgen::prelude::*; use crate::{ doc::{ApplyOpError, Doc}, - op::{Op, OpKind}, + op::{CreateGrid, Op, OpKind}, vector_clock::VectorClock, }; @@ -21,18 +18,28 @@ pub enum Error { RealizeError(#[from] ApplyOpError), } -#[derive(Default)] +#[wasm_bindgen] pub struct State { + actor_id: Uuid, ops: Vec<Op>, } impl State { - pub fn append_op(&mut self, actor_id: &Uuid, kind: OpKind) { + pub fn new() -> Self { + let actor_id = Uuid::now_v7(); + + Self { + actor_id, + ops: vec![], + } + } + + pub fn append_op(&mut self, kind: OpKind) { let clock = self .ops .last() - .map(|op| op.clock.inc(actor_id)) - .unwrap_or_else(|| VectorClock::new().inc(actor_id)); + .map(|op| op.clock.inc(&self.actor_id)) + .unwrap_or_else(|| VectorClock::new().inc(&self.actor_id)); self.ops.push(Op { id: Uuid::now_v7(), @@ -52,6 +59,24 @@ impl State { } } +#[wasm_bindgen] +pub fn make_state() -> State { + State::new() +} + +#[wasm_bindgen] +pub fn create_grid(state: &mut State) { + state.append_op(OpKind::CreateGrid(CreateGrid { + rows: 4, + base_cells_per_row: 16 + })); +} + +pub fn realize(state: &State) -> JsValue { + let doc = state.realize().unwrap(); + serde_wasm_bindgen::to_value(&doc).unwrap() +} + #[cfg(test)] mod tests { use crate::op::CreateGrid; @@ -60,17 +85,12 @@ mod tests { #[test] fn test() { - let alice = Uuid::now_v7(); - - let mut state = State::default(); + let mut state = State::new(); - state.append_op( - &alice, - OpKind::CreateGrid(CreateGrid { - rows: 4, - base_cells_per_row: 16, - }), - ); + state.append_op(OpKind::CreateGrid(CreateGrid { + rows: 4, + base_cells_per_row: 16, + })); let doc = state.realize().unwrap(); let grid = doc.grids.first().unwrap(); |
