1use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use indexmap::{IndexMap, IndexSet};
7pub use waft_embedder::{RestorationData, RestorationMap, RestorationUpdate};
8use waft_foundation::OptionRetained;
9use waft_foundation::Ref;
10use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle};
11use waft_scheduler::{FrameCallback, SchedulerBinding};
12
13#[derive(Default)]
93pub struct RestorationManager {
94 change_notifier: ChangeNotifierData,
95 root_bucket: Option<Ref<RestorationBucket>>,
97 pending_root_bucket: bool,
100 root_bucket_is_valid: bool,
101 is_replacing: bool,
102 debug_doing_update: bool,
103 serialization_scheduled: bool,
104 buckets_needing_serialization: IndexSet<Ref<RestorationBucket>>,
105}
106
107impl ChangeNotifier for RestorationManager {
108 fn change_notifier_data(&self) -> &ChangeNotifierData {
109 &self.change_notifier
110 }
111
112 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
113 &mut self.change_notifier
114 }
115}
116
117impl RestorationManager {
118 pub fn instance(app: &mut App) -> Handle<RestorationManager> {
122 app.singleton::<RestorationManager>()
123 }
124
125 pub fn root_bucket(self: Handle<Self>, app: &mut App) -> Option<Handle<RestorationBucket>> {
147 if app.get(self).root_bucket_is_valid {
148 return app.get(self).root_bucket.handle();
149 }
150 if !app.get(self).pending_root_bucket {
151 app.get_mut(self).pending_root_bucket = true;
152 self.get_root_bucket_from_engine(app);
153 }
154 app.get(self).root_bucket.handle()
155 }
156
157 pub fn is_replacing(self: Handle<Self>, app: &App) -> bool {
166 app.get(self).is_replacing
167 }
168
169 fn get_root_bucket_from_engine(self: Handle<Self>, app: &mut App) {
170 let config = app
171 .platform()
172 .restoration()
173 .and_then(|restoration| restoration.get());
174 if !app.get(self).pending_root_bucket {
175 return;
179 }
180 debug_assert!(app.get(self).root_bucket.is_none());
181 self.parse_and_handle_restoration_update_from_engine(app, config);
182 }
183
184 fn parse_and_handle_restoration_update_from_engine(
185 self: Handle<Self>,
186 app: &mut App,
187 update: Option<RestorationUpdate>,
188 ) {
189 let (enabled, data) = match update {
190 Some(update) => (update.enabled, update.data),
191 None => (false, None),
192 };
193 self.handle_restoration_update_from_engine(app, enabled, data);
194 }
195
196 pub fn handle_restoration_update_from_engine(
211 self: Handle<Self>,
212 app: &mut App,
213 enabled: bool,
214 data: Option<RestorationMap>,
215 ) {
216 debug_assert!(enabled || data.is_none());
217
218 let is_replacing = app.get(self).root_bucket_is_valid && enabled;
219 app.get_mut(self).is_replacing = is_replacing;
220 if is_replacing {
221 SchedulerBinding::add_post_frame_callback(
222 app,
223 FrameCallback::new(move |app, _| app.get_mut(self).is_replacing = false),
224 None,
225 );
226 }
227
228 let new_root = enabled.then(|| RestorationBucket::root(app, self, data));
229 let changed = new_root != app.get(self).root_bucket;
230 let this = app.get_mut(self);
231 let old_root = std::mem::replace(&mut this.root_bucket, new_root);
232 this.root_bucket_is_valid = true;
233 this.pending_root_bucket = false;
234
235 if changed {
236 self.notify_listeners(app);
237 if let Some(old_root) = old_root {
238 old_root.dispose(app);
239 }
240 }
241 }
242
243 pub fn send_to_engine(self: Handle<Self>, app: &mut App, encoded_data: RestorationMap) {
248 if let Some(restoration) = app.platform().restoration() {
249 restoration.put(encoded_data);
250 }
251 }
252
253 pub fn schedule_serialization_for(
261 self: Handle<Self>,
262 app: &mut App,
263 bucket: Handle<RestorationBucket>,
264 ) {
265 debug_assert!(app.get(bucket).manager == Some(self));
266 debug_assert!(!app.get(self).debug_doing_update);
267 if let Some(bucket) = bucket.upgrade(app) {
271 app.get_mut(self)
272 .buckets_needing_serialization
273 .insert(bucket);
274 }
275 if !app.get(self).serialization_scheduled {
276 app.get_mut(self).serialization_scheduled = true;
277 SchedulerBinding::add_post_frame_callback(
278 app,
279 FrameCallback::new(move |app, _| self.do_serialization(app)),
280 None,
281 );
282 }
283 }
284
285 pub fn unschedule_serialization_for(
293 self: Handle<Self>,
294 app: &mut App,
295 bucket: Handle<RestorationBucket>,
296 ) {
297 debug_assert!(app.get(bucket).manager == Some(self));
298 debug_assert!(!app.get(self).debug_doing_update);
299 app.get_mut(self)
300 .buckets_needing_serialization
301 .shift_remove(&bucket);
302 }
303
304 fn do_serialization(self: Handle<Self>, app: &mut App) {
305 if !app.get(self).serialization_scheduled {
306 return;
307 }
308 if cfg!(debug_assertions) {
309 app.get_mut(self).debug_doing_update = true;
310 }
311 app.get_mut(self).serialization_scheduled = false;
312
313 let buckets = std::mem::take(&mut app.get_mut(self).buckets_needing_serialization);
314 for bucket in buckets {
315 bucket.finalize(app);
316 }
317 let root = app
318 .get(self)
319 .root_bucket
320 .handle()
321 .expect("a bucket that scheduled serialization is in the root bucket's hierarchy");
322 let data = root.with_raw_data(app, |data| data.clone());
323 self.send_to_engine(app, data);
324
325 if cfg!(debug_assertions) {
326 app.get_mut(self).debug_doing_update = false;
327 }
328 }
329
330 pub fn flush_data(self: Handle<Self>, app: &mut App) {
348 debug_assert!(!app.get(self).debug_doing_update);
349 if SchedulerBinding::has_scheduled_frame(app) {
350 return;
351 }
352 self.do_serialization(app);
353 debug_assert!(!app.get(self).serialization_scheduled);
354 }
355
356 pub fn dispose(self: Handle<Self>, app: &mut App) {
358 if let Some(root_bucket) = app.get(self).root_bucket.handle() {
359 root_bucket.dispose(app);
360 }
361 ChangeNotifierData::dispose(app, self);
362 }
363}
364
365const CHILDREN_MAP_KEY: &str = "c";
366const VALUES_MAP_KEY: &str = "v";
367
368fn data_key(restoration_id: &str) -> RestorationData {
370 RestorationData::String(restoration_id.to_string())
371}
372
373fn sub_map<'a>(data: &'a mut RestorationMap, key: &str) -> &'a mut RestorationMap {
375 data.entry(data_key(key))
376 .or_insert_with(|| RestorationData::Map(RestorationMap::new()))
377 .as_map_mut()
378 .expect("the values and children entries of raw data are maps")
379}
380
381enum RawData {
387 Own(RestorationMap),
388 InParent,
389}
390
391pub struct RestorationBucket {
458 manager: Option<Handle<RestorationManager>>,
459 parent: Option<Handle<RestorationBucket>>,
460 raw_data: RawData,
461 restoration_id: String,
462 claimed_children: IndexMap<String, Ref<RestorationBucket>>,
465 children_to_add: IndexMap<String, Vec<Ref<RestorationBucket>>>,
468 needs_serialization: bool,
469 debug_owner: Option<Rc<dyn Debug>>,
470}
471
472impl Debug for RestorationBucket {
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 write!(
475 f,
476 "RestorationBucket(restorationId: {}, owner: {})",
477 self.restoration_id,
478 owner_description(self)
479 )
480 }
481}
482
483fn owner_description(bucket: &RestorationBucket) -> String {
485 match &bucket.debug_owner {
486 Some(owner) => format!("{owner:?}"),
487 None => "None".to_string(),
488 }
489}
490
491impl RestorationBucket {
492 pub fn empty(
500 app: &mut App,
501 restoration_id: &str,
502 debug_owner: Option<Rc<dyn Debug>>,
503 ) -> Ref<RestorationBucket> {
504 let bucket = RestorationBucket::new(restoration_id, RestorationMap::new(), debug_owner);
505 let bucket = app.create(bucket);
506 app.expect_dispose(&bucket);
507 bucket
508 }
509
510 pub fn root(
533 app: &mut App,
534 manager: Handle<RestorationManager>,
535 raw_data: Option<RestorationMap>,
536 ) -> Ref<RestorationBucket> {
537 let debug_owner: Option<Rc<dyn Debug>> =
538 cfg!(debug_assertions).then(|| Rc::new(manager) as Rc<dyn Debug>);
539 let mut bucket = RestorationBucket::new("root", raw_data.unwrap_or_default(), debug_owner);
540 bucket.manager = Some(manager);
541 let bucket = app.create(bucket);
542 app.expect_dispose(&bucket);
543 bucket
544 }
545
546 pub fn child(
557 app: &mut App,
558 restoration_id: &str,
559 parent: Handle<RestorationBucket>,
560 debug_owner: Option<Rc<dyn Debug>>,
561 ) -> Ref<RestorationBucket> {
562 debug_assert!(parent.with_raw_children(app, |children| {
563 children.contains_key(&data_key(restoration_id))
564 }));
565 let mut bucket = RestorationBucket::new(restoration_id, RestorationMap::new(), debug_owner);
566 bucket.raw_data = RawData::InParent;
567 bucket.manager = app.get(parent).manager;
568 bucket.parent = Some(parent);
569 let bucket = app.create(bucket);
570 app.expect_dispose(&bucket);
571 bucket
572 }
573
574 fn new(
575 restoration_id: &str,
576 raw_data: RestorationMap,
577 debug_owner: Option<Rc<dyn Debug>>,
578 ) -> RestorationBucket {
579 RestorationBucket {
580 manager: None,
581 parent: None,
582 raw_data: RawData::Own(raw_data),
583 restoration_id: restoration_id.to_string(),
584 claimed_children: IndexMap::new(),
585 children_to_add: IndexMap::new(),
586 needs_serialization: false,
587 debug_owner: cfg!(debug_assertions).then_some(debug_owner).flatten(),
588 }
589 }
590
591 pub fn debug_owner(self: Handle<Self>, app: &App) -> Option<Rc<dyn Debug>> {
597 debug_assert!(self.debug_assert_not_disposed(app));
598 app.get(self).debug_owner.clone()
599 }
600
601 pub fn is_replacing(self: Handle<Self>, app: &App) -> bool {
611 app.get(self)
612 .manager
613 .is_some_and(|manager| manager.is_replacing(app))
614 }
615
616 pub fn restoration_id(self: Handle<Self>, app: &App) -> &str {
620 debug_assert!(self.debug_assert_not_disposed(app));
621 &app.get(self).restoration_id
622 }
623
624 fn with_raw_data<R>(
626 self: Handle<Self>,
627 app: &mut App,
628 action: impl FnOnce(&mut RestorationMap) -> R,
629 ) -> R {
630 let mut ancestry = Vec::new();
631 let mut owner = self;
632 while matches!(app.get(owner).raw_data, RawData::InParent) {
633 ancestry.push(data_key(&app.get(owner).restoration_id));
634 owner = app
635 .get(owner)
636 .parent
637 .expect("a bucket whose map lives in its parent has one");
638 }
639 let mut map = match &mut app.get_mut(owner).raw_data {
640 RawData::Own(map) => map,
641 RawData::InParent => unreachable!("the walk ends at the bucket that owns the map"),
642 };
643 for restoration_id in ancestry.iter().rev() {
644 map = map
645 .get_mut(&data_key(CHILDREN_MAP_KEY))
646 .and_then(RestorationData::as_map_mut)
647 .and_then(|children| children.get_mut(restoration_id))
648 .and_then(RestorationData::as_map_mut)
649 .expect("a stored bucket's map is under its parent's children");
650 }
651 action(map)
652 }
653
654 fn with_raw_children<R>(
656 self: Handle<Self>,
657 app: &mut App,
658 action: impl FnOnce(&mut RestorationMap) -> R,
659 ) -> R {
660 self.with_raw_data(app, |data| action(sub_map(data, CHILDREN_MAP_KEY)))
661 }
662
663 fn with_raw_values<R>(
665 self: Handle<Self>,
666 app: &mut App,
667 action: impl FnOnce(&mut RestorationMap) -> R,
668 ) -> R {
669 self.with_raw_data(app, |data| action(sub_map(data, VALUES_MAP_KEY)))
670 }
671
672 pub fn read(
686 self: Handle<Self>,
687 app: &mut App,
688 restoration_id: &str,
689 ) -> Option<RestorationData> {
690 debug_assert!(self.debug_assert_not_disposed(app));
691 self.with_raw_values(app, |values| values.get(&data_key(restoration_id)).cloned())
692 }
693
694 pub fn write(
710 self: Handle<Self>,
711 app: &mut App,
712 restoration_id: &str,
713 value: impl Into<RestorationData>,
714 ) {
715 debug_assert!(self.debug_assert_not_disposed(app));
716 let value = value.into();
717 let key = data_key(restoration_id);
718 let written = self.with_raw_values(app, |values| {
719 if values.get(&key) != Some(&value) || !values.contains_key(&key) {
720 values.insert(key, value);
721 return true;
722 }
723 false
724 });
725 if written {
726 self.mark_needs_serialization(app);
727 }
728 }
729
730 pub fn remove(
743 self: Handle<Self>,
744 app: &mut App,
745 restoration_id: &str,
746 ) -> Option<RestorationData> {
747 debug_assert!(self.debug_assert_not_disposed(app));
748 let key = data_key(restoration_id);
749 let (result, needs_update) = self.with_raw_data(app, |data| {
750 let values = sub_map(data, VALUES_MAP_KEY);
751 let needs_update = values.contains_key(&key);
752 let result = values.shift_remove(&key);
753 let emptied = values.is_empty();
754 if emptied {
755 data.shift_remove(&data_key(VALUES_MAP_KEY));
756 }
757 (result, needs_update)
758 });
759 if needs_update {
760 self.mark_needs_serialization(app);
761 }
762 result
763 }
764
765 pub fn contains(self: Handle<Self>, app: &mut App, restoration_id: &str) -> bool {
774 debug_assert!(self.debug_assert_not_disposed(app));
775 self.with_raw_values(app, |values| values.contains_key(&data_key(restoration_id)))
776 }
777
778 pub fn claim_child(
803 self: Handle<Self>,
804 app: &mut App,
805 restoration_id: &str,
806 debug_owner: Option<Rc<dyn Debug>>,
807 ) -> Ref<RestorationBucket> {
808 debug_assert!(self.debug_assert_not_disposed(app));
809 let claimed = app.get(self).claimed_children.contains_key(restoration_id);
824 let stored = self.with_raw_children(app, |children| {
825 children.contains_key(&data_key(restoration_id))
826 });
827 if claimed || !stored {
828 let child = RestorationBucket::empty(app, restoration_id, debug_owner);
829 self.adopt_child(app, &child);
830 return child;
831 }
832
833 let child = RestorationBucket::child(app, restoration_id, self, debug_owner);
835 app.get_mut(self)
836 .claimed_children
837 .insert(restoration_id.to_string(), child.clone());
838 child
839 }
840
841 pub fn adopt_child(self: Handle<Self>, app: &mut App, child: &Ref<RestorationBucket>) {
855 debug_assert!(self.debug_assert_not_disposed(app));
856 let kept = child.clone();
857 let child = kept.handle();
858 if app.get(child).parent != Some(self) {
859 if let Some(old_parent) = app.get(child).parent {
860 old_parent.remove_child_data(app, child);
861 }
862 app.get_mut(child).parent = Some(self);
863 self.add_child_data(app, kept);
864 if app.get(child).manager != app.get(self).manager {
865 self.recursively_update_manager(app, child);
866 }
867 }
868 debug_assert!(app.get(child).parent == Some(self));
869 debug_assert!(app.get(child).manager == app.get(self).manager);
870 }
871
872 fn drop_child(self: Handle<Self>, app: &mut App, child: Handle<RestorationBucket>) {
873 debug_assert!(app.get(child).parent == Some(self));
874 self.remove_child_data(app, child);
875 app.get_mut(child).parent = None;
876 if app.get(child).manager.is_some() {
877 child.update_manager(app, None);
878 child.visit_children(app, |app, grandchild| {
879 self.recursively_update_manager(app, grandchild);
880 });
881 }
882 }
883
884 fn mark_needs_serialization(self: Handle<Self>, app: &mut App) {
885 if !app.get(self).needs_serialization {
886 app.get_mut(self).needs_serialization = true;
887 if let Some(manager) = app.get(self).manager {
888 manager.schedule_serialization_for(app, self);
889 }
890 }
891 }
892
893 pub fn finalize(self: Handle<Self>, app: &mut App) {
896 debug_assert!(self.debug_assert_not_disposed(app));
897 debug_assert!(app.get(self).needs_serialization);
898 app.get_mut(self).needs_serialization = false;
899 debug_assert!(self.debug_assert_integrity(app));
900 }
901
902 fn recursively_update_manager(self: Handle<Self>, app: &mut App, bucket: Handle<Self>) {
903 bucket.update_manager(app, app.get(self).manager);
904 bucket.visit_children(app, |app, child| {
905 self.recursively_update_manager(app, child)
906 });
907 }
908
909 fn update_manager(
910 self: Handle<Self>,
911 app: &mut App,
912 new_manager: Option<Handle<RestorationManager>>,
913 ) {
914 if app.get(self).manager == new_manager {
915 return;
916 }
917 if app.get(self).needs_serialization
918 && let Some(manager) = app.get(self).manager
919 {
920 manager.unschedule_serialization_for(app, self);
921 }
922 app.get_mut(self).manager = new_manager;
923 if app.get(self).needs_serialization && app.get(self).manager.is_some() {
924 app.get_mut(self).needs_serialization = false;
925 self.mark_needs_serialization(app);
926 }
927 }
928
929 fn debug_assert_integrity(self: Handle<Self>, app: &App) -> bool {
930 if !cfg!(debug_assertions) {
931 return true;
932 }
933 let this = app.get(self);
934 if this.children_to_add.is_empty() {
935 return true;
936 }
937 let mut error = vec![
938 "Multiple owners claimed child RestorationBuckets with the same IDs.".to_string(),
939 format!("The following IDs were claimed multiple times from the parent {this:?}:"),
940 ];
941 for (restoration_id, buckets) in &this.children_to_add {
942 debug_assert!(!buckets.is_empty());
943 error.push(format!(" * \"{restoration_id}\" was claimed by:"));
944 for bucket in buckets {
945 error.push(format!(" * {}", owner_description(app.get(bucket))));
946 }
947 let owner = this
948 .claimed_children
949 .get(restoration_id)
950 .expect("a pending child implies a current owner of the same ID");
951 error.push(format!(
952 " * {} (current owner)",
953 owner_description(app.get(owner))
954 ));
955 }
956 panic!("{}", error.join("\n"));
957 }
958
959 fn remove_child_data(self: Handle<Self>, app: &mut App, child: Handle<RestorationBucket>) {
960 debug_assert!(app.get(child).parent == Some(self));
961 let child_id = app.get(child).restoration_id.clone();
962 let removed = app.get_mut(self).claimed_children.shift_remove(&child_id);
963 if removed.handle() == Some(child) {
964 child.reclaim_raw_data(app);
965 let pending_child = app
966 .get_mut(self)
967 .children_to_add
968 .get_mut(&child_id)
969 .and_then(Vec::pop);
970 if let Some(to_add) = pending_child {
971 self.finalize_add_child_data(app, to_add);
972 if app.get(self).children_to_add[&child_id].is_empty() {
973 app.get_mut(self).children_to_add.shift_remove(&child_id);
974 }
975 }
976 let no_children = self.with_raw_children(app, |children| children.is_empty());
977 if no_children {
978 self.with_raw_data(app, |data| data.shift_remove(&data_key(CHILDREN_MAP_KEY)));
979 }
980 self.mark_needs_serialization(app);
981 return;
982 }
983 let Some(pending) = app.get_mut(self).children_to_add.get_mut(&child_id) else {
984 return;
985 };
986 if let Some(index) = pending.iter().position(|bucket| *bucket == child) {
987 pending.remove(index);
988 }
989 if pending.is_empty() {
990 app.get_mut(self).children_to_add.shift_remove(&child_id);
991 }
992 }
993
994 fn add_child_data(self: Handle<Self>, app: &mut App, child: Ref<RestorationBucket>) {
995 debug_assert!(app.get(&child).parent == Some(self));
996 let child_id = app.get(&child).restoration_id.clone();
997 if app.get(self).claimed_children.contains_key(&child_id) {
998 app.get_mut(self)
1002 .children_to_add
1003 .entry(child_id)
1004 .or_default()
1005 .push(child);
1006 self.mark_needs_serialization(app);
1007 return;
1008 }
1009 self.finalize_add_child_data(app, child);
1010 self.mark_needs_serialization(app);
1011 }
1012
1013 fn finalize_add_child_data(self: Handle<Self>, app: &mut App, child: Ref<RestorationBucket>) {
1014 let child_id = app.get(&child).restoration_id.clone();
1015 debug_assert!(!app.get(self).claimed_children.contains_key(&child_id));
1016 debug_assert!(
1017 self.with_raw_children(app, |children| !children.contains_key(&data_key(&child_id)))
1018 );
1019 let child_handle = child.handle();
1020 app.get_mut(self)
1021 .claimed_children
1022 .insert(child_id.clone(), child);
1023 let child = child_handle;
1024 let data = match std::mem::replace(&mut app.get_mut(child).raw_data, RawData::InParent) {
1025 RawData::Own(data) => data,
1026 RawData::InParent => unreachable!("a bucket being stored owns its map"),
1027 };
1028 self.with_raw_children(app, |children| {
1029 children.insert(data_key(&child_id), RestorationData::Map(data));
1030 });
1031 }
1032
1033 fn reclaim_raw_data(self: Handle<Self>, app: &mut App) {
1036 if matches!(app.get(self).raw_data, RawData::Own(_)) {
1037 return;
1038 }
1039 let parent = app
1040 .get(self)
1041 .parent
1042 .expect("a bucket whose map lives in its parent has one");
1043 let key = data_key(&app.get(self).restoration_id);
1044 let data = parent
1045 .with_raw_children(app, |children| children.shift_remove(&key))
1046 .and_then(RestorationData::into_map)
1047 .expect("a stored bucket's map is under its parent's children");
1048 app.get_mut(self).raw_data = RawData::Own(data);
1049 }
1050
1051 fn visit_children(
1052 self: Handle<Self>,
1053 app: &mut App,
1054 visitor: impl Fn(&mut App, Handle<RestorationBucket>),
1055 ) {
1056 let this = app.get(self);
1057 let children: Vec<Handle<RestorationBucket>> = this
1058 .claimed_children
1059 .values()
1060 .map(|child| child.handle())
1061 .chain(
1062 this.children_to_add
1063 .values()
1064 .flatten()
1065 .map(|child| child.handle()),
1066 )
1067 .collect();
1068 for child in children {
1069 visitor(app, child);
1070 }
1071 }
1072
1073 pub fn rename(self: Handle<Self>, app: &mut App, new_restoration_id: &str) {
1086 debug_assert!(self.debug_assert_not_disposed(app));
1087 if new_restoration_id == app.get(self).restoration_id {
1088 return;
1089 }
1090 let kept = self.upgrade(app);
1092 if let Some(parent) = app.get(self).parent {
1093 parent.remove_child_data(app, self);
1094 }
1095 app.get_mut(self).restoration_id = new_restoration_id.to_string();
1096 if let Some(parent) = app.get(self).parent
1097 && let Some(kept) = kept
1098 {
1099 parent.add_child_data(app, kept);
1100 }
1101 }
1102
1103 pub fn dispose(self: Handle<Self>, app: &mut App) {
1116 debug_assert!(self.debug_assert_not_disposed(app));
1117 self.visit_children(app, |app, child| self.drop_child(app, child));
1118 app.get_mut(self).claimed_children.clear();
1119 app.get_mut(self).children_to_add.clear();
1120 if let Some(parent) = app.get(self).parent {
1121 parent.remove_child_data(app, self);
1122 }
1123 app.get_mut(self).parent = None;
1124 self.update_manager(app, None);
1125 app.mark_disposed(self);
1126 }
1127
1128 fn debug_assert_not_disposed(self: Handle<Self>, app: &App) -> bool {
1129 assert!(
1130 app.contains(self) && !app.is_disposed(self),
1131 "A RestorationBucket was used after being disposed.\n\
1132 Once you have called dispose() on a RestorationBucket, it can no longer be used."
1133 );
1134 true
1135 }
1136}
1137
1138#[cfg(test)]
1139mod tests {
1140 use std::cell::{Cell, RefCell};
1141 use std::panic::{AssertUnwindSafe, catch_unwind};
1142 use std::time::Duration;
1143 use waft_foundation::AppCell;
1144
1145 use waft_embedder::Restoration;
1146 use waft_foundation::{ListenableObject, Listener};
1147 use waft_scheduler::FrameTarget;
1148 use waft_test::{IMPLICIT_VIEW_ID, TestPlatform};
1149
1150 use super::*;
1151
1152 #[derive(Default)]
1155 struct RecordingRestoration {
1156 stored: RefCell<Option<RestorationUpdate>>,
1157 puts: RefCell<Vec<RestorationMap>>,
1158 gets: Cell<usize>,
1159 }
1160
1161 impl Restoration for RecordingRestoration {
1162 fn get(&self) -> Option<RestorationUpdate> {
1163 self.gets.set(self.gets.get() + 1);
1164 self.stored.borrow().clone()
1165 }
1166
1167 fn put(&self, data: RestorationMap) {
1168 self.puts.borrow_mut().push(data);
1169 }
1170 }
1171
1172 struct Fixture {
1173 cell: Rc<AppCell>,
1174 restoration: Rc<RecordingRestoration>,
1175 manager: Handle<RestorationManager>,
1176 }
1177
1178 impl Fixture {
1179 fn new() -> Fixture {
1180 let restoration = Rc::new(RecordingRestoration::default());
1181 let platform = TestPlatform::new()
1183 .with_restoration(restoration.clone())
1184 .with_views(&[IMPLICIT_VIEW_ID]);
1185 let cell = AppCell::with_platform(Rc::new(platform));
1186 let mut app = cell.borrow_mut();
1187 let manager = RestorationManager::instance(&mut app);
1188 drop(app);
1189 Fixture {
1190 cell,
1191 restoration,
1192 manager,
1193 }
1194 }
1195
1196 fn restored(data: RestorationMap) -> (Fixture, Handle<RestorationBucket>) {
1198 let mut fixture = Fixture::new();
1199 fixture.push_from_host(true, Some(data));
1200 let root = fixture
1201 .manager
1202 .root_bucket(&mut fixture.cell.borrow_mut())
1203 .expect("restoration is enabled");
1204 (fixture, root)
1205 }
1206
1207 fn push_from_host(&mut self, enabled: bool, data: Option<RestorationMap>) {
1209 self.manager.handle_restoration_update_from_engine(
1210 &mut self.cell.borrow_mut(),
1211 enabled,
1212 data,
1213 );
1214 }
1215
1216 fn serialize(&mut self) -> Vec<RestorationMap> {
1218 self.manager.flush_data(&mut self.cell.borrow_mut());
1219 self.restoration.puts.borrow_mut().drain(..).collect()
1220 }
1221
1222 fn serialized(&mut self) -> Option<RestorationMap> {
1224 let mut puts = self.serialize();
1225 assert!(puts.len() <= 1, "one serialization sends one message");
1226 puts.pop()
1227 }
1228
1229 fn pump(&mut self) {
1230 let views = [IMPLICIT_VIEW_ID];
1231 SchedulerBinding::handle_begin_frame(
1232 &mut self.cell.borrow_mut(),
1233 &views,
1234 Some(Duration::ZERO),
1235 );
1236 self.cell.borrow_mut().drain_microtasks();
1237 SchedulerBinding::handle_draw_frame(&mut self.cell.borrow_mut(), &views);
1238 self.cell.borrow_mut().drain_microtasks();
1239 }
1240 }
1241
1242 fn map<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
1243 entries
1244 .into_iter()
1245 .map(|(key, value)| (RestorationData::from(key), value))
1246 .collect()
1247 }
1248
1249 fn raw_data_set() -> RestorationMap {
1251 map([
1252 (
1253 "v",
1254 map([("value1", 10i64.into()), ("value2", "Hello".into())]).into(),
1255 ),
1256 (
1257 "c",
1258 map([(
1259 "child1",
1260 map([("v", map([("foo", 22i64.into())]).into())]).into(),
1261 )])
1262 .into(),
1263 ),
1264 ])
1265 }
1266
1267 fn other_raw_data_set() -> RestorationMap {
1269 map([
1270 ("v", map([("foo", 33i64.into())]).into()),
1271 (
1272 "c",
1273 map([(
1274 "childFoo",
1275 map([("v", map([("bar", "Hello".into())]).into())]).into(),
1276 )])
1277 .into(),
1278 ),
1279 ])
1280 }
1281
1282 fn at<'a>(data: &'a RestorationMap, path: &[&str]) -> Option<&'a RestorationData> {
1284 let (last, parents) = path.split_last()?;
1285 let mut map = data;
1286 for key in parents {
1287 map = map.get(&RestorationData::from(*key))?.as_map()?;
1288 }
1289 map.get(&RestorationData::from(*last))
1290 }
1291
1292 fn owner(name: &'static str) -> Option<Rc<dyn Debug>> {
1293 Some(Rc::new(name))
1294 }
1295
1296 fn panic_message(error: &Box<dyn std::any::Any + Send>) -> String {
1297 error
1298 .downcast_ref::<String>()
1299 .cloned()
1300 .or_else(|| error.downcast_ref::<&str>().map(|text| text.to_string()))
1301 .unwrap_or_default()
1302 }
1303
1304 #[test]
1305 fn the_root_bucket_comes_from_the_host_and_is_asked_for_once() {
1306 let fixture = Fixture::new();
1307 *fixture.restoration.stored.borrow_mut() = Some(RestorationUpdate {
1308 enabled: true,
1309 data: Some(raw_data_set()),
1310 });
1311
1312 let root = fixture
1313 .manager
1314 .root_bucket(&mut fixture.cell.borrow_mut())
1315 .expect("the host enabled restoration");
1316 assert_eq!(fixture.restoration.gets.get(), 1);
1317 assert_eq!(root.restoration_id(&fixture.cell.borrow()), "root");
1318 assert_eq!(
1319 root.read(&mut fixture.cell.borrow_mut(), "value1"),
1320 Some(10i64.into())
1321 );
1322 assert_eq!(
1323 root.read(&mut fixture.cell.borrow_mut(), "value2"),
1324 Some("Hello".into())
1325 );
1326
1327 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", None);
1328 assert_eq!(
1329 child.read(&mut fixture.cell.borrow_mut(), "foo"),
1330 Some(22i64.into())
1331 );
1332
1333 assert_eq!(
1334 fixture.manager.root_bucket(&mut fixture.cell.borrow_mut()),
1335 Some(root)
1336 );
1337 assert_eq!(
1338 fixture.restoration.gets.get(),
1339 1,
1340 "the host is asked once, then the answer is kept"
1341 );
1342 }
1343
1344 #[test]
1345 fn data_received_before_the_first_access_is_used_without_asking_the_host() {
1346 let mut fixture = Fixture::new();
1347 fixture.push_from_host(true, Some(raw_data_set()));
1348
1349 let root = fixture.manager.root_bucket(&mut fixture.cell.borrow_mut());
1350 assert!(root.is_some());
1351 assert_eq!(fixture.restoration.gets.get(), 0);
1352 }
1353
1354 #[test]
1355 fn new_data_replaces_the_root_bucket_and_notifies_listeners() {
1356 let (mut fixture, root) = Fixture::restored(raw_data_set());
1357 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", None);
1358 assert_eq!(
1359 child.read(&mut fixture.cell.borrow_mut(), "foo"),
1360 Some(22i64.into())
1361 );
1362
1363 let notifications = Rc::new(Cell::new(0));
1364 let counter = Rc::clone(¬ifications);
1365 fixture.manager.add_listener(
1366 &mut fixture.cell.borrow_mut(),
1367 Listener::new(move |_app| counter.set(counter.get() + 1)),
1368 );
1369
1370 fixture.push_from_host(true, Some(other_raw_data_set()));
1371 assert_eq!(notifications.get(), 1);
1372
1373 let new_root = fixture
1374 .manager
1375 .root_bucket(&mut fixture.cell.borrow_mut())
1376 .expect("restoration is still enabled");
1377 assert_ne!(new_root, root);
1378 assert!(
1379 fixture.cell.borrow().is_disposed(root),
1380 "the old root was disposed"
1381 );
1382
1383 child.dispose(&mut fixture.cell.borrow_mut());
1384
1385 assert_eq!(
1386 new_root.read(&mut fixture.cell.borrow_mut(), "foo"),
1387 Some(33i64.into())
1388 );
1389 assert_eq!(
1390 new_root.read(&mut fixture.cell.borrow_mut(), "value1"),
1391 None
1392 );
1393 let new_child = new_root.claim_child(&mut fixture.cell.borrow_mut(), "childFoo", None);
1394 assert_eq!(
1395 new_child.read(&mut fixture.cell.borrow_mut(), "bar"),
1396 Some("Hello".into())
1397 );
1398 }
1399
1400 #[test]
1401 fn there_is_no_root_bucket_while_restoration_is_disabled() {
1402 let mut fixture = Fixture::new();
1403 *fixture.restoration.stored.borrow_mut() = Some(RestorationUpdate {
1404 enabled: false,
1405 data: None,
1406 });
1407 let notifications = Rc::new(Cell::new(0));
1408 let counter = Rc::clone(¬ifications);
1409 fixture.manager.add_listener(
1410 &mut fixture.cell.borrow_mut(),
1411 Listener::new(move |_app| counter.set(counter.get() + 1)),
1412 );
1413
1414 assert_eq!(
1415 fixture.manager.root_bucket(&mut fixture.cell.borrow_mut()),
1416 None
1417 );
1418 assert_eq!(notifications.get(), 0);
1419
1420 fixture.push_from_host(true, Some(raw_data_set()));
1421 assert_eq!(notifications.get(), 1);
1422 assert!(
1423 fixture
1424 .manager
1425 .root_bucket(&mut fixture.cell.borrow_mut())
1426 .is_some()
1427 );
1428
1429 fixture.push_from_host(false, None);
1430 assert_eq!(notifications.get(), 2);
1431 assert_eq!(
1432 fixture.manager.root_bucket(&mut fixture.cell.borrow_mut()),
1433 None
1434 );
1435 }
1436
1437 #[test]
1438 fn a_host_that_stores_nothing_leaves_restoration_off() {
1439 let fixture = Fixture::new();
1440 assert_eq!(
1441 fixture.manager.root_bucket(&mut fixture.cell.borrow_mut()),
1442 None
1443 );
1444 assert_eq!(fixture.restoration.gets.get(), 1);
1445 }
1446
1447 #[test]
1448 fn is_replacing_is_true_until_the_end_of_the_next_frame() {
1449 let (mut fixture, root) = Fixture::restored(raw_data_set());
1450 assert!(!fixture.manager.is_replacing(&fixture.cell.borrow()));
1451 assert!(!root.is_replacing(&fixture.cell.borrow()));
1452
1453 fixture.push_from_host(true, None);
1454 let new_root = fixture
1455 .manager
1456 .root_bucket(&mut fixture.cell.borrow_mut())
1457 .expect("restoration is enabled");
1458 assert_ne!(new_root, root);
1459 assert!(fixture.manager.is_replacing(&fixture.cell.borrow()));
1460 assert!(new_root.is_replacing(&fixture.cell.borrow()));
1461
1462 fixture.pump();
1463 assert!(!fixture.manager.is_replacing(&fixture.cell.borrow()));
1464 assert!(!new_root.is_replacing(&fixture.cell.borrow()));
1465
1466 fixture.push_from_host(false, None);
1467 assert!(!fixture.manager.is_replacing(&fixture.cell.borrow()));
1468 }
1469
1470 #[test]
1471 fn scheduled_serialization_reaches_the_host_at_the_end_of_the_frame() {
1472 let (mut fixture, root) = Fixture::restored(raw_data_set());
1473 root.write(&mut fixture.cell.borrow_mut(), "value1", 22i64);
1474 assert!(fixture.restoration.puts.borrow().is_empty());
1475
1476 fixture.pump();
1477
1478 let puts = fixture
1479 .restoration
1480 .puts
1481 .borrow_mut()
1482 .drain(..)
1483 .collect::<Vec<_>>();
1484 assert_eq!(puts.len(), 1);
1485 assert_eq!(at(&puts[0], &["v", "value1"]), Some(&22i64.into()));
1486 }
1487
1488 #[test]
1491 fn a_disposed_bucket_is_not_kept_for_serialization() {
1492 let (mut fixture, root) = Fixture::restored(raw_data_set());
1493 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", None);
1494 child.write(&mut fixture.cell.borrow_mut(), "foo", 1i64);
1495 let id = child.handle();
1496 child.dispose(&mut fixture.cell.borrow_mut());
1497 drop(child);
1498 fixture.cell.checkpoint();
1499 assert!(!fixture.cell.borrow().contains(id));
1500
1501 fixture.pump();
1502 assert_eq!(fixture.restoration.puts.borrow().len(), 1);
1503 }
1504
1505 #[test]
1508 fn a_bucket_nothing_keeps_still_schedules_the_serialization() {
1509 let (mut fixture, root) = Fixture::restored(raw_data_set());
1510 let child = RestorationBucket::child(&mut fixture.cell.borrow_mut(), "child1", root, None);
1511 let id = child.handle();
1512 drop(child);
1513 id.write(&mut fixture.cell.borrow_mut(), "foo", 1i64);
1514 fixture.cell.checkpoint();
1515 assert!(!fixture.cell.borrow().contains(id));
1516
1517 fixture.pump();
1518 assert_eq!(fixture.restoration.puts.borrow().len(), 1);
1519 }
1520
1521 #[test]
1522 fn flush_data_waits_for_a_scheduled_frame_and_otherwise_sends_at_once() {
1523 let (mut fixture, root) = Fixture::restored(raw_data_set());
1524 SchedulerBinding::schedule_frame(&mut fixture.cell.borrow_mut(), FrameTarget::EveryView);
1525 root.write(&mut fixture.cell.borrow_mut(), "foo", 1i64);
1526
1527 fixture.manager.flush_data(&mut fixture.cell.borrow_mut());
1528 assert!(
1529 fixture.restoration.puts.borrow().is_empty(),
1530 "the scheduled frame will flush it"
1531 );
1532
1533 fixture.pump();
1534 assert_eq!(fixture.restoration.puts.borrow_mut().drain(..).count(), 1);
1535
1536 root.write(&mut fixture.cell.borrow_mut(), "foo", 2i64);
1537 let data = fixture
1538 .serialized()
1539 .expect("a write schedules serialization");
1540 assert_eq!(at(&data, &["v", "foo"]), Some(&2i64.into()));
1541 }
1542
1543 #[test]
1544 fn nothing_is_sent_when_no_bucket_asked_for_serialization() {
1545 let (mut fixture, _root) = Fixture::restored(raw_data_set());
1546 assert!(fixture.serialized().is_none());
1547 }
1548
1549 #[test]
1550 fn root_bucket_values() {
1551 let (mut fixture, root) = Fixture::restored(raw_data_set());
1552 assert_eq!(
1553 root.debug_owner(&fixture.cell.borrow()).is_some(),
1554 cfg!(debug_assertions)
1555 );
1556 assert_eq!(
1557 root.read(&mut fixture.cell.borrow_mut(), "value1"),
1558 Some(10i64.into())
1559 );
1560 assert_eq!(
1561 root.read(&mut fixture.cell.borrow_mut(), "value2"),
1562 Some("Hello".into())
1563 );
1564 assert_eq!(root.read(&mut fixture.cell.borrow_mut(), "value3"), None);
1565 assert!(fixture.serialized().is_none());
1566
1567 root.write(&mut fixture.cell.borrow_mut(), "value1", 22i64);
1568 assert_eq!(
1569 root.read(&mut fixture.cell.borrow_mut(), "value1"),
1570 Some(22i64.into())
1571 );
1572 let data = fixture
1573 .serialized()
1574 .expect("a write schedules serialization");
1575 assert_eq!(at(&data, &["v", "value1"]), Some(&22i64.into()));
1576
1577 root.write(&mut fixture.cell.borrow_mut(), "value3", true);
1578 assert_eq!(
1579 root.read(&mut fixture.cell.borrow_mut(), "value3"),
1580 Some(true.into())
1581 );
1582 let data = fixture
1583 .serialized()
1584 .expect("a write schedules serialization");
1585 assert_eq!(at(&data, &["v", "value3"]), Some(&true.into()));
1586
1587 assert_eq!(
1588 root.remove(&mut fixture.cell.borrow_mut(), "value1"),
1589 Some(22i64.into())
1590 );
1591 assert_eq!(root.read(&mut fixture.cell.borrow_mut(), "value1"), None);
1592 let data = fixture
1593 .serialized()
1594 .expect("a removal schedules serialization");
1595 assert_eq!(at(&data, &["v", "value1"]), None);
1596
1597 assert_eq!(root.remove(&mut fixture.cell.borrow_mut(), "value4"), None);
1598 assert!(
1599 fixture.serialized().is_none(),
1600 "removing what is not there changes nothing"
1601 );
1602
1603 root.write(&mut fixture.cell.borrow_mut(), "value4", None::<i64>);
1604 assert_eq!(
1605 root.read(&mut fixture.cell.borrow_mut(), "value4"),
1606 Some(RestorationData::Null)
1607 );
1608 assert!(root.contains(&mut fixture.cell.borrow_mut(), "value4"));
1609 let data = fixture
1610 .serialized()
1611 .expect("a write schedules serialization");
1612 assert_eq!(at(&data, &["v", "value4"]), Some(&RestorationData::Null));
1613 }
1614
1615 #[test]
1616 fn child_bucket_values() {
1617 let (mut fixture, root) = Fixture::restored(raw_data_set());
1618 let child = RestorationBucket::child(
1619 &mut fixture.cell.borrow_mut(),
1620 "child1",
1621 root,
1622 owner("owner"),
1623 );
1624
1625 assert_eq!(child.restoration_id(&fixture.cell.borrow()), "child1");
1626 assert_eq!(
1627 child.read(&mut fixture.cell.borrow_mut(), "foo"),
1628 Some(22i64.into())
1629 );
1630 assert_eq!(child.read(&mut fixture.cell.borrow_mut(), "bar"), None);
1631 assert!(fixture.serialized().is_none());
1632
1633 child.write(&mut fixture.cell.borrow_mut(), "foo", 44i64);
1634 assert_eq!(
1635 child.read(&mut fixture.cell.borrow_mut(), "foo"),
1636 Some(44i64.into())
1637 );
1638 let data = fixture
1639 .serialized()
1640 .expect("a write schedules serialization");
1641 assert_eq!(at(&data, &["c", "child1", "v", "foo"]), Some(&44i64.into()));
1642
1643 assert_eq!(
1644 child.remove(&mut fixture.cell.borrow_mut(), "foo"),
1645 Some(44i64.into())
1646 );
1647 let data = fixture
1648 .serialized()
1649 .expect("a removal schedules serialization");
1650 assert_eq!(at(&data, &["c", "child1", "v", "foo"]), None);
1651 }
1652
1653 #[test]
1654 fn claiming_a_child_with_existing_data_keeps_that_data() {
1655 let (mut fixture, root) = Fixture::restored(raw_data_set());
1656 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner"));
1657 assert!(
1658 fixture.serialized().is_none(),
1659 "claiming stored data changes nothing"
1660 );
1661 assert_eq!(child.restoration_id(&fixture.cell.borrow()), "child1");
1662 assert_eq!(
1663 child.read(&mut fixture.cell.borrow_mut(), "foo"),
1664 Some(22i64.into())
1665 );
1666
1667 child.write(&mut fixture.cell.borrow_mut(), "bar", 44i64);
1668 let data = fixture
1669 .serialized()
1670 .expect("a write schedules serialization");
1671 assert_eq!(at(&data, &["c", "child1", "v", "bar"]), Some(&44i64.into()));
1672 }
1673
1674 #[test]
1675 fn claiming_a_child_with_no_existing_data_gives_an_empty_bucket() {
1676 let (mut fixture, root) = Fixture::restored(raw_data_set());
1677 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child2", owner("owner"));
1678 assert_eq!(child.restoration_id(&fixture.cell.borrow()), "child2");
1679
1680 child.write(&mut fixture.cell.borrow_mut(), "foo", 55i64);
1681 assert_eq!(
1682 child.read(&mut fixture.cell.borrow_mut(), "foo"),
1683 Some(55i64.into())
1684 );
1685 let data = fixture
1686 .serialized()
1687 .expect("a new child schedules serialization");
1688 assert_eq!(at(&data, &["c", "child2", "v", "foo"]), Some(&55i64.into()));
1689 }
1690
1691 #[cfg(debug_assertions)]
1692 #[test]
1693 fn claiming_a_claimed_child_reports_the_duplicate_ids_at_finalization() {
1694 let (mut fixture, root) = Fixture::restored(raw_data_set());
1695 let _first = root.claim_child(
1696 &mut fixture.cell.borrow_mut(),
1697 "child1",
1698 owner("FirstClaim"),
1699 );
1700 let second = root.claim_child(
1701 &mut fixture.cell.borrow_mut(),
1702 "child1",
1703 owner("SecondClaim"),
1704 );
1705 assert_eq!(second.read(&mut fixture.cell.borrow_mut(), "foo"), None);
1706
1707 let error = catch_unwind(AssertUnwindSafe(|| fixture.serialized())).unwrap_err();
1708 let message = panic_message(&error);
1709 assert!(
1710 message.contains("Multiple owners claimed child RestorationBuckets with the same IDs."),
1711 "{message}"
1712 );
1713 assert!(
1714 message.contains(" * \"child1\" was claimed by:"),
1715 "{message}"
1716 );
1717 assert!(message.contains("\"SecondClaim\""), "{message}");
1718 assert!(
1719 message.contains("\"FirstClaim\" (current owner)"),
1720 "{message}"
1721 );
1722 }
1723
1724 #[test]
1725 fn claiming_a_claimed_child_is_fine_once_the_first_owner_gives_it_up() {
1726 let (mut fixture, root) = Fixture::restored(raw_data_set());
1727 let first = root.claim_child(
1728 &mut fixture.cell.borrow_mut(),
1729 "child1",
1730 owner("FirstClaim"),
1731 );
1732 let second = root.claim_child(
1733 &mut fixture.cell.borrow_mut(),
1734 "child1",
1735 owner("SecondClaim"),
1736 );
1737 second.write(&mut fixture.cell.borrow_mut(), "bar", 55i64);
1738
1739 first.dispose(&mut fixture.cell.borrow_mut());
1740
1741 let data = fixture
1742 .serialized()
1743 .expect("the shuffle schedules serialization");
1744 assert_eq!(at(&data, &["c", "child1", "v", "foo"]), None);
1745 assert_eq!(at(&data, &["c", "child1", "v", "bar"]), Some(&55i64.into()));
1746 }
1747
1748 #[test]
1749 fn unclaiming_and_claiming_the_same_id_gives_a_fresh_bucket() {
1750 let (fixture, root) = Fixture::restored(raw_data_set());
1751 let first = root.claim_child(
1752 &mut fixture.cell.borrow_mut(),
1753 "child1",
1754 owner("FirstClaim"),
1755 );
1756 assert_eq!(
1757 first.read(&mut fixture.cell.borrow_mut(), "foo"),
1758 Some(22i64.into())
1759 );
1760 first.dispose(&mut fixture.cell.borrow_mut());
1761
1762 let second = root.claim_child(
1763 &mut fixture.cell.borrow_mut(),
1764 "child1",
1765 owner("SecondClaim"),
1766 );
1767 assert_eq!(second.read(&mut fixture.cell.borrow_mut(), "foo"), None);
1768 }
1769
1770 #[test]
1771 fn the_raw_data_drops_the_values_and_children_maps_when_they_empty_out() {
1772 let (mut fixture, root) = Fixture::restored(raw_data_set());
1773 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner"));
1774 child.dispose(&mut fixture.cell.borrow_mut());
1775 let data = fixture
1776 .serialized()
1777 .expect("dropping a child schedules serialization");
1778 assert_eq!(at(&data, &["c"]), None);
1779
1780 assert_eq!(
1781 root.remove(&mut fixture.cell.borrow_mut(), "value1"),
1782 Some(10i64.into())
1783 );
1784 assert_eq!(
1785 root.remove(&mut fixture.cell.borrow_mut(), "value2"),
1786 Some("Hello".into())
1787 );
1788 let data = fixture
1789 .serialized()
1790 .expect("a removal schedules serialization");
1791 assert_eq!(at(&data, &["v"]), None);
1792 }
1793
1794 #[test]
1795 fn dispose_deletes_the_data_of_the_whole_subtree() {
1796 let (mut fixture, root) = Fixture::restored(raw_data_set());
1797 let child1 = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1798 child1.claim_child(
1799 &mut fixture.cell.borrow_mut(),
1800 "child1OfChild1",
1801 owner("owner1.1"),
1802 );
1803 let child2 = root.claim_child(&mut fixture.cell.borrow_mut(), "child2", owner("owner2"));
1804 child2.write(&mut fixture.cell.borrow_mut(), "foo", 1i64);
1805
1806 let data = fixture
1807 .serialized()
1808 .expect("new children schedule serialization");
1809 assert!(at(&data, &["c", "child1"]).is_some());
1810 assert!(at(&data, &["c", "child2"]).is_some());
1811
1812 child1.dispose(&mut fixture.cell.borrow_mut());
1813 let data = fixture
1814 .serialized()
1815 .expect("dropping a child schedules serialization");
1816 assert_eq!(at(&data, &["c", "child1"]), None);
1817
1818 child2.dispose(&mut fixture.cell.borrow_mut());
1819 let data = fixture
1820 .serialized()
1821 .expect("dropping a child schedules serialization");
1822 assert_eq!(at(&data, &["c"]), None);
1823 }
1824
1825 #[test]
1826 fn rename_to_the_same_id_changes_nothing() {
1827 let (mut fixture, root) = Fixture::restored(raw_data_set());
1828 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1829
1830 child.rename(&mut fixture.cell.borrow_mut(), "child1");
1831 assert_eq!(child.restoration_id(&fixture.cell.borrow()), "child1");
1832 assert!(fixture.serialized().is_none());
1833 }
1834
1835 #[test]
1836 fn rename_to_an_unused_id_moves_the_data() {
1837 let (mut fixture, root) = Fixture::restored(raw_data_set());
1838 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1839
1840 child.rename(&mut fixture.cell.borrow_mut(), "new-name");
1841 assert_eq!(child.restoration_id(&fixture.cell.borrow()), "new-name");
1842
1843 let data = fixture
1844 .serialized()
1845 .expect("a rename schedules serialization");
1846 assert_eq!(at(&data, &["c", "child1"]), None);
1847 assert_eq!(
1848 at(&data, &["c", "new-name", "v", "foo"]),
1849 Some(&22i64.into())
1850 );
1851 }
1852
1853 #[cfg(debug_assertions)]
1854 #[test]
1855 fn rename_onto_a_used_id_reports_the_duplicate_unless_it_is_given_up() {
1856 let (mut fixture, root) = Fixture::restored(raw_data_set());
1857 let _child1 = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1858 let child2 = root.claim_child(&mut fixture.cell.borrow_mut(), "child2", owner("owner2"));
1859 child2.rename(&mut fixture.cell.borrow_mut(), "child1");
1860
1861 let error = catch_unwind(AssertUnwindSafe(|| fixture.serialized())).unwrap_err();
1862 assert!(
1863 panic_message(&error)
1864 .contains("Multiple owners claimed child RestorationBuckets with the same IDs."),
1865 );
1866 }
1867
1868 #[test]
1869 fn rename_onto_a_given_up_id_takes_it_over() {
1870 let (mut fixture, root) = Fixture::restored(raw_data_set());
1871 let child1 = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1872 let child2 = root.claim_child(&mut fixture.cell.borrow_mut(), "child2", owner("owner2"));
1873 child2.write(&mut fixture.cell.borrow_mut(), "bar", 7i64);
1874 fixture.serialize();
1875
1876 child2.rename(&mut fixture.cell.borrow_mut(), "child1");
1877 child1.dispose(&mut fixture.cell.borrow_mut());
1878
1879 let data = fixture
1880 .serialized()
1881 .expect("the shuffle schedules serialization");
1882 assert_eq!(at(&data, &["c", "child1", "v", "bar"]), Some(&7i64.into()));
1883 assert_eq!(at(&data, &["c", "child2"]), None);
1884 }
1885
1886 #[test]
1887 fn renaming_a_child_that_is_still_waiting_for_its_id() {
1888 let (mut fixture, root) = Fixture::restored(raw_data_set());
1889 let child1 = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1890 let child2 = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner2"));
1891
1892 child2.rename(&mut fixture.cell.borrow_mut(), "foo");
1893
1894 let data = fixture
1895 .serialized()
1896 .expect("the shuffle schedules serialization");
1897 assert_eq!(child1.restoration_id(&fixture.cell.borrow()), "child1");
1898 assert_eq!(child2.restoration_id(&fixture.cell.borrow()), "foo");
1899 assert_eq!(at(&data, &["c", "child1", "v", "foo"]), Some(&22i64.into()));
1900 assert_eq!(
1901 at(&data, &["c", "foo"]),
1902 Some(&RestorationMap::new().into())
1903 );
1904 }
1905
1906 #[test]
1907 fn adopting_a_child_of_this_bucket_changes_nothing() {
1908 let (mut fixture, root) = Fixture::restored(raw_data_set());
1909 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1910
1911 root.adopt_child(&mut fixture.cell.borrow_mut(), &child);
1912 assert!(fixture.serialized().is_none());
1913 }
1914
1915 #[test]
1916 fn adopting_a_fresh_child_puts_it_in_the_hierarchy() {
1917 let (mut fixture, root) = Fixture::restored(raw_data_set());
1918 let child = RestorationBucket::empty(
1919 &mut fixture.cell.borrow_mut(),
1920 "fresh-child",
1921 owner("owner1"),
1922 );
1923 assert!(!child.is_replacing(&fixture.cell.borrow()));
1924
1925 root.adopt_child(&mut fixture.cell.borrow_mut(), &child);
1926 child.write(&mut fixture.cell.borrow_mut(), "value", 22i64);
1927
1928 let data = fixture
1929 .serialized()
1930 .expect("an adoption schedules serialization");
1931 assert_eq!(
1932 at(&data, &["c", "fresh-child", "v", "value"]),
1933 Some(&22i64.into())
1934 );
1935 }
1936
1937 #[test]
1938 fn adopting_a_child_that_already_had_a_parent_moves_its_data() {
1939 let (mut fixture, root) = Fixture::restored(raw_data_set());
1940 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1941 let child_of_child = child.claim_child(
1942 &mut fixture.cell.borrow_mut(),
1943 "childOfChild",
1944 owner("owner2"),
1945 );
1946 child_of_child.write(&mut fixture.cell.borrow_mut(), "foo", "bar");
1947 let data = fixture
1948 .serialized()
1949 .expect("a write schedules serialization");
1950 assert_eq!(
1951 at(&data, &["c", "child1", "c", "childOfChild", "v", "foo"]),
1952 Some(&"bar".into())
1953 );
1954
1955 root.adopt_child(&mut fixture.cell.borrow_mut(), &child_of_child);
1956
1957 let data = fixture
1958 .serialized()
1959 .expect("an adoption schedules serialization");
1960 assert_eq!(at(&data, &["c", "child1", "c"]), None);
1961 assert_eq!(
1962 at(&data, &["c", "childOfChild", "v", "foo"]),
1963 Some(&"bar".into())
1964 );
1965 }
1966
1967 #[cfg(debug_assertions)]
1968 #[test]
1969 fn adopting_onto_a_used_id_reports_the_duplicate_unless_it_is_given_up() {
1970 let (mut fixture, root) = Fixture::restored(raw_data_set());
1971 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1972 let child_of_child =
1973 child.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner2"));
1974 child_of_child.write(&mut fixture.cell.borrow_mut(), "foo", "bar");
1975
1976 root.adopt_child(&mut fixture.cell.borrow_mut(), &child_of_child);
1977
1978 let error = catch_unwind(AssertUnwindSafe(|| fixture.serialized())).unwrap_err();
1979 assert!(
1980 panic_message(&error)
1981 .contains("Multiple owners claimed child RestorationBuckets with the same IDs."),
1982 );
1983 }
1984
1985 #[test]
1986 fn adopting_onto_a_given_up_id_takes_it_over() {
1987 let (mut fixture, root) = Fixture::restored(raw_data_set());
1988 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
1989 let child_of_child =
1990 child.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner2"));
1991 child_of_child.write(&mut fixture.cell.borrow_mut(), "foo", "bar");
1992 fixture.serialize();
1993
1994 root.adopt_child(&mut fixture.cell.borrow_mut(), &child_of_child);
1995 child.dispose(&mut fixture.cell.borrow_mut());
1996
1997 let data = fixture
1998 .serialized()
1999 .expect("the shuffle schedules serialization");
2000 assert_eq!(at(&data, &["c", "child1", "v", "foo"]), Some(&"bar".into()));
2001 }
2002
2003 #[test]
2004 fn a_child_of_a_parentless_bucket_joins_the_manager_when_it_is_adopted() {
2005 let (mut fixture, root) = Fixture::restored(raw_data_set());
2006 let detached =
2007 RestorationBucket::empty(&mut fixture.cell.borrow_mut(), "detached", owner("owner1"));
2008 let child = detached.claim_child(&mut fixture.cell.borrow_mut(), "leaf", owner("owner2"));
2009 child.write(&mut fixture.cell.borrow_mut(), "foo", 3i64);
2010 assert!(
2011 fixture.serialized().is_none(),
2012 "a bucket outside the hierarchy has no manager to schedule with"
2013 );
2014
2015 root.adopt_child(&mut fixture.cell.borrow_mut(), &detached);
2016
2017 let data = fixture
2018 .serialized()
2019 .expect("an adoption schedules serialization");
2020 assert_eq!(
2021 at(&data, &["c", "detached", "c", "leaf", "v", "foo"]),
2022 Some(&3i64.into())
2023 );
2024 }
2025
2026 #[cfg(debug_assertions)]
2027 #[test]
2028 fn a_bucket_cannot_be_used_after_it_is_disposed() {
2029 let cell = AppCell::new();
2030 let mut app = cell.borrow_mut();
2031 let bucket = RestorationBucket::empty(&mut app, "foo", None);
2032 bucket.dispose(&mut app);
2033
2034 let error = catch_unwind(AssertUnwindSafe(|| bucket.read(&mut app, "foo"))).unwrap_err();
2035 assert!(
2036 panic_message(&error).contains("A RestorationBucket was used after being disposed."),
2037 );
2038 }
2039
2040 #[test]
2041 fn disposing_the_manager_disposes_the_root_bucket() {
2042 let (fixture, root) = Fixture::restored(raw_data_set());
2043 fixture.manager.dispose(&mut fixture.cell.borrow_mut());
2044 assert!(fixture.cell.borrow().is_disposed(root));
2045 }
2046
2047 #[test]
2048 fn a_bucket_reports_the_owner_it_was_claimed_with() {
2049 let (fixture, root) = Fixture::restored(raw_data_set());
2050 let child = root.claim_child(&mut fixture.cell.borrow_mut(), "child1", owner("owner1"));
2051 let described = format!("{:?}", fixture.cell.borrow().get(&child));
2052 if cfg!(debug_assertions) {
2053 assert_eq!(
2054 described,
2055 "RestorationBucket(restorationId: child1, owner: \"owner1\")"
2056 );
2057 } else {
2058 assert_eq!(
2059 described,
2060 "RestorationBucket(restorationId: child1, owner: None)"
2061 );
2062 }
2063 }
2064}