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;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
Remote,
Local,
Snapshot,
Rollback,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Change {
Upsert { table: String, id: String, fields: JsonMap, deleted: bool },
Delete { table: String, id: String },
Restore { table: String, id: String },
Purge { table: String, id: String },
File { file: FileState },
Schema { table: String, schema: Option<TableSchema> },
}
impl Change {
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,
}
}
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,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChangeBatch {
pub space_id: String,
pub origin: Origin,
pub changes: Vec<Change>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub complete: bool,
}
pub trait DataStore: Send + Sync {
fn apply(&self, batch: &ChangeBatch) -> Result<()>;
}
impl<T: DataStore + ?Sized> DataStore for Arc<T> {
fn apply(&self, batch: &ChangeBatch) -> Result<()> {
(**self).apply(batch)
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct RowClocks {
pub fields: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deleted: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trashed: Option<bool>,
}
impl RowClocks {
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)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Upload {
pub sha256: String,
pub size_bytes: u64,
pub mime_type: String,
pub done: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PendingMutation {
pub mutation: Mutation,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub upload: Option<Upload>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub held: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub batch: Option<String>,
}
impl PendingMutation {
pub fn new(mutation: Mutation) -> PendingMutation {
PendingMutation { mutation, upload: None, held: None, batch: None }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SpaceState {
pub cursor: i64,
pub schemas: BTreeMap<String, TableSchema>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RowRef {
pub table: String,
pub id: String,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct StateWrite {
pub clocks: Vec<(RowRef, RowClocks)>,
pub purge: Vec<RowRef>,
pub outbox_add: Vec<PendingMutation>,
pub outbox_remove: Vec<String>,
pub outbox_update: Vec<PendingMutation>,
pub cursor: Option<i64>,
pub schemas: Option<BTreeMap<String, TableSchema>>,
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()
}
}
pub trait SyncStore: Send + Sync {
fn load(&self, space_id: &str) -> Result<SpaceState>;
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 outbox(&self, space_id: &str, limit: usize) -> Result<Vec<PendingMutation>>;
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<()>;
fn forget_space(&self, space_id: &str) -> Result<()>;
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"))
}
fn queued(&self, space_id: &str, limit: usize) -> Result<Vec<Mutation>> {
let _ = (space_id, limit);
Ok(Vec::new())
}
fn queue_remove(&self, space_id: &str, mutation_ids: &[String]) -> Result<()> {
let _ = (space_id, mutation_ids);
Ok(())
}
fn transactional(&self) -> Option<&dyn TransactionalStore> {
None
}
}
pub trait TransactionalStore: Send + Sync {
fn transaction(&self, f: &mut dyn FnMut(&dyn TxView) -> Result<()>) -> Result<()>;
}
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<()>;
}