1use std::collections::{BTreeMap, BTreeSet, HashMap};
23use std::sync::{Arc, Mutex};
24use std::time::{Duration, Instant};
25
26use datumesh_core::json::{self, Value};
27use datumesh_core::{
28 check_answer, check_batch, check_slice_answer, format_reference, keys_from_response, lexical, parse_reference,
29 resolve_mesh, Answer, Batch, ErrorCode, ForeignDetail, FunctionDescriptor, KeyDoc, Keys, Manifest, MeshDoc,
30 Receipt, Reference, Request, Retrieval, Slice, SliceRequest,
31};
32
33use crate::foreign::KeyCache;
34
35const MAX_BODY: u64 = 64 << 20;
37const MAX_DOC: u64 = 256 << 10;
39
40#[derive(Clone, Debug)]
42pub struct ClientError {
43 pub code: ErrorCode,
47 pub detail: String,
49}
50
51impl ClientError {
52 pub(crate) fn new(code: ErrorCode, detail: impl Into<String>) -> ClientError {
53 ClientError { code, detail: detail.into() }
54 }
55 pub(crate) fn unavailable(detail: impl Into<String>) -> ClientError {
56 ClientError::new(ErrorCode::InputUnavailable, detail)
57 }
58
59 pub(crate) fn foreign(detail: ForeignDetail, why: impl std::fmt::Display) -> ClientError {
62 ClientError::new(ErrorCode::ForeignUnavailable, format!("{}: {why}", detail.as_str()))
63 }
64
65 pub fn foreign_detail(&self) -> Option<ForeignDetail> {
69 if self.code != ErrorCode::ForeignUnavailable {
70 return None;
71 }
72 ForeignDetail::from_name(self.detail.split(':').next().unwrap_or(""))
73 }
74}
75
76fn transport_detail(e: &ureq::Error) -> Option<ForeignDetail> {
79 use std::io::ErrorKind;
80 Some(match e {
81 ureq::Error::HostNotFound => ForeignDetail::Dns,
82 ureq::Error::Timeout(_) => ForeignDetail::Timeout,
83 ureq::Error::Io(io) if io.to_string().contains("failed to lookup address information") => ForeignDetail::Dns,
85 ureq::Error::Io(io)
88 if io.raw_os_error().is_some_and(|c| (11001..=11004).contains(&c))
89 || io.to_string().to_ascii_lowercase().contains("no such host is known") =>
90 {
91 ForeignDetail::Dns
92 }
93 ureq::Error::Io(io) => match io.kind() {
94 ErrorKind::ConnectionRefused => ForeignDetail::Refused,
95 ErrorKind::TimedOut => ForeignDetail::Timeout,
96 _ => ForeignDetail::Network,
97 },
98 ureq::Error::ConnectionFailed => ForeignDetail::Network,
99 ureq::Error::Tls(_) | ureq::Error::Rustls(_) | ureq::Error::Pem(_) | ureq::Error::TlsRequired => {
100 ForeignDetail::Tls
101 }
102 _ => return None,
103 })
104}
105
106impl std::fmt::Display for ClientError {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 write!(f, "{}: {}", self.code.as_str(), self.detail)
109 }
110}
111
112impl std::error::Error for ClientError {}
113
114#[non_exhaustive]
116#[derive(Clone, Debug)]
117pub struct ClientConfig {
118 pub peers: BTreeMap<String, String>,
120 pub allowed: Option<Vec<String>>,
122 pub timeout: Duration,
124 pub key_ttl: Duration,
126 pub key_refetch: Duration,
128 pub mesh_ttl: Duration,
130}
131
132impl Default for ClientConfig {
133 fn default() -> Self {
134 ClientConfig {
135 peers: BTreeMap::new(),
136 allowed: None,
137 timeout: Duration::from_secs(10),
138 key_ttl: Duration::from_secs(300),
139 key_refetch: Duration::from_secs(10),
140 mesh_ttl: Duration::from_secs(300),
141 }
142 }
143}
144
145#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct RemoteBinding {
148 pub fn_hash: String,
150 pub since: String,
152}
153
154#[derive(Clone, Debug)]
156pub struct Fetched {
157 pub status: u16,
159 pub body: Vec<u8>,
161 pub answer: Answer,
163}
164
165#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct VersionEntry {
168 pub tx: String,
170 pub asof: String,
172 pub receipt: String,
174}
175
176#[derive(Clone, Debug)]
178pub struct Versions {
179 pub cell: Value,
181 pub versions: Vec<VersionEntry>,
183 pub next: Option<String>,
185}
186
187struct Inner {
188 agent: ureq::Agent,
189 cfg: ClientConfig,
190 keys: Arc<KeyCache>,
191 meshes: Mutex<HashMap<String, (MeshDoc, Instant)>>,
192}
193
194#[derive(Clone)]
196pub struct Client {
197 inner: Arc<Inner>,
198}
199
200impl std::fmt::Debug for Client {
201 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202 f.debug_struct("Client").field("allowed", &self.inner.cfg.allowed).finish_non_exhaustive()
203 }
204}
205
206pub fn pct(s: &str) -> String {
208 let mut out = String::with_capacity(s.len());
209 for b in s.bytes() {
210 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b':') {
211 out.push(b as char);
212 } else {
213 out.push_str(&format!("%{b:02X}"));
214 }
215 }
216 out
217}
218
219fn host_of(name: &str) -> &str {
220 name.split('/').next().unwrap_or(name)
221}
222
223impl Client {
224 pub fn new(cfg: ClientConfig) -> Client {
226 Client::with_keys(cfg, Arc::new(KeyCache::default()))
227 }
228
229 pub fn with_keys(cfg: ClientConfig, keys: Arc<KeyCache>) -> Client {
231 let agent: ureq::Agent = ureq::Agent::config_builder()
232 .max_redirects(0)
233 .http_status_as_error(false)
234 .timeout_global(Some(cfg.timeout))
235 .user_agent(concat!("datumesh-http/", env!("CARGO_PKG_VERSION")))
236 .build()
237 .into();
238 Client { inner: Arc::new(Inner { agent, cfg, keys, meshes: Mutex::new(HashMap::new()) }) }
239 }
240
241 pub fn keys(&self) -> &Arc<KeyCache> {
243 &self.inner.keys
244 }
245
246 pub fn allowed(&self, host: &str) -> bool {
248 self.inner.cfg.allowed.as_ref().is_none_or(|a| a.iter().any(|h| h == host))
249 }
250
251 fn check_host(&self, host: &str) -> Result<(), ClientError> {
252 if lexical::check_dns_name(host, "$").is_err() {
253 return Err(ClientError::new(ErrorCode::KeyUnavailable, format!("{host:?} is not a DNS name")));
254 }
255 if !self.allowed(host) {
256 return Err(ClientError::unavailable(format!("{host} is not an allowed host")));
257 }
258 Ok(())
259 }
260
261 pub fn get(&self, url: &str, limit: u64) -> Result<(u16, Vec<u8>), String> {
264 self.request(url, None, limit)
265 }
266
267 fn request(&self, url: &str, post: Option<&[u8]>, limit: u64) -> Result<(u16, Vec<u8>), String> {
268 self.request_with_detail(url, post, limit).map_err(|(m, _)| m)
269 }
270
271 fn fetch(&self, url: &str, post: Option<&[u8]>, limit: u64) -> Result<(u16, Vec<u8>), ClientError> {
277 self.request_with_detail(url, post, limit).map_err(|(m, d)| match d {
278 Some(d) => ClientError::foreign(d, m),
279 None => ClientError::unavailable(m),
280 })
281 }
282
283 fn request_with_detail(
286 &self,
287 url: &str,
288 post: Option<&[u8]>,
289 limit: u64,
290 ) -> Result<(u16, Vec<u8>), (String, Option<ForeignDetail>)> {
291 let mut target = url.to_string();
292 if let Some(rest) = url.strip_prefix("https://") {
293 let host = rest.split(['/', '?']).next().unwrap_or("");
294 if !self.allowed(host) {
295 return Err((format!("{host} is not an allowed host"), None));
296 }
297 if let Some(origin) = self.inner.cfg.peers.get(host) {
298 target = format!("{origin}{}", &rest[host.len()..]);
299 }
300 }
301 let resp = match post {
302 None => self.inner.agent.get(&target).call(),
303 Some(b) => self.inner.agent.post(&target).header("content-type", "application/json").send(b),
304 };
305 let mut resp = resp.map_err(|e| (format!("{url}: {e}"), transport_detail(&e)))?;
306 let status = resp.status().as_u16();
307 let body =
308 resp.body_mut().with_config().limit(limit).read_to_vec().map_err(|e| (format!("{url}: {e}"), None))?;
309 Ok((status, body))
310 }
311
312 pub fn key_document(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
315 self.key_document_with(host, refresh)
316 }
317
318 pub fn publisher_key_document(&self, host: &str) -> Result<KeyDoc, ClientError> {
323 self.key_document_with(host, false)
324 }
325
326 fn key_document_with(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
327 if let Some((doc, _, at)) = self.inner.keys.get(host) {
328 let age = at.elapsed();
329 if (!refresh && age < self.inner.cfg.key_ttl) || (refresh && age < self.inner.cfg.key_refetch) {
330 return Ok(doc);
331 }
332 }
333 self.check_host(host)?;
334 let url = format!("https://{host}/.well-known/datumesh.json");
335 let (status, body) = self.request_with_detail(&url, None, MAX_DOC).map_err(|(e, d)| match d {
336 Some(d) => ClientError::foreign(d, e),
337 None => ClientError::new(ErrorCode::KeyUnavailable, e),
338 })?;
339 let doc = keys_from_response(host, status, if status == 200 { Some(&body) } else { None })
340 .map_err(|e| ClientError::new(e.code(), e.to_string()))?;
341 self.inner.keys.insert(host, &body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
342 Ok(doc)
343 }
344
345 pub fn key_document_bytes(&self, host: &str) -> Option<Vec<u8>> {
347 self.inner.keys.get(host).map(|(_, b, _)| b)
348 }
349
350 pub fn resolve(&self, host: &str) -> Result<MeshDoc, ClientError> {
352 if let Some((m, at)) = self.inner.meshes.lock().unwrap_or_else(|p| p.into_inner()).get(host) {
353 if at.elapsed() < self.inner.cfg.mesh_ttl {
354 return Ok(m.clone());
355 }
356 }
357 self.check_host(host)?;
358 type Got = Result<(u16, Vec<u8>), (String, Option<ForeignDetail>)>;
359 let get = |path: &str| -> Got {
360 let url = format!("https://{host}/.well-known/{path}");
361 self.request_with_detail(&url, None, MAX_DOC)
362 };
363 let keys: Got = get("datumesh.json");
364 let mesh: Got = match &keys {
365 Ok((200, _)) => get("datumesh-mesh.json"),
366 _ => Err((String::new(), None)),
367 };
368 fn ret(r: &Got) -> Retrieval<'_> {
369 match r {
370 Ok((s, b)) => Retrieval::Response { status: *s, body: Some(b.as_slice()) },
371 Err(_) => Retrieval::Failed,
372 }
373 }
374 let resolved = resolve_mesh(host, ret(&keys), ret(&mesh)).map_err(|e| {
375 for r in [&keys, &mesh] {
377 if let Err((why, Some(d))) = r {
378 return ClientError::foreign(*d, why);
379 }
380 }
381 let detail = match (&keys, &mesh) {
382 (Err((e, _)), _) | (_, Err((e, _))) if !e.is_empty() => e.clone(),
383 _ => e.to_string(),
384 };
385 ClientError::new(e.code(), detail)
386 })?;
387 if let Ok((_, body)) = &keys {
388 let _ = self.inner.keys.insert(host, body);
389 }
390 let m = resolved.mesh;
391 self.inner
392 .meshes
393 .lock()
394 .unwrap_or_else(|p| p.into_inner())
395 .insert(host.to_string(), (m.clone(), Instant::now()));
396 Ok(m)
397 }
398
399 fn endpoint(&self, host: &str, name: &str, values: &[(&str, &str)]) -> Result<String, ClientError> {
400 self.resolve(host)?
401 .url(name, values)
402 .ok_or_else(|| ClientError::new(ErrorCode::MeshDoc, format!("{host} has no {name} endpoint")))
403 }
404
405 pub fn binding(&self, host: &str, name: &str, asof: Option<&str>) -> Result<Option<RemoteBinding>, ClientError> {
408 let mesh = self.resolve(host)?;
409 let mut url = format!("{}?name={}", mesh.bindings, pct(name));
410 if let Some(a) = asof {
411 url.push_str(&format!("&asof={}", pct(a)));
412 }
413 let (status, body) = self.fetch(&url, None, MAX_DOC)?;
414 if status != 200 {
415 return Err(ClientError::unavailable(format!("{url}: status {status}")));
416 }
417 let v = json::parse(&body).map_err(|e| ClientError::unavailable(format!("{url}: {e}")))?;
418 let Some(b) = v.get("bindings").and_then(|b| b.get(name)) else {
419 if v.get("bindings").and_then(Value::as_object).is_none() {
420 return Err(ClientError::unavailable(format!("{url}: no bindings object")));
421 }
422 return Ok(None);
423 };
424 let h = b.get("fn_hash").and_then(Value::as_str).unwrap_or("");
425 let since = b.get("since").and_then(Value::as_str).unwrap_or("");
426 if lexical::check_hex(h, 64, "$").is_err() || lexical::check_instant(since, "$").is_err() {
427 return Err(ClientError::unavailable(format!("{url}: malformed binding")));
428 }
429 if asof.is_some_and(|a| since > a) {
430 return Err(ClientError::unavailable(format!("{url}: a binding since after the asof")));
431 }
432 Ok(Some(RemoteBinding { fn_hash: h.to_string(), since: since.to_string() }))
433 }
434
435 pub fn descriptor(&self, host: &str, fn_hash: &str) -> Result<Vec<u8>, ClientError> {
437 let url = self.endpoint(host, "descriptor", &[("hash", fn_hash)])?;
438 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
439 if status != 200 {
440 return Err(ClientError::new(ErrorCode::FnUnavailable, format!("{url}: status {status}")));
441 }
442 let d = FunctionDescriptor::from_json(&body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
443 if d.hash() != fn_hash {
444 return Err(ClientError::new(ErrorCode::FnHashMismatch, format!("{url} gave the descriptor {}", d.hash())));
445 }
446 Ok(body)
447 }
448
449 pub fn keys_for_body(&self, body: &[u8]) -> Keys {
452 let mut hosts = BTreeSet::new();
453 fn walk(v: &Value, hosts: &mut BTreeSet<String>, depth: usize) {
454 if depth > 8 {
455 return;
456 }
457 match v {
458 Value::Object(m) => {
459 for (k, x) in m {
460 if k == "computed_by" {
461 if let Some(s) = x.as_str() {
462 hosts.insert(s.split('#').next().unwrap_or("").to_string());
463 }
464 } else {
465 walk(x, hosts, depth + 1);
466 }
467 }
468 }
469 Value::Array(a) => a.iter().for_each(|x| walk(x, hosts, depth + 1)),
470 _ => {}
471 }
472 }
473 if let Ok(v) = json::parse(body) {
474 walk(&v, &mut hosts, 0);
475 }
476 let mut keys = Keys::new();
477 for h in hosts {
478 match self.key_document(&h, false) {
479 Ok(d) => keys.insert(d),
480 Err(e) => keys.insert_result(&h, Err(datumesh_core::Error::new(e.code, "$", e.detail))),
481 }
482 }
483 keys
484 }
485
486 fn checked<T>(&self, body: &[u8], check: impl Fn(&Keys) -> datumesh_core::Result<T>) -> Result<T, ClientError> {
489 let keys = self.keys_for_body(body);
490 match check(&keys) {
491 Err(e) if matches!(e.code(), ErrorCode::KeyUnknown | ErrorCode::KeyNotValid) => {
492 let mut hosts = BTreeSet::new();
493 if let Ok(v) = json::parse(body) {
494 collect_signers(&v, &mut hosts);
495 }
496 for h in hosts {
497 let _ = self.key_document(&h, true);
498 }
499 check(&self.keys_for_body(body)).map_err(|e| ClientError::new(e.code(), e.to_string()))
500 }
501 r => r.map_err(|e| ClientError::new(e.code(), e.to_string())),
502 }
503 }
504
505 pub fn receipt(&self, host: &str, hash: &str) -> Result<Vec<u8>, ClientError> {
508 let url = self.endpoint(host, "receipt", &[("hash", hash)])?;
509 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
510 if status != 200 {
511 return Err(ClientError::unavailable(format!("{url}: status {status}")));
512 }
513 let h = self.checked(&body, |keys| {
514 let r = datumesh_core::verify(&body, keys, None, None);
515 match r.error() {
516 Some(e) => Err(e),
517 None => Ok(r.hash.unwrap_or_default()),
518 }
519 })?;
520 if h != hash {
521 return Err(ClientError::unavailable(format!("{url} gave the receipt {h}")));
522 }
523 Ok(body)
524 }
525
526 pub fn manifest(&self, host: &str, slice_id: &str, members_hash: &str) -> Result<Vec<u8>, ClientError> {
528 let url = self.endpoint(host, "manifest", &[("slice_id", slice_id), ("members_hash", members_hash)])?;
529 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
530 if status != 200 {
531 return Err(ClientError::unavailable(format!("{url}: status {status}")));
532 }
533 let m = Manifest::from_json(&body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
534 if m.entry() != format!("slice:{slice_id}:{members_hash}") {
535 return Err(ClientError::unavailable(format!("{url} gave the manifest {}", m.entry())));
536 }
537 Ok(body)
538 }
539
540 pub fn blob(&self, host: &str, sha256: &str) -> Result<Vec<u8>, ClientError> {
542 let url = self.endpoint(host, "blob", &[("sha256", sha256)])?;
543 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
544 if status != 200 {
545 return Err(ClientError::unavailable(format!("{url}: status {status}")));
546 }
547 if datumesh_core::sha256_hex(&body) != sha256 {
548 return Err(ClientError::new(ErrorCode::BlobMismatch, format!("{url}: content of another hash")));
549 }
550 Ok(body)
551 }
552
553 pub fn cell(&self, host: &str, rest: &str, request: &Request) -> Result<Fetched, ClientError> {
556 let url = self.endpoint(host, "cell", &[("cell", rest)])?;
557 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
558 let req =
559 request.clone().with_mesh(host).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
560 let answer = self.checked(&body, |keys| check_answer(status, &body, keys, &req))?;
561 Ok(Fetched { status, body, answer })
562 }
563
564 pub fn reference(&self, host: &str, reference: &Reference) -> Result<Fetched, ClientError> {
568 let fn_hash = match &reference.fn_hash {
569 Some(h) => h.clone(),
570 None => {
571 let name = format!("{}/{}", reference.ns, reference.fn_name);
572 self.binding(host, &name, reference.asof.as_deref())?
573 .ok_or_else(|| ClientError::new(ErrorCode::NameUnbound, name.clone()))?
574 .fn_hash
575 }
576 };
577 let cell = reference.resolve(&fn_hash).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
578 let mut request = Request::new(&cell.id(), reference.asof.as_deref())
579 .map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
580 if let Some(p) = &reference.fn_hash {
581 request = request.with_pin(p).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
582 }
583 let uri = format_reference(reference);
584 self.cell(host, &uri["cell://".len()..], &request)
585 }
586
587 pub fn slice_of(&self, host: &str, rest: &str) -> Result<(Slice, Reference), ClientError> {
590 let uri = format!("cell://{rest}");
591 let path = rest.split('?').next().unwrap_or(rest);
592 let query = rest.split_once('?').map(|(_, q)| q).unwrap_or("");
593 let pin = query.split('&').find_map(|p| p.strip_prefix("fn_hash=")).map(str::to_string);
594 let asof = query.split('&').next_back().and_then(|p| p.strip_prefix("asof=")).map(str::to_string);
595 let fn_hash = match pin {
596 Some(p) => p,
597 None => {
598 self.binding(host, path, asof.as_deref())?
599 .ok_or_else(|| ClientError::new(ErrorCode::NameUnbound, path.to_string()))?
600 .fn_hash
601 }
602 };
603 let d = FunctionDescriptor::from_json(&self.descriptor(host, &fn_hash)?)
604 .map_err(|e| ClientError::new(e.code(), e.to_string()))?;
605 let r =
606 parse_reference(&uri, &d.signature.to_value()).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
607 let cell = r.resolve(&fn_hash).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
608 let slice = Slice::from_value(&cell.to_value()).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
609 Ok((slice, r))
610 }
611
612 pub fn slice_page(
616 &self,
617 host: &str,
618 rest: &str,
619 next: Option<&str>,
620 after: Option<BTreeMap<String, datumesh_core::Scalar>>,
621 ) -> Result<Fetched, ClientError> {
622 let (slice, r) = self.slice_of(host, rest)?;
623 let url = match next {
624 Some(n) => {
625 if !n.starts_with(&format!("https://{host}/")) {
626 return Err(ClientError::new(ErrorCode::Envelope, format!("{n} is not on {host}")));
627 }
628 n.to_string()
629 }
630 None => self.endpoint(host, "slice", &[("cell", rest)])?,
631 };
632 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
633 let mut req = SliceRequest::new(slice.id(), r.asof.as_deref())
634 .and_then(|q| q.with_mesh(host))
635 .map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
636 if let Some(p) = &r.fn_hash {
637 req = req.with_pin(p).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
638 }
639 if let Some(a) = after {
640 req = req.with_after(a);
641 }
642 let answer = self.checked(&body, |keys| check_slice_answer(status, &body, keys, &req))?;
643 Ok(Fetched { status, body, answer })
644 }
645
646 pub fn slice(&self, host: &str, rest: &str, next: Option<&str>) -> Result<Fetched, ClientError> {
648 self.slice_page(host, rest, next, None)
649 }
650
651 pub fn batch(&self, host: &str, items: &[String], requests: &[Request]) -> Result<Batch, ClientError> {
654 let url = self.endpoint(host, "cells", &[])?;
655 let body = Value::Array(items.iter().map(|i| Value::String(i.clone())).collect()).to_jcs();
656 let (status, resp) = self.fetch(&url, Some(&body), MAX_BODY)?;
657 let reqs: Vec<Request> =
658 requests.iter().map(|r| r.clone().with_mesh(host).unwrap_or_else(|_| r.clone())).collect();
659 self.checked(&resp, |keys| check_batch(status, &resp, keys, &reqs))
660 }
661
662 pub fn versions(&self, host: &str, rest: &str) -> Result<Versions, ClientError> {
664 let url = self.endpoint(host, "versions", &[("cell", rest)])?;
665 self.versions_at(&url)
666 }
667
668 pub fn versions_at(&self, url: &str) -> Result<Versions, ClientError> {
670 let (status, body) = self.fetch(url, None, MAX_BODY)?;
671 let v = json::parse(&body).map_err(|e| ClientError::unavailable(format!("{url}: {e}")))?;
672 if status != 200 {
673 let code = v
674 .get("error")
675 .and_then(Value::as_str)
676 .and_then(ErrorCode::from_code)
677 .unwrap_or(ErrorCode::InputUnavailable);
678 return Err(ClientError::new(code, format!("{url}: status {status}")));
679 }
680 let cell = v.get("cell").cloned().ok_or_else(|| ClientError::unavailable(format!("{url}: no cell")))?;
681 let mut versions = Vec::new();
682 if let Some(Value::Array(vs)) = v.get("versions") {
683 for x in vs {
684 let s = |k: &str| x.get(k).and_then(Value::as_str).map(str::to_string);
685 match (s("tx"), s("asof"), s("receipt")) {
686 (Some(tx), Some(asof), Some(receipt)) => versions.push(VersionEntry { tx, asof, receipt }),
687 _ => return Err(ClientError::unavailable(format!("{url}: a malformed version"))),
688 }
689 }
690 }
691 Ok(Versions { cell, versions, next: v.get("next").and_then(Value::as_str).map(str::to_string) })
692 }
693
694 pub fn parse_receipt(bytes: &[u8]) -> Result<Receipt, ClientError> {
696 Receipt::from_json(bytes).map_err(|e| ClientError::new(e.code(), e.to_string()))
697 }
698}
699
700fn collect_signers(v: &Value, hosts: &mut BTreeSet<String>) {
701 match v {
702 Value::Object(m) => {
703 for (k, x) in m {
704 if k == "computed_by" {
705 if let Some(s) = x.as_str() {
706 hosts.insert(s.split('#').next().unwrap_or("").to_string());
707 }
708 } else {
709 collect_signers(x, hosts);
710 }
711 }
712 }
713 Value::Array(a) => a.iter().for_each(|x| collect_signers(x, hosts)),
714 _ => {}
715 }
716}
717
718pub fn name_host(name: &str) -> &str {
720 host_of(name)
721}
722
723#[cfg(test)]
724mod transport_detail_tests {
725 use super::*;
726 use std::io::{self, ErrorKind};
727
728 #[test]
730 fn a_windows_resolver_code_is_dns() {
731 let e = ureq::Error::Io(io::Error::from_raw_os_error(11001));
732 assert_eq!(transport_detail(&e), Some(ForeignDetail::Dns));
733 }
734
735 #[test]
737 fn no_such_host_is_known_is_dns() {
738 let e = ureq::Error::Io(io::Error::other("No such host is known. (os error 11001)"));
739 assert_eq!(transport_detail(&e), Some(ForeignDetail::Dns));
740 }
741
742 #[test]
744 fn a_refused_connection_stays_refused() {
745 let e = ureq::Error::Io(io::Error::from(ErrorKind::ConnectionRefused));
746 assert_eq!(transport_detail(&e), Some(ForeignDetail::Refused));
747 }
748}