1use std::cmp::Ordering;
8use std::fmt;
9
10use semver::Version;
11use serde::{Deserialize, Serialize};
12
13use crate::error::ModelError;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ApiVersion {
18 raw: String,
19 parsed: Version,
20}
21
22impl ApiVersion {
23 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 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 #[must_use]
81 pub fn as_str(&self) -> &str {
82 &self.raw
83 }
84
85 #[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#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct SupportedApi {
101 versions: Vec<Version>,
102 lenient: bool,
103}
104
105impl SupportedApi {
106 #[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 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 #[must_use]
153 pub fn with_lenient(mut self, lenient: bool) -> Self {
154 self.lenient = lenient;
155 self
156 }
157
158 #[must_use]
160 pub fn is_lenient(&self) -> bool {
161 self.lenient
162 }
163
164 #[must_use]
170 pub fn supports(&self, advertised: &Version) -> bool {
171 self.classify(advertised).is_some()
172 }
173
174 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
209#[non_exhaustive]
210pub struct SelectedEndpoint {
211 pub root_url: String,
213 pub version: String,
215 pub priority: OrderedPriority,
217 pub source_index: usize,
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
223pub struct OrderedPriority(u64);
224
225impl OrderedPriority {
226 #[must_use]
228 pub fn default_priority() -> Self {
229 Self(1.0_f64.to_bits())
230 }
231
232 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 #[must_use]
248 pub fn get(self) -> f64 {
249 f64::from_bits(self.0)
250 }
251}
252
253#[derive(Debug, Clone, PartialEq)]
255#[non_exhaustive]
256pub struct VersionedEndpoint {
257 pub root_url: String,
259 pub versions: Vec<ApiVersion>,
261 pub priority: OrderedPriority,
263}
264
265impl VersionedEndpoint {
266 #[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
281pub 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 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
333fn 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
359pub 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}