1use crate::session::SessionError;
8use crate::{
9 DocumentAddress, DocumentCreate, DocumentFork, DocumentHistory, DocumentId, DocumentScope, JsonObject,
10 StoredDocument,
11};
12use chord_delta::Op;
13use serde_json::{Value, json};
14use std::fmt;
15use std::sync::Arc;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum DocSemantics {
20 Session,
21 Conversation {
22 history: DocumentHistory,
23 fork: DocumentFork,
24 },
25 Task,
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct CheckpointInfo {
31 pub deltas_since_base: usize,
33}
34
35type Initial = dyn Fn(&Value) -> Value + Send + Sync;
36type Migrate = dyn Fn(&JsonObject, u64) -> Result<Value, String> + Send + Sync;
37type CheckpointWhen = dyn Fn(&DocDefinition, &Value, &[Op], CheckpointInfo) -> Result<bool, String> + Send + Sync;
38
39pub struct DocDefinition {
43 pub kind: String,
45 pub version: u64,
47 pub semantics: DocSemantics,
48 pub initial: Box<Initial>,
49 pub migrate: Option<Box<Migrate>>,
50 pub checkpoint_when: Option<Box<CheckpointWhen>>,
51}
52
53impl fmt::Debug for DocDefinition {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 f.debug_struct("DocDefinition")
56 .field("kind", &self.kind)
57 .field("version", &self.version)
58 .field("semantics", &self.semantics)
59 .finish_non_exhaustive()
60 }
61}
62
63impl DocDefinition {
64 pub fn new(
65 kind: &str,
66 version: u64,
67 semantics: DocSemantics,
68 initial: impl Fn(&Value) -> Value + Send + Sync + 'static,
69 ) -> DocDefinition {
70 DocDefinition {
71 kind: kind.to_owned(),
72 version,
73 semantics,
74 initial: Box::new(initial),
75 migrate: None,
76 checkpoint_when: None,
77 }
78 }
79
80 pub fn migrate(
81 mut self,
82 migrate: impl Fn(&JsonObject, u64) -> Result<Value, String> + Send + Sync + 'static,
83 ) -> Self {
84 self.migrate = Some(Box::new(migrate));
85 self
86 }
87
88 pub fn checkpoint_when(
89 mut self,
90 predicate: impl Fn(&DocDefinition, &Value, &[Op], CheckpointInfo) -> Result<bool, String> + Send + Sync + 'static,
91 ) -> Self {
92 self.checkpoint_when = Some(Box::new(predicate));
93 self
94 }
95
96 pub fn define(self) -> Result<Doc, SessionError> {
98 if self.version < 1 || self.version > crate::MAX_SAFE_ID {
99 return Err(SessionError::Type(format!(
100 "Document {} version must be a positive integer",
101 self.kind
102 )));
103 }
104 Ok(Doc(Arc::new(self)))
105 }
106
107 fn scope_name(&self) -> &'static str {
108 match self.semantics {
109 DocSemantics::Session => "session",
110 DocSemantics::Conversation { .. } => "conversation",
111 DocSemantics::Task => "task",
112 }
113 }
114}
115
116#[derive(Clone, Debug)]
118pub struct Doc(pub(crate) Arc<DocDefinition>);
119
120impl Doc {
121 pub fn definition(&self) -> &DocDefinition {
122 &self.0
123 }
124}
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub enum Owner {
129 Session,
130 Conversation(crate::ConversationId),
131 Task(crate::TaskId),
132}
133
134pub(crate) struct Resolved {
136 pub address: DocumentAddress,
137 pub id: String,
138}
139
140pub(crate) fn resolve_address(definition: &DocDefinition, owner: Owner) -> Result<Resolved, SessionError> {
141 let scope = match (definition.semantics, owner) {
142 (DocSemantics::Session, Owner::Session) => DocumentScope::Session,
143 (DocSemantics::Conversation { .. }, Owner::Conversation(conversation_id)) => {
144 DocumentScope::Conversation { conversation_id }
145 }
146 (DocSemantics::Task, Owner::Task(task_id)) => DocumentScope::Task { task_id },
147 _ => {
148 return Err(SessionError::Type(format!(
149 "Document {} requires a {} ID",
150 definition.kind,
151 definition.scope_name()
152 )));
153 }
154 };
155 let address = DocumentAddress {
156 kind: definition.kind.clone(),
157 scope,
158 key: None,
159 };
160 let id = address_id(&address);
161 Ok(Resolved { address, id })
162}
163
164pub(crate) fn address_id(address: &DocumentAddress) -> String {
165 let (scope, owner) = match address.scope {
166 DocumentScope::Session => ("session", Value::Null),
167 DocumentScope::Conversation { conversation_id } => ("conversation", json!(conversation_id.0)),
168 DocumentScope::Task { task_id } => ("task", json!(task_id.0)),
169 };
170 json!([address.kind, scope, owner, address.key]).to_string()
171}
172
173pub(crate) fn address_of(record: &DocumentCreate) -> DocumentAddress {
174 DocumentAddress {
175 kind: record.kind.clone(),
176 scope: record.scope,
177 key: record.key.clone(),
178 }
179}
180
181pub(crate) fn document_create(definition: &DocDefinition, address: &DocumentAddress, id: DocumentId) -> DocumentCreate {
182 let (history, fork) = match definition.semantics {
183 DocSemantics::Conversation { history, fork } => (Some(history), Some(fork)),
184 _ => (None, None),
185 };
186 DocumentCreate {
187 id,
188 kind: address.kind.clone(),
189 key: address.key.clone(),
190 scope: address.scope,
191 history,
192 fork,
193 }
194}
195
196pub(crate) fn check_record_scope(definition: &DocDefinition, record: &DocumentCreate) -> Result<(), SessionError> {
198 let matches = match (definition.semantics, record.scope) {
199 (DocSemantics::Session, DocumentScope::Session) | (DocSemantics::Task, DocumentScope::Task { .. }) => true,
200 (DocSemantics::Conversation { history, fork }, DocumentScope::Conversation { .. }) => {
201 record.history == Some(history) && record.fork == Some(fork)
202 }
203 _ => false,
204 };
205 if matches {
206 Ok(())
207 } else {
208 Err(SessionError::Type(format!(
209 "Document {} ({}) does not match the supplied definition semantics",
210 record.id.0, record.kind
211 )))
212 }
213}
214
215pub(crate) fn check_record_version(
217 definition: &DocDefinition,
218 record: &DocumentCreate,
219 version: u64,
220) -> Result<(), SessionError> {
221 if version > definition.version {
222 return Err(SessionError::Error(format!(
223 "Document {} ({}) has newer version {} than {}",
224 record.id.0, record.kind, version, definition.version
225 )));
226 }
227 if version < definition.version && definition.migrate.is_none() {
228 return Err(SessionError::Error(format!(
229 "Document {} ({}) requires migration from version {}",
230 record.id.0, record.kind, version
231 )));
232 }
233 Ok(())
234}
235
236pub(crate) fn materialize_document(definition: &DocDefinition, stored: &StoredDocument) -> Result<Value, SessionError> {
238 materialize_value(definition, &stored.record.identity, stored.version, &stored.value)
239}
240
241pub(crate) fn materialize_value(
243 definition: &DocDefinition,
244 record: &DocumentCreate,
245 version: u64,
246 value: &JsonObject,
247) -> Result<Value, SessionError> {
248 check_record_scope(definition, record)?;
249 check_record_version(definition, record, version)?;
250 if version == definition.version {
251 return Ok(Value::Object(value.clone()));
252 }
253 let migrate = definition.migrate.as_ref().expect("checked by check_record_version");
254 object(migrate(value, version).map_err(SessionError::Error)?, &definition.kind)
255}
256
257pub(crate) fn object(value: Value, kind: &str) -> Result<Value, SessionError> {
259 if value.is_object() {
260 Ok(value)
261 } else {
262 Err(SessionError::Type(format!(
263 "Document {kind} value must be a JSON object"
264 )))
265 }
266}