use std::collections::VecDeque;
use std::sync::Arc;
use arrow_array::{ArrayRef, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};
use datumesh_core::json::{self, Value};
use datumesh_core::{lexical, Arg, ErrorCode, Scalar, Slice};
use datumesh_store::SliceValue;
use crate::call::Target;
use crate::envelope::{self, Bytes, Cache, Reply};
use crate::mesh::Inner;
pub const ARROW: &str = "application/vnd.apache.arrow.stream";
const CSV: &str = "text/csv; charset=utf-8";
pub(crate) const BODY_CACHE_BYTES: usize = 64 << 20;
type BodyKey = (String, Vec<u8>, String, Option<usize>, Option<String>);
#[derive(Default)]
pub(crate) struct BodyCache {
entries: VecDeque<(BodyKey, Bytes, &'static str)>,
bytes: usize,
}
impl BodyCache {
fn get(&mut self, key: &BodyKey) -> Option<(Bytes, &'static str)> {
let i = self.entries.iter().position(|(k, _, _)| k == key)?;
let e = self.entries.remove(i)?;
let out = (e.1.clone(), e.2);
self.entries.push_back(e);
Some(out)
}
fn put(&mut self, key: BodyKey, body: &Bytes, content_type: &'static str) {
if body.len() > BODY_CACHE_BYTES {
return;
}
if let Some(i) = self.entries.iter().position(|(k, _, _)| *k == key) {
if let Some(old) = self.entries.remove(i) {
self.bytes -= old.1.len();
}
}
while self.bytes + body.len() > BODY_CACHE_BYTES {
match self.entries.pop_front() {
Some(old) => self.bytes -= old.1.len(),
None => break,
}
}
self.bytes += body.len();
self.entries.push_back((key, body.clone(), content_type));
}
}
fn open_args(t: &Target) -> Vec<String> {
t.cell.args.iter().filter(|(_, a)| matches!(a, Arg::Slice)).map(|(k, _)| k.clone()).collect()
}
fn key_of(m: &SliceValue, open: &[String]) -> Vec<Scalar> {
open.iter().filter_map(|k| m.cell.args.get(k).and_then(Arg::scalar).cloned()).collect()
}
fn cursor(key: &[Scalar]) -> String {
lexical::to_hex(&Value::Array(key.iter().map(Scalar::to_value).collect()).to_jcs())
}
fn parse_cursor(s: &str) -> Option<Vec<Scalar>> {
if !s.len().is_multiple_of(2) || s.len() > 1 << 16 {
return None;
}
let bytes: Option<Vec<u8>> =
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect();
let v = json::parse(&bytes?).ok()?;
let Value::Array(items) = v else { return None };
items.iter().map(|i| Scalar::from_json(&i.to_jcs()).ok()).collect()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Form {
#[default]
Json,
Arrow,
Csv,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct SliceQuery {
pub(crate) limit: Option<usize>,
pub(crate) after: Option<String>,
pub(crate) form: Form,
}
pub(crate) fn split_format(rest: &str) -> Result<(String, Option<Form>), ErrorCode> {
let Some((path, query)) = rest.split_once('?') else {
return Ok((rest.to_string(), None));
};
let mut form = None;
let mut kept = Vec::new();
for p in query.split('&') {
if let Some(v) = p.strip_prefix("format=") {
form = Some(match v {
"json" => Form::Json,
"arrow" => Form::Arrow,
"csv" => Form::Csv,
_ => return Err(ErrorCode::ParseUri),
});
} else {
kept.push(p);
}
}
if kept.is_empty() {
Ok((path.to_string(), form))
} else {
Ok((format!("{path}?{}", kept.join("&")), form))
}
}
pub(crate) fn csv_field(t: &str) -> String {
if t.contains([',', '"', '\r', '\n']) {
format!("\"{}\"", t.replace('"', "\"\""))
} else {
t.to_string()
}
}
pub(crate) fn split_query(rest: &str) -> Result<(String, SliceQuery), ErrorCode> {
let Some((path, query)) = rest.split_once('?') else {
return Ok((rest.to_string(), SliceQuery::default()));
};
let mut q = SliceQuery::default();
let mut kept = Vec::new();
for p in query.split('&') {
if let Some(v) = p.strip_prefix("limit=") {
q.limit = Some(v.parse().map_err(|_| ErrorCode::ParseUri)?);
} else if let Some(v) = p.strip_prefix("after=") {
q.after = Some(v.to_string());
} else {
kept.push(p);
}
}
if kept.is_empty() {
Ok((path.to_string(), q))
} else {
Ok((format!("{path}?{}", kept.join("&")), q))
}
}
fn sort_key_at(t: &Target, key: &[Scalar]) -> Option<Vec<u8>> {
let mut open = key.iter();
let mut parts: Vec<(String, String, String)> = Vec::new();
for (name, a) in &t.cell.args {
let s = match a {
Arg::Value(s) => s,
Arg::Slice => open.next()?,
};
parts.push((name.clone(), s.ty().as_str().to_string(), s.lexical().to_string()));
}
if open.next().is_some() {
return None;
}
let refs: Vec<(&str, &str, &str)> = parts.iter().map(|(n, t, v)| (n.as_str(), t.as_str(), v.as_str())).collect();
Some(datumesh_store::sort_key(&refs))
}
impl Inner {
fn page_of(
&self,
slice: &Slice,
a: &str,
after: Option<&[u8]>,
n: usize,
) -> Result<(Vec<SliceValue>, bool), ErrorCode> {
let read = if slice.is_version_slice() {
if after.is_some() {
return Err(ErrorCode::ParseUri);
}
self.store.slice_values_limit(slice, a, n + 1)
} else {
self.store.slice_page(slice, a, after, n + 1)
};
let mut m = read.map_err(|e| {
tracing::warn!(target: "datumesh_http", error = %e, "slice page");
ErrorCode::InputUnavailable
})?;
let more = m.len() > n;
m.truncate(n);
Ok((m, more))
}
pub(crate) fn slice(&self, rest: &str, now: &str, form: Form) -> Reply {
let (rest, mut q) = match split_query(rest) {
Ok(x) => x,
Err(c) => return envelope::bad_request_reply(c),
};
q.form = form;
let target = match crate::call::resolve(&rest, now, &self.config.aliases, self, true) {
Ok(t) => t,
Err(r) => return self.rejection(r, None),
};
if target.bound.descriptor.lang != "stored" {
return envelope::error_reply(ErrorCode::EvalUnavailable);
}
if self.foreign.is_foreign(&target.fn_name()) {
return envelope::error_reply(ErrorCode::InputUnavailable);
}
if self.config.policy.rule(&target.fn_name()).is_some() {
return Reply::json(403, envelope::unlicensed(), Cache::Private);
}
let a = target.asof().unwrap_or(now).to_string();
let slice = match Slice::from_value(&target.cell.to_value()) {
Ok(s) => s,
Err(e) => {
return envelope::bad_request_reply(if envelope::is_request_code(e.code()) {
e.code()
} else {
ErrorCode::ParseUri
})
}
};
let open = open_args(&target);
let cache = if target.asof().is_some_and(|x| x <= now) {
Cache::Immutable
} else {
Cache::Public(self.config.ttl.latest_max_age.as_secs())
};
let after = match &q.after {
None => None,
Some(c) => match parse_cursor(c) {
Some(k) if k.len() == open.len() => match sort_key_at(&target, &k) {
Some(sk) => Some(sk),
None => return envelope::bad_request_reply(ErrorCode::ParseUri),
},
_ => return envelope::bad_request_reply(ErrorCode::ParseUri),
},
};
let body_key: Option<BodyKey> = (target.asof().is_some_and(|x| x < now) && q.form != Form::Json)
.then(|| (format!("{:?}", q.form), slice.to_value().to_jcs(), a.clone(), q.limit, q.after.clone()));
if let Some(key) = &body_key {
let hit = self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).get(key);
if let Some((body, content_type)) = hit {
return Reply { status: 200, body, content_type, cache, canonical: None, retry_after: None };
}
}
if q.form == Form::Csv {
let (members, _) = match self.page_of(&slice, &a, after.as_deref(), self.config.slice_max) {
Ok(x) => x,
Err(c) => return envelope::error_reply(c),
};
let mut out = String::new();
let mut head: Vec<String> = open.clone();
head.extend(["value".to_string(), "tx".to_string()]);
out.push_str(&head.iter().map(|h| csv_field(h)).collect::<Vec<_>>().join(","));
out.push_str("\r\n");
for m in &members {
let mut cells: Vec<String> = open
.iter()
.map(|k| {
m.cell.args.get(k).and_then(Arg::scalar).map(|x| x.lexical().to_string()).unwrap_or_default()
})
.collect();
cells.push(m.value.lexical().to_string());
cells.push(m.version.tx.clone());
out.push_str(&cells.iter().map(|c| csv_field(c)).collect::<Vec<_>>().join(","));
out.push_str("\r\n");
}
let body: Bytes = out.into_bytes().into();
if let Some(key) = body_key {
self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).put(key, &body, CSV);
}
return Reply { status: 200, body, content_type: CSV, cache, canonical: None, retry_after: None };
}
if q.form == Form::Arrow {
let n = q.limit.unwrap_or(self.config.slice_max);
let (members, _) = match self.page_of(&slice, &a, after.as_deref(), n) {
Ok(x) => x,
Err(c) => return envelope::error_reply(c),
};
return match arrow_stream(&members, &open, &slice, &a, &target.fn_name()) {
Ok(body) => {
let body: Bytes = body.into();
if let Some(key) = body_key {
self.slice_bodies.lock().unwrap_or_else(|p| p.into_inner()).put(key, &body, ARROW);
}
Reply { status: 200, body, content_type: ARROW, cache, canonical: None, retry_after: None }
}
Err(e) => {
tracing::warn!(target: "datumesh_http", error = %e, "arrow");
envelope::error_reply(ErrorCode::EvalUnavailable)
}
};
}
let limit = q.limit.unwrap_or(self.config.slice_page).clamp(1, crate::config::MAX_SLICE_PAGE);
let (members, more) = match self.page_of(&slice, &a, after.as_deref(), limit) {
Ok(x) => x,
Err(c) => return envelope::error_reply(c),
};
let mut page = Vec::with_capacity(members.len());
for m in &members {
match self.receipt_info_by_hash(&m.version.receipt_hash) {
Some(info) => page.push(crate::envelope::with_fn_hash(
datumesh_core::Answer::ok(info.parsed.clone(), info.trust),
Some(&info.parsed.cell().fn_hash),
)),
None => return crate::envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(slice.fn_hash())),
}
}
let next = match members.last().filter(|_| more) {
Some(last) => {
let k = key_of(last, &open);
Some(format!(
"{}/slice/{}&limit={limit}&after={}",
self.config.origin(),
target.rest_asof(&a),
cursor(&k)
))
}
None => None,
};
let fn_hash = slice.fn_hash().to_string();
let answer = datumesh_core::Answer::page(datumesh_core::SlicePage::new(slice, page, next));
crate::envelope::answer_reply(&crate::envelope::with_fn_hash(answer, Some(&fn_hash)), cache)
}
}
pub(crate) fn arrow_stream(
members: &[SliceValue],
open: &[String],
slice: &Slice,
asof: &str,
function: &str,
) -> Result<Vec<u8>, String> {
let mut fields: Vec<Field> = open.iter().map(|k| Field::new(k, DataType::Utf8, false)).collect();
for c in ["value", "type", "receipt", "tx", "asof"] {
fields.push(Field::new(c, DataType::Utf8, false));
}
let metadata = [
("slice_id".to_string(), slice.id().to_string()),
("asof".to_string(), asof.to_string()),
("function".to_string(), function.to_string()),
]
.into_iter()
.collect();
let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
let mut out = Vec::new();
{
let mut w = arrow_ipc::writer::StreamWriter::try_new(&mut out, &schema).map_err(|e| e.to_string())?;
for chunk in members.chunks(65_536) {
let mut cols: Vec<ArrayRef> = Vec::new();
for k in open {
let a: StringArray = chunk
.iter()
.map(|m| Some(m.cell.args.get(k).and_then(Arg::scalar).map(Scalar::lexical).unwrap_or_default()))
.collect();
cols.push(Arc::new(a));
}
let v: StringArray = chunk.iter().map(|m| Some(m.value.lexical())).collect();
let t: StringArray = chunk.iter().map(|m| Some(m.value.ty().as_str())).collect();
let r: StringArray = chunk.iter().map(|m| Some(m.version.receipt_hash.as_str())).collect();
let tx: StringArray = chunk.iter().map(|m| Some(m.version.tx.as_str())).collect();
let at: StringArray = chunk.iter().map(|m| Some(m.version.asof.as_str())).collect();
for a in [v, t, r, tx, at] {
cols.push(Arc::new(a));
}
let batch = RecordBatch::try_new(schema.clone(), cols).map_err(|e| e.to_string())?;
w.write(&batch).map_err(|e| e.to_string())?;
}
w.finish().map_err(|e| e.to_string())?;
}
Ok(out)
}