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::cmp::Ordering;
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, 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
37/// The open arguments of a target, ascending.
38fn open_args(t: &Target) -> Vec<String> {
39    t.cell.args.iter().filter(|(_, a)| matches!(a, Arg::Slice)).map(|(k, _)| k.clone()).collect()
40}
41
42fn key_cmp(a: &[Scalar], b: &[Scalar]) -> Ordering {
43    for (x, y) in a.iter().zip(b) {
44        let o = datumesh_formula::eval::cmp_scalar(x, y);
45        if o != Ordering::Equal {
46            return o;
47        }
48    }
49    a.len().cmp(&b.len())
50}
51
52fn key_of(m: &SliceValue, open: &[String]) -> Vec<Scalar> {
53    open.iter().filter_map(|k| m.cell.args.get(k).and_then(Arg::scalar).cloned()).collect()
54}
55
56/// A cursor: hex of the JCS bytes of the key's typed scalars.
57fn cursor(key: &[Scalar]) -> String {
58    lexical::to_hex(&Value::Array(key.iter().map(Scalar::to_value).collect()).to_jcs())
59}
60
61fn parse_cursor(s: &str) -> Option<Vec<Scalar>> {
62    if !s.len().is_multiple_of(2) || s.len() > 1 << 16 {
63        return None;
64    }
65    let bytes: Option<Vec<u8>> =
66        (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect();
67    let v = json::parse(&bytes?).ok()?;
68    let Value::Array(items) = v else { return None };
69    items.iter().map(|i| Scalar::from_json(&i.to_jcs()).ok()).collect()
70}
71
72/// What a slice request asks besides the slice.
73#[derive(Clone, Debug, Default)]
74pub(crate) struct SliceQuery {
75    pub(crate) limit: Option<usize>,
76    pub(crate) after: Option<String>,
77    pub(crate) arrow: bool,
78}
79
80/// Splits `?limit=` and `?after=` off a slice request's query; the rest is the slice's.
81pub(crate) fn split_query(rest: &str) -> Result<(String, SliceQuery), ErrorCode> {
82    let Some((path, query)) = rest.split_once('?') else {
83        return Ok((rest.to_string(), SliceQuery::default()));
84    };
85    let mut q = SliceQuery::default();
86    let mut kept = Vec::new();
87    for p in query.split('&') {
88        if let Some(v) = p.strip_prefix("limit=") {
89            q.limit = Some(v.parse().map_err(|_| ErrorCode::ParseUri)?);
90        } else if let Some(v) = p.strip_prefix("after=") {
91            q.after = Some(v.to_string());
92        } else {
93            kept.push(p);
94        }
95    }
96    if kept.is_empty() {
97        Ok((path.to_string(), q))
98    } else {
99        Ok((format!("{path}?{}", kept.join("&")), q))
100    }
101}
102
103impl Inner {
104    /// The members of a slice as of `a`, and the instant they answer as of (`a`, or for a
105    /// latest request, the `at` of a cached entry they are reused from). Cached when `a` is at
106    /// or before now. A latest request (`latest`, `a` = now) reuses the cached entry of the
107    /// slice with the greatest `at <= now` when no member changed after that `at`
108    /// (`slice_changed_after`), so a first page of an unchanged series is a cache hit.
109    fn members(
110        &self,
111        slice: &Slice,
112        a: &str,
113        now: &str,
114        latest: bool,
115    ) -> Result<(Arc<Vec<SliceValue>>, String), ErrorCode> {
116        {
117            let c = self.slices.lock().unwrap_or_else(|p| p.into_inner());
118            if latest {
119                let reuse = c
120                    .iter()
121                    .filter(|(id, at, _)| id == slice.id() && at.as_str() <= now)
122                    .max_by(|x, y| x.1.cmp(&y.1))
123                    .map(|(_, at, m)| (at.clone(), m.clone()));
124                drop(c);
125                if let Some((at, m)) = reuse {
126                    match self.store.slice_changed_after(slice, &at) {
127                        Ok(false) => return Ok((m, at)),
128                        Ok(true) => {}
129                        Err(e) => tracing::warn!(target: "datumesh_http", error = %e, "slice_changed_after"),
130                    }
131                }
132            } else if let Some((_, _, m)) = c.iter().find(|(id, at, _)| id == slice.id() && at == a) {
133                return Ok((m.clone(), a.to_string()));
134            }
135        }
136        let m = Arc::new(self.store.slice_values(slice, a).map_err(|e| {
137            tracing::warn!(target: "datumesh_http", error = %e, "slice_values");
138            ErrorCode::InputUnavailable
139        })?);
140        if a <= now {
141            let mut c = self.slices.lock().unwrap_or_else(|p| p.into_inner());
142            c.retain(|(id, at, _)| !(id == slice.id() && at == a));
143            c.push((slice.id().to_string(), a.to_string(), m.clone()));
144            if c.len() > 8 {
145                c.remove(0);
146            }
147        }
148        Ok((m, a.to_string()))
149    }
150
151    /// Answers a slice request (blocking).
152    pub(crate) fn slice(&self, rest: &str, now: &str, arrow: bool) -> Reply {
153        let (rest, mut q) = match split_query(rest) {
154            Ok(x) => x,
155            Err(c) => return envelope::bad_request_reply(c),
156        };
157        q.arrow = arrow;
158        let target = match crate::call::resolve(&rest, now, &self.config.aliases, self, true) {
159            Ok(t) => t,
160            Err(r) => return self.rejection(r, None),
161        };
162        if target.bound.descriptor.lang != "stored" {
163            // Members of a computed function would each be evaluated: not served in 0.1.0.
164            return envelope::error_reply(ErrorCode::EvalUnavailable);
165        }
166        if self.foreign.is_foreign(&target.fn_name()) {
167            return envelope::error_reply(ErrorCode::InputUnavailable);
168        }
169        if self.config.policy.rule(&target.fn_name()).is_some() {
170            return Reply::json(403, envelope::unlicensed(), Cache::Private);
171        }
172        let a = target.asof().unwrap_or(now).to_string();
173        let slice = match Slice::from_value(&target.cell.to_value()) {
174            Ok(s) => s,
175            Err(e) => {
176                return envelope::bad_request_reply(if envelope::is_request_code(e.code()) {
177                    e.code()
178                } else {
179                    ErrorCode::ParseUri
180                })
181            }
182        };
183        let (members, at) = match self.members(&slice, &a, now, target.asof().is_none()) {
184            Ok(m) => m,
185            Err(c) => return envelope::error_reply(c),
186        };
187        let open = open_args(&target);
188        let total = members.len().min(self.config.slice_max);
189        let cache = if target.asof().is_some_and(|x| x <= now) {
190            Cache::Immutable
191        } else {
192            Cache::Public(self.config.ttl.latest_max_age.as_secs())
193        };
194        let start = match &q.after {
195            None => 0,
196            Some(c) => match parse_cursor(c) {
197                Some(k) => members[..total].partition_point(|m| key_cmp(&key_of(m, &open), &k) != Ordering::Greater),
198                None => return envelope::bad_request_reply(ErrorCode::ParseUri),
199            },
200        };
201        if q.arrow {
202            let end = match q.limit {
203                Some(l) => (start + l).min(total),
204                None => total,
205            };
206            // The instant the members answer as of (CONTRACT-perf H7): `at`, the `asof` the JSON `next` pins.
207            return match arrow_stream(&members[start..end], &open, &slice, &at, &target.fn_name()) {
208                Ok(body) => Reply {
209                    status: 200,
210                    body: body.into(),
211                    content_type: ARROW,
212                    cache,
213                    canonical: None,
214                    retry_after: None,
215                },
216                Err(e) => {
217                    tracing::warn!(target: "datumesh_http", error = %e, "arrow");
218                    envelope::error_reply(ErrorCode::EvalUnavailable)
219                }
220            };
221        }
222        let limit = q.limit.unwrap_or(self.config.slice_page).clamp(1, crate::config::MAX_SLICE_PAGE);
223        let end = (start + limit).min(total);
224        // A page (5.6): the members' envelopes, in key order.
225        let mut page = Vec::with_capacity(end - start);
226        for m in &members[start..end] {
227            match self.receipt_info_by_hash(&m.version.receipt_hash) {
228                Some(info) => page.push(crate::envelope::with_fn_hash(
229                    datumesh_core::Answer::ok(info.parsed.clone(), info.trust),
230                    Some(&info.parsed.cell().fn_hash),
231                )),
232                None => return crate::envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(slice.fn_hash())),
233            }
234        }
235        let next = (end < total).then(|| {
236            let k = key_of(&members[end - 1], &open);
237            format!("{}/slice/{}&limit={limit}&after={}", self.config.origin(), target.rest_asof(&at), cursor(&k))
238        });
239        let fn_hash = slice.fn_hash().to_string();
240        let answer = datumesh_core::Answer::page(datumesh_core::SlicePage::new(slice, page, next));
241        crate::envelope::answer_reply(&crate::envelope::with_fn_hash(answer, Some(&fn_hash)), cache)
242    }
243}
244
245fn arrow_stream(
246    members: &[SliceValue],
247    open: &[String],
248    slice: &Slice,
249    asof: &str,
250    function: &str,
251) -> Result<Vec<u8>, String> {
252    let mut fields: Vec<Field> = open.iter().map(|k| Field::new(k, DataType::Utf8, false)).collect();
253    for c in ["value", "type", "receipt", "tx", "asof"] {
254        fields.push(Field::new(c, DataType::Utf8, false));
255    }
256    let metadata = [
257        ("slice_id".to_string(), slice.id().to_string()),
258        ("asof".to_string(), asof.to_string()),
259        ("function".to_string(), function.to_string()),
260    ]
261    .into_iter()
262    .collect();
263    let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
264    let mut out = Vec::new();
265    {
266        let mut w = arrow_ipc::writer::StreamWriter::try_new(&mut out, &schema).map_err(|e| e.to_string())?;
267        for chunk in members.chunks(65_536) {
268            let mut cols: Vec<ArrayRef> = Vec::new();
269            for k in open {
270                let a: StringArray = chunk
271                    .iter()
272                    .map(|m| Some(m.cell.args.get(k).and_then(Arg::scalar).map(Scalar::lexical).unwrap_or_default()))
273                    .collect();
274                cols.push(Arc::new(a));
275            }
276            let v: StringArray = chunk.iter().map(|m| Some(m.value.lexical())).collect();
277            let t: StringArray = chunk.iter().map(|m| Some(m.value.ty().as_str())).collect();
278            let r: StringArray = chunk.iter().map(|m| Some(m.version.receipt_hash.as_str())).collect();
279            let tx: StringArray = chunk.iter().map(|m| Some(m.version.tx.as_str())).collect();
280            let at: StringArray = chunk.iter().map(|m| Some(m.version.asof.as_str())).collect();
281            for a in [v, t, r, tx, at] {
282                cols.push(Arc::new(a));
283            }
284            let batch = RecordBatch::try_new(schema.clone(), cols).map_err(|e| e.to_string())?;
285            w.write(&batch).map_err(|e| e.to_string())?;
286        }
287        w.finish().map_err(|e| e.to_string())?;
288    }
289    Ok(out)
290}