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, ForeignDetail, FunctionDescriptor, KeyDoc, Keys, Manifest, MeshDoc,
30    Receipt, Reference, 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    /// `E_FOREIGN_UNAVAILABLE` (spec-0.4.3): no HTTP response came back from the other mesh.
60    /// `detail` starts with the envelope's `detail` name, then `": "` and why.
61    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    /// For `E_FOREIGN_UNAVAILABLE` (spec-0.4.3), the envelope's `detail` (`offline`, `network`,
66    /// `dns`, `tls`, `timeout`, `refused`): the start of [`ClientError::detail`]. `None` for
67    /// every other code. Since 0.2.1.
68    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
76/// Why no HTTP response came back (spec-0.4.3's `detail` of `E_FOREIGN_UNAVAILABLE`), when the
77/// failure is one of those; `None` for a failure after a response began, or of another kind.
78fn 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/// The client's configuration.
105#[non_exhaustive]
106#[derive(Clone, Debug)]
107pub struct ClientConfig {
108    /// Origins to use instead of `https://<host>` for some hosts (tests, private networks).
109    pub peers: BTreeMap<String, String>,
110    /// When set, the only hosts fetched from.
111    pub allowed: Option<Vec<String>>,
112    /// The time limit of one request (default 10 s).
113    pub timeout: Duration,
114    /// Key documents' lifetime in the cache (default 300 s).
115    pub key_ttl: Duration,
116    /// The shortest interval between two fetches of one host's key document (default 10 s).
117    pub key_refetch: Duration,
118    /// Mesh documents' lifetime in the cache (default 300 s).
119    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/// A binding another mesh states (SPEC 9.7).
136#[derive(Clone, Debug, PartialEq, Eq)]
137pub struct RemoteBinding {
138    /// The function hash.
139    pub fn_hash: String,
140    /// When the binding began.
141    pub since: String,
142}
143
144/// An answer fetched and checked: its HTTP status, its body as received, and the checked answer.
145#[derive(Clone, Debug)]
146pub struct Fetched {
147    /// The HTTP status.
148    pub status: u16,
149    /// The body.
150    pub body: Vec<u8>,
151    /// The answer, checked against the request.
152    pub answer: Answer,
153}
154
155/// One version a mesh lists (SPEC 9.8).
156#[derive(Clone, Debug, PartialEq, Eq)]
157pub struct VersionEntry {
158    /// The version's `tx`.
159    pub tx: String,
160    /// Its receipt's `asof`.
161    pub asof: String,
162    /// Its receipt hash.
163    pub receipt: String,
164}
165
166/// A page of the versions endpoint (SPEC 9.8).
167#[derive(Clone, Debug)]
168pub struct Versions {
169    /// The cell (4.4).
170    pub cell: Value,
171    /// The versions, ascending by `tx`.
172    pub versions: Vec<VersionEntry>,
173    /// The following page's URL.
174    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/// The client (see the module documentation).
185#[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
196/// Percent-encodes a value as SPEC 5.1 says (literal characters as themselves).
197pub 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    /// A client with this configuration.
215    pub fn new(cfg: ClientConfig) -> Client {
216        Client::with_keys(cfg, Arc::new(KeyCache::default()))
217    }
218
219    /// A client sharing a key cache (the mesh's, so `POST /verify` sees what it fetched).
220    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    /// The key cache.
232    pub fn keys(&self) -> &Arc<KeyCache> {
233        &self.inner.keys
234    }
235
236    /// Whether `host` may be fetched from.
237    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    /// `GET url` (an `https://<host>/...` URL; the origin replaced for a configured peer):
252    /// status and body, at most `limit` bytes.
253    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    /// [`request`](Client::request), its failure with the `E_FOREIGN_UNAVAILABLE` detail when no
262    /// HTTP response came back.
263    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    /// The key document of `host` (SPEC 9.3), from the cache while it is fresh, else fetched;
291    /// `refresh` fetches it again unless it was fetched within the refetch interval.
292    pub fn key_document(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
293        self.key_document_with(host, refresh, false)
294    }
295
296    /// [`key_document`](Client::key_document) of a function's publisher, before this mesh
297    /// computes the function (its declarations, SPEC 8.5): a fetch that got no HTTP response
298    /// is `E_FOREIGN_UNAVAILABLE` (spec-0.4.3), its detail first in
299    /// [`ClientError::detail`] ([`ClientError::foreign_detail`]). Since 0.2.1.
300    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    /// The bytes of `host`'s key document as last fetched.
324    pub fn key_document_bytes(&self, host: &str) -> Option<Vec<u8>> {
325        self.inner.keys.get(host).map(|(_, b, _)| b)
326    }
327
328    /// The mesh document of `host`, resolved with its key document (SPEC 9.6), cached.
329    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    /// The binding of `name` that `host`'s bindings resource states as of `asof` (now when
373    /// `None`), SPEC 9.7.
374    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    /// The descriptor `fn_hash` names, from `host` (its hash checked).
403    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    /// The keys of the signers named in a body (a receipt, an envelope, a page or a batch):
417    /// each signer's key document, from its own host.
418    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    /// Runs `check` with the signers' keys, fetching them again once when a key id is unknown
454    /// (a rotation).
455    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    /// A receipt by its hash from `host`: its hash checked and its signature verified (SPEC
473    /// 10.1 steps 1-6) against its signer's key document.
474    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    /// A slice manifest from `host` (its entry checked).
494    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    /// Blob content by SHA-256 from `host` (its hash checked).
508    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    /// The envelope for `rest` (a cell URI's rest or a call, as the cell endpoint takes it)
521    /// from `host`, checked against `request` (5.5; the host asked is added to it).
522    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    /// The envelope of a reference (pinned or not) from `host`: its URI written by the core,
532    /// the request it describes made from it (the cell id needs the function hash: the pin,
533    /// else the binding `host` states as of the reference's asof).
534    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    /// The slice a slice URI's rest denotes on `host`: the descriptor of its pin, or of the
555    /// name's binding (as of its asof), parsed against.
556    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    /// A page of a slice from `host` (5.6): the first page of `rest` (a slice URI's rest), or,
580    /// with `next`, the page that URL names (which must be on `host`), checked against the
581    /// slice `rest` denotes and, for a following page, the cursor `after`.
582    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    /// The first page of a slice (see [`Client::slice_page`]).
614    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    /// A batch (5.7) to `host`: the requests' rests and the request each describes, checked as
619    /// a whole and item by item.
620    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    /// The versions of a stored cell from `host` (9.8): `rest` is its URI's rest without asof.
630    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    /// A page of the versions endpoint at `url` (a `next`).
636    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    /// A receipt fetched by the client, parsed.
662    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
685/// The host of a function name.
686pub fn name_host(name: &str) -> &str {
687    host_of(name)
688}