forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

subscription.rs551 lines, 18.3 KiBHistoryRawDownload
1//! # JSONPath Subscription Module
2//!
3//! This module provides a mechanism to subscribe to changes that may affect a JSONPath query
4//! result, without re-evaluating the query on every change.
5//!
6//! ## Design Goals
7//!
8//! - **Conservative matching**: The matcher may produce false positives (triggering when
9//! the query result hasn't actually changed) but must never produce false negatives
10//! (missing a notification when the result did change).
11//! - **Lightweight notifications**: Callbacks receive no payload; applications can
12//! debounce/throttle and evaluate the JSONPath themselves.
13//! - **Efficient matching**: Uses an NFA (non-deterministic finite automaton) approach
14//! to match event paths against compiled JSONPath queries in O(path_len × steps) time.
15//!
16//! ## Algorithm Overview
17//!
18//! 1. **Compilation**: JSONPath is parsed and converted into a sequence of lightweight
19//! `MatchSelector`s (no AST storage needed for matching).
20//!
21//! 2. **NFA Simulation**: When an event arrives, we simulate an NFA where:
22//! - States are positions in the step sequence (0..steps.len())
23//! - Transitions occur when a selector matches the current path element
24//! - Recursive steps allow staying at the same state while consuming input
25//! - Acceptance occurs when any state reaches or exceeds `steps.len()`
26
27use std::sync::Arc;
28
29use loro_common::TreeID;
30use smallvec::SmallVec;
31
32use crate::{
33 event::{Diff, Index},
34 jsonpath::{
35 ast::{Query, Segment, Selector},
36 JSONPathParser,
37 },
38 utils::subscription::Subscription,
39 LoroDoc, LoroError, LoroResult,
40};
41
42/// Callback used by `subscribe_jsonpath`.
43///
44/// Note: the callback does **not** carry the query result. It is intended as a
45/// lightweight notification so applications can debounce/throttle and evaluate
46/// JSONPath themselves if needed.
47pub type SubscribeJsonPathCallback = Arc<dyn Fn() + Send + Sync + 'static>;
48
49/// Represents a single path segment used for matching against events.
50///
51/// Path elements are derived from event paths and represent the location of a change
52/// in the document tree. They form the "input alphabet" for our NFA simulation.
53#[derive(Debug, Clone, PartialEq, Eq)]
54enum PathElem {
55 /// A map key (e.g., "title" in `$.books[0].title`)
56 Key(Arc<str>),
57 /// A sequence (list/array) index.
58 /// - `Some(i)` means a specific index changed
59 /// - `None` means "some index changed" (used for list/tree child mutations
60 /// where we don't know which specific indices are affected)
61 Seq(Option<usize>),
62 /// A tree node identifier (for Loro's tree CRDT)
63 Node(TreeID),
64}
65
66impl From<&Index> for PathElem {
67 fn from(value: &Index) -> Self {
68 match value {
69 Index::Key(k) => PathElem::Key(k.as_ref().into()),
70 Index::Seq(i) => PathElem::Seq(Some(*i)),
71 Index::Node(n) => PathElem::Node(*n),
72 }
73 }
74}
75
76// =============================================================================
77// Lightweight Matching Types
78// =============================================================================
79//
80// Instead of storing the full Selector AST (which includes heavyweight
81// FilterExpression trees), we convert selectors to a simple matching-only enum.
82// This reduces memory usage and code complexity.
83
84/// Simplified selector for matching only - no AST storage needed.
85///
86/// All complex selectors (Slice, Wild, Filter, negative Index) become `Wildcard`
87/// since they can match any element during conservative path matching.
88#[derive(Debug, Clone)]
89enum MatchSelector {
90 /// Exact key match (from `Selector::Name`)
91 Name(Arc<str>),
92 /// Exact non-negative index match (from `Selector::Index` where index >= 0)
93 Index(usize),
94 /// Matches anything (from Wild, Slice, Filter, or negative Index)
95 Wildcard,
96}
97
98/// A single step in the linearized JSONPath query.
99#[derive(Debug, Clone)]
100struct Step {
101 /// If true, this step uses recursive descent (`..`) and can match at any depth.
102 recursive: bool,
103 /// Simplified selectors for matching.
104 selectors: SmallVec<[MatchSelector; 2]>,
105}
106
107/// A compiled matcher that conservatively checks whether a change at some path
108/// can affect the JSONPath query.
109#[derive(Debug, Clone)]
110struct JsonPathMatcher {
111 /// Linearized sequence of matching steps
112 steps: Vec<Step>,
113}
114
115impl JsonPathMatcher {
116 /// Compile a JSONPath query into a matcher.
117 fn new(query: &Query) -> Self {
118 let mut steps = Vec::new();
119 build_steps(&query.segments, &mut steps);
120 JsonPathMatcher { steps }
121 }
122
123 /// Returns true if the provided path (from root) could affect the query result.
124 fn may_match(&self, path: &[PathElem]) -> bool {
125 if self.steps.is_empty() {
126 return true;
127 }
128 let positions = self.positions_after(path);
129 positions.iter().any(|&p| p >= self.steps.len())
130 }
131
132 /// Check if any position was reached by passing through a Wildcard step.
133 /// Wildcard steps come from filter/wild/slice selectors - any key change
134 /// under them could affect the query result.
135 #[inline]
136 fn passed_through_wildcard(&self, positions: &[usize]) -> bool {
137 positions.iter().any(|&pos| {
138 pos > 0
139 && self.steps[pos - 1]
140 .selectors
141 .iter()
142 .any(|s| matches!(s, MatchSelector::Wildcard))
143 })
144 }
145
146 /// Simulate the NFA on a path and return all reachable positions after consuming it.
147 ///
148 /// - Position `== steps.len()`: Query fully matched
149 /// - Position `< steps.len()`: Partial match
150 /// - Empty result: No match possible
151 fn positions_after(&self, path: &[PathElem]) -> SmallVec<[usize; 8]> {
152 let mut positions = SmallVec::<[usize; 8]>::new();
153 positions.push(0);
154
155 for elem in path {
156 let mut next = SmallVec::<[usize; 8]>::new();
157
158 for &pos in positions.iter() {
159 if pos >= self.steps.len() {
160 next.push(pos);
161 continue;
162 }
163
164 let step = &self.steps[pos];
165
166 // Recursive descent: can stay at same position
167 if step.recursive {
168 next.push(pos);
169 }
170
171 // If selector matches, advance to next step
172 if selector_matches(&step.selectors, elem) {
173 next.push(pos + 1);
174 }
175 }
176
177 dedup_positions(&mut next);
178 if next.is_empty() {
179 return next;
180 }
181 positions = next;
182 }
183
184 positions
185 }
186}
187
188/// Check if any selector matches the given path element.
189fn selector_matches(selectors: &[MatchSelector], elem: &PathElem) -> bool {
190 selectors.iter().any(|sel| match sel {
191 MatchSelector::Name(name) => matches!(elem, PathElem::Key(k) if k == name),
192 MatchSelector::Index(idx) => match elem {
193 PathElem::Seq(Some(i)) => *i == *idx,
194 PathElem::Seq(None) => true, // Unknown index - conservative match
195 _ => false,
196 },
197 MatchSelector::Wildcard => true,
198 })
199}
200
201/// Convert AST Selector to lightweight MatchSelector.
202fn to_match_selector(sel: &Selector) -> MatchSelector {
203 match sel {
204 Selector::Name { name } => MatchSelector::Name(name.as_str().into()),
205 Selector::Index { index } if *index >= 0 => MatchSelector::Index(*index as usize),
206 // Negative index, Slice, Wild, Filter all become Wildcard
207 _ => MatchSelector::Wildcard,
208 }
209}
210
211/// Linearize the JSONPath AST into a sequence of matching steps.
212fn build_steps(segment: &Segment, steps: &mut Vec<Step>) {
213 match segment {
214 Segment::Root {} => {}
215 Segment::Child { left, selectors } => {
216 build_steps(left, steps);
217 steps.push(Step {
218 recursive: false,
219 selectors: selectors.iter().map(to_match_selector).collect(),
220 });
221 }
222 Segment::Recursive { left, selectors } => {
223 build_steps(left, steps);
224 steps.push(Step {
225 recursive: true,
226 selectors: selectors.iter().map(to_match_selector).collect(),
227 });
228 }
229 }
230}
231
232/// Deduplicate positions in-place.
233#[inline]
234fn dedup_positions(v: &mut SmallVec<[usize; 8]>) {
235 v.sort_unstable();
236 v.dedup();
237}
238
239// =============================================================================
240// Public API
241// =============================================================================
242
243impl LoroDoc {
244 /// Subscribe to updates that may affect the given JSONPath query.
245 ///
246 /// ## Behavior
247 ///
248 /// - **Conservative matching**: The callback may fire for changes that don't
249 /// actually affect the query result (false positives), but it will never
250 /// miss a change that does affect it (no false negatives).
251 /// - **Lightweight notifications**: The callback receives no payload. Applications
252 /// should debounce/throttle and re-evaluate the JSONPath if needed.
253 ///
254 /// ## Returns
255 ///
256 /// A `Subscription` handle. Drop it to unsubscribe.
257 #[cfg(feature = "jsonpath")]
258 pub fn subscribe_jsonpath(
259 &self,
260 jsonpath: &str,
261 callback: SubscribeJsonPathCallback,
262 ) -> LoroResult<Subscription> {
263 let query = JSONPathParser::new()
264 .parse(jsonpath)
265 .map_err(|e| LoroError::ArgErr(e.to_string().into_boxed_str()))?;
266
267 let matcher = Arc::new(JsonPathMatcher::new(&query));
268
269 let sub = self.subscribe_root(Arc::new(move |event| {
270 if event.events.is_empty() {
271 return;
272 }
273
274 let matcher = &matcher;
275 let mut fired = false;
276
277 for container_diff in event.events.iter() {
278 if fired {
279 break;
280 }
281
282 // Convert the container's path to PathElem representation
283 let base_path: SmallVec<[PathElem; 8]> = container_diff
284 .path
285 .iter()
286 .map(|(_, idx)| PathElem::from(idx))
287 .collect();
288
289 // Check 1: Does the container path itself match the query?
290 if matcher.may_match(&base_path) {
291 fired = true;
292 break;
293 }
294
295 // Check 2: Map-specific handling - check each changed key
296 if let Diff::Map(map) = &container_diff.diff {
297 let base_positions = matcher.positions_after(&base_path);
298 if base_positions.is_empty() {
299 continue;
300 }
301
302 // If we passed through a Wildcard (filter/wild/slice), any key
303 // change could affect the result - be conservative.
304 let past_wildcard = matcher.passed_through_wildcard(&base_positions);
305
306 for key in map.updated.keys() {
307 let mut extended: SmallVec<[PathElem; 8]> = base_path.clone();
308 extended.push(PathElem::Key(key.as_ref().into()));
309
310 let extended_positions = matcher.positions_after(&extended);
311
312 // Trigger if key path could match OR we're inside a wildcard selection
313 if !extended_positions.is_empty() || past_wildcard {
314 fired = true;
315 break;
316 }
317 }
318
319 if fired {
320 break;
321 }
322 }
323
324 // Check 3: List/Tree/Counter child mutations
325 // These container types can have child changes at unknown indices
326 let has_child_changes = matches!(
327 &container_diff.diff,
328 Diff::List(_) | Diff::Tree(_) | Diff::Unknown
329 );
330 #[cfg(feature = "counter")]
331 let has_child_changes =
332 has_child_changes || matches!(&container_diff.diff, Diff::Counter(_));
333
334 if has_child_changes {
335 let mut extended: SmallVec<[PathElem; 8]> = base_path.clone();
336 extended.push(PathElem::Seq(None)); // "some child changed"
337 if !matcher.positions_after(&extended).is_empty() {
338 fired = true;
339 }
340 }
341 }
342
343 if fired {
344 (callback)();
345 }
346 }));
347
348 Ok(sub)
349 }
350}
351
352// =============================================================================
353// Tests
354// =============================================================================
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359 use crate::{LoroDoc, MapHandler};
360 use std::sync::atomic::{AtomicUsize, Ordering};
361
362 fn make_book(
363 doc: &LoroDoc,
364 idx: usize,
365 title: &str,
366 available: bool,
367 price: i64,
368 ) -> MapHandler {
369 let books = doc.get_list("books");
370 let book = books
371 .insert_container(idx, MapHandler::new_detached())
372 .unwrap();
373 book.insert("title", title).unwrap();
374 book.insert("available", available).unwrap();
375 book.insert("price", price).unwrap();
376 book
377 }
378
379 #[test]
380 fn jsonpath_subscribe_triggers_on_specific_key() {
381 let doc = LoroDoc::new_auto_commit();
382 let first_book = make_book(&doc, 0, "Old", true, 10);
383 doc.commit_then_renew();
384
385 let hit = Arc::new(AtomicUsize::new(0));
386 let hit_ref = hit.clone();
387 let _sub = doc
388 .subscribe_jsonpath(
389 "$.books[0].title",
390 Arc::new(move || {
391 hit_ref.fetch_add(1, Ordering::SeqCst);
392 }),
393 )
394 .unwrap();
395
396 first_book.insert("title", "New").unwrap();
397 doc.commit_then_renew();
398
399 assert!(hit.load(Ordering::SeqCst) >= 1);
400 }
401
402 #[test]
403 fn jsonpath_subscribe_wildcard_on_list() {
404 let doc = LoroDoc::new_auto_commit();
405 make_book(&doc, 0, "A", true, 10);
406 let second_book = make_book(&doc, 1, "B", true, 20);
407 doc.commit_then_renew();
408
409 let hit = Arc::new(AtomicUsize::new(0));
410 let hit_ref = hit.clone();
411 let _sub = doc
412 .subscribe_jsonpath(
413 "$.books[*].price",
414 Arc::new(move || {
415 hit_ref.fetch_add(1, Ordering::SeqCst);
416 }),
417 )
418 .unwrap();
419
420 second_book.insert("price", 25).unwrap();
421 doc.commit_then_renew();
422
423 assert!(hit.load(Ordering::SeqCst) >= 1);
424 }
425
426 #[test]
427 fn jsonpath_subscribe_negative_index() {
428 let doc = LoroDoc::new_auto_commit();
429 make_book(&doc, 0, "A", true, 10);
430 make_book(&doc, 1, "B", true, 20);
431 doc.commit_then_renew();
432
433 let hit = Arc::new(AtomicUsize::new(0));
434 let hit_ref = hit.clone();
435 let _sub = doc
436 .subscribe_jsonpath(
437 "$.books[-1].title",
438 Arc::new(move || {
439 hit_ref.fetch_add(1, Ordering::SeqCst);
440 }),
441 )
442 .unwrap();
443
444 let books = doc.get_list("books");
445 let last = books.get_child_handler(1).unwrap();
446 last.as_map().unwrap().insert("title", "B updated").unwrap();
447 doc.commit_then_renew();
448
449 assert!(hit.load(Ordering::SeqCst) >= 1);
450 }
451
452 #[test]
453 fn jsonpath_subscribe_slice_range() {
454 let doc = LoroDoc::new_auto_commit();
455 make_book(&doc, 0, "A", true, 10);
456 let second_book = make_book(&doc, 1, "B", true, 20);
457 make_book(&doc, 2, "C", true, 30);
458 doc.commit_then_renew();
459
460 let hit = Arc::new(AtomicUsize::new(0));
461 let hit_ref = hit.clone();
462 let _sub = doc
463 .subscribe_jsonpath(
464 "$.books[0:2].title",
465 Arc::new(move || {
466 hit_ref.fetch_add(1, Ordering::SeqCst);
467 }),
468 )
469 .unwrap();
470
471 second_book.insert("title", "B updated").unwrap();
472 doc.commit_then_renew();
473
474 assert!(hit.load(Ordering::SeqCst) >= 1);
475 }
476
477 #[test]
478 fn jsonpath_subscribe_recursive() {
479 let doc = LoroDoc::new_auto_commit();
480 let store = doc.get_map("store");
481 let nested = store
482 .insert_container("inventory", MapHandler::new_detached())
483 .unwrap();
484 nested.insert("total", 3).unwrap();
485 doc.commit_then_renew();
486
487 let hit = Arc::new(AtomicUsize::new(0));
488 let hit_ref = hit.clone();
489 let _sub = doc
490 .subscribe_jsonpath(
491 "$..total",
492 Arc::new(move || {
493 hit_ref.fetch_add(1, Ordering::SeqCst);
494 }),
495 )
496 .unwrap();
497
498 nested.insert("total", 4).unwrap();
499 doc.commit_then_renew();
500
501 assert!(hit.load(Ordering::SeqCst) >= 1);
502 }
503
504 #[test]
505 fn jsonpath_subscribe_filter_treated_as_wildcard() {
506 let doc = LoroDoc::new_auto_commit();
507 make_book(&doc, 0, "A", true, 10);
508 let second_book = make_book(&doc, 1, "B", false, 20);
509 doc.commit_then_renew();
510
511 let hit = Arc::new(AtomicUsize::new(0));
512 let hit_ref = hit.clone();
513 let _sub = doc
514 .subscribe_jsonpath(
515 "$.books[?@.available].title",
516 Arc::new(move || {
517 hit_ref.fetch_add(1, Ordering::SeqCst);
518 }),
519 )
520 .unwrap();
521
522 second_book.insert("available", true).unwrap();
523 doc.commit_then_renew();
524
525 assert!(hit.load(Ordering::SeqCst) >= 1);
526 }
527
528 #[test]
529 fn jsonpath_subscribe_triggers_once_per_commit() {
530 let doc = LoroDoc::new_auto_commit();
531 let book = make_book(&doc, 0, "A", true, 10);
532 doc.commit_then_renew();
533
534 let hit = Arc::new(AtomicUsize::new(0));
535 let hit_ref = hit.clone();
536 let _sub = doc
537 .subscribe_jsonpath(
538 "$.books[0].title",
539 Arc::new(move || {
540 hit_ref.fetch_add(1, Ordering::SeqCst);
541 }),
542 )
543 .unwrap();
544
545 book.insert("title", "X").unwrap();
546 book.insert("title", "Y").unwrap();
547 doc.commit_then_renew();
548
549 assert_eq!(hit.load(Ordering::SeqCst), 1);
550 }
551}