Skip to main content

datumesh_http/
slice.rs

1//! `GET /slice/<call with *>`: the members of a stored function's slice as of an instant, as
2//! an Arrow IPC stream or as JSON pages, paginated by key.
3//!
4//! Members come from the store's `slice_values` (values, hashes and cells, no receipt bytes),
5//! in SPEC 15.13 key order. A slice read as of an instant at or before now is kept in a small
6//! memory cache (its members cannot change, the store being append-only), so repeated reads
7//! of it are warm. A latest read (no `asof`) reuses the cached members of its slice while no
8//! member changed after the cached instant, and its `next` links pin that instant.
9//!
10//! JSON: a page envelope (SPEC 5.6, spec-0.4.2): `{"outcome": "ok", "slice", "members",
11//! "next"?, "fn_hash"}`, `members` the members' `ok` envelopes ascending by key, `next` the URL
12//! of the following page (`limit=` and `after=` the last key, hex of its JCS bytes), absent on
13//! the last page. Pages are of `limit` members (default 1,000, at most 10,000), all with the
14//! asof of the first page.
15//!
16//! Arrow (`Accept: application/vnd.apache.arrow.stream`): one stream, record batches of up
17//! to 65,536 rows, a column per open argument and `value`, `type`, `receipt`, `tx`, `asof`
18//! (UTF-8: lexical forms, so no number is rounded), schema metadata `slice_id`, `asof`,
19//! `function`. The whole slice (up to the configured bound) in one stream.
20
21use std::collections::VecDeque;
22use std::sync::Arc;
23
24use arrow_array::{ArrayRef, RecordBatch, StringArray};
25use arrow_schema::{DataType, Field, Schema};
26use datumesh_core::json::{self, Value};
27use datumesh_core::{lexical, Arg, ErrorCode, Scalar, Slice};
28use datumesh_store::SliceValue;
29
30use crate::call::Target;
31use crate::envelope::{self, Bytes, Cache, Reply};
32use crate::mesh::Inner;
33
34/// The media type of Arrow IPC streams.
35pub const ARROW: &str = "application/vnd.apache.arrow.stream";
36/// The media type of the CSV form of a slice (RFC 4180, UTF-8).
37const CSV: &str = "text/csv; charset=utf-8";
38
39/// The most bytes of whole-slice bodies the cache holds (CONTRACT-0.5.1 H1: 64 MB). A body larger than this is not cached.
40pub(crate) const BODY_CACHE_BYTES: usize = 64 << 20;
41
42/// What a cached body answers to: the form, the slice (its canonical JSON, which names the function hash and the
43/// arguments), the instant (explicit and in the past), and the `limit=` and `after=` the request named.
44type BodyKey = (String, Vec<u8>, String, Option<usize>, Option<String>);
45
46/// The encoded bodies of whole-slice answers (CSV and Arrow) at an explicit past `asof`: such an answer is immutable (no
47/// later write has a tx at or before that instant), so the encoded bytes are kept, least recently used first out, bounded
48/// by [`BODY_CACHE_BYTES`] in all. JSON pages and latest answers are not cached.
49#[derive(Default)]
50pub(crate) struct BodyCache {
51    /// Each entry: the key, the body, its media type and the `next` link of its page (H2).
52    entries: VecDeque<(BodyKey, Bytes, &'static str, Option<String>)>,
53    bytes: usize,
54}
55
56impl BodyCache {
57    fn get(&mut self, key: &BodyKey) -> Option<(Bytes, &'static str, Option<String>)> {
58        let i = self.entries.iter().position(|(k, _, _, _)| k == key)?;
59        let e = self.entries.remove(i)?;
60        let out = (e.1.clone(), e.2, e.3.clone());
61        self.entries.push_back(e);
62        Some(out)
63    }
64
65    fn put(&mut self, key: BodyKey, body: &Bytes, content_type: &'static str, next: Option<String>) {
66        if body.len() > BODY_CACHE_BYTES {
67            return;
68        }
69        if let Some(i) = self.entries.iter().position(|(k, _, _, _)| *k == key) {
70            if let Some(old) = self.entries.remove(i) {
71                self.bytes -= old.1.len();
72            }
73        }
74        while self.bytes + body.len() > BODY_CACHE_BYTES {
75            match self.entries.pop_front() {
76                Some(old) => self.bytes -= old.1.len(),
77                None => break,
78            }
79        }
80        self.bytes += body.len();
81        self.entries.push_back((key, body.clone(), content_type, next));
82    }
83}
84
85/// The open arguments of a target, ascending.
86fn open_args(t: &Target) -> Vec<String> {
87    t.cell.args.iter().filter(|(_, a)| matches!(a, Arg::Slice)).map(|(k, _)| k.clone()).collect()
88}
89
90fn key_of(m: &SliceValue, open: &[String]) -> Vec<Scalar> {
91    open.iter().filter_map(|k| m.cell.args.get(k).and_then(Arg::scalar).cloned()).collect()
92}
93
94/// A cursor: hex of the JCS bytes of the key's typed scalars.
95fn cursor(key: &[Scalar]) -> String {
96    lexical::to_hex(&Value::Array(key.iter().map(Scalar::to_value).collect()).to_jcs())
97}
98
99fn parse_cursor(s: &str) -> Option<Vec<Scalar>> {
100    if !s.len().is_multiple_of(2) || s.len() > 1 << 16 {
101        return None;
102    }
103    let bytes: Option<Vec<u8>> =
104        (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect();
105    let v = json::parse(&bytes?).ok()?;
106    let Value::Array(items) = v else { return None };
107    items.iter().map(|i| Scalar::from_json(&i.to_jcs()).ok()).collect()
108}
109
110/// The form of a slice answer: JSON pages (the default), an Arrow stream or CSV (Build 2 Part 6, G1: each
111/// its own address, `?format=arrow` and `?format=csv`, or chosen by `Accept` for Arrow).
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub(crate) enum Form {
114    #[default]
115    Json,
116    Arrow,
117    Csv,
118}
119
120/// What a slice request asks besides the slice.
121#[derive(Clone, Debug, Default)]
122pub(crate) struct SliceQuery {
123    pub(crate) limit: Option<usize>,
124    pub(crate) after: Option<String>,
125    pub(crate) form: Form,
126}
127
128/// Splits `?format=` off a slice request's query: the form it names (`None` when there is none), and
129/// the rest of the request. An unknown format is `E_PARSE_URI`.
130pub(crate) fn split_format(rest: &str) -> Result<(String, Option<Form>), ErrorCode> {
131    let Some((path, query)) = rest.split_once('?') else {
132        return Ok((rest.to_string(), None));
133    };
134    let mut form = None;
135    let mut kept = Vec::new();
136    for p in query.split('&') {
137        if let Some(v) = p.strip_prefix("format=") {
138            form = Some(match v {
139                "json" => Form::Json,
140                "arrow" => Form::Arrow,
141                "csv" => Form::Csv,
142                _ => return Err(ErrorCode::ParseUri),
143            });
144        } else {
145            kept.push(p);
146        }
147    }
148    if kept.is_empty() {
149        Ok((path.to_string(), form))
150    } else {
151        Ok((format!("{path}?{}", kept.join("&")), form))
152    }
153}
154
155/// A CSV field: quoted when it holds a comma, a quote or a line break (RFC 4180).
156pub(crate) fn csv_field(t: &str) -> String {
157    if t.contains([',', '"', '\r', '\n']) {
158        format!("\"{}\"", t.replace('"', "\"\""))
159    } else {
160        t.to_string()
161    }
162}
163
164/// Splits `?limit=` and `?after=` off a slice request's query; the rest is the slice's.
165pub(crate) fn split_query(rest: &str) -> Result<(String, SliceQuery), ErrorCode> {
166    let Some((path, query)) = rest.split_once('?') else {
167        return Ok((rest.to_string(), SliceQuery::default()));
168    };
169    let mut q = SliceQuery::default();
170    let mut kept = Vec::new();
171    for p in query.split('&') {
172        if let Some(v) = p.strip_prefix("limit=") {
173            q.limit = Some(v.parse().map_err(|_| ErrorCode::ParseUri)?);
174        } else if let Some(v) = p.strip_prefix("after=") {
175            q.after = Some(v.to_string());
176        } else {
177            kept.push(p);
178        }
179    }
180    if kept.is_empty() {
181        Ok((path.to_string(), q))
182    } else {
183        Ok((format!("{path}?{}", kept.join("&")), q))
184    }
185}
186
187/// The sort key (CONTRACT-0.5.1 S1) of a member at a cursor: the cell's arguments in name order, the open ones from the
188/// cursor's key scalars (in the open arguments' order), the fixed ones as the slice gives them.
189fn sort_key_at(t: &Target, key: &[Scalar]) -> Option<Vec<u8>> {
190    let mut open = key.iter();
191    let mut parts: Vec<(String, String, String)> = Vec::new();
192    for (name, a) in &t.cell.args {
193        let s = match a {
194            Arg::Value(s) => s,
195            Arg::Slice => open.next()?,
196        };
197        parts.push((name.clone(), s.ty().as_str().to_string(), s.lexical().to_string()));
198    }
199    if open.next().is_some() {
200        return None;
201    }
202    let refs: Vec<(&str, &str, &str)> = parts.iter().map(|(n, t, v)| (n.as_str(), t.as_str(), v.as_str())).collect();
203    Some(datumesh_store::sort_key(&refs))
204}
205
206impl Inner {
207    /// The members of a whole-slice answer (CSV, Arrow): `limit=` when named, never above `slice_max` (H2).
208    fn whole_slice_page(&self, q: &SliceQuery) -> usize {
209        q.limit.unwrap_or(self.config.slice_max).min(self.config.slice_max).max(1)
210    }
211
212    /// The `Link: rel="next"` of a whole-slice page (H2, CONTRACT-protocol-part1 0.5.3): only for a request that names a
213    /// `limit` and has members after this page. The same URL as the request's, pinned to the instant the members answer
214    /// as of (as JSON's `next` is), with the cursor of the page's last member, which is JSON's cursor.
215    #[allow(clippy::too_many_arguments)]
216    fn whole_slice_next(
217        &self,
218        target: &Target,
219        a: &str,
220        open: &[String],
221        last: Option<&SliceValue>,
222        more: bool,
223        q: &SliceQuery,
224        n: usize,
225    ) -> Option<String> {
226        if !more || q.limit.is_none() {
227            return None;
228        }
229        let fmt = match q.form {
230            Form::Csv => "csv",
231            Form::Arrow => "arrow",
232            Form::Json => return None,
233        };
234        let k = key_of(last?, open);
235        Some(format!(
236            "{}/slice/{}&format={fmt}&limit={n}&after={}",
237            self.config.origin(),
238            target.rest_asof(a),
239            cursor(&k)
240        ))
241    }
242
243    /// One page of `n` members of `slice` as of `a`, after `after` (a sort key), and whether more follow (the store's
244    /// slice pages, CONTRACT-0.5.1 H1: `n + 1` members are read, never the whole slice).
245    fn page_of(
246        &self,
247        slice: &Slice,
248        a: &str,
249        after: Option<&[u8]>,
250        n: usize,
251    ) -> Result<(Vec<SliceValue>, bool), ErrorCode> {
252        let read = if slice.is_version_slice() {
253            // A version slice has no key order to page by: its first page only.
254            if after.is_some() {
255                return Err(ErrorCode::ParseUri);
256            }
257            self.store.slice_values_limit(slice, a, n + 1)
258        } else {
259            self.store.slice_page(slice, a, after, n + 1)
260        };
261        let mut m = read.map_err(|e| {
262            tracing::warn!(target: "datumesh_http", error = %e, "slice page");
263            ErrorCode::InputUnavailable
264        })?;
265        let more = m.len() > n;
266        m.truncate(n);
267        Ok((m, more))
268    }
269
270    /// Answers a slice request (blocking) in the form asked, with the `Link` to the next page of a whole-slice answer.
271    pub(crate) fn slice(&self, rest: &str, now: &str, form: Form) -> (Reply, Option<String>) {
272        // The store's barrier first (second review B2): a slice's answer is immutable, so it waits for the writers
273        // in flight, and a store that does not answer in time is 503.
274        if self.store.barrier().is_err() {
275            return (envelope::error_reply(datumesh_core::ErrorCode::InputUnavailable), None);
276        }
277        let mut next = None;
278        let r = self.slice_answer(rest, now, form, &mut next);
279        (r, next)
280    }
281
282    fn slice_answer(&self, rest: &str, now: &str, form: Form, next: &mut Option<String>) -> Reply {
283        let (rest, mut q) = match split_query(rest) {
284            Ok(x) => x,
285            Err(c) => return envelope::bad_request_reply(c),
286        };
287        q.form = form;
288        let target = match crate::call::resolve(&rest, now, &self.config.aliases, self, true) {
289            Ok(t) => t,
290            Err(r) => return self.rejection(r, None),
291        };
292        if target.bound.descriptor.lang != "stored" {
293            // Members of a computed function would each be evaluated: not served in 0.1.0.
294            return envelope::error_reply(ErrorCode::EvalUnavailable);
295        }
296        if self.foreign.is_foreign(&target.fn_name()) {
297            return envelope::error_reply(ErrorCode::InputUnavailable);
298        }
299        if self.config.policy.rule(&target.fn_name()).is_some() {
300            return Reply::json(403, envelope::unlicensed(), Cache::Private);
301        }
302        let a = target.asof().unwrap_or(now).to_string();
303        let slice = match Slice::from_value(&target.cell.to_value()) {
304            Ok(s) => s,
305            Err(e) => {
306                return envelope::bad_request_reply(if envelope::is_request_code(e.code()) {
307                    e.code()
308                } else {
309                    ErrorCode::ParseUri
310                })
311            }
312        };
313        let open = open_args(&target);
314        let cache = if target.asof().is_some_and(|x| x <= now) {
315            Cache::Immutable
316        } else {
317            Cache::Public(self.config.ttl.latest_max_age.as_secs())
318        };
319        let after = match &q.after {
320            None => None,
321            Some(c) => match parse_cursor(c) {
322                Some(k) if k.len() == open.len() => match sort_key_at(&target, &k) {
323                    Some(sk) => Some(sk),
324                    None => return envelope::bad_request_reply(ErrorCode::ParseUri),
325                },
326                _ => return envelope::bad_request_reply(ErrorCode::ParseUri),
327            },
328        };
329        // A whole-slice body (CSV, Arrow) at an explicit past asof is cached (CONTRACT-0.5.1 H1).
330        let body_key: Option<BodyKey> = (target.asof().is_some_and(|x| x < now) && q.form != Form::Json)
331            .then(|| (format!("{:?}", q.form), slice.to_value().to_jcs(), a.clone(), q.limit, q.after.clone()));
332        if let Some(key) = &body_key {
333            let hit = self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).get(key);
334            if let Some((body, content_type, link)) = hit {
335                *next = link;
336                return Reply { status: 200, body, content_type, cache, canonical: None, retry_after: None };
337            }
338        }
339        if q.form == Form::Csv {
340            // One row a member, in key order: its key arguments, its value and its tx. At most `limit` rows, else the
341            // whole slice up to the bound; with a `limit` and more members, a `Link` to the next page (H2).
342            let n = self.whole_slice_page(&q);
343            let (members, more) = match self.page_of(&slice, &a, after.as_deref(), n) {
344                Ok(x) => x,
345                Err(c) => return envelope::error_reply(c),
346            };
347            let mut out = String::new();
348            let mut head: Vec<String> = open.clone();
349            head.extend(["value".to_string(), "tx".to_string()]);
350            out.push_str(&head.iter().map(|h| csv_field(h)).collect::<Vec<_>>().join(","));
351            out.push_str("\r\n");
352            for m in &members {
353                let mut cells: Vec<String> = open
354                    .iter()
355                    .map(|k| {
356                        m.cell.args.get(k).and_then(Arg::scalar).map(|x| x.lexical().to_string()).unwrap_or_default()
357                    })
358                    .collect();
359                cells.push(m.value.lexical().to_string());
360                cells.push(m.version.tx.clone());
361                out.push_str(&cells.iter().map(|c| csv_field(c)).collect::<Vec<_>>().join(","));
362                out.push_str("\r\n");
363            }
364            let body: Bytes = out.into_bytes().into();
365            let link = self.whole_slice_next(&target, &a, &open, members.last(), more, &q, n);
366            if let Some(key) = body_key {
367                self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).put(key, &body, CSV, link.clone());
368            }
369            *next = link;
370            return Reply { status: 200, body, content_type: CSV, cache, canonical: None, retry_after: None };
371        }
372        if q.form == Form::Arrow {
373            let n = self.whole_slice_page(&q);
374            let (members, more) = match self.page_of(&slice, &a, after.as_deref(), n) {
375                Ok(x) => x,
376                Err(c) => return envelope::error_reply(c),
377            };
378            // The instant the members answer as of (CONTRACT-perf H7): `at`, the `asof` the JSON `next` pins.
379            return match arrow_stream(&members, &open, &slice, &a, &target.fn_name()) {
380                Ok(body) => {
381                    let body: Bytes = body.into();
382                    let link = self.whole_slice_next(&target, &a, &open, members.last(), more, &q, n);
383                    if let Some(key) = body_key {
384                        self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).put(
385                            key,
386                            &body,
387                            ARROW,
388                            link.clone(),
389                        );
390                    }
391                    *next = link;
392                    Reply { status: 200, body, content_type: ARROW, cache, canonical: None, retry_after: None }
393                }
394                Err(e) => {
395                    tracing::warn!(target: "datumesh_http", error = %e, "arrow");
396                    envelope::error_reply(ErrorCode::EvalUnavailable)
397                }
398            };
399        }
400        let limit = q.limit.unwrap_or(self.config.slice_page).clamp(1, crate::config::MAX_SLICE_PAGE);
401        let (members, more) = match self.page_of(&slice, &a, after.as_deref(), limit) {
402            Ok(x) => x,
403            Err(c) => return envelope::error_reply(c),
404        };
405        // A page (5.6): the members' envelopes, in key order.
406        let mut page = Vec::with_capacity(members.len());
407        for m in &members {
408            match self.receipt_info_by_hash(&m.version.receipt_hash) {
409                Some(info) => page.push(crate::envelope::with_fn_hash(
410                    datumesh_core::Answer::ok(info.parsed.clone(), info.trust),
411                    Some(&info.parsed.cell().fn_hash),
412                )),
413                None => return crate::envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(slice.fn_hash())),
414            }
415        }
416        let next = match members.last().filter(|_| more) {
417            Some(last) => {
418                let k = key_of(last, &open);
419                Some(format!(
420                    "{}/slice/{}&limit={limit}&after={}",
421                    self.config.origin(),
422                    target.rest_asof(&a),
423                    cursor(&k)
424                ))
425            }
426            None => None,
427        };
428        let fn_hash = slice.fn_hash().to_string();
429        let answer = datumesh_core::Answer::page(datumesh_core::SlicePage::new(slice, page, next));
430        crate::envelope::answer_reply(&crate::envelope::with_fn_hash(answer, Some(&fn_hash)), cache)
431    }
432}
433
434pub(crate) fn arrow_stream(
435    members: &[SliceValue],
436    open: &[String],
437    slice: &Slice,
438    asof: &str,
439    function: &str,
440) -> Result<Vec<u8>, String> {
441    let mut fields: Vec<Field> = open.iter().map(|k| Field::new(k, DataType::Utf8, false)).collect();
442    for c in ["value", "type", "receipt", "tx", "asof"] {
443        fields.push(Field::new(c, DataType::Utf8, false));
444    }
445    let metadata = [
446        ("slice_id".to_string(), slice.id().to_string()),
447        ("asof".to_string(), asof.to_string()),
448        ("function".to_string(), function.to_string()),
449    ]
450    .into_iter()
451    .collect();
452    let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
453    let mut out = Vec::new();
454    {
455        let mut w = arrow_ipc::writer::StreamWriter::try_new(&mut out, &schema).map_err(|e| e.to_string())?;
456        for chunk in members.chunks(65_536) {
457            let mut cols: Vec<ArrayRef> = Vec::new();
458            for k in open {
459                let a: StringArray = chunk
460                    .iter()
461                    .map(|m| Some(m.cell.args.get(k).and_then(Arg::scalar).map(Scalar::lexical).unwrap_or_default()))
462                    .collect();
463                cols.push(Arc::new(a));
464            }
465            let v: StringArray = chunk.iter().map(|m| Some(m.value.lexical())).collect();
466            let t: StringArray = chunk.iter().map(|m| Some(m.value.ty().as_str())).collect();
467            let r: StringArray = chunk.iter().map(|m| Some(m.version.receipt_hash.as_str())).collect();
468            let tx: StringArray = chunk.iter().map(|m| Some(m.version.tx.as_str())).collect();
469            let at: StringArray = chunk.iter().map(|m| Some(m.version.asof.as_str())).collect();
470            for a in [v, t, r, tx, at] {
471                cols.push(Arc::new(a));
472            }
473            let batch = RecordBatch::try_new(schema.clone(), cols).map_err(|e| e.to_string())?;
474            w.write(&batch).map_err(|e| e.to_string())?;
475        }
476        w.finish().map_err(|e| e.to_string())?;
477    }
478    Ok(out)
479}