routing/bedrock/
with_error_reporter.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use async_trait::async_trait;
use router_error::RouterError;
use sandbox::{CapabilityBound, Request, Routable, Router, RouterResponse};

use crate::error::{ErrorReporter, RouteRequestErrorInfo};

pub trait WithErrorReporter {
    /// Returns a router that reports errors to `error_reporter`.
    fn with_error_reporter(
        self,
        route_request: RouteRequestErrorInfo,
        error_reporter: impl ErrorReporter,
    ) -> Self;
}

struct RouterWithErrorReporter<T: CapabilityBound, R: ErrorReporter> {
    router: Router<T>,
    route_request: RouteRequestErrorInfo,
    error_reporter: R,
}

#[async_trait]
impl<T: CapabilityBound, R: ErrorReporter> Routable<T> for RouterWithErrorReporter<T, R> {
    async fn route(
        &self,
        request: Option<Request>,
        debug: bool,
    ) -> Result<RouterResponse<T>, RouterError> {
        match self.router.route(request, debug).await {
            Ok(res) => Ok(res),
            Err(err) => {
                self.error_reporter.report(&self.route_request, &err).await;
                Err(err)
            }
        }
    }
}

impl<T: CapabilityBound> WithErrorReporter for Router<T> {
    fn with_error_reporter(
        self,
        route_request: RouteRequestErrorInfo,
        error_reporter: impl ErrorReporter,
    ) -> Self {
        Self::new(RouterWithErrorReporter { router: self, route_request, error_reporter })
    }
}