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 storage seams of ADR 0017 ยง2: the app owns values, Kovlet owns clocks.
//!
//! - A [`DataStore`] holds the app's rows. The app implements it (or uses the
//!   built-in [`MemoryStore`] / `SqliteStore::builtin`). It has one method,
//!   `apply`, which writes changes the core has already merged.
//! - A [`SyncStore`] holds Kovlet's bookkeeping: per-field clocks and the
//!   deleted register, the outbox, the cursor and schemas per space, and a few
//!   client-wide values. Kovlet ships the implementations
//!   ([`MemorySyncStore`], `SqliteStore`); apps don't implement it.
//!
//! The core is the only thing that merges: an app never compares HLCs.

use std::collections::BTreeMap;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::error::Result;
use crate::protocol::{FileState, JsonMap, Mutation, TableSchema};

pub mod builtin;
pub mod memory;
#[cfg(feature = "sqlite")]
pub mod sqlite;

pub use builtin::{MemoryStore, ReadStore, Row};
pub use memory::MemorySyncStore;

/// Where a batch comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
    /// Ops from other clients (or this client's own ops replayed in a delta).
    Remote,
    /// This client's own write (write-through), or its replay after a crash.
    Local,
    /// A full catch-up; the last batch has `complete: true`.
    Snapshot,
    /// The server rejected a write; these are the server's values.
    Rollback,
}

/// One change for the app's store. Every change is already merged: apply it as given.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Change {
    /// Write these fields. `fields` is a patch: absent columns stay as they
    /// are, and `null` empties a field. A row seen for the first time arrives
    /// with every field the server has. `deleted` is the row's trash state.
    Upsert { table: String, id: String, fields: JsonMap, deleted: bool },
    /// Move the row to the app's trash; keep its values.
    Delete { table: String, id: String },
    /// Take the row out of the trash.
    Restore { table: String, id: String },
    /// The row no longer exists for this client: drop it.
    Purge { table: String, id: String },
    /// File metadata only; the bytes are fetched on demand.
    File { file: FileState },
    /// A table's schema changed; `None` when the table was dropped.
    Schema { table: String, schema: Option<TableSchema> },
}

impl Change {
    /// The table a row change touches.
    pub fn table(&self) -> Option<&str> {
        match self {
            Change::Upsert { table, .. }
            | Change::Delete { table, .. }
            | Change::Restore { table, .. }
            | Change::Purge { table, .. }
            | Change::Schema { table, .. } => Some(table),
            Change::File { .. } => None,
        }
    }

    /// The id a change touches: the row's id, or the file's id for
    /// [`Change::File`]. `None` for [`Change::Schema`].
    pub fn id(&self) -> Option<&str> {
        match self {
            Change::Upsert { id, .. }
            | Change::Delete { id, .. }
            | Change::Restore { id, .. }
            | Change::Purge { id, .. } => Some(id),
            Change::File { file } => Some(&file.id),
            Change::Schema { .. } => None,
        }
    }
}

/// A batch of changes for one space, applied in order.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChangeBatch {
    pub space_id: String,
    pub origin: Origin,
    pub changes: Vec<Change>,
    /// Snapshot only: the last batch of the snapshot (any purges come before it).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub complete: bool,
}

/// The app's store. The contract (checked by [`crate::testing::check_data_store`]):
///
/// 1. Fields are patches; `null` empties a field.
/// 2. Trashed rows are kept: `delete` marks a row, `restore` unmarks it, and an
///    upsert with `deleted: true` updates a row that stays hidden.
/// 3. `apply` is idempotent: a batch may be delivered again after a crash.
/// 4. Batches arrive in order, one at a time, on a core thread. An error
///    pauses that space's sync and retries later; the cursor does not move.
pub trait DataStore: Send + Sync {
    /// Write these changes, in order, atomically if you can. Must be idempotent.
    fn apply(&self, batch: &ChangeBatch) -> Result<()>;
}

impl<T: DataStore + ?Sized> DataStore for Arc<T> {
    fn apply(&self, batch: &ChangeBatch) -> Result<()> {
        (**self).apply(batch)
    }
}

/// The clocks of one row. `fields["*"]` is a row-level stamp for every field
/// without its own entry.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct RowClocks {
    pub fields: BTreeMap<String, String>,
    /// The deleted register's stamp.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted: Option<String>,
    /// The deleted register's value: whether the row is in the trash.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trashed: Option<bool>,
}

impl RowClocks {
    /// The stamp a field currently carries (its own, else the row stamp `*`).
    pub fn field(&self, f: &str) -> Option<&str> {
        self.fields.get(f).or_else(|| self.fields.get("*")).map(String::as_str)
    }
    pub fn is_trashed(&self) -> bool {
        self.trashed.unwrap_or(false)
    }
}

/// A pending file upload attached to a `file/put`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Upload {
    pub sha256: String,
    pub size_bytes: u64,
    pub mime_type: String,
    /// Whether the bytes are on the server.
    pub done: bool,
}

/// A queued local mutation, durable before the write returns.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PendingMutation {
    pub mutation: Mutation,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upload: Option<Upload>,
    /// Set while the server holds the write back (e.g. `quota_exceeded`): the error code.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub held: Option<String>,
    /// The atomic batch (`Space::transact`) this write belongs to: the batch
    /// is sent, acked, held and rolled back as one unit (ADR 0021 ยง6.2).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub batch: Option<String>,
}

impl PendingMutation {
    /// A plain queued write (no upload, not held, not in a batch).
    pub fn new(mutation: Mutation) -> PendingMutation {
        PendingMutation { mutation, upload: None, held: None, batch: None }
    }
}

/// Everything a SyncStore keeps per space, besides clocks and the outbox.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SpaceState {
    /// The highest seq applied. 0 asks the server for a snapshot.
    pub cursor: i64,
    pub schemas: BTreeMap<String, TableSchema>,
}

/// A `(table, id)` pair.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RowRef {
    pub table: String,
    pub id: String,
}

/// One atomic write to a space's bookkeeping. Every part is optional.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct StateWrite {
    /// Clock upserts: each replaces the row's clocks.
    pub clocks: Vec<(RowRef, RowClocks)>,
    /// Rows whose clocks are dropped.
    pub purge: Vec<RowRef>,
    /// Outbox entries to append, in order.
    pub outbox_add: Vec<PendingMutation>,
    /// Outbox entries to remove, by mutation id.
    pub outbox_remove: Vec<String>,
    /// Outbox entries to replace in place (held, uploaded), by mutation id.
    pub outbox_update: Vec<PendingMutation>,
    pub cursor: Option<i64>,
    pub schemas: Option<BTreeMap<String, TableSchema>>,
    /// Client-wide `meta_*` values written in the same transaction (protocol 2
    /// subscription state, whose resume cursor must move with the data).
    pub meta: Vec<(String, String)>,
}

impl StateWrite {
    pub fn is_empty(&self) -> bool {
        self.clocks.is_empty()
            && self.purge.is_empty()
            && self.outbox_add.is_empty()
            && self.outbox_remove.is_empty()
            && self.outbox_update.is_empty()
            && self.cursor.is_none()
            && self.schemas.is_none()
            && self.meta.is_empty()
    }
}

/// Kovlet's bookkeeping. Every data method is scoped to one space, `commit` is
/// the only write to them, and `meta_*` is client-wide.
pub trait SyncStore: Send + Sync {
    fn load(&self, space_id: &str) -> Result<SpaceState>;
    /// The clocks of these rows; rows without clocks are absent.
    fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>>;
    /// Every row this store holds clocks for (snapshot purges).
    fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>>;
    /// Up to `limit` outbox entries, in enqueue order.
    fn outbox(&self, space_id: &str, limit: usize) -> Result<Vec<PendingMutation>>;
    /// Applies one write atomically.
    fn commit(&self, space_id: &str, write: &StateWrite) -> Result<()>;
    fn meta_get(&self, key: &str) -> Result<Option<String>>;
    fn meta_set(&self, key: &str, value: &str) -> Result<()>;
    /// Drops everything kept for one space: cursor, cached schemas, clocks and
    /// outbox (queued writes are discarded). The next open starts from a
    /// snapshot. Client-wide `meta_*` values and the app's rows stay. Call it
    /// only for a space that isn't open: [`crate::Client::forget_space`]
    /// checks that.
    fn forget_space(&self, space_id: &str) -> Result<()>;

    /// Appends writes queued with [`Space::queue`](crate::Space::queue), in
    /// order, in **one** durable transaction. They wait here until the queue
    /// worker merges them into clocks and the outbox. Entries whose
    /// `mutation_id` is already queued are ignored.
    ///
    /// The default refuses: a SyncStore without a durable queue can't back
    /// `queue()`. Kovlet's own stores implement it.
    fn queue_add(&self, space_id: &str, entries: &[Mutation]) -> Result<()> {
        let _ = (space_id, entries);
        Err(crate::error::Error::config("this SyncStore has no write queue: use space.write(), or a Kovlet SyncStore"))
    }
    /// Up to `limit` queued writes, oldest first.
    fn queued(&self, space_id: &str, limit: usize) -> Result<Vec<Mutation>> {
        let _ = (space_id, limit);
        Ok(Vec::new())
    }
    /// Drops queued writes the worker has merged, by mutation id.
    fn queue_remove(&self, space_id: &str, mutation_ids: &[String]) -> Result<()> {
        let _ = (space_id, mutation_ids);
        Ok(())
    }

    /// A store that shares a transaction with the app's data (SqliteStore):
    /// runs `apply` and `commit` atomically. `None` for plain SyncStores.
    fn transactional(&self) -> Option<&dyn TransactionalStore> {
        None
    }
}

/// Both seams in one object, sharing a transaction (the SQLite store).
/// The core reads clocks, merges and writes inside one transaction.
pub trait TransactionalStore: Send + Sync {
    /// Runs `f` inside one transaction. `f` gets a view that reads clocks and
    /// applies/commits inside that transaction.
    fn transaction(&self, f: &mut dyn FnMut(&dyn TxView) -> Result<()>) -> Result<()>;
}

/// The operations available inside a [`TransactionalStore::transaction`].
pub trait TxView {
    fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>>;
    fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>>;
    fn apply(&self, batch: &ChangeBatch) -> Result<()>;
    fn commit(&self, space_id: &str, write: &StateWrite) -> Result<()>;
    fn meta_set(&self, key: &str, value: &str) -> Result<()>;
}