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)>,
52 bytes: usize,
53}
54
55impl BodyCache {
56 fn get(&mut self, key: &BodyKey) -> Option<(Bytes, &'static str)> {
57 let i = self.entries.iter().position(|(k, _, _)| k == key)?;
58 let e = self.entries.remove(i)?;
59 let out = (e.1.clone(), e.2);
60 self.entries.push_back(e);
61 Some(out)
62 }
63
64 fn put(&mut self, key: BodyKey, body: &Bytes, content_type: &'static str) {
65 if body.len() > BODY_CACHE_BYTES {
66 return;
67 }
68 if let Some(i) = self.entries.iter().position(|(k, _, _)| *k == key) {
69 if let Some(old) = self.entries.remove(i) {
70 self.bytes -= old.1.len();
71 }
72 }
73 while self.bytes + body.len() > BODY_CACHE_BYTES {
74 match self.entries.pop_front() {
75 Some(old) => self.bytes -= old.1.len(),
76 None => break,
77 }
78 }
79 self.bytes += body.len();
80 self.entries.push_back((key, body.clone(), content_type));
81 }
82}
83
84fn open_args(t: &Target) -> Vec<String> {
86 t.cell.args.iter().filter(|(_, a)| matches!(a, Arg::Slice)).map(|(k, _)| k.clone()).collect()
87}
88
89fn key_of(m: &SliceValue, open: &[String]) -> Vec<Scalar> {
90 open.iter().filter_map(|k| m.cell.args.get(k).and_then(Arg::scalar).cloned()).collect()
91}
92
93fn cursor(key: &[Scalar]) -> String {
95 lexical::to_hex(&Value::Array(key.iter().map(Scalar::to_value).collect()).to_jcs())
96}
97
98fn parse_cursor(s: &str) -> Option<Vec<Scalar>> {
99 if !s.len().is_multiple_of(2) || s.len() > 1 << 16 {
100 return None;
101 }
102 let bytes: Option<Vec<u8>> =
103 (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect();
104 let v = json::parse(&bytes?).ok()?;
105 let Value::Array(items) = v else { return None };
106 items.iter().map(|i| Scalar::from_json(&i.to_jcs()).ok()).collect()
107}
108
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
112pub(crate) enum Form {
113 #[default]
114 Json,
115 Arrow,
116 Csv,
117}
118
119#[derive(Clone, Debug, Default)]
121pub(crate) struct SliceQuery {
122 pub(crate) limit: Option<usize>,
123 pub(crate) after: Option<String>,
124 pub(crate) form: Form,
125}
126
127pub(crate) fn split_format(rest: &str) -> Result<(String, Option<Form>), ErrorCode> {
130 let Some((path, query)) = rest.split_once('?') else {
131 return Ok((rest.to_string(), None));
132 };
133 let mut form = None;
134 let mut kept = Vec::new();
135 for p in query.split('&') {
136 if let Some(v) = p.strip_prefix("format=") {
137 form = Some(match v {
138 "json" => Form::Json,
139 "arrow" => Form::Arrow,
140 "csv" => Form::Csv,
141 _ => return Err(ErrorCode::ParseUri),
142 });
143 } else {
144 kept.push(p);
145 }
146 }
147 if kept.is_empty() {
148 Ok((path.to_string(), form))
149 } else {
150 Ok((format!("{path}?{}", kept.join("&")), form))
151 }
152}
153
154pub(crate) fn csv_field(t: &str) -> String {
156 if t.contains([',', '"', '\r', '\n']) {
157 format!("\"{}\"", t.replace('"', "\"\""))
158 } else {
159 t.to_string()
160 }
161}
162
163pub(crate) fn split_query(rest: &str) -> Result<(String, SliceQuery), ErrorCode> {
165 let Some((path, query)) = rest.split_once('?') else {
166 return Ok((rest.to_string(), SliceQuery::default()));
167 };
168 let mut q = SliceQuery::default();
169 let mut kept = Vec::new();
170 for p in query.split('&') {
171 if let Some(v) = p.strip_prefix("limit=") {
172 q.limit = Some(v.parse().map_err(|_| ErrorCode::ParseUri)?);
173 } else if let Some(v) = p.strip_prefix("after=") {
174 q.after = Some(v.to_string());
175 } else {
176 kept.push(p);
177 }
178 }
179 if kept.is_empty() {
180 Ok((path.to_string(), q))
181 } else {
182 Ok((format!("{path}?{}", kept.join("&")), q))
183 }
184}
185
186fn sort_key_at(t: &Target, key: &[Scalar]) -> Option<Vec<u8>> {
189 let mut open = key.iter();
190 let mut parts: Vec<(String, String, String)> = Vec::new();
191 for (name, a) in &t.cell.args {
192 let s = match a {
193 Arg::Value(s) => s,
194 Arg::Slice => open.next()?,
195 };
196 parts.push((name.clone(), s.ty().as_str().to_string(), s.lexical().to_string()));
197 }
198 if open.next().is_some() {
199 return None;
200 }
201 let refs: Vec<(&str, &str, &str)> = parts.iter().map(|(n, t, v)| (n.as_str(), t.as_str(), v.as_str())).collect();
202 Some(datumesh_store::sort_key(&refs))
203}
204
205impl Inner {
206 fn page_of(
209 &self,
210 slice: &Slice,
211 a: &str,
212 after: Option<&[u8]>,
213 n: usize,
214 ) -> Result<(Vec<SliceValue>, bool), ErrorCode> {
215 let read = if slice.is_version_slice() {
216 if after.is_some() {
218 return Err(ErrorCode::ParseUri);
219 }
220 self.store.slice_values_limit(slice, a, n + 1)
221 } else {
222 self.store.slice_page(slice, a, after, n + 1)
223 };
224 let mut m = read.map_err(|e| {
225 tracing::warn!(target: "datumesh_http", error = %e, "slice page");
226 ErrorCode::InputUnavailable
227 })?;
228 let more = m.len() > n;
229 m.truncate(n);
230 Ok((m, more))
231 }
232
233 pub(crate) fn slice(&self, rest: &str, now: &str, form: Form) -> Reply {
235 let (rest, mut q) = match split_query(rest) {
236 Ok(x) => x,
237 Err(c) => return envelope::bad_request_reply(c),
238 };
239 q.form = form;
240 let target = match crate::call::resolve(&rest, now, &self.config.aliases, self, true) {
241 Ok(t) => t,
242 Err(r) => return self.rejection(r, None),
243 };
244 if target.bound.descriptor.lang != "stored" {
245 return envelope::error_reply(ErrorCode::EvalUnavailable);
247 }
248 if self.foreign.is_foreign(&target.fn_name()) {
249 return envelope::error_reply(ErrorCode::InputUnavailable);
250 }
251 if self.config.policy.rule(&target.fn_name()).is_some() {
252 return Reply::json(403, envelope::unlicensed(), Cache::Private);
253 }
254 let a = target.asof().unwrap_or(now).to_string();
255 let slice = match Slice::from_value(&target.cell.to_value()) {
256 Ok(s) => s,
257 Err(e) => {
258 return envelope::bad_request_reply(if envelope::is_request_code(e.code()) {
259 e.code()
260 } else {
261 ErrorCode::ParseUri
262 })
263 }
264 };
265 let open = open_args(&target);
266 let cache = if target.asof().is_some_and(|x| x <= now) {
267 Cache::Immutable
268 } else {
269 Cache::Public(self.config.ttl.latest_max_age.as_secs())
270 };
271 let after = match &q.after {
272 None => None,
273 Some(c) => match parse_cursor(c) {
274 Some(k) if k.len() == open.len() => match sort_key_at(&target, &k) {
275 Some(sk) => Some(sk),
276 None => return envelope::bad_request_reply(ErrorCode::ParseUri),
277 },
278 _ => return envelope::bad_request_reply(ErrorCode::ParseUri),
279 },
280 };
281 let body_key: Option<BodyKey> = (target.asof().is_some_and(|x| x < now) && q.form != Form::Json)
283 .then(|| (format!("{:?}", q.form), slice.to_value().to_jcs(), a.clone(), q.limit, q.after.clone()));
284 if let Some(key) = &body_key {
285 let hit = self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).get(key);
286 if let Some((body, content_type)) = hit {
287 return Reply { status: 200, body, content_type, cache, canonical: None, retry_after: None };
288 }
289 }
290 if q.form == Form::Csv {
291 let (members, _) = match self.page_of(&slice, &a, after.as_deref(), self.config.slice_max) {
294 Ok(x) => x,
295 Err(c) => return envelope::error_reply(c),
296 };
297 let mut out = String::new();
298 let mut head: Vec<String> = open.clone();
299 head.extend(["value".to_string(), "tx".to_string()]);
300 out.push_str(&head.iter().map(|h| csv_field(h)).collect::<Vec<_>>().join(","));
301 out.push_str("\r\n");
302 for m in &members {
303 let mut cells: Vec<String> = open
304 .iter()
305 .map(|k| {
306 m.cell.args.get(k).and_then(Arg::scalar).map(|x| x.lexical().to_string()).unwrap_or_default()
307 })
308 .collect();
309 cells.push(m.value.lexical().to_string());
310 cells.push(m.version.tx.clone());
311 out.push_str(&cells.iter().map(|c| csv_field(c)).collect::<Vec<_>>().join(","));
312 out.push_str("\r\n");
313 }
314 let body: Bytes = out.into_bytes().into();
315 if let Some(key) = body_key {
316 self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).put(key, &body, CSV);
317 }
318 return Reply { status: 200, body, content_type: CSV, cache, canonical: None, retry_after: None };
319 }
320 if q.form == Form::Arrow {
321 let n = q.limit.unwrap_or(self.config.slice_max);
322 let (members, _) = match self.page_of(&slice, &a, after.as_deref(), n) {
323 Ok(x) => x,
324 Err(c) => return envelope::error_reply(c),
325 };
326 return match arrow_stream(&members, &open, &slice, &a, &target.fn_name()) {
328 Ok(body) => {
329 let body: Bytes = body.into();
330 if let Some(key) = body_key {
331 self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).put(key, &body, ARROW);
332 }
333 Reply { status: 200, body, content_type: ARROW, cache, canonical: None, retry_after: None }
334 }
335 Err(e) => {
336 tracing::warn!(target: "datumesh_http", error = %e, "arrow");
337 envelope::error_reply(ErrorCode::EvalUnavailable)
338 }
339 };
340 }
341 let limit = q.limit.unwrap_or(self.config.slice_page).clamp(1, crate::config::MAX_SLICE_PAGE);
342 let (members, more) = match self.page_of(&slice, &a, after.as_deref(), limit) {
343 Ok(x) => x,
344 Err(c) => return envelope::error_reply(c),
345 };
346 let mut page = Vec::with_capacity(members.len());
348 for m in &members {
349 match self.receipt_info_by_hash(&m.version.receipt_hash) {
350 Some(info) => page.push(crate::envelope::with_fn_hash(
351 datumesh_core::Answer::ok(info.parsed.clone(), info.trust),
352 Some(&info.parsed.cell().fn_hash),
353 )),
354 None => return crate::envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(slice.fn_hash())),
355 }
356 }
357 let next = match members.last().filter(|_| more) {
358 Some(last) => {
359 let k = key_of(last, &open);
360 Some(format!(
361 "{}/slice/{}&limit={limit}&after={}",
362 self.config.origin(),
363 target.rest_asof(&a),
364 cursor(&k)
365 ))
366 }
367 None => None,
368 };
369 let fn_hash = slice.fn_hash().to_string();
370 let answer = datumesh_core::Answer::page(datumesh_core::SlicePage::new(slice, page, next));
371 crate::envelope::answer_reply(&crate::envelope::with_fn_hash(answer, Some(&fn_hash)), cache)
372 }
373}
374
375pub(crate) fn arrow_stream(
376 members: &[SliceValue],
377 open: &[String],
378 slice: &Slice,
379 asof: &str,
380 function: &str,
381) -> Result<Vec<u8>, String> {
382 let mut fields: Vec<Field> = open.iter().map(|k| Field::new(k, DataType::Utf8, false)).collect();
383 for c in ["value", "type", "receipt", "tx", "asof"] {
384 fields.push(Field::new(c, DataType::Utf8, false));
385 }
386 let metadata = [
387 ("slice_id".to_string(), slice.id().to_string()),
388 ("asof".to_string(), asof.to_string()),
389 ("function".to_string(), function.to_string()),
390 ]
391 .into_iter()
392 .collect();
393 let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
394 let mut out = Vec::new();
395 {
396 let mut w = arrow_ipc::writer::StreamWriter::try_new(&mut out, &schema).map_err(|e| e.to_string())?;
397 for chunk in members.chunks(65_536) {
398 let mut cols: Vec<ArrayRef> = Vec::new();
399 for k in open {
400 let a: StringArray = chunk
401 .iter()
402 .map(|m| Some(m.cell.args.get(k).and_then(Arg::scalar).map(Scalar::lexical).unwrap_or_default()))
403 .collect();
404 cols.push(Arc::new(a));
405 }
406 let v: StringArray = chunk.iter().map(|m| Some(m.value.lexical())).collect();
407 let t: StringArray = chunk.iter().map(|m| Some(m.value.ty().as_str())).collect();
408 let r: StringArray = chunk.iter().map(|m| Some(m.version.receipt_hash.as_str())).collect();
409 let tx: StringArray = chunk.iter().map(|m| Some(m.version.tx.as_str())).collect();
410 let at: StringArray = chunk.iter().map(|m| Some(m.version.asof.as_str())).collect();
411 for a in [v, t, r, tx, at] {
412 cols.push(Arc::new(a));
413 }
414 let batch = RecordBatch::try_new(schema.clone(), cols).map_err(|e| e.to_string())?;
415 w.write(&batch).map_err(|e| e.to_string())?;
416 }
417 w.finish().map_err(|e| e.to_string())?;
418 }
419 Ok(out)
420}