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 super::dict_ext::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 sandbox::{CapabilityBound, Dict, Request, Routable, Router, RouterResponse};
12use std::fmt::Debug;
13
14/// Implements the `lazy_get` function for [`Routable<Dict>`].
15pub trait LazyGet<T: CapabilityBound>: Routable<Dict> {
16    /// Returns a router that requests a dictionary from the specified `path` relative to
17    /// the base routable or fails the request with `not_found_error` if the member is not
18    /// found.
19    fn lazy_get<P>(self, path: P, not_found_error: RoutingError) -> Router<T>
20    where
21        P: IterablePath + Debug + 'static;
22}
23
24impl<R: Routable<Dict> + 'static, T: CapabilityBound> LazyGet<T> for R {
25    fn lazy_get<P>(self, path: P, not_found_error: RoutingError) -> Router<T>
26    where
27        P: IterablePath + Debug + 'static,
28    {
29        #[derive(Debug)]
30        struct ScopedDictRouter<P: IterablePath + Debug + 'static> {
31            router: Router<Dict>,
32            path: P,
33            not_found_error: RoutingError,
34        }
35
36        #[async_trait]
37        impl<P: IterablePath + Debug + 'static, T: CapabilityBound> Routable<T> for ScopedDictRouter<P> {
38            async fn route(
39                &self,
40                request: Option<Request>,
41                debug: bool,
42            ) -> Result<RouterResponse<T>, RouterError> {
43                let get_init_request = || -> Result<Option<Request>, RoutingError> {
44                    let res = if self.path.iter_segments().count() > 1 {
45                        request_with_dictionary_replacement(request.as_ref())?
46                    } else {
47                        request.as_ref().map(|r| r.try_clone()).transpose()?
48                    };
49                    Ok(res)
50                };
51
52                // If `debug` is true, that should only apply to the capability at `path`.
53                // Here we're looking up the containing dictionary, so set `debug = false`, to
54                // obtain the actual Dict and not its debug info.
55                let init_request = (get_init_request)()?;
56                match self.router.route(init_request, false).await? {
57                    RouterResponse::<Dict>::Capability(dict) => {
58                        let moniker: ExtendedMoniker = self.not_found_error.clone().into();
59                        let resp =
60                            dict.get_with_request(&moniker, &self.path, request, debug).await?;
61                        let resp =
62                            resp.ok_or_else(|| RouterError::from(self.not_found_error.clone()))?;
63                        let resp = resp.try_into().map_err(|debug_name: &'static str| {
64                            RoutingError::BedrockWrongCapabilityType {
65                                expected: T::debug_typename().into(),
66                                actual: debug_name.into(),
67                                moniker,
68                            }
69                        })?;
70                        return Ok(resp);
71                    }
72                    RouterResponse::<Dict>::Debug(data) => Ok(RouterResponse::<T>::Debug(data)),
73                    RouterResponse::<Dict>::Unavailable => {
74                        if !debug {
75                            Ok(RouterResponse::<T>::Unavailable)
76                        } else {
77                            // `debug=true` was the input to this function but the call above to
78                            // [`Router::route`] used `debug=false`. Call the router again with the
79                            // same arguments but with `debug=true` so that we return the debug
80                            // info to the caller (which ought to be [`CapabilitySource::Void`]).
81                            let init_request = (get_init_request)()?;
82                            match self.router.route(init_request, true).await? {
83                                RouterResponse::<Dict>::Debug(d) => {
84                                    Ok(RouterResponse::<T>::Debug(d))
85                                }
86                                _ => {
87                                    // This shouldn't happen (we passed debug=true).
88                                    let moniker = self.not_found_error.clone().into();
89                                    Err(RoutingError::BedrockWrongCapabilityType {
90                                        expected: "RouterResponse::Debug".into(),
91                                        actual: "not RouterResponse::Debug".into(),
92                                        moniker,
93                                    }
94                                    .into())
95                                }
96                            }
97                        }
98                    }
99                }
100            }
101        }
102
103        Router::<T>::new(ScopedDictRouter {
104            router: Router::<Dict>::new(self),
105            path,
106            not_found_error: not_found_error.into(),
107        })
108    }
109}