1use std::fmt;
8
9use hidane_proto::google::firestore::v1::{MapValue, Value, value::ValueType};
10pub use hidane_proto::ordered::Fields;
11
12use crate::hash_order::hash_order;
13
14#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct FieldPath(Vec<String>);
16
17impl FieldPath {
18 pub fn parse(path: &str) -> Result<Self, String> {
20 let invalid = || {
21 format!(
22 "Invalid property path \"{path}\". Unquoted property paths must match regex \
23 ([a-zA-Z_][a-zA-Z_0-9]*), and quoted property paths must match regex \
24 (`(?:[^`\\\\]|(?:\\\\.))+`)"
25 )
26 };
27 let mut segments = Vec::new();
28 let mut chars = path.chars().peekable();
29 loop {
30 let mut segment = String::new();
31 if chars.peek() == Some(&'`') {
32 chars.next();
33 loop {
34 match chars.next() {
35 Some('`') => break,
36 Some('\\') => segment.push(chars.next().ok_or_else(invalid)?),
37 Some(c) => segment.push(c),
38 None => return Err(invalid()),
39 }
40 }
41 if segment.is_empty() {
42 return Err(invalid());
43 }
44 } else {
45 while let Some(&c) = chars.peek() {
46 if c == '.' {
47 break;
48 }
49 let valid = if segment.is_empty() {
50 c.is_ascii_alphabetic() || c == '_'
51 } else {
52 c.is_ascii_alphanumeric() || c == '_'
53 };
54 if !valid {
55 return Err(invalid());
56 }
57 segment.push(c);
58 chars.next();
59 }
60 if segment.is_empty() {
61 return Err(invalid());
62 }
63 }
64 segments.push(segment);
65 match chars.next() {
66 None => return Ok(Self(segments)),
67 Some('.') => {}
68 Some(_) => return Err(invalid()),
69 }
70 }
71 }
72
73 pub fn from_segments<I, S>(segments: I) -> Self
74 where
75 I: IntoIterator<Item = S>,
76 S: Into<String>,
77 {
78 Self(segments.into_iter().map(Into::into).collect())
79 }
80
81 pub fn segments(&self) -> &[String] {
82 &self.0
83 }
84}
85
86impl fmt::Display for FieldPath {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 for (i, segment) in self.0.iter().enumerate() {
91 if i > 0 {
92 f.write_str(".")?;
93 }
94 let mut chars = segment.chars();
95 let simple = chars
96 .next()
97 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
98 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
99 if simple {
100 f.write_str(segment)?;
101 } else {
102 f.write_str("`")?;
103 for c in segment.chars() {
104 if c == '`' || c == '\\' {
105 f.write_str("\\")?;
106 }
107 write!(f, "{c}")?;
108 }
109 f.write_str("`")?;
110 }
111 }
112 Ok(())
113 }
114}
115
116pub fn get<'a>(fields: &'a Fields, path: &FieldPath) -> Option<&'a Value> {
118 let (last, parents) = path.0.split_last()?;
119 let mut current = fields;
120 for segment in parents {
121 match ¤t.get(segment)?.value_type {
122 Some(ValueType::MapValue(map)) => current = &map.fields,
123 _ => return None,
124 }
125 }
126 current.get(last)
127}
128
129pub fn set(fields: &mut Fields, path: &FieldPath, value: Value) {
131 let Some((last, parents)) = path.0.split_last() else {
132 return;
133 };
134 let mut current = fields;
135 for segment in parents {
136 let entry = current.entry(segment.clone()).or_insert_with(empty_map);
137 if !matches!(entry.value_type, Some(ValueType::MapValue(_))) {
138 *entry = empty_map();
139 }
140 let Some(ValueType::MapValue(map)) = &mut entry.value_type else {
141 unreachable!("just made it a map");
142 };
143 current = &mut map.fields;
144 }
145 current.insert(last.clone(), value);
146}
147
148pub fn delete(fields: &mut Fields, path: &FieldPath) {
150 let Some((last, parents)) = path.0.split_last() else {
151 return;
152 };
153 let mut current = fields;
154 for segment in parents {
155 match current.get_mut(segment).and_then(|v| v.value_type.as_mut()) {
156 Some(ValueType::MapValue(map)) => current = &mut map.fields,
157 _ => return,
158 }
159 }
160 current.remove(last);
161}
162
163#[derive(Default)]
166struct MaskTree {
167 whole: bool,
169 children: Vec<(String, MaskTree)>,
170}
171
172impl MaskTree {
173 fn new(paths: &[FieldPath]) -> Self {
174 let mut root = Self::default();
175 for path in paths {
176 let mut node = &mut root;
177 for segment in path.segments() {
178 let at = match node.children.iter().position(|(name, _)| name == segment) {
179 Some(at) => at,
180 None => {
181 node.children.push((segment.clone(), Self::default()));
182 node.children.len() - 1
183 }
184 };
185 node = &mut node.children[at].1;
186 }
187 node.whole = true;
188 }
189 root
190 }
191
192 fn ordered(&self) -> impl Iterator<Item = &(String, MaskTree)> {
195 let names: Vec<&str> = self
196 .children
197 .iter()
198 .map(|(name, _)| name.as_str())
199 .collect();
200 hash_order(&names).into_iter().map(|i| &self.children[i])
201 }
202
203 fn flatten(&self, prefix: &mut Vec<String>, out: &mut Vec<FieldPath>) {
207 let (whole, below): (Vec<_>, Vec<_>) =
208 self.children.iter().partition(|(_, node)| node.whole);
209 let children: Vec<&(String, MaskTree)> = whole.into_iter().chain(below).collect();
210 let names: Vec<&str> = children.iter().map(|(name, _)| name.as_str()).collect();
211 for (name, below) in hash_order(&names).into_iter().map(|i| children[i]) {
212 prefix.push(name.clone());
213 if below.whole {
214 out.push(FieldPath(prefix.clone()));
215 } else {
216 below.flatten(prefix, out);
217 }
218 prefix.pop();
219 }
220 }
221}
222
223pub fn mask_paths(mask: &[FieldPath]) -> Vec<FieldPath> {
228 let mut out = Vec::new();
229 MaskTree::new(mask).flatten(&mut Vec::new(), &mut out);
230 out
231}
232
233fn in_hash_order<T>(mut entries: Vec<(String, T)>) -> impl Iterator<Item = (String, T)> {
235 let order = hash_order(&entries.iter().map(|(name, _)| name).collect::<Vec<_>>());
236 let mut taken: Vec<Option<(String, T)>> = entries.drain(..).map(Some).collect();
237 order.into_iter().filter_map(move |i| taken[i].take())
238}
239
240fn map_fields(value: &Value) -> Option<&Fields> {
241 match &value.value_type {
242 Some(ValueType::MapValue(map)) => Some(&map.fields),
243 _ => None,
244 }
245}
246
247fn map_of(fields: Fields) -> Value {
248 Value {
249 value_type: Some(ValueType::MapValue(MapValue { fields })),
250 }
251}
252
253pub fn project(fields: &Fields, paths: &[FieldPath]) -> Fields {
257 project_level(fields, &MaskTree::new(paths))
258}
259
260fn project_level(fields: &Fields, mask: &MaskTree) -> Fields {
261 let mut found = Vec::new();
262 for (name, below) in mask.ordered() {
263 let Some(value) = fields.get(name) else {
264 continue;
265 };
266 if below.whole {
267 found.push((name.clone(), value.clone()));
268 } else if let Some(map) = map_fields(value) {
269 let inner = project_level(map, below);
270 if !inner.is_empty() {
271 found.push((name.clone(), map_of(inner)));
272 }
273 }
274 }
275 in_hash_order(found).collect()
276}
277
278pub fn apply_mask(existing: &mut Fields, input: &Fields, mask: &[FieldPath]) {
287 merge_level(existing, Some(input), &MaskTree::new(mask));
288}
289
290fn merge_level(existing: &mut Fields, input: Option<&Fields>, mask: &MaskTree) {
291 let mut changes = Vec::new();
292 for (name, below) in mask.ordered() {
293 let old = existing.get(name);
294 let given = input.and_then(|fields| fields.get(name));
295 let new = if below.whole {
296 given.cloned()
297 } else {
298 let mut inner = old.and_then(map_fields).cloned().unwrap_or_default();
299 merge_level(&mut inner, given.and_then(map_fields), below);
300 match old {
301 Some(old) if map_fields(old).is_some() || !inner.is_empty() => Some(map_of(inner)),
303 Some(old) => Some(old.clone()),
304 None if inner.is_empty() => None,
305 None => Some(map_of(inner)),
306 }
307 };
308 if new.as_ref() != old {
309 changes.push((name.clone(), new));
310 }
311 }
312 for (name, new) in in_hash_order(changes) {
313 existing.remove(&name);
314 if let Some(value) = new {
315 existing.insert(name, value);
316 }
317 }
318}
319
320fn empty_map() -> Value {
321 Value {
322 value_type: Some(ValueType::MapValue(MapValue::default())),
323 }
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 #[test]
331 fn mask_paths_as_rules_see_them() {
332 let listed = |mask: &[&str]| -> Vec<String> {
333 let mask: Vec<FieldPath> = mask.iter().map(|p| FieldPath::parse(p).unwrap()).collect();
334 mask_paths(&mask).iter().map(ToString::to_string).collect()
335 };
336 assert_eq!(listed(&["c", "b", "a"]), ["a", "b", "c"]);
338 assert_eq!(listed(&["n", "m.b", "z"]), ["z", "m.b", "n"]);
339 assert_eq!(listed(&["b", "a", "b"]), ["a", "b"]);
340 assert_eq!(listed(&["m.b", "m"]), ["m"]);
341 assert_eq!(listed(&["m.b.c", "m.a", "z"]), ["z", "m.a", "m.b.c"]);
342 assert_eq!(
343 listed(&["x.y", "a", "`q r`", "b.c.d"]),
344 ["a", "`q r`", "b.c.d", "x.y"]
345 );
346 assert_eq!(listed(&["b.c", "r", "B.x", "R"]), ["r", "R", "b.c", "B.x"]);
348 assert_eq!(listed(&["m.b.c", "m.r"]), ["m.r", "m.b.c"]);
349 assert!(listed(&[]).is_empty());
350 }
351
352 fn int(i: i64) -> Value {
353 Value {
354 value_type: Some(ValueType::IntegerValue(i)),
355 }
356 }
357
358 fn map(entries: &[(&str, Value)]) -> Value {
359 Value {
360 value_type: Some(ValueType::MapValue(MapValue {
361 fields: entries
362 .iter()
363 .map(|(k, v)| ((*k).to_owned(), v.clone()))
364 .collect(),
365 })),
366 }
367 }
368
369 fn fields(entries: &[(&str, Value)]) -> Fields {
370 entries
371 .iter()
372 .map(|(k, v)| ((*k).to_owned(), v.clone()))
373 .collect()
374 }
375
376 fn fp(s: &str) -> FieldPath {
377 FieldPath::parse(s).unwrap()
378 }
379
380 #[test]
381 fn display_is_the_canonical_form() {
382 for canonical in [
383 "a", "a.b", "_x9", "`a b`.c", "`1a`", "`x\\`y`", "`a\\\\b`", "`é`",
384 ] {
385 assert_eq!(fp(canonical).to_string(), canonical);
386 }
387 assert_eq!(fp("`a`.`b`").to_string(), "a.b");
388 }
389
390 #[test]
391 fn parses_unquoted_and_quoted_segments() {
392 assert_eq!(fp("a").segments(), ["a"]);
393 assert_eq!(fp("a.b_1._c").segments(), ["a", "b_1", "_c"]);
394 assert_eq!(fp("`a.b`.c").segments(), ["a.b", "c"]);
395 assert_eq!(fp("`x\\`y`").segments(), ["x`y"]);
396 assert_eq!(fp("`\\\\`").segments(), ["\\"]);
397 assert_eq!(fp("`1st`").segments(), ["1st"]);
398 }
399
400 #[test]
401 fn rejects_like_the_official_emulator() {
402 for bad in [
403 "", "a..b", ".a", "a.", "1a", "a-b", "``", "`a", "`a`b", "a b",
404 ] {
405 let err = FieldPath::parse(bad).unwrap_err();
406 assert!(
407 err.starts_with(&format!("Invalid property path \"{bad}\". Unquoted")),
408 "{bad}: {err}"
409 );
410 }
411 assert_eq!(
413 FieldPath::parse("a..b").unwrap_err(),
414 "Invalid property path \"a..b\". Unquoted property paths must match regex \
415 ([a-zA-Z_][a-zA-Z_0-9]*), and quoted property paths must match regex \
416 (`(?:[^`\\\\]|(?:\\\\.))+`)"
417 );
418 }
419
420 #[test]
421 fn update_mask_matches_the_official_emulator() {
422 let mut doc = fields(&[
425 ("a", int(1)),
426 ("b", int(2)),
427 ("c", map(&[("x", int(1)), ("y", int(2))])),
428 ]);
429 let input = fields(&[("a", int(10)), ("c", map(&[("x", int(5))])), ("e", int(9))]);
430 apply_mask(&mut doc, &input, &[fp("a"), fp("c.x"), fp("d")]);
431 assert_eq!(
432 doc,
433 fields(&[
434 ("a", int(10)),
435 ("b", int(2)),
436 ("c", map(&[("x", int(5)), ("y", int(2))])),
437 ])
438 );
439 }
440
441 #[test]
442 fn masks_on_missing_documents_create_only_the_masked_fields() {
443 let mut doc = Fields::new();
444 let input = fields(&[("a", int(1)), ("b", map(&[("x", int(1))]))]);
445 apply_mask(&mut doc, &input, &[fp("b.x")]);
446 assert_eq!(doc, fields(&[("b", map(&[("x", int(1))]))]));
447 }
448
449 #[test]
450 fn read_masks_project_nested_fields() {
451 let doc = fields(&[
452 ("a", int(1)),
453 ("b", map(&[("x", int(1)), ("y", int(2))])),
454 ("c", int(3)),
455 ]);
456 assert_eq!(
457 project(
458 &doc,
459 &[fp("b.x"), fp("c"), fp("missing"), fp("a.not_a_map")]
460 ),
461 fields(&[("b", map(&[("x", int(1))])), ("c", int(3))])
462 );
463 }
464
465 fn layout(fields: &Fields) -> String {
467 fields
468 .iter()
469 .map(|(name, value)| match &value.value_type {
470 Some(ValueType::MapValue(map)) => format!("{name}{{{}}}", layout(&map.fields)),
471 _ => name.clone(),
472 })
473 .collect::<Vec<_>>()
474 .join(",")
475 }
476
477 #[test]
481 fn masked_fields_that_change_move_to_the_end_in_hash_order() {
482 let base = || {
483 fields(&[
484 ("zeta", int(1)),
485 ("alpha", int(2)),
486 ("mid", map(&[("z", int(3)), ("a", int(4))])),
487 ])
488 };
489 let mut doc = base();
490 apply_mask(
491 &mut doc,
492 &fields(&[("beta", int(9)), ("alpha", int(10))]),
493 &[fp("beta"), fp("alpha")],
494 );
495 assert_eq!(layout(&doc), "zeta,mid{z,a},alpha,beta");
496
497 let mut doc = base();
499 apply_mask(
500 &mut doc,
501 &fields(&[
502 ("deep", map(&[("x", map(&[("y", int(1))]))])),
503 ("alpha", int(2)),
504 ]),
505 &[fp("deep.x.y"), fp("alpha")],
506 );
507 assert_eq!(layout(&doc), "zeta,alpha,mid{z,a},deep{x{y}}");
508 }
509
510 #[test]
511 fn a_map_changed_inside_moves_to_the_end() {
512 let base = || {
513 fields(&[
514 ("mid", map(&[("z", int(3)), ("a", int(4))])),
515 ("zeta", int(1)),
516 ("alpha", int(2)),
517 ])
518 };
519 let mut doc = base();
520 apply_mask(
521 &mut doc,
522 &fields(&[("mid", map(&[("b", int(5))]))]),
523 &[fp("mid.b")],
524 );
525 assert_eq!(layout(&doc), "zeta,alpha,mid{z,a,b}");
526
527 let mut doc = base();
528 apply_mask(&mut doc, &Fields::new(), &[fp("mid.z")]);
529 assert_eq!(layout(&doc), "zeta,alpha,mid{a}");
530
531 let mut doc = fields(&[
532 ("p", map(&[("x", int(1)), ("y", int(2))])),
533 ("alpha", int(1)),
534 ("zeta", int(2)),
535 ("mid", int(3)),
536 ]);
537 apply_mask(
538 &mut doc,
539 &fields(&[("alpha", int(9))]),
540 &[fp("p.y"), fp("alpha")],
541 );
542 assert_eq!(layout(&doc), "zeta,mid,p{x},alpha");
543 }
544
545 #[test]
546 fn the_changed_fields_have_a_hash_map_of_their_own() {
547 let present = [
548 "str", "int", "dbl", "zeta", "alpha", "a", "b", "c", "x1", "x2", "x3",
549 ];
550 let doc_with = |extra: &[(&str, Value)]| {
551 let mut doc = fields(&[("keep", int(0))]);
552 for (n, name) in present.iter().enumerate() {
553 doc.insert((*name).to_owned(), int(n as i64));
554 }
555 doc.extend(extra.iter().map(|(k, v)| ((*k).to_owned(), v.clone())));
556 doc
557 };
558 let input: Fields = present
559 .iter()
560 .enumerate()
561 .map(|(n, name)| ((*name).to_owned(), int(n as i64 + 100)))
562 .collect();
563 let mask: Vec<FieldPath> = present
564 .iter()
565 .chain(&["gone1", "gone2"])
566 .map(|p| fp(p))
567 .collect();
568
569 let mut doc = doc_with(&[]);
571 apply_mask(&mut doc, &input, &mask);
572 assert_eq!(layout(&doc), "keep,zeta,str,a,b,c,alpha,x1,x2,x3,int,dbl");
573
574 let mut doc = doc_with(&[("gone1", int(1)), ("gone2", int(2))]);
576 apply_mask(&mut doc, &input, &mask);
577 assert_eq!(layout(&doc), "keep,zeta,a,b,c,int,dbl,str,alpha,x1,x2,x3");
578 }
579
580 #[test]
581 fn read_masks_return_fields_in_hash_order() {
582 let doc = fields(&[
583 ("str", int(1)),
584 ("mid", map(&[("z", int(1)), ("a", int(2))])),
585 ("zeta", int(3)),
586 ("alpha", int(4)),
587 ("a", int(5)),
588 ]);
589 let masked = |mask: &[&str]| {
590 layout(&project(
591 &doc,
592 &mask.iter().map(|p| fp(p)).collect::<Vec<_>>(),
593 ))
594 };
595 assert_eq!(masked(&["a", "alpha", "zeta"]), "zeta,a,alpha");
596 assert_eq!(masked(&["mid.a", "mid.z", "str"]), "str,mid{a,z}");
597 assert_eq!(masked(&["mid", "str"]), "str,mid{z,a}");
599 }
600
601 #[test]
602 fn set_replaces_non_map_intermediates() {
603 let mut doc = fields(&[("a", int(1))]);
604 set(&mut doc, &fp("a.b"), int(2));
605 assert_eq!(doc, fields(&[("a", map(&[("b", int(2))]))]));
606 }
607}