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::DeprecatedGetToken { responder } => {
621                        let response = self
622                            .real_dir
623                            .deprecated_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                    #[cfg(fuchsia_api_level_at_least = "NEXT")]
631                    fio::DirectoryRequest::GetToken { responder } => {
632                        let response = self
633                            .real_dir
634                            .get_token()
635                            .await
636                            .expect("failed to forward GetToken request");
637                        responder.send(response).expect("failed to respond to GetToken request");
638                    }
639                    request => unimplemented!("request: {:?}", request),
640                }
641            }
642        }
643    }
644
645    /// Repeatedly polls `fut` until it returns `Poll::Ready`. When using a `TestExecutor` with fake
646    /// time, only `run_until_stalled` can be used but `run_until_stalled` is incompatible with
647    /// external filesystems. This function bridges the gap by continuously polling the future until
648    /// the filesystem responds.
649    fn run_until_ready<F>(executor: &mut TestExecutor, fut: F) -> F::Output
650    where
651        F: std::future::Future,
652    {
653        let mut fut = std::pin::pin!(fut);
654        loop {
655            match executor.run_until_stalled(&mut fut) {
656                Poll::Ready(result) => return result,
657                Poll::Pending => std::thread::yield_now(),
658            }
659        }
660    }
661
662    /// Asserts that a file doesn't exist.
663    fn assert_file_not_found(
664        executor: &mut TestExecutor,
665        directory: &fio::DirectoryProxy,
666        file_name: &str,
667    ) {
668        let open_fut =
669            fuchsia_fs::directory::open_file(directory, file_name, fuchsia_fs::PERM_READABLE);
670        let result = run_until_ready(executor, open_fut);
671        assert_matches!(result, Result::Err(e) if e.is_not_found_error());
672    }
673
674    /// Verifies the contents of a file.
675    fn assert_file_contents(
676        executor: &mut TestExecutor,
677        directory: &fio::DirectoryProxy,
678        file_name: &str,
679        expected_contents: TestStruct,
680    ) {
681        let read_fut = fuchsia_fs::directory::read_file(directory, file_name);
682        let data = run_until_ready(executor, read_fut).expect("reading file");
683        let data = fidl::unpersist::<TestStruct>(&data).expect("failed to read file as TestStruct");
684        assert_eq!(data, expected_contents);
685    }
686
687    #[fuchsia::test]
688    fn test_first_write_syncs_immediately() {
689        let written_value = VALUE1;
690        let mut executor = TestExecutor::new_with_fake_time();
691        executor.set_fake_time(MonotonicInstant::from_nanos(0));
692
693        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
694        let storage_dir = open_tempdir(&tempdir);
695        let (interceptor, storage_dir) = DirectoryInterceptor::new(storage_dir);
696        let mut sync_receiver = interceptor.install_sync_notifier();
697
698        let storage_fut = FidlStorage::with_file_proxy(
699            vec![(LibTestStruct::KEY, None)],
700            Clone::clone(&storage_dir),
701            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
702        );
703        futures::pin_mut!(storage_fut);
704
705        let (storage, _sync_tasks) =
706            if let Poll::Ready(storage) = executor.run_until_stalled(&mut storage_fut) {
707                storage.expect("file proxy should be created")
708            } else {
709                panic!("storage creation stalled");
710            };
711
712        // Write to device storage.
713        let value_to_write = LibTestStruct { value: written_value };
714        let write_future = storage.write(value_to_write);
715        futures::pin_mut!(write_future);
716
717        // Initial cache check is done if no read was ever performed.
718        assert_matches!(
719            run_until_ready(&mut executor, &mut write_future),
720            Result::Ok(UpdateState::Updated)
721        );
722
723        // Storage is not yet ready.
724        assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
725
726        // Wait for the sync task to complete.
727        run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
728
729        // Validate the value matches what was set.
730        assert_file_contents(
731            &mut executor,
732            &storage_dir,
733            "xyz.pfidl",
734            value_to_write.to_storable(),
735        );
736    }
737
738    #[fuchsia::test]
739    fn test_second_write_syncs_after_interval() {
740        let written_value = VALUE1;
741        let second_value = VALUE2;
742        let mut executor = TestExecutor::new_with_fake_time();
743        executor.set_fake_time(MonotonicInstant::from_nanos(0));
744
745        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
746        let storage_dir = open_tempdir(&tempdir);
747        let (interceptor, storage_dir) = DirectoryInterceptor::new(storage_dir);
748        let mut sync_receiver = interceptor.install_sync_notifier();
749
750        let storage_fut = FidlStorage::with_file_proxy(
751            vec![(LibTestStruct::KEY, None)],
752            Clone::clone(&storage_dir),
753            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
754        );
755        futures::pin_mut!(storage_fut);
756
757        let (storage, _sync_tasks) =
758            if let Poll::Ready(storage) = executor.run_until_stalled(&mut storage_fut) {
759                storage.expect("file proxy should be created")
760            } else {
761                panic!("storage creation stalled");
762            };
763
764        // Write to device storage.
765        let value_to_write = LibTestStruct { value: written_value };
766        let write_future = storage.write(value_to_write);
767        futures::pin_mut!(write_future);
768
769        // Initial cache check is done if no read was ever performed.
770        assert_matches!(
771            run_until_ready(&mut executor, &mut write_future),
772            Result::Ok(UpdateState::Updated)
773        );
774
775        // Storage is not yet ready.
776        assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
777
778        // Wait for the sync task to complete.
779        run_until_ready(&mut executor, &mut sync_receiver.next()).expect("directory never synced");
780
781        // Validate that the file has been synced.
782        assert_file_contents(
783            &mut executor,
784            &storage_dir,
785            "xyz.pfidl",
786            value_to_write.to_storable(),
787        );
788
789        // Write second time to device storage.
790        let value_to_write2 = LibTestStruct { value: second_value };
791        let write_future = storage.write(value_to_write2);
792        futures::pin_mut!(write_future);
793
794        // Initial cache check is done if no read was ever performed.
795        assert_matches!(
796            run_until_ready(&mut executor, &mut write_future),
797            Result::Ok(UpdateState::Updated)
798        );
799
800        // Storage is not yet ready, should still equal old value.
801        assert_file_contents(
802            &mut executor,
803            &storage_dir,
804            "xyz.pfidl",
805            value_to_write.to_storable(),
806        );
807
808        // Move executor to just before sync interval.
809        executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000 - 1));
810        assert!(!executor.wake_expired_timers());
811
812        // Move executor to just after sync interval. It should run now.
813        executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000));
814        run_until_ready(&mut executor, &mut sync_receiver.next()).expect("directory never synced");
815
816        // Validate that the file has been synced.
817
818        assert_file_contents(
819            &mut executor,
820            &storage_dir,
821            "xyz.pfidl",
822            value_to_write2.to_storable(),
823        );
824    }
825
826    #[derive(Copy, Clone, Default, Debug)]
827    struct LibWrongStruct;
828
829    impl FidlStorageConvertible for LibWrongStruct {
830        type Storable = WrongStruct;
831        type Loader = NoneT;
832        const KEY: &'static str = "WRONG_STRUCT";
833
834        fn to_storable(self) -> Self::Storable {
835            WrongStruct
836        }
837
838        fn from_storable(_: Self::Storable) -> Self {
839            LibWrongStruct
840        }
841    }
842
843    // Test that attempting to write two kinds of structs to a storage instance that only supports
844    // one results in a failure.
845    #[fuchsia::test]
846    async fn test_write_with_mismatch_type_returns_error() {
847        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
848        let storage_dir = open_tempdir(&tempdir);
849
850        let (storage, sync_tasks) = FidlStorage::with_file_proxy(
851            vec![(LibTestStruct::KEY, None)],
852            storage_dir,
853            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
854        )
855        .await
856        .expect("file proxy should be created");
857        for task in sync_tasks {
858            task.detach();
859        }
860
861        // Write successfully to storage once.
862        let result = storage.write(LibTestStruct { value: VALUE2 }).await;
863        assert!(result.is_ok());
864
865        // Write to device storage again with a different type to validate that the type can't
866        // be changed.
867        let result = storage.write(LibWrongStruct).await;
868        assert_matches!(result, Err(e) if e.to_string() == "Invalid data keyed by WRONG_STRUCT");
869    }
870
871    // Test that multiple writes to FidlStorage will cause a write each time, but will only
872    // sync to the fs at an interval.
873    #[fuchsia::test]
874    fn test_multiple_write_debounce() {
875        // Custom executor for this test so that we can advance the clock arbitrarily and verify the
876        // state of the executor at any given point.
877        let mut executor = TestExecutor::new_with_fake_time();
878        executor.set_fake_time(MonotonicInstant::from_nanos(0));
879
880        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
881        let storage_dir = open_tempdir(&tempdir);
882        let (interceptor, storage_dir) = DirectoryInterceptor::new(storage_dir);
883        let mut sync_receiver = interceptor.install_sync_notifier();
884
885        let storage_fut = FidlStorage::with_file_proxy(
886            vec![(LibTestStruct::KEY, None)],
887            Clone::clone(&storage_dir),
888            move |_| Ok((String::from("xyz_temp.pfidl"), String::from("xyz.pfidl"))),
889        );
890        let (storage, _sync_tasks) =
891            run_until_ready(&mut executor, storage_fut).expect("file proxy should be created");
892
893        let first_value = VALUE1;
894        let second_value = VALUE2;
895        let third_value = VALUE0;
896
897        // First write finishes immediately.
898        let value_to_write = LibTestStruct { value: first_value };
899        // Initial cache check is done if no read was ever performed.
900        let result = run_until_ready(&mut executor, storage.write(value_to_write));
901        assert_matches!(result, Result::Ok(UpdateState::Updated));
902
903        // Storage is not yet ready.
904        assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
905
906        // Wake the initial time without advancing the clock. Confirms that the first write is
907        // "immediate".
908        run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
909
910        // Validate that the file has been synced.
911        assert_file_contents(
912            &mut executor,
913            &storage_dir,
914            "xyz.pfidl",
915            value_to_write.to_storable(),
916        );
917
918        // Write second time to device storage.
919        let value_to_write2 = LibTestStruct { value: second_value };
920        let result = run_until_ready(&mut executor, storage.write(value_to_write2));
921        // Value is marked as updated after the write.
922        assert_matches!(result, Result::Ok(UpdateState::Updated));
923
924        // Validate the updated values are still returned from the storage cache.
925        let data = run_until_ready(&mut executor, storage.get::<LibTestStruct>());
926        assert_eq!(data, value_to_write2);
927
928        // But the data has not been persisted to disk.
929        assert_file_contents(
930            &mut executor,
931            &storage_dir,
932            "xyz.pfidl",
933            value_to_write.to_storable(),
934        );
935
936        // Now write a third time before advancing the clock.
937        let value_to_write3 = LibTestStruct { value: third_value };
938        let result = run_until_ready(&mut executor, storage.write(value_to_write3));
939        // Value is marked as updated after the write.
940        assert_matches!(result, Result::Ok(UpdateState::Updated));
941
942        // Validate the updated values are still returned from the storage cache.
943
944        let data = run_until_ready(&mut executor, storage.get::<LibTestStruct>());
945        assert_eq!(data, value_to_write3);
946
947        // But the data has still not been persisted to disk.
948        assert_file_contents(
949            &mut executor,
950            &storage_dir,
951            "xyz.pfidl",
952            value_to_write.to_storable(),
953        );
954
955        // Move clock to just before sync interval.
956        executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000 - 1));
957        assert!(!executor.wake_expired_timers());
958
959        // And validate that the data has still not been synced to disk.
960        assert_file_contents(
961            &mut executor,
962            &storage_dir,
963            "xyz.pfidl",
964            value_to_write.to_storable(),
965        );
966
967        // Move executor to just after sync interval.
968        executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000));
969        run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
970
971        // Validate that the file has finally been synced.
972        assert_file_contents(
973            &mut executor,
974            &storage_dir,
975            "xyz.pfidl",
976            value_to_write3.to_storable(),
977        );
978    }
979
980    // Tests that syncing can recover after a failed write. The test cases list the number of failed
981    // attempts and the maximum amount of time waited from the previous write.
982    #[allow(clippy::unused_unit)]
983    #[test_case(1, 500)]
984    #[test_case(2, 1_000)]
985    #[test_case(3, 2_000)]
986    #[test_case(4, 4_000)]
987    #[test_case(5, 8_000)]
988    #[test_case(6, 16_000)]
989    #[test_case(7, 32_000)]
990    #[test_case(8, 64_000)]
991    #[test_case(9, 128_000)]
992    #[test_case(10, 256_000)]
993    #[test_case(11, 512_000)]
994    #[test_case(12, 1_024_000)]
995    #[test_case(13, 1_800_000)]
996    #[test_case(14, 1_800_000)]
997    fn test_exponential_backoff(retry_count: usize, max_wait_time: usize) {
998        let mut executor = TestExecutor::new_with_fake_time();
999        executor.set_fake_time(MonotonicInstant::from_nanos(0));
1000
1001        let tempdir = tempfile::tempdir().expect("failed to create tempdir");
1002        let storage_dir = open_tempdir(&tempdir);
1003        let (interceptor, storage_dir) = DirectoryInterceptor::new(storage_dir);
1004        let attempts = std::sync::Mutex::new(0);
1005        interceptor.set_open_interceptor(Box::new(move |path, create| {
1006            let mut attempts_guard = attempts.lock().unwrap();
1007            if path == "abc_tmp.pfidl" && create && *attempts_guard < retry_count {
1008                *attempts_guard += 1;
1009                Some(Status::NO_SPACE)
1010            } else {
1011                None
1012            }
1013        }));
1014        let mut sync_receiver = interceptor.install_sync_notifier();
1015
1016        let expected_data = vec![1];
1017        let cached_storage = Rc::new(Mutex::new(CachedStorage {
1018            current_data: Some(expected_data.clone()),
1019            temp_file_path: "abc_tmp.pfidl".to_owned(),
1020            file_path: "abc.pfidl".to_owned(),
1021        }));
1022
1023        let (sender, receiver) = futures::channel::mpsc::unbounded();
1024
1025        // Call spawn in a future since we have to be in an executor context to call spawn.
1026        let task = fasync::Task::local(FidlStorage::synchronize_task(
1027            Clone::clone(&storage_dir),
1028            Rc::clone(&cached_storage),
1029            receiver,
1030        ));
1031        futures::pin_mut!(task);
1032
1033        executor.set_fake_time(MonotonicInstant::from_nanos(0));
1034        sender.unbounded_send(()).expect("can send flush signal");
1035        assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1036
1037        let mut clock_nanos = 0;
1038        // (2^i) * 500 = exponential backoff.
1039        // 1,000,000 = convert ms to ns.
1040        for new_duration in (0..retry_count).map(|i| {
1041            (2_i64.pow(i as u32) * MIN_FLUSH_INTERVAL_MS).min(max_wait_time as i64) * 1_000_000
1042                - (i == retry_count - 1) as i64
1043        }) {
1044            executor.set_fake_time(MonotonicInstant::from_nanos(clock_nanos));
1045            // Task should not complete while retrying.
1046            assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1047
1048            // Check that files don't exist.
1049            assert_file_not_found(&mut executor, &storage_dir, "abc_tmp.pfidl");
1050            assert_file_not_found(&mut executor, &storage_dir, "abc.pfidl");
1051
1052            clock_nanos += new_duration;
1053        }
1054
1055        executor.set_fake_time(MonotonicInstant::from_nanos(clock_nanos));
1056        // At this point the clock should be 1ns before the timer, so it shouldn't wake.
1057        assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1058
1059        // Check that files don't exist.
1060        assert_file_not_found(&mut executor, &storage_dir, "abc_tmp.pfidl");
1061        assert_file_not_found(&mut executor, &storage_dir, "abc.pfidl");
1062
1063        // Now pass the timer where we can read the result.
1064        clock_nanos += 1;
1065        executor.set_fake_time(MonotonicInstant::from_nanos(clock_nanos));
1066        assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1067        run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
1068
1069        // Check that the file now matches what was in the cache.
1070        let read_fut = fuchsia_fs::directory::read_file(&storage_dir, "abc.pfidl");
1071        let data = run_until_ready(&mut executor, read_fut).expect("reading file");
1072        assert_eq!(data, expected_data);
1073
1074        drop(sender);
1075        // Ensure the task can properly exit.
1076        run_until_ready(&mut executor, task);
1077    }
1078}