Skip to main content

libtea_core/
version.rs

1//! TEA API version selection.
2//!
3//! Advertised versions are SemVer 2.0.0. Build metadata does not affect
4//! precedence or whether a client supports a version. The selected path uses
5//! the advertised spelling exactly, including build metadata.
6
7use std::cmp::Ordering;
8use std::fmt;
9
10use semver::Version;
11use serde::{Deserialize, Serialize};
12
13use crate::error::ModelError;
14
15/// One advertised API version, preserving the wire spelling.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ApiVersion {
18    raw: String,
19    parsed: Version,
20}
21
22impl ApiVersion {
23    /// Parse a SemVer 2.0.0 version string.
24    ///
25    /// # Errors
26    ///
27    /// Returns an error when the text is not SemVer 2.0.0.
28    pub fn parse(text: &str) -> Result<Self, ModelError> {
29        let parsed = Version::parse(text).map_err(|err| {
30            ModelError::Invalid(format!("API version `{text}` is not SemVer 2.0.0: {err}"))
31        })?;
32        Ok(Self {
33            raw: text.to_owned(),
34            parsed,
35        })
36    }
37
38    /// Parse a SemVer version, or a short `MAJOR` / `MAJOR.MINOR` form.
39    ///
40    /// `1` is read as `1.0.0` and `1.2` as `1.2.0` for comparison. The
41    /// advertised spelling is kept for [`Self::as_str`], so the request path
42    /// stays `/v1/` for a server that advertised `1`. Used only when the
43    /// client is configured with lenient versions; see
44    /// [`SupportedApi::with_lenient`].
45    ///
46    /// # Errors
47    ///
48    /// Returns an error when the text is neither SemVer 2.0.0 nor a short
49    /// numeric form without leading zeros.
50    pub fn parse_lenient(text: &str) -> Result<Self, ModelError> {
51        if let Ok(strict) = Self::parse(text) {
52            return Ok(strict);
53        }
54        let short = |part: &str| -> Option<u64> {
55            let digits = !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
56            let canonical = part == "0" || !part.starts_with('0');
57            (digits && canonical).then(|| part.parse().ok()).flatten()
58        };
59        let mut parts = text.split('.');
60        let parsed = match (parts.next(), parts.next(), parts.next()) {
61            (Some(major), None, None) => short(major).map(|m| Version::new(m, 0, 0)),
62            (Some(major), Some(minor), None) => short(major)
63                .zip(short(minor))
64                .map(|(m, n)| Version::new(m, n, 0)),
65            _ => None,
66        };
67        parsed
68            .map(|parsed| Self {
69                raw: text.to_owned(),
70                parsed,
71            })
72            .ok_or_else(|| {
73                ModelError::Invalid(format!(
74                    "API version `{text}` is neither SemVer 2.0.0 nor MAJOR[.MINOR]"
75                ))
76            })
77    }
78
79    /// Advertised spelling, used after `/v` in the path.
80    #[must_use]
81    pub fn as_str(&self) -> &str {
82        &self.raw
83    }
84
85    /// Parsed version. Comparison ignores build metadata.
86    #[must_use]
87    pub fn semver(&self) -> &Version {
88        &self.parsed
89    }
90}
91
92impl fmt::Display for ApiVersion {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str(&self.raw)
95    }
96}
97
98/// A version the client implements.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct SupportedApi {
101    versions: Vec<Version>,
102    lenient: bool,
103}
104
105impl SupportedApi {
106    /// Support the pinned TEA 1.0.0 contract.
107    #[must_use]
108    pub fn tea_1_0_0() -> Self {
109        Self {
110            versions: vec![Version::new(1, 0, 0)],
111            lenient: false,
112        }
113    }
114
115    /// Replace the supported set.
116    ///
117    /// # Errors
118    ///
119    /// Returns an error when a string is not SemVer 2.0.0.
120    pub fn from_versions<I, S>(values: I) -> Result<Self, ModelError>
121    where
122        I: IntoIterator<Item = S>,
123        S: AsRef<str>,
124    {
125        let mut versions = Vec::new();
126        for value in values {
127            versions.push(ApiVersion::parse(value.as_ref())?.parsed);
128        }
129        if versions.is_empty() {
130            return Err(ModelError::Invalid(
131                "at least one supported API version is required".into(),
132            ));
133        }
134        Ok(Self {
135            versions,
136            lenient: false,
137        })
138    }
139
140    /// Accept any advertised *stable* version with the same major as a
141    /// supported one.
142    ///
143    /// Off by default (exact precedence match). When on, `1.0.1` and `1.1.0`
144    /// are selected for a client that supports `1.0.0` (a pre-release such as
145    /// `1.1.0-rc.1` is not), exact matches sort before same-major ones in
146    /// [`select_endpoints`], and callers should
147    /// parse documents with [`ApiVersion::parse_lenient`] so short forms such
148    /// as `1` are accepted. **Risk:** the models were checked against the
149    /// pinned 1.0.0 schemas only; a compatible-looking server may send
150    /// responses this client cannot read or reads wrongly. Major version `0`
151    /// is never matched by major alone.
152    #[must_use]
153    pub fn with_lenient(mut self, lenient: bool) -> Self {
154        self.lenient = lenient;
155        self
156    }
157
158    /// Whether lenient version matching is on.
159    #[must_use]
160    pub fn is_lenient(&self) -> bool {
161        self.lenient
162    }
163
164    /// Whether an advertised version is implemented.
165    ///
166    /// SemVer build metadata is ignored. Prerelease identifiers are not. In
167    /// lenient mode a *stable* version with the same major as a supported one
168    /// is also accepted; a pre-release is accepted only on an exact match.
169    #[must_use]
170    pub fn supports(&self, advertised: &Version) -> bool {
171        self.classify(advertised).is_some()
172    }
173
174    /// How an advertised version matches: exactly, or (lenient mode only) as
175    /// a stable version of a supported major.
176    fn classify(&self, advertised: &Version) -> Option<MatchKind> {
177        if self
178            .versions
179            .iter()
180            .any(|supported| supported.cmp_precedence(advertised) == Ordering::Equal)
181        {
182            return Some(MatchKind::Exact);
183        }
184        (self.lenient
185            && advertised.pre.is_empty()
186            && self
187                .versions
188                .iter()
189                .any(|supported| supported.major >= 1 && supported.major == advertised.major))
190        .then_some(MatchKind::SameMajor)
191    }
192}
193
194/// How an advertised version relates to the supported set. `Exact` sorts first.
195#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
196enum MatchKind {
197    Exact,
198    SameMajor,
199}
200
201impl Default for SupportedApi {
202    fn default() -> Self {
203        Self::tea_1_0_0()
204    }
205}
206
207/// Chosen endpoint after version negotiation.
208#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
209#[non_exhaustive]
210pub struct SelectedEndpoint {
211    /// Absolute API root without a version prefix and without a trailing slash.
212    pub root_url: String,
213    /// Exact advertised version string to place after `/v`.
214    pub version: String,
215    /// Priority used for ordering. Omitted priorities are already replaced with `1`.
216    pub priority: OrderedPriority,
217    /// Index of the endpoint in the document before sorting.
218    pub source_index: usize,
219}
220
221/// Finite priority in the closed range 0..=1, stored as bits so it can be ordered.
222#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
223pub struct OrderedPriority(u64);
224
225impl OrderedPriority {
226    /// Treat an omitted priority as `1`.
227    #[must_use]
228    pub fn default_priority() -> Self {
229        Self(1.0_f64.to_bits())
230    }
231
232    /// Validate a priority.
233    ///
234    /// # Errors
235    ///
236    /// Returns an error when the value is non-finite or outside 0..=1.
237    pub fn parse(value: f64) -> Result<Self, ModelError> {
238        if !value.is_finite() || !(0.0..=1.0).contains(&value) {
239            return Err(ModelError::Invalid(
240                "priority must be a finite number from 0 to 1".into(),
241            ));
242        }
243        Ok(Self(value.to_bits()))
244    }
245
246    /// Numeric priority.
247    #[must_use]
248    pub fn get(self) -> f64 {
249        f64::from_bits(self.0)
250    }
251}
252
253/// One candidate API base before selection.
254#[derive(Debug, Clone, PartialEq)]
255#[non_exhaustive]
256pub struct VersionedEndpoint {
257    /// API root as advertised.
258    pub root_url: String,
259    /// Advertised versions, in document order.
260    pub versions: Vec<ApiVersion>,
261    /// Effective priority.
262    pub priority: OrderedPriority,
263}
264
265impl VersionedEndpoint {
266    /// Build a candidate endpoint.
267    #[must_use]
268    pub fn new(
269        root_url: impl Into<String>,
270        versions: Vec<ApiVersion>,
271        priority: OrderedPriority,
272    ) -> Self {
273        Self {
274            root_url: root_url.into(),
275            versions,
276            priority,
277        }
278    }
279}
280
281/// Select candidate endpoints in the order a client should try them.
282///
283/// The order is the highest mutually supported SemVer precedence, then the
284/// highest priority, then the original document index. Within one endpoint,
285/// tied build-metadata spellings keep the first advertised string.
286///
287/// # Errors
288///
289/// Returns an error when no endpoint advertises a supported version.
290pub fn select_endpoints(
291    endpoints: &[VersionedEndpoint],
292    supported: &SupportedApi,
293) -> Result<Vec<SelectedEndpoint>, ModelError> {
294    let mut selected = Vec::new();
295    for (source_index, endpoint) in endpoints.iter().enumerate() {
296        let Some(best) = highest_supported(&endpoint.versions, supported) else {
297            continue;
298        };
299        selected.push((
300            SelectedEndpoint {
301                root_url: endpoint.root_url.clone(),
302                version: best.0.as_str().to_owned(),
303                priority: endpoint.priority,
304                source_index,
305            },
306            best.1,
307            best.0.semver().clone(),
308        ));
309    }
310    if selected.is_empty() {
311        return Err(ModelError::Invalid(
312            "no endpoint advertises an API version this client supports".into(),
313        ));
314    }
315    // Exact matches first, then (lenient mode only) same-major stable versions.
316    // Within a class: highest version, then priority, then document order. In
317    // strict mode every candidate is `Exact`, so the order is unchanged.
318    selected.sort_by(
319        |(left, left_kind, left_version), (right, right_kind, right_version)| {
320            left_kind
321                .cmp(right_kind)
322                .then_with(|| right_version.cmp_precedence(left_version))
323                .then_with(|| right.priority.get().total_cmp(&left.priority.get()))
324                .then_with(|| left.source_index.cmp(&right.source_index))
325        },
326    );
327    Ok(selected
328        .into_iter()
329        .map(|(endpoint, _, _)| endpoint)
330        .collect())
331}
332
333/// The best advertised version of one endpoint: an exact match beats any
334/// same-major version; within a kind the highest precedence wins.
335fn highest_supported<'a>(
336    versions: &'a [ApiVersion],
337    supported: &SupportedApi,
338) -> Option<(&'a ApiVersion, MatchKind)> {
339    let mut best: Option<(&ApiVersion, MatchKind)> = None;
340    for version in versions {
341        let Some(kind) = supported.classify(version.semver()) else {
342            continue;
343        };
344        let replace = match best {
345            None => true,
346            Some((current, current_kind)) => {
347                kind < current_kind
348                    || (kind == current_kind
349                        && version.semver().cmp_precedence(current.semver()) == Ordering::Greater)
350            }
351        };
352        if replace {
353            best = Some((version, kind));
354        }
355    }
356    best
357}
358
359/// Build `{root}/v{version}/` without encoding `+` in build metadata.
360///
361/// # Errors
362///
363/// Returns an error when `root` is not an absolute base URL or the version is empty.
364pub fn versioned_api_prefix(root: &str, version: &str) -> Result<String, ModelError> {
365    let root = root.trim_end_matches('/');
366    if version.is_empty() || version.contains('/') {
367        return Err(ModelError::Invalid(
368            "API version path segment is empty".into(),
369        ));
370    }
371    let prefix = format!("{root}/v{version}/");
372    let parsed = url::Url::parse(&prefix)
373        .map_err(|err| ModelError::Invalid(format!("versioned API URL is invalid: {err}")))?;
374    if parsed.path().contains("%2B") || parsed.path().contains("%2b") {
375        return Err(ModelError::Invalid(
376            "build metadata `+` must remain unencoded in the version path".into(),
377        ));
378    }
379    Ok(prefix)
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    fn endpoint(url: &str, versions: &[&str], priority: f64) -> VersionedEndpoint {
387        VersionedEndpoint {
388            root_url: url.into(),
389            versions: versions
390                .iter()
391                .map(|v| ApiVersion::parse(v).unwrap())
392                .collect(),
393            priority: OrderedPriority::parse(priority).unwrap(),
394        }
395    }
396
397    #[test]
398    fn prefers_higher_version_over_priority() {
399        let supported = SupportedApi::from_versions(["1.0.0", "1.1.0"]).unwrap();
400        let endpoints = vec![
401            endpoint("https://low.example", &["1.0.0"], 1.0),
402            endpoint("https://high.example", &["1.1.0"], 0.1),
403        ];
404        let selected = select_endpoints(&endpoints, &supported).unwrap();
405        assert_eq!(selected[0].root_url, "https://high.example");
406    }
407
408    #[test]
409    fn uses_priority_when_versions_match_and_defaults_omitted_priority() {
410        let supported = SupportedApi::tea_1_0_0();
411        let endpoints = vec![
412            endpoint("https://api2.example.com/mytea", &["1.0.0"], 0.5),
413            endpoint("https://api.example.com", &["1.0.0"], 1.0),
414        ];
415        let selected = select_endpoints(&endpoints, &supported).unwrap();
416        assert_eq!(selected[0].root_url, "https://api.example.com");
417        assert_eq!(selected[0].version, "1.0.0");
418    }
419
420    #[test]
421    fn keeps_build_metadata_spelling() {
422        let supported = SupportedApi::tea_1_0_0();
423        let endpoints = vec![endpoint(
424            "https://api.example.com",
425            &["1.0.0+build.5", "1.0.0+other"],
426            1.0,
427        )];
428        let selected = select_endpoints(&endpoints, &supported).unwrap();
429        assert_eq!(selected[0].version, "1.0.0+build.5");
430        let prefix = versioned_api_prefix(&selected[0].root_url, &selected[0].version).unwrap();
431        assert_eq!(prefix, "https://api.example.com/v1.0.0+build.5/");
432    }
433
434    #[test]
435    fn prerelease_is_not_the_stable_version() {
436        let supported = SupportedApi::tea_1_0_0();
437        let endpoints = vec![endpoint("https://api.example.com", &["1.0.0-rc.1"], 1.0)];
438        assert!(select_endpoints(&endpoints, &supported).is_err());
439    }
440
441    #[test]
442    fn absent_priority_beats_lower_explicit_priority() {
443        let supported = SupportedApi::tea_1_0_0();
444        let mut lower = endpoint("https://b.example", &["1.0.0"], 0.5);
445        let mut higher = endpoint("https://a.example", &["1.0.0"], 0.0);
446        higher.priority = OrderedPriority::default_priority();
447        lower.priority = OrderedPriority::parse(0.5).unwrap();
448        let selected = select_endpoints(&[lower, higher], &supported).unwrap();
449        assert_eq!(selected[0].root_url, "https://a.example");
450    }
451}