kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! An in-memory [`SyncStore`], for tests, scripts and apps that resync on start.

use std::collections::{BTreeMap, HashMap};
use std::sync::Mutex;

use super::{PendingMutation, RowClocks, RowRef, SpaceState, StateWrite, SyncStore};
use crate::error::Result;
use crate::protocol::Mutation;

#[derive(Default)]
struct Space {
    state: SpaceState,
    clocks: BTreeMap<RowRef, RowClocks>,
    outbox: Vec<PendingMutation>,
    queue: Vec<Mutation>,
}

/// Keeps every piece of bookkeeping in memory. Nothing survives a restart.
#[derive(Default)]
pub struct MemorySyncStore {
    spaces: Mutex<HashMap<String, Space>>,
    meta: Mutex<HashMap<String, String>>,
}

impl MemorySyncStore {
    pub fn new() -> MemorySyncStore {
        MemorySyncStore::default()
    }
}

impl SyncStore for MemorySyncStore {
    fn load(&self, space_id: &str) -> Result<SpaceState> {
        Ok(self.spaces.lock().unwrap().get(space_id).map(|s| s.state.clone()).unwrap_or_default())
    }

    fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
        let spaces = self.spaces.lock().unwrap();
        let mut out = BTreeMap::new();
        if let Some(s) = spaces.get(space_id) {
            for id in ids {
                if let Some(rc) = s.clocks.get(&RowRef { table: table.into(), id: id.clone() }) {
                    out.insert(id.clone(), rc.clone());
                }
            }
        }
        Ok(out)
    }

    fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>> {
        Ok(self.spaces.lock().unwrap().get(space_id).map(|s| s.clocks.keys().cloned().collect()).unwrap_or_default())
    }

    fn outbox(&self, space_id: &str, limit: usize) -> Result<Vec<PendingMutation>> {
        Ok(self
            .spaces
            .lock()
            .unwrap()
            .get(space_id)
            .map(|s| s.outbox.iter().take(limit).cloned().collect())
            .unwrap_or_default())
    }

    fn commit(&self, space_id: &str, w: &StateWrite) -> Result<()> {
        let mut spaces = self.spaces.lock().unwrap();
        let s = spaces.entry(space_id.to_string()).or_default();
        for (r, rc) in &w.clocks {
            s.clocks.insert(r.clone(), rc.clone());
        }
        for r in &w.purge {
            s.clocks.remove(r);
        }
        if !w.outbox_remove.is_empty() {
            s.outbox.retain(|p| !w.outbox_remove.contains(&p.mutation.mutation_id));
        }
        for u in &w.outbox_update {
            if let Some(p) = s.outbox.iter_mut().find(|p| p.mutation.mutation_id == u.mutation.mutation_id) {
                *p = u.clone();
            }
        }
        for a in &w.outbox_add {
            if !s.outbox.iter().any(|p| p.mutation.mutation_id == a.mutation.mutation_id) {
                s.outbox.push(a.clone());
            }
        }
        if let Some(c) = w.cursor {
            s.state.cursor = c;
        }
        if let Some(sc) = &w.schemas {
            s.state.schemas = sc.clone();
        }
        drop(spaces);
        for (k, v) in &w.meta {
            self.meta_set(k, v)?;
        }
        Ok(())
    }

    fn forget_space(&self, space_id: &str) -> Result<()> {
        self.spaces.lock().unwrap().remove(space_id);
        // The space's queue goes with it.
        Ok(())
    }

    fn queue_add(&self, space_id: &str, entries: &[Mutation]) -> Result<()> {
        let mut spaces = self.spaces.lock().unwrap();
        let s = spaces.entry(space_id.to_string()).or_default();
        for m in entries {
            if !s.queue.iter().any(|q| q.mutation_id == m.mutation_id) {
                s.queue.push(m.clone());
            }
        }
        Ok(())
    }

    fn queued(&self, space_id: &str, limit: usize) -> Result<Vec<Mutation>> {
        let spaces = self.spaces.lock().unwrap();
        Ok(spaces.get(space_id).map(|s| s.queue.iter().take(limit).cloned().collect()).unwrap_or_default())
    }

    fn queue_remove(&self, space_id: &str, mutation_ids: &[String]) -> Result<()> {
        if let Some(s) = self.spaces.lock().unwrap().get_mut(space_id) {
            let ids: std::collections::HashSet<&String> = mutation_ids.iter().collect();
            s.queue.retain(|m| !ids.contains(&m.mutation_id));
        }
        Ok(())
    }

    fn meta_get(&self, key: &str) -> Result<Option<String>> {
        Ok(self.meta.lock().unwrap().get(key).cloned())
    }

    fn meta_set(&self, key: &str, value: &str) -> Result<()> {
        self.meta.lock().unwrap().insert(key.into(), value.into());
        Ok(())
    }
}