Skip to main content

vatsim_api/
client.rs

1//! Async HTTP client for the VATSIM APIs.
2//!
3//! [`VatsimClient`] provides methods for fetching the
4//! [data feed](https://vatsim.dev/api/data-api/get-network-data) and
5//! [slurper](https://vatsim.dev/api/slurper-api/get-user-info) endpoints.
6//! Datafeed responses are cached locally; use [`CachePolicy`] to control
7//! whether a call may return a cached copy or must refresh from the network.
8
9// These only carry `impl VatsimClient` blocks, so they are private: the methods
10// land on `VatsimClient` itself and the module path is not part of the API.
11mod datafeed;
12mod slurper;
13
14use reqwest::Client;
15use serde::Deserialize;
16use std::sync::Arc;
17use tokio::sync::RwLock;
18
19const STATUS_URL: &str = "https://status.vatsim.net/status.json";
20const DATAFEED_ENDPOINT: &str = "/v3/vatsim-data.json";
21const SLURPER_ENDPOINT: &str = "/users/info";
22const DATAFEED_CACHE_TTL_SECS: u64 = 15;
23
24/// Controls whether [`VatsimClient::datafeed`] may return a cached response.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum CachePolicy {
27    /// Return a cached copy if one exists and is still within the TTL.
28    Cached,
29    /// Always fetch from the network, ignoring any cached data.
30    Refresh,
31}
32
33/// Async HTTP client for the VATSIM data feed and slurper APIs.
34///
35/// The client is cheaply cloneable (backed by an [`Arc`]) and safe to share
36/// across tasks. Datafeed responses are cached locally according to
37/// [`ClientConfig::cache_ttl_secs`].
38#[derive(Clone)]
39pub struct VatsimClient {
40    inner: Arc<ClientInner>,
41}
42
43/// Configuration for a [`VatsimClient`].
44#[derive(Debug, Clone)]
45pub struct ClientConfig {
46    /// URL of the [VATSIM status endpoint](https://status.vatsim.net/status.json)
47    /// used to discover data feed mirror URLs.
48    pub status_url: String,
49    /// If set, bypasses status URL discovery and fetches the data feed from this
50    /// URL directly.
51    pub datafeed_url_override: Option<String>,
52    /// If set, uses this URL for slurper requests instead of the default.
53    pub slurper_url_override: Option<String>,
54    /// How many seconds a cached datafeed response is considered fresh.
55    pub cache_ttl_secs: u64,
56}
57
58impl Default for ClientConfig {
59    fn default() -> Self {
60        Self {
61            status_url: STATUS_URL.to_string(),
62            datafeed_url_override: None,
63            slurper_url_override: None,
64            cache_ttl_secs: DATAFEED_CACHE_TTL_SECS,
65        }
66    }
67}
68
69struct ClientInner {
70    http: Client,
71    config: ClientConfig,
72    datafeed_cache: RwLock<Option<(crate::types::datafeed::DataFeed, std::time::Instant)>>,
73    datafeed_urls: RwLock<Vec<String>>,
74}
75
76impl VatsimClient {
77    /// Creates a new [`VatsimClient`] with the default configuration.
78    #[must_use]
79    pub fn new() -> Self {
80        Self::with_config(ClientConfig::default())
81    }
82
83    /// Creates a new [`VatsimClient`] pointing at a mock server.
84    ///
85    /// Both the datafeed and slurper URL overrides are set to routes under
86    /// the given base URL.
87    #[must_use]
88    pub fn with_mock_base_url(mock_base_url: impl Into<String>) -> Self {
89        let base = mock_base_url.into().trim_end_matches('/').to_owned();
90        Self::with_config(ClientConfig {
91            datafeed_url_override: Some(format!("{base}{DATAFEED_ENDPOINT}")),
92            slurper_url_override: Some(format!("{base}{SLURPER_ENDPOINT}")),
93            ..Default::default()
94        })
95    }
96
97    /// Creates a new [`VatsimClient`] with the given [`ClientConfig`].
98    ///
99    /// # Panics
100    ///
101    /// Panics if the underlying HTTP client cannot be built (e.g. TLS
102    /// initialization failure). This should not happen under normal
103    /// circumstances.
104    #[must_use]
105    pub fn with_config(config: ClientConfig) -> Self {
106        Self {
107            inner: Arc::new(ClientInner {
108                http: Client::builder()
109                    .user_agent(concat!(
110                        env!("CARGO_PKG_NAME"),
111                        "/",
112                        env!("CARGO_PKG_VERSION"),
113                        " (+",
114                        env!("CARGO_PKG_REPOSITORY"),
115                        ")"
116                    ))
117                    .build()
118                    .expect("failed to build HTTP client"),
119                config,
120                datafeed_cache: RwLock::new(None),
121                datafeed_urls: RwLock::new(Vec::new()),
122            }),
123        }
124    }
125}
126
127impl Default for VatsimClient {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133#[derive(Deserialize)]
134struct StatusResponse {
135    data: StatusData,
136}
137
138#[derive(Deserialize)]
139struct StatusData {
140    v3: Vec<String>,
141}