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        // Windows' resolver (CONTRACT-1.8b H3): WSAHOST_NOT_FOUND (11001) to WSANO_DATA (11004),
86        // or its text.
87        ureq::Error::Io(io)
88            if io.raw_os_error().is_some_and(|c| (11001..=11004).contains(&c))
89                || io.to_string().to_ascii_lowercase().contains("no such host is known") =>
90        {
91            ForeignDetail::Dns
92        }
93        ureq::Error::Io(io) => match io.kind() {
94            ErrorKind::ConnectionRefused => ForeignDetail::Refused,
95            ErrorKind::TimedOut => ForeignDetail::Timeout,
96            _ => ForeignDetail::Network,
97        },
98        ureq::Error::ConnectionFailed => ForeignDetail::Network,
99        ureq::Error::Tls(_) | ureq::Error::Rustls(_) | ureq::Error::Pem(_) | ureq::Error::TlsRequired => {
100            ForeignDetail::Tls
101        }
102        _ => return None,
103    })
104}
105
106impl std::fmt::Display for ClientError {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        write!(f, "{}: {}", self.code.as_str(), self.detail)
109    }
110}
111
112impl std::error::Error for ClientError {}
113
114/// The client's configuration.
115#[non_exhaustive]
116#[derive(Clone, Debug)]
117pub struct ClientConfig {
118    /// Origins to use instead of `https://<host>` for some hosts (tests, private networks).
119    pub peers: BTreeMap<String, String>,
120    /// When set, the only hosts fetched from.
121    pub allowed: Option<Vec<String>>,
122    /// The time limit of one request (default 10 s).
123    pub timeout: Duration,
124    /// Key documents' lifetime in the cache (default 300 s).
125    pub key_ttl: Duration,
126    /// The shortest interval between two fetches of one host's key document (default 10 s).
127    pub key_refetch: Duration,
128    /// Mesh documents' lifetime in the cache (default 300 s).
129    pub mesh_ttl: Duration,
130}
131
132impl Default for ClientConfig {
133    fn default() -> Self {
134        ClientConfig {
135            peers: BTreeMap::new(),
136            allowed: None,
137            timeout: Duration::from_secs(10),
138            key_ttl: Duration::from_secs(300),
139            key_refetch: Duration::from_secs(10),
140            mesh_ttl: Duration::from_secs(300),
141        }
142    }
143}
144
145/// A binding another mesh states (SPEC 9.7).
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct RemoteBinding {
148    /// The function hash.
149    pub fn_hash: String,
150    /// When the binding began.
151    pub since: String,
152}
153
154/// An answer fetched and checked: its HTTP status, its body as received, and the checked answer.
155#[derive(Clone, Debug)]
156pub struct Fetched {
157    /// The HTTP status.
158    pub status: u16,
159    /// The body.
160    pub body: Vec<u8>,
161    /// The answer, checked against the request.
162    pub answer: Answer,
163}
164
165/// One version a mesh lists (SPEC 9.8).
166#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct VersionEntry {
168    /// The version's `tx`.
169    pub tx: String,
170    /// Its receipt's `asof`.
171    pub asof: String,
172    /// Its receipt hash.
173    pub receipt: String,
174}
175
176/// A page of the versions endpoint (SPEC 9.8).
177#[derive(Clone, Debug)]
178pub struct Versions {
179    /// The cell (4.4).
180    pub cell: Value,
181    /// The versions, ascending by `tx`.
182    pub versions: Vec<VersionEntry>,
183    /// The following page's URL.
184    pub next: Option<String>,
185}
186
187struct Inner {
188    agent: ureq::Agent,
189    cfg: ClientConfig,
190    keys: Arc<KeyCache>,
191    meshes: Mutex<HashMap<String, (MeshDoc, Instant)>>,
192}
193
194/// The client (see the module documentation).
195#[derive(Clone)]
196pub struct Client {
197    inner: Arc<Inner>,
198}
199
200impl std::fmt::Debug for Client {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        f.debug_struct("Client").field("allowed", &self.inner.cfg.allowed).finish_non_exhaustive()
203    }
204}
205
206/// Percent-encodes a value as SPEC 5.1 says (literal characters as themselves).
207pub fn pct(s: &str) -> String {
208    let mut out = String::with_capacity(s.len());
209    for b in s.bytes() {
210        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b':') {
211            out.push(b as char);
212        } else {
213            out.push_str(&format!("%{b:02X}"));
214        }
215    }
216    out
217}
218
219fn host_of(name: &str) -> &str {
220    name.split('/').next().unwrap_or(name)
221}
222
223impl Client {
224    /// A client with this configuration.
225    pub fn new(cfg: ClientConfig) -> Client {
226        Client::with_keys(cfg, Arc::new(KeyCache::default()))
227    }
228
229    /// A client sharing a key cache (the mesh's, so `POST /verify` sees what it fetched).
230    pub fn with_keys(cfg: ClientConfig, keys: Arc<KeyCache>) -> Client {
231        let agent: ureq::Agent = ureq::Agent::config_builder()
232            .max_redirects(0)
233            .http_status_as_error(false)
234            .timeout_global(Some(cfg.timeout))
235            .user_agent(concat!("datumesh-http/", env!("CARGO_PKG_VERSION")))
236            .build()
237            .into();
238        Client { inner: Arc::new(Inner { agent, cfg, keys, meshes: Mutex::new(HashMap::new()) }) }
239    }
240
241    /// The key cache.
242    pub fn keys(&self) -> &Arc<KeyCache> {
243        &self.inner.keys
244    }
245
246    /// Whether `host` may be fetched from.
247    pub fn allowed(&self, host: &str) -> bool {
248        self.inner.cfg.allowed.as_ref().is_none_or(|a| a.iter().any(|h| h == host))
249    }
250
251    fn check_host(&self, host: &str) -> Result<(), ClientError> {
252        if lexical::check_dns_name(host, "$").is_err() {
253            return Err(ClientError::new(ErrorCode::KeyUnavailable, format!("{host:?} is not a DNS name")));
254        }
255        if !self.allowed(host) {
256            return Err(ClientError::unavailable(format!("{host} is not an allowed host")));
257        }
258        Ok(())
259    }
260
261    /// `GET url` (an `https://<host>/...` URL; the origin replaced for a configured peer):
262    /// status and body, at most `limit` bytes.
263    pub fn get(&self, url: &str, limit: u64) -> Result<(u16, Vec<u8>), String> {
264        self.request(url, None, limit)
265    }
266
267    fn request(&self, url: &str, post: Option<&[u8]>, limit: u64) -> Result<(u16, Vec<u8>), String> {
268        self.request_with_detail(url, post, limit).map_err(|(m, _)| m)
269    }
270
271    /// A request to another mesh whose failure is a [`ClientError`]: `E_FOREIGN_UNAVAILABLE`
272    /// (spec-0.4.3) with its detail (`offline`, `network`, `dns`, `tls`, `timeout`, `refused`)
273    /// when no HTTP response came back, `E_INPUT_UNAVAILABLE` for a failure after a response
274    /// began (a body that could not be read, a host not allowed). A mesh that answered, with
275    /// any status, is not this function's failure. Since the cross-mesh failure change.
276    fn fetch(&self, url: &str, post: Option<&[u8]>, limit: u64) -> Result<(u16, Vec<u8>), ClientError> {
277        self.request_with_detail(url, post, limit).map_err(|(m, d)| match d {
278            Some(d) => ClientError::foreign(d, m),
279            None => ClientError::unavailable(m),
280        })
281    }
282
283    /// [`request`](Client::request), its failure with the `E_FOREIGN_UNAVAILABLE` detail when no
284    /// HTTP response came back.
285    fn request_with_detail(
286        &self,
287        url: &str,
288        post: Option<&[u8]>,
289        limit: u64,
290    ) -> Result<(u16, Vec<u8>), (String, Option<ForeignDetail>)> {
291        let mut target = url.to_string();
292        if let Some(rest) = url.strip_prefix("https://") {
293            let host = rest.split(['/', '?']).next().unwrap_or("");
294            if !self.allowed(host) {
295                return Err((format!("{host} is not an allowed host"), None));
296            }
297            if let Some(origin) = self.inner.cfg.peers.get(host) {
298                target = format!("{origin}{}", &rest[host.len()..]);
299            }
300        }
301        let resp = match post {
302            None => self.inner.agent.get(&target).call(),
303            Some(b) => self.inner.agent.post(&target).header("content-type", "application/json").send(b),
304        };
305        let mut resp = resp.map_err(|e| (format!("{url}: {e}"), transport_detail(&e)))?;
306        let status = resp.status().as_u16();
307        let body =
308            resp.body_mut().with_config().limit(limit).read_to_vec().map_err(|e| (format!("{url}: {e}"), None))?;
309        Ok((status, body))
310    }
311
312    /// The key document of `host` (SPEC 9.3), from the cache while it is fresh, else fetched;
313    /// `refresh` fetches it again unless it was fetched within the refetch interval.
314    pub fn key_document(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
315        self.key_document_with(host, refresh)
316    }
317
318    /// [`key_document`](Client::key_document) of a function's publisher, before this mesh
319    /// computes the function (its declarations, SPEC 8.5): a fetch that got no HTTP response
320    /// is `E_FOREIGN_UNAVAILABLE` (spec-0.4.3), its detail first in
321    /// [`ClientError::detail`] ([`ClientError::foreign_detail`]). Since 0.2.1.
322    pub fn publisher_key_document(&self, host: &str) -> Result<KeyDoc, ClientError> {
323        self.key_document_with(host, false)
324    }
325
326    fn key_document_with(&self, host: &str, refresh: bool) -> Result<KeyDoc, ClientError> {
327        if let Some((doc, _, at)) = self.inner.keys.get(host) {
328            let age = at.elapsed();
329            if (!refresh && age < self.inner.cfg.key_ttl) || (refresh && age < self.inner.cfg.key_refetch) {
330                return Ok(doc);
331            }
332        }
333        self.check_host(host)?;
334        let url = format!("https://{host}/.well-known/datumesh.json");
335        let (status, body) = self.request_with_detail(&url, None, MAX_DOC).map_err(|(e, d)| match d {
336            Some(d) => ClientError::foreign(d, e),
337            None => ClientError::new(ErrorCode::KeyUnavailable, e),
338        })?;
339        let doc = keys_from_response(host, status, if status == 200 { Some(&body) } else { None })
340            .map_err(|e| ClientError::new(e.code(), e.to_string()))?;
341        self.inner.keys.insert(host, &body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
342        Ok(doc)
343    }
344
345    /// The bytes of `host`'s key document as last fetched.
346    pub fn key_document_bytes(&self, host: &str) -> Option<Vec<u8>> {
347        self.inner.keys.get(host).map(|(_, b, _)| b)
348    }
349
350    /// The mesh document of `host`, resolved with its key document (SPEC 9.6), cached.
351    pub fn resolve(&self, host: &str) -> Result<MeshDoc, ClientError> {
352        if let Some((m, at)) = self.inner.meshes.lock().unwrap_or_else(|p| p.into_inner()).get(host) {
353            if at.elapsed() < self.inner.cfg.mesh_ttl {
354                return Ok(m.clone());
355            }
356        }
357        self.check_host(host)?;
358        type Got = Result<(u16, Vec<u8>), (String, Option<ForeignDetail>)>;
359        let get = |path: &str| -> Got {
360            let url = format!("https://{host}/.well-known/{path}");
361            self.request_with_detail(&url, None, MAX_DOC)
362        };
363        let keys: Got = get("datumesh.json");
364        let mesh: Got = match &keys {
365            Ok((200, _)) => get("datumesh-mesh.json"),
366            _ => Err((String::new(), None)),
367        };
368        fn ret(r: &Got) -> Retrieval<'_> {
369            match r {
370                Ok((s, b)) => Retrieval::Response { status: *s, body: Some(b.as_slice()) },
371                Err(_) => Retrieval::Failed,
372            }
373        }
374        let resolved = resolve_mesh(host, ret(&keys), ret(&mesh)).map_err(|e| {
375            // No response from the host: E_FOREIGN_UNAVAILABLE with why.
376            for r in [&keys, &mesh] {
377                if let Err((why, Some(d))) = r {
378                    return ClientError::foreign(*d, why);
379                }
380            }
381            let detail = match (&keys, &mesh) {
382                (Err((e, _)), _) | (_, Err((e, _))) if !e.is_empty() => e.clone(),
383                _ => e.to_string(),
384            };
385            ClientError::new(e.code(), detail)
386        })?;
387        if let Ok((_, body)) = &keys {
388            let _ = self.inner.keys.insert(host, body);
389        }
390        let m = resolved.mesh;
391        self.inner
392            .meshes
393            .lock()
394            .unwrap_or_else(|p| p.into_inner())
395            .insert(host.to_string(), (m.clone(), Instant::now()));
396        Ok(m)
397    }
398
399    fn endpoint(&self, host: &str, name: &str, values: &[(&str, &str)]) -> Result<String, ClientError> {
400        self.resolve(host)?
401            .url(name, values)
402            .ok_or_else(|| ClientError::new(ErrorCode::MeshDoc, format!("{host} has no {name} endpoint")))
403    }
404
405    /// The binding of `name` that `host`'s bindings resource states as of `asof` (now when
406    /// `None`), SPEC 9.7.
407    pub fn binding(&self, host: &str, name: &str, asof: Option<&str>) -> Result<Option<RemoteBinding>, ClientError> {
408        let mesh = self.resolve(host)?;
409        let mut url = format!("{}?name={}", mesh.bindings, pct(name));
410        if let Some(a) = asof {
411            url.push_str(&format!("&asof={}", pct(a)));
412        }
413        let (status, body) = self.fetch(&url, None, MAX_DOC)?;
414        if status != 200 {
415            return Err(ClientError::unavailable(format!("{url}: status {status}")));
416        }
417        let v = json::parse(&body).map_err(|e| ClientError::unavailable(format!("{url}: {e}")))?;
418        let Some(b) = v.get("bindings").and_then(|b| b.get(name)) else {
419            if v.get("bindings").and_then(Value::as_object).is_none() {
420                return Err(ClientError::unavailable(format!("{url}: no bindings object")));
421            }
422            return Ok(None);
423        };
424        let h = b.get("fn_hash").and_then(Value::as_str).unwrap_or("");
425        let since = b.get("since").and_then(Value::as_str).unwrap_or("");
426        if lexical::check_hex(h, 64, "$").is_err() || lexical::check_instant(since, "$").is_err() {
427            return Err(ClientError::unavailable(format!("{url}: malformed binding")));
428        }
429        if asof.is_some_and(|a| since > a) {
430            return Err(ClientError::unavailable(format!("{url}: a binding since after the asof")));
431        }
432        Ok(Some(RemoteBinding { fn_hash: h.to_string(), since: since.to_string() }))
433    }
434
435    /// The descriptor `fn_hash` names, from `host` (its hash checked).
436    pub fn descriptor(&self, host: &str, fn_hash: &str) -> Result<Vec<u8>, ClientError> {
437        let url = self.endpoint(host, "descriptor", &[("hash", fn_hash)])?;
438        let (status, body) = self.fetch(&url, None, MAX_BODY)?;
439        if status != 200 {
440            return Err(ClientError::new(ErrorCode::FnUnavailable, format!("{url}: status {status}")));
441        }
442        let d = FunctionDescriptor::from_json(&body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
443        if d.hash() != fn_hash {
444            return Err(ClientError::new(ErrorCode::FnHashMismatch, format!("{url} gave the descriptor {}", d.hash())));
445        }
446        Ok(body)
447    }
448
449    /// The keys of the signers named in a body (a receipt, an envelope, a page or a batch):
450    /// each signer's key document, from its own host.
451    pub fn keys_for_body(&self, body: &[u8]) -> Keys {
452        let mut hosts = BTreeSet::new();
453        fn walk(v: &Value, hosts: &mut BTreeSet<String>, depth: usize) {
454            if depth > 8 {
455                return;
456            }
457            match v {
458                Value::Object(m) => {
459                    for (k, x) in m {
460                        if k == "computed_by" {
461                            if let Some(s) = x.as_str() {
462                                hosts.insert(s.split('#').next().unwrap_or("").to_string());
463                            }
464                        } else {
465                            walk(x, hosts, depth + 1);
466                        }
467                    }
468                }
469                Value::Array(a) => a.iter().for_each(|x| walk(x, hosts, depth + 1)),
470                _ => {}
471            }
472        }
473        if let Ok(v) = json::parse(body) {
474            walk(&v, &mut hosts, 0);
475        }
476        let mut keys = Keys::new();
477        for h in hosts {
478            match self.key_document(&h, false) {
479                Ok(d) => keys.insert(d),
480                Err(e) => keys.insert_result(&h, Err(datumesh_core::Error::new(e.code, "$", e.detail))),
481            }
482        }
483        keys
484    }
485
486    /// Runs `check` with the signers' keys, fetching them again once when a key id is unknown
487    /// (a rotation).
488    fn checked<T>(&self, body: &[u8], check: impl Fn(&Keys) -> datumesh_core::Result<T>) -> Result<T, ClientError> {
489        let keys = self.keys_for_body(body);
490        match check(&keys) {
491            Err(e) if matches!(e.code(), ErrorCode::KeyUnknown | ErrorCode::KeyNotValid) => {
492                let mut hosts = BTreeSet::new();
493                if let Ok(v) = json::parse(body) {
494                    collect_signers(&v, &mut hosts);
495                }
496                for h in hosts {
497                    let _ = self.key_document(&h, true);
498                }
499                check(&self.keys_for_body(body)).map_err(|e| ClientError::new(e.code(), e.to_string()))
500            }
501            r => r.map_err(|e| ClientError::new(e.code(), e.to_string())),
502        }
503    }
504
505    /// A receipt by its hash from `host`: its hash checked and its signature verified (SPEC
506    /// 10.1 steps 1-6) against its signer's key document.
507    pub fn receipt(&self, host: &str, hash: &str) -> Result<Vec<u8>, ClientError> {
508        let url = self.endpoint(host, "receipt", &[("hash", hash)])?;
509        let (status, body) = self.fetch(&url, None, MAX_BODY)?;
510        if status != 200 {
511            return Err(ClientError::unavailable(format!("{url}: status {status}")));
512        }
513        let h = self.checked(&body, |keys| {
514            let r = datumesh_core::verify(&body, keys, None, None);
515            match r.error() {
516                Some(e) => Err(e),
517                None => Ok(r.hash.unwrap_or_default()),
518            }
519        })?;
520        if h != hash {
521            return Err(ClientError::unavailable(format!("{url} gave the receipt {h}")));
522        }
523        Ok(body)
524    }
525
526    /// A slice manifest from `host` (its entry checked).
527    pub fn manifest(&self, host: &str, slice_id: &str, members_hash: &str) -> Result<Vec<u8>, ClientError> {
528        let url = self.endpoint(host, "manifest", &[("slice_id", slice_id), ("members_hash", members_hash)])?;
529        let (status, body) = self.fetch(&url, None, MAX_BODY)?;
530        if status != 200 {
531            return Err(ClientError::unavailable(format!("{url}: status {status}")));
532        }
533        let m = Manifest::from_json(&body).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
534        if m.entry() != format!("slice:{slice_id}:{members_hash}") {
535            return Err(ClientError::unavailable(format!("{url} gave the manifest {}", m.entry())));
536        }
537        Ok(body)
538    }
539
540    /// Blob content by SHA-256 from `host` (its hash checked).
541    pub fn blob(&self, host: &str, sha256: &str) -> Result<Vec<u8>, ClientError> {
542        let url = self.endpoint(host, "blob", &[("sha256", sha256)])?;
543        let (status, body) = self.fetch(&url, None, MAX_BODY)?;
544        if status != 200 {
545            return Err(ClientError::unavailable(format!("{url}: status {status}")));
546        }
547        if datumesh_core::sha256_hex(&body) != sha256 {
548            return Err(ClientError::new(ErrorCode::BlobMismatch, format!("{url}: content of another hash")));
549        }
550        Ok(body)
551    }
552
553    /// The envelope for `rest` (a cell URI's rest or a call, as the cell endpoint takes it)
554    /// from `host`, checked against `request` (5.5; the host asked is added to it).
555    pub fn cell(&self, host: &str, rest: &str, request: &Request) -> Result<Fetched, ClientError> {
556        let url = self.endpoint(host, "cell", &[("cell", rest)])?;
557        let (status, body) = self.fetch(&url, None, MAX_BODY)?;
558        let req =
559            request.clone().with_mesh(host).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
560        let answer = self.checked(&body, |keys| check_answer(status, &body, keys, &req))?;
561        Ok(Fetched { status, body, answer })
562    }
563
564    /// The envelope of a reference (pinned or not) from `host`: its URI written by the core,
565    /// the request it describes made from it (the cell id needs the function hash: the pin,
566    /// else the binding `host` states as of the reference's asof).
567    pub fn reference(&self, host: &str, reference: &Reference) -> Result<Fetched, ClientError> {
568        let fn_hash = match &reference.fn_hash {
569            Some(h) => h.clone(),
570            None => {
571                let name = format!("{}/{}", reference.ns, reference.fn_name);
572                self.binding(host, &name, reference.asof.as_deref())?
573                    .ok_or_else(|| ClientError::new(ErrorCode::NameUnbound, name.clone()))?
574                    .fn_hash
575            }
576        };
577        let cell = reference.resolve(&fn_hash).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
578        let mut request = Request::new(&cell.id(), reference.asof.as_deref())
579            .map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
580        if let Some(p) = &reference.fn_hash {
581            request = request.with_pin(p).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
582        }
583        let uri = format_reference(reference);
584        self.cell(host, &uri["cell://".len()..], &request)
585    }
586
587    /// The slice a slice URI's rest denotes on `host`: the descriptor of its pin, or of the
588    /// name's binding (as of its asof), parsed against.
589    pub fn slice_of(&self, host: &str, rest: &str) -> Result<(Slice, Reference), ClientError> {
590        let uri = format!("cell://{rest}");
591        let path = rest.split('?').next().unwrap_or(rest);
592        let query = rest.split_once('?').map(|(_, q)| q).unwrap_or("");
593        let pin = query.split('&').find_map(|p| p.strip_prefix("fn_hash=")).map(str::to_string);
594        let asof = query.split('&').next_back().and_then(|p| p.strip_prefix("asof=")).map(str::to_string);
595        let fn_hash = match pin {
596            Some(p) => p,
597            None => {
598                self.binding(host, path, asof.as_deref())?
599                    .ok_or_else(|| ClientError::new(ErrorCode::NameUnbound, path.to_string()))?
600                    .fn_hash
601            }
602        };
603        let d = FunctionDescriptor::from_json(&self.descriptor(host, &fn_hash)?)
604            .map_err(|e| ClientError::new(e.code(), e.to_string()))?;
605        let r =
606            parse_reference(&uri, &d.signature.to_value()).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
607        let cell = r.resolve(&fn_hash).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
608        let slice = Slice::from_value(&cell.to_value()).map_err(|e| ClientError::new(e.code(), e.to_string()))?;
609        Ok((slice, r))
610    }
611
612    /// A page of a slice from `host` (5.6): the first page of `rest` (a slice URI's rest), or,
613    /// with `next`, the page that URL names (which must be on `host`), checked against the
614    /// slice `rest` denotes and, for a following page, the cursor `after`.
615    pub fn slice_page(
616        &self,
617        host: &str,
618        rest: &str,
619        next: Option<&str>,
620        after: Option<BTreeMap<String, datumesh_core::Scalar>>,
621    ) -> Result<Fetched, ClientError> {
622        let (slice, r) = self.slice_of(host, rest)?;
623        let url = match next {
624            Some(n) => {
625                if !n.starts_with(&format!("https://{host}/")) {
626                    return Err(ClientError::new(ErrorCode::Envelope, format!("{n} is not on {host}")));
627                }
628                n.to_string()
629            }
630            None => self.endpoint(host, "slice", &[("cell", rest)])?,
631        };
632        let (status, body) = self.fetch(&url, None, MAX_BODY)?;
633        let mut req = SliceRequest::new(slice.id(), r.asof.as_deref())
634            .and_then(|q| q.with_mesh(host))
635            .map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
636        if let Some(p) = &r.fn_hash {
637            req = req.with_pin(p).map_err(|e| ClientError::new(ErrorCode::Envelope, format!("{e:?}")))?;
638        }
639        if let Some(a) = after {
640            req = req.with_after(a);
641        }
642        let answer = self.checked(&body, |keys| check_slice_answer(status, &body, keys, &req))?;
643        Ok(Fetched { status, body, answer })
644    }
645
646    /// The first page of a slice (see [`Client::slice_page`]).
647    pub fn slice(&self, host: &str, rest: &str, next: Option<&str>) -> Result<Fetched, ClientError> {
648        self.slice_page(host, rest, next, None)
649    }
650
651    /// A batch (5.7) to `host`: the requests' rests and the request each describes, checked as
652    /// a whole and item by item.
653    pub fn batch(&self, host: &str, items: &[String], requests: &[Request]) -> Result<Batch, ClientError> {
654        let url = self.endpoint(host, "cells", &[])?;
655        let body = Value::Array(items.iter().map(|i| Value::String(i.clone())).collect()).to_jcs();
656        let (status, resp) = self.fetch(&url, Some(&body), MAX_BODY)?;
657        let reqs: Vec<Request> =
658            requests.iter().map(|r| r.clone().with_mesh(host).unwrap_or_else(|_| r.clone())).collect();
659        self.checked(&resp, |keys| check_batch(status, &resp, keys, &reqs))
660    }
661
662    /// The versions of a stored cell from `host` (9.8): `rest` is its URI's rest without asof.
663    pub fn versions(&self, host: &str, rest: &str) -> Result<Versions, ClientError> {
664        let url = self.endpoint(host, "versions", &[("cell", rest)])?;
665        self.versions_at(&url)
666    }
667
668    /// A page of the versions endpoint at `url` (a `next`).
669    pub fn versions_at(&self, url: &str) -> Result<Versions, ClientError> {
670        let (status, body) = self.fetch(url, None, MAX_BODY)?;
671        let v = json::parse(&body).map_err(|e| ClientError::unavailable(format!("{url}: {e}")))?;
672        if status != 200 {
673            let code = v
674                .get("error")
675                .and_then(Value::as_str)
676                .and_then(ErrorCode::from_code)
677                .unwrap_or(ErrorCode::InputUnavailable);
678            return Err(ClientError::new(code, format!("{url}: status {status}")));
679        }
680        let cell = v.get("cell").cloned().ok_or_else(|| ClientError::unavailable(format!("{url}: no cell")))?;
681        let mut versions = Vec::new();
682        if let Some(Value::Array(vs)) = v.get("versions") {
683            for x in vs {
684                let s = |k: &str| x.get(k).and_then(Value::as_str).map(str::to_string);
685                match (s("tx"), s("asof"), s("receipt")) {
686                    (Some(tx), Some(asof), Some(receipt)) => versions.push(VersionEntry { tx, asof, receipt }),
687                    _ => return Err(ClientError::unavailable(format!("{url}: a malformed version"))),
688                }
689            }
690        }
691        Ok(Versions { cell, versions, next: v.get("next").and_then(Value::as_str).map(str::to_string) })
692    }
693
694    /// A receipt fetched by the client, parsed.
695    pub fn parse_receipt(bytes: &[u8]) -> Result<Receipt, ClientError> {
696        Receipt::from_json(bytes).map_err(|e| ClientError::new(e.code(), e.to_string()))
697    }
698}
699
700fn collect_signers(v: &Value, hosts: &mut BTreeSet<String>) {
701    match v {
702        Value::Object(m) => {
703            for (k, x) in m {
704                if k == "computed_by" {
705                    if let Some(s) = x.as_str() {
706                        hosts.insert(s.split('#').next().unwrap_or("").to_string());
707                    }
708                } else {
709                    collect_signers(x, hosts);
710                }
711            }
712        }
713        Value::Array(a) => a.iter().for_each(|x| collect_signers(x, hosts)),
714        _ => {}
715    }
716}
717
718/// The host of a function name.
719pub fn name_host(name: &str) -> &str {
720    host_of(name)
721}
722
723#[cfg(test)]
724mod transport_detail_tests {
725    use super::*;
726    use std::io::{self, ErrorKind};
727
728    /// CONTRACT-1.8b H3, test 1: a Windows resolver error code (WSAHOST_NOT_FOUND, 11001) is `dns`.
729    #[test]
730    fn a_windows_resolver_code_is_dns() {
731        let e = ureq::Error::Io(io::Error::from_raw_os_error(11001));
732        assert_eq!(transport_detail(&e), Some(ForeignDetail::Dns));
733    }
734
735    /// CONTRACT-1.8b H3, test 2: the text "No such host is known" is `dns`.
736    #[test]
737    fn no_such_host_is_known_is_dns() {
738        let e = ureq::Error::Io(io::Error::other("No such host is known. (os error 11001)"));
739        assert_eq!(transport_detail(&e), Some(ForeignDetail::Dns));
740    }
741
742    /// CONTRACT-1.8b H3, test 3: everything else is unchanged.
743    #[test]
744    fn a_refused_connection_stays_refused() {
745        let e = ureq::Error::Io(io::Error::from(ErrorKind::ConnectionRefused));
746        assert_eq!(transport_detail(&e), Some(ForeignDetail::Refused));
747    }
748}