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        series_page,
204        series_sitemap,
205        whatif,
206        x_calc,
207        x_keys_challenge,
208        x_keys,
209        x_interval,
210        health,
211        metrics,
212        openapi_json
213    )
214)]
215struct ApiDoc;
216
217/// The OpenAPI document (generated from the handlers' annotations).
218pub fn openapi() -> utoipa::openapi::OpenApi {
219    ApiDoc::openapi()
220}
221
222/// The envelope of a cell.
223#[utoipa::path(get, path = "/cell/{cell}",
224    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=`.")),
225    responses(
226        (status = 200, description = "`ok` or `stale`", content_type = "application/json"),
227        (status = 202, description = "`pending`: poll the job (SPEC 5.5)", content_type = "application/json"),
228        (status = 400, description = "`bad_request`", content_type = "application/json"),
229        (status = 402, description = "`payment_required`", content_type = "application/json"),
230        (status = 403, description = "`unlicensed`", content_type = "application/json"),
231        (status = 404, description = "`not_covered` (with `fault` when the evaluation faulted)", content_type = "application/json"),
232        (status = 406, description = "the Accept header excludes JSON"),
233        (status = 429, description = "`rate_limited`, with `Retry-After`", content_type = "application/json"),
234        (status = 500, description = "`error`", content_type = "application/json"),
235        (status = 503, description = "`error`: the store or another mesh is unavailable", content_type = "application/json"),
236    ))]
237async fn cell(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
238    let inner = mesh.inner.clone();
239    let (client, principal) = match who(&inner, &headers, peer_of(&req)) {
240        Ok(x) => x,
241        Err(r) => return to_response(r),
242    };
243    let mut resp = match admit(&inner, &client, 1) {
244        Err(r) => to_response(r),
245        Ok(()) => {
246            let rest = rest_of(&uri, "/cell/");
247            let p = principal.clone();
248            let r = within_budget(inner.clone(), move |i, on| {
249                let now = i.now();
250                i.answer(&rest, p.as_ref(), i, &now, on)
251            })
252            .await;
253            if let Some(o) = r.outcome() {
254                inner.metrics.outcome("/cell/{cell}", &o);
255            }
256            to_response(r)
257        }
258    };
259    resp.extensions_mut().insert(Who(principal.map(|p| p.id)));
260    resp
261}
262
263/// A batch of cells.
264#[utoipa::path(post, path = "/cells",
265    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"),
266    responses(
267        (status = 200, description = "A JSON array of envelopes, in order; each has the HTTP status its outcome has (`error`: 500)", content_type = "application/json"),
268        (status = 400, description = "Not such an array, or too long", content_type = "application/json"),
269        (status = 429, description = "`rate_limited` (a batch of n cells counts as n / 50 requests)", content_type = "application/json"),
270    ))]
271async fn cells(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
272    let inner = mesh.inner.clone();
273    let peer = peer_of(&req);
274    let (client, principal) = match who(&inner, &headers, peer) {
275        Ok(x) => x,
276        Err(r) => return to_response(r),
277    };
278    let body = match axum::body::to_bytes(req.into_body(), 64 << 20).await {
279        Ok(b) => b,
280        Err(_) => return to_response(envelope::bad_request_reply(ErrorCode::CanonLimit)),
281    };
282    let items = match parse_batch(&body, inner.config.batch_max) {
283        Ok(i) => i,
284        // A refusal of the whole batch (5.7): one envelope.
285        Err((code, detail)) => {
286            tracing::info!(target: "datumesh_http", detail = %detail, "batch refused");
287            return to_response(envelope::bad_request_reply(code));
288        }
289    };
290    if let Err(r) = admit(&inner, &client, inner.limiter.batch_cost(items.len())) {
291        return to_response(r);
292    }
293    let pieces = batch(inner.clone(), items, principal.clone()).await;
294    let mut counts: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
295    for w in &pieces {
296        for (o, k) in &w.outcomes {
297            *counts.entry(o).or_default() += k;
298        }
299    }
300    for (o, k) in counts {
301        inner.metrics.outcomes("/cells", o, k);
302    }
303    // 5.7: [{"envelope": <the envelope>, "status": <its status>}] in request order: the
304    // chunks' runs as they wrote them (the first opening the array).
305    let mut out = Vec::with_capacity(pieces.iter().map(|w| w.bytes.len()).sum::<usize>() + 2);
306    for w in &pieces {
307        out.extend_from_slice(&w.bytes);
308    }
309    out.extend_from_slice(if pieces.is_empty() { b"[]" } else { b"]" });
310    let mut resp =
311        to_response(Reply::json(200, out, if principal.is_some() { Cache::Private } else { Cache::NoStore }));
312    resp.extensions_mut().insert(Who(principal.map(|p| p.id)));
313    resp
314}
315
316fn batch_error(e: &str) -> Response {
317    plain_json(400, Value::Object(vec![("error".into(), Value::String(e.to_string()))]), Cache::NoStore)
318}
319
320/// The batch's requests, or the code of its refusal: `E_PARSE_URI` for a body that is not an
321/// array of requests, `E_CANON_LIMIT` for more than the mesh accepts (5.7).
322fn parse_batch(body: &[u8], max: usize) -> Result<Vec<String>, (ErrorCode, String)> {
323    let pu = |m: String| (ErrorCode::ParseUri, m);
324    // The body is a list of requests, not a protocol object: plain JSON.
325    let v: serde_json::Value = serde_json::from_slice(body).map_err(|e| pu(format!("not JSON: {e}")))?;
326    let serde_json::Value::Array(items) = v else { return Err(pu("not a JSON array".into())) };
327    if items.len() > max {
328        return Err((ErrorCode::CanonLimit, format!("{} requests: at most {max}", items.len())));
329    }
330    items
331        .into_iter()
332        .map(|i| {
333            let s = match i {
334                serde_json::Value::String(s) => s,
335                serde_json::Value::Object(mut o) => match o.remove("cell") {
336                    Some(serde_json::Value::String(s)) => s,
337                    _ => return Err(pu("an object without a string cell".to_string())),
338                },
339                _ => return Err(pu("an item that is neither a string nor an object".to_string())),
340            };
341            Ok(match s.strip_prefix("cell://") {
342                Some(r) => r.to_string(),
343                None => s,
344            })
345        })
346        .collect()
347}
348
349/// A run of a batch's answers as 5.7 writes them: the items
350/// `{"envelope": <the envelope>, "status": <its status>}` (JCS member order) joined by commas,
351/// and how many of each outcome they hold. Each chunk writes its own on the pool, in
352/// parallel: reading 1,000 envelopes (each a receipt, the function hash echoed) to copy and
353/// count them is the costliest part of a warm batch after the answers themselves.
354#[derive(Default)]
355struct Written {
356    bytes: Vec<u8>,
357    outcomes: Vec<(String, u64)>,
358}
359
360impl Written {
361    /// The run of `replies`, opening the array when `first`, else continuing it.
362    fn of<'a>(first: bool, replies: impl Iterator<Item = &'a Reply> + Clone) -> Written {
363        let mut w = Written {
364            bytes: Vec::with_capacity(replies.clone().map(|r| r.body.len() + 32).sum::<usize>() + 1),
365            outcomes: vec![],
366        };
367        w.bytes.push(if first { b'[' } else { b',' });
368        for (i, r) in replies.enumerate() {
369            if i > 0 {
370                w.bytes.push(b',');
371            }
372            w.push(r);
373        }
374        w
375    }
376
377    fn push(&mut self, r: &Reply) {
378        self.bytes.extend_from_slice(b"{\"envelope\":");
379        self.bytes.extend_from_slice(&r.body);
380        self.bytes.extend_from_slice(b",\"status\":");
381        push_u16(&mut self.bytes, r.status);
382        self.bytes.push(b'}');
383        if let Some(o) = r.outcome_str() {
384            match self.outcomes.iter_mut().find(|(x, _)| x == o) {
385                Some((_, k)) => *k += 1,
386                None => self.outcomes.push((o.to_string(), 1)),
387            }
388        }
389    }
390}
391
392/// Appends `n` in decimal (a JSON integer).
393fn push_u16(out: &mut Vec<u8>, n: u16) {
394    let mut buf = [0u8; 5];
395    let (mut i, mut n) = (buf.len(), n);
396    loop {
397        i -= 1;
398        buf[i] = b'0' + (n % 10) as u8;
399        n /= 10;
400        if n == 0 {
401            break;
402        }
403    }
404    out.extend_from_slice(&buf[i..]);
405}
406
407/// The machine's parallelism, read once: `available_parallelism` reads the cgroup files on
408/// Linux (hundreds of microseconds in a container), too slow to pay on every batch.
409fn cores() -> usize {
410    static CORES: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
411    *CORES.get_or_init(|| std::thread::available_parallelism().map(|c| c.get()).unwrap_or(4))
412}
413
414/// Answers a batch within the budget: the requests are answered in chunks across the pool
415/// (one chunk per core; bindings looked up once per name and asof within the batch), each
416/// chunk writing its answers ([`Written`]). Those not answered within the budget become
417/// jobs: each is resolved again to the request it describes (a store read), and its chunk's
418/// answer completes the job. The runs are in request order.
419async fn batch(inner: Arc<Inner>, items: Vec<String>, principal: Option<Principal>) -> Vec<Written> {
420    let n = items.len();
421    let deadline = tokio::time::Instant::now() + inner.config.budget;
422    let chunks = n.div_ceil(64).clamp(1, inner.config.pool_size.min(cores()));
423    let per = n.div_ceil(chunks).max(1);
424    let ranges: Vec<(usize, usize)> =
425        (0..chunks).map(|c| (c * per, ((c + 1) * per).min(n))).take_while(|(lo, hi)| lo < hi).collect();
426    let now = inner.now();
427    let items = Arc::new(items);
428    // Each chunk's answers so far; once the budget has passed (`late`), its answers go to
429    // the channel instead, to complete their jobs. A chunk done within the budget leaves
430    // its answers written instead.
431    let shared: Slots = Arc::new(ranges.iter().map(|_| Mutex::new(Slot::default())).collect());
432    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<(usize, Reply)>();
433    let seen = Arc::new(crate::mesh::Seen::default());
434    let mut tasks = Vec::new();
435    for (c, &(lo, hi)) in ranges.iter().enumerate() {
436        let (i2, items, tx, p, now, shared) =
437            (inner.clone(), items.clone(), tx.clone(), principal.clone(), now.clone(), shared.clone());
438        let seen = seen.clone();
439        let pool = inner.pool.clone();
440        tasks.push(tokio::spawn(async move {
441            pool.run(move || {
442                let memo = Memo::shared(&i2, &seen);
443                for k in lo..hi {
444                    let reply = i2.answer_with(&items[k], p.as_ref(), &memo, &now, &mut |_| {}, false);
445                    let mut slot = shared[c].lock().unwrap_or_else(|p| p.into_inner());
446                    if slot.late {
447                        let _ = tx.send((k, reply));
448                    } else {
449                        slot.answers.push((k, reply));
450                    }
451                }
452                let mut slot = shared[c].lock().unwrap_or_else(|p| p.into_inner());
453                if !slot.late {
454                    let answers = std::mem::take(&mut slot.answers);
455                    slot.written = Some(Written::of(c == 0, answers.iter().map(|(_, r)| r)));
456                }
457            })
458            .await
459        }));
460    }
461    drop(tx);
462    let all = futures_join(&mut tasks, deadline).await;
463    let mut done: Vec<Option<Reply>> = vec![None; n];
464    let mut written: Vec<Option<Written>> = Vec::with_capacity(ranges.len());
465    for slot in shared.iter() {
466        let mut s = slot.lock().unwrap_or_else(|p| p.into_inner());
467        s.late = true;
468        for (k, r) in s.answers.drain(..) {
469            done[k] = Some(r);
470        }
471        written.push(s.written.take());
472    }
473    // A chunk's run: as it wrote it, else its answers (an error for any it has none of: its
474    // task panicked, or the answer completes a job).
475    let runs = |done: Vec<Option<Reply>>, written: Vec<Option<Written>>| -> Vec<Written> {
476        let error = envelope::error_reply(ErrorCode::EvalUnavailable);
477        ranges
478            .iter()
479            .zip(written)
480            .enumerate()
481            .map(|(c, (&(lo, hi), w))| {
482                w.unwrap_or_else(|| Written::of(c == 0, done[lo..hi].iter().map(|d| d.as_ref().unwrap_or(&error))))
483            })
484            .collect()
485    };
486    if all {
487        return runs(done, written);
488    }
489    // Past the budget: every request not answered yet becomes a job, resolved again to the
490    // request it describes.
491    let open: Vec<usize> = ranges
492        .iter()
493        .zip(&written)
494        .filter(|(_, w)| w.is_none())
495        .flat_map(|(&(lo, hi), _)| lo..hi)
496        .filter(|k| done[*k].is_none())
497        .collect();
498    let (i2, items2, open2, now2) = (inner.clone(), items.clone(), open.clone(), now.clone());
499    let requests: Vec<Option<CoreRequest>> = inner
500        .pool
501        .run(move || {
502            let memo = Memo::new(&i2);
503            open2
504                .iter()
505                .map(|k| {
506                    crate::call::resolve(&items2[*k], &now2, &i2.config.aliases, &memo, false)
507                        .ok()
508                        .and_then(|t| request_of(&t))
509                })
510                .collect()
511        })
512        .await
513        .unwrap_or_default();
514    let poll_base = format!("{}/jobs/", inner.config.origin());
515    let est = inner.jobs.estimate(inner.config.budget.as_secs());
516    let mut jobs: Vec<Option<String>> = vec![None; n];
517    for (i, k) in open.iter().enumerate() {
518        let reply = match requests.get(i).cloned().flatten() {
519            Some(req) => match inner.jobs.create(req.clone()) {
520                Some(id) => {
521                    let p = Pending::new(&id, est, &format!("{poll_base}{id}"), req);
522                    jobs[*k] = Some(id);
523                    match p {
524                        Ok(p) => Reply::json(202, envelope::pending(&p), Cache::NoStore),
525                        Err(_) => envelope::error_reply(ErrorCode::EvalUnavailable),
526                    }
527                }
528                None => envelope::error_reply(ErrorCode::EvalUnavailable),
529            },
530            None => envelope::error_reply(ErrorCode::EvalUnavailable),
531        };
532        done[*k] = Some(reply);
533    }
534    let i3 = inner.clone();
535    tokio::spawn(async move {
536        while let Some((k, mut reply)) = rx.recv().await {
537            if let Some(id) = &jobs[k] {
538                reply.cache = Cache::NoStore;
539                reply.canonical = None;
540                i3.jobs.complete(id, reply);
541            }
542        }
543        for t in tasks {
544            let _ = t.await;
545        }
546        // Jobs whose task ended without an answer (a panic) are given up.
547        for id in jobs.into_iter().flatten() {
548            if let Poll::Running(..) = i3.jobs.poll_peek(&id) {
549                i3.jobs.complete(&id, envelope::error_reply(ErrorCode::EvalUnavailable));
550            }
551        }
552    });
553    runs(done, written)
554}
555
556/// A batch chunk's state: whether the budget has passed, its answers so far, and its
557/// answers written once it is done within the budget.
558#[derive(Default)]
559struct Slot {
560    late: bool,
561    answers: Vec<(usize, Reply)>,
562    written: Option<Written>,
563}
564
565/// Each batch chunk's state.
566type Slots = Arc<Vec<Mutex<Slot>>>;
567
568/// Waits for every task until `deadline`: whether all finished.
569async fn futures_join(tasks: &mut [tokio::task::JoinHandle<Option<()>>], deadline: tokio::time::Instant) -> bool {
570    for t in tasks.iter_mut() {
571        if t.is_finished() {
572            continue;
573        }
574        if tokio::time::timeout_at(deadline, t).await.is_err() {
575            return false;
576        }
577    }
578    true
579}
580
581/// The versions of a stored cell (SPEC 9.8, spec-0.4.2).
582#[utoipa::path(get, path = "/versions/{cell}",
583    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.")),
584    responses(
585        (status = 200, description = "`{\"cell\", \"versions\": [{\"asof\", \"receipt\", \"tx\"}], \"next\"?}` ascending by tx", content_type = "application/json"),
586        (status = 400, description = "`bad_request`", content_type = "application/json"),
587        (status = 404, description = "`not_covered` (with `E_NAME_UNBOUND` for an unbound name)", content_type = "application/json"),
588    ))]
589async fn versions(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
590    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
591        return r;
592    }
593    let inner = mesh.inner.clone();
594    let rest = rest_of(&uri, "/versions/");
595    let r = inner
596        .pool
597        .clone()
598        .run(move || inner.versions(&rest))
599        .await
600        .unwrap_or_else(|| envelope::error_reply(ErrorCode::EvalUnavailable));
601    to_response(r)
602}
603
604/// The most versions in one answer of the versions endpoint.
605const VERSIONS_PAGE: usize = 1000;
606
607/// `GET /x/versions/<cell>` (guard patch G9): the versions of a stored cell, ascending by the time
608/// the mesh recorded them, each with its signed time beside it. `GET /versions` keeps the spec's
609/// shape, where `tx` is the signed time.
610#[utoipa::path(get, path = "/x/versions/{cell}",
611    params(("cell" = String, Path, description = "A cell URI's rest without asof, as `/versions`.")),
612    responses(
613        (status = 200, description = "`{cell, versions: [{recorded, signed, asof, receipt}]}` ascending by recorded", content_type = "application/json"),
614        (status = 400, description = "`bad_request`", content_type = "application/json"),
615        (status = 404, description = "`not_covered`", content_type = "application/json"),
616    ))]
617async fn x_versions(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
618    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
619        return r;
620    }
621    let inner = mesh.inner.clone();
622    let rest = rest_of(&uri, "/x/versions/");
623    let r = inner
624        .pool
625        .clone()
626        .run(move || inner.x_versions(&rest))
627        .await
628        .unwrap_or_else(|| envelope::error_reply(ErrorCode::EvalUnavailable));
629    to_response(r)
630}
631
632impl Inner {
633    /// The body of `GET /x/versions/<cell>`: every version of the cell, by recorded time.
634    fn x_versions(&self, rest: &str) -> Reply {
635        let now = self.now();
636        let target = match crate::call::resolve(rest, &now, &self.config.aliases, self, false) {
637            Ok(t) => t,
638            Err(r) => return self.rejection(r, None),
639        };
640        if target.asof().is_some() {
641            return envelope::bad_request_reply(ErrorCode::ParseUri);
642        }
643        let mut vs =
644            match self.store.versions(target.cell_id(), "0001-01-01T00:00:00.000000Z", "9999-12-31T23:59:59.999999Z") {
645                Ok(v) => v,
646                Err(_) => {
647                    return envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(&target.bound.fn_hash))
648                }
649            };
650        vs.sort_by(|a, b| (&a.recorded, a.seq).cmp(&(&b.recorded, b.seq)));
651        vs.truncate(VERSIONS_PAGE);
652        let list: Vec<Value> = vs
653            .iter()
654            .map(|v| {
655                Value::Object(vec![
656                    ("recorded".into(), Value::String(v.recorded.clone())),
657                    ("signed".into(), Value::String(v.tx.clone())),
658                    ("asof".into(), Value::String(v.asof.clone())),
659                    ("receipt".into(), Value::String(v.receipt_hash.clone())),
660                ])
661            })
662            .collect();
663        let body = Value::Object(vec![
664            ("cell".into(), Value::String(target.cell_id().to_string())),
665            ("versions".into(), Value::Array(list)),
666        ]);
667        Reply::json(200, body.to_jcs(), Cache::Public(60))
668    }
669}
670
671impl Inner {
672    fn versions(&self, rest: &str) -> Reply {
673        // `from=` and `to=` are the endpoint's, taken off the end of the query.
674        let (path, query) = match rest.split_once('?') {
675            Some((p, q)) => (p, q),
676            None => (rest, ""),
677        };
678        let mut ps: Vec<&str> = if query.is_empty() { vec![] } else { query.split('&').collect() };
679        let (mut from, mut to) = (None, None);
680        while let Some(last) = ps.last() {
681            if let Some(v) = last.strip_prefix("from=") {
682                from = Some(crate::instant::canonical_or_same(v, false));
683            } else if let Some(v) = last.strip_prefix("to=") {
684                to = Some(crate::instant::canonical_or_same(v, false));
685            } else {
686                break;
687            }
688            ps.pop();
689        }
690        for t in [&from, &to].into_iter().flatten() {
691            if lexical::check_instant(t, "$").is_err() {
692                return envelope::bad_request_reply(ErrorCode::CanonInstant);
693            }
694        }
695        let cell_rest = if ps.is_empty() { path.to_string() } else { format!("{path}?{}", ps.join("&")) };
696        let now = self.now();
697        let target = match crate::call::resolve(&cell_rest, &now, &self.config.aliases, self, false) {
698            Ok(t) => t,
699            Err(r) => return self.rejection(r, None),
700        };
701        if target.asof().is_some() {
702            return envelope::bad_request_reply(ErrorCode::ParseUri);
703        }
704        let lo = from.unwrap_or_else(|| "0001-01-01T00:00:00.000000Z".into());
705        let hi = to.clone().unwrap_or_else(|| "9999-12-31T23:59:59.999999Z".into());
706        // One more than a page, to know there is a next (CONTRACT-0.4.9 H5): the store stops there.
707        let mut vs = match self.store.versions_limit(target.cell_id(), &lo, &hi, VERSIONS_PAGE + 1) {
708            Ok(v) => v,
709            Err(_) => return envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(&target.bound.fn_hash)),
710        };
711        vs.sort_by(|a, b| (&a.tx, &a.receipt_hash).cmp(&(&b.tx, &b.receipt_hash)));
712        let more = vs.len() > VERSIONS_PAGE;
713        vs.truncate(VERSIONS_PAGE);
714        let list: Vec<Value> = vs
715            .iter()
716            .map(|v| {
717                Value::Object(vec![
718                    ("asof".into(), Value::String(v.asof.clone())),
719                    ("receipt".into(), Value::String(v.receipt_hash.clone())),
720                    ("tx".into(), Value::String(v.tx.clone())),
721                ])
722            })
723            .collect();
724        let mut body = vec![("cell".to_string(), target.cell.to_value()), ("versions".to_string(), Value::Array(list))];
725        if more {
726            if let Some(last) = vs.last() {
727                let us = datumesh_formula::calendar::parse_instant(&last.tx).unwrap_or(0) + 1;
728                let next_from = datumesh_formula::calendar::instant_text(us).unwrap_or_default();
729                let mut next = format!("{}/versions/{cell_rest}", self.config.origin());
730                next.push(if cell_rest.contains('?') { '&' } else { '?' });
731                next.push_str(&format!("from={next_from}"));
732                if let Some(t) = &to {
733                    next.push_str(&format!("&to={t}"));
734                }
735                body.push(("next".to_string(), Value::String(next)));
736            }
737        }
738        Reply::json(200, Value::Object(body).to_jcs(), Cache::Public(self.config.ttl.latest_max_age.as_secs()))
739    }
740}
741
742/// The members of a slice.
743#[utoipa::path(get, path = "/slice/{cell}",
744    params(
745        ("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)."),
746    ),
747    responses(
748        (status = 200, description = "JSON page of members, or with `Accept: application/vnd.apache.arrow.stream` an Arrow IPC stream", content_type = "application/json"),
749        (status = 400, description = "`bad_request`", content_type = "application/json"),
750        (status = 404, description = "`not_covered`", content_type = "application/json"),
751    ))]
752async fn slice(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
753    let inner = mesh.inner.clone();
754    let (client, _) = match who(&inner, &headers, peer_of(&req)) {
755        Ok(x) => x,
756        Err(r) => return to_response(r),
757    };
758    if let Err(r) = admit(&inner, &client, 1) {
759        return to_response(r);
760    }
761    // A browser on a listed series is sent to its page (Build 2 Part 6, G1): never cached.
762    let rest = rest_of(&uri, "/slice/");
763    if crate::series::redirect_reads_store(&inner, &rest, &headers) {
764        // The call is resolved against the store: on the pool, not on this thread (0.4.7).
765        let (i2, r2, h2) = (inner.clone(), rest.clone(), headers.clone());
766        match inner.pool.clone().run(move || crate::series::slice_redirect(&i2, &r2, &h2)).await {
767            None => return to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
768            Some(Some(to)) => return see_other(&to),
769            // no redirect: the middleware left the `Accept` check to this point
770            Some(None) if !acceptable(&headers, Some(crate::slice::ARROW)) => return not_acceptable(),
771            Some(None) => {}
772        }
773    } else if let Some(to) = crate::series::slice_redirect(&inner, &rest, &headers) {
774        return see_other(&to);
775    }
776    let (rest, format) = match crate::slice::split_format(&rest) {
777        Ok(x) => x,
778        Err(c) => return to_response(envelope::bad_request_reply(c)),
779    };
780    // `?format=` is its own address; without it, an Accept that chooses Arrow gets Arrow, uncached (G1).
781    let accept_arrow = format.is_none() && accepts(&headers, crate::slice::ARROW);
782    let form = if accept_arrow { crate::slice::Form::Arrow } else { format.unwrap_or_default() };
783    let (r, next) = inner
784        .pool
785        .clone()
786        .run(move || {
787            let now = inner.now();
788            inner.slice(&rest, &now, form)
789        })
790        .await
791        .unwrap_or_else(|| (envelope::error_reply(ErrorCode::EvalUnavailable), None));
792    let mut r = r;
793    if accept_arrow {
794        r.cache = Cache::NoStore;
795    }
796    let mut resp = to_response(r);
797    // A whole-slice page that names a `limit` and has more after it: the `Link` to the next (CONTRACT-protocol-part1 H2).
798    if let Some(v) = next.and_then(|n| HeaderValue::from_str(&format!("<{n}>; rel=\"next\"")).ok()) {
799        resp.headers_mut().insert(header::LINK, v);
800    }
801    resp
802}
803
804/// `303 See Other` to `location`, `no-store`.
805fn see_other(location: &str) -> Response {
806    let mut resp = Response::new(Body::empty());
807    *resp.status_mut() = StatusCode::SEE_OTHER;
808    if let Ok(v) = HeaderValue::from_str(location) {
809        resp.headers_mut().insert(header::LOCATION, v);
810    }
811    resp.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
812    resp
813}
814
815fn accepts(headers: &HeaderMap, media: &str) -> bool {
816    headers
817        .get_all(header::ACCEPT)
818        .iter()
819        .filter_map(|v| v.to_str().ok())
820        .any(|v| v.split(',').any(|p| p.split(';').next().unwrap_or("").trim() == media))
821}
822
823/// Whether the client takes JSON (no `Accept`, `*/*`, `application/*` or
824/// `application/json`); for slices also Arrow.
825/// The `406` of a request whose `Accept` allows no media type the route has.
826fn not_acceptable() -> Response {
827    let mut r = Reply::json(
828        406,
829        Value::Object(vec![("error".into(), Value::String("not acceptable: application/json only".into()))]).to_jcs(),
830        Cache::NoStore,
831    );
832    r.content_type = JSON;
833    to_response(r)
834}
835
836fn acceptable(headers: &HeaderMap, also: Option<&str>) -> bool {
837    let vals: Vec<&str> = headers.get_all(header::ACCEPT).iter().filter_map(|v| v.to_str().ok()).collect();
838    if vals.is_empty() {
839        return true;
840    }
841    vals.iter().flat_map(|v| v.split(',')).any(|p| {
842        let mut parts = p.split(';');
843        let m = parts.next().unwrap_or("").trim();
844        let q0 = parts.any(|x| {
845            let x = x.trim();
846            x == "q=0" || x == "q=0.0" || x == "q=0.00" || x == "q=0.000"
847        });
848        !q0 && (m == "*/*" || m == "application/*" || m == JSON || also == Some(m))
849    })
850}
851
852async fn object(
853    inner: Arc<Inner>,
854    what: &'static str,
855    f: impl FnOnce(&Inner) -> Option<Vec<u8>> + Send + 'static,
856) -> Response {
857    let i2 = inner.clone();
858    match inner.pool.run(move || f(&i2)).await.flatten() {
859        Some(bytes) => {
860            let ct = if what == "blob" { "application/octet-stream" } else { JSON };
861            to_response(Reply {
862                status: 200,
863                body: bytes.into(),
864                content_type: ct,
865                cache: Cache::Immutable,
866                canonical: None,
867                retry_after: None,
868            })
869        }
870        None => not_found(what),
871    }
872}
873
874/// The refusal of a request by its client's rate limit (or key), if it is refused.
875fn ip_admit(inner: &Inner, headers: &HeaderMap, req: &Request) -> Option<Response> {
876    let client = match who(inner, headers, peer_of(req)) {
877        Ok((c, _)) => c,
878        Err(r) => return Some(to_response(r)),
879    };
880    admit(inner, &client, 1).err().map(to_response)
881}
882
883/// A receipt by its hash (canonical bytes; gzip when asked).
884#[utoipa::path(get, path = "/receipt/{hash}", params(("hash" = String, Path, description = "The receipt hash (SPEC 8.3).")),
885    responses((status = 200, description = "The receipt's canonical JSON; immutable", content_type = "application/json"), (status = 404, description = "Not held")))]
886async fn receipt(State(mesh): State<Mesh>, Path(hash): Path<String>, headers: HeaderMap, req: Request) -> Response {
887    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
888        return r;
889    }
890    if lexical::check_hex(&hash, 64, "$").is_err() {
891        return not_found("receipt");
892    }
893    object(mesh.inner.clone(), "receipt", move |i| i.store.receipt(&hash).map(|c| c.into_owned())).await
894}
895
896/// A descriptor by its function hash.
897#[utoipa::path(get, path = "/descriptor/{hash}", params(("hash" = String, Path, description = "The function hash.")),
898    responses((status = 200, description = "The descriptor's canonical JSON; immutable", content_type = "application/json"), (status = 404, description = "Not held")))]
899async fn descriptor(State(mesh): State<Mesh>, Path(hash): Path<String>, headers: HeaderMap, req: Request) -> Response {
900    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
901        return r;
902    }
903    if lexical::check_hex(&hash, 64, "$").is_err() {
904        return not_found("descriptor");
905    }
906    object(mesh.inner.clone(), "descriptor", move |i| i.store.descriptor(&hash).map(|c| c.into_owned())).await
907}
908
909/// A slice manifest (SPEC 15.13), by its entry's slice id and members hash: held, or rebuilt from
910/// its members (G5, G10). `?after=&limit=` is the paged form; `?asof=` rebuilds a past read's list.
911#[utoipa::path(get, path = "/manifest/{slice_id}/{members_hash}",
912    params(("slice_id" = String, Path, description = "The slice id."), ("members_hash" = String, Path, description = "The members hash."),
913        ("after" = Option<String>, Query, description = "Paged: the members after this hash (exclusive)."),
914        ("limit" = Option<String>, Query, description = "Paged: at most this many members (1 to 10,000; default 1,000)."),
915        ("asof" = Option<String>, Query, description = "Rebuild as of this instant, from the slice's definition.")),
916    responses((status = 200, description = "The manifest's canonical JSON (immutable), or a page", content_type = "application/json"),
917        (status = 404, description = "Not held and not rebuildable"),
918        (status = 503, description = "`E_INPUT_UNAVAILABLE` (the members do not hash to the entry) or `E_EVAL_BUDGET`")))]
919async fn manifest(
920    State(mesh): State<Mesh>,
921    Path((slice_id, members)): Path<(String, String)>,
922    Query(q): Query<crate::manifest_route::ManifestQuery>,
923    headers: HeaderMap,
924    req: Request,
925) -> Response {
926    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
927        return r;
928    }
929    if lexical::check_hex(&slice_id, 64, "$").is_err() || lexical::check_hex(&members, 64, "$").is_err() {
930        return not_found("manifest");
931    }
932    let (pool, inner) = (mesh.inner.pool.clone(), mesh.inner.clone());
933    let (reply, next) = pool
934        .run(move || crate::manifest_route::reply(&inner, &slice_id, &members, &q))
935        .await
936        .unwrap_or_else(|| (envelope::error_reply(ErrorCode::EvalUnavailable), None));
937    let mut resp = to_response(reply);
938    if let Some(v) = next.and_then(|n| HeaderValue::from_str(&format!("<{n}>; rel=\"next\"")).ok()) {
939        resp.headers_mut().insert(header::LINK, v);
940    }
941    resp
942}
943
944/// Blob content by SHA-256.
945#[utoipa::path(get, path = "/blob/{sha256}", params(("sha256" = String, Path, description = "The content's SHA-256.")),
946    responses((status = 200, description = "The bytes; immutable", content_type = "application/octet-stream"), (status = 404, description = "Not held")))]
947async fn blob(State(mesh): State<Mesh>, Path(sha): Path<String>, headers: HeaderMap, req: Request) -> Response {
948    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
949        return r;
950    }
951    if lexical::check_hex(&sha, 64, "$").is_err() {
952        return not_found("blob");
953    }
954    object(mesh.inner.clone(), "blob", move |i| i.store.blob(&sha).ok().flatten().map(|c| c.into_owned())).await
955}
956
957/// A cell's lineage as nested envelopes.
958#[utoipa::path(get, path = "/explain/{cell}",
959    params(("cell" = String, Path, description = "As for /cell; `depth=` (default 4, at most 16) bounds the walk.")),
960    responses(
961        (status = 200, description = "`{\"envelope\", \"inputs\": [{\"entry\", \"envelope\", \"inputs\"} | {\"entry\", \"slice\", \"members\"}], \"truncated\"}`", content_type = "application/json"),
962        (status = 202, description = "`pending`: the cell is being computed; ask again", content_type = "application/json"),
963        (status = 400, description = "`bad_request`", content_type = "application/json"),
964        (status = 404, description = "`not_covered`", content_type = "application/json"),
965    ))]
966async fn explain(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
967    let inner = mesh.inner.clone();
968    let (client, principal) = match who(&inner, &headers, peer_of(&req)) {
969        Ok(x) => x,
970        Err(r) => return to_response(r),
971    };
972    if let Err(r) = admit(&inner, &client, 1) {
973        return to_response(r);
974    }
975    let mut rest = rest_of(&uri, "/explain/");
976    let mut depth = inner.config.explain_depth;
977    // `depth=` is the explain's own parameter: taken off the query.
978    if let Some((p, q)) = rest.clone().split_once('?') {
979        let kept: Vec<&str> = q.split('&').filter(|x| !x.starts_with("depth=")).collect();
980        if let Some(d) = q.split('&').find_map(|x| x.strip_prefix("depth=")) {
981            depth = d.parse::<usize>().unwrap_or(depth);
982        }
983        rest = if kept.is_empty() { p.to_string() } else { format!("{p}?{}", kept.join("&")) };
984    }
985    let depth = depth.min(16);
986    let r = within_budget(inner, move |i, on| {
987        let now = i.now();
988        let r = i.answer(&rest, principal.as_ref(), i, &now, on);
989        if r.status != 200 {
990            return r;
991        }
992        let env = json::parse(&r.body).unwrap_or(Value::Null);
993        let mut budget = 2_000usize;
994        let v = i.explain_node(env, depth, &mut budget);
995        Reply::json(200, v.to_jcs(), Cache::NoStore)
996    })
997    .await;
998    to_response(r)
999}
1000
1001impl Inner {
1002    /// An envelope with its inputs' envelopes, `depth` levels down, at most `budget` nodes.
1003    fn explain_node(&self, envelope: Value, depth: usize, budget: &mut usize) -> Value {
1004        let inputs: Vec<String> = envelope
1005            .get("receipt")
1006            .and_then(|r| r.get("inputs"))
1007            .and_then(|i| {
1008                if let Value::Array(a) = i {
1009                    Some(a.iter().filter_map(Value::as_str).map(str::to_string).collect())
1010                } else {
1011                    None
1012                }
1013            })
1014            .unwrap_or_default();
1015        let mut truncated = false;
1016        let mut out = Vec::new();
1017        for e in inputs {
1018            if depth == 0 || *budget == 0 {
1019                truncated = true;
1020                break;
1021            }
1022            *budget -= 1;
1023            if e.starts_with("slice:") {
1024                // G6: the count and the slice come from the member-set row (or a held manifest); no rebuild.
1025                let mut node = vec![("entry".to_string(), Value::String(e.clone()))];
1026                if let Some((members, slice)) = crate::manifest_route::count_and_slice(self, &e) {
1027                    node.push(("members".to_string(), envelope::num(members)));
1028                    node.push(("slice".to_string(), slice));
1029                }
1030                out.push(Value::Object(node));
1031                continue;
1032            }
1033            let child = match self.receipt_info_by_hash(&e) {
1034                Some(info) => self.explain_node(json::parse(&info.ok).unwrap_or(Value::Null), depth - 1, budget),
1035                None => json::parse(&envelope::not_covered(None)).unwrap_or(Value::Null),
1036            };
1037            let mut node = vec![("entry".to_string(), Value::String(e.clone()))];
1038            if let Value::Object(m) = child {
1039                node.extend(m);
1040            }
1041            out.push(Value::Object(node));
1042        }
1043        let mut node = vec![("envelope".to_string(), envelope.clone()), ("inputs".to_string(), Value::Array(out))];
1044        node.push(("truncated".to_string(), Value::Bool(truncated)));
1045        Value::Object(node)
1046    }
1047}
1048
1049#[derive(serde::Deserialize)]
1050struct FindQuery {
1051    q: Option<String>,
1052    limit: Option<usize>,
1053    summary: Option<String>,
1054}
1055
1056/// `Retry-After` of a find answer before the find thread's first build (CONTRACT-0.4.9 H4).
1057const FIND_RETRY_SECS: u64 = 5;
1058
1059/// The hybrid `/find` (CONTRACT-build2-part2-read R3; see `crate::find`), and `/find?summary=1`.
1060#[utoipa::path(get, path = "/find",
1061    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.")),
1062    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")))]
1063async fn find(State(mesh): State<Mesh>, Query(q): Query<FindQuery>, headers: HeaderMap, req: Request) -> Response {
1064    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1065        return r;
1066    }
1067    let inner = mesh.inner.clone();
1068    let query = q.q.unwrap_or_default();
1069    let limit = q.limit.unwrap_or(crate::find::DEFAULT_LIMIT).clamp(1, crate::find::MAX_LIMIT);
1070    let summary = q.summary.as_deref() == Some("1");
1071    // The summary and the empty query are read from the find thread's last build (CONTRACT-0.4.9 H4): before
1072    // its first build they are `503`. Any other query is answered on the request.
1073    let empty = crate::find::query_words(&query).is_empty();
1074    let r = inner
1075        .pool
1076        .clone()
1077        .run(move || {
1078            if summary {
1079                crate::find::summary(&inner)
1080            } else if empty {
1081                crate::find::empty_answer(&inner, limit)
1082            } else {
1083                Some(crate::find::answer(&inner, &query, limit))
1084            }
1085        })
1086        .await
1087        .unwrap_or(None);
1088    match r {
1089        Some(v) => plain_json(200, v, Cache::Public(60)),
1090        None => to_response(crate::envelope::not_yet_reply(FIND_RETRY_SECS, "The catalogue summary")),
1091    }
1092}
1093
1094#[derive(serde::Deserialize)]
1095struct VerifyQuery {
1096    level: Option<String>,
1097    blob: Option<String>,
1098    form: Option<String>,
1099}
1100
1101/// Verification as a service: the core verifier on a submitted receipt, with this mesh's
1102/// keys; free, unauthenticated, rate-limited per IP.
1103#[utoipa::path(post, path = "/verify",
1104    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.")),
1105    request_body(content = String, description = "The receipt's JSON text, exactly as received (or the offered form).", content_type = "application/json"),
1106    responses(
1107        (status = 200, description = "`{\"ok\", \"level\", \"code\", \"hash\", \"computed_by\", \"path\", \"detail\", \"blob_checked\"}`", content_type = "application/json"),
1108        (status = 429, description = "`rate_limited`", content_type = "application/json"),
1109    ))]
1110async fn verify_receipt(
1111    State(mesh): State<Mesh>,
1112    Query(q): Query<VerifyQuery>,
1113    headers: HeaderMap,
1114    req: Request,
1115) -> Response {
1116    let inner = mesh.inner.clone();
1117    let ip = client_ip(&inner, &headers, peer_of(&req));
1118    if let Err(s) = inner.limiter.admit_verify(ip) {
1119        return to_response(envelope::rate_limited_reply(s));
1120    }
1121    let body: Bytes = match axum::body::to_bytes(req.into_body(), 4 << 20).await {
1122        Ok(b) => b,
1123        Err(_) => return batch_error("body too large"),
1124    };
1125    if q.form.as_deref() == Some("offered") {
1126        let Ok(v) = json::parse(&body) else { return batch_error("form=offered: not strict JSON") };
1127        let Some(receipt) = v.get("receipt").and_then(Value::as_str).map(|s| s.as_bytes().to_vec()) else {
1128            return batch_error("form=offered: no receipt text");
1129        };
1130        let blob = match v.get("blob_hex").and_then(Value::as_str).map(hex) {
1131            None => None,
1132            Some(Some(b)) if b.len() <= 1 << 20 => Some(b),
1133            Some(_) => return batch_error("blob_hex: hex of at most 1 MiB"),
1134        };
1135        let m = mesh.clone();
1136        let rc = v.get("recompute").cloned();
1137        let r = inner.pool.run(move || m.verify_offered(&receipt, rc.as_ref(), blob.as_deref())).await;
1138        return match r {
1139            Some(v) => to_response(Reply::json(200, v.body, Cache::NoStore)),
1140            None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1141        };
1142    }
1143    let signed = q.level.as_deref() == Some("signed");
1144    let blob = match q.blob.as_deref().map(hex) {
1145        None => None,
1146        Some(Some(b)) if b.len() <= 1 << 20 => Some(b),
1147        Some(_) => return batch_error("blob: hex of at most 1 MiB"),
1148    };
1149    let m = mesh.clone();
1150    let r = inner.pool.run(move || m.verify(&body, signed, blob.as_deref())).await;
1151    match r {
1152        Some(v) => to_response(Reply::json(200, v.body, Cache::NoStore)),
1153        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1154    }
1155}
1156
1157fn hex(s: &str) -> Option<Vec<u8>> {
1158    if !s.len().is_multiple_of(2) {
1159        return None;
1160    }
1161    (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
1162}
1163
1164/// A job: `pending` again while it runs, then the envelope of the original request.
1165#[utoipa::path(get, path = "/jobs/{job}", params(("job" = String, Path, description = "The job id of a `pending` envelope.")),
1166    responses(
1167        (status = 202, description = "`pending`, the same job and request", content_type = "application/json"),
1168        (status = 400, description = "`bad_request` with `E_JOB_UNKNOWN`: unknown or expired", content_type = "application/json"),
1169        (status = 200, description = "The completed envelope (any outcome but pending, with its status), bound to the original request", content_type = "application/json"),
1170    ))]
1171async fn job(State(mesh): State<Mesh>, Path(id): Path<String>, headers: HeaderMap, req: Request) -> Response {
1172    let inner = mesh.inner.clone();
1173    let (client, _) = match who(&inner, &headers, peer_of(&req)) {
1174        Ok(x) => x,
1175        Err(r) => return to_response(r),
1176    };
1177    if let Err(r) = admit(&inner, &client, 1) {
1178        return to_response(r);
1179    }
1180    let unknown = || to_response(Reply::json(400, envelope::bad_request(ErrorCode::JobUnknown), Cache::NoStore));
1181    let valid = (32..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
1182    if !valid {
1183        return unknown();
1184    }
1185    match inner.jobs.poll(&id) {
1186        Poll::Unknown => unknown(),
1187        Poll::Done(r) => to_response(r),
1188        Poll::Running(request, elapsed) => {
1189            let poll = format!("{}/jobs/{id}", inner.config.origin());
1190            match Pending::new(&id, inner.jobs.estimate(elapsed), &poll, request) {
1191                Ok(p) => to_response(Reply::json(202, envelope::pending(&p), Cache::NoStore)),
1192                Err(_) => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1193            }
1194        }
1195    }
1196}
1197
1198/// The key document (SPEC 9.2): the store's namespace record for this mesh's host.
1199#[utoipa::path(get, path = "/.well-known/datumesh.json", responses((status = 200, description = "The key document", content_type = "application/json"), (status = 404, description = "None stored")))]
1200async fn key_document(State(mesh): State<Mesh>) -> Response {
1201    let m = mesh.clone();
1202    match mesh.inner.pool.run(move || m.key_document()).await.flatten() {
1203        Some(doc) => to_response(Reply::json(200, doc, Cache::Public(300))),
1204        None => not_found("key document"),
1205    }
1206}
1207
1208/// The mesh document (SPEC 9.6).
1209#[utoipa::path(get, path = "/.well-known/datumesh-mesh.json", responses((status = 200, description = "The mesh document", content_type = "application/json")))]
1210async fn mesh_document(State(mesh): State<Mesh>) -> Response {
1211    to_response(Reply::json(200, mesh.mesh_document(), Cache::Public(300)))
1212}
1213
1214/// Which function each name denotes as of an instant (SPEC 9.7).
1215#[utoipa::path(get, path = "/bindings",
1216    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).")),
1217    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")))]
1218async fn bindings(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
1219    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1220        return r;
1221    }
1222    let inner = mesh.inner.clone();
1223    let mut names = Vec::new();
1224    let mut asof = None;
1225    for p in uri.query().unwrap_or("").split('&').filter(|p| !p.is_empty()) {
1226        let (k, v) = p.split_once('=').unwrap_or((p, ""));
1227        let Some(v) = pct_decode(v) else { return batch_error("percent-encoding (SPEC 5.1)") };
1228        match k {
1229            "name" if lexical::check_function_name(&v, "$").is_ok() => names.push(v),
1230            "asof"
1231                if lexical::check_instant(&crate::instant::canonical_or_same(&v, true), "$").is_ok()
1232                    && asof.is_none() =>
1233            {
1234                asof = Some(crate::instant::canonical_or_same(&v, true))
1235            }
1236            _ => return batch_error(&format!("parameter {k}")),
1237        }
1238    }
1239    let r = inner
1240        .pool
1241        .clone()
1242        .run(move || {
1243            let at = asof.unwrap_or_else(|| inner.now());
1244            let mut out = Vec::new();
1245            for n in names {
1246                if !inner.config.owns(crate::foreign::host_of(&n)) {
1247                    continue;
1248                }
1249                // A class name is answered with its class hash (9.7, spec-0.5.0); any other name
1250                // with the function it means.
1251                let found = match inner.store.resolve_class_binding(&n, &at) {
1252                    Ok(Some(c)) => ("class_hash", c.class_hash, c.tx),
1253                    Ok(None) => match inner.store.resolve_binding(&n, &at) {
1254                        Ok(Some(b)) => ("fn_hash", b.fn_hash, b.tx),
1255                        Ok(None) => continue,
1256                        Err(_) => return None,
1257                    },
1258                    Err(_) => return None,
1259                };
1260                out.push((
1261                    n,
1262                    Value::Object(vec![
1263                        (found.0.into(), Value::String(found.1)),
1264                        ("since".into(), Value::String(found.2)),
1265                    ]),
1266                ));
1267            }
1268            Some(Value::Object(vec![("asof".into(), Value::String(at)), ("bindings".into(), Value::Object(out))]))
1269        })
1270        .await
1271        .flatten();
1272    match r {
1273        Some(v) => plain_json(200, v, Cache::Public(inner_latest(&mesh))),
1274        None => to_response(envelope::error_reply(ErrorCode::InputUnavailable)),
1275    }
1276}
1277
1278fn inner_latest(mesh: &Mesh) -> u64 {
1279    mesh.inner.config.ttl.latest_max_age.as_secs()
1280}
1281
1282/// Strict percent-decoding (SPEC 5.1): literal characters as themselves, `%` and two
1283/// uppercase hex digits for other bytes, UTF-8.
1284fn pct_decode(s: &str) -> Option<String> {
1285    let b = s.as_bytes();
1286    let mut out = Vec::new();
1287    let mut i = 0;
1288    while i < b.len() {
1289        let c = b[i];
1290        if c == b'%' {
1291            let h = b.get(i + 1..i + 3)?;
1292            if !h.iter().all(|x| x.is_ascii_digit() || (b'A'..=b'F').contains(x)) {
1293                return None;
1294            }
1295            let v = u8::from_str_radix(std::str::from_utf8(h).ok()?, 16).ok()?;
1296            if v.is_ascii_alphanumeric() || matches!(v, b'-' | b'.' | b'_' | b'~' | b':') {
1297                return None;
1298            }
1299            out.push(v);
1300            i += 3;
1301        } else if c.is_ascii_alphanumeric() || matches!(c, b'-' | b'.' | b'_' | b'~' | b':') {
1302            out.push(c);
1303            i += 1;
1304        } else {
1305            return None;
1306        }
1307    }
1308    String::from_utf8(out).ok()
1309}
1310
1311/// Liveness and the store's health.
1312#[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")))]
1313async fn health(State(mesh): State<Mesh>) -> Response {
1314    let m = mesh.clone();
1315    let ok = tokio::time::timeout(
1316        Duration::from_secs(5),
1317        mesh.inner.pool.run(move || m.inner.store.namespace(&m.inner.config.host).is_ok()),
1318    )
1319    .await
1320    .ok()
1321    .flatten()
1322    .unwrap_or(false);
1323    let v = Value::Object(vec![("status".into(), Value::String(if ok { "ok" } else { "store unavailable" }.into()))]);
1324    plain_json(if ok { 200 } else { 503 }, v, Cache::NoStore)
1325}
1326
1327/// Prometheus metrics.
1328#[utoipa::path(get, path = "/metrics", responses((status = 200, description = "Prometheus text", content_type = "text/plain")))]
1329async fn metrics(State(mesh): State<Mesh>) -> Response {
1330    // The store is synchronous: its count is read on the pool, never on this thread (CONTRACT-http-listing L10).
1331    // With no listed host there is nothing to count (no pool hop); a store failure leaves the total out (smaller 9).
1332    let listed = if mesh.inner.config.listed_meshes.is_empty() {
1333        Some(0)
1334    } else {
1335        let store = mesh.inner.store.clone();
1336        mesh.inner.pool.clone().run(move || store.listing_count().ok()).await.flatten()
1337    };
1338    let mut r = Reply::json(200, metrics_text(&mesh.inner, listed).into_bytes(), Cache::NoStore);
1339    r.content_type = "text/plain; version=0.0.4";
1340    to_response(r)
1341}
1342
1343/// This document.
1344#[utoipa::path(get, path = "/openapi.json", responses((status = 200, description = "The OpenAPI document", content_type = "application/json")))]
1345async fn openapi_json() -> Response {
1346    let mut r = Reply::json(200, openapi().to_json().unwrap_or_default().into_bytes(), Cache::Public(300));
1347    r.content_type = JSON;
1348    to_response(r)
1349}
1350
1351pub(crate) fn metrics_text(inner: &Inner, listed_names: Option<u64>) -> String {
1352    use std::fmt::Write;
1353    use std::sync::atomic::Ordering::Relaxed;
1354    let mut out = String::new();
1355    inner.metrics.write(&mut out);
1356    // The names listed from other meshes, all hosts (CONTRACT-http-listing L10): check.sh reads it. Absent when the store
1357    // cannot count them, so check.sh tells a store error from an empty list (smaller 9).
1358    if let Some(n) = listed_names {
1359        let _ = writeln!(out, "# HELP datumesh_listed_names_total Names listed from other meshes, all hosts.");
1360        let _ = writeln!(out, "# TYPE datumesh_listed_names_total gauge");
1361        let _ = writeln!(out, "datumesh_listed_names_total {n}");
1362    }
1363    let _ = writeln!(out, "# HELP datumesh_listing_lookups_total Store lookups of listings made for requests.");
1364    let _ = writeln!(out, "# TYPE datumesh_listing_lookups_total counter");
1365    let _ = writeln!(out, "datumesh_listing_lookups_total {}", inner.listing_lookups.load(Relaxed));
1366    let p = &inner.pool;
1367    let g = |out: &mut String, name: &str, help: &str, kind: &str, v: String| {
1368        let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}\n{name} {v}");
1369    };
1370    g(&mut out, "datumesh_pool_size", "The blocking pool's size: the concurrency limit.", "gauge", p.size.to_string());
1371    g(&mut out, "datumesh_pool_in_use", "Pool threads busy now.", "gauge", p.in_use.load(Relaxed).to_string());
1372    g(&mut out, "datumesh_pool_peak", "The most pool threads busy at once.", "gauge", p.peak.load(Relaxed).to_string());
1373    g(&mut out, "datumesh_pool_runs_total", "Tasks run on the pool.", "counter", p.runs.load(Relaxed).to_string());
1374    g(
1375        &mut out,
1376        "datumesh_pool_waited_total",
1377        "Tasks that found the pool saturated and waited for a thread.",
1378        "counter",
1379        p.waited.load(Relaxed).to_string(),
1380    );
1381    let (held, running) = inner.jobs.counts();
1382    g(&mut out, "datumesh_jobs_held", "Jobs held (running or done).", "gauge", held.to_string());
1383    g(&mut out, "datumesh_jobs_running", "Jobs running.", "gauge", running.to_string());
1384    g(
1385        &mut out,
1386        "datumesh_jobs_created_total",
1387        "Requests answered pending.",
1388        "counter",
1389        inner.jobs.created.load(Relaxed).to_string(),
1390    );
1391    g(
1392        &mut out,
1393        "datumesh_rate_limited_total",
1394        "Requests refused by a rate limit.",
1395        "counter",
1396        inner.limiter.refused.load(Relaxed).to_string(),
1397    );
1398    g(
1399        &mut out,
1400        "datumesh_peer_fetches_total",
1401        "Requests to other meshes.",
1402        "counter",
1403        inner.foreign.fetches.load(Relaxed).to_string(),
1404    );
1405    g(
1406        &mut out,
1407        "datumesh_peer_failures_total",
1408        "Requests to other meshes that failed.",
1409        "counter",
1410        inner.foreign.failures.load(Relaxed).to_string(),
1411    );
1412    g(
1413        &mut out,
1414        "datumesh_peer_imported_total",
1415        "Foreign versions imported into the store.",
1416        "counter",
1417        inner.foreign.imported.load(Relaxed).to_string(),
1418    );
1419    let m = inner.engine.memo_stats();
1420    g(&mut out, "datumesh_memo_entries", "Engine memo entries.", "gauge", m.entries.to_string());
1421    g(&mut out, "datumesh_memo_bytes", "Engine memo size, approximately.", "gauge", m.approx_bytes.to_string());
1422    g(
1423        &mut out,
1424        "datumesh_uptime_seconds",
1425        "Seconds since the mesh started.",
1426        "gauge",
1427        inner.started.elapsed().as_secs().to_string(),
1428    );
1429    out
1430}
1431
1432/// The refusal of a read whose path text names a listed name (B1): `None` when it names none; a store failure is `503`.
1433fn refuse_text(inner: &Inner, text: &str) -> Option<Reply> {
1434    let alias = |a: &str| inner.config.aliases.get(a).cloned();
1435    match crate::listing::checked_in(inner, inner, &alias, text) {
1436        Ok(Some(l)) => Some(crate::listing::refusal(&l)),
1437        Ok(None) => None,
1438        Err(_) => Some(crate::listing::unavailable()),
1439    }
1440}
1441
1442/// Request ids, the access log, metrics and `Accept`.
1443async fn around(State(mesh): State<Mesh>, req: Request, next: Next) -> Response {
1444    let start = Instant::now();
1445    let route = req.extensions().get::<MatchedPath>().map(|m| m.as_str().to_string()).unwrap_or_else(|| "other".into());
1446    let route = match route.as_str() {
1447        "/cell/{*rest}" => "/cell/{cell}".to_string(),
1448        "/slice/{*rest}" => "/slice/{cell}".to_string(),
1449        "/explain/{*rest}" => "/explain/{cell}".to_string(),
1450        "/versions/{*rest}" => "/versions/{cell}".to_string(),
1451        "/x/versions/{*rest}" => "/x/versions/{cell}".to_string(),
1452        "/fn/{*name}" => "/fn/{name}".to_string(),
1453        "/takeover/{*domain}" => "/takeover/{domain}".to_string(),
1454        "/series/{*rest}" => "/series/{page}".to_string(),
1455        "/catalog/{*rest}" => "/catalog/{page}".to_string(),
1456        "/x/interval/{*function}" => "/x/interval/{function}".to_string(),
1457        _ => route,
1458    };
1459    let id = req
1460        .headers()
1461        .get("x-request-id")
1462        .and_then(|v| v.to_str().ok())
1463        .filter(|s| !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
1464        .map(str::to_string)
1465        .unwrap_or_else(|| {
1466            let mut b = [0u8; 8];
1467            let _ = getrandom::fill(&mut b);
1468            lexical::to_hex(&b)
1469        });
1470    let ip = client_ip(&mesh.inner, req.headers(), peer_of(&req));
1471    let method = req.method().clone();
1472    let also = if route == "/slice/{cell}" { Some(crate::slice::ARROW) } else { None };
1473    // The function page is HTML for people (Build 2 Part 4, P2) as well as JSON for agents.
1474    let html_ok = (route == "/fn/{name}" || route == "/takeover/{domain}") && accepts(req.headers(), "text/html");
1475    // The series pages and the sitemap choose their own media type, and a slice's browser redirect or
1476    // format is answered whatever its Accept (Build 2 Part 6, G1).
1477    let own_form = matches!(
1478        route.as_str(),
1479        "/series/{page}" | "/series/sitemap.xml" | "/x/interval/{function}" | "/catalog" | "/catalog/{page}"
1480    ) || (route == "/slice/{cell}"
1481        && crate::series::negotiation_free(&mesh.inner, &rest_of(req.uri(), "/slice/"), req.headers()));
1482    // A read of a listed name is refused here, before anything else (CONTRACT-http-listing L6): every method, and every read
1483    // route that names a function (B1). A store failure answers 503 (fail closed).
1484    let listed_prefix = match route.as_str() {
1485        "/cell/{cell}" => Some("/cell/"),
1486        "/slice/{cell}" => Some("/slice/"),
1487        "/series/{page}" => Some("/series/"),
1488        "/versions/{cell}" => Some("/versions/"),
1489        "/explain/{cell}" => Some("/explain/"),
1490        "/x/versions/{cell}" => Some("/x/versions/"),
1491        "/x/interval/{function}" => Some("/x/interval/"),
1492        _ => None,
1493    };
1494    let listed_refusal = match listed_prefix {
1495        Some(prefix) if !mesh.inner.config.listed_meshes.is_empty() => {
1496            let text = rest_of(req.uri(), prefix);
1497            let inner = mesh.inner.clone();
1498            match mesh.inner.pool.clone().run(move || refuse_text(&inner, &text)).await {
1499                Some(r) => r,
1500                None => Some(crate::listing::unavailable()),
1501            }
1502        }
1503        _ => None,
1504    };
1505    let mut resp = if let Some(r) = listed_refusal {
1506        to_response(r)
1507    } else if route != "/blob/{sha256}"
1508        && route != "/metrics"
1509        && !html_ok
1510        && !own_form
1511        && !acceptable(req.headers(), also)
1512    {
1513        not_acceptable()
1514    } else {
1515        next.run(req).instrument(tracing::info_span!("request", request_id = %id)).await
1516    };
1517    let elapsed = start.elapsed();
1518    let status = resp.status().as_u16();
1519    mesh.inner.metrics.record(&route, status, elapsed);
1520    let principal = resp.extensions().get::<Who>().and_then(|w| w.0.clone());
1521    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");
1522    if let Ok(v) = HeaderValue::from_str(&id) {
1523        resp.headers_mut().insert("x-request-id", v);
1524    }
1525    resp.headers_mut().insert(header::VARY, HeaderValue::from_static("Accept, Accept-Encoding, Authorization"));
1526    if let Ok(v) = HeaderValue::from_str(&format!("app;dur={:.3}", elapsed.as_secs_f64() * 1000.0)) {
1527        resp.headers_mut().insert("server-timing", v);
1528    }
1529    resp
1530}
1531
1532/// describe (SPEC 16.8): a class or an object, by class name, key encoding, object id, cell id or
1533/// short id (`{id}`, percent-encoded as a path). A class's method table gives each method its
1534/// `description` from the catalog entry `{class}/{method}` when that is 1 to 1,024 bytes.
1535/// `POST /whatif` (spec-0.6.0, 5.9): the scenario of a cell under overrides, labelled a scenario,
1536/// never a fact.
1537#[utoipa::path(post, path = "/whatif",
1538    request_body(content = String, description = "The JSON of 5.9: `cell`, `asof`?, `overrides`, `solve`?", content_type = "application/json"),
1539    responses(
1540        (status = 200, description = "`scenario`: `{asof, cell, overrides, type, value[, solved]}`, no receipt", content_type = "application/json"),
1541        (status = 400, description = "`bad_request`", content_type = "application/json"),
1542        (status = 404, description = "`not_covered`, with `fault` when the scenario faulted or has no solution", content_type = "application/json"),
1543        (status = 500, description = "`error`", content_type = "application/json"),
1544    ))]
1545async fn whatif(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
1546    let inner = mesh.inner.clone();
1547    let peer = peer_of(&req);
1548    let (client, principal) = match who(&inner, &headers, peer) {
1549        Ok(x) => x,
1550        Err(r) => return to_response(r),
1551    };
1552    if let Err(r) = admit(&inner, &client, 1) {
1553        return to_response(r);
1554    }
1555    let body = match axum::body::to_bytes(req.into_body(), 1 << 20).await {
1556        Ok(b) => b,
1557        Err(_) => return to_response(envelope::bad_request_reply(ErrorCode::CanonLimit)),
1558    };
1559    if !inner.config.listed_meshes.is_empty() {
1560        // A scenario that names a listed function is refused as a read is (B1): any word of the body that is one.
1561        let (inner2, body2) = (inner.clone(), body.clone());
1562        let text = String::from_utf8_lossy(&body2).into_owned();
1563        match inner.pool.clone().run(move || crate::listing::checked_words(&inner2, &text)).await {
1564            Some(Ok(Some(l))) => return to_response(crate::listing::refusal(&l)),
1565            Some(Ok(None)) => {}
1566            _ => return to_response(crate::listing::unavailable()),
1567        }
1568    }
1569    let mesh2 = mesh.clone();
1570    match inner.pool.clone().run(move || mesh2.whatif(&body, principal.as_ref())).await {
1571        Some(r) => to_response(r),
1572        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1573    }
1574}
1575
1576/// `POST /x/calc` (Build 2 Part 3 addition, C3; D27, D30): a formula over cells, evaluated in a
1577/// scope: the value, its type, the formula and its canonical form, the asof and the lineage of the
1578/// cells read. Nothing is written: no receipt, no version, no binding.
1579#[utoipa::path(post, path = "/x/calc",
1580    request_body(content = String, description = "`{\"formula\": <body>, \"asof\"?: <instant>}`; the body is at most 4096 bytes", content_type = "application/json"),
1581    responses(
1582        (status = 200, description = "`kind: calculation`: `{outcome, kind, value, type, unit?, formula, canonical, asof, lineage}`, no receipt, no trust; `lineage` is `[{call, receipt, publisher, trust}]`", content_type = "application/json"),
1583        (status = 400, description = "`bad_request`, with the code (a request code, or a formula's `E_FORMULA_*`)", content_type = "application/json"),
1584        (status = 404, description = "`not_covered`, with `fault` when the calculation faulted", content_type = "application/json"),
1585        (status = 413, description = "`E_TOO_LARGE`: the formula is more than 4096 bytes", content_type = "application/json"),
1586        (status = 429, description = "`rate_limited`", content_type = "application/json"),
1587        (status = 500, description = "`error`", content_type = "application/json"),
1588        (status = 503, description = "`error` with `E_EVAL_BUDGET` (the mesh's budget ran out; no job) or `E_EVAL_UNAVAILABLE`", content_type = "application/json"),
1589    ))]
1590async fn x_calc(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
1591    let inner = mesh.inner.clone();
1592    let peer = peer_of(&req);
1593    let (client, principal) = match who(&inner, &headers, peer) {
1594        Ok(x) => x,
1595        Err(r) => return to_response(r),
1596    };
1597    if let Err(r) = admit(&inner, &client, 1) {
1598        return to_response(r);
1599    }
1600    if let Err(s) = inner.limiter.admit_calc(client_ip(&inner, &headers, peer)) {
1601        return to_response(envelope::rate_limited_reply(s));
1602    }
1603    // A body of a 4 KiB formula with its JSON escapes is well under 64 KiB; more is refused as too large.
1604    let body = match axum::body::to_bytes(req.into_body(), 64 << 10).await {
1605        Ok(b) => b,
1606        Err(_) => return to_response(crate::calc::too_large_reply()),
1607    };
1608    // A formula that reads a listed name is refused as a read is (CONTRACT-http-listing L6), before any resolution.
1609    if !inner.config.listed_meshes.is_empty() {
1610        let (inner2, body2) = (inner.clone(), body.clone());
1611        match inner.pool.clone().run(move || crate::listing::checked_formula(&inner2, &body2)).await {
1612            Some(Ok(Some(l))) => return to_response(crate::listing::refusal(&l)),
1613            Some(Ok(None)) => {}
1614            _ => return to_response(crate::listing::unavailable()),
1615        }
1616    }
1617    let mesh2 = mesh.clone();
1618    match inner.pool.clone().run(move || mesh2.calc(&body, principal.as_ref())).await {
1619        Some(r) => to_response(r),
1620        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1621    }
1622}
1623
1624/// `GET /x/keys/challenge` (QUESTIONS-build2 D39, `DATUMESH_KEY_NAMES=1`): a challenge to sign with the key to
1625/// register. Off: `404`.
1626#[utoipa::path(get, path = "/x/keys/challenge",
1627    responses(
1628        (status = 200, description = "`{\"challenge\", \"expires\"}`, no-store", content_type = "application/json"),
1629        (status = 404, description = "Key-derived names are off on this mesh", content_type = "application/json"),
1630        (status = 429, description = "`rate_limited`, with `Retry-After`", content_type = "application/json")))]
1631async fn x_keys_challenge(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
1632    if !mesh.inner.config.key_names {
1633        return not_found("endpoint");
1634    }
1635    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1636        return r;
1637    }
1638    let inner = mesh.inner.clone();
1639    match inner.pool.clone().run(move || crate::keynames::challenge(&inner)).await {
1640        Some(r) => to_response(r),
1641        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1642    }
1643}
1644
1645/// `POST /x/keys` (QUESTIONS-build2 D39, `DATUMESH_KEY_NAMES=1`): registers a public key by its proof of
1646/// possession (`{"public_key", "challenge", "signature"}`). The key's namespace is `<host>/key/k<24 hex>`.
1647/// `201` when the key is added, `200` when it was there. Off: `404`.
1648#[utoipa::path(post, path = "/x/keys",
1649    request_body(content = String, description = "`{\"public_key\": <64 hex>, \"challenge\": <as issued>, \"signature\": <128 hex, Ed25519 over the challenge's UTF-8 bytes>}`", content_type = "application/json"),
1650    responses(
1651        (status = 201, description = "`{\"namespace\", \"key_id\"}`: the key is added to the key document", content_type = "application/json"),
1652        (status = 200, description = "The same body: the key was registered before", content_type = "application/json"),
1653        (status = 400, description = "`E_KEY_MALFORMED`, or `E_CHALLENGE` (unknown, expired or used)", content_type = "application/json"),
1654        (status = 403, description = "`E_KEY_SIGNATURE`", content_type = "application/json"),
1655        (status = 404, description = "Key-derived names are off on this mesh", content_type = "application/json"),
1656        (status = 429, description = "`rate_limited`, with `Retry-After` (`DATUMESH_RATE_KEYS_PER_IP`)", content_type = "application/json")))]
1657async fn x_keys(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
1658    let inner = mesh.inner.clone();
1659    if !inner.config.key_names {
1660        return not_found("endpoint");
1661    }
1662    if let Some(r) = ip_admit(&inner, &headers, &req) {
1663        return r;
1664    }
1665    let ip = client_ip(&inner, &headers, peer_of(&req));
1666    if let Err(s) = inner.limiter.admit_keys(ip) {
1667        return to_response(crate::keynames::rate_limited(s));
1668    }
1669    // A body over the limit is read to its end and is then malformed, as any other that does not parse.
1670    let body = axum::body::to_bytes(req.into_body(), crate::keynames::MAX_BODY).await.unwrap_or_default();
1671    let i2 = inner.clone();
1672    match inner
1673        .pool
1674        .clone()
1675        .run(move || match crate::keynames::parse(&body) {
1676            Ok(p) => crate::keynames::register(&i2, &p),
1677            Err(detail) => crate::keynames::refuse(400, "E_KEY_MALFORMED", &detail),
1678        })
1679        .await
1680    {
1681        Some(r) => to_response(r),
1682        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1683    }
1684}
1685
1686#[utoipa::path(get, path = "/describe/{id}",
1687    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).")),
1688    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")))]
1689async fn describe(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
1690    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1691        return r;
1692    }
1693    let Some(id) = crate::call::url_decode(uri.path().strip_prefix("/describe/").unwrap_or("")) else {
1694        return to_response(envelope::bad_request_reply(ErrorCode::CanonPercent));
1695    };
1696    let inner = mesh.inner.clone();
1697    match inner.pool.clone().run(move || mesh.describe(&id)).await {
1698        Some(r) => {
1699            // A function's page is named by a `Link` header, not a member of the answer (16.8 is
1700            // checked strictly by core; Build 2 Part 4, P2).
1701            let link = function_describe_link(&inner, &r);
1702            let mut resp = to_response(r);
1703            if let Some(v) = link.and_then(|l| HeaderValue::from_str(&l).ok()) {
1704                resp.headers_mut().insert(header::LINK, v);
1705            }
1706            resp
1707        }
1708        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1709    }
1710}
1711
1712/// The `Link` header of a describe answer for a function: its page, `rel="describedby"`.
1713fn function_describe_link(inner: &Inner, r: &Reply) -> Option<String> {
1714    if r.status != 200 {
1715        return None;
1716    }
1717    let v = json::parse(&r.body).ok()?;
1718    if v.get("kind")?.as_str()? != "function" {
1719        return None;
1720    }
1721    let name = v.get("fn")?.as_str()?;
1722    Some(format!("<{}>; rel=\"describedby\"", crate::fnpage::page_url(inner, name)))
1723}
1724
1725/// `POST /bundles` (Build 2 Part 4, P1): a publisher's bundle, checked and imported (see `bundles`).
1726async fn bundles(State(mesh): State<Mesh>, req: Request) -> Response {
1727    to_response(crate::bundles::post(mesh.inner.clone(), req.into_body()).await)
1728}
1729
1730/// `GET /fn/<name>` (Build 2 Part 4, P2): the function page, HTML or, by `Accept` or `?format=json`,
1731/// the same data as JSON.
1732async fn function_page(
1733    State(mesh): State<Mesh>,
1734    Path(name): Path<String>,
1735    uri: Uri,
1736    headers: HeaderMap,
1737    req: Request,
1738) -> Response {
1739    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1740        return r;
1741    }
1742    let format_json = uri.query().is_some_and(|q| q.split('&').any(|p| p == "format=json"));
1743    let json_form = format_json || (accepts(&headers, JSON) && !accepts(&headers, "text/html"));
1744    let inner = mesh.inner.clone();
1745    match inner.pool.clone().run(move || crate::fnpage::respond(&mesh.inner, &name, json_form)).await {
1746        Some(r) => to_response(r),
1747        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1748    }
1749}
1750
1751/// `GET /takeover/<domain>` (D24): what a source's domain can do to publish the values this mesh
1752/// relays from it; HTML, or JSON by `Accept` or `?format=json`.
1753#[utoipa::path(get, path = "/takeover/{domain}",
1754    params(("domain" = String, Path, description = "The source's DNS name (SPEC 2.1)")),
1755    responses(
1756        (status = 200, description = "`{\"domain\", \"host\", \"functions\": [{\"name\", \"page\", \"fn_hash\"}], \"steps\": [...]}`, or the HTML page", content_type = "application/json"),
1757        (status = 400, description = "E_CANON_NAME: not a DNS name", content_type = "application/json"),
1758        (status = 404, description = "not_covered: no function relayed from the domain on this mesh", content_type = "application/json")))]
1759async fn takeover_page(
1760    State(mesh): State<Mesh>,
1761    Path(domain): Path<String>,
1762    uri: Uri,
1763    headers: HeaderMap,
1764    req: Request,
1765) -> Response {
1766    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1767        return r;
1768    }
1769    let format_json = uri.query().is_some_and(|q| q.split('&').any(|p| p == "format=json"));
1770    let json_form = format_json || (accepts(&headers, JSON) && !accepts(&headers, "text/html"));
1771    let inner = mesh.inner.clone();
1772    match inner.pool.clone().run(move || crate::takeover::respond(&mesh.inner, &domain, json_form)).await {
1773        Some(r) => to_response(r),
1774        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1775    }
1776}
1777
1778/// `GET /catalog`, `/catalog/<domain>`, `/catalog/<domain>/subject?key=<key encoding>` and `/catalog/rule` (CONTRACT-classes-round
1779/// C9): HTML for people, from the catalogue's last build (`503` before it).
1780async fn catalog_page(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
1781    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
1782        return r;
1783    }
1784    let rest = uri.path().strip_prefix("/catalog").unwrap_or("").trim_start_matches('/').to_string();
1785    let key = uri
1786        .query()
1787        .and_then(|q| q.split('&').find_map(|kv| kv.strip_prefix("key=")))
1788        .map(crate::catalog_view::unpercent);
1789    let after = uri
1790        .query()
1791        .and_then(|q| q.split('&').find_map(|kv| kv.strip_prefix("after=")))
1792        .map(crate::catalog_view::unpercent);
1793    let inner = mesh.inner.clone();
1794    match inner
1795        .pool
1796        .clone()
1797        .run(move || crate::catalog_view::respond_paged(&mesh.inner, &rest, key.as_deref(), after.as_deref()))
1798        .await
1799    {
1800        Some(o) => series_response(o),
1801        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1802    }
1803}
1804
1805/// The per-IP budget of the series pages (`DATUMESH_RATE_SERIES_PER_IP`), after the ordinary per-IP limit.
1806fn series_admit(inner: &Inner, headers: &HeaderMap, req: &Request) -> Option<Response> {
1807    let peer = peer_of(req);
1808    let client = match who(inner, headers, peer) {
1809        Ok((c, _)) => c,
1810        Err(r) => return Some(to_response(r)),
1811    };
1812    if let Err(r) = admit(inner, &client, 1) {
1813        return Some(to_response(r));
1814    }
1815    let ip = client_ip(inner, headers, peer);
1816    inner.limiter.admit_series(ip).err().map(|s| to_response(envelope::rate_limited_reply(s)))
1817}
1818
1819/// A series answer as a response: its status, body, media type, `Cache-Control` and `ETag`.
1820fn series_response(o: crate::series::Out) -> Response {
1821    let mut resp = Response::new(Body::from(o.body));
1822    *resp.status_mut() = StatusCode::from_u16(o.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1823    let h = resp.headers_mut();
1824    h.insert(header::CONTENT_TYPE, HeaderValue::from_static(o.content_type));
1825    if let Ok(v) = HeaderValue::from_str(&o.cache) {
1826        h.insert(header::CACHE_CONTROL, v);
1827    }
1828    if let Some(e) = o.etag.as_deref().and_then(|e| HeaderValue::from_str(e).ok()) {
1829        h.insert(header::ETAG, e);
1830    }
1831    if let Some(s) = o.retry_after {
1832        h.insert(header::RETRY_AFTER, HeaderValue::from(s));
1833    }
1834    resp
1835}
1836
1837async fn series_answer(mesh: Mesh, headers: &HeaderMap, rest: String) -> Response {
1838    let inm = headers.get(header::IF_NONE_MATCH).and_then(|v| v.to_str().ok()).map(str::to_string);
1839    let inner = mesh.inner.clone();
1840    match inner.pool.clone().run(move || crate::series::respond(&mesh.inner, &rest, inm.as_deref())).await {
1841        Some(o) => series_response(o),
1842        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1843    }
1844}
1845
1846/// `GET /series/<function>/<YYYY-MM>[.csv]`, `/series/<function>/<YYYY>[.csv]` and `/series/<function>/`: the
1847/// month or year page of a relayed or computed series, its CSV, or its index (Build 2 Part 6, G1 to G5).
1848#[utoipa::path(get, path = "/series/{page}",
1849    params(("page" = String, Path, description = "The series' function name, then `/YYYY-MM`, `/YYYY` (each with an optional `.csv`) or `/` for the index")),
1850    responses(
1851        (status = 200, description = "The page (HTML with a JSON-LD dataset), its CSV (`text/csv`), or the index", content_type = "text/html"),
1852        (status = 304, description = "`ETag` unchanged"),
1853        (status = 404, description = "No stored value at this address, or the function is not in the series file (cacheable 600 s)", content_type = "text/html"),
1854        (status = 429, description = "`rate_limited`, with `Retry-After` (the per-IP and the series budgets)", content_type = "application/json"),
1855    ))]
1856async fn series_page(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
1857    if let Some(r) = series_admit(&mesh.inner, &headers, &req) {
1858        return r;
1859    }
1860    let rest = uri.path().strip_prefix("/series/").unwrap_or("").to_string();
1861    series_answer(mesh, &headers, rest).await
1862}
1863
1864/// `GET /series/sitemap.xml`: every index and page of the listed series, with `lastmod` (the as-of); a sitemap
1865/// index of `sitemap-<n>.xml` files past 50,000 URLs.
1866#[utoipa::path(get, path = "/series/sitemap.xml",
1867    responses(
1868        (status = 200, description = "A sitemap (`application/xml`) or a sitemap index", content_type = "application/xml"),
1869        (status = 404, description = "No series file: no pages", content_type = "text/html"),
1870        (status = 429, description = "`rate_limited`, with `Retry-After`", content_type = "application/json"),
1871    ))]
1872async fn series_sitemap(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
1873    if let Some(r) = series_admit(&mesh.inner, &headers, &req) {
1874        return r;
1875    }
1876    series_answer(mesh, &headers, "sitemap.xml".to_string()).await
1877}
1878
1879/// `GET /x/interval/<function>?<key>=<value|*>...&from=<date>&to=<date>[&format=csv|arrow]` (D32, an extension):
1880/// the stored cells of a listed series in `[from, to]`, each with its receipt.
1881#[utoipa::path(get, path = "/x/interval/{function}",
1882    params(
1883        ("function" = String, Path, description = "The function name of a series listed in the series file"),
1884        ("from" = String, Query, description = "The first date, `YYYY-MM-DD`, inclusive"),
1885        ("to" = String, Query, description = "The last date, `YYYY-MM-DD`, inclusive; at most 10 years after `from` for a series with month pages"),
1886        ("format" = Option<String>, Query, description = "`csv` or `arrow`; JSON without it. Each is an address of its own"),
1887    ),
1888    responses(
1889        (status = 200, description = "JSON `{function, from, to, asof, count, members: [{keys, value, type, tx, asof, receipt_hash, receipt}]}`; CSV (long form: the open keys, `date`, `value`, `receipt`); or an Arrow IPC stream", content_type = "application/json"),
1890        (status = 304, description = "`ETag` unchanged"),
1891        (status = 400, description = "`bad_request`: a missing or malformed `from` or `to`, `from` after `to`, an argument the function lacks, or `E_RANGE_TOO_LARGE`", content_type = "application/json"),
1892        (status = 404, description = "The function is not in the series file", content_type = "application/json"),
1893        (status = 429, description = "`rate_limited`, with `Retry-After` (the per-IP and the series budgets)", content_type = "application/json"),
1894    ))]
1895async fn x_interval(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
1896    if let Some(r) = series_admit(&mesh.inner, &headers, &req) {
1897        return r;
1898    }
1899    let function = uri.path().strip_prefix("/x/interval/").unwrap_or("").to_string();
1900    let query = uri.query().unwrap_or("").to_string();
1901    let inm = headers.get(header::IF_NONE_MATCH).and_then(|v| v.to_str().ok()).map(str::to_string);
1902    let inner = mesh.inner.clone();
1903    match inner.pool.clone().run(move || crate::series::interval(&mesh.inner, &function, &query, inm.as_deref())).await
1904    {
1905        Some(o) => series_response(o),
1906        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
1907    }
1908}
1909
1910async fn fallback() -> Response {
1911    not_found("endpoint")
1912}
1913
1914impl Mesh {
1915    /// The router of every endpoint. Serve it with
1916    /// `into_make_service_with_connect_info::<SocketAddr>()` (the client IP comes from it).
1917    pub fn router(&self) -> Router {
1918        Router::new()
1919            .route("/cell/{*rest}", get(cell))
1920            .route("/cells", post(cells))
1921            .route("/slice/{*rest}", get(slice))
1922            .route("/receipt/{hash}", get(receipt))
1923            .route("/descriptor/{hash}", get(descriptor))
1924            .route("/manifest/{slice_id}/{members_hash}", get(manifest))
1925            .route("/versions/{*rest}", get(versions))
1926            .route("/x/versions/{*rest}", get(x_versions))
1927            .route("/blob/{sha256}", get(blob))
1928            .route("/explain/{*rest}", get(explain))
1929            .route("/find", get(find))
1930            .route("/verify", post(verify_receipt))
1931            .route("/jobs/{job}", get(job))
1932            .route("/.well-known/datumesh.json", get(key_document))
1933            .route("/.well-known/datumesh-mesh.json", get(mesh_document))
1934            .route("/bindings", get(bindings))
1935            .route("/describe/{*id}", get(describe))
1936            .route("/fn/{*name}", get(function_page))
1937            .route("/takeover/{*domain}", get(takeover_page))
1938            .route("/catalog", get(catalog_page))
1939            .route("/catalog/{*rest}", get(catalog_page))
1940            .route("/series/sitemap.xml", get(series_sitemap))
1941            .route("/series/{*rest}", get(series_page))
1942            .route("/bundles", post(bundles))
1943            .route("/whatif", post(whatif))
1944            .route("/x/calc", post(x_calc))
1945            .route("/x/keys/challenge", get(x_keys_challenge))
1946            .route("/x/keys", post(x_keys))
1947            .route("/x/interval/{*function}", get(x_interval))
1948            .route("/health", get(health))
1949            .route("/metrics", get(metrics))
1950            .route("/openapi.json", get(openapi_json))
1951            .fallback(fallback)
1952            .layer(middleware::from_fn_with_state(self.clone(), around))
1953            .layer(tower_http::compression::CompressionLayer::new().gzip(true))
1954            .with_state(self.clone())
1955    }
1956
1957    /// Serves the router on `listener` until `shutdown` resolves.
1958    pub async fn serve(
1959        &self,
1960        listener: tokio::net::TcpListener,
1961        shutdown: impl std::future::Future<Output = ()> + Send + 'static,
1962    ) -> std::io::Result<()> {
1963        axum::serve(listener, self.router().into_make_service_with_connect_info::<SocketAddr>())
1964            .with_graceful_shutdown(shutdown)
1965            .await
1966    }
1967}
1968
1969impl IntoResponse for Reply {
1970    fn into_response(self) -> Response {
1971        to_response(self)
1972    }
1973}
1974
1975#[cfg(test)]
1976mod tests {
1977    use super::*;
1978
1979    fn reply(status: u16, body: &str) -> Reply {
1980        Reply::json(status, body.as_bytes().to_vec(), Cache::NoStore)
1981    }
1982
1983    /// The runs the chunks write, concatenated and closed, are the batch as 5.7 writes it, and
1984    /// count its outcomes.
1985    #[test]
1986    fn runs_make_the_batch() {
1987        let h = "a".repeat(64);
1988        let replies = [
1989            reply(200, &format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"value":"1"}},"trust":"primary"}}"#)),
1990            reply(400, r#"{"error":"E_CANON_NUMBER","outcome":"bad_request"}"#),
1991            reply(
1992                200,
1993                &format!(r#"{{"age_seconds":3,"fn_hash":"{h}","outcome":"stale","receipt":{{}},"trust":"computed"}}"#),
1994            ),
1995            reply(404, r#"{"error":"E_NAME_UNBOUND","outcome":"not_covered"}"#),
1996            reply(200, &format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"value":"2"}},"trust":"primary"}}"#)),
1997        ];
1998        let mut want = b"[".to_vec();
1999        for (i, r) in replies.iter().enumerate() {
2000            if i > 0 {
2001                want.push(b',');
2002            }
2003            want.extend_from_slice(b"{\"envelope\":");
2004            want.extend_from_slice(&r.body);
2005            want.extend_from_slice(format!(",\"status\":{}}}", r.status).as_bytes());
2006        }
2007        want.push(b']');
2008        for split in 1..replies.len() {
2009            let runs = [Written::of(true, replies[..split].iter()), Written::of(false, replies[split..].iter())];
2010            let mut got: Vec<u8> = runs.iter().flat_map(|w| w.bytes.iter().copied()).collect();
2011            got.push(b']');
2012            assert_eq!(String::from_utf8(got).unwrap(), String::from_utf8(want.clone()).unwrap());
2013            let mut counts = std::collections::BTreeMap::new();
2014            for (o, k) in runs.iter().flat_map(|w| w.outcomes.iter()) {
2015                *counts.entry(o.as_str()).or_insert(0) += k;
2016            }
2017            let want_counts: std::collections::BTreeMap<&str, u64> =
2018                [("bad_request", 1), ("not_covered", 1), ("ok", 2), ("stale", 1)].into_iter().collect();
2019            assert_eq!(counts, want_counts);
2020        }
2021        for (n, s) in [(0u16, "0"), (7, "7"), (200, "200"), (404, "404"), (65535, "65535")] {
2022            let mut out = Vec::new();
2023            push_u16(&mut out, n);
2024            assert_eq!(out, s.as_bytes());
2025        }
2026    }
2027
2028    /// The outcome of each envelope, whatever members come before it.
2029    #[test]
2030    fn outcomes() {
2031        let h = "0".repeat(64);
2032        for (body, want) in [
2033            (format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"outcome":"x"}}}}"#), Some("ok")),
2034            (r#"{"age_seconds":12,"outcome":"stale"}"#.to_string(), Some("stale")),
2035            (r#"{"error":"E_PARSE_URI","outcome":"bad_request"}"#.to_string(), Some("bad_request")),
2036            (r#"{"outcome":"pending","poll":"https://a.example/jobs/1"}"#.to_string(), Some("pending")),
2037            (r#"{"error":"no such endpoint"}"#.to_string(), None),
2038            (r#"{"outcome""#.to_string(), None),
2039        ] {
2040            assert_eq!(reply(200, &body).outcome_str(), want, "{body}");
2041            assert_eq!(reply(200, &body).outcome(), want.map(str::to_string), "{body}");
2042        }
2043        let mut arrow = reply(200, r#"{"outcome":"ok"}"#);
2044        arrow.content_type = "application/vnd.apache.arrow.stream";
2045        assert_eq!(arrow.outcome(), None);
2046    }
2047}