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