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