Skip to main content

libtea_core/
discovery.rs

1//! `.well-known/tea` documents and `/discovery` responses.
2//!
3//! Parsing enforces the pinned schema constraints that decide failover:
4//! `schemaVersion` 1, non-empty endpoint lists, absolute base URLs, and
5//! SemVer versions. Priority omitted on the wire becomes `1`.
6
7use serde::Deserialize;
8use url::Url;
9
10use crate::error::{ModelError, PolicyError};
11use crate::ids::ProductReleaseId;
12use crate::policy::parse_api_base;
13use crate::version::{
14    select_endpoints, ApiVersion, OrderedPriority, SelectedEndpoint, SupportedApi,
15    VersionedEndpoint,
16};
17
18/// A validated `.well-known/tea` document.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct WellKnownDocument {
21    endpoints: Vec<WellKnownEndpoint>,
22}
23
24/// One well-known endpoint.
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct WellKnownEndpoint {
28    /// Advertised API root.
29    pub url: String,
30    /// Advertised versions in document order.
31    pub versions: Vec<ApiVersion>,
32    /// Effective priority.
33    pub priority: OrderedPriority,
34}
35
36/// One resolved product release from `/discovery`.
37#[derive(Debug, Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct DiscoveryInfo {
40    /// Product release UUID.
41    pub product_release: ProductReleaseId,
42    /// Servers that can serve that release.
43    pub servers: Vec<DiscoveryServer>,
44}
45
46/// One `servers[]` entry.
47#[derive(Debug, Clone, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct DiscoveryServer {
50    /// API root.
51    pub root_url: String,
52    /// Advertised versions in document order.
53    pub versions: Vec<ApiVersion>,
54    /// Effective priority.
55    pub priority: OrderedPriority,
56}
57
58#[derive(Debug, Deserialize)]
59#[serde(rename_all = "camelCase")]
60struct WellKnownWire {
61    schema_version: i64,
62    endpoints: Vec<EndpointWire>,
63}
64
65#[derive(Debug, Deserialize)]
66struct EndpointWire {
67    url: String,
68    versions: Vec<String>,
69    #[serde(default)]
70    priority: Option<f64>,
71}
72
73#[derive(Debug, Deserialize)]
74#[serde(rename_all = "camelCase")]
75struct DiscoveryWire {
76    product_release_uuid: String,
77    servers: Vec<ServerWire>,
78}
79
80#[derive(Debug, Deserialize)]
81#[serde(rename_all = "camelCase")]
82struct ServerWire {
83    root_url: String,
84    versions: Vec<String>,
85    #[serde(default)]
86    priority: Option<f64>,
87}
88
89impl WellKnownDocument {
90    /// Parse and validate a well-known document.
91    ///
92    /// # Errors
93    ///
94    /// Returns an error when the JSON is not a schema version 1 document.
95    pub fn parse(bytes: &[u8]) -> Result<Self, ModelError> {
96        Self::parse_with(bytes, false)
97    }
98
99    /// Like [`Self::parse`], but also accepts short API versions such as `1`
100    /// and `1.0` (see [`ApiVersion::parse_lenient`]).
101    ///
102    /// # Errors
103    ///
104    /// Returns an error when the JSON is not a schema version 1 document.
105    pub fn parse_lenient(bytes: &[u8]) -> Result<Self, ModelError> {
106        Self::parse_with(bytes, true)
107    }
108
109    fn parse_with(bytes: &[u8], lenient: bool) -> Result<Self, ModelError> {
110        let wire: WellKnownWire = serde_json::from_slice(bytes)?;
111        if wire.schema_version != 1 {
112            return Err(ModelError::Invalid(
113                "well-known schemaVersion must be 1".into(),
114            ));
115        }
116        if wire.endpoints.is_empty() {
117            return Err(ModelError::Invalid(
118                "well-known endpoints must not be empty".into(),
119            ));
120        }
121        let mut endpoints = Vec::with_capacity(wire.endpoints.len());
122        for endpoint in wire.endpoints {
123            endpoints.push(parse_endpoint(endpoint, lenient)?);
124        }
125        Ok(Self { endpoints })
126    }
127
128    /// Endpoints in document order.
129    #[must_use]
130    pub fn endpoints(&self) -> &[WellKnownEndpoint] {
131        &self.endpoints
132    }
133
134    /// Order endpoints for connection attempts.
135    ///
136    /// # Errors
137    ///
138    /// Returns an error when none advertise a supported version.
139    pub fn select(&self, supported: &SupportedApi) -> Result<Vec<SelectedEndpoint>, ModelError> {
140        let view: Vec<VersionedEndpoint> = self
141            .endpoints
142            .iter()
143            .map(|endpoint| VersionedEndpoint {
144                root_url: endpoint.url.clone(),
145                versions: endpoint.versions.clone(),
146                priority: endpoint.priority,
147            })
148            .collect();
149        select_endpoints(&view, supported)
150    }
151}
152
153impl DiscoveryInfo {
154    /// Parse a successful `/discovery` body.
155    ///
156    /// An empty array is rejected. The specification requires `404` with a TEA
157    /// error body when the identifier does not resolve, not `200 []`.
158    ///
159    /// # Errors
160    ///
161    /// Returns an error when the body is not a non-empty array of discovery objects.
162    pub fn parse_list(bytes: &[u8]) -> Result<Vec<Self>, ModelError> {
163        Self::parse_list_with(bytes, false)
164    }
165
166    /// Like [`Self::parse_list`], but also accepts short API versions such as
167    /// `1` and `1.0` (see [`ApiVersion::parse_lenient`]).
168    ///
169    /// # Errors
170    ///
171    /// Returns an error when the body is not a non-empty array of discovery objects.
172    pub fn parse_list_lenient(bytes: &[u8]) -> Result<Vec<Self>, ModelError> {
173        Self::parse_list_with(bytes, true)
174    }
175
176    fn parse_list_with(bytes: &[u8], lenient: bool) -> Result<Vec<Self>, ModelError> {
177        let wire: Vec<DiscoveryWire> = serde_json::from_slice(bytes)?;
178        if wire.is_empty() {
179            return Err(ModelError::Invalid(
180                "discovery success body must be a non-empty array".into(),
181            ));
182        }
183        wire.into_iter()
184            .map(|item| parse_discovery(item, lenient))
185            .collect()
186    }
187
188    /// Order this release's servers for later API calls.
189    ///
190    /// # Errors
191    ///
192    /// Returns an error when none advertise a supported version.
193    pub fn select_server(
194        &self,
195        supported: &SupportedApi,
196    ) -> Result<Vec<SelectedEndpoint>, ModelError> {
197        let view: Vec<VersionedEndpoint> = self
198            .servers
199            .iter()
200            .map(|server| VersionedEndpoint {
201                root_url: server.root_url.clone(),
202                versions: server.versions.clone(),
203                priority: server.priority,
204            })
205            .collect();
206        select_endpoints(&view, supported)
207    }
208}
209
210fn parse_endpoint(endpoint: EndpointWire, lenient: bool) -> Result<WellKnownEndpoint, ModelError> {
211    validate_base(&endpoint.url)?;
212    Ok(WellKnownEndpoint {
213        url: endpoint.url,
214        versions: parse_versions(endpoint.versions, lenient)?,
215        priority: parse_priority(endpoint.priority)?,
216    })
217}
218
219fn parse_discovery(item: DiscoveryWire, lenient: bool) -> Result<DiscoveryInfo, ModelError> {
220    if item.servers.is_empty() {
221        return Err(ModelError::Invalid(
222            "discovery servers must not be empty".into(),
223        ));
224    }
225    let mut servers = Vec::with_capacity(item.servers.len());
226    for server in item.servers {
227        validate_base(&server.root_url)?;
228        servers.push(DiscoveryServer {
229            root_url: server.root_url,
230            versions: parse_versions(server.versions, lenient)?,
231            priority: parse_priority(server.priority)?,
232        });
233    }
234    Ok(DiscoveryInfo {
235        product_release: ProductReleaseId::parse(&item.product_release_uuid)?,
236        servers,
237    })
238}
239
240fn parse_versions(values: Vec<String>, lenient: bool) -> Result<Vec<ApiVersion>, ModelError> {
241    if values.is_empty() {
242        return Err(ModelError::Invalid("versions must not be empty".into()));
243    }
244    values
245        .iter()
246        .map(|value| {
247            if lenient {
248                ApiVersion::parse_lenient(value)
249            } else {
250                ApiVersion::parse(value)
251            }
252        })
253        .collect()
254}
255
256fn parse_priority(value: Option<f64>) -> Result<OrderedPriority, ModelError> {
257    match value {
258        None => Ok(OrderedPriority::default_priority()),
259        Some(priority) => OrderedPriority::parse(priority),
260    }
261}
262
263fn validate_base(text: &str) -> Result<Url, ModelError> {
264    parse_api_base(text).map_err(|err: PolicyError| ModelError::Invalid(err.to_string()))
265}
266
267/// Decide whether a `404` body is a TEA error response.
268///
269/// Recognition follows the discovery document: `Content-Type` is
270/// `application/json` with optional parameters, and the body is a JSON object
271/// with a string `error` property. Unknown `error` values still count. This is
272/// intentionally wider than `additionalProperties: false`, because the prose
273/// says a later error value must not become a failover trigger.
274#[must_use]
275pub fn tea_error_code(content_type: Option<&str>, body: &[u8]) -> Option<String> {
276    if !is_json_content_type(content_type) {
277        return None;
278    }
279    let value: serde_json::Value = serde_json::from_slice(body).ok()?;
280    let error = value.get("error")?.as_str()?;
281    Some(error.to_owned())
282}
283
284/// Whether a media type is `application/json`, ignoring parameters and case.
285#[must_use]
286pub fn is_json_content_type(content_type: Option<&str>) -> bool {
287    let Some(content_type) = content_type else {
288        return false;
289    };
290    let essence = content_type.split(';').next().unwrap_or("").trim();
291    essence.eq_ignore_ascii_case("application/json")
292}
293
294/// Append one query parameter, encoding it a single time.
295///
296/// # Errors
297///
298/// Returns an error when `prefix` is not a valid URL.
299pub fn with_query(prefix: &str, name: &str, value: &str) -> Result<Url, ModelError> {
300    let mut url = Url::parse(prefix)
301        .map_err(|err| ModelError::Invalid(format!("cannot build query URL: {err}")))?;
302    url.query_pairs_mut().clear().append_pair(name, value);
303    Ok(url)
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn selects_the_normative_well_known_example() {
312        let json = br#"{
313          "schemaVersion": 1,
314          "endpoints": [
315            {"url": "https://api.example.com", "versions": ["1.0.0"], "priority": 1},
316            {"url": "https://api2.example.com/mytea", "versions": ["1.0.0"], "priority": 0.5}
317          ]
318        }"#;
319        let doc = WellKnownDocument::parse(json).unwrap();
320        let selected = doc.select(&SupportedApi::tea_1_0_0()).unwrap();
321        assert_eq!(selected[0].root_url, "https://api.example.com");
322        assert_eq!(selected[1].priority.get(), 0.5);
323    }
324
325    #[test]
326    fn omitted_priority_is_one_and_http_base_parses() {
327        let json = br#"{
328          "schemaVersion": 1,
329          "endpoints": [{"url": "http://localhost:8080/tea", "versions": ["1.0.0"]}]
330        }"#;
331        let doc = WellKnownDocument::parse(json).unwrap();
332        assert_eq!(doc.endpoints()[0].priority.get(), 1.0);
333    }
334
335    #[test]
336    fn empty_discovery_array_is_rejected() {
337        assert!(DiscoveryInfo::parse_list(b"[]").is_err());
338    }
339
340    #[test]
341    fn tea_error_recognition_keeps_unknown_codes() {
342        assert_eq!(
343            tea_error_code(
344                Some("application/json; charset=utf-8"),
345                br#"{"error":"FUTURE","extra":1}"#
346            ),
347            Some("FUTURE".into())
348        );
349        assert!(tea_error_code(Some("application/json"), br#"{"message":"Not Found"}"#).is_none());
350        assert!(tea_error_code(Some("text/html"), br#"{"error":"OBJECT_UNKNOWN"}"#).is_none());
351    }
352}