Skip to main content

tilo_resource/
upsert.rs

1//! Collection items addressed by what they hold, and places named by a
2//! neighbour, so a caller never counts positions.
3//!
4//! A position read a moment ago is stale once anyone else inserts, removes
5//! or sorts: an agent that writes "item 3" overwrites or shifts whatever is
6//! third by then. [`EditOp::UpsertItem`](crate::EditOp::UpsertItem) names
7//! the item by its fields instead and is resolved against the document as
8//! it is when the edit applies, merged edits of others included; [`At`]
9//! names a place by the item beside it.
10
11use automerge::{ObjId, ObjType, ReadDoc, Value};
12use serde::{Deserialize, Serialize};
13
14use crate::collection::Id;
15use crate::model::{Doc, ModelError};
16
17/// Where an inserted or moved item goes: a position (clamped to the end),
18/// the end, or beside an item named by its id.
19#[derive(Clone, Debug, Default, PartialEq, Eq)]
20pub enum At {
21    Index(usize),
22    #[default]
23    End,
24    After(Id),
25    Before(Id),
26}
27
28impl From<usize> for At {
29    fn from(index: usize) -> Self {
30        Self::Index(index)
31    }
32}
33
34impl At {
35    /// The position among `others`, the collection's items in order without
36    /// the one being placed.
37    ///
38    /// # Errors
39    /// The item it names to place beside is not among `others`.
40    pub fn index(&self, others: &[&Id]) -> Result<usize, ModelError> {
41        let beside = |id: &Id| {
42            others
43                .iter()
44                .position(|other| *other == id)
45                .ok_or_else(|| ModelError::invalid(format!("no item `{id}` to place it beside")))
46        };
47        Ok(match self {
48            Self::Index(index) => (*index).min(others.len()),
49            Self::End => others.len(),
50            Self::After(id) => beside(id)?.saturating_add(1),
51            Self::Before(id) => beside(id)?,
52        })
53    }
54}
55
56impl Serialize for At {
57    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
58        match self {
59            Self::Index(index) => serializer.serialize_u64(*index as u64),
60            Self::End => serializer.serialize_str("end"),
61            Self::After(id) => serde_json::json!({ "after": id.as_str() }).serialize(serializer),
62            Self::Before(id) => serde_json::json!({ "before": id.as_str() }).serialize(serializer),
63        }
64    }
65}
66
67impl<'de> Deserialize<'de> for At {
68    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
69        at_from_json(&serde_json::Value::deserialize(deserializer)?)
70            .map_err(serde::de::Error::custom)
71    }
72}
73
74#[inline(never)]
75fn at_from_json(value: &serde_json::Value) -> Result<At, String> {
76    const SHAPE: &str = "`at` is a position, \"end\", {\"after\": id} or {\"before\": id}";
77    if let Some(index) = value.as_u64() {
78        return usize::try_from(index)
79            .map(At::Index)
80            .map_err(|_| SHAPE.to_owned());
81    }
82    match value {
83        serde_json::Value::String(text) if text.trim().eq_ignore_ascii_case("end") => Ok(At::End),
84        serde_json::Value::Null => Ok(At::End),
85        serde_json::Value::Object(fields) if fields.len() == 1 => {
86            let id = |value: &serde_json::Value| {
87                value
88                    .as_str()
89                    .map(|id| Id::from_raw(id.trim()))
90                    .ok_or_else(|| SHAPE.to_owned())
91            };
92            match (fields.get("after"), fields.get("before")) {
93                (Some(after), None) => id(after).map(At::After),
94                (None, Some(before)) => id(before).map(At::Before),
95                _ => Err(SHAPE.to_owned()),
96            }
97        }
98        _ => Err(SHAPE.to_owned()),
99    }
100}
101
102/// One item of a collection as an upsert reads it: its id, and the map its
103/// fields are stored in.
104pub(crate) struct Candidate {
105    pub(crate) id: Id,
106    pub(crate) fields: ObjId,
107}
108
109/// The one of `items` whose fields hold `matching`, `None` when none does.
110///
111/// # Errors
112/// `matching` names no field, or more than one item matches: which one is
113/// meant is unclear, and updating either could overwrite another's row.
114pub(crate) fn matching_one<'a>(
115    doc: &Doc,
116    items: &'a [Candidate],
117    matching: &serde_json::Map<String, serde_json::Value>,
118) -> Result<Option<&'a Candidate>, ModelError> {
119    if matching.is_empty() {
120        return Err(ModelError::invalid(
121            "upsert-item needs `match`: the fields that identify the item",
122        ));
123    }
124    let mut found = items.iter().filter(|item| {
125        matching
126            .iter()
127            .all(|(key, wanted)| same_value(stored(doc, &item.fields, key).as_ref(), wanted))
128    });
129    match (found.next(), found.next()) {
130        (None, _) => Ok(None),
131        (Some(one), None) => Ok(Some(one)),
132        (Some(first), Some(second)) => Err(ModelError::invalid(format!(
133            "`match` {} fits items `{}` and `{}`: name more fields so it fits one",
134            serde_json::Value::Object(matching.clone()),
135            first.id,
136            second.id
137        ))),
138    }
139}
140
141/// The fields of `value` that differ from what the item stored at `fields`
142/// holds: an upsert run again changes nothing.
143///
144/// # Errors
145/// `value` is not an object of fields.
146pub(crate) fn changed_fields(
147    doc: &Doc,
148    fields: &ObjId,
149    value: &serde_json::Value,
150) -> Result<Vec<(String, serde_json::Value)>, ModelError> {
151    Ok(fields_of(value)?
152        .iter()
153        .filter(|(key, wanted)| stored(doc, fields, key).as_ref() != Some(*wanted))
154        .map(|(key, wanted)| (key.clone(), wanted.clone()))
155        .collect())
156}
157
158/// What a new item holds: `value` with the fields of `matching` it leaves
159/// out, so the item is found by them the next time.
160///
161/// # Errors
162/// `value` is not an object of fields.
163pub(crate) fn inserted(
164    matching: &serde_json::Map<String, serde_json::Value>,
165    value: &serde_json::Value,
166) -> Result<serde_json::Value, ModelError> {
167    let mut fields = fields_of(value)?.clone();
168    for (key, wanted) in matching {
169        fields.entry(key.clone()).or_insert_with(|| wanted.clone());
170    }
171    Ok(serde_json::Value::Object(fields))
172}
173
174/// The id a new item found by `matching` is minted under: the same for the
175/// same key whoever inserts it, so two inserts of one key made at once
176/// merge into one item rather than two.
177pub(crate) fn key_id(matching: &serde_json::Map<String, serde_json::Value>) -> Id {
178    let mut hasher = blake3::Hasher::new();
179    let mut keys: Vec<&String> = matching.keys().collect();
180    keys.sort();
181    for key in keys {
182        hasher.update(fold(key).as_bytes());
183        hasher.update(&[0]);
184        let wanted = matching.get(key).map_or_else(String::new, key_text);
185        hasher.update(wanted.as_bytes());
186        hasher.update(&[0]);
187    }
188    let hash = hasher.finalize().to_hex();
189    Id::from_raw(format!("key-{}", hash.get(..24).unwrap_or_default()))
190}
191
192fn fields_of(
193    value: &serde_json::Value,
194) -> Result<&serde_json::Map<String, serde_json::Value>, ModelError> {
195    value.as_object().ok_or_else(|| {
196        ModelError::invalid("upsert-item's `value` is an object of the item's fields")
197    })
198}
199
200/// The scalar or text stored under `key` in `fields`, as JSON; `None` when
201/// absent or a container.
202fn stored(doc: &Doc, fields: &ObjId, key: &str) -> Option<serde_json::Value> {
203    match doc.get(fields, key).ok()?? {
204        (Value::Scalar(scalar), _) => tilo_automerge::json::scalar_json(&scalar).ok(),
205        (Value::Object(ObjType::Text), text) => doc.text(&text).ok().map(serde_json::Value::String),
206        (Value::Object(_), _) => None,
207    }
208}
209
210/// Whether `stored` holds the key value `wanted`: numbers by value (`7`,
211/// `7.0` and `"7"` alike), text alike but for case and spacing, absent as
212/// null.
213pub(crate) fn same_value(stored: Option<&serde_json::Value>, wanted: &serde_json::Value) -> bool {
214    let stored = stored.unwrap_or(&serde_json::Value::Null);
215    match (number(stored), number(wanted)) {
216        (Some(a), Some(b)) => (a - b).abs() <= f64::EPSILON * a.abs().max(b.abs()).max(1.0),
217        _ => match (stored, wanted) {
218            (serde_json::Value::String(_), _) | (_, serde_json::Value::String(_)) => {
219                fold(&key_text(stored)) == fold(&key_text(wanted))
220            }
221            _ => stored == wanted,
222        },
223    }
224}
225
226fn number(value: &serde_json::Value) -> Option<f64> {
227    match value {
228        serde_json::Value::Number(number) => number.as_f64(),
229        serde_json::Value::String(text) => {
230            text.trim().parse::<f64>().ok().filter(|n| n.is_finite())
231        }
232        _ => None,
233    }
234}
235
236fn key_text(value: &serde_json::Value) -> String {
237    match value {
238        serde_json::Value::String(text) => fold(text),
239        serde_json::Value::Null => String::new(),
240        other => number(other).map_or_else(|| other.to_string(), |number| number.to_string()),
241    }
242}
243
244/// `text` lower-cased with its spacing collapsed.
245fn fold(text: &str) -> String {
246    text.split_whitespace()
247        .collect::<Vec<_>>()
248        .join(" ")
249        .to_lowercase()
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use serde_json::json;
256
257    tilo_test_env::scenario! {
258        fn upsert_places_and_keys_read_as_written;
259
260        phase at_reads_a_position_the_end_or_a_neighbour_and_writes_back_the_same;
261        {
262            for (text, at) in [
263                (json!(2), At::Index(2)),
264                (json!("end"), At::End),
265                (json!({"after": "b"}), At::After(Id::from("b"))),
266                (json!({"before": "a"}), At::Before(Id::from("a"))),
267            ] {
268                let read: At = serde_json::from_value(text.clone()).unwrap();
269                assert_eq!(read, at);
270                assert_eq!(serde_json::to_value(&read).unwrap(), text);
271            }
272            assert!(serde_json::from_value::<At>(json!({"after": "a", "before": "b"})).is_err());
273            assert!(serde_json::from_value::<At>(json!("middle")).is_err());
274        }
275
276        phase at_places_beside_the_item_it_names;
277        {
278            let (a, b, c) = (Id::from("a"), Id::from("b"), Id::from("c"));
279            let others = [&a, &b, &c];
280            assert_eq!(At::Index(9).index(&others).unwrap(), 3);
281            assert_eq!(At::End.index(&others).unwrap(), 3);
282            assert_eq!(At::After(b.clone()).index(&others).unwrap(), 2);
283            assert_eq!(At::Before(a.clone()).index(&others).unwrap(), 0);
284            assert!(At::After(Id::from("gone")).index(&others).is_err());
285        }
286
287        phase keys_match_folded_text_and_numbers_by_value;
288        {
289            assert!(same_value(Some(&json!("  Ana  Lima ")), &json!("ana lima")));
290            assert!(same_value(Some(&json!(7)), &json!("7.0")));
291            assert!(same_value(Some(&json!(7.0)), &json!(7)));
292            assert!(!same_value(Some(&json!("Ana")), &json!("Anna")));
293            assert!(!same_value(None, &json!("Ana")));
294            assert!(same_value(None, &json!(null)));
295        }
296
297        phase one_key_mints_one_id_however_it_is_written;
298        {
299            let one = key_id(json!({"Name": "Ana Lima"}).as_object().unwrap());
300            let same = key_id(json!({"name": " ana  lima"}).as_object().unwrap());
301            let other = key_id(json!({"Name": "Ben"}).as_object().unwrap());
302            assert_eq!(one, same);
303            assert_ne!(one, other);
304        }
305    }
306}