1use std::time::Duration;
9
10use serde_json::Value;
11use zeroize::Zeroizing;
12
13use super::CloudError;
14use super::config::normalize_origin;
15use lean_ctx_protocol::cloud::{
16 CLOUD_API_PREFIX, HEADER_IDEMPOTENCY_KEY, HEADER_INSTANCE, HEADER_MIN_ENGINE, HEADER_NAMES,
17 HEADER_PROTOCOL, MAX_BODY_BYTES, NAMES_VAULT, parse_protocol_header,
18};
19
20pub fn user_agent() -> String {
22 format!("lean-ctx/{}", env!("CARGO_PKG_VERSION"))
23}
24
25pub struct CloudClient {
27 origin: String,
28 agent: ureq::Agent,
29 auth: Option<(String, Zeroizing<String>)>,
30 answered_minor: std::sync::atomic::AtomicU16,
33}
34
35pub const PROTOCOL_V2: &str = "2.2";
42
43const PROTOCOL_MAJOR: u16 = 2;
45
46fn incompatible(peer: &str) -> Option<CloudError> {
49 match parse_protocol_header(peer) {
50 Some((PROTOCOL_MAJOR, _)) => None,
51 Some((major, minor)) => Some(CloudError::Protocol(format!(
52 "The Cloud speaks protocol {major}.{minor}; this instance requires Cloud-Protocol \
53 {PROTOCOL_MAJOR}.x: upgrade the Cloud server"
54 ))),
55 None => Some(CloudError::Protocol(format!(
56 "The Cloud sent no valid protocol version; this instance requires Cloud-Protocol \
57 {PROTOCOL_MAJOR}.x"
58 ))),
59 }
60}
61
62#[derive(Debug, Clone, PartialEq)]
64pub struct CloudResponse {
65 pub status: u16,
66 pub body: Value,
68 pub etag: Option<String>,
69}
70
71impl CloudClient {
72 pub fn answered_minor(&self) -> Option<u16> {
75 let minor = self
76 .answered_minor
77 .load(std::sync::atomic::Ordering::Relaxed);
78 (minor != u16::MAX).then_some(minor)
79 }
80
81 pub fn new(origin: &str) -> Result<Self, CloudError> {
82 let origin = normalize_origin(origin)?;
83 let agent: ureq::Agent = ureq::config::Config::builder()
84 .tls_config(lean_ctx::core::http_client::platform_tls_config())
85 .http_status_as_error(false)
86 .max_redirects(0)
87 .timeout_resolve(Some(Duration::from_secs(5)))
88 .timeout_connect(Some(Duration::from_secs(10)))
89 .timeout_recv_response(Some(Duration::from_secs(30)))
90 .build()
91 .into();
92 Ok(Self {
93 origin,
94 agent,
95 auth: None,
96 answered_minor: std::sync::atomic::AtomicU16::new(u16::MAX),
97 })
98 }
99
100 pub fn bounded(origin: &str, total: Duration) -> Result<Self, CloudError> {
104 let origin = normalize_origin(origin)?;
105 let agent: ureq::Agent = ureq::config::Config::builder()
106 .tls_config(lean_ctx::core::http_client::platform_tls_config())
107 .http_status_as_error(false)
108 .max_redirects(0)
109 .timeout_global(Some(total))
110 .build()
111 .into();
112 Ok(Self {
113 origin,
114 agent,
115 auth: None,
116 answered_minor: std::sync::atomic::AtomicU16::new(u16::MAX),
117 })
118 }
119
120 pub fn with_token(mut self, instance_id: &str, access_token: &str) -> Self {
122 self.auth = Some((
123 instance_id.to_string(),
124 Zeroizing::new(access_token.to_string()),
125 ));
126 self
127 }
128
129 pub fn origin(&self) -> &str {
130 &self.origin
131 }
132
133 pub fn get(&self, path: &str) -> Result<Value, CloudError> {
134 Ok(self.send("GET", path, None, &[], MAX_BODY_BYTES)?.body)
135 }
136
137 pub fn post(&self, path: &str, body: &Value) -> Result<Value, CloudError> {
139 let key = uuid::Uuid::new_v4().simple().to_string();
140 self.post_idempotent(path, body, &key)
141 }
142
143 pub fn post_idempotent(
145 &self,
146 path: &str,
147 body: &Value,
148 key: &str,
149 ) -> Result<Value, CloudError> {
150 Ok(self
151 .send(
152 "POST",
153 path,
154 Some(body),
155 &[(HEADER_IDEMPOTENCY_KEY, key)],
156 MAX_BODY_BYTES,
157 )?
158 .body)
159 }
160
161 pub fn delete(&self, path: &str) -> Result<(), CloudError> {
162 self.send("DELETE", path, None, &[], MAX_BODY_BYTES)
163 .map(|_| ())
164 }
165
166 pub fn send(
169 &self,
170 method: &str,
171 path: &str,
172 body: Option<&Value>,
173 extra: &[(&str, &str)],
174 max_body: usize,
175 ) -> Result<CloudResponse, CloudError> {
176 let (status, etag, _, value) = self.exchange(method, path, body, extra, max_body)?;
177 if (200..300).contains(&status) || status == 304 {
178 if (200..300).contains(&status) && status != 204 && value.is_null() {
179 return Err(CloudError::Protocol(format!(
180 "{method} {path}: body is not JSON"
181 )));
182 }
183 return Ok(CloudResponse {
184 status,
185 body: value,
186 etag,
187 });
188 }
189 Err(CloudError::from_response(status, &value))
190 }
191
192 pub fn get_bytes(&self, path: &str, max_body: usize) -> Result<Vec<u8>, CloudError> {
194 let (status, _, bytes, value) = self.exchange("GET", path, None, &[], max_body)?;
195 if (200..300).contains(&status) {
196 return Ok(bytes);
197 }
198 Err(CloudError::from_response(status, &value))
199 }
200
201 pub fn send_answer(
205 &self,
206 method: &str,
207 path: &str,
208 body: Option<&Value>,
209 max_body: usize,
210 ) -> Result<(u16, Value), CloudError> {
211 self.send_answer_with(method, path, body, &[], max_body)
212 }
213
214 pub fn send_answer_with(
218 &self,
219 method: &str,
220 path: &str,
221 body: Option<&Value>,
222 extra: &[(&str, &str)],
223 max_body: usize,
224 ) -> Result<(u16, Value), CloudError> {
225 let (status, _, _, value) = self.exchange(method, path, body, extra, max_body)?;
226 Ok((status, value))
227 }
228
229 pub fn put_bytes_answer(
232 &self,
233 path: &str,
234 bytes: &[u8],
235 max_body: usize,
236 ) -> Result<(u16, Value), CloudError> {
237 let (status, _, _, value) = self.exchange_raw(
238 "PUT",
239 path,
240 Some((bytes, "application/octet-stream")),
241 &[],
242 max_body,
243 )?;
244 Ok((status, value))
245 }
246
247 pub fn send_json_bytes_answer(
252 &self,
253 method: &str,
254 path: &str,
255 body: &[u8],
256 max_body: usize,
257 ) -> Result<(u16, Value), CloudError> {
258 let (status, _, _, value) = self.exchange_raw(
259 method,
260 path,
261 Some((body, "application/json")),
262 &[],
263 max_body,
264 )?;
265 Ok((status, value))
266 }
267
268 pub fn get_bytes_answer(
271 &self,
272 path: &str,
273 max_body: usize,
274 ) -> Result<(u16, Vec<u8>, Value), CloudError> {
275 let (status, _, bytes, value) = self.exchange_raw("GET", path, None, &[], max_body)?;
276 Ok((status, bytes, value))
277 }
278
279 fn exchange(
282 &self,
283 method: &str,
284 path: &str,
285 body: Option<&Value>,
286 extra: &[(&str, &str)],
287 max_body: usize,
288 ) -> Result<(u16, Option<String>, Vec<u8>, Value), CloudError> {
289 let encoded = match (method, body) {
290 ("GET", _) | ("DELETE", None) => None,
291 (_, Some(body)) => Some(
292 serde_json::to_vec(body)
293 .map_err(|e| CloudError::Protocol(format!("encode request: {e}")))?,
294 ),
295 (_, None) => Some(Vec::new()),
296 };
297 self.exchange_raw(
298 method,
299 path,
300 encoded.as_deref().map(|bytes| (bytes, "application/json")),
301 extra,
302 max_body,
303 )
304 }
305
306 fn exchange_raw(
308 &self,
309 method: &str,
310 path: &str,
311 body: Option<(&[u8], &str)>,
312 extra: &[(&str, &str)],
313 max_body: usize,
314 ) -> Result<(u16, Option<String>, Vec<u8>, Value), CloudError> {
315 let url = format!("{}{CLOUD_API_PREFIX}{path}", self.origin);
316 let user_agent = user_agent();
317 let bearer = self
318 .auth
319 .as_ref()
320 .map(|(_, token)| Zeroizing::new(format!("Bearer {}", token.as_str())));
321 let mut headers: Vec<(&str, &str)> = vec![
322 (HEADER_PROTOCOL, PROTOCOL_V2),
323 (HEADER_NAMES, NAMES_VAULT),
324 ("User-Agent", &user_agent),
325 ];
326 if let (Some((instance, _)), Some(bearer)) = (&self.auth, &bearer) {
327 headers.push((HEADER_INSTANCE, instance));
328 headers.push(("Authorization", bearer));
329 }
330 headers.retain(|(name, _)| !extra.iter().any(|(e, _)| e.eq_ignore_ascii_case(name)));
331 headers.extend_from_slice(extra);
332
333 let result = match (method, body) {
334 ("GET", _) => with_headers(self.agent.get(&url), &headers).call(),
335 ("DELETE", None) => with_headers(self.agent.delete(&url), &headers).call(),
336 ("DELETE", Some((bytes, content_type))) => {
339 with_headers(self.agent.delete(&url).force_send_body(), &headers)
340 .header("Content-Type", content_type)
341 .send(bytes)
342 }
343 (_, body) => {
344 let (bytes, content_type) = body.unwrap_or((&[], "application/json"));
345 let request = match method {
346 "PUT" => self.agent.put(&url),
347 "PATCH" => self.agent.patch(&url),
348 _ => self.agent.post(&url),
349 };
350 with_headers(request, &headers)
351 .header("Content-Type", content_type)
352 .send(bytes)
353 }
354 };
355 let response = result.map_err(|e| offline(&e))?;
356 let status = response.status().as_u16();
357 let header = |name: &str| {
358 response
359 .headers()
360 .get(name)
361 .and_then(|v| v.to_str().ok())
362 .map(str::to_string)
363 };
364 let peer_protocol = header(HEADER_PROTOCOL);
365 let min_instance = header(HEADER_MIN_ENGINE);
366 let etag = header("etag");
367 let retry_after = header("retry-after");
368 let bytes = response
369 .into_body()
370 .into_with_config()
371 .limit(max_body as u64)
372 .read_to_vec()
373 .map_err(|e| CloudError::Protocol(format!("response body: {e}")))?;
374 let mut value = if bytes.iter().all(u8::is_ascii_whitespace) {
375 Value::Null
376 } else {
377 serde_json::from_slice(&bytes).unwrap_or(Value::Null)
378 };
379 honour_retry_after(status, retry_after.as_deref(), &mut value);
380 if status == 426 {
381 let min = min_instance
382 .or_else(|| value["error"]["min_instance"].as_str().map(str::to_string));
383 return Err(CloudError::UpgradeRequired { min });
384 }
385 if !answered_by_edge(status)
389 && let Some(refused) = peer_protocol.as_deref().and_then(incompatible)
390 {
391 return Err(refused);
392 }
393 if let Some((PROTOCOL_MAJOR, minor)) =
394 peer_protocol.as_deref().and_then(parse_protocol_header)
395 {
396 self.answered_minor
397 .store(minor, std::sync::atomic::Ordering::Relaxed);
398 }
399 Ok((status, etag, bytes, value))
400 }
401}
402
403fn answered_by_edge(status: u16) -> bool {
406 matches!(status, 413 | 429 | 500..=599)
407}
408
409pub(crate) fn honour_retry_after(status: u16, header: Option<&str>, value: &mut Value) {
414 if !matches!(status, 429 | 503) {
415 return;
416 }
417 let Some(seconds) = header.and_then(|h| h.trim().parse::<u64>().ok()) else {
418 return;
419 };
420 if !value.is_object() {
421 *value = Value::Object(serde_json::Map::new());
422 }
423 if let Some(body) = value.as_object_mut()
424 && !body.get("error").is_some_and(Value::is_object)
425 {
426 body.insert("error".into(), Value::Object(serde_json::Map::new()));
427 }
428 if let Some(error) = value.get_mut("error").and_then(Value::as_object_mut)
429 && !error.contains_key("retry_after_s")
430 {
431 error.insert("retry_after_s".into(), seconds.into());
432 }
433}
434
435#[cfg(test)]
436mod retry_after_tests {
437 use super::*;
438
439 #[test]
440 fn the_retry_after_header_fills_a_missing_retry_after_s() {
441 let mut body = serde_json::json!({"error": {"code": "quota_exceeded", "message": "x"}});
442 honour_retry_after(429, Some(" 120 "), &mut body);
443 assert_eq!(body["error"]["retry_after_s"], 120);
444 honour_retry_after(429, Some("5"), &mut body);
446 assert_eq!(body["error"]["retry_after_s"], 120);
447 let mut other = serde_json::json!({"error": {"code": "not_found", "message": "x"}});
448 honour_retry_after(404, Some("5"), &mut other);
449 honour_retry_after(429, Some("Wed, 21 Oct 2026 07:28:00 GMT"), &mut other);
450 assert!(other["error"].get("retry_after_s").is_none());
451 }
452}
453
454fn with_headers<B>(
455 mut request: ureq::RequestBuilder<B>,
456 headers: &[(&str, &str)],
457) -> ureq::RequestBuilder<B> {
458 for (name, value) in headers {
459 request = request.header(*name, *value);
460 }
461 request
462}
463
464fn offline(error: &ureq::Error) -> CloudError {
465 let kind = match error {
466 ureq::Error::Timeout(_) => "timeout".to_string(),
467 ureq::Error::HostNotFound => "host not found".to_string(),
468 ureq::Error::ConnectionFailed => "connection failed".to_string(),
469 ureq::Error::Io(e) => format!("i/o: {}", e.kind()),
470 ureq::Error::Tls(_) | ureq::Error::Rustls(_) => "tls".to_string(),
471 ureq::Error::TooManyRedirects | ureq::Error::RedirectFailed => {
472 return CloudError::Protocol("The Cloud answered with a redirect".into());
473 }
474 other => other.to_string().chars().take(120).collect(),
475 };
476 CloudError::Offline(kind)
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482
483 #[test]
484 fn clients_refuse_plain_http_to_remote_hosts() {
485 assert!(CloudClient::new("http://cloud.example.com").is_err());
486 assert!(CloudClient::new("https://cloud.example.com").is_ok());
487 assert!(CloudClient::new("http://127.0.0.1:9").is_ok());
488 }
489
490 #[test]
491 fn only_a_2x_answer_is_accepted_and_a_refusal_names_the_protocol() {
492 assert!(incompatible("2.0").is_none());
493 assert!(incompatible("2.7").is_none());
494 for peer in ["1.9", "1.8", "1.0", "3.0", "", "two"] {
495 let Some(CloudError::Protocol(message)) = incompatible(peer) else {
496 panic!("{peer:?} must be refused");
497 };
498 assert!(message.contains("Cloud-Protocol 2.x"), "{message}");
499 }
500 }
501
502 fn answering(raw: String) -> String {
504 use std::io::{BufRead as _, Read as _, Write as _};
505 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
506 let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
507 std::thread::spawn(move || {
508 let Some(Ok(stream)) = listener.incoming().next() else {
509 return;
510 };
511 let mut writer = stream.try_clone().unwrap();
512 let mut reader = std::io::BufReader::new(stream);
513 let mut length = 0usize;
514 loop {
515 let mut line = String::new();
516 if reader.read_line(&mut line).unwrap_or(0) == 0 {
517 return;
518 }
519 let line = line.trim_end();
520 if line.is_empty() {
521 break;
522 }
523 if let Some((name, value)) = line.split_once(':')
524 && name.eq_ignore_ascii_case("content-length")
525 {
526 length = value.trim().parse().unwrap_or(0);
527 }
528 }
529 let mut body = vec![0; length];
530 let _ = reader.read_exact(&mut body);
531 let _ = writer.write_all(raw.as_bytes());
532 });
533 origin
534 }
535
536 fn edge(status: u16, headers: &str, body: &str) -> String {
537 format!(
538 "HTTP/1.1 {status} X\r\nContent-Type: text/html\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
539 body.len()
540 )
541 }
542
543 #[test]
546 fn edge_errors_are_classified_by_status_not_by_protocol_header() {
547 let page = "<html><body>busy</body></html>";
548 let garbled = format!("{HEADER_PROTOCOL}: nginx\r\n");
549 let origin = answering(edge(429, &format!("{garbled}Retry-After: 42\r\n"), page));
550 let limited = CloudClient::new(&origin).unwrap().post("/x", &Value::Null);
551 assert_eq!(
552 limited,
553 Err(CloudError::RateLimited {
554 retry_after: Some(42)
555 })
556 );
557 for status in [502, 503, 504] {
558 let origin = answering(edge(status, &garbled, page));
559 let down = CloudClient::new(&origin).unwrap().get("/keys").unwrap_err();
560 assert!(
561 matches!(down, CloudError::Server { status: s, .. } if s == status),
562 "{status}: {down:?}"
563 );
564 assert!(down.is_transient());
565 }
566 let origin = answering(edge(413, "", page));
567 let too_large = CloudClient::new(&origin).unwrap().post("/x", &Value::Null);
568 assert_eq!(
569 too_large,
570 Err(CloudError::Server {
571 status: 413,
572 code: "payload_too_large".into()
573 })
574 );
575 let origin = answering(format!(
577 "HTTP/1.1 200 OK\r\n{garbled}Content-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
578 ));
579 assert!(matches!(
580 CloudClient::new(&origin).unwrap().get("/keys"),
581 Err(CloudError::Protocol(_))
582 ));
583 }
584
585 #[test]
586 fn a_bare_retry_after_header_becomes_the_error_body() {
587 let mut body = Value::Null;
588 honour_retry_after(429, Some("17"), &mut body);
589 assert_eq!(body, serde_json::json!({"error": {"retry_after_s": 17}}));
590 let mut other = serde_json::json!({"detail": "x"});
591 honour_retry_after(503, Some("3"), &mut other);
592 assert_eq!(
593 other,
594 serde_json::json!({"detail": "x", "error": {"retry_after_s": 3}})
595 );
596 }
597
598 #[test]
599 fn unreachable_cloud_is_offline() {
600 let client = CloudClient::new("http://127.0.0.1:9").unwrap();
601 assert!(matches!(client.get("/keys"), Err(CloudError::Offline(_))));
602 }
603}