libtea-core 0.1.8

Independent Rust types and protocol rules for the CycloneDX Transparency Exchange API. No network I/O.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! TEA API version selection.
//!
//! Advertised versions are SemVer 2.0.0. Build metadata does not affect
//! precedence or whether a client supports a version. The selected path uses
//! the advertised spelling exactly, including build metadata.

use std::cmp::Ordering;
use std::fmt;

use semver::Version;
use serde::{Deserialize, Serialize};

use crate::error::ModelError;

/// One advertised API version, preserving the wire spelling.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiVersion {
    raw: String,
    parsed: Version,
}

impl ApiVersion {
    /// Parse a SemVer 2.0.0 version string.
    ///
    /// # Errors
    ///
    /// Returns an error when the text is not SemVer 2.0.0.
    pub fn parse(text: &str) -> Result<Self, ModelError> {
        let parsed = Version::parse(text).map_err(|err| {
            ModelError::Invalid(format!("API version `{text}` is not SemVer 2.0.0: {err}"))
        })?;
        Ok(Self {
            raw: text.to_owned(),
            parsed,
        })
    }

    /// Parse a SemVer version, or a short `MAJOR` / `MAJOR.MINOR` form.
    ///
    /// `1` is read as `1.0.0` and `1.2` as `1.2.0` for comparison. The
    /// advertised spelling is kept for [`Self::as_str`], so the request path
    /// stays `/v1/` for a server that advertised `1`. Used only when the
    /// client is configured with lenient versions; see
    /// [`SupportedApi::with_lenient`].
    ///
    /// # Errors
    ///
    /// Returns an error when the text is neither SemVer 2.0.0 nor a short
    /// numeric form without leading zeros.
    pub fn parse_lenient(text: &str) -> Result<Self, ModelError> {
        if let Ok(strict) = Self::parse(text) {
            return Ok(strict);
        }
        let short = |part: &str| -> Option<u64> {
            let digits = !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
            let canonical = part == "0" || !part.starts_with('0');
            (digits && canonical).then(|| part.parse().ok()).flatten()
        };
        let mut parts = text.split('.');
        let parsed = match (parts.next(), parts.next(), parts.next()) {
            (Some(major), None, None) => short(major).map(|m| Version::new(m, 0, 0)),
            (Some(major), Some(minor), None) => short(major)
                .zip(short(minor))
                .map(|(m, n)| Version::new(m, n, 0)),
            _ => None,
        };
        parsed
            .map(|parsed| Self {
                raw: text.to_owned(),
                parsed,
            })
            .ok_or_else(|| {
                ModelError::Invalid(format!(
                    "API version `{text}` is neither SemVer 2.0.0 nor MAJOR[.MINOR]"
                ))
            })
    }

    /// Advertised spelling, used after `/v` in the path.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.raw
    }

    /// Parsed version. Comparison ignores build metadata.
    #[must_use]
    pub fn semver(&self) -> &Version {
        &self.parsed
    }
}

impl fmt::Display for ApiVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.raw)
    }
}

/// A version the client implements.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SupportedApi {
    versions: Vec<Version>,
    lenient: bool,
}

impl SupportedApi {
    /// Support the pinned TEA 1.0.0 contract.
    #[must_use]
    pub fn tea_1_0_0() -> Self {
        Self {
            versions: vec![Version::new(1, 0, 0)],
            lenient: false,
        }
    }

    /// Replace the supported set.
    ///
    /// # Errors
    ///
    /// Returns an error when a string is not SemVer 2.0.0.
    pub fn from_versions<I, S>(values: I) -> Result<Self, ModelError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut versions = Vec::new();
        for value in values {
            versions.push(ApiVersion::parse(value.as_ref())?.parsed);
        }
        if versions.is_empty() {
            return Err(ModelError::Invalid(
                "at least one supported API version is required".into(),
            ));
        }
        Ok(Self {
            versions,
            lenient: false,
        })
    }

    /// Accept any advertised *stable* version with the same major as a
    /// supported one.
    ///
    /// Off by default (exact precedence match). When on, `1.0.1` and `1.1.0`
    /// are selected for a client that supports `1.0.0` (a pre-release such as
    /// `1.1.0-rc.1` is not), exact matches sort before same-major ones in
    /// [`select_endpoints`], and callers should
    /// parse documents with [`ApiVersion::parse_lenient`] so short forms such
    /// as `1` are accepted. **Risk:** the models were checked against the
    /// pinned 1.0.0 schemas only; a compatible-looking server may send
    /// responses this client cannot read or reads wrongly. Major version `0`
    /// is never matched by major alone.
    #[must_use]
    pub fn with_lenient(mut self, lenient: bool) -> Self {
        self.lenient = lenient;
        self
    }

    /// Whether lenient version matching is on.
    #[must_use]
    pub fn is_lenient(&self) -> bool {
        self.lenient
    }

    /// Whether an advertised version is implemented.
    ///
    /// SemVer build metadata is ignored. Prerelease identifiers are not. In
    /// lenient mode a *stable* version with the same major as a supported one
    /// is also accepted; a pre-release is accepted only on an exact match.
    #[must_use]
    pub fn supports(&self, advertised: &Version) -> bool {
        self.classify(advertised).is_some()
    }

    /// How an advertised version matches: exactly, or (lenient mode only) as
    /// a stable version of a supported major.
    fn classify(&self, advertised: &Version) -> Option<MatchKind> {
        if self
            .versions
            .iter()
            .any(|supported| supported.cmp_precedence(advertised) == Ordering::Equal)
        {
            return Some(MatchKind::Exact);
        }
        (self.lenient
            && advertised.pre.is_empty()
            && self
                .versions
                .iter()
                .any(|supported| supported.major >= 1 && supported.major == advertised.major))
        .then_some(MatchKind::SameMajor)
    }
}

/// How an advertised version relates to the supported set. `Exact` sorts first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum MatchKind {
    Exact,
    SameMajor,
}

impl Default for SupportedApi {
    fn default() -> Self {
        Self::tea_1_0_0()
    }
}

/// Chosen endpoint after version negotiation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SelectedEndpoint {
    /// Absolute API root without a version prefix and without a trailing slash.
    pub root_url: String,
    /// Exact advertised version string to place after `/v`.
    pub version: String,
    /// Priority used for ordering. Omitted priorities are already replaced with `1`.
    pub priority: OrderedPriority,
    /// Index of the endpoint in the document before sorting.
    pub source_index: usize,
}

/// Finite priority in the closed range 0..=1, stored as bits so it can be ordered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrderedPriority(u64);

impl OrderedPriority {
    /// Treat an omitted priority as `1`.
    #[must_use]
    pub fn default_priority() -> Self {
        Self(1.0_f64.to_bits())
    }

    /// Validate a priority.
    ///
    /// # Errors
    ///
    /// Returns an error when the value is non-finite or outside 0..=1.
    pub fn parse(value: f64) -> Result<Self, ModelError> {
        if !value.is_finite() || !(0.0..=1.0).contains(&value) {
            return Err(ModelError::Invalid(
                "priority must be a finite number from 0 to 1".into(),
            ));
        }
        Ok(Self(value.to_bits()))
    }

    /// Numeric priority.
    #[must_use]
    pub fn get(self) -> f64 {
        f64::from_bits(self.0)
    }
}

/// One candidate API base before selection.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct VersionedEndpoint {
    /// API root as advertised.
    pub root_url: String,
    /// Advertised versions, in document order.
    pub versions: Vec<ApiVersion>,
    /// Effective priority.
    pub priority: OrderedPriority,
}

impl VersionedEndpoint {
    /// Build a candidate endpoint.
    #[must_use]
    pub fn new(
        root_url: impl Into<String>,
        versions: Vec<ApiVersion>,
        priority: OrderedPriority,
    ) -> Self {
        Self {
            root_url: root_url.into(),
            versions,
            priority,
        }
    }
}

/// Select candidate endpoints in the order a client should try them.
///
/// The order is the highest mutually supported SemVer precedence, then the
/// highest priority, then the original document index. Within one endpoint,
/// tied build-metadata spellings keep the first advertised string.
///
/// # Errors
///
/// Returns an error when no endpoint advertises a supported version.
pub fn select_endpoints(
    endpoints: &[VersionedEndpoint],
    supported: &SupportedApi,
) -> Result<Vec<SelectedEndpoint>, ModelError> {
    let mut selected = Vec::new();
    for (source_index, endpoint) in endpoints.iter().enumerate() {
        let Some(best) = highest_supported(&endpoint.versions, supported) else {
            continue;
        };
        selected.push((
            SelectedEndpoint {
                root_url: endpoint.root_url.clone(),
                version: best.0.as_str().to_owned(),
                priority: endpoint.priority,
                source_index,
            },
            best.1,
            best.0.semver().clone(),
        ));
    }
    if selected.is_empty() {
        return Err(ModelError::Invalid(
            "no endpoint advertises an API version this client supports".into(),
        ));
    }
    // Exact matches first, then (lenient mode only) same-major stable versions.
    // Within a class: highest version, then priority, then document order. In
    // strict mode every candidate is `Exact`, so the order is unchanged.
    selected.sort_by(
        |(left, left_kind, left_version), (right, right_kind, right_version)| {
            left_kind
                .cmp(right_kind)
                .then_with(|| right_version.cmp_precedence(left_version))
                .then_with(|| right.priority.get().total_cmp(&left.priority.get()))
                .then_with(|| left.source_index.cmp(&right.source_index))
        },
    );
    Ok(selected
        .into_iter()
        .map(|(endpoint, _, _)| endpoint)
        .collect())
}

/// The best advertised version of one endpoint: an exact match beats any
/// same-major version; within a kind the highest precedence wins.
fn highest_supported<'a>(
    versions: &'a [ApiVersion],
    supported: &SupportedApi,
) -> Option<(&'a ApiVersion, MatchKind)> {
    let mut best: Option<(&ApiVersion, MatchKind)> = None;
    for version in versions {
        let Some(kind) = supported.classify(version.semver()) else {
            continue;
        };
        let replace = match best {
            None => true,
            Some((current, current_kind)) => {
                kind < current_kind
                    || (kind == current_kind
                        && version.semver().cmp_precedence(current.semver()) == Ordering::Greater)
            }
        };
        if replace {
            best = Some((version, kind));
        }
    }
    best
}

/// Build `{root}/v{version}/` without encoding `+` in build metadata.
///
/// # Errors
///
/// Returns an error when `root` is not an absolute base URL or the version is empty.
pub fn versioned_api_prefix(root: &str, version: &str) -> Result<String, ModelError> {
    let root = root.trim_end_matches('/');
    if version.is_empty() || version.contains('/') {
        return Err(ModelError::Invalid(
            "API version path segment is empty".into(),
        ));
    }
    let prefix = format!("{root}/v{version}/");
    let parsed = url::Url::parse(&prefix)
        .map_err(|err| ModelError::Invalid(format!("versioned API URL is invalid: {err}")))?;
    if parsed.path().contains("%2B") || parsed.path().contains("%2b") {
        return Err(ModelError::Invalid(
            "build metadata `+` must remain unencoded in the version path".into(),
        ));
    }
    Ok(prefix)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn endpoint(url: &str, versions: &[&str], priority: f64) -> VersionedEndpoint {
        VersionedEndpoint {
            root_url: url.into(),
            versions: versions
                .iter()
                .map(|v| ApiVersion::parse(v).unwrap())
                .collect(),
            priority: OrderedPriority::parse(priority).unwrap(),
        }
    }

    #[test]
    fn prefers_higher_version_over_priority() {
        let supported = SupportedApi::from_versions(["1.0.0", "1.1.0"]).unwrap();
        let endpoints = vec![
            endpoint("https://low.example", &["1.0.0"], 1.0),
            endpoint("https://high.example", &["1.1.0"], 0.1),
        ];
        let selected = select_endpoints(&endpoints, &supported).unwrap();
        assert_eq!(selected[0].root_url, "https://high.example");
    }

    #[test]
    fn uses_priority_when_versions_match_and_defaults_omitted_priority() {
        let supported = SupportedApi::tea_1_0_0();
        let endpoints = vec![
            endpoint("https://api2.example.com/mytea", &["1.0.0"], 0.5),
            endpoint("https://api.example.com", &["1.0.0"], 1.0),
        ];
        let selected = select_endpoints(&endpoints, &supported).unwrap();
        assert_eq!(selected[0].root_url, "https://api.example.com");
        assert_eq!(selected[0].version, "1.0.0");
    }

    #[test]
    fn keeps_build_metadata_spelling() {
        let supported = SupportedApi::tea_1_0_0();
        let endpoints = vec![endpoint(
            "https://api.example.com",
            &["1.0.0+build.5", "1.0.0+other"],
            1.0,
        )];
        let selected = select_endpoints(&endpoints, &supported).unwrap();
        assert_eq!(selected[0].version, "1.0.0+build.5");
        let prefix = versioned_api_prefix(&selected[0].root_url, &selected[0].version).unwrap();
        assert_eq!(prefix, "https://api.example.com/v1.0.0+build.5/");
    }

    #[test]
    fn prerelease_is_not_the_stable_version() {
        let supported = SupportedApi::tea_1_0_0();
        let endpoints = vec![endpoint("https://api.example.com", &["1.0.0-rc.1"], 1.0)];
        assert!(select_endpoints(&endpoints, &supported).is_err());
    }

    #[test]
    fn absent_priority_beats_lower_explicit_priority() {
        let supported = SupportedApi::tea_1_0_0();
        let mut lower = endpoint("https://b.example", &["1.0.0"], 0.5);
        let mut higher = endpoint("https://a.example", &["1.0.0"], 0.0);
        higher.priority = OrderedPriority::default_priority();
        lower.priority = OrderedPriority::parse(0.5).unwrap();
        let selected = select_endpoints(&[lower, higher], &supported).unwrap();
        assert_eq!(selected[0].root_url, "https://a.example");
    }
}