Skip to main content

datumesh_http/
http.rs

1//! The endpoints: an axum router over a [`Mesh`].
2
3use std::net::{IpAddr, Ipv4Addr, SocketAddr};
4use std::sync::{Arc, Mutex};
5use std::time::{Duration, Instant};
6
7use axum::body::{Body, Bytes};
8use axum::extract::{ConnectInfo, MatchedPath, Path, Query, Request, State};
9use axum::http::{header, HeaderMap, HeaderValue, StatusCode, Uri};
10use axum::middleware::{self, Next};
11use axum::response::{IntoResponse, Response};
12use axum::routing::{get, post};
13use axum::Router;
14use datumesh_core::json::{self, Value};
15use datumesh_core::{lexical, ErrorCode, Pending, Request as CoreRequest};
16use tracing::Instrument;
17use utoipa::OpenApi;
18
19use crate::apikeys::Principal;
20use crate::envelope::{self, Cache, Reply, JSON};
21use crate::jobs::Poll;
22use crate::limit::Client;
23use crate::mesh::{Inner, Memo, Mesh};
24
25/// The principal of a request, for the access log.
26#[derive(Clone)]
27struct Who(Option<String>);
28
29fn to_response(r: Reply) -> Response {
30    let mut resp = Response::new(Body::from(r.body));
31    *resp.status_mut() = StatusCode::from_u16(r.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
32    let h = resp.headers_mut();
33    h.insert(header::CONTENT_TYPE, HeaderValue::from_static(r.content_type));
34    if let Ok(v) = HeaderValue::from_str(&r.cache.header()) {
35        h.insert(header::CACHE_CONTROL, v);
36    }
37    if let Some(c) = r.canonical {
38        if let Ok(v) = HeaderValue::from_str(&format!("<{c}>; rel=\"canonical\"")) {
39            h.insert(header::LINK, v);
40        }
41    }
42    if let Some(s) = r.retry_after {
43        h.insert(header::RETRY_AFTER, HeaderValue::from(s));
44    }
45    resp
46}
47
48fn plain_json(status: u16, v: Value, cache: Cache) -> Response {
49    to_response(Reply::json(status, v.to_jcs(), cache))
50}
51
52fn not_found(what: &str) -> Response {
53    plain_json(404, Value::Object(vec![("error".into(), Value::String(format!("no such {what}")))]), Cache::Public(60))
54}
55
56/// The client: its IP and, with a valid API key, its principal. An `Authorization` header
57/// that is not a key of this mesh is answered `unlicensed`.
58fn who(inner: &Inner, headers: &HeaderMap, peer: IpAddr) -> Result<(Client, Option<Principal>), Reply> {
59    let ip = client_ip(inner, headers, peer);
60    match headers.get(header::AUTHORIZATION) {
61        None => Ok((Client::Ip(ip), None)),
62        Some(v) => {
63            let p = v
64                .to_str()
65                .ok()
66                .and_then(|s| s.strip_prefix("Bearer "))
67                .and_then(|k| inner.config.api_keys.principal(k.trim()));
68            match p {
69                Some(p) => Ok((Client::Key(p.id.clone(), p.per_minute), Some(p.clone()))),
70                None => Err(Reply::json(403, envelope::unlicensed(), Cache::Private)),
71            }
72        }
73    }
74}
75
76fn client_ip(inner: &Inner, headers: &HeaderMap, peer: IpAddr) -> IpAddr {
77    if inner.config.trust_proxy {
78        if let Some(ip) = headers
79            .get("x-forwarded-for")
80            .and_then(|v| v.to_str().ok())
81            .and_then(|s| s.rsplit(',').next())
82            .and_then(|s| s.trim().parse::<IpAddr>().ok())
83        {
84            return ip;
85        }
86    }
87    peer
88}
89
90fn peer_of(req: &Request) -> IpAddr {
91    req.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0.ip()).unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED))
92}
93
94/// `rest` of a `/<prefix>/<rest>` request, query included, as received.
95fn rest_of(uri: &Uri, prefix: &str) -> String {
96    let path = uri.path().strip_prefix(prefix).unwrap_or("");
97    match uri.query() {
98        Some(q) => format!("{path}?{q}"),
99        None => path.to_string(),
100    }
101}
102
103/// Runs `f` on the pool within the request's budget: its reply, or, past the budget, a
104/// `pending` envelope whose job gets the reply when `f` finishes. `f` reports the request
105/// description as soon as it knows it.
106async fn within_budget(
107    inner: Arc<Inner>,
108    f: impl FnOnce(&Inner, &mut dyn FnMut(&crate::call::Target)) -> Reply + Send + 'static,
109) -> Reply {
110    let deadline = tokio::time::Instant::now() + inner.config.budget;
111    let (tx, mut rx) = tokio::sync::watch::channel::<Option<CoreRequest>>(None);
112    let pool = inner.pool.clone();
113    let i2 = inner.clone();
114    let mut task = tokio::spawn(async move {
115        pool.run(move || {
116            let mut on = |t: &crate::call::Target| {
117                if let Some(r) = request_of(t) {
118                    let _ = tx.send(Some(r));
119                }
120            };
121            f(&i2, &mut on)
122        })
123        .await
124    });
125    match tokio::time::timeout_at(deadline, &mut task).await {
126        Ok(Ok(Some(r))) => r,
127        Ok(_) => envelope::error_reply(ErrorCode::EvalUnavailable),
128        Err(_) => {
129            let request = rx.borrow_and_update().clone();
130            let Some(request) = request else {
131                // Past the budget before the request was even resolved (the store or another
132                // mesh is slow): the mesh cannot say what it is computing.
133                return envelope::error_reply(ErrorCode::EvalUnavailable);
134            };
135            pend(inner, request, task)
136        }
137    }
138}
139
140/// The request description of a target: its cell id, asof and pin (spec-0.4.2).
141fn request_of(t: &crate::call::Target) -> Option<CoreRequest> {
142    let r = CoreRequest::new(t.cell_id(), t.asof()).ok()?;
143    match &t.pin {
144        Some(p) => r.with_pin(p).ok(),
145        None => Some(r),
146    }
147}
148
149/// A job for a request still running in `task`.
150fn pend(inner: Arc<Inner>, request: CoreRequest, task: tokio::task::JoinHandle<Option<Reply>>) -> Reply {
151    let Some(id) = inner.jobs.create(request.clone()) else {
152        return envelope::error_reply(ErrorCode::EvalUnavailable);
153    };
154    let poll = format!("{}/jobs/{id}", inner.config.origin());
155    let est = inner.jobs.estimate(inner.config.budget.as_secs());
156    let i2 = inner.clone();
157    let id2 = id.clone();
158    tokio::spawn(async move {
159        let r = match task.await {
160            Ok(Some(r)) if r.status != 202 => r,
161            _ => envelope::error_reply(ErrorCode::EvalUnavailable),
162        };
163        let mut r = r;
164        r.cache = Cache::NoStore;
165        r.canonical = None;
166        i2.jobs.complete(&id2, r);
167    });
168    match Pending::new(&id, est, &poll, request) {
169        Ok(p) => Reply::json(202, envelope::pending(&p), Cache::NoStore),
170        Err(_) => envelope::error_reply(ErrorCode::EvalUnavailable),
171    }
172}
173
174fn admit(inner: &Inner, client: &Client, cost: u32) -> Result<(), Reply> {
175    inner.limiter.admit(client, cost).map_err(envelope::rate_limited_reply)
176}
177
178#[derive(OpenApi)]
179#[openapi(
180    info(
181        title = "datumesh-mesh",
182        description = "The Datumesh engine behind HTTPS (spec-0.4.1): cell envelopes (SPEC 5.5), batches, slices, receipts, descriptors, manifests, blobs, lineage, search, verification, jobs, key and mesh documents (SPEC 9.2, 9.6), bindings (SPEC 9.7).",
183        license(name = "Apache-2.0")
184    ),
185    paths(
186        cell,
187        cells,
188        slice,
189        versions,
190        receipt,
191        descriptor,
192        manifest,
193        blob,
194        explain,
195        find,
196        verify_receipt,
197        job,
198        key_document,
199        mesh_document,
200        bindings,
201        describe,
202        takeover_page,
203        whatif,
204        health,
205        metrics,
206        openapi_json
207    )
208)]
209struct ApiDoc;
210
211/// The OpenAPI document (generated from the handlers' annotations).
212pub fn openapi() -> utoipa::openapi::OpenApi {
213    ApiDoc::openapi()
214}
215
216/// The envelope of a cell.
217#[utoipa::path(get, path = "/cell/{cell}",
218    params(("cell" = String, Path, description = "A cell URI's rest (SPEC 5.3), byte for byte, `asof` included; or a call (SPEC 15.3's read syntax, URL-encoded) with an optional `?asof=`.")),
219    responses(
220        (status = 200, description = "`ok` or `stale`", content_type = "application/json"),
221        (status = 202, description = "`pending`: poll the job (SPEC 5.5)", content_type = "application/json"),
222        (status = 400, description = "`bad_request`", content_type = "application/json"),
223        (status = 402, description = "`payment_required`", content_type = "application/json"),
224        (status = 403, description = "`unlicensed`", content_type = "application/json"),
225        (status = 404, description = "`not_covered` (with `fault` when the evaluation faulted)", content_type = "application/json"),
226        (status = 406, description = "the Accept header excludes JSON"),
227        (status = 429, description = "`rate_limited`, with `Retry-After`", content_type = "application/json"),
228        (status = 500, description = "`error`", content_type = "application/json"),
229        (status = 503, description = "`error`: the store or another mesh is unavailable", content_type = "application/json"),
230    ))]
231async fn cell(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
232    let inner = mesh.inner.clone();
233    let (client, principal) = match who(&inner, &headers, peer_of(&req)) {
234        Ok(x) => x,
235        Err(r) => return to_response(r),
236    };
237    let mut resp = match admit(&inner, &client, 1) {
238        Err(r) => to_response(r),
239        Ok(()) => {
240            let rest = rest_of(&uri, "/cell/");
241            let p = principal.clone();
242            let r = within_budget(inner.clone(), move |i, on| {
243                let now = i.now();
244                i.answer(&rest, p.as_ref(), i, &now, on)
245            })
246            .await;
247            if let Some(o) = r.outcome() {
248                inner.metrics.outcome("/cell/{cell}", &o);
249            }
250            to_response(r)
251        }
252    };
253    resp.extensions_mut().insert(Who(principal.map(|p| p.id)));
254    resp
255}
256
257/// A batch of cells.
258#[utoipa::path(post, path = "/cells",
259    request_body(content = String, description = "A JSON array of requests, each a call or a cell URI (`cell://...`) as a string, or `{\"cell\": <that>}`; at most the configured bound (1,000).", content_type = "application/json"),
260    responses(
261        (status = 200, description = "A JSON array of envelopes, in order; each has the HTTP status its outcome has (`error`: 500)", content_type = "application/json"),
262        (status = 400, description = "Not such an array, or too long", content_type = "application/json"),
263        (status = 429, description = "`rate_limited` (a batch of n cells counts as n / 50 requests)", content_type = "application/json"),
264    ))]
265async fn cells(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
266    let inner = mesh.inner.clone();
267    let peer = peer_of(&req);
268    let (client, principal) = match who(&inner, &headers, peer) {
269        Ok(x) => x,
270        Err(r) => return to_response(r),
271    };
272    let body = match axum::body::to_bytes(req.into_body(), 64 << 20).await {
273        Ok(b) => b,
274        Err(_) => return to_response(envelope::bad_request_reply(ErrorCode::CanonLimit)),
275    };
276    let items = match parse_batch(&body, inner.config.batch_max) {
277        Ok(i) => i,
278        // A refusal of the whole batch (5.7): one envelope.
279        Err((code, detail)) => {
280            tracing::info!(target: "datumesh_http", detail = %detail, "batch refused");
281            return to_response(envelope::bad_request_reply(code));
282        }
283    };
284    if let Err(r) = admit(&inner, &client, inner.limiter.batch_cost(items.len())) {
285        return to_response(r);
286    }
287    let pieces = batch(inner.clone(), items, principal.clone()).await;
288    let mut counts: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
289    for w in &pieces {
290        for (o, k) in &w.outcomes {
291            *counts.entry(o).or_default() += k;
292        }
293    }
294    for (o, k) in counts {
295        inner.metrics.outcomes("/cells", o, k);
296    }
297    // 5.7: [{"envelope": <the envelope>, "status": <its status>}] in request order: the
298    // chunks' runs as they wrote them (the first opening the array).
299    let mut out = Vec::with_capacity(pieces.iter().map(|w| w.bytes.len()).sum::<usize>() + 2);
300    for w in &pieces {
301        out.extend_from_slice(&w.bytes);
302    }
303    out.extend_from_slice(if pieces.is_empty() { b"[]" } else { b"]" });
304    let mut resp =
305        to_response(Reply::json(200, out, if principal.is_some() { Cache::Private } else { Cache::NoStore }));
306    resp.extensions_mut().insert(Who(principal.map(|p| p.id)));
307    resp
308}
309
310fn batch_error(e: &str) -> Response {
311    plain_json(400, Value::Object(vec![("error".into(), Value::String(e.to_string()))]), Cache::NoStore)
312}
313
314/// The batch's requests, or the code of its refusal: `E_PARSE_URI` for a body that is not an
315/// array of requests, `E_CANON_LIMIT` for more than the mesh accepts (5.7).
316fn parse_batch(body: &[u8], max: usize) -> Result<Vec<String>, (ErrorCode, String)> {
317    let pu = |m: String| (ErrorCode::ParseUri, m);
318    // The body is a list of requests, not a protocol object: plain JSON.
319    let v: serde_json::Value = serde_json::from_slice(body).map_err(|e| pu(format!("not JSON: {e}")))?;
320    let serde_json::Value::Array(items) = v else { return Err(pu("not a JSON array".into())) };
321    if items.len() > max {
322        return Err((ErrorCode::CanonLimit, format!("{} requests: at most {max}", items.len())));
323    }
324    items
325        .into_iter()
326        .map(|i| {
327            let s = match i {
328                serde_json::Value::String(s) => s,
329                serde_json::Value::Object(mut o) => match o.remove("cell") {
330                    Some(serde_json::Value::String(s)) => s,
331                    _ => return Err(pu("an object without a string cell".to_string())),
332                },
333                _ => return Err(pu("an item that is neither a string nor an object".to_string())),
334            };
335            Ok(match s.strip_prefix("cell://") {
336                Some(r) => r.to_string(),
337                None => s,
338            })
339        })
340        .collect()
341}
342
343/// A run of a batch's answers as 5.7 writes them: the items
344/// `{"envelope": <the envelope>, "status": <its status>}` (JCS member order) joined by commas,
345/// and how many of each outcome they hold. Each chunk writes its own on the pool, in
346/// parallel: reading 1,000 envelopes (each a receipt, the function hash echoed) to copy and
347/// count them is the costliest part of a warm batch after the answers themselves.
348#[derive(Default)]
349struct Written {
350    bytes: Vec<u8>,
351    outcomes: Vec<(String, u64)>,
352}
353
354impl Written {
355    /// The run of `replies`, opening the array when `first`, else continuing it.
356    fn of<'a>(first: bool, replies: impl Iterator<Item = &'a Reply> + Clone) -> Written {
357        let mut w = Written {
358            bytes: Vec::with_capacity(replies.clone().map(|r| r.body.len() + 32).sum::<usize>() + 1),
359            outcomes: vec![],
360        };
361        w.bytes.push(if first { b'[' } else { b',' });
362        for (i, r) in replies.enumerate() {
363            if i > 0 {
364                w.bytes.push(b',');
365            }
366            w.push(r);
367        }
368        w
369    }
370
371    fn push(&mut self, r: &Reply) {
372        self.bytes.extend_from_slice(b"{\"envelope\":");
373        self.bytes.extend_from_slice(&r.body);
374        self.bytes.extend_from_slice(b",\"status\":");
375        push_u16(&mut self.bytes, r.status);
376        self.bytes.push(b'}');
377        if let Some(o) = r.outcome_str() {
378            match self.outcomes.iter_mut().find(|(x, _)| x == o) {
379                Some((_, k)) => *k += 1,
380                None => self.outcomes.push((o.to_string(), 1)),
381            }
382        }
383    }
384}
385
386/// Appends `n` in decimal (a JSON integer).
387fn push_u16(out: &mut Vec<u8>, n: u16) {
388    let mut buf = [0u8; 5];
389    let (mut i, mut n) = (buf.len(), n);
390    loop {
391        i -= 1;
392        buf[i] = b'0' + (n % 10) as u8;
393        n /= 10;
394        if n == 0 {
395            break;
396        }
397    }
398    out.extend_from_slice(&buf[i..]);
399}
400
401/// The machine's parallelism, read once: `available_parallelism` reads the cgroup files on
402/// Linux (hundreds of microseconds in a container), too slow to pay on every batch.
403fn cores() -> usize {
404    static CORES: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
405    *CORES.get_or_init(|| std::thread::available_parallelism().map(|c| c.get()).unwrap_or(4))
406}
407
408/// Answers a batch within the budget: the requests are answered in chunks across the pool
409/// (one chunk per core; bindings looked up once per name and asof within the batch), each
410/// chunk writing its answers ([`Written`]). Those not answered within the budget become
411/// jobs: each is resolved again to the request it describes (a store read), and its chunk's
412/// answer completes the job. The runs are in request order.
413async fn batch(inner: Arc<Inner>, items: Vec<String>, principal: Option<Principal>) -> Vec<Written> {
414    let n = items.len();
415    let deadline = tokio::time::Instant::now() + inner.config.budget;
416    let chunks = n.div_ceil(64).clamp(1, inner.config.pool_size.min(cores()));
417    let per = n.div_ceil(chunks).max(1);
418    let ranges: Vec<(usize, usize)> =
419        (0..chunks).map(|c| (c * per, ((c + 1) * per).min(n))).take_while(|(lo, hi)| lo < hi).collect();
420    let now = inner.now();
421    let items = Arc::new(items);
422    // Each chunk's answers so far; once the budget has passed (`late`), its answers go to
423    // the channel instead, to complete their jobs. A chunk done within the budget leaves
424    // its answers written instead.
425    let shared: Slots = Arc::new(ranges.iter().map(|_| Mutex::new(Slot::default())).collect());
426    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<(usize, Reply)>();
427    let seen = Arc::new(crate::mesh::Seen::default());
428    let mut tasks = Vec::new();
429    for (c, &(lo, hi)) in ranges.iter().enumerate() {
430        let (i2, items, tx, p, now, shared) =
431            (inner.clone(), items.clone(), tx.clone(), principal.clone(), now.clone(), shared.clone());
432        let seen = seen.clone();
433        let pool = inner.pool.clone();
434        tasks.push(tokio::spawn(async move {
435            pool.run(move || {
436                let memo = Memo::shared(&i2, &seen);
437                for k in lo..hi {
438                    let reply = i2.answer_with(&items[k], p.as_ref(), &memo, &now, &mut |_| {}, false);
439                    let mut slot = shared[c].lock().unwrap_or_else(|p| p.into_inner());
440                    if slot.late {
441                        let _ = tx.send((k, reply));
442                    } else {
443                        slot.answers.push((k, reply));
444                    }
445                }
446                let mut slot = shared[c].lock().unwrap_or_else(|p| p.into_inner());
447                if !slot.late {
448                    let answers = std::mem::take(&mut slot.answers);
449                    slot.written = Some(Written::of(c == 0, answers.iter().map(|(_, r)| r)));
450                }
451            })
452            .await
453        }));
454    }
455    drop(tx);
456    let all = futures_join(&mut tasks, deadline).await;
457    let mut done: Vec<Option<Reply>> = vec![None; n];
458    let mut written: Vec<Option<Written>> = Vec::with_capacity(ranges.len());
459    for slot in shared.iter() {
460        let mut s = slot.lock().unwrap_or_else(|p| p.into_inner());
461        s.late = true;
462        for (k, r) in s.answers.drain(..) {
463            done[k] = Some(r);
464        }
465        written.push(s.written.take());
466    }
467    // A chunk's run: as it wrote it, else its answers (an error for any it has none of: its
468    // task panicked, or the answer completes a job).
469    let runs = |done: Vec<Option<Reply>>, written: Vec<Option<Written>>| -> Vec<Written> {
470        let error = envelope::error_reply(ErrorCode::EvalUnavailable);
471        ranges
472            .iter()
473            .zip(written)
474            .enumerate()
475            .map(|(c, (&(lo, hi), w))| {
476                w.unwrap_or_else(|| Written::of(c == 0, done[lo..hi].iter().map(|d| d.as_ref().unwrap_or(&error))))
477            })
478            .collect()
479    };
480    if all {
481        return runs(done, written);
482    }
483    // Past the budget: every request not answered yet becomes a job, resolved again to the
484    // request it describes.
485    let open: Vec<usize> = ranges
486        .iter()
487        .zip(&written)
488        .filter(|(_, w)| w.is_none())
489        .flat_map(|(&(lo, hi), _)| lo..hi)
490        .filter(|k| done[*k].is_none())
491        .collect();
492    let (i2, items2, open2, now2) = (inner.clone(), items.clone(), open.clone(), now.clone());
493    let requests: Vec<Option<CoreRequest>> = inner
494        .pool
495        .run(move || {
496            let memo = Memo::new(&i2);
497            open2
498                .iter()
499                .map(|k| {
500                    crate::call::resolve(&items2[*k], &now2, &i2.config.aliases, &memo, false)
501                        .ok()
502                        .and_then(|t| request_of(&t))
503                })
504                .collect()
505        })
506        .await
507        .unwrap_or_default();
508    let poll_base = format!("{}/jobs/", inner.config.origin());
509    let est = inner.jobs.estimate(inner.config.budget.as_secs());
510    let mut jobs: Vec<Option<String>> = vec![None; n];
511    for (i, k) in open.iter().enumerate() {
512        let reply = match requests.get(i).cloned().flatten() {
513            Some(req) => match inner.jobs.create(req.clone()) {
514                Some(id) => {
515                    let p = Pending::new(&id, est, &format!("{poll_base}{id}"), req);
516                    jobs[*k] = Some(id);
517                    match p {
518                        Ok(p) => Reply::json(202, envelope::pending(&p), Cache::NoStore),
519                        Err(_) => envelope::error_reply(ErrorCode::EvalUnavailable),
520                    }
521                }
522                None => envelope::error_reply(ErrorCode::EvalUnavailable),
523            },
524            None => envelope::error_reply(ErrorCode::EvalUnavailable),
525        };
526        done[*k] = Some(reply);
527    }
528    let i3 = inner.clone();
529    tokio::spawn(async move {
530        while let Some((k, mut reply)) = rx.recv().await {
531            if let Some(id) = &jobs[k] {
532                reply.cache = Cache::NoStore;
533                reply.canonical = None;
534                i3.jobs.complete(id, reply);
535            }
536        }
537        for t in tasks {
538            let _ = t.await;
539        }
540        // Jobs whose task ended without an answer (a panic) are given up.
541        for id in jobs.into_iter().flatten() {
542            if let Poll::Running(..) = i3.jobs.poll_peek(&id) {
543                i3.jobs.complete(&id, envelope::error_reply(ErrorCode::EvalUnavailable));
544            }
545        }
546    });
547    runs(done, written)
548}
549
550/// A batch chunk's state: whether the budget has passed, its answers so far, and its
551/// answers written once it is done within the budget.
552#[derive(Default)]
553struct Slot {
554    late: bool,
555    answers: Vec<(usize, Reply)>,
556    written: Option<Written>,
557}
558
559/// Each batch chunk's state.
560type Slots = Arc<Vec<Mutex<Slot>>>;
561
562/// Waits for every task until `deadline`: whether all finished.
563async fn futures_join(tasks: &mut [tokio::task::JoinHandle<Option<()>>], deadline: tokio::time::Instant) -> bool {
564    for t in tasks.iter_mut() {
565        if t.is_finished() {
566            continue;
567        }
568        if tokio::time::timeout_at(deadline, t).await.is_err() {
569            return false;
570        }
571    }
572    true
573}
574
575/// The versions of a stored cell (SPEC 9.8, spec-0.4.2).
576#[utoipa::path(get, path = "/versions/{cell}",
577    params(("cell" = String, Path, description = "A cell URI's rest without asof (a pin allowed), then optionally `from=` and `to=` (instants, inclusive bounds on tx) as its last parameters.")),
578    responses(
579        (status = 200, description = "`{\"cell\", \"versions\": [{\"asof\", \"receipt\", \"tx\"}], \"next\"?}` ascending by tx", content_type = "application/json"),
580        (status = 400, description = "`bad_request`", content_type = "application/json"),
581        (status = 404, description = "`not_covered` (with `E_NAME_UNBOUND` for an unbound name)", content_type = "application/json"),
582    ))]
583async fn versions(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
584    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
585        return r;
586    }
587    let inner = mesh.inner.clone();
588    let rest = rest_of(&uri, "/versions/");
589    let r = inner
590        .pool
591        .clone()
592        .run(move || inner.versions(&rest))
593        .await
594        .unwrap_or_else(|| envelope::error_reply(ErrorCode::EvalUnavailable));
595    to_response(r)
596}
597
598/// The most versions in one answer of the versions endpoint.
599const VERSIONS_PAGE: usize = 1000;
600
601impl Inner {
602    fn versions(&self, rest: &str) -> Reply {
603        // `from=` and `to=` are the endpoint's, taken off the end of the query.
604        let (path, query) = match rest.split_once('?') {
605            Some((p, q)) => (p, q),
606            None => (rest, ""),
607        };
608        let mut ps: Vec<&str> = if query.is_empty() { vec![] } else { query.split('&').collect() };
609        let (mut from, mut to) = (None, None);
610        while let Some(last) = ps.last() {
611            if let Some(v) = last.strip_prefix("from=") {
612                from = Some(v.to_string());
613            } else if let Some(v) = last.strip_prefix("to=") {
614                to = Some(v.to_string());
615            } else {
616                break;
617            }
618            ps.pop();
619        }
620        for t in [&from, &to].into_iter().flatten() {
621            if lexical::check_instant(t, "$").is_err() {
622                return envelope::bad_request_reply(ErrorCode::CanonInstant);
623            }
624        }
625        let cell_rest = if ps.is_empty() { path.to_string() } else { format!("{path}?{}", ps.join("&")) };
626        let now = self.now();
627        let target = match crate::call::resolve(&cell_rest, &now, &self.config.aliases, self, false) {
628            Ok(t) => t,
629            Err(r) => return self.rejection(r, None),
630        };
631        if target.asof().is_some() {
632            return envelope::bad_request_reply(ErrorCode::ParseUri);
633        }
634        let lo = from.unwrap_or_else(|| "0001-01-01T00:00:00.000000Z".into());
635        let hi = to.clone().unwrap_or_else(|| "9999-12-31T23:59:59.999999Z".into());
636        let mut vs = match self.store.versions(target.cell_id(), &lo, &hi) {
637            Ok(v) => v,
638            Err(_) => return envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(&target.bound.fn_hash)),
639        };
640        vs.sort_by(|a, b| (&a.tx, &a.receipt_hash).cmp(&(&b.tx, &b.receipt_hash)));
641        let more = vs.len() > VERSIONS_PAGE;
642        vs.truncate(VERSIONS_PAGE);
643        let list: Vec<Value> = vs
644            .iter()
645            .map(|v| {
646                Value::Object(vec![
647                    ("asof".into(), Value::String(v.asof.clone())),
648                    ("receipt".into(), Value::String(v.receipt_hash.clone())),
649                    ("tx".into(), Value::String(v.tx.clone())),
650                ])
651            })
652            .collect();
653        let mut body = vec![("cell".to_string(), target.cell.to_value()), ("versions".to_string(), Value::Array(list))];
654        if more {
655            if let Some(last) = vs.last() {
656                let us = datumesh_formula::calendar::parse_instant(&last.tx).unwrap_or(0) + 1;
657                let next_from = datumesh_formula::calendar::instant_text(us).unwrap_or_default();
658                let mut next = format!("{}/versions/{cell_rest}", self.config.origin());
659                next.push(if cell_rest.contains('?') { '&' } else { '?' });
660                next.push_str(&format!("from={next_from}"));
661                if let Some(t) = &to {
662                    next.push_str(&format!("&to={t}"));
663                }
664                body.push(("next".to_string(), Value::String(next)));
665            }
666        }
667        Reply::json(200, Value::Object(body).to_jcs(), Cache::Public(self.config.ttl.latest_max_age.as_secs()))
668    }
669}
670
671/// The members of a slice.
672#[utoipa::path(get, path = "/slice/{cell}",
673    params(
674        ("cell" = String, Path, description = "A slice: a cell URI's rest or a call with `*` for open arguments, of a stored function; `?asof=`, `limit=` (JSON, default 1,000, at most 10,000), `after=` (the cursor of the previous page)."),
675    ),
676    responses(
677        (status = 200, description = "JSON page of members, or with `Accept: application/vnd.apache.arrow.stream` an Arrow IPC stream", content_type = "application/json"),
678        (status = 400, description = "`bad_request`", content_type = "application/json"),
679        (status = 404, description = "`not_covered`", content_type = "application/json"),
680    ))]
681async fn slice(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
682    let inner = mesh.inner.clone();
683    let (client, _) = match who(&inner, &headers, peer_of(&req)) {
684        Ok(x) => x,
685        Err(r) => return to_response(r),
686    };
687    if let Err(r) = admit(&inner, &client, 1) {
688        return to_response(r);
689    }
690    // One manifest path since spec-0.4.2: /manifest/<slice id>/<members hash>.
691    let rest = rest_of(&uri, "/slice/");
692    let arrow = accepts(&headers, crate::slice::ARROW);
693    let r = inner
694        .pool
695        .clone()
696        .run(move || {
697            let now = inner.now();
698            inner.slice(&rest, &now, arrow)
699        })
700        .await
701        .unwrap_or_else(|| envelope::error_reply(ErrorCode::EvalUnavailable));
702    to_response(r)
703}
704
705fn accepts(headers: &HeaderMap, media: &str) -> bool {
706    headers
707        .get_all(header::ACCEPT)
708        .iter()
709        .filter_map(|v| v.to_str().ok())
710        .any(|v| v.split(',').any(|p| p.split(';').next().unwrap_or("").trim() == media))
711}
712
713/// Whether the client takes JSON (no `Accept`, `*/*`, `application/*` or
714/// `application/json`); for slices also Arrow.
715fn acceptable(headers: &HeaderMap, also: Option<&str>) -> bool {
716    let vals: Vec<&str> = headers.get_all(header::ACCEPT).iter().filter_map(|v| v.to_str().ok()).collect();
717    if vals.is_empty() {
718        return true;
719    }
720    vals.iter().flat_map(|v| v.split(',')).any(|p| {
721        let mut parts = p.split(';');
722        let m = parts.next().unwrap_or("").trim();
723        let q0 = parts.any(|x| {
724            let x = x.trim();
725            x == "q=0" || x == "q=0.0" || x == "q=0.00" || x == "q=0.000"
726        });
727        !q0 && (m == "*/*" || m == "application/*" || m == JSON || also == Some(m))
728    })
729}
730
731async fn object(
732    inner: Arc<Inner>,
733    what: &'static str,
734    f: impl FnOnce(&Inner) -> Option<Vec<u8>> + Send + 'static,
735) -> Response {
736    let i2 = inner.clone();
737    match inner.pool.run(move || f(&i2)).await.flatten() {
738        Some(bytes) => {
739            let ct = if what == "blob" { "application/octet-stream" } else { JSON };
740            to_response(Reply {
741                status: 200,
742                body: bytes.into(),
743                content_type: ct,
744                cache: Cache::Immutable,
745                canonical: None,
746                retry_after: None,
747            })
748        }
749        None => not_found(what),
750    }
751}
752
753/// The refusal of a request by its client's rate limit (or key), if it is refused.
754fn ip_admit(inner: &Inner, headers: &HeaderMap, req: &Request) -> Option<Response> {
755    let client = match who(inner, headers, peer_of(req)) {
756        Ok((c, _)) => c,
757        Err(r) => return Some(to_response(r)),
758    };
759    admit(inner, &client, 1).err().map(to_response)
760}
761
762/// A receipt by its hash (canonical bytes; gzip when asked).
763#[utoipa::path(get, path = "/receipt/{hash}", params(("hash" = String, Path, description = "The receipt hash (SPEC 8.3).")),
764    responses((status = 200, description = "The receipt's canonical JSON; immutable", content_type = "application/json"), (status = 404, description = "Not held")))]
765async fn receipt(State(mesh): State<Mesh>, Path(hash): Path<String>, headers: HeaderMap, req: Request) -> Response {
766    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
767        return r;
768    }
769    if lexical::check_hex(&hash, 64, "$").is_err() {
770        return not_found("receipt");
771    }
772    object(mesh.inner.clone(), "receipt", move |i| i.store.receipt(&hash).map(|c| c.into_owned())).await
773}
774
775/// A descriptor by its function hash.
776#[utoipa::path(get, path = "/descriptor/{hash}", params(("hash" = String, Path, description = "The function hash.")),
777    responses((status = 200, description = "The descriptor's canonical JSON; immutable", content_type = "application/json"), (status = 404, description = "Not held")))]
778async fn descriptor(State(mesh): State<Mesh>, Path(hash): Path<String>, headers: HeaderMap, req: Request) -> Response {
779    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
780        return r;
781    }
782    if lexical::check_hex(&hash, 64, "$").is_err() {
783        return not_found("descriptor");
784    }
785    object(mesh.inner.clone(), "descriptor", move |i| i.store.descriptor(&hash).map(|c| c.into_owned())).await
786}
787
788async fn manifest_of(inner: Arc<Inner>, entry: String) -> Response {
789    object(inner, "manifest", move |i| i.store.manifest(&entry).map(|c| c.into_owned())).await
790}
791
792/// A slice manifest (SPEC 15.13), by its entry's slice id and members hash.
793#[utoipa::path(get, path = "/manifest/{slice_id}/{members_hash}",
794    params(("slice_id" = String, Path, description = "The slice id."), ("members_hash" = String, Path, description = "The members hash.")),
795    responses((status = 200, description = "The manifest's canonical JSON; immutable", content_type = "application/json"), (status = 404, description = "Not held")))]
796async fn manifest(
797    State(mesh): State<Mesh>,
798    Path((slice_id, members)): Path<(String, String)>,
799    headers: HeaderMap,
800    req: Request,
801) -> Response {
802    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
803        return r;
804    }
805    if lexical::check_hex(&slice_id, 64, "$").is_err() || lexical::check_hex(&members, 64, "$").is_err() {
806        return not_found("manifest");
807    }
808    manifest_of(mesh.inner.clone(), format!("slice:{slice_id}:{members}")).await
809}
810
811/// Blob content by SHA-256.
812#[utoipa::path(get, path = "/blob/{sha256}", params(("sha256" = String, Path, description = "The content's SHA-256.")),
813    responses((status = 200, description = "The bytes; immutable", content_type = "application/octet-stream"), (status = 404, description = "Not held")))]
814async fn blob(State(mesh): State<Mesh>, Path(sha): Path<String>, headers: HeaderMap, req: Request) -> Response {
815    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
816        return r;
817    }
818    if lexical::check_hex(&sha, 64, "$").is_err() {
819        return not_found("blob");
820    }
821    object(mesh.inner.clone(), "blob", move |i| i.store.blob(&sha).ok().flatten().map(|c| c.into_owned())).await
822}
823
824/// A cell's lineage as nested envelopes.
825#[utoipa::path(get, path = "/explain/{cell}",
826    params(("cell" = String, Path, description = "As for /cell; `depth=` (default 4, at most 16) bounds the walk.")),
827    responses(
828        (status = 200, description = "`{\"envelope\", \"inputs\": [{\"entry\", \"envelope\", \"inputs\"} | {\"entry\", \"slice\", \"members\"}], \"truncated\"}`", content_type = "application/json"),
829        (status = 202, description = "`pending`: the cell is being computed; ask again", content_type = "application/json"),
830        (status = 400, description = "`bad_request`", content_type = "application/json"),
831        (status = 404, description = "`not_covered`", content_type = "application/json"),
832    ))]
833async fn explain(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
834    let inner = mesh.inner.clone();
835    let (client, principal) = match who(&inner, &headers, peer_of(&req)) {
836        Ok(x) => x,
837        Err(r) => return to_response(r),
838    };
839    if let Err(r) = admit(&inner, &client, 1) {
840        return to_response(r);
841    }
842    let mut rest = rest_of(&uri, "/explain/");
843    let mut depth = inner.config.explain_depth;
844    // `depth=` is the explain's own parameter: taken off the query.
845    if let Some((p, q)) = rest.clone().split_once('?') {
846        let kept: Vec<&str> = q.split('&').filter(|x| !x.starts_with("depth=")).collect();
847        if let Some(d) = q.split('&').find_map(|x| x.strip_prefix("depth=")) {
848            depth = d.parse::<usize>().unwrap_or(depth);
849        }
850        rest = if kept.is_empty() { p.to_string() } else { format!("{p}?{}", kept.join("&")) };
851    }
852    let depth = depth.min(16);
853    let r = within_budget(inner, move |i, on| {
854        let now = i.now();
855        let r = i.answer(&rest, principal.as_ref(), i, &now, on);
856        if r.status != 200 {
857            return r;
858        }
859        let env = json::parse(&r.body).unwrap_or(Value::Null);
860        let mut budget = 2_000usize;
861        let v = i.explain_node(env, depth, &mut budget);
862        Reply::json(200, v.to_jcs(), Cache::NoStore)
863    })
864    .await;
865    to_response(r)
866}
867
868impl Inner {
869    /// An envelope with its inputs' envelopes, `depth` levels down, at most `budget` nodes.
870    fn explain_node(&self, envelope: Value, depth: usize, budget: &mut usize) -> Value {
871        let inputs: Vec<String> = envelope
872            .get("receipt")
873            .and_then(|r| r.get("inputs"))
874            .and_then(|i| {
875                if let Value::Array(a) = i {
876                    Some(a.iter().filter_map(Value::as_str).map(str::to_string).collect())
877                } else {
878                    None
879                }
880            })
881            .unwrap_or_default();
882        let mut truncated = false;
883        let mut out = Vec::new();
884        for e in inputs {
885            if depth == 0 || *budget == 0 {
886                truncated = true;
887                break;
888            }
889            *budget -= 1;
890            if e.starts_with("slice:") {
891                let m = self.store.manifest(&e).and_then(|m| datumesh_core::Manifest::from_json(&m).ok());
892                let mut node = vec![("entry".to_string(), Value::String(e.clone()))];
893                if let Some(m) = m {
894                    node.push(("members".to_string(), envelope::num(m.members().len() as u64)));
895                    node.push(("slice".to_string(), m.slice().to_value()));
896                }
897                out.push(Value::Object(node));
898                continue;
899            }
900            let child = match self.receipt_info_by_hash(&e) {
901                Some(info) => self.explain_node(json::parse(&info.ok).unwrap_or(Value::Null), depth - 1, budget),
902                None => json::parse(&envelope::not_covered(None)).unwrap_or(Value::Null),
903            };
904            let mut node = vec![("entry".to_string(), Value::String(e.clone()))];
905            if let Value::Object(m) = child {
906                node.extend(m);
907            }
908            out.push(Value::Object(node));
909        }
910        let mut node = vec![("envelope".to_string(), envelope.clone()), ("inputs".to_string(), Value::Array(out))];
911        node.push(("truncated".to_string(), Value::Bool(truncated)));
912        Value::Object(node)
913    }
914}
915
916#[derive(serde::Deserialize)]
917struct FindQuery {
918    q: Option<String>,
919    limit: Option<usize>,
920    summary: Option<String>,
921}
922
923/// The hybrid `/find` (CONTRACT-build2-part2-read R3; see `crate::find`), and `/find?summary=1`.
924#[utoipa::path(get, path = "/find",
925    params(("q" = Option<String>, Query, description = "The query: words, a name, a label, an alias or a value, or a request such as `<book> <chapter>:<verse>`. Matching is case-insensitive after NFC."), ("limit" = Option<usize>, Query, description = "At most this many results (default 10, at most 50)."), ("summary" = Option<String>, Query, description = "`1`: the catalogue summary (`classes`, `functions`, with labels, cell counts and small dictionaries) instead of results.")),
926    responses((status = 200, description = "`{\"query\", \"vector\": bool, \"results\": [...], \"resolution\"?: {...}}`. Each result has `kind` (`function`, `method` or `class`), `name`, `label`, `description`, `call` (the template with typed placeholders, or the filled call of a resolved request), `match` (`exact`, `text` or `vector`), `score`, and the members of its kind (`descriptor`, `fn_hash`, `since`; a class has `class_hash` and `methods`; a method has `class`). `resolution` has `status` `exact` (`call`, `label`), `ambiguous` (`candidates`, `keys`) or `range` (`error`: `E_RANGE_REFUSED`).", content_type = "application/json")))]
927async fn find(State(mesh): State<Mesh>, Query(q): Query<FindQuery>, headers: HeaderMap, req: Request) -> Response {
928    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
929        return r;
930    }
931    let inner = mesh.inner.clone();
932    let query = q.q.unwrap_or_default();
933    let limit = q.limit.unwrap_or(crate::find::DEFAULT_LIMIT).clamp(1, crate::find::MAX_LIMIT);
934    let summary = q.summary.as_deref() == Some("1");
935    let r = inner
936        .pool
937        .clone()
938        .run(move || if summary { crate::find::summary(&inner) } else { crate::find::answer(&inner, &query, limit) })
939        .await
940        .unwrap_or(Value::Null);
941    plain_json(200, r, Cache::Public(60))
942}
943
944#[derive(serde::Deserialize)]
945struct VerifyQuery {
946    level: Option<String>,
947    blob: Option<String>,
948    form: Option<String>,
949}
950
951/// Verification as a service: the core verifier on a submitted receipt, with this mesh's
952/// keys; free, unauthenticated, rate-limited per IP.
953#[utoipa::path(post, path = "/verify",
954    params(("level" = Option<String>, Query, description = "`recomputed` (default: recompute with the engine as the resolver) or `signed` (steps 1-6)."), ("blob" = Option<String>, Query, description = "Blob content for step 7.7, as hex (at most 1 MiB)."), ("form" = Option<String>, Query, description = "`offered`: the body is `{\"receipt\": <its JSON text>, \"recompute\"?: <SPEC 11's recompute object>, \"blob_hex\"?}` and step 7 uses what is offered instead of this mesh's engine.")),
955    request_body(content = String, description = "The receipt's JSON text, exactly as received (or the offered form).", content_type = "application/json"),
956    responses(
957        (status = 200, description = "`{\"ok\", \"level\", \"code\", \"hash\", \"computed_by\", \"path\", \"detail\", \"blob_checked\"}`", content_type = "application/json"),
958        (status = 429, description = "`rate_limited`", content_type = "application/json"),
959    ))]
960async fn verify_receipt(
961    State(mesh): State<Mesh>,
962    Query(q): Query<VerifyQuery>,
963    headers: HeaderMap,
964    req: Request,
965) -> Response {
966    let inner = mesh.inner.clone();
967    let ip = client_ip(&inner, &headers, peer_of(&req));
968    if let Err(s) = inner.limiter.admit_verify(ip) {
969        return to_response(envelope::rate_limited_reply(s));
970    }
971    let body: Bytes = match axum::body::to_bytes(req.into_body(), 4 << 20).await {
972        Ok(b) => b,
973        Err(_) => return batch_error("body too large"),
974    };
975    if q.form.as_deref() == Some("offered") {
976        let Ok(v) = json::parse(&body) else { return batch_error("form=offered: not strict JSON") };
977        let Some(receipt) = v.get("receipt").and_then(Value::as_str).map(|s| s.as_bytes().to_vec()) else {
978            return batch_error("form=offered: no receipt text");
979        };
980        let blob = match v.get("blob_hex").and_then(Value::as_str).map(hex) {
981            None => None,
982            Some(Some(b)) if b.len() <= 1 << 20 => Some(b),
983            Some(_) => return batch_error("blob_hex: hex of at most 1 MiB"),
984        };
985        let m = mesh.clone();
986        let rc = v.get("recompute").cloned();
987        let r = inner.pool.run(move || m.verify_offered(&receipt, rc.as_ref(), blob.as_deref())).await;
988        return match r {
989            Some(v) => to_response(Reply::json(200, v.body, Cache::NoStore)),
990            None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
991        };
992    }
993    let signed = q.level.as_deref() == Some("signed");
994    let blob = match q.blob.as_deref().map(hex) {
995        None => None,
996        Some(Some(b)) if b.len() <= 1 << 20 => Some(b),
997        Some(_) => return batch_error("blob: hex of at most 1 MiB"),
998    };
999    let m = mesh.clone();
1000    let r = inner.pool.run(move || m.verify(&body, signed, blob.as_deref())).await;
1001    match r {
1002        Some(v) => to_response(Reply::json(200, v.body, Cache::NoStore)),
1003        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1004    }
1005}
1006
1007fn hex(s: &str) -> Option<Vec<u8>> {
1008    if !s.len().is_multiple_of(2) {
1009        return None;
1010    }
1011    (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
1012}
1013
1014/// A job: `pending` again while it runs, then the envelope of the original request.
1015#[utoipa::path(get, path = "/jobs/{job}", params(("job" = String, Path, description = "The job id of a `pending` envelope.")),
1016    responses(
1017        (status = 202, description = "`pending`, the same job and request", content_type = "application/json"),
1018        (status = 400, description = "`bad_request` with `E_JOB_UNKNOWN`: unknown or expired", content_type = "application/json"),
1019        (status = 200, description = "The completed envelope (any outcome but pending, with its status), bound to the original request", content_type = "application/json"),
1020    ))]
1021async fn job(State(mesh): State<Mesh>, Path(id): Path<String>, headers: HeaderMap, req: Request) -> Response {
1022    let inner = mesh.inner.clone();
1023    let (client, _) = match who(&inner, &headers, peer_of(&req)) {
1024        Ok(x) => x,
1025        Err(r) => return to_response(r),
1026    };
1027    if let Err(r) = admit(&inner, &client, 1) {
1028        return to_response(r);
1029    }
1030    let unknown = || to_response(Reply::json(400, envelope::bad_request(ErrorCode::JobUnknown), Cache::NoStore));
1031    let valid = (32..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
1032    if !valid {
1033        return unknown();
1034    }
1035    match inner.jobs.poll(&id) {
1036        Poll::Unknown => unknown(),
1037        Poll::Done(r) => to_response(r),
1038        Poll::Running(request, elapsed) => {
1039            let poll = format!("{}/jobs/{id}", inner.config.origin());
1040            match Pending::new(&id, inner.jobs.estimate(elapsed), &poll, request) {
1041                Ok(p) => to_response(Reply::json(202, envelope::pending(&p), Cache::NoStore)),
1042                Err(_) => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1043            }
1044        }
1045    }
1046}
1047
1048/// The key document (SPEC 9.2): the store's namespace record for this mesh's host.
1049#[utoipa::path(get, path = "/.well-known/datumesh.json", responses((status = 200, description = "The key document", content_type = "application/json"), (status = 404, description = "None stored")))]
1050async fn key_document(State(mesh): State<Mesh>) -> Response {
1051    let m = mesh.clone();
1052    match mesh.inner.pool.run(move || m.key_document()).await.flatten() {
1053        Some(doc) => to_response(Reply::json(200, doc, Cache::Public(300))),
1054        None => not_found("key document"),
1055    }
1056}
1057
1058/// The mesh document (SPEC 9.6).
1059#[utoipa::path(get, path = "/.well-known/datumesh-mesh.json", responses((status = 200, description = "The mesh document", content_type = "application/json")))]
1060async fn mesh_document(State(mesh): State<Mesh>) -> Response {
1061    to_response(Reply::json(200, mesh.mesh_document(), Cache::Public(300)))
1062}
1063
1064/// Which function each name denotes as of an instant (SPEC 9.7).
1065#[utoipa::path(get, path = "/bindings",
1066    params(("name" = String, Query, description = "A function name, percent-encoded as in SPEC 5.1; repeat for several."), ("asof" = Option<String>, Query, description = "An instant (default: now).")),
1067    responses((status = 200, description = "`{\"asof\", \"bindings\": {name: {\"fn_hash\", \"since\"}}}`", content_type = "application/json"), (status = 400, description = "A malformed name or asof", content_type = "application/json")))]
1068async fn bindings(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
1069    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1070        return r;
1071    }
1072    let inner = mesh.inner.clone();
1073    let mut names = Vec::new();
1074    let mut asof = None;
1075    for p in uri.query().unwrap_or("").split('&').filter(|p| !p.is_empty()) {
1076        let (k, v) = p.split_once('=').unwrap_or((p, ""));
1077        let Some(v) = pct_decode(v) else { return batch_error("percent-encoding (SPEC 5.1)") };
1078        match k {
1079            "name" if lexical::check_function_name(&v, "$").is_ok() => names.push(v),
1080            "asof" if lexical::check_instant(&v, "$").is_ok() && asof.is_none() => asof = Some(v),
1081            _ => return batch_error(&format!("parameter {k}")),
1082        }
1083    }
1084    let r = inner
1085        .pool
1086        .clone()
1087        .run(move || {
1088            let at = asof.unwrap_or_else(|| inner.now());
1089            let mut out = Vec::new();
1090            for n in names {
1091                if !inner.config.owns(crate::foreign::host_of(&n)) {
1092                    continue;
1093                }
1094                // A class name is answered with its class hash (9.7, spec-0.5.0); any other name
1095                // with the function it means.
1096                let found = match inner.store.resolve_class_binding(&n, &at) {
1097                    Ok(Some(c)) => ("class_hash", c.class_hash, c.tx),
1098                    Ok(None) => match inner.store.resolve_binding(&n, &at) {
1099                        Ok(Some(b)) => ("fn_hash", b.fn_hash, b.tx),
1100                        Ok(None) => continue,
1101                        Err(_) => return None,
1102                    },
1103                    Err(_) => return None,
1104                };
1105                out.push((
1106                    n,
1107                    Value::Object(vec![
1108                        (found.0.into(), Value::String(found.1)),
1109                        ("since".into(), Value::String(found.2)),
1110                    ]),
1111                ));
1112            }
1113            Some(Value::Object(vec![("asof".into(), Value::String(at)), ("bindings".into(), Value::Object(out))]))
1114        })
1115        .await
1116        .flatten();
1117    match r {
1118        Some(v) => plain_json(200, v, Cache::Public(inner_latest(&mesh))),
1119        None => to_response(envelope::error_reply(ErrorCode::InputUnavailable)),
1120    }
1121}
1122
1123fn inner_latest(mesh: &Mesh) -> u64 {
1124    mesh.inner.config.ttl.latest_max_age.as_secs()
1125}
1126
1127/// Strict percent-decoding (SPEC 5.1): literal characters as themselves, `%` and two
1128/// uppercase hex digits for other bytes, UTF-8.
1129fn pct_decode(s: &str) -> Option<String> {
1130    let b = s.as_bytes();
1131    let mut out = Vec::new();
1132    let mut i = 0;
1133    while i < b.len() {
1134        let c = b[i];
1135        if c == b'%' {
1136            let h = b.get(i + 1..i + 3)?;
1137            if !h.iter().all(|x| x.is_ascii_digit() || (b'A'..=b'F').contains(x)) {
1138                return None;
1139            }
1140            let v = u8::from_str_radix(std::str::from_utf8(h).ok()?, 16).ok()?;
1141            if v.is_ascii_alphanumeric() || matches!(v, b'-' | b'.' | b'_' | b'~' | b':') {
1142                return None;
1143            }
1144            out.push(v);
1145            i += 3;
1146        } else if c.is_ascii_alphanumeric() || matches!(c, b'-' | b'.' | b'_' | b'~' | b':') {
1147            out.push(c);
1148            i += 1;
1149        } else {
1150            return None;
1151        }
1152    }
1153    String::from_utf8(out).ok()
1154}
1155
1156/// Liveness and the store's health.
1157#[utoipa::path(get, path = "/health", responses((status = 200, description = "`{\"status\": \"ok\"}`", content_type = "application/json"), (status = 503, description = "The store does not answer", content_type = "application/json")))]
1158async fn health(State(mesh): State<Mesh>) -> Response {
1159    let m = mesh.clone();
1160    let ok = tokio::time::timeout(
1161        Duration::from_secs(5),
1162        mesh.inner.pool.run(move || m.inner.store.namespace(&m.inner.config.host).is_ok()),
1163    )
1164    .await
1165    .ok()
1166    .flatten()
1167    .unwrap_or(false);
1168    let v = Value::Object(vec![("status".into(), Value::String(if ok { "ok" } else { "store unavailable" }.into()))]);
1169    plain_json(if ok { 200 } else { 503 }, v, Cache::NoStore)
1170}
1171
1172/// Prometheus metrics.
1173#[utoipa::path(get, path = "/metrics", responses((status = 200, description = "Prometheus text", content_type = "text/plain")))]
1174async fn metrics(State(mesh): State<Mesh>) -> Response {
1175    let mut r = Reply::json(200, metrics_text(&mesh.inner).into_bytes(), Cache::NoStore);
1176    r.content_type = "text/plain; version=0.0.4";
1177    to_response(r)
1178}
1179
1180/// This document.
1181#[utoipa::path(get, path = "/openapi.json", responses((status = 200, description = "The OpenAPI document", content_type = "application/json")))]
1182async fn openapi_json() -> Response {
1183    let mut r = Reply::json(200, openapi().to_json().unwrap_or_default().into_bytes(), Cache::Public(300));
1184    r.content_type = JSON;
1185    to_response(r)
1186}
1187
1188pub(crate) fn metrics_text(inner: &Inner) -> String {
1189    use std::fmt::Write;
1190    use std::sync::atomic::Ordering::Relaxed;
1191    let mut out = String::new();
1192    inner.metrics.write(&mut out);
1193    let p = &inner.pool;
1194    let g = |out: &mut String, name: &str, help: &str, kind: &str, v: String| {
1195        let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}\n{name} {v}");
1196    };
1197    g(&mut out, "datumesh_pool_size", "The blocking pool's size: the concurrency limit.", "gauge", p.size.to_string());
1198    g(&mut out, "datumesh_pool_in_use", "Pool threads busy now.", "gauge", p.in_use.load(Relaxed).to_string());
1199    g(&mut out, "datumesh_pool_peak", "The most pool threads busy at once.", "gauge", p.peak.load(Relaxed).to_string());
1200    g(&mut out, "datumesh_pool_runs_total", "Tasks run on the pool.", "counter", p.runs.load(Relaxed).to_string());
1201    g(
1202        &mut out,
1203        "datumesh_pool_waited_total",
1204        "Tasks that found the pool saturated and waited for a thread.",
1205        "counter",
1206        p.waited.load(Relaxed).to_string(),
1207    );
1208    let (held, running) = inner.jobs.counts();
1209    g(&mut out, "datumesh_jobs_held", "Jobs held (running or done).", "gauge", held.to_string());
1210    g(&mut out, "datumesh_jobs_running", "Jobs running.", "gauge", running.to_string());
1211    g(
1212        &mut out,
1213        "datumesh_jobs_created_total",
1214        "Requests answered pending.",
1215        "counter",
1216        inner.jobs.created.load(Relaxed).to_string(),
1217    );
1218    g(
1219        &mut out,
1220        "datumesh_rate_limited_total",
1221        "Requests refused by a rate limit.",
1222        "counter",
1223        inner.limiter.refused.load(Relaxed).to_string(),
1224    );
1225    g(
1226        &mut out,
1227        "datumesh_peer_fetches_total",
1228        "Requests to other meshes.",
1229        "counter",
1230        inner.foreign.fetches.load(Relaxed).to_string(),
1231    );
1232    g(
1233        &mut out,
1234        "datumesh_peer_failures_total",
1235        "Requests to other meshes that failed.",
1236        "counter",
1237        inner.foreign.failures.load(Relaxed).to_string(),
1238    );
1239    g(
1240        &mut out,
1241        "datumesh_peer_imported_total",
1242        "Foreign versions imported into the store.",
1243        "counter",
1244        inner.foreign.imported.load(Relaxed).to_string(),
1245    );
1246    let m = inner.engine.memo_stats();
1247    g(&mut out, "datumesh_memo_entries", "Engine memo entries.", "gauge", m.entries.to_string());
1248    g(&mut out, "datumesh_memo_bytes", "Engine memo size, approximately.", "gauge", m.approx_bytes.to_string());
1249    g(
1250        &mut out,
1251        "datumesh_uptime_seconds",
1252        "Seconds since the mesh started.",
1253        "gauge",
1254        inner.started.elapsed().as_secs().to_string(),
1255    );
1256    out
1257}
1258
1259/// Request ids, the access log, metrics and `Accept`.
1260async fn around(State(mesh): State<Mesh>, req: Request, next: Next) -> Response {
1261    let start = Instant::now();
1262    let route = req.extensions().get::<MatchedPath>().map(|m| m.as_str().to_string()).unwrap_or_else(|| "other".into());
1263    let route = match route.as_str() {
1264        "/cell/{*rest}" => "/cell/{cell}".to_string(),
1265        "/slice/{*rest}" => "/slice/{cell}".to_string(),
1266        "/explain/{*rest}" => "/explain/{cell}".to_string(),
1267        "/versions/{*rest}" => "/versions/{cell}".to_string(),
1268        "/fn/{*name}" => "/fn/{name}".to_string(),
1269        "/takeover/{*domain}" => "/takeover/{domain}".to_string(),
1270        _ => route,
1271    };
1272    let id = req
1273        .headers()
1274        .get("x-request-id")
1275        .and_then(|v| v.to_str().ok())
1276        .filter(|s| !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
1277        .map(str::to_string)
1278        .unwrap_or_else(|| {
1279            let mut b = [0u8; 8];
1280            let _ = getrandom::fill(&mut b);
1281            lexical::to_hex(&b)
1282        });
1283    let ip = client_ip(&mesh.inner, req.headers(), peer_of(&req));
1284    let method = req.method().clone();
1285    let also = if route == "/slice/{cell}" { Some(crate::slice::ARROW) } else { None };
1286    // The function page is HTML for people (Build 2 Part 4, P2) as well as JSON for agents.
1287    let html_ok = (route == "/fn/{name}" || route == "/takeover/{domain}") && accepts(req.headers(), "text/html");
1288    let mut resp = if route != "/blob/{sha256}" && route != "/metrics" && !html_ok && !acceptable(req.headers(), also) {
1289        let mut r = Reply::json(
1290            406,
1291            Value::Object(vec![("error".into(), Value::String("not acceptable: application/json only".into()))])
1292                .to_jcs(),
1293            Cache::NoStore,
1294        );
1295        r.content_type = JSON;
1296        to_response(r)
1297    } else {
1298        next.run(req).instrument(tracing::info_span!("request", request_id = %id)).await
1299    };
1300    let elapsed = start.elapsed();
1301    let status = resp.status().as_u16();
1302    mesh.inner.metrics.record(&route, status, elapsed);
1303    let principal = resp.extensions().get::<Who>().and_then(|w| w.0.clone());
1304    tracing::info!(target: "datumesh_http::access", request_id = %id, %method, route = %route, status, ms = elapsed.as_secs_f64() * 1000.0, ip = %ip, principal = principal.as_deref().unwrap_or("-"), "request");
1305    if let Ok(v) = HeaderValue::from_str(&id) {
1306        resp.headers_mut().insert("x-request-id", v);
1307    }
1308    resp.headers_mut().insert(header::VARY, HeaderValue::from_static("Accept, Accept-Encoding, Authorization"));
1309    if let Ok(v) = HeaderValue::from_str(&format!("app;dur={:.3}", elapsed.as_secs_f64() * 1000.0)) {
1310        resp.headers_mut().insert("server-timing", v);
1311    }
1312    resp
1313}
1314
1315/// describe (SPEC 16.8): a class or an object, by class name, key encoding, object id, cell id or
1316/// short id (`{id}`, percent-encoded as a path). A class's method table gives each method its
1317/// `description` from the catalog entry `{class}/{method}` when that is 1 to 1,024 bytes.
1318/// `POST /whatif` (spec-0.6.0, 5.9): the scenario of a cell under overrides, labelled a scenario,
1319/// never a fact.
1320#[utoipa::path(post, path = "/whatif",
1321    request_body(content = String, description = "The JSON of 5.9: `cell`, `asof`?, `overrides`, `solve`?", content_type = "application/json"),
1322    responses(
1323        (status = 200, description = "`scenario`: `{asof, cell, overrides, type, value[, solved]}`, no receipt", content_type = "application/json"),
1324        (status = 400, description = "`bad_request`", content_type = "application/json"),
1325        (status = 404, description = "`not_covered`, with `fault` when the scenario faulted or has no solution", content_type = "application/json"),
1326        (status = 500, description = "`error`", content_type = "application/json"),
1327    ))]
1328async fn whatif(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
1329    let inner = mesh.inner.clone();
1330    let peer = peer_of(&req);
1331    let (client, principal) = match who(&inner, &headers, peer) {
1332        Ok(x) => x,
1333        Err(r) => return to_response(r),
1334    };
1335    if let Err(r) = admit(&inner, &client, 1) {
1336        return to_response(r);
1337    }
1338    let body = match axum::body::to_bytes(req.into_body(), 1 << 20).await {
1339        Ok(b) => b,
1340        Err(_) => return to_response(envelope::bad_request_reply(ErrorCode::CanonLimit)),
1341    };
1342    let mesh2 = mesh.clone();
1343    match inner.pool.clone().run(move || mesh2.whatif(&body, principal.as_ref())).await {
1344        Some(r) => to_response(r),
1345        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1346    }
1347}
1348
1349#[utoipa::path(get, path = "/describe/{id}",
1350    params(("id" = String, Path, description = "A class name, an object's key encoding, an object id, a cell id or a short id (12 hex digits).")),
1351    responses((status = 200, description = "A describe-class or describe-object document (SPEC 16.8)", content_type = "application/json"), (status = 400, description = "`E_KEY_ENCODING`, `E_KEY_NORMALISATION` or `E_SHORT_ID_AMBIGUOUS`", content_type = "application/json"), (status = 404, description = "An id the mesh does not know", content_type = "application/json")))]
1352async fn describe(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
1353    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1354        return r;
1355    }
1356    let Some(id) = crate::call::url_decode(uri.path().strip_prefix("/describe/").unwrap_or("")) else {
1357        return to_response(envelope::bad_request_reply(ErrorCode::CanonPercent));
1358    };
1359    let inner = mesh.inner.clone();
1360    match inner.pool.clone().run(move || mesh.describe(&id)).await {
1361        Some(r) => {
1362            // A function's page is named by a `Link` header, not a member of the answer (16.8 is
1363            // checked strictly by core; Build 2 Part 4, P2).
1364            let link = function_describe_link(&inner, &r);
1365            let mut resp = to_response(r);
1366            if let Some(v) = link.and_then(|l| HeaderValue::from_str(&l).ok()) {
1367                resp.headers_mut().insert(header::LINK, v);
1368            }
1369            resp
1370        }
1371        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1372    }
1373}
1374
1375/// The `Link` header of a describe answer for a function: its page, `rel="describedby"`.
1376fn function_describe_link(inner: &Inner, r: &Reply) -> Option<String> {
1377    if r.status != 200 {
1378        return None;
1379    }
1380    let v = json::parse(&r.body).ok()?;
1381    if v.get("kind")?.as_str()? != "function" {
1382        return None;
1383    }
1384    let name = v.get("fn")?.as_str()?;
1385    Some(format!("<{}>; rel=\"describedby\"", crate::fnpage::page_url(inner, name)))
1386}
1387
1388/// `POST /bundles` (Build 2 Part 4, P1): a publisher's bundle, checked and imported (see `bundles`).
1389async fn bundles(State(mesh): State<Mesh>, req: Request) -> Response {
1390    to_response(crate::bundles::post(mesh.inner.clone(), req.into_body()).await)
1391}
1392
1393/// `GET /fn/<name>` (Build 2 Part 4, P2): the function page, HTML or, by `Accept` or `?format=json`,
1394/// the same data as JSON.
1395async fn function_page(
1396    State(mesh): State<Mesh>,
1397    Path(name): Path<String>,
1398    uri: Uri,
1399    headers: HeaderMap,
1400    req: Request,
1401) -> Response {
1402    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1403        return r;
1404    }
1405    let format_json = uri.query().is_some_and(|q| q.split('&').any(|p| p == "format=json"));
1406    let json_form = format_json || (accepts(&headers, JSON) && !accepts(&headers, "text/html"));
1407    let inner = mesh.inner.clone();
1408    match inner.pool.clone().run(move || crate::fnpage::respond(&mesh.inner, &name, json_form)).await {
1409        Some(r) => to_response(r),
1410        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1411    }
1412}
1413
1414/// `GET /takeover/<domain>` (D24): what a source's domain can do to publish the values this mesh
1415/// relays from it; HTML, or JSON by `Accept` or `?format=json`.
1416#[utoipa::path(get, path = "/takeover/{domain}",
1417    params(("domain" = String, Path, description = "The source's DNS name (SPEC 2.1)")),
1418    responses(
1419        (status = 200, description = "`{\"domain\", \"host\", \"functions\": [{\"name\", \"page\", \"fn_hash\"}], \"steps\": [...]}`, or the HTML page", content_type = "application/json"),
1420        (status = 400, description = "E_CANON_NAME: not a DNS name", content_type = "application/json"),
1421        (status = 404, description = "not_covered: no function relayed from the domain on this mesh", content_type = "application/json")))]
1422async fn takeover_page(
1423    State(mesh): State<Mesh>,
1424    Path(domain): Path<String>,
1425    uri: Uri,
1426    headers: HeaderMap,
1427    req: Request,
1428) -> Response {
1429    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1430        return r;
1431    }
1432    let format_json = uri.query().is_some_and(|q| q.split('&').any(|p| p == "format=json"));
1433    let json_form = format_json || (accepts(&headers, JSON) && !accepts(&headers, "text/html"));
1434    let inner = mesh.inner.clone();
1435    match inner.pool.clone().run(move || crate::takeover::respond(&mesh.inner, &domain, json_form)).await {
1436        Some(r) => to_response(r),
1437        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1438    }
1439}
1440
1441async fn fallback() -> Response {
1442    not_found("endpoint")
1443}
1444
1445impl Mesh {
1446    /// The router of every endpoint. Serve it with
1447    /// `into_make_service_with_connect_info::<SocketAddr>()` (the client IP comes from it).
1448    pub fn router(&self) -> Router {
1449        Router::new()
1450            .route("/cell/{*rest}", get(cell))
1451            .route("/cells", post(cells))
1452            .route("/slice/{*rest}", get(slice))
1453            .route("/receipt/{hash}", get(receipt))
1454            .route("/descriptor/{hash}", get(descriptor))
1455            .route("/manifest/{slice_id}/{members_hash}", get(manifest))
1456            .route("/versions/{*rest}", get(versions))
1457            .route("/blob/{sha256}", get(blob))
1458            .route("/explain/{*rest}", get(explain))
1459            .route("/find", get(find))
1460            .route("/verify", post(verify_receipt))
1461            .route("/jobs/{job}", get(job))
1462            .route("/.well-known/datumesh.json", get(key_document))
1463            .route("/.well-known/datumesh-mesh.json", get(mesh_document))
1464            .route("/bindings", get(bindings))
1465            .route("/describe/{*id}", get(describe))
1466            .route("/fn/{*name}", get(function_page))
1467            .route("/takeover/{*domain}", get(takeover_page))
1468            .route("/bundles", post(bundles))
1469            .route("/whatif", post(whatif))
1470            .route("/health", get(health))
1471            .route("/metrics", get(metrics))
1472            .route("/openapi.json", get(openapi_json))
1473            .fallback(fallback)
1474            .layer(middleware::from_fn_with_state(self.clone(), around))
1475            .layer(tower_http::compression::CompressionLayer::new().gzip(true))
1476            .with_state(self.clone())
1477    }
1478
1479    /// Serves the router on `listener` until `shutdown` resolves.
1480    pub async fn serve(
1481        &self,
1482        listener: tokio::net::TcpListener,
1483        shutdown: impl std::future::Future<Output = ()> + Send + 'static,
1484    ) -> std::io::Result<()> {
1485        axum::serve(listener, self.router().into_make_service_with_connect_info::<SocketAddr>())
1486            .with_graceful_shutdown(shutdown)
1487            .await
1488    }
1489}
1490
1491impl IntoResponse for Reply {
1492    fn into_response(self) -> Response {
1493        to_response(self)
1494    }
1495}
1496
1497#[cfg(test)]
1498mod tests {
1499    use super::*;
1500
1501    fn reply(status: u16, body: &str) -> Reply {
1502        Reply::json(status, body.as_bytes().to_vec(), Cache::NoStore)
1503    }
1504
1505    /// The runs the chunks write, concatenated and closed, are the batch as 5.7 writes it, and
1506    /// count its outcomes.
1507    #[test]
1508    fn runs_make_the_batch() {
1509        let h = "a".repeat(64);
1510        let replies = [
1511            reply(200, &format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"value":"1"}},"trust":"primary"}}"#)),
1512            reply(400, r#"{"error":"E_CANON_NUMBER","outcome":"bad_request"}"#),
1513            reply(
1514                200,
1515                &format!(r#"{{"age_seconds":3,"fn_hash":"{h}","outcome":"stale","receipt":{{}},"trust":"computed"}}"#),
1516            ),
1517            reply(404, r#"{"error":"E_NAME_UNBOUND","outcome":"not_covered"}"#),
1518            reply(200, &format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"value":"2"}},"trust":"primary"}}"#)),
1519        ];
1520        let mut want = b"[".to_vec();
1521        for (i, r) in replies.iter().enumerate() {
1522            if i > 0 {
1523                want.push(b',');
1524            }
1525            want.extend_from_slice(b"{\"envelope\":");
1526            want.extend_from_slice(&r.body);
1527            want.extend_from_slice(format!(",\"status\":{}}}", r.status).as_bytes());
1528        }
1529        want.push(b']');
1530        for split in 1..replies.len() {
1531            let runs = [Written::of(true, replies[..split].iter()), Written::of(false, replies[split..].iter())];
1532            let mut got: Vec<u8> = runs.iter().flat_map(|w| w.bytes.iter().copied()).collect();
1533            got.push(b']');
1534            assert_eq!(String::from_utf8(got).unwrap(), String::from_utf8(want.clone()).unwrap());
1535            let mut counts = std::collections::BTreeMap::new();
1536            for (o, k) in runs.iter().flat_map(|w| w.outcomes.iter()) {
1537                *counts.entry(o.as_str()).or_insert(0) += k;
1538            }
1539            let want_counts: std::collections::BTreeMap<&str, u64> =
1540                [("bad_request", 1), ("not_covered", 1), ("ok", 2), ("stale", 1)].into_iter().collect();
1541            assert_eq!(counts, want_counts);
1542        }
1543        for (n, s) in [(0u16, "0"), (7, "7"), (200, "200"), (404, "404"), (65535, "65535")] {
1544            let mut out = Vec::new();
1545            push_u16(&mut out, n);
1546            assert_eq!(out, s.as_bytes());
1547        }
1548    }
1549
1550    /// The outcome of each envelope, whatever members come before it.
1551    #[test]
1552    fn outcomes() {
1553        let h = "0".repeat(64);
1554        for (body, want) in [
1555            (format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"outcome":"x"}}}}"#), Some("ok")),
1556            (r#"{"age_seconds":12,"outcome":"stale"}"#.to_string(), Some("stale")),
1557            (r#"{"error":"E_PARSE_URI","outcome":"bad_request"}"#.to_string(), Some("bad_request")),
1558            (r#"{"outcome":"pending","poll":"https://a.example/jobs/1"}"#.to_string(), Some("pending")),
1559            (r#"{"error":"no such endpoint"}"#.to_string(), None),
1560            (r#"{"outcome""#.to_string(), None),
1561        ] {
1562            assert_eq!(reply(200, &body).outcome_str(), want, "{body}");
1563            assert_eq!(reply(200, &body).outcome(), want.map(str::to_string), "{body}");
1564        }
1565        let mut arrow = reply(200, r#"{"outcome":"ok"}"#);
1566        arrow.content_type = "application/vnd.apache.arrow.stream";
1567        assert_eq!(arrow.outcome(), None);
1568    }
1569}