Skip to main content

zebra_test/
transcript.rs

1//! A [`Service`] implementation based on a fixed transcript.
2
3use std::{
4    fmt::Debug,
5    sync::Arc,
6    task::{Context, Poll},
7    time::Duration,
8};
9
10use color_eyre::{
11    eyre::{eyre, Report, WrapErr},
12    section::Section,
13    section::SectionExt,
14};
15use futures::future::{ready, Ready};
16use tokio::time::timeout;
17use tower::{Service, ServiceExt};
18
19type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
20
21/// Maximum time for one transcript request, including readiness and its response.
22const TRANSCRIPT_STEP_TIMEOUT: Duration = Duration::from_secs(60);
23
24/// An error-checking function: is the value an expected error?
25///
26/// If the checked error is the expected error, the function should return `Ok(())`.
27/// Otherwise, it should just return the checked error, wrapped inside `Err`.
28pub type ErrorChecker = fn(Option<BoxError>) -> Result<(), BoxError>;
29
30/// An expected error in a transcript.
31#[derive(Debug, Clone)]
32pub enum ExpectedTranscriptError {
33    /// Match any error
34    Any,
35    /// Use a validator function to check for matching errors
36    Exact(Arc<ErrorChecker>),
37}
38
39impl ExpectedTranscriptError {
40    /// Convert the `verifier` function into an exact error checker
41    pub fn exact(verifier: ErrorChecker) -> Self {
42        ExpectedTranscriptError::Exact(verifier.into())
43    }
44
45    /// Check the actual error `e` against this expected error.
46    #[track_caller]
47    fn check(&self, e: BoxError) -> Result<(), Report> {
48        match self {
49            ExpectedTranscriptError::Any => Ok(()),
50            ExpectedTranscriptError::Exact(checker) => checker(Some(e)),
51        }
52        .map_err(ErrorCheckerError)
53        .wrap_err("service returned an error but it didn't match the expected error")
54    }
55
56    fn mock(&self) -> Report {
57        match self {
58            ExpectedTranscriptError::Any => eyre!("mock error"),
59            ExpectedTranscriptError::Exact(checker) => {
60                checker(None).map_err(|e| eyre!(e)).expect_err(
61                    "transcript should correctly produce the expected mock error when passed None",
62                )
63            }
64        }
65    }
66}
67
68#[derive(Debug, thiserror::Error)]
69#[error("ErrorChecker Error: {0}")]
70struct ErrorCheckerError(BoxError);
71
72/// A transcript: a list of requests and expected results.
73#[must_use]
74pub struct Transcript<R, S, I>
75where
76    I: Iterator<Item = (R, Result<S, ExpectedTranscriptError>)>,
77{
78    messages: I,
79}
80
81impl<R, S, I> From<I> for Transcript<R, S, I::IntoIter>
82where
83    I: IntoIterator<Item = (R, Result<S, ExpectedTranscriptError>)>,
84{
85    fn from(messages: I) -> Self {
86        Self {
87            messages: messages.into_iter(),
88        }
89    }
90}
91
92impl<R, S, I> Transcript<R, S, I>
93where
94    I: Iterator<Item = (R, Result<S, ExpectedTranscriptError>)>,
95    R: Debug,
96    S: Debug + Eq,
97{
98    /// Check this transcript against the responses from the `to_check` service.
99    ///
100    /// Each request has a 60-second deadline covering both readiness and the response. A timeout
101    /// returns an error identifying the request.
102    pub async fn check<C>(mut self, mut to_check: C) -> Result<(), Report>
103    where
104        C: Service<R, Response = S>,
105        C::Error: Into<BoxError>,
106    {
107        for (req, expected_rsp) in &mut self.messages {
108            let request_context = format!("{req:?}");
109            let response = timeout(TRANSCRIPT_STEP_TIMEOUT, async {
110                let service = to_check
111                    .ready()
112                    .await
113                    .map_err(Into::into)
114                    .map_err(|e| eyre!(e))
115                    .expect("expected service to not fail during execution of transcript");
116
117                service.call(req).await
118            })
119            .await
120            .wrap_err_with(|| format!("transcript timed out for request: {request_context}"))?;
121
122            match (response, expected_rsp) {
123                (Ok(rsp), Ok(expected_rsp)) => {
124                    if rsp != expected_rsp {
125                        Err(eyre!(
126                            "response doesn't match transcript's expected response"
127                        ))
128                        .with_section(|| format!("{expected_rsp:?}").header("Expected Response:"))
129                        .with_section(|| format!("{rsp:?}").header("Found Response:"))?;
130                    }
131                }
132                (Ok(rsp), Err(error_checker)) => {
133                    let error = Err(eyre!("received a response when an error was expected"))
134                        .with_section(|| format!("{rsp:?}").header("Found Response:"));
135
136                    let error = match std::panic::catch_unwind(|| error_checker.mock()) {
137                        Ok(expected_err) => error
138                            .with_section(|| format!("{expected_err:?}").header("Expected Error:")),
139                        Err(pi) => {
140                            let payload = pi
141                                .downcast_ref::<String>()
142                                .cloned()
143                                .or_else(|| pi.downcast_ref::<&str>().map(ToString::to_string))
144                                .unwrap_or_else(|| "<non string panic payload>".into());
145
146                            error
147                                .section(payload.header("Panic:"))
148                                .wrap_err("ErrorChecker panicked when producing expected response")
149                        }
150                    };
151
152                    error?;
153                }
154                (Err(e), Ok(expected_rsp)) => {
155                    Err(eyre!("received an error when a response was expected"))
156                        .with_error(|| ErrorCheckerError(e.into()))
157                        .with_section(|| format!("{expected_rsp:?}").header("Expected Response:"))?
158                }
159                (Err(e), Err(error_checker)) => {
160                    error_checker.check(e.into())?;
161                    continue;
162                }
163            }
164        }
165        Ok(())
166    }
167}
168
169impl<R, S, I> Service<R> for Transcript<R, S, I>
170where
171    R: Debug + Eq,
172    I: Iterator<Item = (R, Result<S, ExpectedTranscriptError>)>,
173{
174    type Response = S;
175    type Error = Report;
176    type Future = Ready<Result<S, Report>>;
177
178    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
179        Poll::Ready(Ok(()))
180    }
181
182    #[track_caller]
183    fn call(&mut self, request: R) -> Self::Future {
184        if let Some((expected_request, response)) = self.messages.next() {
185            if request != expected_request {
186                return ready(
187                    Err(eyre!("received unexpected request"))
188                        .with_section(|| {
189                            format!("{expected_request:?}").header("Expected Request:")
190                        })
191                        .with_section(|| format!("{request:?}").header("Found Request:")),
192                );
193            }
194
195            match response {
196                Ok(response) => ready(Ok(response)),
197                Err(check_fn) => ready(Err(check_fn.mock())),
198            }
199        } else {
200            ready(Err(eyre!("Got request after transcript ended")))
201        }
202    }
203}