Skip to main content

day_part_http/
session.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Runtime routing. Selection is captured for a logical request; changes affect the next one.
5use crate::{
6    Capabilities,
7    simulation::Simulation,
8    statistics::Store,
9    transport::{Transport, TransportConfig},
10};
11use std::sync::{Arc, Mutex, OnceLock};
12
13pub(crate) fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
14    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
15}
16
17pub(crate) struct Resolved {
18    pub transport: Arc<dyn Transport>,
19    pub clock: Option<Arc<dyn crate::simulation::Clock>>,
20}
21type Factory = dyn Fn(&TransportConfig) -> Arc<dyn Transport> + Send + Sync;
22/// An HTTP/WebSocket provider. Native is the default; custom providers must describe their
23/// capabilities honestly. Reqwest is optional and unavailable on wasm.
24#[derive(Clone, Default)]
25pub enum Provider {
26    #[default]
27    Native,
28    Custom(Arc<Factory>),
29    #[cfg(all(feature = "reqwest", not(target_arch = "wasm32")))]
30    Reqwest,
31}
32impl Provider {
33    pub fn custom(
34        factory: impl Fn(&TransportConfig) -> Arc<dyn Transport> + Send + Sync + 'static,
35    ) -> Self {
36        Self::Custom(Arc::new(factory))
37    }
38    pub(crate) fn build(&self, config: &TransportConfig) -> Arc<dyn Transport> {
39        match self {
40            Self::Native => crate::platform_transport(config),
41            Self::Custom(f) => f(config),
42            #[cfg(all(feature = "reqwest", not(target_arch = "wasm32")))]
43            Self::Reqwest => Arc::new(crate::reqwest_provider::Reqwest::new(config)),
44        }
45    }
46}
47struct Settings {
48    provider: Provider,
49    generation: u64,
50    simulation: Option<Simulation>,
51}
52struct Inner {
53    settings: Mutex<Settings>,
54    stats: Arc<Store>,
55}
56/// An isolated routing and statistics scope. Clones share settings. A new session uses the
57/// native provider and does not inherit global interception. Default clients use `global()`.
58#[derive(Clone)]
59pub struct Session(Arc<Inner>);
60impl Default for Session {
61    fn default() -> Self {
62        Self::new()
63    }
64}
65impl Session {
66    #[must_use]
67    pub fn new() -> Self {
68        Self(Arc::new(Inner {
69            settings: Mutex::new(Settings {
70                provider: Provider::Native,
71                generation: 0,
72                simulation: None,
73            }),
74            stats: Arc::new(Store::default()),
75        }))
76    }
77    pub fn global() -> Self {
78        static GLOBAL: OnceLock<Session> = OnceLock::new();
79        GLOBAL.get_or_init(Self::new).clone()
80    }
81    /// Applies to subsequent requests, including clients that already exist.
82    pub fn set_provider(&self, provider: Provider) {
83        let mut s = lock(&self.0.settings);
84        s.provider = provider;
85        s.generation += 1;
86    }
87    /// Enable/disable interception. Active transfers keep their selected handler and provider.
88    pub fn set_simulation(&self, simulation: Option<Simulation>) {
89        lock(&self.0.settings).simulation = simulation;
90    }
91    #[must_use]
92    pub fn statistics(&self) -> crate::Statistics {
93        self.0.stats.snapshot()
94    }
95    /// The latest 256 exchanges/sockets, including in-progress operations; totals are unbounded
96    /// counters, but history storage is bounded. These are not physical TCP connection counts.
97    #[must_use]
98    pub fn transfers(&self) -> Vec<crate::TransferStatistics> {
99        self.0.stats.transfers()
100    }
101    pub(crate) fn resolve(
102        &self,
103        config: &TransportConfig,
104        cache: &Mutex<Option<(u64, Arc<dyn Transport>)>>,
105        url: &str,
106        method: &str,
107    ) -> Resolved {
108        let simulation = lock(&self.0.settings).simulation.clone();
109        let simulation = simulation.filter(|s| s.intercepts(method, url));
110        let (selected, clock, simulated) = match simulation {
111            Some(s) => (s.transport(), Some(s.clock()), true),
112            None => (self.provider_transport(config, cache), None, false),
113        };
114        Resolved {
115            transport: crate::statistics::observe(selected, self.0.stats.clone(), simulated),
116            clock,
117        }
118    }
119
120    pub(crate) fn provider_transport(
121        &self,
122        config: &TransportConfig,
123        cache: &Mutex<Option<(u64, Arc<dyn Transport>)>>,
124    ) -> Arc<dyn Transport> {
125        let (provider, generation) = {
126            let s = lock(&self.0.settings);
127            (s.provider.clone(), s.generation)
128        };
129        let cached = lock(cache)
130            .as_ref()
131            .filter(|(g, _)| *g == generation)
132            .map(|(_, t)| t.clone());
133        cached.unwrap_or_else(|| {
134            let t = provider.build(config);
135            *lock(cache) = Some((generation, t.clone()));
136            t
137        })
138    }
139    pub(crate) fn observe(&self, t: Arc<dyn Transport>) -> Arc<dyn Transport> {
140        crate::statistics::observe(t, self.0.stats.clone(), false)
141    }
142}
143
144pub(crate) fn simulated_capabilities() -> Capabilities {
145    Capabilities {
146        streaming: true,
147        upload_streaming: true,
148        upload_progress: true,
149        manual_redirects: true,
150        websockets: true,
151        websocket_ping: true,
152        websocket_headers: true,
153        ..Default::default()
154    }
155}