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 "LeanCTX Cloud speaks protocol {major}.{minor}; this instance requires Cloud-Protocol \
53 {PROTOCOL_MAJOR}.x: upgrade the LeanCTX Cloud server"
54 ))),
55 None => Some(CloudError::Protocol(format!(
56 "LeanCTX 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 get_bytes_answer(
250 &self,
251 path: &str,
252 max_body: usize,
253 ) -> Result<(u16, Vec<u8>, Value), CloudError> {
254 let (status, _, bytes, value) = self.exchange_raw("GET", path, None, &[], max_body)?;
255 Ok((status, bytes, value))
256 }
257
258 fn exchange(
261 &self,
262 method: &str,
263 path: &str,
264 body: Option<&Value>,
265 extra: &[(&str, &str)],
266 max_body: usize,
267 ) -> Result<(u16, Option<String>, Vec<u8>, Value), CloudError> {
268 let encoded = match (method, body) {
269 ("GET", _) | ("DELETE", None) => None,
270 (_, Some(body)) => Some(
271 serde_json::to_vec(body)
272 .map_err(|e| CloudError::Protocol(format!("encode request: {e}")))?,
273 ),
274 (_, None) => Some(Vec::new()),
275 };
276 self.exchange_raw(
277 method,
278 path,
279 encoded.as_deref().map(|bytes| (bytes, "application/json")),
280 extra,
281 max_body,
282 )
283 }
284
285 fn exchange_raw(
287 &self,
288 method: &str,
289 path: &str,
290 body: Option<(&[u8], &str)>,
291 extra: &[(&str, &str)],
292 max_body: usize,
293 ) -> Result<(u16, Option<String>, Vec<u8>, Value), CloudError> {
294 let url = format!("{}{CLOUD_API_PREFIX}{path}", self.origin);
295 let user_agent = user_agent();
296 let bearer = self
297 .auth
298 .as_ref()
299 .map(|(_, token)| Zeroizing::new(format!("Bearer {}", token.as_str())));
300 let mut headers: Vec<(&str, &str)> = vec![
301 (HEADER_PROTOCOL, PROTOCOL_V2),
302 (HEADER_NAMES, NAMES_VAULT),
303 ("User-Agent", &user_agent),
304 ];
305 if let (Some((instance, _)), Some(bearer)) = (&self.auth, &bearer) {
306 headers.push((HEADER_INSTANCE, instance));
307 headers.push(("Authorization", bearer));
308 }
309 headers.retain(|(name, _)| !extra.iter().any(|(e, _)| e.eq_ignore_ascii_case(name)));
310 headers.extend_from_slice(extra);
311
312 let result = match (method, body) {
313 ("GET", _) => with_headers(self.agent.get(&url), &headers).call(),
314 ("DELETE", None) => with_headers(self.agent.delete(&url), &headers).call(),
315 ("DELETE", Some((bytes, content_type))) => {
318 with_headers(self.agent.delete(&url).force_send_body(), &headers)
319 .header("Content-Type", content_type)
320 .send(bytes)
321 }
322 (_, body) => {
323 let (bytes, content_type) = body.unwrap_or((&[], "application/json"));
324 let request = match method {
325 "PUT" => self.agent.put(&url),
326 "PATCH" => self.agent.patch(&url),
327 _ => self.agent.post(&url),
328 };
329 with_headers(request, &headers)
330 .header("Content-Type", content_type)
331 .send(bytes)
332 }
333 };
334 let response = result.map_err(|e| offline(&e))?;
335 let status = response.status().as_u16();
336 let header = |name: &str| {
337 response
338 .headers()
339 .get(name)
340 .and_then(|v| v.to_str().ok())
341 .map(str::to_string)
342 };
343 let peer_protocol = header(HEADER_PROTOCOL);
344 let min_instance = header(HEADER_MIN_ENGINE);
345 let etag = header("etag");
346 let retry_after = header("retry-after");
347 let bytes = response
348 .into_body()
349 .into_with_config()
350 .limit(max_body as u64)
351 .read_to_vec()
352 .map_err(|e| CloudError::Protocol(format!("response body: {e}")))?;
353 let mut value = if bytes.iter().all(u8::is_ascii_whitespace) {
354 Value::Null
355 } else {
356 serde_json::from_slice(&bytes).unwrap_or(Value::Null)
357 };
358 honour_retry_after(status, retry_after.as_deref(), &mut value);
359 if status == 426 {
360 let min = min_instance
361 .or_else(|| value["error"]["min_instance"].as_str().map(str::to_string));
362 return Err(CloudError::UpgradeRequired { min });
363 }
364 if !answered_by_edge(status)
368 && let Some(refused) = peer_protocol.as_deref().and_then(incompatible)
369 {
370 return Err(refused);
371 }
372 if let Some((PROTOCOL_MAJOR, minor)) =
373 peer_protocol.as_deref().and_then(parse_protocol_header)
374 {
375 self.answered_minor
376 .store(minor, std::sync::atomic::Ordering::Relaxed);
377 }
378 Ok((status, etag, bytes, value))
379 }
380}
381
382fn answered_by_edge(status: u16) -> bool {
385 matches!(status, 413 | 429 | 500..=599)
386}
387
388pub(crate) fn honour_retry_after(status: u16, header: Option<&str>, value: &mut Value) {
393 if !matches!(status, 429 | 503) {
394 return;
395 }
396 let Some(seconds) = header.and_then(|h| h.trim().parse::<u64>().ok()) else {
397 return;
398 };
399 if !value.is_object() {
400 *value = Value::Object(serde_json::Map::new());
401 }
402 if let Some(body) = value.as_object_mut()
403 && !body.get("error").is_some_and(Value::is_object)
404 {
405 body.insert("error".into(), Value::Object(serde_json::Map::new()));
406 }
407 if let Some(error) = value.get_mut("error").and_then(Value::as_object_mut)
408 && !error.contains_key("retry_after_s")
409 {
410 error.insert("retry_after_s".into(), seconds.into());
411 }
412}
413
414#[cfg(test)]
415mod retry_after_tests {
416 use super::*;
417
418 #[test]
419 fn the_retry_after_header_fills_a_missing_retry_after_s() {
420 let mut body = serde_json::json!({"error": {"code": "quota_exceeded", "message": "x"}});
421 honour_retry_after(429, Some(" 120 "), &mut body);
422 assert_eq!(body["error"]["retry_after_s"], 120);
423 honour_retry_after(429, Some("5"), &mut body);
425 assert_eq!(body["error"]["retry_after_s"], 120);
426 let mut other = serde_json::json!({"error": {"code": "not_found", "message": "x"}});
427 honour_retry_after(404, Some("5"), &mut other);
428 honour_retry_after(429, Some("Wed, 21 Oct 2026 07:28:00 GMT"), &mut other);
429 assert!(other["error"].get("retry_after_s").is_none());
430 }
431}
432
433fn with_headers<B>(
434 mut request: ureq::RequestBuilder<B>,
435 headers: &[(&str, &str)],
436) -> ureq::RequestBuilder<B> {
437 for (name, value) in headers {
438 request = request.header(*name, *value);
439 }
440 request
441}
442
443fn offline(error: &ureq::Error) -> CloudError {
444 let kind = match error {
445 ureq::Error::Timeout(_) => "timeout".to_string(),
446 ureq::Error::HostNotFound => "host not found".to_string(),
447 ureq::Error::ConnectionFailed => "connection failed".to_string(),
448 ureq::Error::Io(e) => format!("i/o: {}", e.kind()),
449 ureq::Error::Tls(_) | ureq::Error::Rustls(_) => "tls".to_string(),
450 ureq::Error::TooManyRedirects | ureq::Error::RedirectFailed => {
451 return CloudError::Protocol("LeanCTX Cloud answered with a redirect".into());
452 }
453 other => other.to_string().chars().take(120).collect(),
454 };
455 CloudError::Offline(kind)
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461
462 #[test]
463 fn clients_refuse_plain_http_to_remote_hosts() {
464 assert!(CloudClient::new("http://cloud.example.com").is_err());
465 assert!(CloudClient::new("https://cloud.example.com").is_ok());
466 assert!(CloudClient::new("http://127.0.0.1:9").is_ok());
467 }
468
469 #[test]
470 fn only_a_2x_answer_is_accepted_and_a_refusal_names_the_protocol() {
471 assert!(incompatible("2.0").is_none());
472 assert!(incompatible("2.7").is_none());
473 for peer in ["1.9", "1.8", "1.0", "3.0", "", "two"] {
474 let Some(CloudError::Protocol(message)) = incompatible(peer) else {
475 panic!("{peer:?} must be refused");
476 };
477 assert!(message.contains("Cloud-Protocol 2.x"), "{message}");
478 }
479 }
480
481 fn answering(raw: String) -> String {
483 use std::io::{BufRead as _, Read as _, Write as _};
484 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
485 let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
486 std::thread::spawn(move || {
487 let Some(Ok(stream)) = listener.incoming().next() else {
488 return;
489 };
490 let mut writer = stream.try_clone().unwrap();
491 let mut reader = std::io::BufReader::new(stream);
492 let mut length = 0usize;
493 loop {
494 let mut line = String::new();
495 if reader.read_line(&mut line).unwrap_or(0) == 0 {
496 return;
497 }
498 let line = line.trim_end();
499 if line.is_empty() {
500 break;
501 }
502 if let Some((name, value)) = line.split_once(':')
503 && name.eq_ignore_ascii_case("content-length")
504 {
505 length = value.trim().parse().unwrap_or(0);
506 }
507 }
508 let mut body = vec![0; length];
509 let _ = reader.read_exact(&mut body);
510 let _ = writer.write_all(raw.as_bytes());
511 });
512 origin
513 }
514
515 fn edge(status: u16, headers: &str, body: &str) -> String {
516 format!(
517 "HTTP/1.1 {status} X\r\nContent-Type: text/html\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
518 body.len()
519 )
520 }
521
522 #[test]
525 fn edge_errors_are_classified_by_status_not_by_protocol_header() {
526 let page = "<html><body>busy</body></html>";
527 let garbled = format!("{HEADER_PROTOCOL}: nginx\r\n");
528 let origin = answering(edge(429, &format!("{garbled}Retry-After: 42\r\n"), page));
529 let limited = CloudClient::new(&origin).unwrap().post("/x", &Value::Null);
530 assert_eq!(
531 limited,
532 Err(CloudError::RateLimited {
533 retry_after: Some(42)
534 })
535 );
536 for status in [502, 503, 504] {
537 let origin = answering(edge(status, &garbled, page));
538 let down = CloudClient::new(&origin).unwrap().get("/keys").unwrap_err();
539 assert!(
540 matches!(down, CloudError::Server { status: s, .. } if s == status),
541 "{status}: {down:?}"
542 );
543 assert!(down.is_transient());
544 }
545 let origin = answering(edge(413, "", page));
546 let too_large = CloudClient::new(&origin).unwrap().post("/x", &Value::Null);
547 assert_eq!(
548 too_large,
549 Err(CloudError::Server {
550 status: 413,
551 code: "payload_too_large".into()
552 })
553 );
554 let origin = answering(format!(
556 "HTTP/1.1 200 OK\r\n{garbled}Content-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
557 ));
558 assert!(matches!(
559 CloudClient::new(&origin).unwrap().get("/keys"),
560 Err(CloudError::Protocol(_))
561 ));
562 }
563
564 #[test]
565 fn a_bare_retry_after_header_becomes_the_error_body() {
566 let mut body = Value::Null;
567 honour_retry_after(429, Some("17"), &mut body);
568 assert_eq!(body, serde_json::json!({"error": {"retry_after_s": 17}}));
569 let mut other = serde_json::json!({"detail": "x"});
570 honour_retry_after(503, Some("3"), &mut other);
571 assert_eq!(
572 other,
573 serde_json::json!({"detail": "x", "error": {"retry_after_s": 3}})
574 );
575 }
576
577 #[test]
578 fn unreachable_cloud_is_offline() {
579 let client = CloudClient::new("http://127.0.0.1:9").unwrap();
580 assert!(matches!(client.get("/keys"), Err(CloudError::Offline(_))));
581 }
582}