forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

subscription.rs232 lines, 7.5 KiBHistoryRawDownload
1use super::{
2 arena::SharedArena,
3 event::{DiffEvent, DocDiff},
4};
5use crate::{
6 container::idx::ContainerIdx,
7 utils::subscription::{DeferredPanic, SubscriberSet},
8 ContainerDiff, LoroDoc, Subscription,
9};
10use loro_common::{ContainerID, ID};
11use rustc_hash::FxHashMap;
12use smallvec::SmallVec;
13use std::{collections::VecDeque, sync::Arc};
14
15use crate::sync::Mutex;
16/// The callback of the local update.
17pub type LocalUpdateCallback = Box<dyn Fn(&Vec<u8>) -> bool + Send + Sync + 'static>;
18/// The callback of the peer id change. The second argument is the next counter for the peer.
19pub type PeerIdUpdateCallback = Box<dyn Fn(&ID) -> bool + Send + Sync + 'static>;
20#[allow(clippy::unused_unit)]
21pub type Subscriber = Arc<dyn for<'a> Fn(DiffEvent<'a>) + Send + Sync>;
22
23impl LoroDoc {
24 /// Subscribe to the changes of the peer id.
25 pub fn subscribe_peer_id_change(&self, callback: PeerIdUpdateCallback) -> Subscription {
26 let (s, enable) = self.peer_id_change_subs.inner().insert((), callback);
27 enable();
28 s
29 }
30}
31
32struct ObserverInner {
33 subscriber_set: SubscriberSet<Option<ContainerIdx>, Subscriber>,
34 queue: Arc<Mutex<VecDeque<DocDiff>>>,
35}
36
37impl Default for ObserverInner {
38 fn default() -> Self {
39 Self {
40 subscriber_set: SubscriberSet::new(),
41 queue: Arc::new(Mutex::new(VecDeque::new())),
42 }
43 }
44}
45
46pub struct Observer {
47 inner: ObserverInner,
48 arena: SharedArena,
49}
50
51impl std::fmt::Debug for Observer {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 f.debug_struct("Observer").finish()
54 }
55}
56
57impl Observer {
58 pub fn new(arena: SharedArena) -> Self {
59 Self {
60 arena,
61 inner: ObserverInner::default(),
62 }
63 }
64
65 pub fn subscribe(&self, id: &ContainerID, callback: Subscriber) -> Subscription {
66 let idx = self.arena.register_container(id);
67 let inner = &self.inner;
68 let (sub, enable) = inner.subscriber_set.insert(Some(idx), callback);
69 enable();
70 sub
71 }
72
73 pub fn subscribe_root(&self, callback: Subscriber) -> Subscription {
74 let inner = &self.inner;
75 let (sub, enable) = inner.subscriber_set.insert(None, callback);
76 enable();
77 sub
78 }
79
80 pub(crate) fn emit(&self, doc_diff: DocDiff) {
81 let mut panic = DeferredPanic::default();
82 let success = self.emit_inner(doc_diff, &mut panic);
83 if success {
84 let mut e = self.inner.queue.lock().pop_front();
85 while let Some(event) = e {
86 self.emit_inner(event, &mut panic);
87 e = self.inner.queue.lock().pop_front();
88 }
89 }
90 panic.resume();
91 }
92
93 // When emitting changes, we need to make sure that the observer is not locked.
94 /// A subscriber that panics does not stop the others; its panic is put in `panic`.
95 fn emit_inner(&self, doc_diff: DocDiff, panic: &mut DeferredPanic) -> bool {
96 let inner = &self.inner;
97 let mut container_events_map: FxHashMap<ContainerIdx, SmallVec<[&ContainerDiff; 1]>> =
98 Default::default();
99 for container_diff in doc_diff.diff.iter() {
100 self.arena
101 .with_ancestors(container_diff.idx, |ancestor, _| {
102 if inner.subscriber_set.may_include(&Some(ancestor)) {
103 container_events_map
104 .entry(ancestor)
105 .or_default()
106 .push(container_diff);
107 }
108 });
109 }
110
111 {
112 // Check whether we are calling events recursively.
113 // If so, push the event to the queue
114 if inner.subscriber_set.is_recursive_calling(&None)
115 || container_events_map
116 .keys()
117 .any(|x| inner.subscriber_set.is_recursive_calling(&Some(*x)))
118 {
119 drop(container_events_map);
120 inner.queue.lock().push_back(doc_diff);
121 return false;
122 }
123 }
124
125 for (container_idx, container_diffs) in container_events_map {
126 panic.run(|| {
127 inner
128 .subscriber_set
129 .retain(&Some(container_idx), &mut |callback| {
130 (callback)(DiffEvent {
131 current_target: Some(
132 self.arena.get_container_id(container_idx).unwrap(),
133 ),
134 events: &container_diffs,
135 event_meta: &doc_diff,
136 });
137 true
138 })
139 .unwrap()
140 });
141 }
142
143 let events: Vec<_> = doc_diff.diff.iter().collect();
144 panic.run(|| {
145 inner
146 .subscriber_set
147 .retain(&None, &mut |callback| {
148 (callback)(DiffEvent {
149 current_target: None,
150 events: &events,
151 event_meta: &doc_diff,
152 });
153 true
154 })
155 .unwrap()
156 });
157
158 true
159 }
160}
161
162#[cfg(test)]
163mod test {
164 use std::sync::atomic::{AtomicUsize, Ordering};
165
166 use super::*;
167 use crate::{cursor::PosType, handler::HandlerTrait, LoroDoc};
168
169 #[test]
170 fn test_recursive_events() {
171 let loro = Arc::new(LoroDoc::new());
172 let loro_cp = loro.clone();
173 let count = Arc::new(AtomicUsize::new(0));
174 let count_cp = Arc::clone(&count);
175 let _g = loro_cp.subscribe_root(Arc::new(move |_| {
176 count_cp.fetch_add(1, Ordering::SeqCst);
177 let mut txn = loro.txn().unwrap();
178 let text = loro.get_text("id");
179 if text.get_value().as_string().unwrap().len() > 10 {
180 return;
181 }
182 text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode)
183 .unwrap();
184 txn.commit().unwrap();
185 }));
186
187 let loro = loro_cp;
188 let mut txn = loro.txn().unwrap();
189 let text = loro.get_text("id");
190 text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode)
191 .unwrap();
192 txn.commit().unwrap();
193 let count = count.load(Ordering::SeqCst);
194 assert!(count > 2, "{}", count);
195 }
196
197 #[test]
198 fn unsubscribe() {
199 let loro = Arc::new(LoroDoc::new());
200 let count = Arc::new(AtomicUsize::new(0));
201 let count_cp = Arc::clone(&count);
202 let sub = loro.subscribe_root(Arc::new(move |_| {
203 count_cp.fetch_add(1, Ordering::SeqCst);
204 }));
205
206 let text = loro.get_text("id");
207
208 assert_eq!(count.load(Ordering::SeqCst), 0);
209 {
210 let mut txn = loro.txn().unwrap();
211 text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode)
212 .unwrap();
213 txn.commit().unwrap();
214 }
215 assert_eq!(count.load(Ordering::SeqCst), 1);
216 {
217 let mut txn = loro.txn().unwrap();
218 text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode)
219 .unwrap();
220 txn.commit().unwrap();
221 }
222 assert_eq!(count.load(Ordering::SeqCst), 2);
223 sub.unsubscribe();
224 {
225 let mut txn = loro.txn().unwrap();
226 text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode)
227 .unwrap();
228 txn.commit().unwrap();
229 }
230 assert_eq!(count.load(Ordering::SeqCst), 2);
231 }
232}