routing/bedrock/
lazy_get.rs1use 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
14pub trait LazyGet<T: CapabilityBound>: Routable<Dict> {
16 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 init_request = if self.path.iter_segments().count() > 1 {
47 request_with_dictionary_replacement(request.as_ref())?
48 } else {
49 request.as_ref().map(|r| r.try_clone()).transpose()?
50 };
51 match self.router.route(init_request, false).await? {
52 RouterResponse::<Dict>::Capability(dict) => {
53 let moniker: ExtendedMoniker = self.not_found_error.clone().into();
54 let resp =
55 dict.get_with_request(&moniker, &self.path, request, debug).await?;
56 let resp =
57 resp.ok_or_else(|| RouterError::from(self.not_found_error.clone()))?;
58 let resp = resp.try_into().map_err(|debug_name: &'static str| {
59 RoutingError::BedrockWrongCapabilityType {
60 expected: T::debug_typename().into(),
61 actual: debug_name.into(),
62 moniker,
63 }
64 })?;
65 return Ok(resp);
66 }
67 _ => Err(RoutingError::BedrockMemberAccessUnsupported {
68 moniker: self.not_found_error.clone().into(),
69 }
70 .into()),
71 }
72 }
73 }
74
75 Router::<T>::new(ScopedDictRouter {
76 router: Router::<Dict>::new(self),
77 path,
78 not_found_error: not_found_error.into(),
79 })
80 }
81}