1use 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
26const MIN_FLUSH_INTERVAL_MS: i64 = 500;
29const MAX_FLUSH_INTERVAL_MS: i64 = 1_800_000; const 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
42pub struct FidlStorage {
45 typed_storage_map: HashMap<&'static str, TypedStorage>,
47
48 typed_loader_map: HashMap<&'static str, Box<dyn Any>>,
49
50 caching_enabled: bool,
52
53 debounce_writes: bool,
56
57 storage_dir: DirectoryProxy,
58}
59
60struct TypedStorage {
63 flush_sender: UnboundedSender<()>,
65
66 cached_storage: Rc<Mutex<CachedStorage>>,
68}
69
70struct CachedStorage {
73 current_data: Option<Vec<u8>>,
76
77 temp_file_path: String,
88
89 file_path: String,
91}
92
93impl CachedStorage {
94 async fn sync(&mut self, storage_dir: &DirectoryProxy) -> Result<(), Error> {
96 {
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 .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 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 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 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 let mut last_flush: MonotonicInstant = MonotonicInstant::now() - MIN_FLUSH_DURATION;
202
203 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 if retrying {
218 continue;
219 }
220
221 let now = MonotonicInstant::now();
223 let next_flush_time = if now - last_flush > MIN_FLUSH_DURATION {
224 now
227 } else {
228 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 if has_pending_flush {
241 let mut cached_storage = cached_storage.lock().await;
242
243 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 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 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 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 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 .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 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 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 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 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 #[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 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 #[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 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 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 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 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 assert_matches!(
719 run_until_ready(&mut executor, &mut write_future),
720 Result::Ok(UpdateState::Updated)
721 );
722
723 assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
725
726 run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
728
729 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 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 assert_matches!(
771 run_until_ready(&mut executor, &mut write_future),
772 Result::Ok(UpdateState::Updated)
773 );
774
775 assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
777
778 run_until_ready(&mut executor, &mut sync_receiver.next()).expect("directory never synced");
780
781 assert_file_contents(
783 &mut executor,
784 &storage_dir,
785 "xyz.pfidl",
786 value_to_write.to_storable(),
787 );
788
789 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 assert_matches!(
796 run_until_ready(&mut executor, &mut write_future),
797 Result::Ok(UpdateState::Updated)
798 );
799
800 assert_file_contents(
802 &mut executor,
803 &storage_dir,
804 "xyz.pfidl",
805 value_to_write.to_storable(),
806 );
807
808 executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000 - 1));
810 assert!(!executor.wake_expired_timers());
811
812 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 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 #[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 let result = storage.write(LibTestStruct { value: VALUE2 }).await;
863 assert!(result.is_ok());
864
865 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 #[fuchsia::test]
874 fn test_multiple_write_debounce() {
875 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 let value_to_write = LibTestStruct { value: first_value };
899 let result = run_until_ready(&mut executor, storage.write(value_to_write));
901 assert_matches!(result, Result::Ok(UpdateState::Updated));
902
903 assert_file_not_found(&mut executor, &storage_dir, "xyz.pfidl");
905
906 run_until_ready(&mut executor, sync_receiver.next()).expect("directory never synced");
909
910 assert_file_contents(
912 &mut executor,
913 &storage_dir,
914 "xyz.pfidl",
915 value_to_write.to_storable(),
916 );
917
918 let value_to_write2 = LibTestStruct { value: second_value };
920 let result = run_until_ready(&mut executor, storage.write(value_to_write2));
921 assert_matches!(result, Result::Ok(UpdateState::Updated));
923
924 let data = run_until_ready(&mut executor, storage.get::<LibTestStruct>());
926 assert_eq!(data, value_to_write2);
927
928 assert_file_contents(
930 &mut executor,
931 &storage_dir,
932 "xyz.pfidl",
933 value_to_write.to_storable(),
934 );
935
936 let value_to_write3 = LibTestStruct { value: third_value };
938 let result = run_until_ready(&mut executor, storage.write(value_to_write3));
939 assert_matches!(result, Result::Ok(UpdateState::Updated));
941
942 let data = run_until_ready(&mut executor, storage.get::<LibTestStruct>());
945 assert_eq!(data, value_to_write3);
946
947 assert_file_contents(
949 &mut executor,
950 &storage_dir,
951 "xyz.pfidl",
952 value_to_write.to_storable(),
953 );
954
955 executor.set_fake_time(MonotonicInstant::from_nanos(MIN_FLUSH_INTERVAL_MS * 1_000_000 - 1));
957 assert!(!executor.wake_expired_timers());
958
959 assert_file_contents(
961 &mut executor,
962 &storage_dir,
963 "xyz.pfidl",
964 value_to_write.to_storable(),
965 );
966
967 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 assert_file_contents(
973 &mut executor,
974 &storage_dir,
975 "xyz.pfidl",
976 value_to_write3.to_storable(),
977 );
978 }
979
980 #[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 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 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 assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1047
1048 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 assert_eq!(executor.run_until_stalled(&mut task), Poll::Pending);
1058
1059 assert_file_not_found(&mut executor, &storage_dir, "abc_tmp.pfidl");
1061 assert_file_not_found(&mut executor, &storage_dir, "abc.pfidl");
1062
1063 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 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 run_until_ready(&mut executor, task);
1077 }
1078}