Skip to main content

datumesh_http/
client.rs

1//! The store-less client of other meshes (for `datumesh-local` and for this mesh's cross-mesh
2//! reads): fetch a host's key document and mesh document, its bindings, a cell's envelope (by
3//! call, URI or pin), slice pages, batches, receipts, descriptors, manifests, blobs and
4//! versions, and **check** each with the core: the envelope against the request
5//! (`check_answer`, `check_slice_answer`, `check_batch`), every receipt's signature against
6//! its signer's key document (fetched from the signer's own host, never from the mesh that
7//! served it), and content-addressed bytes against their hash. Nothing is stored; the import
8//! into a store is [`crate::foreign::Foreign`]'s, a layer on top.
9//!
10//! **Blocking.** The client is synchronous (ureq, rustls with the Mozilla roots, no redirects,
11//! a time limit per request, bodies bounded): this mesh's engine reads foreign cells from
12//! inside an evaluation, which runs on a blocking thread, and `datumesh-local`'s CLI is
13//! synchronous too. An async caller runs it on `tokio::task::spawn_blocking`, as the mesh's
14//! own handlers do with the engine. [`Client`] is cheap to clone and shares its caches.
15//!
16//! **Caches.** Key documents (default 300 s; a key id the cached document lacks refetches it,
17//! at most every 10 s) and mesh documents (300 s), in memory. Nothing else is cached here.
18//!
19//! **Allowlist.** With [`ClientConfig::allowed`] set, only those hosts are fetched from
20//! (anything else is refused with `E_INPUT_UNAVAILABLE` before any request).
21
22use 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, FunctionDescriptor, KeyDoc, Keys, Manifest, MeshDoc, Receipt, Reference,
30    Request, Retrieval, Slice, SliceRequest,
31};
32
33use crate::foreign::KeyCache;
34
35/// The largest body read from another mesh.
36const MAX_BODY: u64 = 64 << 20;
37/// The largest key or mesh document read (SPEC 9.3's suggested bound).
38const MAX_DOC: u64 = 256 << 10;
39
40/// A failure of the client: the code of the `error` envelope a mesh would give for it, and why.
41#[derive(Clone, Debug)]
42pub struct ClientError {
43    /// `E_INPUT_UNAVAILABLE` (the other mesh is down, answered otherwise, or is not allowed),
44    /// `E_MESH_DOC`, `E_KEY_UNAVAILABLE` or `E_KEY_DOC` (resolving its host), `E_ENVELOPE` (an
45    /// answer that fails the check), or what checking a receipt gave.
46    pub code: ErrorCode,
47    /// Why.
48    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
60impl std::fmt::Display for ClientError {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        write!(f, "{}: {}", self.code.as_str(), self.detail)
63    }
64}
65
66impl std::error::Error for ClientError {}
67
68/// The client's configuration.
69#[non_exhaustive]
70#[derive(Clone, Debug)]
71pub struct ClientConfig {
72    /// Origins to use instead of `https://<host>` for some hosts (tests, private networks).
73    pub peers: BTreeMap<String, String>,
74    /// When set, the only hosts fetched from.
75    pub allowed: Option<Vec<String>>,
76    /// The time limit of one request (default 10 s).
77    pub timeout: Duration,
78    /// Key documents' lifetime in the cache (default 300 s).
79    pub key_ttl: Duration,
80    /// The shortest interval between two fetches of one host's key document (default 10 s).
81    pub key_refetch: Duration,
82    /// Mesh documents' lifetime in the cache (default 300 s).
83    pub mesh_ttl: Duration,
84}
85
86impl Default for ClientConfig {
87    fn default() -> Self {
88        ClientConfig {
89            peers: BTreeMap::new(),
90            allowed: None,
91            timeout: Duration::from_secs(10),
92            key_ttl: Duration::from_secs(300),
93            key_refetch: Duration::from_secs(10),
94            mesh_ttl: Duration::from_secs(300),
95        }
96    }
97}
98
99/// A binding another mesh states (SPEC 9.7).
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct RemoteBinding {
102    /// The function hash.
103    pub fn_hash: String,
104    /// When the binding began.
105    pub since: String,
106}
107
108/// An answer fetched and checked: its HTTP status, its body as received, and the checked answer.
109#[derive(Clone, Debug)]
110pub struct Fetched {
111    /// The HTTP status.
112    pub status: u16,
113    /// The body.
114    pub body: Vec<u8>,
115    /// The answer, checked against the request.
116    pub answer: Answer,
117}
118
119/// One version a mesh lists (SPEC 9.8).
120#[derive(Clone, Debug, PartialEq, Eq)]
121pub struct VersionEntry {
122    /// The version's `tx`.
123    pub tx: String,
124    /// Its receipt's `asof`.
125    pub asof: String,
126    /// Its receipt hash.
127    pub receipt: String,
128}
129
130/// A page of the versions endpoint (SPEC 9.8).
131#[derive(Clone, Debug)]
132pub struct Versions {
133    /// The cell (4.4).
134    pub cell: Value,
135    /// The versions, ascending by `tx`.
136    pub versions: Vec<VersionEntry>,
137    /// The following page's URL.
138    pub next: Option<String>,
139}
140
141struct Inner {
142    agent: ureq::Agent,
143    cfg: ClientConfig,
144    keys: Arc<KeyCache>,
145    meshes: Mutex<HashMap<String, (MeshDoc, Instant)>>,
146}
147
148/// The client (see the module documentation).
149#[derive(Clone)]
150pub struct Client {
151    inner: Arc<Inner>,
152}
153
154impl std::fmt::Debug for Client {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        f.debug_struct("Client").field("allowed", &self.inner.cfg.allowed).finish_non_exhaustive()
157    }
158}
159
160/// Percent-encodes a value as SPEC 5.1 says (literal characters as themselves).
161pub fn pct(s: &str) -> String {
162    let mut out = String::with_capacity(s.len());
163    for b in s.bytes() {
164        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b':') {
165            out.push(b as char);
166        } else {
167            out.push_str(&format!("%{b:02X}"));
168        }
169    }
170    out
171}
172
173fn host_of(name: &str) -> &str {
174    name.split('/').next().unwrap_or(name)
175}
176
177impl Client {
178    /// A client with this configuration.
179    pub fn new(cfg: ClientConfig) -> Client {
180        Client::with_keys(cfg, Arc::new(KeyCache::default()))
181    }
182
183    /// A client sharing a key cache (the mesh's, so `POST /verify` sees what it fetched).
184    pub fn with_keys(cfg: ClientConfig, keys: Arc<KeyCache>) -> Client {
185        let agent: ureq::Agent = ureq::Agent::config_builder()
186            .max_redirects(0)
187            .http_status_as_error(false)
188            .timeout_global(Some(cfg.timeout))
189            .user_agent(concat!("datumesh-http/", env!("CARGO_PKG_VERSION")))
190            .build()
191            .into();
192        Client { inner: Arc::new(Inner { agent, cfg, keys, meshes: Mutex::new(HashMap::new()) }) }
193    }
194
195    /// The key cache.
196    pub fn keys(&self) -> &Arc<KeyCache> {
197        &self.inner.keys
198    }
199
200    /// Whether `host` may be fetched from.
201    pub fn allowed(&self, host: &str) -> bool {
202        self.inner.cfg.allowed.as_ref().is_none_or(|a| a.iter().any(|h| h == host))
203    }
204
205    fn check_host(&self, host: &str) -> Result<(), ClientError> {
206        if lexical::check_dns_name(host, "$").is_err() {
207            return Err(ClientError::new(ErrorCode::KeyUnavailable, format!("{host:?} is not a DNS name")));
208        }
209        if !self.allowed(host) {
210            return Err(ClientError::unavailable(format!("{host} is not an allowed host")));
211        }
212        Ok(())
213    }
214
215    /// `GET url` (an `https://<host>/...` URL; the origin replaced for a configured peer):
216    /// status and body, at most `limit` bytes.
217    pub fn get(&self, url: &str, limit: u64) -> Result<(u16, Vec<u8>), String> {
218        self.request(url, None, limit)
219    }
220
221    fn request(&self, url: &str, post: Option<&[u8]>, limit: u64) -> Result<(u16, Vec<u8>), String> {
222        let mut target = url.to_string();
223        if let Some(rest) = url.strip_prefix("https://") {
224            let host = rest.split(['/', '?']).next().unwrap_or("");
225            if !self.allowed(host) {
226                return Err(format!("{host} is not an allowed host"));
227            }
228            if let Some(origin) = self.inner.cfg.peers.get(host) {
229                target = format!("{origin}{}", &rest[host.len()..]);
230            }
231        }
232        let resp = match post {
233            None => self.inner.agent.get(&target).call(),
234            Some(b) => self.inner.agent.post(&target).header("content-type", "application/json").send(b),
235        };
236        let mut resp = resp.map_err(|e| format!("{url}: {e}"))?;
237        let status = resp.status().as_u16();
238        let body = resp.body_mut().with_config().limit(limit).read_to_vec().map_err(|e| format!("{url}: {e}"))?;
239        Ok((status, body))
240    }
241
242    /// The key document of `host` (SPEC 9.3), from the cache while it is fresh, else fetched;
243    /// `refresh` fetches it again unless it was fetched within the refetch interval.
244    pub fn key_document(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
245        if let Some((doc, _, at)) = self.inner.keys.get(host) {
246            let age = at.elapsed();
247            if (!refresh && age < self.inner.cfg.key_ttl) || (refresh && age < self.inner.cfg.key_refetch) {
248                return Ok(doc);
249            }
250        }
251        self.check_host(host)?;
252        let url = format!("https://{host}/.well-known/datumesh.json");
253        let (status, body) = self.get(&url, MAX_DOC).map_err(|e| ClientError::new(ErrorCode::KeyUnavailable, e))?;
254        let doc = keys_from_response(host, status, if status == 200 { Some(&body) } else { None })
255            .map_err(|e| ClientError::new(e.code(), e.to_string()))?;
256        self.inner.keys.insert(host, &body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
257        Ok(doc)
258    }
259
260    /// The bytes of `host`'s key document as last fetched.
261    pub fn key_document_bytes(&self, host: &str) -> Option<Vec<u8>> {
262        self.inner.keys.get(host).map(|(_, b, _)| b)
263    }
264
265    /// The mesh document of `host`, resolved with its key document (SPEC 9.6), cached.
266    pub fn resolve(&self, host: &str) -> Result<MeshDoc, ClientError> {
267        if let Some((m, at)) = self.inner.meshes.lock().unwrap_or_else(|p| p.into_inner()).get(host) {
268            if at.elapsed() < self.inner.cfg.mesh_ttl {
269                return Ok(m.clone());
270            }
271        }
272        self.check_host(host)?;
273        let keys = self.get(&format!("https://{host}/.well-known/datumesh.json"), MAX_DOC);
274        let mesh = match &keys {
275            Ok((200, _)) => self.get(&format!("https://{host}/.well-known/datumesh-mesh.json"), MAX_DOC),
276            _ => Err(String::new()),
277        };
278        fn ret(r: &Result<(u16, Vec<u8>), String>) -> Retrieval<'_> {
279            match r {
280                Ok((s, b)) => Retrieval::Response { status: *s, body: Some(b.as_slice()) },
281                Err(_) => Retrieval::Failed,
282            }
283        }
284        let resolved = resolve_mesh(host, ret(&keys), ret(&mesh)).map_err(|e| {
285            let detail = match (&keys, &mesh) {
286                (Err(e), _) | (_, Err(e)) if !e.is_empty() => e.clone(),
287                _ => e.to_string(),
288            };
289            ClientError::new(e.code(), detail)
290        })?;
291        if let Ok((_, body)) = &keys {
292            let _ = self.inner.keys.insert(host, body);
293        }
294        let m = resolved.mesh;
295        self.inner
296            .meshes
297            .lock()
298            .unwrap_or_else(|p| p.into_inner())
299            .insert(host.to_string(), (m.clone(), Instant::now()));
300        Ok(m)
301    }
302
303    fn endpoint(&self, host: &str, name: &str, values: &[(&str, &str)]) -> Result<String, ClientError> {
304        self.resolve(host)?
305            .url(name, values)
306            .ok_or_else(|| ClientError::new(ErrorCode::MeshDoc, format!("{host} has no {name} endpoint")))
307    }
308
309    /// The binding of `name` that `host`'s bindings resource states as of `asof` (now when
310    /// `None`), SPEC 9.7.
311    pub fn binding(&self, host: &str, name: &str, asof: Option<&str>) -> Result<Option<RemoteBinding>, ClientError> {
312        let mesh = self.resolve(host)?;
313        let mut url = format!("{}?name={}", mesh.bindings, pct(name));
314        if let Some(a) = asof {
315            url.push_str(&format!("&asof={}", pct(a)));
316        }
317        let (status, body) = self.get(&url, MAX_DOC).map_err(ClientError::unavailable)?;
318        if status != 200 {
319            return Err(ClientError::unavailable(format!("{url}: status {status}")));
320        }
321        let v = json::parse(&body).map_err(|e| ClientError::unavailable(format!("{url}: {e}")))?;
322        let Some(b) = v.get("bindings").and_then(|b| b.get(name)) else {
323            if v.get("bindings").and_then(Value::as_object).is_none() {
324                return Err(ClientError::unavailable(format!("{url}: no bindings object")));
325            }
326            return Ok(None);
327        };
328        let h = b.get("fn_hash").and_then(Value::as_str).unwrap_or("");
329        let since = b.get("since").and_then(Value::as_str).unwrap_or("");
330        if lexical::check_hex(h, 64, "$").is_err() || lexical::check_instant(since, "$").is_err() {
331            return Err(ClientError::unavailable(format!("{url}: malformed binding")));
332        }
333        if asof.is_some_and(|a| since > a) {
334            return Err(ClientError::unavailable(format!("{url}: a binding since after the asof")));
335        }
336        Ok(Some(RemoteBinding { fn_hash: h.to_string(), since: since.to_string() }))
337    }
338
339    /// The descriptor `fn_hash` names, from `host` (its hash checked).
340    pub fn descriptor(&self, host: &str, fn_hash: &str) -> Result<Vec<u8>, ClientError> {
341        let url = self.endpoint(host, "descriptor", &[("hash", fn_hash)])?;
342        let (status, body) = self.get(&url, MAX_BODY).map_err(ClientError::unavailable)?;
343        if status != 200 {
344            return Err(ClientError::new(ErrorCode::FnUnavailable, format!("{url}: status {status}")));
345        }
346        let d = FunctionDescriptor::from_json(&body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
347        if d.hash() != fn_hash {
348            return Err(ClientError::new(ErrorCode::FnHashMismatch, format!("{url} gave the descriptor {}", d.hash())));
349        }
350        Ok(body)
351    }
352
353    /// The keys of the signers named in a body (a receipt, an envelope, a page or a batch):
354    /// each signer's key document, from its own host.
355    pub fn keys_for_body(&self, body: &[u8]) -> Keys {
356        let mut hosts = BTreeSet::new();
357        fn walk(v: &Value, hosts: &mut BTreeSet<String>, depth: usize) {
358            if depth > 8 {
359                return;
360            }
361            match v {
362                Value::Object(m) => {
363                    for (k, x) in m {
364                        if k == "computed_by" {
365                            if let Some(s) = x.as_str() {
366                                hosts.insert(s.split('#').next().unwrap_or("").to_string());
367                            }
368                        } else {
369                            walk(x, hosts, depth + 1);
370                        }
371                    }
372                }
373                Value::Array(a) => a.iter().for_each(|x| walk(x, hosts, depth + 1)),
374                _ => {}
375            }
376        }
377        if let Ok(v) = json::parse(body) {
378            walk(&v, &mut hosts, 0);
379        }
380        let mut keys = Keys::new();
381        for h in hosts {
382            match self.key_document(&h, false) {
383                Ok(d) => keys.insert(d),
384                Err(e) => keys.insert_result(&h, Err(datumesh_core::Error::new(e.code, "$", e.detail))),
385            }
386        }
387        keys
388    }
389
390    /// Runs `check` with the signers' keys, fetching them again once when a key id is unknown
391    /// (a rotation).
392    fn checked<T>(&self, body: &[u8], check: impl Fn(&Keys) -> datumesh_core::Result<T>) -> Result<T, ClientError> {
393        let keys = self.keys_for_body(body);
394        match check(&keys) {
395            Err(e) if matches!(e.code(), ErrorCode::KeyUnknown | ErrorCode::KeyNotValid) => {
396                let mut hosts = BTreeSet::new();
397                if let Ok(v) = json::parse(body) {
398                    collect_signers(&v, &mut hosts);
399                }
400                for h in hosts {
401                    let _ = self.key_document(&h, true);
402                }
403                check(&self.keys_for_body(body)).map_err(|e| ClientError::new(e.code(), e.to_string()))
404            }
405            r => r.map_err(|e| ClientError::new(e.code(), e.to_string())),
406        }
407    }
408
409    /// A receipt by its hash from `host`: its hash checked and its signature verified (SPEC
410    /// 10.1 steps 1-6) against its signer's key document.
411    pub fn receipt(&self, host: &str, hash: &str) -> Result<Vec<u8>, ClientError> {
412        let url = self.endpoint(host, "receipt", &[("hash", hash)])?;
413        let (status, body) = self.get(&url, MAX_BODY).map_err(ClientError::unavailable)?;
414        if status != 200 {
415            return Err(ClientError::unavailable(format!("{url}: status {status}")));
416        }
417        let h = self.checked(&body, |keys| {
418            let r = datumesh_core::verify(&body, keys, None, None);
419            match r.error() {
420                Some(e) => Err(e),
421                None => Ok(r.hash.unwrap_or_default()),
422            }
423        })?;
424        if h != hash {
425            return Err(ClientError::unavailable(format!("{url} gave the receipt {h}")));
426        }
427        Ok(body)
428    }
429
430    /// A slice manifest from `host` (its entry checked).
431    pub fn manifest(&self, host: &str, slice_id: &str, members_hash: &str) -> Result<Vec<u8>, ClientError> {
432        let url = self.endpoint(host, "manifest", &[("slice_id", slice_id), ("members_hash", members_hash)])?;
433        let (status, body) = self.get(&url, MAX_BODY).map_err(ClientError::unavailable)?;
434        if status != 200 {
435            return Err(ClientError::unavailable(format!("{url}: status {status}")));
436        }
437        let m = Manifest::from_json(&body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
438        if m.entry() != format!("slice:{slice_id}:{members_hash}") {
439            return Err(ClientError::unavailable(format!("{url} gave the manifest {}", m.entry())));
440        }
441        Ok(body)
442    }
443
444    /// Blob content by SHA-256 from `host` (its hash checked).
445    pub fn blob(&self, host: &str, sha256: &str) -> Result<Vec<u8>, ClientError> {
446        let url = self.endpoint(host, "blob", &[("sha256", sha256)])?;
447        let (status, body) = self.get(&url, MAX_BODY).map_err(ClientError::unavailable)?;
448        if status != 200 {
449            return Err(ClientError::unavailable(format!("{url}: status {status}")));
450        }
451        if datumesh_core::sha256_hex(&body) != sha256 {
452            return Err(ClientError::new(ErrorCode::BlobMismatch, format!("{url}: content of another hash")));
453        }
454        Ok(body)
455    }
456
457    /// The envelope for `rest` (a cell URI's rest or a call, as the cell endpoint takes it)
458    /// from `host`, checked against `request` (5.5; the host asked is added to it).
459    pub fn cell(&self, host: &str, rest: &str, request: &Request) -> Result<Fetched, ClientError> {
460        let url = self.endpoint(host, "cell", &[("cell", rest)])?;
461        let (status, body) = self.get(&url, MAX_BODY).map_err(ClientError::unavailable)?;
462        let req =
463            request.clone().with_mesh(host).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
464        let answer = self.checked(&body, |keys| check_answer(status, &body, keys, &req))?;
465        Ok(Fetched { status, body, answer })
466    }
467
468    /// The envelope of a reference (pinned or not) from `host`: its URI written by the core,
469    /// the request it describes made from it (the cell id needs the function hash: the pin,
470    /// else the binding `host` states as of the reference's asof).
471    pub fn reference(&self, host: &str, reference: &Reference) -> Result<Fetched, ClientError> {
472        let fn_hash = match &reference.fn_hash {
473            Some(h) => h.clone(),
474            None => {
475                let name = format!("{}/{}", reference.ns, reference.fn_name);
476                self.binding(host, &name, reference.asof.as_deref())?
477                    .ok_or_else(|| ClientError::new(ErrorCode::NameUnbound, name.clone()))?
478                    .fn_hash
479            }
480        };
481        let cell = reference.resolve(&fn_hash).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
482        let mut request = Request::new(&cell.id(), reference.asof.as_deref())
483            .map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
484        if let Some(p) = &reference.fn_hash {
485            request = request.with_pin(p).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
486        }
487        let uri = format_reference(reference);
488        self.cell(host, &uri["cell://".len()..], &request)
489    }
490
491    /// The slice a slice URI's rest denotes on `host`: the descriptor of its pin, or of the
492    /// name's binding (as of its asof), parsed against.
493    pub fn slice_of(&self, host: &str, rest: &str) -> Result<(Slice, Reference), ClientError> {
494        let uri = format!("cell://{rest}");
495        let path = rest.split('?').next().unwrap_or(rest);
496        let query = rest.split_once('?').map(|(_, q)| q).unwrap_or("");
497        let pin = query.split('&').find_map(|p| p.strip_prefix("fn_hash=")).map(str::to_string);
498        let asof = query.split('&').next_back().and_then(|p| p.strip_prefix("asof=")).map(str::to_string);
499        let fn_hash = match pin {
500            Some(p) => p,
501            None => {
502                self.binding(host, path, asof.as_deref())?
503                    .ok_or_else(|| ClientError::new(ErrorCode::NameUnbound, path.to_string()))?
504                    .fn_hash
505            }
506        };
507        let d = FunctionDescriptor::from_json(&self.descriptor(host, &fn_hash)?)
508            .map_err(|e| ClientError::new(e.code(), e.to_string()))?;
509        let r =
510            parse_reference(&uri, &d.signature.to_value()).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
511        let cell = r.resolve(&fn_hash).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
512        let slice = Slice::from_value(&cell.to_value()).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
513        Ok((slice, r))
514    }
515
516    /// A page of a slice from `host` (5.6): the first page of `rest` (a slice URI's rest), or,
517    /// with `next`, the page that URL names (which must be on `host`), checked against the
518    /// slice `rest` denotes and, for a following page, the cursor `after`.
519    pub fn slice_page(
520        &self,
521        host: &str,
522        rest: &str,
523        next: Option<&str>,
524        after: Option<BTreeMap<String, datumesh_core::Scalar>>,
525    ) -> Result<Fetched, ClientError> {
526        let (slice, r) = self.slice_of(host, rest)?;
527        let url = match next {
528            Some(n) => {
529                if !n.starts_with(&format!("https://{host}/")) {
530                    return Err(ClientError::new(ErrorCode::Envelope, format!("{n} is not on {host}")));
531                }
532                n.to_string()
533            }
534            None => self.endpoint(host, "slice", &[("cell", rest)])?,
535        };
536        let (status, body) = self.get(&url, MAX_BODY).map_err(ClientError::unavailable)?;
537        let mut req = SliceRequest::new(slice.id(), r.asof.as_deref())
538            .and_then(|q| q.with_mesh(host))
539            .map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
540        if let Some(p) = &r.fn_hash {
541            req = req.with_pin(p).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
542        }
543        if let Some(a) = after {
544            req = req.with_after(a);
545        }
546        let answer = self.checked(&body, |keys| check_slice_answer(status, &body, keys, &req))?;
547        Ok(Fetched { status, body, answer })
548    }
549
550    /// The first page of a slice (see [`Client::slice_page`]).
551    pub fn slice(&self, host: &str, rest: &str, next: Option<&str>) -> Result<Fetched, ClientError> {
552        self.slice_page(host, rest, next, None)
553    }
554
555    /// A batch (5.7) to `host`: the requests' rests and the request each describes, checked as
556    /// a whole and item by item.
557    pub fn batch(&self, host: &str, items: &[String], requests: &[Request]) -> Result<Batch, ClientError> {
558        let url = self.endpoint(host, "cells", &[])?;
559        let body = Value::Array(items.iter().map(|i| Value::String(i.clone())).collect()).to_jcs();
560        let (status, resp) = self.request(&url, Some(&body), MAX_BODY).map_err(ClientError::unavailable)?;
561        let reqs: Vec<Request> =
562            requests.iter().map(|r| r.clone().with_mesh(host).unwrap_or_else(|_| r.clone())).collect();
563        self.checked(&resp, |keys| check_batch(status, &resp, keys, &reqs))
564    }
565
566    /// The versions of a stored cell from `host` (9.8): `rest` is its URI's rest without asof.
567    pub fn versions(&self, host: &str, rest: &str) -> Result<Versions, ClientError> {
568        let url = self.endpoint(host, "versions", &[("cell", rest)])?;
569        self.versions_at(&url)
570    }
571
572    /// A page of the versions endpoint at `url` (a `next`).
573    pub fn versions_at(&self, url: &str) -> Result<Versions, ClientError> {
574        let (status, body) = self.get(url, MAX_BODY).map_err(ClientError::unavailable)?;
575        let v = json::parse(&body).map_err(|e| ClientError::unavailable(format!("{url}: {e}")))?;
576        if status != 200 {
577            let code = v
578                .get("error")
579                .and_then(Value::as_str)
580                .and_then(ErrorCode::from_code)
581                .unwrap_or(ErrorCode::InputUnavailable);
582            return Err(ClientError::new(code, format!("{url}: status {status}")));
583        }
584        let cell = v.get("cell").cloned().ok_or_else(|| ClientError::unavailable(format!("{url}: no cell")))?;
585        let mut versions = Vec::new();
586        if let Some(Value::Array(vs)) = v.get("versions") {
587            for x in vs {
588                let s = |k: &str| x.get(k).and_then(Value::as_str).map(str::to_string);
589                match (s("tx"), s("asof"), s("receipt")) {
590                    (Some(tx), Some(asof), Some(receipt)) => versions.push(VersionEntry { tx, asof, receipt }),
591                    _ => return Err(ClientError::unavailable(format!("{url}: a malformed version"))),
592                }
593            }
594        }
595        Ok(Versions { cell, versions, next: v.get("next").and_then(Value::as_str).map(str::to_string) })
596    }
597
598    /// A receipt fetched by the client, parsed.
599    pub fn parse_receipt(bytes: &[u8]) -> Result<Receipt, ClientError> {
600        Receipt::from_json(bytes).map_err(|e| ClientError::new(e.code(), e.to_string()))
601    }
602}
603
604fn collect_signers(v: &Value, hosts: &mut BTreeSet<String>) {
605    match v {
606        Value::Object(m) => {
607            for (k, x) in m {
608                if k == "computed_by" {
609                    if let Some(s) = x.as_str() {
610                        hosts.insert(s.split('#').next().unwrap_or("").to_string());
611                    }
612                } else {
613                    collect_signers(x, hosts);
614                }
615            }
616        }
617        Value::Array(a) => a.iter().for_each(|x| collect_signers(x, hosts)),
618        _ => {}
619    }
620}
621
622/// The host of a function name.
623pub fn name_host(name: &str) -> &str {
624    host_of(name)
625}