Skip to main content

base/interface/exec/in_process/
network.rs

1//! A network that is not there.
2
3use std::collections::BTreeMap;
4use std::sync::{Arc, Mutex};
5
6use crate::interface::exec::{ExecError, HttpRequest, HttpResponse, Network, Origin};
7
8/// Answers only what it was given, and refuses everything else.
9///
10/// Refusing rather than returning an empty 200: a tool that got an empty page
11/// for a url nobody scripted would report that the page was empty, which is a
12/// different and much harder failure to notice than "nothing answers here".
13#[derive(Clone, Default)]
14pub struct OfflineNetwork {
15    fixtures: Arc<Mutex<BTreeMap<String, HttpResponse>>>,
16    asked: Arc<Mutex<Vec<String>>>,
17}
18
19impl OfflineNetwork {
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    pub fn with(self, url: impl Into<String>, status: u16, body: impl Into<String>) -> Self {
25        self.fixtures
26            .lock()
27            .unwrap_or_else(std::sync::PoisonError::into_inner)
28            .insert(
29                url.into(),
30                HttpResponse {
31                    status,
32                    headers: BTreeMap::new(),
33                    body: body.into().into_bytes(),
34                },
35            );
36        self
37    }
38
39    /// Every url that was asked for, in order.
40    pub fn asked(&self) -> Vec<String> {
41        self.asked
42            .lock()
43            .unwrap_or_else(std::sync::PoisonError::into_inner)
44            .clone()
45    }
46}
47
48#[async_trait::async_trait]
49impl Network for OfflineNetwork {
50    async fn send(&self, req: HttpRequest, _origin: Origin) -> Result<HttpResponse, ExecError> {
51        self.asked
52            .lock()
53            .unwrap_or_else(std::sync::PoisonError::into_inner)
54            .push(req.url.clone());
55        self.fixtures
56            .lock()
57            .unwrap_or_else(std::sync::PoisonError::into_inner)
58            .get(&req.url)
59            .cloned()
60            .ok_or_else(|| ExecError::unavailable(format!("offline: {}", req.url)))
61    }
62
63    fn permits(&self, _host: &str, _origin: Origin) -> bool {
64        // Permitted and unreachable are different answers. Saying "not
65        // permitted" here would make a caller report a policy refusal for
66        // something no policy refused.
67        true
68    }
69}