use crate::session::SessionError;
use crate::{
DocumentAddress, DocumentCreate, DocumentFork, DocumentHistory, DocumentId, DocumentScope, JsonObject,
StoredDocument,
};
use chord_delta::Op;
use serde_json::{Value, json};
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DocSemantics {
Session,
Conversation {
history: DocumentHistory,
fork: DocumentFork,
},
Task,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CheckpointInfo {
pub deltas_since_base: usize,
}
type Initial = dyn Fn(&Value) -> Value + Send + Sync;
type Migrate = dyn Fn(&JsonObject, u64) -> Result<Value, String> + Send + Sync;
type CheckpointWhen = dyn Fn(&DocDefinition, &Value, &[Op], CheckpointInfo) -> Result<bool, String> + Send + Sync;
pub struct DocDefinition {
pub kind: String,
pub version: u64,
pub semantics: DocSemantics,
pub initial: Box<Initial>,
pub migrate: Option<Box<Migrate>>,
pub checkpoint_when: Option<Box<CheckpointWhen>>,
}
impl fmt::Debug for DocDefinition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DocDefinition")
.field("kind", &self.kind)
.field("version", &self.version)
.field("semantics", &self.semantics)
.finish_non_exhaustive()
}
}
impl DocDefinition {
pub fn new(
kind: &str,
version: u64,
semantics: DocSemantics,
initial: impl Fn(&Value) -> Value + Send + Sync + 'static,
) -> DocDefinition {
DocDefinition {
kind: kind.to_owned(),
version,
semantics,
initial: Box::new(initial),
migrate: None,
checkpoint_when: None,
}
}
pub fn migrate(
mut self,
migrate: impl Fn(&JsonObject, u64) -> Result<Value, String> + Send + Sync + 'static,
) -> Self {
self.migrate = Some(Box::new(migrate));
self
}
pub fn checkpoint_when(
mut self,
predicate: impl Fn(&DocDefinition, &Value, &[Op], CheckpointInfo) -> Result<bool, String> + Send + Sync + 'static,
) -> Self {
self.checkpoint_when = Some(Box::new(predicate));
self
}
pub fn define(self) -> Result<Doc, SessionError> {
if self.version < 1 || self.version > crate::MAX_SAFE_ID {
return Err(SessionError::Type(format!(
"Document {} version must be a positive integer",
self.kind
)));
}
Ok(Doc(Arc::new(self)))
}
fn scope_name(&self) -> &'static str {
match self.semantics {
DocSemantics::Session => "session",
DocSemantics::Conversation { .. } => "conversation",
DocSemantics::Task => "task",
}
}
}
#[derive(Clone, Debug)]
pub struct Doc(pub(crate) Arc<DocDefinition>);
impl Doc {
pub fn definition(&self) -> &DocDefinition {
&self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Owner {
Session,
Conversation(crate::ConversationId),
Task(crate::TaskId),
}
pub(crate) struct Resolved {
pub address: DocumentAddress,
pub id: String,
}
pub(crate) fn resolve_address(definition: &DocDefinition, owner: Owner) -> Result<Resolved, SessionError> {
let scope = match (definition.semantics, owner) {
(DocSemantics::Session, Owner::Session) => DocumentScope::Session,
(DocSemantics::Conversation { .. }, Owner::Conversation(conversation_id)) => {
DocumentScope::Conversation { conversation_id }
}
(DocSemantics::Task, Owner::Task(task_id)) => DocumentScope::Task { task_id },
_ => {
return Err(SessionError::Type(format!(
"Document {} requires a {} ID",
definition.kind,
definition.scope_name()
)));
}
};
let address = DocumentAddress {
kind: definition.kind.clone(),
scope,
key: None,
};
let id = address_id(&address);
Ok(Resolved { address, id })
}
pub(crate) fn address_id(address: &DocumentAddress) -> String {
let (scope, owner) = match address.scope {
DocumentScope::Session => ("session", Value::Null),
DocumentScope::Conversation { conversation_id } => ("conversation", json!(conversation_id.0)),
DocumentScope::Task { task_id } => ("task", json!(task_id.0)),
};
json!([address.kind, scope, owner, address.key]).to_string()
}
pub(crate) fn address_of(record: &DocumentCreate) -> DocumentAddress {
DocumentAddress {
kind: record.kind.clone(),
scope: record.scope,
key: record.key.clone(),
}
}
pub(crate) fn document_create(definition: &DocDefinition, address: &DocumentAddress, id: DocumentId) -> DocumentCreate {
let (history, fork) = match definition.semantics {
DocSemantics::Conversation { history, fork } => (Some(history), Some(fork)),
_ => (None, None),
};
DocumentCreate {
id,
kind: address.kind.clone(),
key: address.key.clone(),
scope: address.scope,
history,
fork,
}
}
pub(crate) fn check_record_scope(definition: &DocDefinition, record: &DocumentCreate) -> Result<(), SessionError> {
let matches = match (definition.semantics, record.scope) {
(DocSemantics::Session, DocumentScope::Session) | (DocSemantics::Task, DocumentScope::Task { .. }) => true,
(DocSemantics::Conversation { history, fork }, DocumentScope::Conversation { .. }) => {
record.history == Some(history) && record.fork == Some(fork)
}
_ => false,
};
if matches {
Ok(())
} else {
Err(SessionError::Type(format!(
"Document {} ({}) does not match the supplied definition semantics",
record.id.0, record.kind
)))
}
}
pub(crate) fn check_record_version(
definition: &DocDefinition,
record: &DocumentCreate,
version: u64,
) -> Result<(), SessionError> {
if version > definition.version {
return Err(SessionError::Error(format!(
"Document {} ({}) has newer version {} than {}",
record.id.0, record.kind, version, definition.version
)));
}
if version < definition.version && definition.migrate.is_none() {
return Err(SessionError::Error(format!(
"Document {} ({}) requires migration from version {}",
record.id.0, record.kind, version
)));
}
Ok(())
}
pub(crate) fn materialize_document(definition: &DocDefinition, stored: &StoredDocument) -> Result<Value, SessionError> {
materialize_value(definition, &stored.record.identity, stored.version, &stored.value)
}
pub(crate) fn materialize_value(
definition: &DocDefinition,
record: &DocumentCreate,
version: u64,
value: &JsonObject,
) -> Result<Value, SessionError> {
check_record_scope(definition, record)?;
check_record_version(definition, record, version)?;
if version == definition.version {
return Ok(Value::Object(value.clone()));
}
let migrate = definition.migrate.as_ref().expect("checked by check_record_version");
object(migrate(value, version).map_err(SessionError::Error)?, &definition.kind)
}
pub(crate) fn object(value: Value, kind: &str) -> Result<Value, SessionError> {
if value.is_object() {
Ok(value)
} else {
Err(SessionError::Type(format!(
"Document {kind} value must be a JSON object"
)))
}
}