1use anyhow::Context;
6use chrono::{Datelike, TimeZone, Timelike};
7use fidl::endpoints::ServerEnd;
8use fidl_fuchsia_hardware_rtc::{DeviceRequest, DeviceRequestStream};
9use fidl_fuchsia_io as fio;
10use fidl_fuchsia_metrics::MetricEvent;
11use fidl_fuchsia_metrics_test::{LogMethod, MetricEventLoggerQuerierProxy};
12use fidl_fuchsia_testing::{FakeClockControlProxy, FakeClockProxy};
13use fidl_fuchsia_time::{MaintenanceRequest, MaintenanceRequestStream};
14use fidl_fuchsia_time_external::{PushSourceMarker, Status, TimeSample};
15use fidl_test_time::{TimeSourceControlRequest, TimeSourceControlRequestStream};
16use fuchsia_async as fasync;
17use fuchsia_component::server::ServiceFs;
18use fuchsia_component_test::{
19 Capability, ChildOptions, ChildRef, LocalComponentHandles, RealmBuilder, RealmInstance, Ref,
20 Route,
21};
22use fuchsia_sync::Mutex;
23use futures::channel::mpsc::Sender;
24use futures::stream::{Stream, StreamExt, TryStreamExt};
25use futures::{Future, FutureExt, SinkExt};
26use push_source::{PushSource, TestUpdateAlgorithm, Update};
27use std::ops::Deref;
28use std::sync::{Arc, LazyLock};
29use time_metrics_registry::PROJECT_ID;
30use vfs::pseudo_directory;
31use zx::{self as zx, Rights};
32
33const TIMEKEEPER_URL: &str = "#meta/timekeeper_for_integration.cm";
35const TIMEKEEPER_FAKE_TIME_URL: &str = "#meta/timekeeper_with_fake_time.cm";
37const COBALT_URL: &str = "#meta/fake_cobalt.cm";
39const FAKE_CLOCK_URL: &str = "#meta/fake_clock.cm";
41
42pub struct NestedTimekeeper {
45 _realm_instance: RealmInstance,
46}
47
48impl Into<RealmInstance> for NestedTimekeeper {
49 fn into(self) -> RealmInstance {
51 self._realm_instance
52 }
53}
54
55impl NestedTimekeeper {
56 pub async fn new(
69 clock: Arc<zx::Clock>,
70 rtc_options: RtcOptions,
71 use_fake_clock: bool,
72 ) -> (
73 Self,
74 Arc<PushSourcePuppet>,
75 RtcUpdates,
76 MetricEventLoggerQuerierProxy,
77 Option<FakeClockController>,
78 ) {
79 let push_source_puppet = Arc::new(PushSourcePuppet::new());
80
81 let builder = RealmBuilder::new().await.unwrap();
82 let fake_cobalt =
83 builder.add_child("fake_cobalt", COBALT_URL, ChildOptions::new()).await.unwrap();
84
85 let timekeeper_url = if use_fake_clock { TIMEKEEPER_FAKE_TIME_URL } else { TIMEKEEPER_URL };
86 log::trace!("using timekeeper_url: {}", timekeeper_url);
87 let timekeeper = builder
88 .add_child("timekeeper_test", timekeeper_url, ChildOptions::new().eager())
89 .await
90 .with_context(|| format!("while starting up timekeeper_test from: {timekeeper_url}"))
91 .unwrap();
92
93 let timesource_server = builder
94 .add_local_child(
95 "timesource_mock",
96 {
97 let push_source_puppet = Arc::clone(&push_source_puppet);
98 move |handles: LocalComponentHandles| {
99 Box::pin(timesource_mock_server(handles, Arc::clone(&push_source_puppet)))
100 }
101 },
102 ChildOptions::new(),
103 )
104 .await
105 .context("while starting up timesource_mock")
106 .unwrap();
107
108 let maintenance_server = builder
109 .add_local_child(
110 "maintenance_mock",
111 move |handles: LocalComponentHandles| {
112 Box::pin(maintenance_mock_server(handles, Arc::clone(&clock)))
113 },
114 ChildOptions::new(),
115 )
116 .await
117 .context("while starting up maintenance_mock")
118 .unwrap();
119
120 if use_fake_clock {
122 let fake_clock =
123 builder.add_child("fake_clock", FAKE_CLOCK_URL, ChildOptions::new()).await.unwrap();
124
125 builder
126 .add_route(
127 Route::new()
128 .capability(Capability::protocol_by_name(
129 "fuchsia.testing.FakeClockControl",
130 ))
131 .from(&fake_clock)
132 .to(Ref::parent()),
133 )
134 .await
135 .context("while setting up FakeClockControl")
136 .unwrap();
137
138 builder
139 .add_route(
140 Route::new()
141 .capability(Capability::protocol_by_name("fuchsia.testing.FakeClock"))
142 .from(&fake_clock)
143 .to(Ref::parent())
144 .to(&timekeeper),
145 )
146 .await
147 .context("while setting up FakeClock")
148 .unwrap();
149
150 builder
151 .add_route(
152 Route::new()
153 .capability(Capability::protocol_by_name("fuchsia.logger.LogSink"))
154 .from(Ref::parent())
155 .to(&fake_clock),
156 )
157 .await
158 .context("while setting up LogSink")
159 .unwrap();
160 };
161
162 builder
163 .add_route(
164 Route::new()
165 .capability(Capability::protocol_by_name("fuchsia.time.Maintenance"))
166 .from(&maintenance_server)
167 .to(&timekeeper),
168 )
169 .await
170 .context("while setting up Maintenance")
171 .unwrap();
172
173 builder
174 .add_route(
175 Route::new()
176 .capability(Capability::protocol_by_name("test.time.TimeSourceControl"))
177 .from(×ource_server)
178 .to(&timekeeper),
179 )
180 .await
181 .unwrap();
182
183 builder
184 .add_route(
185 Route::new()
186 .capability(Capability::protocol_by_name(
187 "fuchsia.metrics.test.MetricEventLoggerQuerier",
188 ))
189 .from(&fake_cobalt)
190 .to(Ref::parent()),
191 )
192 .await
193 .unwrap();
194
195 builder
196 .add_route(
197 Route::new()
198 .capability(Capability::protocol_by_name(
199 "fuchsia.metrics.MetricEventLoggerFactory",
200 ))
201 .from(&fake_cobalt)
202 .to(&timekeeper),
203 )
204 .await
205 .unwrap();
206
207 builder
208 .add_route(
209 Route::new()
210 .capability(Capability::protocol_by_name("fuchsia.logger.LogSink"))
211 .from(Ref::parent())
212 .to(&fake_cobalt)
213 .to(&timekeeper)
214 .to(×ource_server)
215 .to(&maintenance_server),
216 )
217 .await
218 .unwrap();
219
220 builder
221 .add_route(
222 Route::new()
223 .capability(Capability::configuration("fuchsia.time.config.WritableUTCTime"))
224 .from(Ref::parent())
225 .to(&timekeeper),
226 )
227 .await
228 .unwrap();
229
230 builder
231 .add_route(
232 Route::new()
233 .capability(Capability::configuration(
234 "fuchsia.time.config.TimeSourceEndpointUrl",
235 ))
236 .from(Ref::void())
237 .to(&timekeeper),
238 )
239 .await
240 .unwrap();
241
242 let rtc_updates = setup_rtc(rtc_options, &builder, &timekeeper).await;
243 let realm_instance = builder.build().await.unwrap();
244
245 let fake_clock_control = if use_fake_clock {
246 let control_proxy = realm_instance.root.connect_to_protocol_at_exposed_dir().unwrap();
247 let clock_proxy = realm_instance.root.connect_to_protocol_at_exposed_dir().unwrap();
248 Some(FakeClockController { control_proxy, clock_proxy })
249 } else {
250 None
251 };
252
253 let cobalt_querier = realm_instance
254 .root
255 .connect_to_protocol_at_exposed_dir()
256 .expect("the connection succeeds");
257
258 let nested_timekeeper = Self { _realm_instance: realm_instance };
259
260 (nested_timekeeper, push_source_puppet, rtc_updates, cobalt_querier, fake_clock_control)
261 }
262}
263
264pub struct RemotePushSourcePuppet {
265 proxy: fidl_test_time_realm::PushSourcePuppetProxy,
266}
267
268impl RemotePushSourcePuppet {
269 pub fn new(proxy: fidl_test_time_realm::PushSourcePuppetProxy) -> Arc<Self> {
271 Arc::new(Self { proxy })
272 }
273
274 pub async fn set_sample(&self, sample: TimeSample) {
276 self.proxy.set_sample(&sample).await.expect("original API was infallible");
277 }
278
279 pub async fn set_status(&self, status: Status) {
281 self.proxy.set_status(status).await.expect("original API was infallible");
282 }
283
284 pub async fn simulate_crash(&self) {
286 self.proxy.crash().await.expect("original local API was infallible");
287 }
288
289 pub async fn lifetime_served_connections(&self) -> u32 {
292 self.proxy.get_lifetime_served_connections().await.expect("original API was infallible")
293 }
294}
295
296pub struct PushSourcePuppet {
298 inner: Mutex<PushSourcePuppetInner>,
301 cumulative_clients: Mutex<u32>,
303}
304
305impl PushSourcePuppet {
306 fn new() -> Self {
308 Self { inner: Mutex::new(PushSourcePuppetInner::new()), cumulative_clients: Mutex::new(0) }
309 }
310
311 fn serve_client(&self, server_end: ServerEnd<PushSourceMarker>) {
313 log::debug!("serve_client entry");
314 let mut inner = self.inner.lock();
315 if inner.served_client() {
319 *inner = PushSourcePuppetInner::new();
320 }
321 inner.serve_client(server_end);
322 *self.cumulative_clients.lock() += 1;
323 }
324
325 pub async fn set_sample(&self, sample: TimeSample) {
327 let mut sink = self.inner.lock().get_sink();
328 sink.send(sample.into()).await.unwrap();
329 }
330
331 pub async fn set_status(&self, status: Status) {
333 let mut sink = self.inner.lock().get_sink();
334 sink.send(status.into()).await.unwrap();
335 }
336
337 pub fn simulate_crash(&self) {
339 *self.inner.lock() = PushSourcePuppetInner::new();
340 }
342
343 pub fn lifetime_served_connections(&self) -> u32 {
346 *self.cumulative_clients.lock()
347 }
348}
349
350struct PushSourcePuppetInner {
353 push_source: Arc<PushSource<TestUpdateAlgorithm>>,
354 tasks: Vec<fasync::Task<()>>,
356 update_sink: Sender<Update>,
358}
359
360impl PushSourcePuppetInner {
361 fn new() -> Self {
362 let (update_algorithm, update_sink) = TestUpdateAlgorithm::new();
363 let push_source = Arc::new(PushSource::new(update_algorithm, Status::Ok).unwrap());
364 let push_source_clone = Arc::clone(&push_source);
365 let tasks = vec![fasync::Task::spawn(async move {
366 push_source_clone.poll_updates().await.unwrap();
367 })];
368 Self { push_source, tasks, update_sink }
369 }
370
371 fn served_client(&self) -> bool {
373 self.tasks.len() > 1
374 }
375
376 fn serve_client(&mut self, server_end: ServerEnd<PushSourceMarker>) {
378 let push_source_clone = Arc::clone(&self.push_source);
379 self.tasks.push(fasync::Task::spawn(async move {
380 push_source_clone.handle_requests_for_stream(server_end.into_stream()).await.unwrap();
381 }));
382 }
383
384 fn get_sink(&self) -> Sender<Update> {
389 self.update_sink.clone()
390 }
391}
392
393#[derive(Clone, Debug)]
395pub struct RtcUpdates(Arc<Mutex<Vec<fidl_fuchsia_hardware_rtc::Time>>>);
396
397impl RtcUpdates {
398 pub fn to_vec(&self) -> Vec<fidl_fuchsia_hardware_rtc::Time> {
400 self.0.lock().clone()
401 }
402}
403
404pub struct RemoteRtcUpdates {
407 proxy: fidl_test_time_realm::RtcUpdatesProxy,
408}
409
410impl RemoteRtcUpdates {
411 pub async fn to_vec(&self) -> Vec<fidl_fuchsia_hardware_rtc::Time> {
412 self.proxy
413 .get(fidl_test_time_realm::GetRequest::default())
414 .await
415 .expect("no errors or overflows") .unwrap()
417 .0
418 }
419 pub fn new(proxy: fidl_test_time_realm::RtcUpdatesProxy) -> Self {
420 RemoteRtcUpdates { proxy }
421 }
422}
423
424pub struct FakeClockController {
427 control_proxy: FakeClockControlProxy,
428 clock_proxy: FakeClockProxy,
429}
430
431impl Deref for FakeClockController {
432 type Target = FakeClockControlProxy;
433
434 fn deref(&self) -> &Self::Target {
435 &self.control_proxy
436 }
437}
438
439impl FakeClockController {
440 pub fn new(control_proxy: FakeClockControlProxy, clock_proxy: FakeClockProxy) -> Self {
442 FakeClockController { control_proxy, clock_proxy }
443 }
444
445 pub fn into_components(self) -> (FakeClockControlProxy, FakeClockProxy) {
447 (self.control_proxy, self.clock_proxy)
448 }
449
450 pub async fn get_monotonic(&self) -> Result<i64, fidl::Error> {
451 self.clock_proxy.get().await.map(|(_boot, mono)| mono.into_nanos())
452 }
453
454 pub async fn get_reference(&self) -> Result<zx::BootInstant, fidl::Error> {
456 self.get_monotonic().await.map(|v| zx::BootInstant::from_nanos(v))
457 }
458}
459
460pub enum RtcOptions {
462 None,
465 InitialRtcTime(zx::SyntheticInstant),
467 InjectedRtc(fio::DirectoryProxy),
483}
484
485impl From<fidl_test_time_realm::RtcOptions> for RtcOptions {
486 fn from(value: fidl_test_time_realm::RtcOptions) -> Self {
487 match value {
488 fidl_test_time_realm::RtcOptions::DevClassRtc(h) => {
489 RtcOptions::InjectedRtc(h.into_proxy())
490 }
491 fidl_test_time_realm::RtcOptions::InitialRtcTime(t) => {
492 RtcOptions::InitialRtcTime(zx::SyntheticInstant::from_nanos(t))
493 }
494 _ => unimplemented!(),
495 }
496 }
497}
498
499impl From<zx::SyntheticInstant> for RtcOptions {
500 fn from(value: zx::SyntheticInstant) -> Self {
501 RtcOptions::InitialRtcTime(value)
502 }
503}
504
505impl From<Option<zx::SyntheticInstant>> for RtcOptions {
506 fn from(value: Option<zx::SyntheticInstant>) -> Self {
507 value.map(|t| t.into()).unwrap_or(Self::None)
508 }
509}
510
511async fn setup_rtc(
522 rtc_options: RtcOptions,
523 builder: &RealmBuilder,
524 timekeeper: &ChildRef,
525) -> RtcUpdates {
526 let rtc_updates = RtcUpdates(Arc::new(Mutex::new(vec![])));
527
528 let rtc_dir = match rtc_options {
529 RtcOptions::InitialRtcTime(initial_time) => {
530 log::debug!("using fake fuchsia.hardware.rtc.Service");
531 pseudo_directory! {
532 "fuchsia.hardware.rtc.Service" => pseudo_directory! {
533 "default" => pseudo_directory! {
534 "device" => vfs::service::host({
535 let rtc_updates = rtc_updates.clone();
536 move |stream| {
537 serve_fake_rtc(initial_time, rtc_updates.clone(), stream)
538 }
539 })
540 }
541 }
542 }
543 }
544 RtcOptions::None => {
545 log::debug!("using an empty fuchsia.hardware.rtc.Service directory");
546 pseudo_directory! {
547 "fuchsia.hardware.rtc.Service" => pseudo_directory! {
548 }
549 }
550 }
551 RtcOptions::InjectedRtc(h) => {
552 log::debug!("using RTC provided by client");
553 pseudo_directory! {
554 "fuchsia.hardware.rtc.Service" => vfs::remote::remote_dir(h)
555 }
556 }
557 };
558
559 let fake_rtc_server = builder
560 .add_local_child(
561 "fake_rtc",
562 {
563 move |handles| {
564 let rtc_dir = rtc_dir.clone();
565 async move {
566 let mut fs = ServiceFs::new();
567 fs.add_remote(
568 "svc",
569 vfs::directory::serve_read_only(
570 rtc_dir,
571 vfs::execution_scope::ExecutionScope::new(),
572 ),
573 );
574 fs.serve_connection(handles.outgoing_dir)
575 .expect("failed to serve fake RTC ServiceFs");
576 fs.collect::<()>().await;
577 Ok(())
578 }
579 .boxed()
580 }
581 },
582 ChildOptions::new().eager(),
583 )
584 .await
585 .unwrap();
586
587 builder
588 .add_route(
589 Route::new()
590 .capability(Capability::service::<fidl_fuchsia_hardware_rtc::ServiceMarker>())
591 .from(&fake_rtc_server)
592 .to(&*timekeeper),
593 )
594 .await
595 .unwrap();
596
597 rtc_updates
598}
599
600async fn serve_fake_rtc(
603 initial_time: zx::SyntheticInstant,
604 rtc_updates: RtcUpdates,
605 mut stream: DeviceRequestStream,
606) {
607 let mut current = zx_time_to_rtc_time(initial_time);
608 while let Some(req) = stream.try_next().await.unwrap() {
609 match req {
610 DeviceRequest::Get { responder } => {
611 log::debug!("serve_fake_rtc: DeviceRequest::Get: {current:?}");
612 responder.send(Ok(¤t)).unwrap();
613 }
614 DeviceRequest::Set2 { rtc, responder } => {
615 log::debug!("serve_fake_rtc: DeviceRequest::Set2: {rtc:?}");
616 rtc_updates.0.lock().push(rtc);
617 current = rtc;
618 responder.send(Ok(())).unwrap();
619 }
620 DeviceRequest::_UnknownMethod { .. } => {}
621 }
622 }
623}
624
625async fn serve_test_control(puppet: &PushSourcePuppet, stream: TimeSourceControlRequestStream) {
626 stream
627 .try_for_each_concurrent(None, |req| async {
628 let _ = &req;
629 let TimeSourceControlRequest::ConnectPushSource { push_source, .. } = req;
630 puppet.serve_client(push_source);
631 Ok(())
632 })
633 .await
634 .unwrap();
635}
636
637async fn serve_maintenance(clock_handle: Arc<zx::Clock>, mut stream: MaintenanceRequestStream) {
638 while let Some(req) = stream.try_next().await.unwrap() {
639 let MaintenanceRequest::GetWritableUtcClock { responder } = req;
640 responder.send(clock_handle.duplicate_handle(Rights::SAME_RIGHTS).unwrap()).unwrap();
641 }
642}
643
644async fn timesource_mock_server(
645 handles: LocalComponentHandles,
646 push_source_puppet: Arc<PushSourcePuppet>,
647) -> Result<(), anyhow::Error> {
648 let mut fs = ServiceFs::new();
649 let mut tasks = vec![];
650
651 fs.dir("svc").add_fidl_service(move |stream: TimeSourceControlRequestStream| {
652 let puppet_clone = Arc::clone(&push_source_puppet);
653
654 tasks.push(fasync::Task::local(async move {
655 serve_test_control(&*puppet_clone, stream).await;
656 }));
657 });
658
659 fs.serve_connection(handles.outgoing_dir)?;
660 fs.collect::<()>().await;
661
662 Ok(())
663}
664
665async fn maintenance_mock_server(
666 handles: LocalComponentHandles,
667 clock: Arc<zx::Clock>,
668) -> Result<(), anyhow::Error> {
669 let mut fs = ServiceFs::new();
670 let mut tasks = vec![];
671
672 fs.dir("svc").add_fidl_service(move |stream: MaintenanceRequestStream| {
673 let clock_clone = Arc::clone(&clock);
674
675 tasks.push(fasync::Task::local(async move {
676 serve_maintenance(clock_clone, stream).await;
677 }));
678 });
679
680 fs.serve_connection(handles.outgoing_dir)?;
681 fs.collect::<()>().await;
682
683 Ok(())
684}
685
686fn from_rfc2822(date: &str) -> zx::SyntheticInstant {
687 zx::SyntheticInstant::from_nanos(
688 chrono::DateTime::parse_from_rfc2822(date).unwrap().timestamp_nanos_opt().unwrap(),
689 )
690}
691
692pub static BACKSTOP_TIME: LazyLock<zx::SyntheticInstant> =
693 LazyLock::new(|| from_rfc2822("Sun, 20 Sep 2020 01:01:01 GMT"));
694pub static VALID_RTC_TIME: LazyLock<zx::SyntheticInstant> =
695 LazyLock::new(|| from_rfc2822("Sun, 20 Sep 2020 02:02:02 GMT"));
696pub static BEFORE_BACKSTOP_TIME: LazyLock<zx::SyntheticInstant> =
697 LazyLock::new(|| from_rfc2822("Fri, 06 Mar 2020 04:04:04 GMT"));
698pub static VALID_TIME: LazyLock<zx::SyntheticInstant> =
699 LazyLock::new(|| from_rfc2822("Tue, 29 Sep 2020 02:19:01 GMT"));
700pub static VALID_TIME_2: LazyLock<zx::SyntheticInstant> =
701 LazyLock::new(|| from_rfc2822("Wed, 30 Sep 2020 14:59:59 GMT"));
702
703pub const BETWEEN_SAMPLES: zx::BootDuration = zx::BootDuration::from_seconds(5);
705
706pub const STD_DEV: zx::BootDuration = zx::BootDuration::from_millis(50);
708
709pub fn new_clock() -> Arc<zx::SyntheticClock> {
712 Arc::new(new_nonshareable_clock())
713}
714
715pub fn new_nonshareable_clock() -> zx::SyntheticClock {
717 zx::SyntheticClock::create(zx::ClockOpts::MAPPABLE, Some(*BACKSTOP_TIME)).unwrap()
718}
719
720fn zx_time_to_rtc_time(zx_time: zx::SyntheticInstant) -> fidl_fuchsia_hardware_rtc::Time {
721 let date = chrono::Utc.timestamp_nanos(zx_time.into_nanos());
722 fidl_fuchsia_hardware_rtc::Time {
723 seconds: date.second() as u8,
724 minutes: date.minute() as u8,
725 hours: date.hour() as u8,
726 day: date.day() as u8,
727 month: date.month() as u8,
728 year: date.year() as u16,
729 }
730}
731
732pub fn rtc_time_to_zx_time(rtc_time: fidl_fuchsia_hardware_rtc::Time) -> zx::SyntheticInstant {
733 let date = chrono::Utc
734 .with_ymd_and_hms(
735 rtc_time.year as i32,
736 rtc_time.month as u32,
737 rtc_time.day as u32,
738 rtc_time.hours as u32,
739 rtc_time.minutes as u32,
740 rtc_time.seconds as u32,
741 )
742 .unwrap();
743 zx::SyntheticInstant::from_nanos(date.timestamp_nanos_opt().unwrap())
744}
745
746pub fn create_cobalt_event_stream(
748 proxy: Arc<MetricEventLoggerQuerierProxy>,
749 log_method: LogMethod,
750) -> std::pin::Pin<Box<dyn Stream<Item = MetricEvent>>> {
751 async_utils::hanging_get::client::HangingGetStream::new(proxy, move |p| {
752 p.watch_logs(PROJECT_ID, log_method)
753 })
754 .map(|res| futures::stream::iter(res.expect("there should be a valid result here").0))
755 .flatten()
756 .boxed()
757}
758
759#[macro_export]
761macro_rules! poll_until_some {
762 ($condition:expr) => {
763 $crate::poll_until_some_impl(
764 $condition,
765 &$crate::SourceLocation::new(file!(), line!(), column!()),
766 )
767 };
768}
769
770#[macro_export]
773macro_rules! poll_until_some_async {
774 ($condition:expr) => {{
775 let loc = $crate::SourceLocation::new(file!(), line!(), column!());
776 log::info!("=> poll_until_some_async() for {}", &loc);
777 let mut result = None;
778 loop {
779 result = $condition.await;
780 if result.is_some() {
781 break;
782 }
783 fasync::Timer::new(fasync::MonotonicInstant::after($crate::RETRY_WAIT_DURATION)).await;
784 }
785 log::info!("=> poll_until_some_async() done for {}", &loc);
786 result.expect("we loop around while result is None")
787 }};
788}
789
790#[macro_export]
793macro_rules! poll_until_async {
794 ($condition:expr) => {
795 $crate::poll_until_async_impl(
796 $condition,
797 &$crate::SourceLocation::new(file!(), line!(), column!()),
798 )
799 };
800}
801
802#[macro_export]
804macro_rules! poll_until_async_2 {
805 ($condition:expr) => {{
806 let loc = $crate::SourceLocation::new(file!(), line!(), column!());
807 log::info!("=> poll_until_async() for {}", &loc);
808 let mut result = true;
809 loop {
810 result = $condition.await;
811 if result {
812 break;
813 }
814 fasync::Timer::new(fasync::MonotonicInstant::after($crate::RETRY_WAIT_DURATION)).await;
815 }
816 log::info!("=> poll_until_async_2() done for {}", &loc);
817 result
818 }};
819}
820
821#[macro_export]
823macro_rules! poll_until {
824 ($condition:expr) => {
825 $crate::poll_until_impl(
826 $condition,
827 &$crate::SourceLocation::new(file!(), line!(), column!()),
828 )
829 };
830}
831
832pub const RETRY_WAIT_DURATION: zx::MonotonicDuration = zx::MonotonicDuration::from_millis(10);
834
835pub struct SourceLocation {
836 file: &'static str,
837 line: u32,
838 column: u32,
839}
840
841impl std::fmt::Display for SourceLocation {
842 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
843 write!(f, "(file: {}, line: {}, column: {})", self.file, self.line, self.column)
844 }
845}
846
847impl SourceLocation {
848 pub fn new(file: &'static str, line: u32, column: u32) -> Self {
849 Self { file, line, column }
850 }
851}
852
853pub async fn poll_until_some_impl<T, F>(poll_fn: F, loc: &SourceLocation) -> T
855where
856 F: Fn() -> Option<T>,
857{
858 log::info!("=> poll_until_some() for {}", loc);
859 loop {
860 match poll_fn() {
861 Some(value) => {
862 log::info!("<= poll_until_some() for {}", loc);
863 return value;
864 }
865 None => fasync::Timer::new(fasync::MonotonicInstant::after(RETRY_WAIT_DURATION)).await,
866 }
867 }
868}
869
870pub async fn poll_until_async_impl<F, Fut>(poll_fn: F, loc: &SourceLocation)
872where
873 F: Fn() -> Fut,
874 Fut: Future<Output = bool>,
875{
876 log::info!("=> poll_until_async() for {}", loc);
877 while !poll_fn().await {
878 fasync::Timer::new(fasync::MonotonicInstant::after(RETRY_WAIT_DURATION)).await
879 }
880 log::info!("<= poll_until_async() for {}", loc);
881}
882
883pub async fn poll_until_impl<F: Fn() -> bool>(poll_fn: F, loc: &SourceLocation) {
885 log::info!("=> poll_until() for {}", loc);
886 while !poll_fn() {
887 fasync::Timer::new(fasync::MonotonicInstant::after(RETRY_WAIT_DURATION)).await
888 }
889 log::info!("<= poll_until() for {}", loc);
890}