Skip to main content

waft_services/
restoration.rs

1//! Flutter counterpart: `services/restoration.dart`.
2
3use 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/// Manages the restoration data in the framework and synchronizes it with the host.
14///
15/// Restoration data can be serialized out and - at a later point in time - be
16/// used to restore the application to the previous state described by the
17/// serialized data. Mobile operating systems use the concept of state
18/// restoration to provide the illusion that apps continue to run in the
19/// background forever: after an app has been backgrounded, the user can always
20/// return to it and find it in the same state. In practice, the operating
21/// system may, however, terminate the app to free resources for other apps
22/// running in the foreground. Before that happens, the app gets a chance to
23/// serialize out its restoration data. When the user navigates back to the
24/// backgrounded app, it is restarted and the serialized restoration data is
25/// provided to it again. Ideally, the app will use that data to restore itself
26/// to the same state it was in when the user backgrounded the app.
27///
28/// Restoration data is organized in a tree of [`RestorationBucket`]s which is
29/// rooted in the [`root_bucket`](Self::root_bucket). All information that the
30/// application needs to restore its current state must be stored in a bucket in
31/// this hierarchy. To store data in the hierarchy, entities must claim ownership
32/// of a child bucket from a parent bucket (which may be the root bucket provided
33/// by this [`RestorationManager`]). The owner of a bucket may store arbitrary
34/// [`RestorationData`] in the bucket. The values are stored in the bucket under a
35/// given restoration ID as key. A restoration ID is a string that must be unique
36/// within a given bucket. To access the stored value again during state
37/// restoration, the same restoration ID must be provided again. The owner of the
38/// bucket may also make the bucket available to other entities so that they can
39/// claim child buckets from it for their own restoration needs. Within a bucket,
40/// child buckets are also identified by unique restoration IDs. The restoration
41/// ID must be provided when claiming a child bucket.
42///
43/// When restoration data is provided to the [`RestorationManager`] (e.g. after
44/// the application relaunched when foregrounded again), the bucket hierarchy
45/// with all the data stored in it is restored. Entities can retrieve the data
46/// again by using the same restoration IDs that they originally used to store
47/// the data.
48///
49/// In addition to providing restoration data when the app is launched,
50/// restoration data may also be provided to a running app to restore it to a
51/// previous state (e.g. when the user hits the back/forward button in the web
52/// browser). When this happens, the [`RestorationManager`] notifies its listeners
53/// (added via [`add_listener`]) that a new root bucket is available. In response
54/// to the notification, listeners must stop using the old bucket and restore
55/// their state from the information in the new root bucket.
56///
57/// Some platforms restrict the size of the restoration data. Therefore, the
58/// data stored in the buckets should be as small as possible while still
59/// allowing the app to restore its current state from it. Data that can be
60/// retrieved from other services (e.g. a database or a web server) should not
61/// be included in the restoration data. Instead, a small identifier (e.g. a
62/// UUID, database record number, or resource locator) should be stored that can
63/// be used to retrieve the data again from its original source during state
64/// restoration.
65///
66/// The [`RestorationManager`] sends a copy of the bucket hierarchy over to the
67/// host at the end of a frame in which the data in the hierarchy or its shape
68/// has changed. The host caches the data until the operating system needs it.
69/// The application is responsible for keeping the data in the bucket always
70/// up-to-date to reflect its current state.
71///
72/// ## Discussion
73///
74/// Due to the threading model of the platforms Flutter runs on, restoration data
75/// must be stored in the buckets proactively as described above. When the
76/// operating system asks for the restoration data, it will do so on the platform
77/// thread expecting a synchronous response. To avoid the risk of deadlocks, the
78/// platform thread cannot block and call into the thread running the application
79/// to retrieve the restoration data. For this reason, the [`RestorationManager`]
80/// always sends the latest copy of the restoration data over to the host
81/// whenever it changes. That way, the restoration data is always ready to go on
82/// the platform thread when the operating system needs it.
83///
84/// Dart's `ServicesBinding.restorationManager` is [`instance`](Self::instance),
85/// the App's singleton.
86///
87/// See also:
88///
89///  * [`RestorationBucket`], which make up the restoration data hierarchy.
90///
91/// [`add_listener`]: waft_foundation::ListenableObject::add_listener
92#[derive(Default)]
93pub struct RestorationManager {
94    change_notifier: ChangeNotifierData,
95    // May be `None` to indicate that restoration is turned off.
96    root_bucket: Option<Ref<RestorationBucket>>,
97    // Dart's `Completer` for the outstanding request to the engine; the host answers
98    // within the call, so only the fact that a request is in flight remains.
99    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    /// The application's restoration manager.
119    ///
120    /// Dart's `ServicesBinding.instance.restorationManager`.
121    pub fn instance(app: &mut App) -> Handle<RestorationManager> {
122        app.singleton::<RestorationManager>()
123    }
124
125    /// The root of the [`RestorationBucket`] hierarchy containing the restoration
126    /// data.
127    ///
128    /// Child buckets can be claimed from this bucket via
129    /// [`RestorationBucket::claim_child`]. If the [`RestorationManager`] has been
130    /// asked to restore the application to a previous state, these buckets will
131    /// contain the previously stored data. Otherwise the root bucket (and all
132    /// children claimed from it) will be empty.
133    ///
134    /// The [`RestorationManager`] informs its listeners when the value returned by
135    /// this getter changes. This happens when new restoration data has been
136    /// provided to the [`RestorationManager`] to restore the application to a
137    /// different state. In response to the notification, listeners must stop using
138    /// the old root bucket and obtain the new one via this getter (it will have
139    /// been updated to return the new bucket just before the listeners are
140    /// notified).
141    ///
142    /// The restoration data describing the current bucket hierarchy is retrieved
143    /// from the host the first time the root bucket is accessed via this getter.
144    ///
145    /// Returns `None` if state restoration is currently turned off.
146    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    /// Returns true for the frame after the root bucket has been replaced with a
158    /// new non-null bucket.
159    ///
160    /// When true, entities should forget their current state and restore
161    /// their state according to the information in the new root bucket.
162    ///
163    /// The [`RestorationManager`] informs its listeners when this flag changes from
164    /// false to true.
165    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            // The restoration data was obtained via other means (e.g. by calling
176            // `handle_restoration_update_from_engine` while the request to the host was
177            // outstanding). Ignore the host's response.
178            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    /// Parses the restoration information obtained from the host.
197    ///
198    /// The `enabled` parameter indicates whether the host wants to receive
199    /// restoration data. When `enabled` is false, state restoration is turned
200    /// off and the root bucket is set to `None`. When `enabled` is true, the
201    /// provided restoration `data` becomes the new root bucket. If `data` is
202    /// `None`, an empty root bucket is instantiated.
203    ///
204    /// A host may call this method at any time to inject restoration data
205    /// (obtained e.g. from [`send_to_engine`](Self::send_to_engine)) into the
206    /// [`RestorationManager`], which is what Flutter's `push` message on
207    /// `SystemChannels.restoration` does. When the method is called before the
208    /// root bucket is accessed, [`root_bucket`](Self::root_bucket) answers without
209    /// asking the host.
210    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    /// Sends the provided restoration data to the host.
244    ///
245    /// The `encoded_data` describes the entire bucket hierarchy that makes up the
246    /// current restoration data.
247    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    /// Called by a [`RestorationBucket`] to request serialization for that bucket.
254    ///
255    /// This method is called by a bucket in the hierarchy whenever the data
256    /// in it or the shape of the hierarchy has changed.
257    ///
258    /// Calling this is a no-op when the bucket is already scheduled for
259    /// serialization.
260    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        // Dart's set holds the bucket until the frame's serialization. One that nothing keeps any
268        // more is freed before then and its data with it, so there is nothing of it to finalize;
269        // the serialization is still scheduled for the change it made.
270        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    /// Called by a [`RestorationBucket`] to unschedule a request for serialization.
286    ///
287    /// This method is called by a bucket in the hierarchy whenever it no longer
288    /// needs to be serialized (e.g. because the bucket got disposed).
289    ///
290    /// It is safe to call this even when the bucket wasn't scheduled for
291    /// serialization before.
292    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    /// Called to manually flush the restoration data to the host.
331    ///
332    /// A change in restoration data is usually accompanied by scheduling a frame
333    /// (because the restoration data is modified inside a `State::set_state` call,
334    /// because it is usually something that affects the interface). Restoration
335    /// data is automatically flushed to the host at the end of a frame. As a
336    /// result, it is uncommon to need to call this method directly. However, if
337    /// restoration data is changed without triggering a frame, this method must
338    /// be called to ensure that the updated restoration data is sent to the
339    /// host in a timely manner. An example of such a use case is the scrollable,
340    /// where the final scroll offset after a scroll activity finishes is
341    /// determined between frames without scheduling a new frame.
342    ///
343    /// Calling this method is a no-op if a frame is already scheduled. In that
344    /// case, the restoration data will be flushed to the host at the end of
345    /// that frame. If this method is called and no frame is scheduled, the
346    /// current restoration data is directly sent to the host.
347    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    /// Discards any resources used by the manager, and the root bucket with them.
357    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
368/// A restoration ID as the raw data maps key it.
369fn data_key(restoration_id: &str) -> RestorationData {
370    RestorationData::String(restoration_id.to_string())
371}
372
373/// Dart's `_rawData.putIfAbsent(key, () => <Object?, Object?>{})`.
374fn 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
381/// Where a bucket's raw map lives.
382///
383/// Dart's child bucket holds the very map its parent stores under its restoration ID in
384/// `_rawChildren`; a Rust value has one owner, so a bucket whose parent stores it reads
385/// and writes its map through that parent.
386enum RawData {
387    Own(RestorationMap),
388    InParent,
389}
390
391/// A [`RestorationBucket`] holds pieces of the restoration data that a part of
392/// the application needs to restore its state.
393///
394/// For a general overview of how state restoration works, see the
395/// [`RestorationManager`].
396///
397/// [`RestorationBucket`]s are organized in a tree that is rooted in
398/// [`RestorationManager::root_bucket`] and managed by a [`RestorationManager`].
399/// The tree is serializable and must contain all the data an application needs
400/// to restore its current state at a later point in time.
401///
402/// A [`RestorationBucket`] stores restoration data as key-value pairs. The key is
403/// a string representing a restoration ID that identifies a piece of data
404/// uniquely within a bucket. The value is any [`RestorationData`]. Furthermore, a
405/// [`RestorationBucket`] may have child buckets, which are identified within their
406/// parent via a unique restoration ID as well.
407///
408/// During state restoration, the data previously stored in the
409/// [`RestorationBucket`] hierarchy will be made available again to the
410/// application to restore it to the state it had when the data was collected.
411/// State restoration to a previous state may happen when the app is launched
412/// (e.g. after it has been terminated gracefully while running in the
413/// background) or after the app has already been running for a while.
414///
415/// ## Lifecycle
416///
417/// A [`RestorationBucket`] is rarely instantiated directly via its constructors.
418/// Instead, when an entity wants to store data in or retrieve data from a
419/// restoration bucket, it typically obtains a child bucket from a parent by
420/// calling [`claim_child`](Self::claim_child). If no parent is available,
421/// [`RestorationManager::root_bucket`] may be used as a parent. When claiming a
422/// child, the claimer must provide the restoration ID of the child it would
423/// like to own. A child bucket with a given restoration ID can at most have
424/// one owner. If another owner tries to claim a bucket with the same ID from
425/// the same parent, an error is raised (see discussion in
426/// [`claim_child`](Self::claim_child)). The restoration IDs that a given owner
427/// uses to claim a child (and to store data in that child, see below) must be
428/// stable across app launches to ensure that after the app restarts the owner can
429/// retrieve the same data again that it stored during a previous run.
430///
431/// Per convention, the owner of the bucket has exclusive access to the values
432/// stored in the bucket. It can read, add, modify, and remove values via the
433/// [`read`](Self::read), [`write`](Self::write), and [`remove`](Self::remove)
434/// methods. In general, the owner should store all the data in the bucket that it
435/// needs to restore its current state. If its current state changes, the data in
436/// the bucket must be updated. At the same time, the data in the bucket should be
437/// kept to a minimum. For example, for data that can be retrieved from other
438/// sources (like a database or web service) only enough information (e.g. an ID
439/// or resource locator) to re-obtain that data should be stored in the bucket. In
440/// addition to managing the data in a bucket, an owner may also make the bucket
441/// available to other entities so they can claim child buckets from it via
442/// [`claim_child`](Self::claim_child) for their own restoration needs.
443///
444/// The bucket returned by [`claim_child`](Self::claim_child) may either contain
445/// state information that the owner had previously (e.g. during a previous run of
446/// the application) stored in it or it may be empty. If the bucket contains data,
447/// the owner is expected to restore its state with the information previously
448/// stored in the bucket. If the bucket is empty, it may initialize itself to
449/// default values.
450///
451/// When the data stored in a bucket is no longer needed to restore the
452/// application to its current state (e.g. because the owner of the bucket is no
453/// longer shown on screen), the bucket must be [`dispose`](Self::dispose)d. This
454/// will remove all information stored in the bucket from the app's restoration
455/// data and that information will not be available again when the application is
456/// restored to this state in the future.
457pub struct RestorationBucket {
458    manager: Option<Handle<RestorationManager>>,
459    parent: Option<Handle<RestorationBucket>>,
460    raw_data: RawData,
461    restoration_id: String,
462    // The restoration IDs and associated buckets of children that have been
463    // claimed via `claim_child`.
464    claimed_children: IndexMap<String, Ref<RestorationBucket>>,
465    // Newly created child buckets whose restoration ID is still in use, see
466    // comment in `claim_child` for details.
467    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
483/// Dart's `'$debugOwner'`.
484fn 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    /// Creates an empty [`RestorationBucket`] to be provided to
493    /// [`adopt_child`](Self::adopt_child) to add it to the bucket hierarchy.
494    ///
495    /// Instantiating a bucket directly is rare, most buckets are created by
496    /// claiming a child from a parent via [`claim_child`](Self::claim_child). If no
497    /// parent bucket is available, [`RestorationManager::root_bucket`] may be used
498    /// as a parent.
499    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    /// Creates the root [`RestorationBucket`] for the provided restoration
511    /// `manager`.
512    ///
513    /// The `raw_data` must either be `None` (in which case an empty bucket will be
514    /// instantiated) or it must be a nested map describing the entire bucket
515    /// hierarchy in the following format:
516    ///
517    /// ```text
518    /// {
519    ///  'v': {  // key-value pairs
520    ///     // * key is a string representation of a restoration ID
521    ///     // * value is any RestorationData
522    ///    '<restoration-id>': <RestorationData>,
523    ///   },
524    ///  'c': {  // child buckets
525    ///    '<restoration-id>': <nested map representing a child bucket>
526    ///   }
527    /// }
528    /// ```
529    ///
530    /// Instantiating a bucket directly is rare, most buckets are created by
531    /// claiming a child from a parent via [`claim_child`](Self::claim_child).
532    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    /// Creates a child bucket initialized with the data that the provided
547    /// `parent` has stored under the provided `restoration_id`.
548    ///
549    /// This constructor cannot be used if the `parent` does not have any child
550    /// data stored under the given ID. In that case, create an empty bucket (via
551    /// [`empty`](Self::empty)) and have the parent adopt it via
552    /// [`adopt_child`](Self::adopt_child).
553    ///
554    /// Instantiating a bucket directly is rare, most buckets are created by
555    /// claiming a child from a parent via [`claim_child`](Self::claim_child).
556    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    /// The owner of the bucket that was provided when the bucket was claimed via
592    /// [`claim_child`](Self::claim_child).
593    ///
594    /// The value is used in error messages. Accessing the value is only valid
595    /// in debug mode, otherwise it will return `None`.
596    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    /// Returns true when entities processing this bucket should restore their
602    /// state from the information in the bucket (e.g. via [`read`](Self::read) and
603    /// [`claim_child`](Self::claim_child)) instead of copying their current state
604    /// information into the bucket (e.g. via [`write`](Self::write) and
605    /// [`adopt_child`](Self::adopt_child)).
606    ///
607    /// This flag is true for the frame after the [`RestorationManager`] has been
608    /// instructed to restore the application from newly provided restoration
609    /// data.
610    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    /// The restoration ID under which the bucket is currently stored in the
617    /// parent of this bucket (or wants to be stored if it is currently
618    /// parent-less).
619    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    /// The bucket's own raw map, wherever it currently lives.
625    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    /// Maps a restoration ID to the raw map representation of a child bucket.
655    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    /// Maps a restoration ID to a value that is stored in this bucket.
664    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    // Get and store values.
673
674    /// Returns the value that is currently stored in the bucket under the provided
675    /// `restoration_id`.
676    ///
677    /// Returns `None` if nothing is stored under that ID.
678    ///
679    /// See also:
680    ///
681    ///  * [`write`](Self::write), which stores a value in the bucket.
682    ///  * [`remove`](Self::remove), which removes a value from the bucket.
683    ///  * [`contains`](Self::contains), which checks whether any value is stored
684    ///    under a given restoration ID.
685    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    /// Stores the provided `value` under the provided `restoration_id` in the
695    /// bucket.
696    ///
697    /// Any value that has previously been stored under that ID is overwritten
698    /// with the new value.
699    ///
700    /// [`RestorationData::Null`] is stored in the bucket as-is. To remove a value,
701    /// use [`remove`](Self::remove).
702    ///
703    /// See also:
704    ///
705    ///  * [`read`](Self::read), which retrieves a stored value from the bucket.
706    ///  * [`remove`](Self::remove), which removes a value from the bucket.
707    ///  * [`contains`](Self::contains), which checks whether any value is stored
708    ///    under a given restoration ID.
709    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    /// Deletes the value currently stored under the provided `restoration_id` from
731    /// the bucket.
732    ///
733    /// The value removed from the bucket is returned. If no value was stored under
734    /// that ID, `None` is returned.
735    ///
736    /// See also:
737    ///
738    ///  * [`read`](Self::read), which retrieves a stored value from the bucket.
739    ///  * [`write`](Self::write), which stores a value in the bucket.
740    ///  * [`contains`](Self::contains), which checks whether any value is stored
741    ///    under a given restoration ID.
742    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    /// Checks whether a value is stored in the bucket under the provided
766    /// `restoration_id`.
767    ///
768    /// See also:
769    ///
770    ///  * [`read`](Self::read), which retrieves a stored value from the bucket.
771    ///  * [`write`](Self::write), which stores a value in the bucket.
772    ///  * [`remove`](Self::remove), which removes a value from the bucket.
773    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    // Child management.
779
780    /// Claims ownership of the child with the provided `restoration_id` from this
781    /// bucket.
782    ///
783    /// If the application is getting restored to a previous state, the bucket
784    /// will contain all the data that was previously stored in the bucket.
785    /// Otherwise, an empty bucket is returned.
786    ///
787    /// The claimer of the bucket is expected to use the data stored in the bucket
788    /// to restore itself to its previous state described by the data in the
789    /// bucket. If the bucket is empty, it should initialize itself to default
790    /// values. Whenever the information that the claimer needs to restore its
791    /// state changes, the data in the bucket should be updated to reflect that.
792    ///
793    /// A child bucket with a given `restoration_id` can only have one owner. If
794    /// another owner claims a child bucket with the same `restoration_id` the end
795    /// of the current frame panics in debug mode unless the previous owner has
796    /// either deleted its bucket by calling [`dispose`](Self::dispose) or has moved
797    /// it to a new parent via [`adopt_child`](Self::adopt_child).
798    ///
799    /// When the returned bucket is no longer needed, it must be
800    /// [`dispose`](Self::dispose)d to delete the information stored in it from the
801    /// app's restoration data.
802    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        // There are three cases to consider:
810        // 1. Claiming an ID that has already been claimed.
811        // 2. Claiming an ID that doesn't yet exist in the raw children.
812        // 3. Claiming an ID that does exist in the raw children and hasn't been
813        //    claimed yet.
814        // If an ID has already been claimed (case 1) the current owner may give up
815        // that ID later this frame and it can be re-used. In anticipation of the
816        // previous owner's surrender of the id, we return an empty bucket for this
817        // new claim and check in `debug_assert_integrity` that at the end of the
818        // frame the old owner actually did surrender the id.
819        // Case 2 also requires the creation of a new empty bucket.
820        // In case 3 we create a new bucket wrapping the existing raw child data.
821
822        // Case 1+2: Adopt and return an empty bucket.
823        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        // Case 3: Return a bucket wrapping the existing data.
834        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    /// Adopts the provided `child` bucket.
842    ///
843    /// The `child` will be dropped from its old parent, if it had one.
844    ///
845    /// The `child` is stored under its
846    /// [`restoration_id`](Self::restoration_id) in this bucket. If this bucket
847    /// already contains a child bucket under the same ID, the owner of that
848    /// existing bucket must give it up (e.g. by moving the child bucket to a
849    /// different parent or by disposing it) before the end of the current frame.
850    /// Otherwise the illegal use of duplicated restoration IDs panics in debug
851    /// mode.
852    ///
853    /// No-op if the provided bucket is already a child of this bucket.
854    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    /// Called by the [`RestorationManager`] just before the data of the bucket
894    /// is serialized and sent to the host.
895    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            // Delay addition until the end of the frame in the hopes that the current
999            // owner of the child with the same ID will have given up that child by
1000            // then.
1001            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    /// Dart's `parent._rawChildren.remove(id)`: the map the parent stored comes back to
1034    /// the bucket it belongs to.
1035    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    // Bucket management.
1074
1075    /// Changes the restoration ID under which the bucket is (or will be) stored
1076    /// in its parent to `new_restoration_id`.
1077    ///
1078    /// No-op if the bucket is already stored under the provided ID.
1079    ///
1080    /// If another owner has already claimed a bucket with the provided
1081    /// `new_restoration_id` the end of the current frame panics in debug mode
1082    /// unless the other owner has deleted its bucket by calling
1083    /// [`dispose`](Self::dispose), [`rename`](Self::rename)d it using another ID, or
1084    /// has moved it to a new parent via [`adopt_child`](Self::adopt_child).
1085    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        // Taken before the parent lets go of the bucket, which may be what keeps it.
1091        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    /// Deletes the bucket and all the data stored in it from the bucket
1104    /// hierarchy.
1105    ///
1106    /// After [`dispose`](Self::dispose) has been called, the data stored in this
1107    /// bucket and its children are no longer part of the app's restoration data.
1108    /// The data originally stored in the bucket will not be available again when
1109    /// the application is restored to this state in the future. It is up to the
1110    /// owners of the children to either move them (via
1111    /// [`adopt_child`](Self::adopt_child)) to a new parent that is still part of
1112    /// the bucket hierarchy or to [`dispose`](Self::dispose) of them as well.
1113    ///
1114    /// This method must only be called by the object's owner.
1115    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    /// A host that answers `Restoration::get` with what it was handed and records every
1153    /// `Restoration::put`.
1154    #[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            // A view, for a test that schedules a frame.
1182            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        /// A manager whose root bucket holds `data`, as after a restart.
1197        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        /// Flutter's `_pushDataFromEngine`.
1208        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        /// Flutter's `MockRestorationManager.doSerialization`: what reached the host.
1217        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        /// The data the host would keep, or `None` when nothing was scheduled.
1223        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    /// Flutter's `_createRawDataSet`.
1250    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    /// Flutter's `_createEncodedRestorationData2`.
1268    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    /// The value stored down `path`, e.g. `["c", "child1", "v", "foo"]`.
1283    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(&notifications);
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(&notifications);
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    /// Dart's `dispose` calls `unscheduleSerializationFor`, so the set that holds the buckets
1489    /// waiting for the frame's serialization does not keep a disposed one alive.
1490    #[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    /// A bucket nothing keeps any more that changes before the checkpoint frees it is not held
1506    /// for the frame's serialization, and the change is still sent.
1507    #[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}