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        // The system resolver's failure arrives as an I/O error, not `HostNotFound`.
84        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/// The client's configuration.
107#[non_exhaustive]
108#[derive(Clone, Debug)]
109pub struct ClientConfig {
110    /// Origins to use instead of `https://<host>` for some hosts (tests, private networks).
111    pub peers: BTreeMap<String, String>,
112    /// When set, the only hosts fetched from.
113    pub allowed: Option<Vec<String>>,
114    /// The time limit of one request (default 10 s).
115    pub timeout: Duration,
116    /// Key documents' lifetime in the cache (default 300 s).
117    pub key_ttl: Duration,
118    /// The shortest interval between two fetches of one host's key document (default 10 s).
119    pub key_refetch: Duration,
120    /// Mesh documents' lifetime in the cache (default 300 s).
121    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/// A binding another mesh states (SPEC 9.7).
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct RemoteBinding {
140    /// The function hash.
141    pub fn_hash: String,
142    /// When the binding began.
143    pub since: String,
144}
145
146/// An answer fetched and checked: its HTTP status, its body as received, and the checked answer.
147#[derive(Clone, Debug)]
148pub struct Fetched {
149    /// The HTTP status.
150    pub status: u16,
151    /// The body.
152    pub body: Vec<u8>,
153    /// The answer, checked against the request.
154    pub answer: Answer,
155}
156
157/// One version a mesh lists (SPEC 9.8).
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub struct VersionEntry {
160    /// The version's `tx`.
161    pub tx: String,
162    /// Its receipt's `asof`.
163    pub asof: String,
164    /// Its receipt hash.
165    pub receipt: String,
166}
167
168/// A page of the versions endpoint (SPEC 9.8).
169#[derive(Clone, Debug)]
170pub struct Versions {
171    /// The cell (4.4).
172    pub cell: Value,
173    /// The versions, ascending by `tx`.
174    pub versions: Vec<VersionEntry>,
175    /// The following page's URL.
176    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/// The client (see the module documentation).
187#[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
198/// Percent-encodes a value as SPEC 5.1 says (literal characters as themselves).
199pub 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    /// A client with this configuration.
217    pub fn new(cfg: ClientConfig) -> Client {
218        Client::with_keys(cfg, Arc::new(KeyCache::default()))
219    }
220
221    /// A client sharing a key cache (the mesh's, so `POST /verify` sees what it fetched).
222    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    /// The key cache.
234    pub fn keys(&self) -> &Arc<KeyCache> {
235        &self.inner.keys
236    }
237
238    /// Whether `host` may be fetched from.
239    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    /// `GET url` (an `https://<host>/...` URL; the origin replaced for a configured peer):
254    /// status and body, at most `limit` bytes.
255    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    /// A request to another mesh whose failure is a [`ClientError`]: `E_FOREIGN_UNAVAILABLE`
264    /// (spec-0.4.3) with its detail (`offline`, `network`, `dns`, `tls`, `timeout`, `refused`)
265    /// when no HTTP response came back, `E_INPUT_UNAVAILABLE` for a failure after a response
266    /// began (a body that could not be read, a host not allowed). A mesh that answered, with
267    /// any status, is not this function's failure. Since the cross-mesh failure change.
268    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    /// [`request`](Client::request), its failure with the `E_FOREIGN_UNAVAILABLE` detail when no
276    /// HTTP response came back.
277    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    /// The key document of `host` (SPEC 9.3), from the cache while it is fresh, else fetched;
305    /// `refresh` fetches it again unless it was fetched within the refetch interval.
306    pub fn key_document(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
307        self.key_document_with(host, refresh)
308    }
309
310    /// [`key_document`](Client::key_document) of a function's publisher, before this mesh
311    /// computes the function (its declarations, SPEC 8.5): a fetch that got no HTTP response
312    /// is `E_FOREIGN_UNAVAILABLE` (spec-0.4.3), its detail first in
313    /// [`ClientError::detail`] ([`ClientError::foreign_detail`]). Since 0.2.1.
314    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    /// The bytes of `host`'s key document as last fetched.
338    pub fn key_document_bytes(&self, host: &str) -> Option<Vec<u8>> {
339        self.inner.keys.get(host).map(|(_, b, _)| b)
340    }
341
342    /// The mesh document of `host`, resolved with its key document (SPEC 9.6), cached.
343    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            // No response from the host: E_FOREIGN_UNAVAILABLE with why.
368            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    /// The binding of `name` that `host`'s bindings resource states as of `asof` (now when
398    /// `None`), SPEC 9.7.
399    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    /// The descriptor `fn_hash` names, from `host` (its hash checked).
428    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    /// The keys of the signers named in a body (a receipt, an envelope, a page or a batch):
442    /// each signer's key document, from its own host.
443    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    /// Runs `check` with the signers' keys, fetching them again once when a key id is unknown
479    /// (a rotation).
480    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    /// A receipt by its hash from `host`: its hash checked and its signature verified (SPEC
498    /// 10.1 steps 1-6) against its signer's key document.
499    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    /// A slice manifest from `host` (its entry checked).
519    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    /// Blob content by SHA-256 from `host` (its hash checked).
533    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    /// The envelope for `rest` (a cell URI's rest or a call, as the cell endpoint takes it)
546    /// from `host`, checked against `request` (5.5; the host asked is added to it).
547    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    /// The envelope of a reference (pinned or not) from `host`: its URI written by the core,
557    /// the request it describes made from it (the cell id needs the function hash: the pin,
558    /// else the binding `host` states as of the reference's asof).
559    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    /// The slice a slice URI's rest denotes on `host`: the descriptor of its pin, or of the
580    /// name's binding (as of its asof), parsed against.
581    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    /// A page of a slice from `host` (5.6): the first page of `rest` (a slice URI's rest), or,
605    /// with `next`, the page that URL names (which must be on `host`), checked against the
606    /// slice `rest` denotes and, for a following page, the cursor `after`.
607    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    /// The first page of a slice (see [`Client::slice_page`]).
639    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    /// A batch (5.7) to `host`: the requests' rests and the request each describes, checked as
644    /// a whole and item by item.
645    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    /// The versions of a stored cell from `host` (9.8): `rest` is its URI's rest without asof.
655    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    /// A page of the versions endpoint at `url` (a `next`).
661    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    /// A receipt fetched by the client, parsed.
687    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
710/// The host of a function name.
711pub fn name_host(name: &str) -> &str {
712    host_of(name)
713}