Skip to main content

fdf_component/
server.rs

1// Copyright 2024 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 core::ffi::c_void;
6use core::ptr::NonNull;
7use std::num::NonZero;
8use std::sync::{Arc, OnceLock};
9
10use log::{debug, error, warn};
11use zx::Status;
12
13use fdf::{
14    AsAsyncDispatcherRef, AsyncDispatcher, Channel, DispatcherBuilder, DriverDispatcherRef,
15    DriverHandle, fdf_handle_t,
16};
17use fdf_fidl::DriverChannel;
18use fidl_next::{Request, Responder, Server, ServerDispatcher, ServerEnd};
19use fidl_next_fuchsia_driver_framework::{
20    Driver as DriverProtocol, DriverLocalServerHandler, DriverStartArgs, HealthCheckError, driver,
21};
22
23use crate::health::{HealthAlertReporter, run_health_check};
24use crate::{Driver, DriverContext, DriverError};
25use fdf_sys::fdf_dispatcher_get_current_dispatcher;
26use fuchsia_async::LocalExecutorBuilder;
27
28/// The driver transport the lifecycle server reads on. Reads are registered against the root
29/// dispatcher's always-on interface so that requests (notably `Resume`) keep being delivered
30/// while the driver's dispatchers are suspended.
31pub(crate) type Transport = DriverChannel<AsyncDispatcher>;
32
33/// Implements the lifecycle management of a rust driver, including starting and stopping it
34/// and setting up the rust async dispatcher and logging for the driver to use, and running a
35/// message loop for the driver start and stop messages.
36///
37/// Lifecycle requests are handled in order. Health checks are the one exception: they are
38/// spawned as tasks on the same thread so that a slow or hung check can never delay `Stop`,
39/// `Suspend` or `Resume`.
40pub struct DriverServer<T> {
41    /// Holds the lifecycle channel until [`Self::message_loop`] hands it to the fidl_next server.
42    server_handle: OnceLock<Channel<[fidl_next::Chunk]>>,
43    root_dispatcher: DriverDispatcherRef<'static>,
44    /// The running driver, wrapped in [`Arc`] so health check tasks spawned on the local
45    /// scope can hold a reference to it without `unsafe` lifetime extension. The health scope
46    /// is cancelled before the driver is taken out of here to be stopped or dropped, so
47    /// [`Driver::stop`] never runs concurrently with a health check.
48    driver: OnceLock<Arc<T>>,
49}
50
51impl<T: Driver> DriverServer<T> {
52    /// Called by the driver host to start the driver.
53    ///
54    /// # Safety
55    ///
56    /// The caller must provide a valid non-zero driver transport channel handle for
57    /// `server_handle`.
58    pub unsafe extern "C" fn initialize(server_handle: fdf_handle_t) -> *mut c_void {
59        // SAFETY: We verify that the pointer returned is non-null, ensuring that this was
60        // called from within a driver context.
61        let root_dispatcher = NonNull::new(unsafe { fdf_dispatcher_get_current_dispatcher() })
62            .expect("Non-null current dispatcher");
63        // SAFETY: We use NonZero::new to verify that we've been given a non-zero
64        // driver handle, and expect that the caller (which is the driver runtime) has given us
65        // a valid driver transport fidl channel.
66        let server_handle = OnceLock::from(unsafe {
67            Channel::from_driver_handle(DriverHandle::new_unchecked(
68                NonZero::new(server_handle).expect("valid driver handle"),
69            ))
70        });
71
72        // SAFETY: the root dispatcher is expected to live as long as this driver is loaded.
73        let root_dispatcher = unsafe { DriverDispatcherRef::from_raw(root_dispatcher) };
74        // We leak the box holding the server so that the driver runtime can take control over the
75        // lifetime of the server object.
76        let server_ptr = Box::into_raw(Box::new(Self {
77            server_handle,
78            root_dispatcher: root_dispatcher.clone(),
79            driver: OnceLock::default(),
80        }));
81
82        // Reconstitute the pointer to the `DriverServer` as a mut reference to use it in the main
83        // loop.
84        // SAFETY: We are the exclusive owner of the object until we drop the server handle,
85        // triggering the driver host to call `destroy`.
86        let server = unsafe { &mut *server_ptr };
87
88        let root_dispatcher_always_on = root_dispatcher.always_on_dispatcher();
89        server.start_rust_async_dispatcher(root_dispatcher_always_on);
90
91        // Take the pointer of the server object to use as the identifier for the server to the
92        // driver runtime. It uses this as an opaque identifier and expects no particular layout of
93        // the object pointed to, and we use it to free the box at unload in `Self::destroy`.
94        server_ptr.cast()
95    }
96
97    fn start_rust_async_dispatcher(
98        &'static mut self,
99        read_dispatcher: DriverDispatcherRef<'static>,
100    ) {
101        // Build a new dispatcher that we can have spin on a fuchsia-async executor main loop
102        // to act as a reactor for non-driver events. Use the always_on_dispatcher on it because
103        // this thread is always running and we don't want to hold up the driver's dispatcher
104        // suspension operation.
105        let rust_async_dispatcher = DispatcherBuilder::new()
106            .name("fuchsia-async")
107            .allow_thread_blocking()
108            .scheduler_role(&self.root_dispatcher.scheduler_role())
109            .create_released()
110            .expect("failure creating blocking dispatcher for rust async")
111            .always_on_dispatcher();
112        // Post the task to the dispatcher that will run the fuchsia-async loop, and have it run
113        // the server's message loop waiting for start and stop messages from the driver host.
114        rust_async_dispatcher
115            .post_task_sync(move |status| {
116                // bail immediately if we were somehow cancelled before we started
117                if status.is_ok() {
118                    self.run_executor_loop(read_dispatcher);
119                } else {
120                    self.server_handle.take();
121                }
122            })
123            .expect("failure spawning main event loop for rust async dispatch");
124    }
125
126    fn run_executor_loop(&'static mut self, read_dispatcher: DriverDispatcherRef<'static>) {
127        fdf_core::override_current_dispatcher(self.root_dispatcher.clone(), || {
128            // create and run a fuchsia-async executor, giving it the "root" dispatcher to
129            // actually execute driver tasks on, as this thread will be effectively blocked
130            // by the reactor loop.
131            let port = zx::Port::create_with_opts(zx::PortOptions::BIND_TO_INTERRUPT);
132            let mut executor = LocalExecutorBuilder::new().port(port).build();
133            executor.run_singlethreaded(async move {
134                self.message_loop(read_dispatcher).await;
135            });
136        });
137    }
138
139    /// Called by the driver host after shutting down a driver and once the handle passed to
140    /// [`Self::initialize`] is dropped.
141    ///
142    /// # Safety
143    ///
144    /// This must only be called after the handle provided to [`Self::initialize`] has been
145    /// dropped, which indicates that the main event loop of the driver lifecycle has ended.
146    pub unsafe extern "C" fn destroy(obj: *mut c_void) {
147        let obj: *mut Self = obj.cast();
148        // SAFETY: We built this object in `initialize` and gave ownership of its
149        // lifetime to the driver framework, which is now giving it to us to free.
150        unsafe { drop(Box::from_raw(obj)) }
151    }
152
153    /// Implements the main message loop for handling start and stop messages from rust
154    /// driver host and passing them on to the implementation of [`Driver`] we contain.
155    async fn message_loop(&mut self, dispatcher: DriverDispatcherRef<'_>) {
156        let server_handle = self.server_handle.take().expect("driver server handle already taken");
157        let server_end: ServerEnd<DriverProtocol, Transport> = ServerEnd::from_untyped(
158            DriverChannel::new_with_dispatcher(AsyncDispatcher::new(&dispatcher), server_handle),
159        );
160        let server = ServerDispatcher::new(server_end);
161        let fidl_server = server.server();
162        let handler = LifecycleHandler {
163            server: Some(self),
164            health_alert_reporter: HealthAlertReporter::new(fidl_server.clone()),
165            fidl_server,
166            health_tasks: Some(fuchsia_async::Scope::new_with_name("driver-health")),
167        };
168        match server.run_local(handler).await {
169            // The driver host closed the channel without sending `Stop`.
170            Ok(mut handler) if handler.server.is_some() => {
171                warn!(
172                    "Driver server channel closed before a stop message; \
173                     stop() will not be called."
174                );
175                handler.finish().await;
176            }
177            Ok(_) => {}
178            Err(e) => error!("Driver server channel failed: {e}, exiting main loop."),
179        }
180    }
181
182    /// Handles the start message by initializing logging and calling the [`Driver::start`] with
183    /// a constructed [`DriverContext`].
184    ///
185    /// # Panics
186    ///
187    /// This method panics if the start message has already been received.
188    /// [`LifecycleHandler::start`] rejects a second start before reaching this method.
189    async fn handle_start(
190        &self,
191        start_args: DriverStartArgs,
192        health_alert_reporter: HealthAlertReporter,
193    ) -> Result<(), Status> {
194        let context = DriverContext::new(
195            AsyncDispatcher::new(&self.root_dispatcher),
196            start_args,
197            health_alert_reporter,
198        )?;
199        context.start_logging(T::NAME)?;
200
201        log::debug!("driver starting");
202
203        let driver = T::start(context).await.map_err(DriverError::log_to_status)?;
204        self.driver
205            .set(Arc::new(driver))
206            .map_err(|_| ())
207            .expect("Driver received start message twice");
208        Ok(())
209    }
210
211    async fn handle_stop(&mut self) {
212        log::debug!("driver stopping");
213        match self.driver.take() {
214            Some(driver) => driver.stop().await,
215            None => warn!("received stop message without a running driver"),
216        }
217    }
218
219    async fn handle_suspend(&self) -> Result<(), Status> {
220        log::debug!("driver suspending");
221        let driver = self.driver.get().ok_or(Status::BAD_STATE)?;
222        driver.system_suspend().await.map_err(DriverError::log_to_status)
223    }
224
225    async fn handle_resume(&self, lease: Option<zx::EventPair>) -> Result<(), Status> {
226        log::debug!("driver resuming");
227        let driver = self.driver.get().ok_or(Status::BAD_STATE)?;
228        driver.system_resume(lease).await.map_err(DriverError::log_to_status)
229    }
230
231    /// Returns a reference to the driver, if it has been started.
232    /// This is meant to be used only for testing.
233    pub(crate) fn testing_get_driver(&self) -> Option<&'_ T> {
234        self.driver.get().map(Arc::as_ref)
235    }
236}
237
238/// The `fidl_next` server handler for the driver lifecycle protocol. It borrows the
239/// [`DriverServer`] for the duration of [`DriverServer::message_loop`] only.
240struct LifecycleHandler<'a, T> {
241    /// `None` once the driver has stopped or failed to start, after which the server must not be
242    /// touched: the driver host is free to destroy it as soon as the channel closes.
243    server: Option<&'a mut DriverServer<T>>,
244    fidl_server: Server<DriverProtocol, Transport>,
245    /// The reporter handed to the driver through its [`DriverContext`].
246    health_alert_reporter: HealthAlertReporter,
247    /// Owns the in-flight health checks. Cancelled before the driver stops, so health checks
248    /// never run concurrently with [`Driver::stop`] or outlive the driver. `None` afterwards.
249    health_tasks: Option<fuchsia_async::Scope>,
250}
251
252impl<T: Driver> LifecycleHandler<'_, T> {
253    /// Cancels all in-flight health checks and waits for them to finish.
254    async fn cancel_health_tasks(&mut self) {
255        if let Some(health_tasks) = self.health_tasks.take() {
256            health_tasks.cancel().await;
257        }
258    }
259
260    /// Tears down the driver and closes the channel. This is the last thing the handler does
261    /// with the server: the driver host treats the channel closing as the signal that the driver
262    /// is fully stopped.
263    async fn finish(&mut self) {
264        self.health_alert_reporter.close();
265        self.cancel_health_tasks().await;
266        if let Some(server) = self.server.take() {
267            // The driver is dropped here, on the fuchsia-async thread and inside its executor,
268            // so that it can release any async resources it holds.
269            drop(server.driver.take());
270        }
271        self.fidl_server.close();
272    }
273}
274
275fn log_reply<E: std::fmt::Display>(method: &str, reply: Result<(), E>) {
276    if let Err(e) = reply {
277        warn!("Failed to reply to {method}: {e}");
278    }
279}
280
281impl<T: Driver> DriverLocalServerHandler<Transport> for LifecycleHandler<'_, T> {
282    async fn start(
283        &mut self,
284        request: Request<driver::Start, Transport>,
285        responder: Responder<driver::Start, Transport>,
286    ) {
287        let Some(server) = self.server.as_deref() else {
288            return;
289        };
290        // A second start is rejected without disturbing the running driver. It must not go
291        // through `handle_start`, whose failure closes the channel below.
292        if server.driver.get().is_some() {
293            error!("Driver received start message twice");
294            log_reply("Start", responder.respond_err(Status::BAD_STATE).await);
295            return;
296        }
297        let res = server
298            .handle_start(request.payload().start_args, self.health_alert_reporter.clone())
299            .await;
300        let reply = match res {
301            Ok(()) => responder.respond(()).await,
302            Err(status) => responder.respond_err(status).await,
303        };
304        if let Err(e) = reply {
305            error!("Failed to reply to Start: {e}, exiting main loop.");
306            self.finish().await;
307        } else if res.is_err() {
308            debug!("driver failed to start, exiting main loop");
309            self.finish().await;
310        }
311    }
312
313    async fn stop(&mut self) {
314        // Stop accepting health alerts and abandon any health checks still in flight before
315        // calling `Driver::stop`.
316        self.health_alert_reporter.close();
317        self.cancel_health_tasks().await;
318        if let Some(server) = self.server.as_deref_mut() {
319            server.handle_stop().await;
320        }
321        self.finish().await;
322    }
323
324    async fn suspend(&mut self, responder: Responder<driver::Suspend, Transport>) {
325        let Some(server) = self.server.as_deref() else {
326            return;
327        };
328        let reply = match server.handle_suspend().await {
329            Ok(()) => responder.respond(()).await,
330            Err(status) => responder.respond_err(status).await,
331        };
332        log_reply("Suspend", reply);
333    }
334
335    async fn resume(
336        &mut self,
337        request: Request<driver::Resume, Transport>,
338        responder: Responder<driver::Resume, Transport>,
339    ) {
340        let Some(server) = self.server.as_deref() else {
341            return;
342        };
343        let lease = request.payload().power_element_lease;
344        let reply = match server.handle_resume(lease).await {
345            Ok(()) => responder.respond(()).await,
346            Err(status) => responder.respond_err(status).await,
347        };
348        log_reply("Resume", reply);
349    }
350
351    async fn health_check(
352        &mut self,
353        request: Request<driver::HealthCheck, Transport>,
354        responder: Responder<driver::HealthCheck, Transport>,
355    ) {
356        let request = request.payload().request;
357        let running =
358            self.server.as_deref().and_then(|server| Some((server, server.driver.get()?)));
359        let (Some((server, driver)), Some(health_tasks)) = (running, &self.health_tasks) else {
360            if let Err(e) = responder.respond_err(HealthCheckError::InvalidState).await {
361                debug!("Failed to reply to HealthCheck: {e}");
362            }
363            return;
364        };
365        let driver = Arc::clone(driver);
366        let root_dispatcher = server.root_dispatcher.clone();
367        // Run the check as its own task so that it cannot hold up the requests that follow it,
368        // including `Stop`. The task owns the responder and replies when the check completes.
369        health_tasks.spawn_local(async move {
370            let result = run_health_check(driver.as_ref(), root_dispatcher, request).await;
371            // Unlike Start/Suspend/Resume, whose replies the host always waits for, a health
372            // check reply can legitimately arrive after the host has given up and closed the
373            // channel (the server's deadline is deliberately later than the host's), so a failed
374            // reply is not a bug and must not panic.
375            let reply = match result {
376                Ok(response) => responder.respond(response).await,
377                Err(e) => responder.respond_err(e).await,
378            };
379            if let Err(e) = reply {
380                debug!("Failed to reply to HealthCheck: {e}");
381            }
382        });
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use crate::{
390        DriverError, HealthAlert, HealthAlertReporter, HealthCheckRequest, HealthCheckResponse,
391        HealthCheckResult, HealthCondition, HealthDiagnosticItem, HealthDiagnosticValue,
392        HealthStatus,
393    };
394
395    use fdf::{CurrentDispatcher, OnDispatcher};
396    use fdf_env::test::spawn_in_driver;
397    use fidl_next_fuchsia_driver_framework::DriverClientHandler;
398    use futures::StreamExt;
399    use futures::channel::{mpsc, oneshot};
400    use zx::Status;
401
402    use fdf::Channel;
403    use fidl_next::{ClientDispatcher, ClientEnd};
404
405    #[derive(Default)]
406    struct TestDriver {
407        _not_empty: bool,
408    }
409
410    impl Driver for TestDriver {
411        const NAME: &str = "test_driver";
412
413        async fn start(context: DriverContext) -> Result<Self, DriverError> {
414            let DriverContext { root_dispatcher, start_args, .. } = context;
415            println!("created new test driver on dispatcher: {root_dispatcher:?}");
416            println!("driver start message: {start_args:?}");
417            Ok(Self::default())
418        }
419        async fn stop(&self) {
420            println!("driver stop message");
421        }
422        async fn system_suspend(&self) -> Result<(), DriverError> {
423            println!("driver suspend message");
424            Ok(())
425        }
426        async fn system_resume(&self, _lease: Option<zx::EventPair>) -> Result<(), DriverError> {
427            println!("driver resume message");
428            Ok(())
429        }
430    }
431
432    crate::driver_register!(TestDriver);
433
434    #[derive(Debug)]
435    struct DriverClient;
436    impl DriverClientHandler for DriverClient {
437        async fn on_health_alert(
438            &mut self,
439            _request: fidl_next::Request<
440                fidl_next_fuchsia_driver_framework::driver::OnHealthAlert,
441                fdf_fidl::DriverChannel,
442            >,
443        ) {
444        }
445    }
446
447    #[test]
448    fn register_driver() {
449        assert_eq!(__fuchsia_driver_registration__.version, 1);
450        let initialize_func = __fuchsia_driver_registration__.v1.initialize.expect("initializer");
451        let destroy_func = __fuchsia_driver_registration__.v1.destroy.expect("destroy function");
452
453        let (server_chan, client_chan) = Channel::<[fidl_next::Chunk]>::create();
454
455        spawn_in_driver("driver registration", async move {
456            let client_end: ClientEnd<fidl_next_fuchsia_driver_framework::Driver, _> =
457                ClientEnd::from_untyped(fdf_fidl::DriverChannel::new(client_chan));
458            let dispatcher = ClientDispatcher::new(client_end);
459            let client = dispatcher.client();
460
461            let client_task = CurrentDispatcher.spawn(async move {
462                dispatcher.run(DriverClient).await.unwrap_err();
463            });
464
465            let channel_handle = server_chan.into_driver_handle().into_raw().get();
466            let driver_server = unsafe { initialize_func(channel_handle) } as usize;
467            assert_ne!(driver_server, 0);
468
469            assert_eq!(client.suspend().await.unwrap(), Err(Status::BAD_STATE));
470            assert_eq!(client.resume(None::<zx::EventPair>).await.unwrap(), Err(Status::BAD_STATE));
471
472            client
473                .start(fidl_next_fuchsia_driver_framework::DriverStartArgs::default())
474                .await
475                .unwrap()
476                .unwrap();
477
478            assert_eq!(
479                client.start(DriverStartArgs::default()).await.unwrap(),
480                Err(Status::BAD_STATE)
481            );
482
483            client.suspend().await.unwrap().unwrap();
484            client.resume(None::<zx::EventPair>).await.unwrap().unwrap();
485
486            client.stop().await.unwrap();
487            client_task.await.unwrap();
488
489            unsafe {
490                destroy_func(driver_server as *mut c_void);
491            }
492        })
493    }
494
495    struct TestDriverAnyhowSuccess;
496
497    impl Driver for TestDriverAnyhowSuccess {
498        const NAME: &str = "test_driver_anyhow_success";
499
500        async fn start(_context: DriverContext) -> Result<Self, DriverError> {
501            Ok(Self)
502        }
503        async fn stop(&self) {}
504    }
505
506    #[test]
507    fn test_anyhow_success() {
508        let registration = crate::macros::make_driver_registration::<TestDriverAnyhowSuccess>();
509        let initialize_func = registration.v1.initialize.expect("initializer");
510        let destroy_func = registration.v1.destroy.expect("destroy function");
511
512        let (server_chan, client_chan) = Channel::<[fidl_next::Chunk]>::create();
513
514        spawn_in_driver("driver anyhow success", async move {
515            let client_end: ClientEnd<fidl_next_fuchsia_driver_framework::Driver, _> =
516                ClientEnd::from_untyped(fdf_fidl::DriverChannel::new(client_chan));
517            let dispatcher = ClientDispatcher::new(client_end);
518            let client = dispatcher.client();
519
520            let client_task = CurrentDispatcher.spawn(async move {
521                dispatcher.run(DriverClient).await.unwrap_err();
522            });
523
524            let channel_handle = server_chan.into_driver_handle().into_raw().get();
525            let driver_server = unsafe { initialize_func(channel_handle) } as usize;
526            assert_ne!(driver_server, 0);
527
528            client
529                .start(fidl_next_fuchsia_driver_framework::DriverStartArgs::default())
530                .await
531                .unwrap()
532                .unwrap();
533
534            client.stop().await.unwrap();
535            client_task.await.unwrap();
536
537            unsafe {
538                destroy_func(driver_server as *mut c_void);
539            }
540        })
541    }
542
543    struct TestDriverAnyhowFailure;
544
545    impl Driver for TestDriverAnyhowFailure {
546        const NAME: &str = "test_driver_anyhow_failure";
547
548        async fn start(_context: DriverContext) -> Result<Self, DriverError> {
549            Err(anyhow::anyhow!(Status::INVALID_ARGS).into())
550        }
551        async fn stop(&self) {}
552    }
553
554    #[test]
555    fn test_anyhow_failure() {
556        let registration = crate::macros::make_driver_registration::<TestDriverAnyhowFailure>();
557        let initialize_func = registration.v1.initialize.expect("initializer");
558        let destroy_func = registration.v1.destroy.expect("destroy function");
559
560        let (server_chan, client_chan) = Channel::<[fidl_next::Chunk]>::create();
561
562        spawn_in_driver("driver anyhow failure", async move {
563            let client_end: ClientEnd<fidl_next_fuchsia_driver_framework::Driver, _> =
564                ClientEnd::from_untyped(fdf_fidl::DriverChannel::new(client_chan));
565            let dispatcher = ClientDispatcher::new(client_end);
566            let client = dispatcher.client();
567
568            let client_task = CurrentDispatcher.spawn(async move {
569                dispatcher.run(DriverClient).await.unwrap_err();
570            });
571
572            let channel_handle = server_chan.into_driver_handle().into_raw().get();
573            let driver_server = unsafe { initialize_func(channel_handle) } as usize;
574            assert_ne!(driver_server, 0);
575
576            let res = client
577                .start(fidl_next_fuchsia_driver_framework::DriverStartArgs::default())
578                .await
579                .unwrap();
580
581            assert_eq!(res.unwrap_err(), Status::INVALID_ARGS);
582
583            client_task.await.unwrap();
584
585            unsafe {
586                destroy_func(driver_server as *mut c_void);
587            }
588        })
589    }
590
591    struct TestDriverAnyhowFailureDefault;
592
593    impl Driver for TestDriverAnyhowFailureDefault {
594        const NAME: &str = "test_driver_anyhow_failure_default";
595
596        async fn start(_context: DriverContext) -> Result<Self, DriverError> {
597            Err(anyhow::anyhow!("some generic error").into())
598        }
599        async fn stop(&self) {}
600    }
601
602    #[test]
603    fn test_anyhow_failure_default() {
604        let registration =
605            crate::macros::make_driver_registration::<TestDriverAnyhowFailureDefault>();
606        let initialize_func = registration.v1.initialize.expect("initializer");
607        let destroy_func = registration.v1.destroy.expect("destroy function");
608
609        let (server_chan, client_chan) = Channel::<[fidl_next::Chunk]>::create();
610
611        spawn_in_driver("driver anyhow failure default", async move {
612            let client_end: ClientEnd<fidl_next_fuchsia_driver_framework::Driver, _> =
613                ClientEnd::from_untyped(fdf_fidl::DriverChannel::new(client_chan));
614            let dispatcher = ClientDispatcher::new(client_end);
615            let client = dispatcher.client();
616
617            let client_task = CurrentDispatcher.spawn(async move {
618                dispatcher.run(DriverClient).await.unwrap_err();
619            });
620
621            let channel_handle = server_chan.into_driver_handle().into_raw().get();
622            let driver_server = unsafe { initialize_func(channel_handle) } as usize;
623            assert_ne!(driver_server, 0);
624
625            let res = client
626                .start(fidl_next_fuchsia_driver_framework::DriverStartArgs::default())
627                .await
628                .unwrap();
629
630            assert_eq!(res.unwrap_err(), Status::INTERNAL);
631
632            client_task.await.unwrap();
633
634            unsafe {
635                destroy_func(driver_server as *mut c_void);
636            }
637        })
638    }
639
640    type TestClient = fidl_next::Client<DriverProtocol, DriverChannel>;
641    type AlertReceiver = mpsc::UnboundedReceiver<HealthAlert>;
642
643    /// Collects `OnHealthAlert` events sent by the server.
644    #[derive(Debug)]
645    struct AlertCollector(mpsc::UnboundedSender<HealthAlert>);
646
647    impl DriverClientHandler for AlertCollector {
648        async fn on_health_alert(
649            &mut self,
650            request: Request<driver::OnHealthAlert, DriverChannel>,
651        ) {
652            let _ = self.0.unbounded_send(request.payload().alert);
653        }
654    }
655
656    /// Initializes a `DriverServer` for `D` over a fresh driver channel, runs `body` against a
657    /// client of it, then waits for the server to release the channel and destroys it. `body` is
658    /// responsible for stopping the driver if it started it. `body` also receives the stream of
659    /// `OnHealthAlert` events the server sends.
660    fn with_driver_server<D, F, Fut>(name: &str, body: F)
661    where
662        D: Driver,
663        F: FnOnce(TestClient, AlertReceiver) -> Fut + Send + 'static,
664        Fut: std::future::Future<Output = ()> + Send,
665    {
666        let registration = crate::macros::make_driver_registration::<D>();
667        let initialize_func = registration.v1.initialize.expect("initializer");
668        let destroy_func = registration.v1.destroy.expect("destroy function");
669        let (server_chan, client_chan) = Channel::<[fidl_next::Chunk]>::create();
670
671        spawn_in_driver(name, async move {
672            let client_end: ClientEnd<DriverProtocol, _> =
673                ClientEnd::from_untyped(DriverChannel::new(client_chan));
674            let dispatcher = ClientDispatcher::new(client_end);
675            let client = dispatcher.client();
676            // Dropping the last `Client` stops the client dispatcher, so keep one alive until the
677            // server has closed the channel regardless of what `body` does with its copy.
678            let keepalive = client.clone();
679            let (alert_tx, alert_rx) = mpsc::unbounded();
680
681            let client_task = CurrentDispatcher.spawn(async move {
682                // The dispatcher exits with `PeerClosed` once the server releases its end of the
683                // channel, which is when the driver has finished stopping (or failed to start).
684                dispatcher.run(AlertCollector(alert_tx)).await.unwrap_err();
685            });
686
687            let channel_handle = server_chan.into_driver_handle().into_raw().get();
688            // SAFETY: `channel_handle` is a valid, non-zero FDF channel handle created above.
689            // Ownership of the handle is given to `initialize_func`.
690            let driver_server = unsafe { initialize_func(channel_handle) } as usize;
691            assert_ne!(driver_server, 0);
692
693            body(client, alert_rx).await;
694
695            client_task.await.unwrap();
696            drop(keepalive);
697            // SAFETY: `driver_server` was returned by `initialize_func` and the server has
698            // released its channel, so it is idle and safe to destroy.
699            unsafe {
700                destroy_func(driver_server as *mut c_void);
701            }
702        })
703    }
704
705    #[test]
706    fn test_stop_before_start() {
707        with_driver_server::<TestDriver, _, _>("stop before start", |client, _alerts| async move {
708            client.stop().await.unwrap();
709        });
710    }
711
712    #[test]
713    fn test_requests_queued_behind_start() {
714        with_driver_server::<TestDriver, _, _>(
715            "requests queued behind start",
716            |client, _alerts| async move {
717                let start = client.start(DriverStartArgs::default());
718                let suspend = client.suspend();
719                let resume = client.resume(None::<zx::EventPair>);
720                let stop = client.stop();
721                let (start, suspend, resume, stop) = futures::join!(start, suspend, resume, stop);
722                start.unwrap().unwrap();
723                suspend.unwrap().unwrap();
724                resume.unwrap().unwrap();
725                stop.unwrap();
726            },
727        );
728    }
729
730    #[test]
731    fn test_health_check_before_start_is_rejected() {
732        with_driver_server::<TestDriver, _, _>(
733            "health check before start",
734            |client, _alerts| async move {
735                assert_eq!(
736                    client.health_check(HealthCheckRequest::Ping).await.unwrap(),
737                    Err(HealthCheckError::InvalidState)
738                );
739                client.start(DriverStartArgs::default()).await.unwrap().unwrap();
740                client.stop().await.unwrap();
741            },
742        );
743    }
744
745    #[test]
746    fn test_health_check_default() {
747        with_driver_server::<TestDriver, _, _>(
748            "health check default",
749            |client, _alerts| async move {
750                client.start(DriverStartArgs::default()).await.unwrap().unwrap();
751
752                // With the default `health_check`, PING answers OK (an empty response) after the
753                // root dispatcher liveness check, and deeper levels are not supported. None of them
754                // disturb the lifecycle requests that follow.
755                let ping = client.health_check(HealthCheckRequest::Ping).await.unwrap();
756                assert_eq!(ping, Ok(HealthCheckResponse::default()));
757                for level in [HealthCheckRequest::Fast, HealthCheckRequest::Deep] {
758                    let res = client.health_check(level).await.unwrap();
759                    assert_eq!(res, Err(HealthCheckError::NotSupported));
760                }
761                client.suspend().await.unwrap().unwrap();
762                client.stop().await.unwrap();
763            },
764        );
765    }
766
767    /// Overrides `health_check` to answer with structured diagnostics.
768    struct CustomHealthCheckDriver;
769
770    impl Driver for CustomHealthCheckDriver {
771        const NAME: &str = "custom_health_check_driver";
772
773        async fn start(_context: DriverContext) -> Result<Self, DriverError> {
774            Ok(Self)
775        }
776        async fn stop(&self) {}
777
778        async fn health_check(&self, request: HealthCheckRequest) -> HealthCheckResult {
779            if request == HealthCheckRequest::Deep {
780                return Err(HealthCheckError::NotSupported);
781            }
782            Ok(HealthCheckResponse {
783                conditions: Some(vec![HealthCondition {
784                    status: Some(HealthStatus::Degraded),
785                    reason_code: Some("FIFO_UNDERRUN".to_string()),
786                    message: Some("Recovered from underrun".to_string()),
787                    ..Default::default()
788                }]),
789                diagnostics: Some(vec![HealthDiagnosticItem {
790                    key: "underruns".to_string(),
791                    value: HealthDiagnosticValue::UintValue(2),
792                }]),
793            })
794        }
795    }
796
797    #[test]
798    fn test_health_check_custom() {
799        with_driver_server::<CustomHealthCheckDriver, _, _>(
800            "health check custom",
801            |client, _alerts| async move {
802                client.start(DriverStartArgs::default()).await.unwrap().unwrap();
803
804                let res = client.health_check(HealthCheckRequest::Fast).await.unwrap().unwrap();
805                let conditions = res.conditions.as_ref().expect("conditions");
806                assert_eq!(conditions.len(), 1);
807                assert_eq!(conditions[0].status, Some(HealthStatus::Degraded));
808                assert_eq!(conditions[0].reason_code.as_deref(), Some("FIFO_UNDERRUN"));
809                assert_eq!(res.diagnostics.as_ref().map(|d| d.len()), Some(1));
810
811                let err = client.health_check(HealthCheckRequest::Deep).await.unwrap();
812                assert_eq!(err, Err(HealthCheckError::NotSupported));
813                let unknown =
814                    client.health_check(HealthCheckRequest::UnknownOrdinal_(99)).await.unwrap();
815                assert_eq!(unknown, Err(HealthCheckError::NotSupported));
816
817                client.stop().await.unwrap();
818            },
819        );
820    }
821
822    /// Signals `test_stop_with_hung_health_check` once the hung check has been entered. Only
823    /// that test's driver type touches it, so a concurrently running test cannot consume the
824    /// sender.
825    static HUNG_HEALTH_CHECK_STARTED: std::sync::Mutex<Option<oneshot::Sender<()>>> =
826        std::sync::Mutex::new(None);
827
828    /// Never answers a health check and signals `HUNG_HEALTH_CHECK_STARTED` on entry.
829    struct SignallingHungHealthCheckDriver;
830
831    impl Driver for SignallingHungHealthCheckDriver {
832        const NAME: &str = "signalling_hung_health_check_driver";
833
834        async fn start(_context: DriverContext) -> Result<Self, DriverError> {
835            Ok(Self)
836        }
837        async fn stop(&self) {}
838
839        async fn health_check(&self, _request: HealthCheckRequest) -> HealthCheckResult {
840            if let Some(tx) = HUNG_HEALTH_CHECK_STARTED.lock().unwrap().take() {
841                let _ = tx.send(());
842            }
843            futures::future::pending().await
844        }
845    }
846
847    #[test]
848    fn test_stop_with_hung_health_check() {
849        with_driver_server::<SignallingHungHealthCheckDriver, _, _>(
850            "stop with hung health check",
851            |client, _alerts| async move {
852                client.start(DriverStartArgs::default()).await.unwrap().unwrap();
853
854                let (started_tx, started_rx) = oneshot::channel();
855                *HUNG_HEALTH_CHECK_STARTED.lock().unwrap() = Some(started_tx);
856                let hc_client = client.clone();
857                let hc_task = CurrentDispatcher
858                    .compute(async move { hc_client.health_check(HealthCheckRequest::Fast).await });
859                started_rx.await.unwrap();
860
861                // Stop must complete even though the health check never does; the pending call
862                // then fails because the server closes the channel once the driver has stopped.
863                client.stop().await.unwrap();
864                assert!(hc_task.await.unwrap().is_err());
865            },
866        );
867    }
868
869    /// Never answers a health check.
870    struct HungHealthCheckDriver;
871
872    impl Driver for HungHealthCheckDriver {
873        const NAME: &str = "hung_health_check_driver";
874
875        async fn start(_context: DriverContext) -> Result<Self, DriverError> {
876            Ok(Self)
877        }
878        async fn stop(&self) {}
879
880        async fn health_check(&self, _request: HealthCheckRequest) -> HealthCheckResult {
881            futures::future::pending().await
882        }
883    }
884
885    #[test]
886    fn test_health_check_times_out() {
887        with_driver_server::<HungHealthCheckDriver, _, _>(
888            "health check times out",
889            |client, _alerts| async move {
890                client.start(DriverStartArgs::default()).await.unwrap().unwrap();
891
892                // The driver never answers, so the server's own PING deadline (real time,
893                // ~350ms) must produce the reply.
894                let res = client.health_check(HealthCheckRequest::Ping).await.unwrap();
895                assert_eq!(res, Err(HealthCheckError::Timeout));
896
897                client.stop().await.unwrap();
898            },
899        );
900    }
901
902    /// Lets `test_forwards_health_alerts` report an alert from outside the driver after it has
903    /// started, the way a driver's own background task would.
904    static ALERTING_DRIVER_REPORTER: std::sync::Mutex<Option<HealthAlertReporter>> =
905        std::sync::Mutex::new(None);
906
907    /// Reports an alert from inside `start` and publishes its reporter for the test to report
908    /// another later.
909    struct AlertingDriver;
910
911    impl Driver for AlertingDriver {
912        const NAME: &str = "alerting_driver";
913
914        async fn start(context: DriverContext) -> Result<Self, DriverError> {
915            context.report_health_alert(HealthAlert::UpstreamNeighborFault(
916                HealthCheckResponse::default(),
917            ));
918            *ALERTING_DRIVER_REPORTER.lock().unwrap() = Some(context.health_alert_reporter());
919            Ok(Self)
920        }
921        async fn stop(&self) {}
922    }
923
924    #[test]
925    fn test_forwards_health_alerts() {
926        with_driver_server::<AlertingDriver, _, _>(
927            "forwards health alerts",
928            |client, mut alerts| async move {
929                client.start(DriverStartArgs::default()).await.unwrap().unwrap();
930                // The alert reported during `start` is sent over the `Driver` channel.
931                assert!(matches!(alerts.next().await, Some(HealthAlert::UpstreamNeighborFault(_))));
932
933                let reporter =
934                    ALERTING_DRIVER_REPORTER.lock().unwrap().take().expect("driver started");
935                reporter.report_health_alert(HealthAlert::SelfFault(HealthCheckResponse {
936                    conditions: Some(vec![HealthCondition {
937                        status: Some(HealthStatus::Unhealthy),
938                        reason_code: Some("DMA_STALLED".to_string()),
939                        ..Default::default()
940                    }]),
941                    ..Default::default()
942                }));
943                let Some(HealthAlert::SelfFault(details)) = alerts.next().await else {
944                    panic!("expected SelfFault");
945                };
946                assert_eq!(
947                    details.conditions.unwrap()[0].reason_code.as_deref(),
948                    Some("DMA_STALLED")
949                );
950
951                client.stop().await.unwrap();
952            },
953        );
954    }
955}