Skip to main content

datex_core/value_updates/
update_handler.rs

1use crate::{
2    prelude::*,
3    runtime::cache::shared_references_cache::SharedReferencesCache,
4    shared_values::base_shared_value_container::observers::{
5        ObserverCallback, TransceiverId,
6    },
7    value_updates::{
8        UpdateReturn,
9        errors::UpdateError,
10        update_data::{
11            AppendEntryUpdateData, DecrementUpdateData, DeleteEntryUpdateData,
12            IncrementUpdateData, ListSpliceUpdateData, ReplaceUpdateData,
13            SetEntryUpdateData, Update, UpdateData, UpdateOperation,
14        },
15    },
16    values::{value::Value, value_container::ValueContainer},
17};
18use core::{
19    cell::RefCell,
20    fmt::{Debug, Formatter},
21};
22
23pub type UpdateResult = Result<UpdateReturn, UpdateError>;
24
25/// Converts a Result with any types that can be converted into UpdateReturn and UpdateError into an UpdateResult.
26pub fn into_update_result<T: Into<UpdateReturn>, E: Into<UpdateError>>(
27    result: Result<T, E>,
28) -> UpdateResult {
29    match result {
30        Ok(value) => Ok(value.into()),
31        Err(err) => Err(err.into()),
32    }
33}
34
35pub trait UpdateHandler {
36    fn try_handle_update(
37        &mut self,
38        update: Update,
39        cache: &RefCell<SharedReferencesCache>,
40    ) -> UpdateResult;
41
42    fn try_set_entry(
43        &mut self,
44        path: Vec<ValueContainer>,
45        source_id: TransceiverId,
46        data: SetEntryUpdateData,
47        cache: &RefCell<SharedReferencesCache>,
48    ) -> Result<Option<ValueContainer>, UpdateError> {
49        Ok(self.try_handle_update(
50            Update::new(
51                source_id,
52                UpdateData::new_with_path(
53                    UpdateOperation::SetEntry(Box::new(data)),
54                    path,
55                ),
56            ),
57            cache,
58        )?.try_into().expect("UpdateReturn should be convertible into Result<Option<ValueContainer>, UpdateError>"))
59    }
60
61    fn try_delete_entry(
62        &mut self,
63        path: Vec<ValueContainer>,
64        source_id: TransceiverId,
65        data: DeleteEntryUpdateData,
66        cache: &RefCell<SharedReferencesCache>,
67    ) -> Result<Option<ValueContainer>, UpdateError> {
68        Ok(self.try_handle_update(
69            Update::new(
70                source_id,
71                UpdateData::new_with_path(
72                    UpdateOperation::DeleteEntry(Box::new(data)),
73                    path,
74                ),
75            ),
76            cache,
77        )?.try_into().expect("UpdateReturn should be convertible into Result<Option<ValueContainer>, UpdateError>"))
78    }
79
80    fn try_append_entry(
81        &mut self,
82        path: Vec<ValueContainer>,
83        source_id: TransceiverId,
84        data: AppendEntryUpdateData,
85        cache: &RefCell<SharedReferencesCache>,
86    ) -> Result<(), UpdateError> {
87        let _: () = self.try_handle_update(
88            Update::new(
89                source_id,
90                UpdateData::new_with_path(
91                    UpdateOperation::AppendEntry(Box::new(data)),
92                    path,
93                ),
94            ),
95            cache,
96        )?
97        .try_into()
98        .expect(
99            "UpdateReturn should be convertible into Result<(), UpdateError>",
100        );
101        Ok(())
102    }
103
104    fn try_clear(
105        &mut self,
106        path: Vec<ValueContainer>,
107        source_id: TransceiverId,
108        cache: &RefCell<SharedReferencesCache>,
109    ) -> Result<ValueContainer, UpdateError> {
110        Ok(self.try_handle_update(
111            Update::new(
112                source_id,
113                UpdateData::new_with_path(UpdateOperation::Clear, path),
114            ),
115            cache,
116        )?
117        .try_into()
118        .expect(
119            "UpdateReturn should be convertible into Result<ValueContainer, UpdateError>",
120        ))
121    }
122
123    fn try_list_splice(
124        &mut self,
125        path: Vec<ValueContainer>,
126        source_id: TransceiverId,
127        data: ListSpliceUpdateData,
128        cache: &RefCell<SharedReferencesCache>,
129    ) -> Result<Vec<ValueContainer>, UpdateError> {
130        Ok(self.try_handle_update(
131            Update::new(
132                source_id,
133                UpdateData::new_with_path(
134                    UpdateOperation::ListSplice(Box::new(data)),
135                    path,
136                ),
137            ),
138            cache,
139        )?
140        .try_into()
141        .expect(
142            "UpdateReturn should be convertible into Result<Vec<ValueContainer>, UpdateError>",
143        ))
144    }
145
146    fn try_increment(
147        &mut self,
148        path: Vec<ValueContainer>,
149        source_id: TransceiverId,
150        data: IncrementUpdateData,
151        cache: &RefCell<SharedReferencesCache>,
152    ) -> Result<(), UpdateError> {
153        let _: () = self.try_handle_update(
154            Update::new(
155                source_id,
156                UpdateData::new_with_path(
157                    UpdateOperation::Increment(Box::new(data)),
158                    path,
159                ),
160            ),
161            cache,
162        )?
163        .try_into()
164        .expect(
165            "UpdateReturn should be convertible into Result<(), UpdateError>",
166        );
167        Ok(())
168    }
169    fn try_decrement(
170        &mut self,
171        path: Vec<ValueContainer>,
172        source_id: TransceiverId,
173        data: DecrementUpdateData,
174        cache: &RefCell<SharedReferencesCache>,
175    ) -> Result<(), UpdateError> {
176        let _: () = self.try_handle_update(
177            Update::new(
178                source_id,
179                UpdateData::new_with_path(
180                    UpdateOperation::Decrement(Box::new(data)),
181                    path,
182                ),
183            ),
184            cache,
185        )?
186        .try_into()
187        .expect(
188            "UpdateReturn should be convertible into Result<(), UpdateError>",
189        );
190        Ok(())
191    }
192    fn try_replace(
193        &mut self,
194        path: Vec<ValueContainer>,
195        source_id: TransceiverId,
196        data: ReplaceUpdateData,
197        cache: &RefCell<SharedReferencesCache>,
198    ) -> Result<(), UpdateError> {
199        let _: () = self.try_handle_update(
200            Update::new(
201                source_id,
202                UpdateData::new_with_path(
203                    UpdateOperation::Replace(Box::new(data)),
204                    path,
205                ),
206            ),
207            cache,
208        )?
209        .try_into()
210        .expect(
211            "UpdateReturn should be convertible into Result<(), UpdateError>",
212        );
213        Ok(())
214    }
215}
216
217/// The local observer callback hold the callback and the path of the value if referenced
218/// by a shared container
219pub struct UpdateCallbackData {
220    pub callback: ObserverCallback,
221    pub path: Vec<ValueContainer>,
222}
223impl UpdateCallbackData {
224    /// Creates a new UpdateCallbackData with the same callback,
225    /// appending the provided child_key to the path.
226    pub fn with_child_path(
227        &self,
228        child_key: impl Into<ValueContainer>,
229    ) -> Self {
230        let mut new_path = self.path.clone();
231        new_path.push(child_key.into());
232        UpdateCallbackData {
233            callback: self.callback.clone(),
234            path: new_path,
235        }
236    }
237}
238
239impl Debug for UpdateCallbackData {
240    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
241        f.debug_struct("LocalObserveData")
242            .field("callback", &"<ObserverCallback>")
243            .field("path", &self.path)
244            .finish()
245    }
246}
247
248pub trait UpdateCallbackDataAccess {
249    fn get_update_callback_data(&self) -> Option<&UpdateCallbackData> {
250        None
251    }
252}
253
254pub trait InternalMutabilityUpdateHandler: UpdateCallbackDataAccess {
255    fn set_update_callback_data(
256        &mut self,
257        observe_data: Option<UpdateCallbackData>,
258    );
259
260    /// Updates the update callback data for a child value based on the current update callback data of the parent.
261    fn set_child_update_callback_data(
262        &self,
263        child_key: impl Into<ValueContainer>,
264        child_value: &mut Value,
265    ) {
266        if let Some(callback_data) = self.get_update_callback_data() {
267            let child_callback_data = callback_data.with_child_path(child_key);
268            child_value.set_update_callback_data(Some(child_callback_data));
269        } else {
270            child_value.set_update_callback_data(None);
271        }
272    }
273
274    /// Updates the update callback data for a child value if it is a [ValueContainer::Local],
275    /// based on the current update callback data of the parent.
276    fn set_child_update_callback_data_if_local(
277        &self,
278        child_key: &(impl Into<ValueContainer> + Clone),
279        child_value: &mut ValueContainer,
280    ) {
281        if let ValueContainer::Local(child_value) = child_value {
282            self.set_child_update_callback_data(child_key.clone(), child_value);
283        }
284    }
285
286    /// Triggers the update callback if the source_id is provided and the callback data is available.
287    fn maybe_trigger_update_callback(
288        &self,
289        source_id: Option<TransceiverId>,
290        update_operation_generator: impl FnOnce() -> UpdateOperation,
291    ) {
292        if let Some(source_id) = source_id
293            && let Some(callback_data) = self.get_update_callback_data()
294        {
295            let operation = update_operation_generator();
296            (callback_data.callback)(&Update::new(
297                source_id,
298                UpdateData::new_with_path(
299                    operation,
300                    callback_data.path.clone(),
301                ),
302            ));
303        }
304    }
305}
306
307pub trait UpdateHandlerImpl: UpdateCallbackDataAccess {
308    /// Handles an update operation on the implementing type and returns an UpdateResult.
309    /// The replacement operation must be handled at a higher level, as it is not specific to the implementing type - there are special cases, such as Option / Box.
310    /// If the optional source_id is provided, it should be used to notify observers of the internal update.
311    fn try_update(
312        &mut self,
313        operation: UpdateOperation,
314        source_id: Option<TransceiverId>,
315        // TODO - Do we really need cache here? Probably only for type checks, that can not be made on pointer addr only
316        // such as type impl constraint checks or sub type checks. TBD
317        cache: &RefCell<SharedReferencesCache>,
318    ) -> UpdateResult {
319        let maybe_callback_data = if let Some(callback_data) =
320            self.get_update_callback_data()
321            && let Some(source_id) = &source_id
322        {
323            Some((
324                Update::new(
325                    source_id.clone(),
326                    UpdateData::new_with_path(
327                        operation.clone(),
328                        callback_data.path.clone(),
329                    ),
330                ),
331                callback_data.callback.clone(),
332            ))
333        } else {
334            None
335        };
336
337        let ret = match operation {
338            UpdateOperation::SetEntry(data) => {
339                into_update_result(self.try_set_entry(*data, cache))
340            }
341            UpdateOperation::DeleteEntry(data) => {
342                into_update_result(self.try_delete_entry(*data, cache))
343            }
344            UpdateOperation::AppendEntry(data) => {
345                into_update_result(self.try_append_entry(*data, cache))
346            }
347            UpdateOperation::Clear => into_update_result(self.try_clear(cache)),
348            UpdateOperation::ListSplice(data) => {
349                into_update_result(self.try_list_splice(*data, cache))
350            }
351            UpdateOperation::Increment(data) => {
352                into_update_result(self.try_increment(*data, cache))
353            }
354            UpdateOperation::Decrement(data) => {
355                into_update_result(self.try_decrement(*data, cache))
356            }
357            UpdateOperation::Replace(_data) => {
358                into_update_result(self.try_replace(*_data, cache))
359            }
360        }?;
361
362        // trigger callback
363        if let Some((update, callback)) = maybe_callback_data {
364            callback(&update);
365        }
366
367        Ok(ret)
368    }
369
370    fn try_set_entry(
371        &mut self,
372        _data: SetEntryUpdateData,
373        _cache: &RefCell<SharedReferencesCache>,
374    ) -> Result<Option<ValueContainer>, UpdateError> {
375        Err(UpdateError::InvalidUpdate)
376    }
377
378    fn try_delete_entry(
379        &mut self,
380        _data: DeleteEntryUpdateData,
381        _cache: &RefCell<SharedReferencesCache>,
382    ) -> Result<ValueContainer, UpdateError> {
383        Err(UpdateError::InvalidUpdate)
384    }
385
386    fn try_append_entry(
387        &mut self,
388        _data: AppendEntryUpdateData,
389        _cache: &RefCell<SharedReferencesCache>,
390    ) -> Result<(), UpdateError> {
391        Err(UpdateError::InvalidUpdate)
392    }
393
394    fn try_clear(
395        &mut self,
396        _cache: &RefCell<SharedReferencesCache>,
397    ) -> Result<ValueContainer, UpdateError> {
398        Err(UpdateError::InvalidUpdate)
399    }
400
401    fn try_list_splice(
402        &mut self,
403        _data: ListSpliceUpdateData,
404        _cache: &RefCell<SharedReferencesCache>,
405    ) -> Result<Vec<ValueContainer>, UpdateError> {
406        Err(UpdateError::InvalidUpdate)
407    }
408
409    fn try_increment(
410        &mut self,
411        _data: IncrementUpdateData,
412        _cache: &RefCell<SharedReferencesCache>,
413    ) -> Result<(), UpdateError> {
414        Err(UpdateError::InvalidUpdate)
415    }
416    fn try_decrement(
417        &mut self,
418        _data: DecrementUpdateData,
419        _cache: &RefCell<SharedReferencesCache>,
420    ) -> Result<(), UpdateError> {
421        Err(UpdateError::InvalidUpdate)
422    }
423    fn try_replace(
424        &mut self,
425        _data: ReplaceUpdateData,
426        _cache: &RefCell<SharedReferencesCache>,
427    ) -> Result<(), UpdateError> {
428        Err(UpdateError::InvalidUpdate)
429    }
430}