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