Skip to main content

jmap_scene_server/memory/
history.rs

1//! Object history for `SceneAsset`, `SceneRegion` and `SceneObject` in the
2//! memory backend (draft-ietf-jmap-object-history-03 with the -04 editor's
3//! copy changes; docs/design/object-history.md §7; docs/design/DECISIONS.md
4//! decision 22). `SceneAvatar` keeps none.
5//!
6//! Off until [`MemoryBackend::with_object_history`]. Versions live in a
7//! `jmap_object_history_server::HistoryStore` inside the scoped state, so a
8//! conditional rollback discards them with the rest. Region access and the
9//! `invitedUserIds` redaction are applied to every entry by the handlers,
10//! as for current objects (§8.2).
11
12use std::collections::HashMap;
13
14use jmap_object_history_server::{HistoryRetention, HistoryStore};
15use jmap_object_history_types::{HistoryEntry, HistoryObject, ObjectHistoryAccountCapability};
16use jmap_scene_types::{SceneObject, SceneRegion};
17use jmap_server::{
18    AddedItem, BackendChangesError, BackendQueryError, BackendSetError,
19    DestroyedQueryChangesParams, DestroyedQueryParams, HistoryGetParams, HistoryGetResult,
20    JmapObject, MemoryCaller, ObjectHistoryBackend, QueryChangesResult, QueryObject, QueryResult,
21    Restored, SetError, SetErrorType, SetObject, apply_restore_patch, limit_or_max,
22    resolve_query_start,
23};
24use jmap_types::{Id, JmapError, PatchObject, State};
25use serde_json::Value;
26
27use super::{Change, Inner, MemoryBackend, MemoryError};
28
29/// The types this backend keeps history for.
30const SUPPORTED: &[&str] = &["SceneAsset", "SceneRegion", "SceneObject"];
31
32fn not_found() -> BackendSetError<MemoryError> {
33    BackendSetError::SetError(Box::new(SetError::new(SetErrorType::NotFound)))
34}
35
36fn invalid(property: &str) -> BackendSetError<MemoryError> {
37    BackendSetError::SetError(Box::new(
38        SetError::new(SetErrorType::InvalidProperties).with_properties([property]),
39    ))
40}
41
42fn bad_date(e: &jmap_types::ValidationError) -> JmapError {
43    JmapError::invalid_arguments(e.to_string())
44}
45
46impl Inner {
47    /// Record the update of `id` from `previous`.
48    pub(super) fn record_replace(
49        &mut self,
50        type_name: &str,
51        account: &Id,
52        id: &Id,
53        previous: Value,
54    ) {
55        if let Some(h) = self.history.as_mut() {
56            h.record_replace(type_name, account, id, previous);
57        }
58    }
59
60    /// Record the destruction of `id` with `last` as its final state; every
61    /// route counts (§3), so the `SceneRegion` and `SceneObject` cascades too.
62    pub(super) fn record_destroy(&mut self, type_name: &str, account: &Id, id: &Id, last: Value) {
63        if let Some(h) = self.history.as_mut() {
64            h.record_destroy(type_name, account, id, last);
65        }
66    }
67
68    /// The current `type_name` object `id`, if any.
69    pub(super) fn current(&self, type_name: &'static str, account: &Id, id: &Id) -> Option<&Value> {
70        self.objects(type_name, account).and_then(|m| m.get(id))
71    }
72
73    fn prune_history(&mut self) {
74        if let Some(h) = self.history.as_mut() {
75            h.prune();
76        }
77    }
78
79    /// Destroyed objects, most recently destroyed first (§4). No filter or
80    /// sort is evaluated over destroyed scene objects:
81    /// any is `unsupportedFilter`/`unsupportedSort` (§4 allows fewer).
82    fn destroyed_results<O: QueryObject>(
83        &self,
84        account: &Id,
85        params: (Option<&jmap_types::UTCDate>, Option<&jmap_types::UTCDate>),
86        filter: Option<&O::Filter>,
87        sort: Option<&[O::Comparator]>,
88    ) -> Result<Vec<Id>, BackendQueryError<MemoryError>> {
89        let Some(h) = self.history.as_ref() else {
90            return Ok(Vec::new());
91        };
92        if sort.is_some_and(|s| !s.is_empty()) {
93            return Err(BackendQueryError::Method(JmapError::unsupported_sort()));
94        }
95        if filter.is_some() {
96            return Err(BackendQueryError::Method(JmapError::unsupported_filter()));
97        }
98        Ok(h.destroyed(O::TYPE_NAME, account, params.0, params.1)
99            .map_err(|e| BackendQueryError::Method(bad_date(&e)))?
100            .into_iter()
101            .map(|d| d.id)
102            .collect())
103    }
104}
105
106impl<C: MemoryCaller> MemoryBackend<C> {
107    /// Keep object history for the types `capability.supportedTypes` lists
108    /// (`SceneAsset`, `SceneRegion`, `SceneObject`) in every account, with `retention`;
109    /// `capability` is also what
110    /// [`ObjectHistoryBackend::object_history_capability`] advertises.
111    ///
112    /// # Panics
113    ///
114    /// When `supportedTypes` names another type.
115    #[must_use]
116    pub fn with_object_history(
117        self,
118        capability: ObjectHistoryAccountCapability,
119        retention: HistoryRetention,
120    ) -> Self {
121        for t in &capability.supported_types {
122            assert!(
123                SUPPORTED.contains(&t.as_str()),
124                "the memory backend keeps no history for {t}"
125            );
126        }
127        self.lock().history = Some(HistoryStore::new(capability, retention));
128        self
129    }
130
131    /// Fix the history clock at `ms` milliseconds since the epoch.
132    pub fn set_history_clock_for_test(&self, ms: i64) {
133        if let Some(h) = self.lock().history.as_mut() {
134            h.set_clock(ms);
135        }
136    }
137}
138
139impl<C: MemoryCaller> ObjectHistoryBackend for MemoryBackend<C> {
140    fn object_history_capability(
141        &self,
142        _caller: &C,
143        account_id: &Id,
144    ) -> Option<ObjectHistoryAccountCapability> {
145        let inner = self.lock();
146        inner.accounts.get(account_id.as_ref())?;
147        inner.history.as_ref().map(|h| h.capability().clone())
148    }
149
150    async fn get_object_history<O: HistoryObject>(
151        &self,
152        _caller: &C,
153        account_id: &Id,
154        params: HistoryGetParams<'_>,
155    ) -> Result<HistoryGetResult<O>, BackendQueryError<MemoryError>> {
156        let mut inner = self.locked().await;
157        inner.prune_history();
158        let empty = HashMap::new();
159        let live = inner.objects(O::TYPE_NAME, account_id).unwrap_or(&empty);
160        let Some(h) = inner.history.as_ref() else {
161            return Ok(HistoryGetResult::new(
162                Vec::new(),
163                params.ids.map(<[Id]>::to_vec).unwrap_or_default(),
164            ));
165        };
166        let (rows, not_found) = h
167            .select(O::TYPE_NAME, account_id, params.ids, live, params.arguments)
168            .map_err(|e| BackendQueryError::Method(bad_date(&e)))?;
169        let mut entries = Vec::with_capacity(rows.len());
170        for (snapshot, info) in rows {
171            let object = serde_json::from_value::<O>(snapshot)
172                .map_err(|e| BackendQueryError::Other(MemoryError::new(e.to_string())))?;
173            entries.push(HistoryEntry::new(object, info));
174        }
175        Ok(HistoryGetResult::new(entries, not_found))
176    }
177
178    async fn query_destroyed<O: HistoryObject + QueryObject>(
179        &self,
180        _caller: &C,
181        account_id: &Id,
182        params: DestroyedQueryParams<'_, O>,
183    ) -> Result<QueryResult, BackendQueryError<MemoryError>> {
184        let mut inner = self.locked().await;
185        inner.prune_history();
186        let q = &params.query;
187        let all = inner.destroyed_results::<O>(
188            account_id,
189            (params.destroyed_after, params.destroyed_before),
190            q.filter,
191            q.sort,
192        )?;
193        let start = resolve_query_start(&all, q.position, q.anchor, q.anchor_offset)
194            .map_err(BackendQueryError::Method)?;
195        let ids: Vec<Id> = all[start..]
196            .iter()
197            .take(limit_or_max(q.limit))
198            .cloned()
199            .collect();
200        let state = inner.history.as_ref().map_or_else(String::new, |h| {
201            h.destroyed_query_state(
202                O::TYPE_NAME,
203                account_id,
204                params.destroyed_after,
205                params.destroyed_before,
206            )
207        });
208        Ok(QueryResult::new(
209            ids,
210            start as u64,
211            Some(all.len() as u64),
212            State::from(state),
213            true,
214        ))
215    }
216
217    async fn query_destroyed_changes<O: HistoryObject + QueryObject>(
218        &self,
219        _caller: &C,
220        account_id: &Id,
221        params: DestroyedQueryChangesParams<'_, O>,
222    ) -> Result<QueryChangesResult, BackendChangesError<MemoryError>> {
223        let mut inner = self.locked().await;
224        inner.prune_history();
225        let q = &params.query_changes;
226        let all = inner
227            .destroyed_results::<O>(
228                account_id,
229                (params.destroyed_after, params.destroyed_before),
230                q.filter,
231                q.sort,
232            )
233            .map_err(|e| match e {
234                BackendQueryError::Other(e) => BackendChangesError::Other(e),
235                _ => BackendChangesError::CannotCalculate,
236            })?;
237        let Some(h) = inner.history.as_ref() else {
238            return Err(BackendChangesError::CannotCalculate);
239        };
240        // A state of another kind or window cannot be calculated (decision
241        // 25).
242        let changed = h
243            .destroyed_changes_since(
244                O::TYPE_NAME,
245                account_id,
246                q.since_query_state.as_ref(),
247                params.destroyed_after,
248                params.destroyed_before,
249            )
250            .ok_or(BackendChangesError::CannotCalculate)?;
251        if let Some(max) = q.max_changes
252            && changed.len() as u64 > max
253        {
254            return Err(BackendChangesError::TooManyChanges { limit: max });
255        }
256        let new_state = h.destroyed_query_state(
257            O::TYPE_NAME,
258            account_id,
259            params.destroyed_after,
260            params.destroyed_before,
261        );
262        let added: Vec<AddedItem> = all
263            .iter()
264            .enumerate()
265            .filter(|(_, id)| changed.contains(id))
266            .map(|(i, id)| AddedItem::new(id.clone(), i as u64))
267            .collect();
268        Ok(QueryChangesResult::new(
269            q.since_query_state.clone(),
270            State::from(new_state),
271            Some(all.len() as u64),
272            changed,
273            added,
274        ))
275    }
276
277    async fn restore_object<O: HistoryObject + SetObject>(
278        &self,
279        _caller: &C,
280        account_id: &Id,
281        id: &Id,
282        patch: Option<PatchObject>,
283    ) -> Result<Restored<O>, BackendSetError<MemoryError>> {
284        let mut inner = self.locked().await;
285        inner.prune_history();
286        if inner.current(O::TYPE_NAME, account_id, id).is_some() {
287            return Err(not_found());
288        }
289        let Some(Value::Object(final_version)) = inner
290            .history
291            .as_ref()
292            .and_then(|h| h.final_version(O::TYPE_NAME, account_id, id))
293            .cloned()
294        else {
295            return Err(not_found());
296        };
297        let baseline = apply_restore_patch::<O>(&final_version, patch.as_ref())
298            .map_err(BackendSetError::SetError)?;
299        let value = Value::Object(baseline.clone());
300        if O::TYPE_NAME == SceneObject::TYPE_NAME {
301            // An object lives in a current region, under a current parent
302            // (§5.2: a missing one fails as an update naming it would).
303            let region = value.get("regionId").and_then(Value::as_str).map(Id::from);
304            if !region.is_some_and(|r| {
305                inner
306                    .current(SceneRegion::TYPE_NAME, account_id, &r)
307                    .is_some()
308            }) {
309                return Err(invalid("regionId"));
310            }
311            if let Some(parent) = value.get("parentId").and_then(Value::as_str).map(Id::from)
312                && inner
313                    .current(SceneObject::TYPE_NAME, account_id, &parent)
314                    .is_none()
315            {
316                return Err(invalid("parentId"));
317            }
318        }
319        let object = serde_json::from_value::<O>(value.clone()).map_err(|_| invalid("id"))?;
320        if let Some(h) = inner.history.as_mut() {
321            h.restore(O::TYPE_NAME, account_id, id);
322        }
323        let type_name: &'static str = O::TYPE_NAME;
324        inner
325            .objects_mut(type_name, account_id)
326            .insert(id.clone(), value);
327        inner.commit(type_name, account_id, vec![(id.clone(), Change::Restored)]);
328        Ok(Restored::new(object, baseline))
329    }
330}