1use 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#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct WellKnownDocument {
21 endpoints: Vec<WellKnownEndpoint>,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct WellKnownEndpoint {
28 pub url: String,
30 pub versions: Vec<ApiVersion>,
32 pub priority: OrderedPriority,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct DiscoveryInfo {
40 pub product_release: ProductReleaseId,
42 pub servers: Vec<DiscoveryServer>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct DiscoveryServer {
50 pub root_url: String,
52 pub versions: Vec<ApiVersion>,
54 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 pub fn parse(bytes: &[u8]) -> Result<Self, ModelError> {
96 Self::parse_with(bytes, false)
97 }
98
99 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 #[must_use]
130 pub fn endpoints(&self) -> &[WellKnownEndpoint] {
131 &self.endpoints
132 }
133
134 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 pub fn parse_list(bytes: &[u8]) -> Result<Vec<Self>, ModelError> {
163 Self::parse_list_with(bytes, false)
164 }
165
166 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 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#[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#[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
294pub 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}