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 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::{
12    CapabilityBound, Dict, Request, Routable, Router, RouterResponse, WeakInstanceToken,
13};
14use std::fmt::Debug;
15
16/// Implements the `lazy_get` function for [`Routable<Dict>`].
17pub trait LazyGet<T: CapabilityBound>: Routable<Dict> {
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<Dict> + '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<Dict>,
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                debug: bool,
44                target: WeakInstanceToken,
45            ) -> Result<RouterResponse<T>, RouterError> {
46                let get_init_request = || -> Result<Option<Request>, RoutingError> {
47                    let res = if self.path.iter_segments().count() > 1 {
48                        request_with_dictionary_replacement(request.as_ref())?
49                    } else {
50                        request.as_ref().map(|r| r.try_clone()).transpose().map_err(|e| {
51                            RoutingError::try_from(e).unwrap_or(RoutingError::UnexpectedError)
52                        })?
53                    };
54                    Ok(res)
55                };
56
57                // If `debug` is true, that should only apply to the capability at `path`.
58                // Here we're looking up the containing dictionary, so set `debug = false`, to
59                // obtain the actual Dict and not its debug info.
60                let init_request = (get_init_request)()?;
61                match self.router.route(init_request, false, target.clone()).await? {
62                    RouterResponse::<Dict>::Capability(dict) => {
63                        let moniker: ExtendedMoniker = self.not_found_error.clone().into();
64                        let resp = dict
65                            .get_with_request(&moniker, &self.path, request, debug, target.clone())
66                            .await?;
67                        let resp =
68                            resp.ok_or_else(|| RouterError::from(self.not_found_error.clone()))?;
69                        let resp = resp.try_into().map_err(|debug_name: &'static str| {
70                            RoutingError::BedrockWrongCapabilityType {
71                                expected: T::debug_typename().into(),
72                                actual: debug_name.into(),
73                                moniker,
74                            }
75                        })?;
76                        return Ok(resp);
77                    }
78                    RouterResponse::<Dict>::Debug(data) => Ok(RouterResponse::<T>::Debug(data)),
79                    RouterResponse::<Dict>::Unavailable => {
80                        if !debug {
81                            Ok(RouterResponse::<T>::Unavailable)
82                        } else {
83                            // `debug=true` was the input to this function but the call above to
84                            // [`Router::route`] used `debug=false`. Call the router again with the
85                            // same arguments but with `debug=true` so that we return the debug
86                            // info to the caller (which ought to be [`CapabilitySource::Void`]).
87                            let init_request = (get_init_request)()?;
88                            match self.router.route(init_request, true, target).await? {
89                                RouterResponse::<Dict>::Debug(d) => {
90                                    Ok(RouterResponse::<T>::Debug(d))
91                                }
92                                _ => {
93                                    // This shouldn't happen (we passed debug=true).
94                                    let moniker = self.not_found_error.clone().into();
95                                    Err(RoutingError::BedrockWrongCapabilityType {
96                                        expected: "RouterResponse::Debug".into(),
97                                        actual: "not RouterResponse::Debug".into(),
98                                        moniker,
99                                    }
100                                    .into())
101                                }
102                            }
103                        }
104                    }
105                }
106            }
107        }
108
109        Router::<T>::new(ScopedDictRouter {
110            router: Router::<Dict>::new(self),
111            path,
112            not_found_error: not_found_error.into(),
113        })
114    }
115}