1use 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
34pub const ARROW: &str = "application/vnd.apache.arrow.stream";
36const CSV: &str = "text/csv; charset=utf-8";
38
39pub(crate) const BODY_CACHE_BYTES: usize = 64 << 20;
41
42type BodyKey = (String, Vec<u8>, String, Option<usize>, Option<String>);
45
46#[derive(Default)]
50pub(crate) struct BodyCache {
51 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
85fn 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
94fn 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub(crate) enum Form {
114 #[default]
115 Json,
116 Arrow,
117 Csv,
118}
119
120#[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
128pub(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
155pub(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
164pub(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
187fn 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 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 #[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 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 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 pub(crate) fn slice(&self, rest: &str, now: &str, form: Form) -> (Reply, Option<String>) {
272 let mut next = None;
273 let r = self.slice_answer(rest, now, form, &mut next);
274 (r, next)
275 }
276
277 fn slice_answer(&self, rest: &str, now: &str, form: Form, next: &mut Option<String>) -> Reply {
278 let (rest, mut q) = match split_query(rest) {
279 Ok(x) => x,
280 Err(c) => return envelope::bad_request_reply(c),
281 };
282 q.form = form;
283 let target = match crate::call::resolve(&rest, now, &self.config.aliases, self, true) {
284 Ok(t) => t,
285 Err(r) => return self.rejection(r, None),
286 };
287 if target.bound.descriptor.lang != "stored" {
288 return envelope::error_reply(ErrorCode::EvalUnavailable);
290 }
291 if self.foreign.is_foreign(&target.fn_name()) {
292 return envelope::error_reply(ErrorCode::InputUnavailable);
293 }
294 if self.config.policy.rule(&target.fn_name()).is_some() {
295 return Reply::json(403, envelope::unlicensed(), Cache::Private);
296 }
297 let a = target.asof().unwrap_or(now).to_string();
298 let slice = match Slice::from_value(&target.cell.to_value()) {
299 Ok(s) => s,
300 Err(e) => {
301 return envelope::bad_request_reply(if envelope::is_request_code(e.code()) {
302 e.code()
303 } else {
304 ErrorCode::ParseUri
305 })
306 }
307 };
308 let open = open_args(&target);
309 let cache = if target.asof().is_some_and(|x| x <= now) {
310 Cache::Immutable
311 } else {
312 Cache::Public(self.config.ttl.latest_max_age.as_secs())
313 };
314 let after = match &q.after {
315 None => None,
316 Some(c) => match parse_cursor(c) {
317 Some(k) if k.len() == open.len() => match sort_key_at(&target, &k) {
318 Some(sk) => Some(sk),
319 None => return envelope::bad_request_reply(ErrorCode::ParseUri),
320 },
321 _ => return envelope::bad_request_reply(ErrorCode::ParseUri),
322 },
323 };
324 let body_key: Option<BodyKey> = (target.asof().is_some_and(|x| x < now) && q.form != Form::Json)
326 .then(|| (format!("{:?}", q.form), slice.to_value().to_jcs(), a.clone(), q.limit, q.after.clone()));
327 if let Some(key) = &body_key {
328 let hit = self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).get(key);
329 if let Some((body, content_type, link)) = hit {
330 *next = link;
331 return Reply { status: 200, body, content_type, cache, canonical: None, retry_after: None };
332 }
333 }
334 if q.form == Form::Csv {
335 let n = self.whole_slice_page(&q);
338 let (members, more) = match self.page_of(&slice, &a, after.as_deref(), n) {
339 Ok(x) => x,
340 Err(c) => return envelope::error_reply(c),
341 };
342 let mut out = String::new();
343 let mut head: Vec<String> = open.clone();
344 head.extend(["value".to_string(), "tx".to_string()]);
345 out.push_str(&head.iter().map(|h| csv_field(h)).collect::<Vec<_>>().join(","));
346 out.push_str("\r\n");
347 for m in &members {
348 let mut cells: Vec<String> = open
349 .iter()
350 .map(|k| {
351 m.cell.args.get(k).and_then(Arg::scalar).map(|x| x.lexical().to_string()).unwrap_or_default()
352 })
353 .collect();
354 cells.push(m.value.lexical().to_string());
355 cells.push(m.version.tx.clone());
356 out.push_str(&cells.iter().map(|c| csv_field(c)).collect::<Vec<_>>().join(","));
357 out.push_str("\r\n");
358 }
359 let body: Bytes = out.into_bytes().into();
360 let link = self.whole_slice_next(&target, &a, &open, members.last(), more, &q, n);
361 if let Some(key) = body_key {
362 self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).put(key, &body, CSV, link.clone());
363 }
364 *next = link;
365 return Reply { status: 200, body, content_type: CSV, cache, canonical: None, retry_after: None };
366 }
367 if q.form == Form::Arrow {
368 let n = self.whole_slice_page(&q);
369 let (members, more) = match self.page_of(&slice, &a, after.as_deref(), n) {
370 Ok(x) => x,
371 Err(c) => return envelope::error_reply(c),
372 };
373 return match arrow_stream(&members, &open, &slice, &a, &target.fn_name()) {
375 Ok(body) => {
376 let body: Bytes = body.into();
377 let link = self.whole_slice_next(&target, &a, &open, members.last(), more, &q, n);
378 if let Some(key) = body_key {
379 self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).put(
380 key,
381 &body,
382 ARROW,
383 link.clone(),
384 );
385 }
386 *next = link;
387 Reply { status: 200, body, content_type: ARROW, cache, canonical: None, retry_after: None }
388 }
389 Err(e) => {
390 tracing::warn!(target: "datumesh_http", error = %e, "arrow");
391 envelope::error_reply(ErrorCode::EvalUnavailable)
392 }
393 };
394 }
395 let limit = q.limit.unwrap_or(self.config.slice_page).clamp(1, crate::config::MAX_SLICE_PAGE);
396 let (members, more) = match self.page_of(&slice, &a, after.as_deref(), limit) {
397 Ok(x) => x,
398 Err(c) => return envelope::error_reply(c),
399 };
400 let mut page = Vec::with_capacity(members.len());
402 for m in &members {
403 match self.receipt_info_by_hash(&m.version.receipt_hash) {
404 Some(info) => page.push(crate::envelope::with_fn_hash(
405 datumesh_core::Answer::ok(info.parsed.clone(), info.trust),
406 Some(&info.parsed.cell().fn_hash),
407 )),
408 None => return crate::envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(slice.fn_hash())),
409 }
410 }
411 let next = match members.last().filter(|_| more) {
412 Some(last) => {
413 let k = key_of(last, &open);
414 Some(format!(
415 "{}/slice/{}&limit={limit}&after={}",
416 self.config.origin(),
417 target.rest_asof(&a),
418 cursor(&k)
419 ))
420 }
421 None => None,
422 };
423 let fn_hash = slice.fn_hash().to_string();
424 let answer = datumesh_core::Answer::page(datumesh_core::SlicePage::new(slice, page, next));
425 crate::envelope::answer_reply(&crate::envelope::with_fn_hash(answer, Some(&fn_hash)), cache)
426 }
427}
428
429pub(crate) fn arrow_stream(
430 members: &[SliceValue],
431 open: &[String],
432 slice: &Slice,
433 asof: &str,
434 function: &str,
435) -> Result<Vec<u8>, String> {
436 let mut fields: Vec<Field> = open.iter().map(|k| Field::new(k, DataType::Utf8, false)).collect();
437 for c in ["value", "type", "receipt", "tx", "asof"] {
438 fields.push(Field::new(c, DataType::Utf8, false));
439 }
440 let metadata = [
441 ("slice_id".to_string(), slice.id().to_string()),
442 ("asof".to_string(), asof.to_string()),
443 ("function".to_string(), function.to_string()),
444 ]
445 .into_iter()
446 .collect();
447 let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
448 let mut out = Vec::new();
449 {
450 let mut w = arrow_ipc::writer::StreamWriter::try_new(&mut out, &schema).map_err(|e| e.to_string())?;
451 for chunk in members.chunks(65_536) {
452 let mut cols: Vec<ArrayRef> = Vec::new();
453 for k in open {
454 let a: StringArray = chunk
455 .iter()
456 .map(|m| Some(m.cell.args.get(k).and_then(Arg::scalar).map(Scalar::lexical).unwrap_or_default()))
457 .collect();
458 cols.push(Arc::new(a));
459 }
460 let v: StringArray = chunk.iter().map(|m| Some(m.value.lexical())).collect();
461 let t: StringArray = chunk.iter().map(|m| Some(m.value.ty().as_str())).collect();
462 let r: StringArray = chunk.iter().map(|m| Some(m.version.receipt_hash.as_str())).collect();
463 let tx: StringArray = chunk.iter().map(|m| Some(m.version.tx.as_str())).collect();
464 let at: StringArray = chunk.iter().map(|m| Some(m.version.asof.as_str())).collect();
465 for a in [v, t, r, tx, at] {
466 cols.push(Arc::new(a));
467 }
468 let batch = RecordBatch::try_new(schema.clone(), cols).map_err(|e| e.to_string())?;
469 w.write(&batch).map_err(|e| e.to_string())?;
470 }
471 w.finish().map_err(|e| e.to_string())?;
472 }
473 Ok(out)
474}