Skip to main content

routing/bedrock/
lazy_get.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 crate::bedrock::dict_ext::request_with_dictionary_replacement;
6use crate::{DictExt, RoutingError};
7use async_trait::async_trait;
8use capability_source::CapabilitySource;
9use cm_types::IterablePath;
10use fidl_fuchsia_component_runtime::RouteRequest;
11use moniker::ExtendedMoniker;
12use router_error::RouterError;
13use runtime_capabilities::{
14    Capability, CapabilityBound, Dictionary, Routable, Router, WeakInstanceToken,
15};
16use std::fmt::Debug;
17use std::sync::Arc;
18
19/// Implements the `lazy_get` function for [`Routable<Dictionary>`].
20pub trait LazyGet<T: CapabilityBound> {
21    /// Returns a router that requests a dictionary from the specified `path` relative to
22    /// the base routable or fails the request with `not_found_error` if the member is not
23    /// found.
24    fn lazy_get<P>(self, path: P, not_found_error: RoutingError) -> Arc<Router<T>>
25    where
26        P: IterablePath + Debug + 'static;
27}
28
29impl<T: CapabilityBound> LazyGet<T> for Arc<Router<Dictionary>>
30where
31    Arc<T>: TryFrom<Capability>,
32{
33    fn lazy_get<P>(self, path: P, not_found_error: RoutingError) -> Arc<Router<T>>
34    where
35        P: IterablePath + Debug + 'static,
36    {
37        #[derive(Debug)]
38        struct ScopedDictRouter<P: IterablePath + Debug + 'static> {
39            router: Arc<Router<Dictionary>>,
40            path: P,
41            not_found_error: RoutingError,
42        }
43
44        #[async_trait]
45        impl<P: IterablePath + Debug + 'static, T: CapabilityBound> Routable<T> for ScopedDictRouter<P>
46        where
47            Arc<T>: TryFrom<Capability>,
48        {
49            async fn route(
50                &self,
51                request: RouteRequest,
52                target: Arc<WeakInstanceToken>,
53            ) -> Result<Option<Arc<T>>, RouterError> {
54                let get_init_request = || request_with_dictionary_replacement(&request);
55
56                let init_request = (get_init_request)()?;
57                match self.router.route(init_request, target.clone()).await? {
58                    Some(dict) => {
59                        let moniker: ExtendedMoniker = self.not_found_error.clone().into();
60                        match dict.get_with_request(&moniker, &self.path, request, target).await {
61                            Err(router_error)
62                                if let Ok(RoutingError::BedrockNotPresentInDictionary {
63                                    ..
64                                }) = router_error.clone().try_into() =>
65                            {
66                                Err(self.not_found_error.clone().into())
67                            }
68                            Err(e) => Err(e),
69                            Ok(None) => Ok(None),
70                            Ok(Some(cap)) => {
71                                let actual_type_name = cap.debug_typename();
72                                let cap: Arc<T> = cap.try_into().map_err(|_| {
73                                    RoutingError::BedrockWrongCapabilityType {
74                                        expected: T::debug_typename().into(),
75                                        actual: actual_type_name.into(),
76                                        moniker,
77                                    }
78                                })?;
79                                Ok(Some(cap))
80                            }
81                        }
82                    }
83                    None => Ok(None),
84                }
85            }
86
87            async fn route_debug(
88                &self,
89                request: RouteRequest,
90                target: Arc<WeakInstanceToken>,
91            ) -> Result<CapabilitySource, RouterError> {
92                let get_init_request = || request_with_dictionary_replacement(&request);
93
94                // When performing a debug route, we only want to call `route_debug` on the
95                // capability at `path`. Here we're looking up the containing dictionary, so we do
96                // non-debug routing, to obtain the actual Dictionary and not its debug info.
97                let init_request = (get_init_request)()?;
98                match self.router.route(init_request, target.clone()).await? {
99                    Some(dict) => {
100                        let moniker: ExtendedMoniker = self.not_found_error.clone().into();
101                        match dict
102                            .get_with_request_debug(&moniker, &self.path, request, target)
103                            .await
104                        {
105                            Err(router_error)
106                                if let Ok(RoutingError::BedrockNotPresentInDictionary {
107                                    ..
108                                }) = router_error.clone().try_into() =>
109                            {
110                                Err(self.not_found_error.clone().into())
111                            }
112                            other_result => other_result,
113                        }
114                    }
115                    None => {
116                        // The above route was non-debug, but the routing operation failed. Call
117                        // the router again with the same arguments but with `route_debug` so that
118                        // we return the debug info to the caller (which ought to be
119                        // [`CapabilitySource::Void`]).
120                        let init_request = (get_init_request)()?;
121                        self.router.route_debug(init_request, target).await
122                    }
123                }
124            }
125        }
126
127        Router::<T>::new(ScopedDictRouter {
128            router: self,
129            path,
130            not_found_error: not_found_error.into(),
131        })
132    }
133}