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) => match io.kind() {
86 ErrorKind::ConnectionRefused => ForeignDetail::Refused,
87 ErrorKind::TimedOut => ForeignDetail::Timeout,
88 _ => ForeignDetail::Network,
89 },
90 ureq::Error::ConnectionFailed => ForeignDetail::Network,
91 ureq::Error::Tls(_) | ureq::Error::Rustls(_) | ureq::Error::Pem(_) | ureq::Error::TlsRequired => {
92 ForeignDetail::Tls
93 }
94 _ => return None,
95 })
96}
97
98impl std::fmt::Display for ClientError {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 write!(f, "{}: {}", self.code.as_str(), self.detail)
101 }
102}
103
104impl std::error::Error for ClientError {}
105
106#[non_exhaustive]
108#[derive(Clone, Debug)]
109pub struct ClientConfig {
110 pub peers: BTreeMap<String, String>,
112 pub allowed: Option<Vec<String>>,
114 pub timeout: Duration,
116 pub key_ttl: Duration,
118 pub key_refetch: Duration,
120 pub mesh_ttl: Duration,
122}
123
124impl Default for ClientConfig {
125 fn default() -> Self {
126 ClientConfig {
127 peers: BTreeMap::new(),
128 allowed: None,
129 timeout: Duration::from_secs(10),
130 key_ttl: Duration::from_secs(300),
131 key_refetch: Duration::from_secs(10),
132 mesh_ttl: Duration::from_secs(300),
133 }
134 }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct RemoteBinding {
140 pub fn_hash: String,
142 pub since: String,
144}
145
146#[derive(Clone, Debug)]
148pub struct Fetched {
149 pub status: u16,
151 pub body: Vec<u8>,
153 pub answer: Answer,
155}
156
157#[derive(Clone, Debug, PartialEq, Eq)]
159pub struct VersionEntry {
160 pub tx: String,
162 pub asof: String,
164 pub receipt: String,
166}
167
168#[derive(Clone, Debug)]
170pub struct Versions {
171 pub cell: Value,
173 pub versions: Vec<VersionEntry>,
175 pub next: Option<String>,
177}
178
179struct Inner {
180 agent: ureq::Agent,
181 cfg: ClientConfig,
182 keys: Arc<KeyCache>,
183 meshes: Mutex<HashMap<String, (MeshDoc, Instant)>>,
184}
185
186#[derive(Clone)]
188pub struct Client {
189 inner: Arc<Inner>,
190}
191
192impl std::fmt::Debug for Client {
193 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194 f.debug_struct("Client").field("allowed", &self.inner.cfg.allowed).finish_non_exhaustive()
195 }
196}
197
198pub fn pct(s: &str) -> String {
200 let mut out = String::with_capacity(s.len());
201 for b in s.bytes() {
202 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b':') {
203 out.push(b as char);
204 } else {
205 out.push_str(&format!("%{b:02X}"));
206 }
207 }
208 out
209}
210
211fn host_of(name: &str) -> &str {
212 name.split('/').next().unwrap_or(name)
213}
214
215impl Client {
216 pub fn new(cfg: ClientConfig) -> Client {
218 Client::with_keys(cfg, Arc::new(KeyCache::default()))
219 }
220
221 pub fn with_keys(cfg: ClientConfig, keys: Arc<KeyCache>) -> Client {
223 let agent: ureq::Agent = ureq::Agent::config_builder()
224 .max_redirects(0)
225 .http_status_as_error(false)
226 .timeout_global(Some(cfg.timeout))
227 .user_agent(concat!("datumesh-http/", env!("CARGO_PKG_VERSION")))
228 .build()
229 .into();
230 Client { inner: Arc::new(Inner { agent, cfg, keys, meshes: Mutex::new(HashMap::new()) }) }
231 }
232
233 pub fn keys(&self) -> &Arc<KeyCache> {
235 &self.inner.keys
236 }
237
238 pub fn allowed(&self, host: &str) -> bool {
240 self.inner.cfg.allowed.as_ref().is_none_or(|a| a.iter().any(|h| h == host))
241 }
242
243 fn check_host(&self, host: &str) -> Result<(), ClientError> {
244 if lexical::check_dns_name(host, "$").is_err() {
245 return Err(ClientError::new(ErrorCode::KeyUnavailable, format!("{host:?} is not a DNS name")));
246 }
247 if !self.allowed(host) {
248 return Err(ClientError::unavailable(format!("{host} is not an allowed host")));
249 }
250 Ok(())
251 }
252
253 pub fn get(&self, url: &str, limit: u64) -> Result<(u16, Vec<u8>), String> {
256 self.request(url, None, limit)
257 }
258
259 fn request(&self, url: &str, post: Option<&[u8]>, limit: u64) -> Result<(u16, Vec<u8>), String> {
260 self.request_with_detail(url, post, limit).map_err(|(m, _)| m)
261 }
262
263 fn fetch(&self, url: &str, post: Option<&[u8]>, limit: u64) -> Result<(u16, Vec<u8>), ClientError> {
269 self.request_with_detail(url, post, limit).map_err(|(m, d)| match d {
270 Some(d) => ClientError::foreign(d, m),
271 None => ClientError::unavailable(m),
272 })
273 }
274
275 fn request_with_detail(
278 &self,
279 url: &str,
280 post: Option<&[u8]>,
281 limit: u64,
282 ) -> Result<(u16, Vec<u8>), (String, Option<ForeignDetail>)> {
283 let mut target = url.to_string();
284 if let Some(rest) = url.strip_prefix("https://") {
285 let host = rest.split(['/', '?']).next().unwrap_or("");
286 if !self.allowed(host) {
287 return Err((format!("{host} is not an allowed host"), None));
288 }
289 if let Some(origin) = self.inner.cfg.peers.get(host) {
290 target = format!("{origin}{}", &rest[host.len()..]);
291 }
292 }
293 let resp = match post {
294 None => self.inner.agent.get(&target).call(),
295 Some(b) => self.inner.agent.post(&target).header("content-type", "application/json").send(b),
296 };
297 let mut resp = resp.map_err(|e| (format!("{url}: {e}"), transport_detail(&e)))?;
298 let status = resp.status().as_u16();
299 let body =
300 resp.body_mut().with_config().limit(limit).read_to_vec().map_err(|e| (format!("{url}: {e}"), None))?;
301 Ok((status, body))
302 }
303
304 pub fn key_document(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
307 self.key_document_with(host, refresh)
308 }
309
310 pub fn publisher_key_document(&self, host: &str) -> Result<KeyDoc, ClientError> {
315 self.key_document_with(host, false)
316 }
317
318 fn key_document_with(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
319 if let Some((doc, _, at)) = self.inner.keys.get(host) {
320 let age = at.elapsed();
321 if (!refresh && age < self.inner.cfg.key_ttl) || (refresh && age < self.inner.cfg.key_refetch) {
322 return Ok(doc);
323 }
324 }
325 self.check_host(host)?;
326 let url = format!("https://{host}/.well-known/datumesh.json");
327 let (status, body) = self.request_with_detail(&url, None, MAX_DOC).map_err(|(e, d)| match d {
328 Some(d) => ClientError::foreign(d, e),
329 None => ClientError::new(ErrorCode::KeyUnavailable, e),
330 })?;
331 let doc = keys_from_response(host, status, if status == 200 { Some(&body) } else { None })
332 .map_err(|e| ClientError::new(e.code(), e.to_string()))?;
333 self.inner.keys.insert(host, &body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
334 Ok(doc)
335 }
336
337 pub fn key_document_bytes(&self, host: &str) -> Option<Vec<u8>> {
339 self.inner.keys.get(host).map(|(_, b, _)| b)
340 }
341
342 pub fn resolve(&self, host: &str) -> Result<MeshDoc, ClientError> {
344 if let Some((m, at)) = self.inner.meshes.lock().unwrap_or_else(|p| p.into_inner()).get(host) {
345 if at.elapsed() < self.inner.cfg.mesh_ttl {
346 return Ok(m.clone());
347 }
348 }
349 self.check_host(host)?;
350 type Got = Result<(u16, Vec<u8>), (String, Option<ForeignDetail>)>;
351 let get = |path: &str| -> Got {
352 let url = format!("https://{host}/.well-known/{path}");
353 self.request_with_detail(&url, None, MAX_DOC)
354 };
355 let keys: Got = get("datumesh.json");
356 let mesh: Got = match &keys {
357 Ok((200, _)) => get("datumesh-mesh.json"),
358 _ => Err((String::new(), None)),
359 };
360 fn ret(r: &Got) -> Retrieval<'_> {
361 match r {
362 Ok((s, b)) => Retrieval::Response { status: *s, body: Some(b.as_slice()) },
363 Err(_) => Retrieval::Failed,
364 }
365 }
366 let resolved = resolve_mesh(host, ret(&keys), ret(&mesh)).map_err(|e| {
367 for r in [&keys, &mesh] {
369 if let Err((why, Some(d))) = r {
370 return ClientError::foreign(*d, why);
371 }
372 }
373 let detail = match (&keys, &mesh) {
374 (Err((e, _)), _) | (_, Err((e, _))) if !e.is_empty() => e.clone(),
375 _ => e.to_string(),
376 };
377 ClientError::new(e.code(), detail)
378 })?;
379 if let Ok((_, body)) = &keys {
380 let _ = self.inner.keys.insert(host, body);
381 }
382 let m = resolved.mesh;
383 self.inner
384 .meshes
385 .lock()
386 .unwrap_or_else(|p| p.into_inner())
387 .insert(host.to_string(), (m.clone(), Instant::now()));
388 Ok(m)
389 }
390
391 fn endpoint(&self, host: &str, name: &str, values: &[(&str, &str)]) -> Result<String, ClientError> {
392 self.resolve(host)?
393 .url(name, values)
394 .ok_or_else(|| ClientError::new(ErrorCode::MeshDoc, format!("{host} has no {name} endpoint")))
395 }
396
397 pub fn binding(&self, host: &str, name: &str, asof: Option<&str>) -> Result<Option<RemoteBinding>, ClientError> {
400 let mesh = self.resolve(host)?;
401 let mut url = format!("{}?name={}", mesh.bindings, pct(name));
402 if let Some(a) = asof {
403 url.push_str(&format!("&asof={}", pct(a)));
404 }
405 let (status, body) = self.fetch(&url, None, MAX_DOC)?;
406 if status != 200 {
407 return Err(ClientError::unavailable(format!("{url}: status {status}")));
408 }
409 let v = json::parse(&body).map_err(|e| ClientError::unavailable(format!("{url}: {e}")))?;
410 let Some(b) = v.get("bindings").and_then(|b| b.get(name)) else {
411 if v.get("bindings").and_then(Value::as_object).is_none() {
412 return Err(ClientError::unavailable(format!("{url}: no bindings object")));
413 }
414 return Ok(None);
415 };
416 let h = b.get("fn_hash").and_then(Value::as_str).unwrap_or("");
417 let since = b.get("since").and_then(Value::as_str).unwrap_or("");
418 if lexical::check_hex(h, 64, "$").is_err() || lexical::check_instant(since, "$").is_err() {
419 return Err(ClientError::unavailable(format!("{url}: malformed binding")));
420 }
421 if asof.is_some_and(|a| since > a) {
422 return Err(ClientError::unavailable(format!("{url}: a binding since after the asof")));
423 }
424 Ok(Some(RemoteBinding { fn_hash: h.to_string(), since: since.to_string() }))
425 }
426
427 pub fn descriptor(&self, host: &str, fn_hash: &str) -> Result<Vec<u8>, ClientError> {
429 let url = self.endpoint(host, "descriptor", &[("hash", fn_hash)])?;
430 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
431 if status != 200 {
432 return Err(ClientError::new(ErrorCode::FnUnavailable, format!("{url}: status {status}")));
433 }
434 let d = FunctionDescriptor::from_json(&body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
435 if d.hash() != fn_hash {
436 return Err(ClientError::new(ErrorCode::FnHashMismatch, format!("{url} gave the descriptor {}", d.hash())));
437 }
438 Ok(body)
439 }
440
441 pub fn keys_for_body(&self, body: &[u8]) -> Keys {
444 let mut hosts = BTreeSet::new();
445 fn walk(v: &Value, hosts: &mut BTreeSet<String>, depth: usize) {
446 if depth > 8 {
447 return;
448 }
449 match v {
450 Value::Object(m) => {
451 for (k, x) in m {
452 if k == "computed_by" {
453 if let Some(s) = x.as_str() {
454 hosts.insert(s.split('#').next().unwrap_or("").to_string());
455 }
456 } else {
457 walk(x, hosts, depth + 1);
458 }
459 }
460 }
461 Value::Array(a) => a.iter().for_each(|x| walk(x, hosts, depth + 1)),
462 _ => {}
463 }
464 }
465 if let Ok(v) = json::parse(body) {
466 walk(&v, &mut hosts, 0);
467 }
468 let mut keys = Keys::new();
469 for h in hosts {
470 match self.key_document(&h, false) {
471 Ok(d) => keys.insert(d),
472 Err(e) => keys.insert_result(&h, Err(datumesh_core::Error::new(e.code, "$", e.detail))),
473 }
474 }
475 keys
476 }
477
478 fn checked<T>(&self, body: &[u8], check: impl Fn(&Keys) -> datumesh_core::Result<T>) -> Result<T, ClientError> {
481 let keys = self.keys_for_body(body);
482 match check(&keys) {
483 Err(e) if matches!(e.code(), ErrorCode::KeyUnknown | ErrorCode::KeyNotValid) => {
484 let mut hosts = BTreeSet::new();
485 if let Ok(v) = json::parse(body) {
486 collect_signers(&v, &mut hosts);
487 }
488 for h in hosts {
489 let _ = self.key_document(&h, true);
490 }
491 check(&self.keys_for_body(body)).map_err(|e| ClientError::new(e.code(), e.to_string()))
492 }
493 r => r.map_err(|e| ClientError::new(e.code(), e.to_string())),
494 }
495 }
496
497 pub fn receipt(&self, host: &str, hash: &str) -> Result<Vec<u8>, ClientError> {
500 let url = self.endpoint(host, "receipt", &[("hash", hash)])?;
501 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
502 if status != 200 {
503 return Err(ClientError::unavailable(format!("{url}: status {status}")));
504 }
505 let h = self.checked(&body, |keys| {
506 let r = datumesh_core::verify(&body, keys, None, None);
507 match r.error() {
508 Some(e) => Err(e),
509 None => Ok(r.hash.unwrap_or_default()),
510 }
511 })?;
512 if h != hash {
513 return Err(ClientError::unavailable(format!("{url} gave the receipt {h}")));
514 }
515 Ok(body)
516 }
517
518 pub fn manifest(&self, host: &str, slice_id: &str, members_hash: &str) -> Result<Vec<u8>, ClientError> {
520 let url = self.endpoint(host, "manifest", &[("slice_id", slice_id), ("members_hash", members_hash)])?;
521 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
522 if status != 200 {
523 return Err(ClientError::unavailable(format!("{url}: status {status}")));
524 }
525 let m = Manifest::from_json(&body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
526 if m.entry() != format!("slice:{slice_id}:{members_hash}") {
527 return Err(ClientError::unavailable(format!("{url} gave the manifest {}", m.entry())));
528 }
529 Ok(body)
530 }
531
532 pub fn blob(&self, host: &str, sha256: &str) -> Result<Vec<u8>, ClientError> {
534 let url = self.endpoint(host, "blob", &[("sha256", sha256)])?;
535 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
536 if status != 200 {
537 return Err(ClientError::unavailable(format!("{url}: status {status}")));
538 }
539 if datumesh_core::sha256_hex(&body) != sha256 {
540 return Err(ClientError::new(ErrorCode::BlobMismatch, format!("{url}: content of another hash")));
541 }
542 Ok(body)
543 }
544
545 pub fn cell(&self, host: &str, rest: &str, request: &Request) -> Result<Fetched, ClientError> {
548 let url = self.endpoint(host, "cell", &[("cell", rest)])?;
549 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
550 let req =
551 request.clone().with_mesh(host).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
552 let answer = self.checked(&body, |keys| check_answer(status, &body, keys, &req))?;
553 Ok(Fetched { status, body, answer })
554 }
555
556 pub fn reference(&self, host: &str, reference: &Reference) -> Result<Fetched, ClientError> {
560 let fn_hash = match &reference.fn_hash {
561 Some(h) => h.clone(),
562 None => {
563 let name = format!("{}/{}", reference.ns, reference.fn_name);
564 self.binding(host, &name, reference.asof.as_deref())?
565 .ok_or_else(|| ClientError::new(ErrorCode::NameUnbound, name.clone()))?
566 .fn_hash
567 }
568 };
569 let cell = reference.resolve(&fn_hash).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
570 let mut request = Request::new(&cell.id(), reference.asof.as_deref())
571 .map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
572 if let Some(p) = &reference.fn_hash {
573 request = request.with_pin(p).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
574 }
575 let uri = format_reference(reference);
576 self.cell(host, &uri["cell://".len()..], &request)
577 }
578
579 pub fn slice_of(&self, host: &str, rest: &str) -> Result<(Slice, Reference), ClientError> {
582 let uri = format!("cell://{rest}");
583 let path = rest.split('?').next().unwrap_or(rest);
584 let query = rest.split_once('?').map(|(_, q)| q).unwrap_or("");
585 let pin = query.split('&').find_map(|p| p.strip_prefix("fn_hash=")).map(str::to_string);
586 let asof = query.split('&').next_back().and_then(|p| p.strip_prefix("asof=")).map(str::to_string);
587 let fn_hash = match pin {
588 Some(p) => p,
589 None => {
590 self.binding(host, path, asof.as_deref())?
591 .ok_or_else(|| ClientError::new(ErrorCode::NameUnbound, path.to_string()))?
592 .fn_hash
593 }
594 };
595 let d = FunctionDescriptor::from_json(&self.descriptor(host, &fn_hash)?)
596 .map_err(|e| ClientError::new(e.code(), e.to_string()))?;
597 let r =
598 parse_reference(&uri, &d.signature.to_value()).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
599 let cell = r.resolve(&fn_hash).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
600 let slice = Slice::from_value(&cell.to_value()).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
601 Ok((slice, r))
602 }
603
604 pub fn slice_page(
608 &self,
609 host: &str,
610 rest: &str,
611 next: Option<&str>,
612 after: Option<BTreeMap<String, datumesh_core::Scalar>>,
613 ) -> Result<Fetched, ClientError> {
614 let (slice, r) = self.slice_of(host, rest)?;
615 let url = match next {
616 Some(n) => {
617 if !n.starts_with(&format!("https://{host}/")) {
618 return Err(ClientError::new(ErrorCode::Envelope, format!("{n} is not on {host}")));
619 }
620 n.to_string()
621 }
622 None => self.endpoint(host, "slice", &[("cell", rest)])?,
623 };
624 let (status, body) = self.fetch(&url, None, MAX_BODY)?;
625 let mut req = SliceRequest::new(slice.id(), r.asof.as_deref())
626 .and_then(|q| q.with_mesh(host))
627 .map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
628 if let Some(p) = &r.fn_hash {
629 req = req.with_pin(p).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
630 }
631 if let Some(a) = after {
632 req = req.with_after(a);
633 }
634 let answer = self.checked(&body, |keys| check_slice_answer(status, &body, keys, &req))?;
635 Ok(Fetched { status, body, answer })
636 }
637
638 pub fn slice(&self, host: &str, rest: &str, next: Option<&str>) -> Result<Fetched, ClientError> {
640 self.slice_page(host, rest, next, None)
641 }
642
643 pub fn batch(&self, host: &str, items: &[String], requests: &[Request]) -> Result<Batch, ClientError> {
646 let url = self.endpoint(host, "cells", &[])?;
647 let body = Value::Array(items.iter().map(|i| Value::String(i.clone())).collect()).to_jcs();
648 let (status, resp) = self.fetch(&url, Some(&body), MAX_BODY)?;
649 let reqs: Vec<Request> =
650 requests.iter().map(|r| r.clone().with_mesh(host).unwrap_or_else(|_| r.clone())).collect();
651 self.checked(&resp, |keys| check_batch(status, &resp, keys, &reqs))
652 }
653
654 pub fn versions(&self, host: &str, rest: &str) -> Result<Versions, ClientError> {
656 let url = self.endpoint(host, "versions", &[("cell", rest)])?;
657 self.versions_at(&url)
658 }
659
660 pub fn versions_at(&self, url: &str) -> Result<Versions, ClientError> {
662 let (status, body) = self.fetch(url, None, MAX_BODY)?;
663 let v = json::parse(&body).map_err(|e| ClientError::unavailable(format!("{url}: {e}")))?;
664 if status != 200 {
665 let code = v
666 .get("error")
667 .and_then(Value::as_str)
668 .and_then(ErrorCode::from_code)
669 .unwrap_or(ErrorCode::InputUnavailable);
670 return Err(ClientError::new(code, format!("{url}: status {status}")));
671 }
672 let cell = v.get("cell").cloned().ok_or_else(|| ClientError::unavailable(format!("{url}: no cell")))?;
673 let mut versions = Vec::new();
674 if let Some(Value::Array(vs)) = v.get("versions") {
675 for x in vs {
676 let s = |k: &str| x.get(k).and_then(Value::as_str).map(str::to_string);
677 match (s("tx"), s("asof"), s("receipt")) {
678 (Some(tx), Some(asof), Some(receipt)) => versions.push(VersionEntry { tx, asof, receipt }),
679 _ => return Err(ClientError::unavailable(format!("{url}: a malformed version"))),
680 }
681 }
682 }
683 Ok(Versions { cell, versions, next: v.get("next").and_then(Value::as_str).map(str::to_string) })
684 }
685
686 pub fn parse_receipt(bytes: &[u8]) -> Result<Receipt, ClientError> {
688 Receipt::from_json(bytes).map_err(|e| ClientError::new(e.code(), e.to_string()))
689 }
690}
691
692fn collect_signers(v: &Value, hosts: &mut BTreeSet<String>) {
693 match v {
694 Value::Object(m) => {
695 for (k, x) in m {
696 if k == "computed_by" {
697 if let Some(s) = x.as_str() {
698 hosts.insert(s.split('#').next().unwrap_or("").to_string());
699 }
700 } else {
701 collect_signers(x, hosts);
702 }
703 }
704 }
705 Value::Array(a) => a.iter().for_each(|x| collect_signers(x, hosts)),
706 _ => {}
707 }
708}
709
710pub fn name_host(name: &str) -> &str {
712 host_of(name)
713}