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