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