Skip to main content

settings_storage/
fidl_storage.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::UpdateState;
6use crate::private::Sealed;
7use crate::storage_factory::{DefaultLoader, NoneT};
8use anyhow::{Context, Error, bail, format_err};
9use fidl::{Persistable, Status, persist, unpersist};
10use fidl_fuchsia_io::DirectoryProxy;
11use fuchsia_async::{MonotonicInstant, Task, Timer};
12use fuchsia_fs::Flags;
13use fuchsia_fs::file::ReadError;
14use fuchsia_fs::node::OpenError;
15
16use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
17use futures::future::OptionFuture;
18use futures::lock::{Mutex, MutexGuard};
19use futures::{FutureExt, StreamExt};
20use std::any::Any;
21use std::collections::HashMap;
22use std::pin::pin;
23use std::rc::Rc;
24use zx::MonotonicDuration;
25
26/// Minimum amount of time between flushing to disk, in milliseconds. The flush call triggers
27/// file I/O which is slow.
28const MIN_FLUSH_INTERVAL_MS: i64 = 500;
29const MAX_FLUSH_INTERVAL_MS: i64 = 1_800_000; // 30 minutes
30const MIN_FLUSH_DURATION: MonotonicDuration = MonotonicDuration::from_millis(MIN_FLUSH_INTERVAL_MS);
31
32pub trait FidlStorageConvertible {
33    type Storable;
34    type Loader;
35
36    const KEY: &'static str;
37
38    fn to_storable(self) -> Self::Storable;
39    fn from_storable(storable: Self::Storable) -> Self;
40}
41
42/// Stores device level settings in persistent storage.
43/// User level settings should not use this.
44pub struct FidlStorage {
45    /// Map of [`FidlStorageConvertible`] keys to their typed storage.
46    typed_storage_map: HashMap<&'static str, TypedStorage>,
47
48    typed_loader_map: HashMap<&'static str, Box<dyn Any>>,
49
50    /// If true, reads will be returned from the data in memory rather than reading from storage.
51    caching_enabled: bool,
52
53    /// If true, writes to the underlying storage will only occur at most every
54    /// [MIN_WRITE_INTERVAL_MS].
55    debounce_writes: bool,
56
57    storage_dir: DirectoryProxy,
58}
59
60/// A wrapper for managing all communication and caching for one particular type of data being
61/// stored. The actual types are erased.
62struct TypedStorage {
63    /// Sender to communicate with task loop that handles flushes.
64    flush_sender: UnboundedSender<()>,
65
66    /// Cached storage managed through interior mutability.
67    cached_storage: Rc<Mutex<CachedStorage>>,
68}
69
70/// `CachedStorage` abstracts over a cached value that's read from and written
71/// to some backing store.
72struct CachedStorage {
73    /// Cache for the most recently read or written value. The value is stored as the encoded bytes
74    /// of the persistent fidl.
75    current_data: Option<Vec<u8>>,
76
77    /// File path that will be used to write a temporary file when syncing to disk. After syncing,
78    /// this file is deleted.
79    ///
80    /// The approach used for syncing is:
81    /// * Write data to temp file
82    /// * Rename temp file to permanent file
83    /// * Delete temp file.
84    ///
85    /// This ensures that even if there's a power cut, the data in the permanent file is never
86    /// partially written.
87    temp_file_path: String,
88
89    /// File path to used for permanent file storage on disk.
90    file_path: String,
91}
92
93impl CachedStorage {
94    /// Triggers a sync on the file proxy.
95    async fn sync(&mut self, storage_dir: &DirectoryProxy) -> Result<(), Error> {
96        // Scope is important. file_proxy needs to be out-of-scope when the directory is renamed.
97        {
98            let file_proxy = fuchsia_fs::directory::open_file(
99                storage_dir,
100                &self.temp_file_path,
101                Flags::FLAG_MUST_CREATE
102                    | Flags::FILE_TRUNCATE
103                    | fuchsia_fs::PERM_READABLE
104                    | fuchsia_fs::PERM_WRITABLE,
105            )
106            .await
107            .with_context(|| format!("unable to open {:?} for writing", self.temp_file_path))?;
108            fuchsia_fs::file::write(&file_proxy, self.current_data.as_ref().unwrap())
109                .await
110                .context("failed to write data to file")?;
111            file_proxy
112                .close()
113                .await
114                .context("failed to call close on temp file")?
115                .map_err(zx::Status::err_from_raw)?;
116        }
117        fuchsia_fs::directory::rename(storage_dir, &self.temp_file_path, &self.file_path)
118            .await
119            .context("failed to rename temp file to permanent file")?;
120        storage_dir
121            .sync()
122            .await
123            .context("failed to call sync on directory after rename")?
124            .map_err(zx::Status::err_from_raw)
125            // This is only returned when the directory is backed by a VFS, so this is fine to
126            // ignore.
127            .or_else(|e| if let zx::Status::NOT_SUPPORTED = e { Ok(()) } else { Err(e) })
128            .context("failed to sync rename to directory")
129    }
130}
131
132impl FidlStorage {
133    /// Construct a fidl storage from:
134    /// * The iterable item, which will produce the keys for storage
135    /// * A generator function that will produce a file proxy for each key. It will return the temp
136    ///   file path and final file path for storing the data for this key.
137    ///
138    /// On success, returns the FidlStorage as well as the list of background synchronizing tasks.
139    /// The background tasks can be awaited or detached.
140    pub async fn with_file_proxy<I, G>(
141        iter: I,
142        storage_dir: DirectoryProxy,
143        files_generator: G,
144    ) -> Result<(Self, Vec<Task<()>>), Error>
145    where
146        I: IntoIterator<Item = (&'static str, Option<Box<dyn Any>>)>,
147        G: Fn(&'static str) -> Result<(String, String), Error>,
148    {
149        let mut typed_storage_map = HashMap::new();
150        let iter = iter.into_iter();
151        typed_storage_map.reserve(iter.size_hint().0);
152        let mut typed_loader_map = HashMap::new();
153        let mut sync_tasks = Vec::with_capacity(iter.size_hint().0);
154        for (key, loader) in iter {
155            // Generate a separate file proxy for each key.
156            let (flush_sender, flush_receiver) = futures::channel::mpsc::unbounded::<()>();
157            let (temp_file_path, file_path) =
158                files_generator(key).context("failed to generate file")?;
159
160            let cached_storage = Rc::new(Mutex::new(CachedStorage {
161                current_data: None,
162                temp_file_path,
163                file_path,
164            }));
165            let storage = TypedStorage { flush_sender, cached_storage: Rc::clone(&cached_storage) };
166
167            // Each key has an independent flush queue.
168            let sync_task = Task::local(Self::synchronize_task(
169                Clone::clone(&storage_dir),
170                cached_storage,
171                flush_receiver,
172            ));
173            sync_tasks.push(sync_task);
174            let _ = typed_storage_map.insert(key, storage);
175            if let Some(loader) = loader {
176                let _ = typed_loader_map.insert(key, loader);
177            }
178        }
179        Ok((
180            FidlStorage {
181                caching_enabled: true,
182                debounce_writes: true,
183                typed_storage_map,
184                typed_loader_map,
185                storage_dir,
186            },
187            sync_tasks,
188        ))
189    }
190
191    async fn synchronize_task(
192        storage_dir: DirectoryProxy,
193        cached_storage: Rc<Mutex<CachedStorage>>,
194        flush_receiver: UnboundedReceiver<()>,
195    ) {
196        let mut has_pending_flush = false;
197
198        // The time of the last flush. Initialized to MIN_FLUSH_INTERVAL_MS before the
199        // current time so that the first flush always goes through, no matter the
200        // timing.
201        let mut last_flush: MonotonicInstant = MonotonicInstant::now() - MIN_FLUSH_DURATION;
202
203        // Timer for flush cooldown. OptionFuture allows us to wait on the future even
204        // if it's None.
205        let mut next_flush_timer = pin!(OptionFuture::<Timer>::from(None).fuse());
206        let mut retries = 0;
207        let mut retrying = false;
208
209        let flush_fuse = flush_receiver.fuse();
210
211        futures::pin_mut!(flush_fuse);
212        loop {
213            futures::select! {
214                _ = flush_fuse.select_next_some() => {
215                    // Flush currently unable to complete. Don't prevent exponential
216                    // backoff from occurring.
217                    if retrying {
218                        continue;
219                    }
220
221                    // Received a request to do a flush.
222                    let now = MonotonicInstant::now();
223                    let next_flush_time = if now - last_flush > MIN_FLUSH_DURATION {
224                        // Last flush happened more than MIN_FLUSH_INTERVAL_MS ago,
225                        // flush immediately in next iteration of loop.
226                        now
227                    } else {
228                        // Last flush was less than MIN_FLUSH_INTERVAL_MS ago, schedule
229                        // it accordingly. It's okay if the time is in the past, Timer
230                        // will still trigger on the next loop iteration.
231                        last_flush + MIN_FLUSH_DURATION
232                    };
233
234                    has_pending_flush = true;
235                    next_flush_timer.set(OptionFuture::from(Some(Timer::new(next_flush_time))).fuse());
236                }
237
238                _ = next_flush_timer => {
239                    // Timer triggered, check for pending syncs.
240                    if has_pending_flush {
241                        let mut cached_storage = cached_storage.lock().await;
242
243                        // If the sync fails, exponentionally backoff the syncs until a
244                        // maximum wait time.
245                        if let Err(e) = cached_storage.sync(&storage_dir).await {
246                            retrying = true;
247                            let flush_duration = MonotonicDuration::from_millis(
248                                2_i64.saturating_pow(retries)
249                                    .saturating_mul(MIN_FLUSH_INTERVAL_MS)
250                                    .min(MAX_FLUSH_INTERVAL_MS)
251                            );
252                            let next_flush_time = MonotonicInstant::now() + flush_duration;
253                            log::error!(
254                                "Failed to sync write to disk for {:?}, delaying by {:?}, \
255                                    caused by: {:?}",
256                                cached_storage.file_path,
257                                flush_duration,
258                                e
259                            );
260
261                            // Reset the timer so we can try again in the future
262                            next_flush_timer.set(OptionFuture::from(Some(Timer::new(next_flush_time))).fuse());
263                            retries += 1;
264                            continue;
265                        }
266                        last_flush = MonotonicInstant::now();
267                        has_pending_flush = false;
268                        retrying = false;
269                        retries = 0;
270                    }
271                }
272
273                complete => break,
274            }
275        }
276    }
277
278    pub fn set_caching_enabled(&mut self, enabled: bool) {
279        self.caching_enabled = enabled;
280    }
281
282    pub fn set_debounce_writes(&mut self, debounce: bool) {
283        self.debounce_writes = debounce;
284    }
285
286    async fn inner_write(
287        &self,
288        key: &'static str,
289        new_value: Vec<u8>,
290    ) -> Result<UpdateState, Error> {
291        let typed_storage = self
292            .typed_storage_map
293            .get(key)
294            .ok_or_else(|| format_err!("Invalid data keyed by {}", key))?;
295        let mut cached_storage = typed_storage.cached_storage.lock().await;
296        let bytes;
297        let cached_value = match cached_storage.current_data.as_ref() {
298            Some(cached_value) => Some(cached_value),
299            None => {
300                let file_proxy = fuchsia_fs::directory::open_file(
301                    &self.storage_dir,
302                    &cached_storage.file_path,
303                    fuchsia_fs::PERM_READABLE,
304                )
305                .await;
306                bytes = match file_proxy {
307                    Ok(file_proxy) => match fuchsia_fs::file::read(&file_proxy).await {
308                        Ok(bytes) => Some(bytes),
309                        Err(ReadError::Open(OpenError::OpenError(e))) if e == Status::NOT_FOUND => {
310                            None
311                        }
312                        Err(e) => {
313                            bail!("failed to get value from fidl storage for {:?}: {:?}", key, e)
314                        }
315                    },
316                    Err(OpenError::OpenError(Status::NOT_FOUND)) => None,
317                    Err(e) => bail!("unable to read data on disk for {:?}: {:?}", key, e),
318                };
319                bytes.as_ref()
320            }
321        };
322
323        Ok(if cached_value.map(|c| *c != new_value).unwrap_or(true) {
324            cached_storage.current_data = Some(new_value);
325            if !self.debounce_writes {
326                // Not debouncing writes for testing, just sync immediately.
327                cached_storage
328                    .sync(&self.storage_dir)
329                    .await
330                    .with_context(|| format!("Failed to sync data for key {key:?}"))?;
331            } else {
332                typed_storage.flush_sender.unbounded_send(()).with_context(|| {
333                    format!("flush_sender failed to send flush message, associated key is {key}")
334                })?;
335            }
336            UpdateState::Updated
337        } else {
338            UpdateState::Unchanged
339        })
340    }
341
342    /// Write `new_value` to storage. The write will be persisted to disk at a set interval.
343    pub async fn write<T>(&self, new_value: T) -> Result<UpdateState, Error>
344    where
345        T: FidlStorageConvertible,
346        <T as FidlStorageConvertible>::Storable: Persistable,
347    {
348        let new_value = persist(&new_value.to_storable())?;
349        self.inner_write(T::KEY, new_value).await
350    }
351
352    /// Test-only method to write directly to disk without touching the cache. This is used for
353    /// setting up data as if it existed on disk before the storage was constructed.
354    pub async fn write_test_bytes(&self, key: &'static str, value: Vec<u8>) -> Result<(), Error> {
355        self.inner_write(key, value).await.map(|_| ())
356    }
357
358    async fn get_inner(&self, key: &'static str) -> MutexGuard<'_, CachedStorage> {
359        let typed_storage = self
360            .typed_storage_map
361            .get(key)
362            // TODO(https://fxbug.dev/42064613) Replace this with an error result.
363            .unwrap_or_else(|| panic!("Invalid data keyed by {key}"));
364        let mut cached_storage = typed_storage.cached_storage.lock().await;
365        if (cached_storage.current_data.is_none() || !self.caching_enabled)
366            && let Some(file_proxy) = match fuchsia_fs::directory::open_file(
367                &self.storage_dir,
368                &cached_storage.file_path,
369                fuchsia_fs::PERM_READABLE,
370            )
371            .await
372            {
373                Ok(file_proxy) => Some(file_proxy),
374                Err(OpenError::OpenError(Status::NOT_FOUND)) => None,
375                // TODO(https://fxbug.dev/42064613) Replace this with an error result.
376                Err(e) => panic!("failed to open file for {key:?}: {e:?}"),
377            }
378        {
379            let data = match fuchsia_fs::file::read(&file_proxy).await {
380                Ok(data) => Some(data),
381                Err(ReadError::ReadError(Status::NOT_FOUND)) => None,
382                // TODO(https://fxbug.dev/42064613) Replace this with an error result.
383                Err(e) => panic!("failed to get fidl data from disk for {key:?}: {e:?}"),
384            };
385
386            cached_storage.current_data = data;
387        }
388
389        cached_storage
390    }
391
392    /// Gets the latest value cached locally, or loads the value from storage.
393    /// Doesn't support multiple concurrent callers of the same struct.
394    pub async fn get<T>(&self) -> T
395    where
396        T: FidlStorageConvertible,
397        T::Storable: Persistable,
398        T::Loader: DefaultDispatcher<T>,
399    {
400        match self.get_inner(T::KEY).await.current_data.as_ref().map(|data| {
401            T::from_storable(
402                unpersist(data).expect("Should not be able to save mismatching types in file"),
403            )
404        }) {
405            Some(data) => data,
406            None => <T::Loader as DefaultDispatcher<T>>::get_default(self),
407        }
408    }
409}
410
411pub trait DefaultDispatcher<T>: Sealed {
412    fn get_default(_: &FidlStorage) -> T;
413}
414
415impl<T> DefaultDispatcher<T> for NoneT
416where
417    T: Default,
418{
419    fn get_default(_: &FidlStorage) -> T {
420        T::default()
421    }
422}
423
424impl<T, L> DefaultDispatcher<T> for L
425where
426    T: FidlStorageConvertible<Loader = L>,
427    L: DefaultLoader<Result = T> + 'static,
428{
429    fn get_default(storage: &FidlStorage) -> T {
430        match storage.typed_loader_map.get(T::KEY) {
431            Some(loader) => match loader.downcast_ref::<T::Loader>() {
432                Some(loader) => loader.default_value(),
433                None => {
434                    panic!("Mismatch key and loader for key {}", T::KEY);
435                }
436            },
437            None => panic!("Missing loader for {}", T::KEY),
438        }
439    }
440}
441
442#[cfg(test)]
443mod tests {
444    use super::*;
445    use assert_matches::assert_matches;
446    use fasync::TestExecutor;
447    use fidl::epitaph::ChannelEpitaphExt;
448    use fidl_fuchsia_io as fio;
449    use fidl_test_storage::{TestStruct, WrongStruct};
450    use fuchsia_async as fasync;
451    use futures::TryStreamExt;
452    use std::sync::Arc;
453    use std::task::Poll;
454    use test_case::test_case;
455
456    const VALUE0: i32 = 3;
457    const VALUE1: i32 = 33;
458    const VALUE2: i32 = 128;
459
460    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
461    struct LibTestStruct {
462        value: i32,
463    }
464
465    impl FidlStorageConvertible for LibTestStruct {
466        type Storable = TestStruct;
467        type Loader = NoneT;
468        const KEY: &'static str = "testkey";
469
470        fn to_storable(self) -> Self::Storable {
471            TestStruct { value: self.value }
472        }
473
474        fn from_storable(storable: Self::Storable) -> Self {
475            Self { value: storable.value }
476        }
477    }
478
479    impl Default for LibTestStruct {
480        fn default() -> Self {
481            Self { value: VALUE0 }
482        }
483    }
484
485    fn open_tempdir(tempdir: &tempfile::TempDir) -> fio::DirectoryProxy {
486        fuchsia_fs::directory::open_in_namespace(
487            tempdir.path().to_str().expect("tempdir path is not valid UTF-8"),
488            fuchsia_fs::PERM_READABLE | fuchsia_fs::PERM_WRITABLE,
489        )
490        .expect("failed to open connection to tempdir")
491    }
492
493    #[fuchsia::test]
494    async fn test_get() {
495        let value_to_get = LibTestStruct { value: VALUE1 };
496        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
497        let content = persist(&value_to_get.to_storable()).unwrap();
498        std::fs::write(tempdir.path().join("xyz.pfidl"), content).expect("failed to write file");
499        let storage_dir = open_tempdir(&tempdir);
500
501        let (storage, sync_tasks) = FidlStorage::with_file_proxy(
502            vec![(LibTestStruct::KEY, None)],
503            storage_dir,
504            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
505        )
506        .await
507        .expect("should be able to generate file");
508        for task in sync_tasks {
509            task.detach();
510        }
511        let result = storage.get::<LibTestStruct>().await;
512
513        assert_eq!(result.value, VALUE1);
514    }
515
516    #[fuchsia::test]
517    async fn test_get_default() {
518        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
519        let storage_dir = open_tempdir(&tempdir);
520
521        let (storage, sync_tasks) = FidlStorage::with_file_proxy(
522            vec![(LibTestStruct::KEY, None)],
523            storage_dir,
524            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
525        )
526        .await
527        .expect("file proxy should be created");
528        for task in sync_tasks {
529            task.detach();
530        }
531        let result = storage.get::<LibTestStruct>().await;
532
533        assert_eq!(result.value, VALUE0);
534    }
535
536    /// Proxies directory request to a real directory while allowing for some of the requests to be
537    /// intercepted.
538    struct DirectoryInterceptor {
539        real_dir: fio::DirectoryProxy,
540        inner: std::sync::Mutex<DirectoryInterceptorInner>,
541    }
542
543    struct DirectoryInterceptorInner {
544        sync_notifier: Option<futures::channel::mpsc::UnboundedSender<()>>,
545        #[allow(clippy::type_complexity)]
546        open_interceptor: Box<dyn Fn(&str, bool) -> Option<Status>>,
547    }
548
549    impl DirectoryInterceptor {
550        // TODO(b/356474618): re-enable and fix existing occurance
551        #[allow(clippy::arc_with_non_send_sync)]
552        fn new(real_dir: fio::DirectoryProxy) -> (Arc<Self>, fio::DirectoryProxy) {
553            let (proxy, requests) =
554                fidl::endpoints::create_proxy_and_stream::<fio::DirectoryMarker>();
555            let this = Arc::new(Self {
556                real_dir,
557                inner: std::sync::Mutex::new(DirectoryInterceptorInner {
558                    sync_notifier: None,
559                    open_interceptor: Box::new(|_, _| None),
560                }),
561            });
562            fasync::Task::local(this.clone().run(requests)).detach();
563            (this.clone(), proxy)
564        }
565
566        /// Returns a receiver that will be notified after each Sync request to the real directory
567        /// has completed.
568        fn install_sync_notifier(&self) -> futures::channel::mpsc::UnboundedReceiver<()> {
569            let (sender, receiver) = futures::channel::mpsc::unbounded();
570            self.inner.lock().unwrap().sync_notifier = Some(sender);
571            receiver
572        }
573
574        /// Sets a callback to be called on every Open request. If the callback returns an error,
575        /// then the request will be failed with that error instead of being forwarded to the real
576        /// directory.
577        #[allow(clippy::type_complexity)]
578        fn set_open_interceptor(&self, interceptor: Box<dyn Fn(&str, bool) -> Option<Status>>) {
579            self.inner.lock().unwrap().open_interceptor = interceptor;
580        }
581
582        async fn run(self: Arc<Self>, mut requests: fio::DirectoryRequestStream) {
583            while let Ok(Some(request)) = requests.try_next().await {
584                match request {
585                    fio::DirectoryRequest::Open {
586                        path,
587                        flags,
588                        options,
589                        object,
590                        control_handle: _,
591                    } => {
592                        let create = flags.intersects(fio::Flags::FLAG_MUST_CREATE);
593                        match (self.inner.lock().unwrap().open_interceptor)(&path, create) {
594                            Some(status) => {
595                                object.close_with_epitaph(status).expect("failed to send epitaph");
596                            }
597                            None => {
598                                self.real_dir
599                                    .open(&path, flags, &options, object)
600                                    .expect("failed to forward Open3 request");
601                            }
602                        }
603                    }
604                    fio::DirectoryRequest::Sync { responder } => {
605                        let response =
606                            self.real_dir.sync().await.expect("failed to forward Sync request");
607                        responder.send(response).expect("failed to respond to Sync request");
608                        if let Some(sender) = &self.inner.lock().unwrap().sync_notifier {
609                            sender.unbounded_send(()).unwrap();
610                        }
611                    }
612                    fio::DirectoryRequest::Rename { src, dst_parent_token, dst, responder } => {
613                        let response = self
614                            .real_dir
615                            .rename(&src, dst_parent_token, &dst)
616                            .await
617                            .expect("failed to forward Rename request");
618                        responder.send(response).expect("failed to respond to Rename request");
619                    }
620                    fio::DirectoryRequest::GetToken { responder } => {
621                        let response = self
622                            .real_dir
623                            .get_token()
624                            .await
625                            .expect("failed to forward GetToken request");
626                        responder
627                            .send(response.0, response.1)
628                            .expect("failed to respond to GetToken request");
629                    }
630                    request => unimplemented!("request: {:?}", request),
631                }
632            }
633        }
634    }
635
636    /// Repeatedly polls `fut` until it returns `Poll::Ready`. When using a `TestExecutor` with fake
637    /// time, only `run_until_stalled` can be used but `run_until_stalled` is incompatible with
638    /// external filesystems. This function bridges the gap by continuously polling the future until
639    /// the filesystem responds.
640    fn run_until_ready<F>(executor: &mut TestExecutor, fut: F) -> F::Output
641    where
642        F: std::future::Future,
643    {
644        let mut fut = std::pin::pin!(fut);
645        loop {
646            match executor.run_until_stalled(&mut fut) {
647                Poll::Ready(result) => return result,
648                Poll::Pending => std::thread::yield_now(),
649            }
650        }
651    }
652
653    /// Asserts that a file doesn't exist.
654    fn assert_file_not_found(
655        executor: &mut TestExecutor,
656        directory: &fio::DirectoryProxy,
657        file_name: &str,
658    ) {
659        let open_fut =
660            fuchsia_fs::directory::open_file(directory, file_name, fuchsia_fs::PERM_READABLE);
661        let result = run_until_ready(executor, open_fut);
662        assert_matches!(result, Result::Err(e) if e.is_not_found_error());
663    }
664
665    /// Verifies the contents of a file.
666    fn assert_file_contents(
667        executor: &mut TestExecutor,
668        directory: &fio::DirectoryProxy,
669        file_name: &str,
670        expected_contents: TestStruct,
671    ) {
672        let read_fut = fuchsia_fs::directory::read_file(directory, file_name);
673        let data = run_until_ready(executor, read_fut).expect("reading file");
674        let data = fidl::unpersist::<TestStruct>(&data).expect("failed to read file as TestStruct");
675        assert_eq!(data, expected_contents);
676    }
677
678    #[fuchsia::test]
679    fn test_first_write_syncs_immediately() {
680        let written_value = VALUE1;
681        let mut executor = TestExecutor::new_with_fake_time();
682        executor.set_fake_time(MonotonicInstant::from_nanos(0));
683
684        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
685        let storage_dir = open_tempdir(&tempdir);
686        let (interceptor, storage_dir) = DirectoryInterceptor::new(storage_dir);
687        let mut sync_receiver = interceptor.install_sync_notifier();
688
689        let storage_fut = FidlStorage::with_file_proxy(
690            vec![(LibTestStruct::KEY, None)],
691            Clone::clone(&storage_dir),
692            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
693        );
694        futures::pin_mut!(storage_fut);
695
696        let (storage, _sync_tasks) =
697            if let Poll::Ready(storage) = executor.run_until_stalled(&mut storage_fut) {
698                storage.expect("file proxy should be created")
699            } else {
700                panic!("storage creation stalled");
701            };
702
703        // Write to device storage.
704        let value_to_write = LibTestStruct { value: written_value };
705        let write_future = storage.write(value_to_write);
706        futures::pin_mut!(write_future);
707
708        // Initial cache check is done if no read was ever performed.
709        assert_matches!(
710            run_until_ready(&mut executor, &mut write_future),
711            Result::Ok(UpdateState::Updated)
712        );
713
714        // Storage is not yet ready.
715        assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
716
717        // Wait for the sync task to complete.
718        run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
719
720        // Validate the value matches what was set.
721        assert_file_contents(
722            &mut executor,
723            &storage_dir,
724            "xyz.pfidl",
725            value_to_write.to_storable(),
726        );
727    }
728
729    #[fuchsia::test]
730    fn test_second_write_syncs_after_interval() {
731        let written_value = VALUE1;
732        let second_value = VALUE2;
733        let mut executor = TestExecutor::new_with_fake_time();
734        executor.set_fake_time(MonotonicInstant::from_nanos(0));
735
736        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
737        let storage_dir = open_tempdir(&tempdir);
738        let (interceptor, storage_dir) = DirectoryInterceptor::new(storage_dir);
739        let mut sync_receiver = interceptor.install_sync_notifier();
740
741        let storage_fut = FidlStorage::with_file_proxy(
742            vec![(LibTestStruct::KEY, None)],
743            Clone::clone(&storage_dir),
744            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
745        );
746        futures::pin_mut!(storage_fut);
747
748        let (storage, _sync_tasks) =
749            if let Poll::Ready(storage) = executor.run_until_stalled(&mut storage_fut) {
750                storage.expect("file proxy should be created")
751            } else {
752                panic!("storage creation stalled");
753            };
754
755        // Write to device storage.
756        let value_to_write = LibTestStruct { value: written_value };
757        let write_future = storage.write(value_to_write);
758        futures::pin_mut!(write_future);
759
760        // Initial cache check is done if no read was ever performed.
761        assert_matches!(
762            run_until_ready(&mut executor, &mut write_future),
763            Result::Ok(UpdateState::Updated)
764        );
765
766        // Storage is not yet ready.
767        assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
768
769        // Wait for the sync task to complete.
770        run_until_ready(&mut executor, &mut sync_receiver.next()).expect("directory never synced");
771
772        // Validate that the file has been synced.
773        assert_file_contents(
774            &mut executor,
775            &storage_dir,
776            "xyz.pfidl",
777            value_to_write.to_storable(),
778        );
779
780        // Write second time to device storage.
781        let value_to_write2 = LibTestStruct { value: second_value };
782        let write_future = storage.write(value_to_write2);
783        futures::pin_mut!(write_future);
784
785        // Initial cache check is done if no read was ever performed.
786        assert_matches!(
787            run_until_ready(&mut executor, &mut write_future),
788            Result::Ok(UpdateState::Updated)
789        );
790
791        // Storage is not yet ready, should still equal old value.
792        assert_file_contents(
793            &mut executor,
794            &storage_dir,
795            "xyz.pfidl",
796            value_to_write.to_storable(),
797        );
798
799        // Move executor to just before sync interval.
800        executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000 - 1));
801        assert!(!executor.wake_expired_timers());
802
803        // Move executor to just after sync interval. It should run now.
804        executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000));
805        run_until_ready(&mut executor, &mut sync_receiver.next()).expect("directory never synced");
806
807        // Validate that the file has been synced.
808
809        assert_file_contents(
810            &mut executor,
811            &storage_dir,
812            "xyz.pfidl",
813            value_to_write2.to_storable(),
814        );
815    }
816
817    #[derive(Copy, Clone, Default, Debug)]
818    struct LibWrongStruct;
819
820    impl FidlStorageConvertible for LibWrongStruct {
821        type Storable = WrongStruct;
822        type Loader = NoneT;
823        const KEY: &'static str = "WRONG_STRUCT";
824
825        fn to_storable(self) -> Self::Storable {
826            WrongStruct
827        }
828
829        fn from_storable(_: Self::Storable) -> Self {
830            LibWrongStruct
831        }
832    }
833
834    // Test that attempting to write two kinds of structs to a storage instance that only supports
835    // one results in a failure.
836    #[fuchsia::test]
837    async fn test_write_with_mismatch_type_returns_error() {
838        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
839        let storage_dir = open_tempdir(&tempdir);
840
841        let (storage, sync_tasks) = FidlStorage::with_file_proxy(
842            vec![(LibTestStruct::KEY, None)],
843            storage_dir,
844            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
845        )
846        .await
847        .expect("file proxy should be created");
848        for task in sync_tasks {
849            task.detach();
850        }
851
852        // Write successfully to storage once.
853        let result = storage.write(LibTestStruct { value: VALUE2 }).await;
854        assert!(result.is_ok());
855
856        // Write to device storage again with a different type to validate that the type can't
857        // be changed.
858        let result = storage.write(LibWrongStruct).await;
859        assert_matches!(result, Err(e) if e.to_string() == "Invalid data keyed by WRONG_STRUCT");
860    }
861
862    // Test that multiple writes to FidlStorage will cause a write each time, but will only
863    // sync to the fs at an interval.
864    #[fuchsia::test]
865    fn test_multiple_write_debounce() {
866        // Custom executor for this test so that we can advance the clock arbitrarily and verify the
867        // state of the executor at any given point.
868        let mut executor = TestExecutor::new_with_fake_time();
869        executor.set_fake_time(MonotonicInstant::from_nanos(0));
870
871        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
872        let storage_dir = open_tempdir(&tempdir);
873        let (interceptor, storage_dir) = DirectoryInterceptor::new(storage_dir);
874        let mut sync_receiver = interceptor.install_sync_notifier();
875
876        let storage_fut = FidlStorage::with_file_proxy(
877            vec![(LibTestStruct::KEY, None)],
878            Clone::clone(&storage_dir),
879            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
880        );
881        let (storage, _sync_tasks) =
882            run_until_ready(&mut executor, storage_fut).expect("file proxy should be created");
883
884        let first_value = VALUE1;
885        let second_value = VALUE2;
886        let third_value = VALUE0;
887
888        // First write finishes immediately.
889        let value_to_write = LibTestStruct { value: first_value };
890        // Initial cache check is done if no read was ever performed.
891        let result = run_until_ready(&mut executor, storage.write(value_to_write));
892        assert_matches!(result, Result::Ok(UpdateState::Updated));
893
894        // Storage is not yet ready.
895        assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
896
897        // Wake the initial time without advancing the clock. Confirms that the first write is
898        // "immediate".
899        run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
900
901        // Validate that the file has been synced.
902        assert_file_contents(
903            &mut executor,
904            &storage_dir,
905            "xyz.pfidl",
906            value_to_write.to_storable(),
907        );
908
909        // Write second time to device storage.
910        let value_to_write2 = LibTestStruct { value: second_value };
911        let result = run_until_ready(&mut executor, storage.write(value_to_write2));
912        // Value is marked as updated after the write.
913        assert_matches!(result, Result::Ok(UpdateState::Updated));
914
915        // Validate the updated values are still returned from the storage cache.
916        let data = run_until_ready(&mut executor, storage.get::<LibTestStruct>());
917        assert_eq!(data, value_to_write2);
918
919        // But the data has not been persisted to disk.
920        assert_file_contents(
921            &mut executor,
922            &storage_dir,
923            "xyz.pfidl",
924            value_to_write.to_storable(),
925        );
926
927        // Now write a third time before advancing the clock.
928        let value_to_write3 = LibTestStruct { value: third_value };
929        let result = run_until_ready(&mut executor, storage.write(value_to_write3));
930        // Value is marked as updated after the write.
931        assert_matches!(result, Result::Ok(UpdateState::Updated));
932
933        // Validate the updated values are still returned from the storage cache.
934
935        let data = run_until_ready(&mut executor, storage.get::<LibTestStruct>());
936        assert_eq!(data, value_to_write3);
937
938        // But the data has still not been persisted to disk.
939        assert_file_contents(
940            &mut executor,
941            &storage_dir,
942            "xyz.pfidl",
943            value_to_write.to_storable(),
944        );
945
946        // Move clock to just before sync interval.
947        executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000 - 1));
948        assert!(!executor.wake_expired_timers());
949
950        // And validate that the data has still not been synced to disk.
951        assert_file_contents(
952            &mut executor,
953            &storage_dir,
954            "xyz.pfidl",
955            value_to_write.to_storable(),
956        );
957
958        // Move executor to just after sync interval.
959        executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000));
960        run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
961
962        // Validate that the file has finally been synced.
963        assert_file_contents(
964            &mut executor,
965            &storage_dir,
966            "xyz.pfidl",
967            value_to_write3.to_storable(),
968        );
969    }
970
971    // Tests that syncing can recover after a failed write. The test cases list the number of failed
972    // attempts and the maximum amount of time waited from the previous write.
973    #[allow(clippy::unused_unit)]
974    #[test_case(1, 500)]
975    #[test_case(2, 1_000)]
976    #[test_case(3, 2_000)]
977    #[test_case(4, 4_000)]
978    #[test_case(5, 8_000)]
979    #[test_case(6, 16_000)]
980    #[test_case(7, 32_000)]
981    #[test_case(8, 64_000)]
982    #[test_case(9, 128_000)]
983    #[test_case(10, 256_000)]
984    #[test_case(11, 512_000)]
985    #[test_case(12, 1_024_000)]
986    #[test_case(13, 1_800_000)]
987    #[test_case(14, 1_800_000)]
988    fn test_exponential_backoff(retry_count: usize, max_wait_time: usize) {
989        let mut executor = TestExecutor::new_with_fake_time();
990        executor.set_fake_time(MonotonicInstant::from_nanos(0));
991
992        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
993        let storage_dir = open_tempdir(&tempdir);
994        let (interceptor, storage_dir) = DirectoryInterceptor::new(storage_dir);
995        let attempts = std::sync::Mutex::new(0);
996        interceptor.set_open_interceptor(Box::new(move |path, create| {
997            let mut attempts_guard = attempts.lock().unwrap();
998            if path == "abc_tmp.pfidl" && create && *attempts_guard < retry_count {
999                *attempts_guard += 1;
1000                Some(Status::NO_SPACE)
1001            } else {
1002                None
1003            }
1004        }));
1005        let mut sync_receiver = interceptor.install_sync_notifier();
1006
1007        let expected_data = vec![1];
1008        let cached_storage = Rc::new(Mutex::new(CachedStorage {
1009            current_data: Some(expected_data.clone()),
1010            temp_file_path: "abc_tmp.pfidl".to_owned(),
1011            file_path: "abc.pfidl".to_owned(),
1012        }));
1013
1014        let (sender, receiver) = futures::channel::mpsc::unbounded();
1015
1016        // Call spawn in a future since we have to be in an executor context to call spawn.
1017        let task = fasync::Task::local(FidlStorage::synchronize_task(
1018            Clone::clone(&storage_dir),
1019            Rc::clone(&cached_storage),
1020            receiver,
1021        ));
1022        futures::pin_mut!(task);
1023
1024        executor.set_fake_time(MonotonicInstant::from_nanos(0));
1025        sender.unbounded_send(()).expect("can send flush signal");
1026        assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1027
1028        let mut clock_nanos = 0;
1029        // (2^i) * 500 = exponential backoff.
1030        // 1,000,000 = convert ms to ns.
1031        for new_duration in (0..retry_count).map(|i| {
1032            (2_i64.pow(i as u32) * MIN_FLUSH_INTERVAL_MS).min(max_wait_time as i64) * 1_000_000
1033                - (i == retry_count - 1) as i64
1034        }) {
1035            executor.set_fake_time(MonotonicInstant::from_nanos(clock_nanos));
1036            // Task should not complete while retrying.
1037            assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1038
1039            // Check that files don't exist.
1040            assert_file_not_found(&mut executor, &storage_dir, "abc_tmp.pfidl");
1041            assert_file_not_found(&mut executor, &storage_dir, "abc.pfidl");
1042
1043            clock_nanos += new_duration;
1044        }
1045
1046        executor.set_fake_time(MonotonicInstant::from_nanos(clock_nanos));
1047        // At this point the clock should be 1ns before the timer, so it shouldn't wake.
1048        assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1049
1050        // Check that files don't exist.
1051        assert_file_not_found(&mut executor, &storage_dir, "abc_tmp.pfidl");
1052        assert_file_not_found(&mut executor, &storage_dir, "abc.pfidl");
1053
1054        // Now pass the timer where we can read the result.
1055        clock_nanos += 1;
1056        executor.set_fake_time(MonotonicInstant::from_nanos(clock_nanos));
1057        assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1058        run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
1059
1060        // Check that the file now matches what was in the cache.
1061        let read_fut = fuchsia_fs::directory::read_file(&storage_dir, "abc.pfidl");
1062        let data = run_until_ready(&mut executor, read_fut).expect("reading file");
1063        assert_eq!(data, expected_data);
1064
1065        drop(sender);
1066        // Ensure the task can properly exit.
1067        run_until_ready(&mut executor, task);
1068    }
1069}