routing/bedrock/
with_default.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 async_trait::async_trait;
6use router_error::RouterError;
7use sandbox::{CapabilityBound, Request, Routable, Router, RouterResponse};
8
9pub trait WithDefault {
10    /// Returns a router that exceptions a `None` request, supplying the provided default.
11    fn with_default(self, request: Request) -> Self;
12}
13
14#[derive(Debug)]
15struct RouterWithDefault<T: CapabilityBound> {
16    router: Router<T>,
17    default_request: Request,
18}
19
20#[async_trait]
21impl<T: CapabilityBound> Routable<T> for RouterWithDefault<T> {
22    async fn route(
23        &self,
24        request: Option<Request>,
25        debug: bool,
26    ) -> Result<RouterResponse<T>, RouterError> {
27        let request =
28            if let Some(request) = request { request } else { self.default_request.try_clone()? };
29        self.router.route(Some(request), debug).await
30    }
31}
32
33impl<T: CapabilityBound> WithDefault for Router<T> {
34    fn with_default(self, request: Request) -> Self {
35        Self::new(RouterWithDefault { router: self, default_request: request })
36    }
37}