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
//! The built-in store, for apps with no database of their own (ADR 0017 ยง2):
//! a [`DataStore`] that the app can also read.

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

use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::{Change, ChangeBatch, DataStore, Origin};
use crate::error::Result;
use crate::protocol::{FileState, JsonMap};

/// A row as the built-in store holds it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Row {
    pub id: String,
    pub fields: JsonMap,
    /// Whether the row is in the trash.
    #[serde(default)]
    pub trashed: bool,
}

impl Row {
    /// The row as one JSON object with `id` merged in (what typed decoders expect).
    pub fn to_object(&self) -> Value {
        let mut m = self.fields.clone();
        m.insert("id".into(), Value::String(self.id.clone()));
        Value::Object(m)
    }
}

/// Reads from a built-in store.
pub trait ReadStore: Send + Sync {
    /// Live (not trashed) rows of a table, ordered by id.
    fn rows(&self, space_id: &str, table: &str) -> Result<Vec<Row>>;
    /// One row, trashed or not.
    fn get(&self, space_id: &str, table: &str, id: &str) -> Result<Option<Row>>;
    /// Live (not trashed) files.
    fn files(&self, space_id: &str) -> Result<Vec<FileState>>;
}

#[derive(Default)]
struct Data {
    rows: HashMap<String, BTreeMap<String, BTreeMap<String, Row>>>, // space โ†’ table โ†’ id โ†’ row
    files: HashMap<String, BTreeMap<String, FileState>>,
    snapshot_files: HashMap<String, HashSet<String>>,
}

/// An in-memory built-in store.
#[derive(Default)]
pub struct MemoryStore {
    data: Mutex<Data>,
}

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

/// Applies one change to a table map; shared by the memory and SQLite built-in stores.
pub(crate) fn apply_row_change(tables: &mut BTreeMap<String, BTreeMap<String, Row>>, c: &Change) {
    match c {
        Change::Upsert { table, id, fields, deleted } => {
            let t = tables.entry(table.clone()).or_default();
            let row =
                t.entry(id.clone()).or_insert_with(|| Row { id: id.clone(), fields: JsonMap::new(), trashed: false });
            for (k, v) in fields {
                if v.is_null() {
                    row.fields.remove(k);
                } else {
                    row.fields.insert(k.clone(), v.clone());
                }
            }
            row.trashed = *deleted;
        }
        Change::Delete { table, id } | Change::Restore { table, id } => {
            if let Some(row) = tables.get_mut(table).and_then(|t| t.get_mut(id)) {
                row.trashed = matches!(c, Change::Delete { .. });
            }
        }
        Change::Purge { table, id } => {
            if let Some(t) = tables.get_mut(table) {
                t.remove(id);
            }
        }
        Change::Schema { table, schema: None } => {
            tables.remove(table);
        }
        Change::Schema { .. } | Change::File { .. } => {}
    }
}

impl DataStore for MemoryStore {
    fn apply(&self, batch: &ChangeBatch) -> Result<()> {
        let mut d = self.data.lock().unwrap();
        for c in &batch.changes {
            if let Change::File { file } = c {
                d.files.entry(batch.space_id.clone()).or_default().insert(file.id.clone(), file.clone());
                continue;
            }
            let tables = d.rows.entry(batch.space_id.clone()).or_default();
            apply_row_change(tables, c);
        }
        if batch.origin == Origin::Snapshot {
            let seen = d.snapshot_files.entry(batch.space_id.clone()).or_default();
            for c in &batch.changes {
                if let Change::File { file } = c {
                    seen.insert(file.id.clone());
                }
            }
            if batch.complete {
                // A complete snapshot lists every file: anything else is gone.
                let seen = d.snapshot_files.remove(&batch.space_id).unwrap_or_default();
                if let Some(files) = d.files.get_mut(&batch.space_id) {
                    files.retain(|id, _| seen.contains(id));
                }
            }
        }
        Ok(())
    }
}

impl ReadStore for MemoryStore {
    fn rows(&self, space_id: &str, table: &str) -> Result<Vec<Row>> {
        let d = self.data.lock().unwrap();
        Ok(d.rows
            .get(space_id)
            .and_then(|t| t.get(table))
            .map(|t| t.values().filter(|r| !r.trashed).cloned().collect())
            .unwrap_or_default())
    }

    fn get(&self, space_id: &str, table: &str, id: &str) -> Result<Option<Row>> {
        let d = self.data.lock().unwrap();
        Ok(d.rows.get(space_id).and_then(|t| t.get(table)).and_then(|t| t.get(id)).cloned())
    }

    fn files(&self, space_id: &str) -> Result<Vec<FileState>> {
        let d = self.data.lock().unwrap();
        Ok(d.files.get(space_id).map(|f| f.values().filter(|f| !f.deleted).cloned().collect()).unwrap_or_default())
    }
}