use std::collections::BTreeMap;
use datumesh_core::json;
use datumesh_core::lexical::{check_function_name, check_hex, check_name};
use datumesh_core::{Error as CoreError, ErrorCode};
use crate::error::{Error, Result};
pub const FIND_MISSES_CAP: usize = 100_000;
pub(crate) const MISS_BYTES: usize = 512;
pub(crate) const EMBED_DIM: usize = 384;
pub(crate) const SUMMARY_VALUES: usize = 50;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CatalogKind {
Class,
Method,
Function,
}
impl CatalogKind {
pub fn as_str(self) -> &'static str {
match self {
CatalogKind::Class => "class",
CatalogKind::Method => "method",
CatalogKind::Function => "function",
}
}
pub(crate) fn parse(s: &str) -> Option<CatalogKind> {
Some(match s {
"class" => CatalogKind::Class,
"method" => CatalogKind::Method,
"function" => CatalogKind::Function,
_ => return None,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CatalogSource {
Publisher,
Operator,
}
impl CatalogSource {
pub fn as_str(self) -> &'static str {
match self {
CatalogSource::Publisher => "publisher",
CatalogSource::Operator => "operator",
}
}
pub(crate) fn parse(s: &str) -> Option<CatalogSource> {
Some(match s {
"publisher" => CatalogSource::Publisher,
"operator" => CatalogSource::Operator,
_ => return None,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CatalogEntry {
pub kind: CatalogKind,
pub name: String,
pub hash: Option<String>,
pub label: String,
pub description: String,
pub args: BTreeMap<String, String>,
pub examples: String,
pub source: CatalogSource,
pub signed_by: Option<String>,
}
pub type Facets = BTreeMap<String, Vec<String>>;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CatalogEntryExt {
pub entry: CatalogEntry,
pub facets: Facets,
pub extends: Option<String>,
pub source_name: Option<String>,
}
impl CatalogEntryExt {
pub fn new(entry: CatalogEntry) -> CatalogEntryExt {
CatalogEntryExt { entry, facets: Facets::new(), extends: None, source_name: None }
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FacetedEntry {
pub kind: CatalogKind,
pub name: String,
pub hash: Option<String>,
pub facets: Facets,
pub first_bound: Option<String>,
pub source_name: Option<String>,
}
pub(crate) const FACET_KEYS: &[&str] = &["domain", "frequency", "measure", "region", "thing"];
pub(crate) const FACET_MAX: usize = 8;
pub(crate) struct CatalogRow<'a> {
pub(crate) entry: &'a CatalogEntry,
pub(crate) facets: String,
pub(crate) extends: Option<&'a str>,
pub(crate) source_name: Option<&'a str>,
}
impl<'a> CatalogRow<'a> {
pub(crate) fn plain(entry: &'a CatalogEntry) -> Self {
CatalogRow { entry, facets: "{}".to_string(), extends: None, source_name: None }
}
pub(crate) fn ext(e: &'a CatalogEntryExt) -> Self {
CatalogRow {
entry: &e.entry,
facets: facets_json(&e.facets),
extends: e.extends.as_deref(),
source_name: e.source_name.as_deref(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeyValue {
pub value: String,
pub label: String,
pub aliases: Vec<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EmbedRef {
Entry,
Value,
}
impl EmbedRef {
pub fn as_str(self) -> &'static str {
match self {
EmbedRef::Entry => "entry",
EmbedRef::Value => "value",
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Embedding {
pub ref_kind: EmbedRef,
pub ref_id: i64,
pub vec: Vec<f32>,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingEmbedding {
pub ref_kind: EmbedRef,
pub ref_id: i64,
pub text: String,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub enum Hit {
Entry {
id: i64,
entry: CatalogEntry,
score: f64,
},
Value {
id: i64,
owner: String,
key: String,
value: String,
label: String,
aliases: Vec<String>,
score: f64,
},
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Summary {
pub entries: Vec<SummaryEntry>,
pub dictionaries: Vec<Dictionary>,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SummaryEntry {
pub kind: CatalogKind,
pub name: String,
pub label: String,
pub n_cells: i64,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Dictionary {
pub owner: String,
pub key: String,
pub n_values: i64,
pub values: Vec<DictionaryValue>,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DictionaryValue {
pub value: String,
pub label: String,
pub n_cells: i64,
}
pub(crate) fn invalid(path: &str, detail: impl Into<String>) -> Error {
Error::Invalid(CoreError::new(ErrorCode::Schema, path, detail))
}
pub(crate) fn check_catalog_entry(e: &CatalogEntry) -> Result<()> {
check_function_name(&e.name, "name")?;
if let Some(h) = &e.hash {
check_hex(h, 64, "hash")?;
}
if e.label.len() > 120 {
return Err(invalid("label", "a label has at most 120 bytes"));
}
if e.description.is_empty() || e.description.len() > 1024 {
return Err(invalid("description", "a description has 1 to 1024 bytes"));
}
for (k, v) in &e.args {
check_name(k, "args")?;
if v.len() > 1024 {
return Err(invalid("args", "an argument's text has at most 1024 bytes"));
}
}
if args_json(&e.args).len() > 65536 {
return Err(invalid("args", "the arguments have at most 65536 bytes of JSON"));
}
let examples = canonical_examples(&e.examples)?;
if examples.len() > 65536 {
return Err(invalid("examples", "the examples have at most 65536 bytes of JSON"));
}
if let Some(s) = &e.signed_by {
if s.is_empty() || s.len() > 256 {
return Err(invalid("signed_by", "a key reference has 1 to 256 bytes"));
}
}
Ok(())
}
pub(crate) fn check_catalog_ext(e: &CatalogEntryExt) -> Result<()> {
check_catalog_entry(&e.entry)?;
check_facets(&e.facets)?;
check_extends(e.entry.kind, e.extends.as_deref())
}
pub(crate) fn check_facets(f: &Facets) -> Result<()> {
for (k, names) in f {
if !FACET_KEYS.contains(&k.as_str()) {
return Err(invalid("facets", format!("{k:?} is not a facet key")));
}
if names.is_empty() || names.len() > FACET_MAX {
return Err(invalid("facets", "a facet has 1 to 8 names"));
}
for n in names {
check_name(n, "facets")?;
if n.len() > 32 {
return Err(invalid("facets", "a facet name has at most 32 bytes"));
}
}
if names.windows(2).any(|w| w[0] >= w[1]) {
return Err(invalid("facets", "the names of a facet are ascending and unique"));
}
}
Ok(())
}
pub(crate) fn check_extends(kind: CatalogKind, extends: Option<&str>) -> Result<()> {
let Some(class) = extends else { return Ok(()) };
check_function_name(class, "extends")?;
if kind != CatalogKind::Function {
return Err(invalid("extends", "only a function extends a class"));
}
Ok(())
}
pub(crate) fn check_key_values(owner: &str, key: &str, values: &[KeyValue]) -> Result<()> {
check_function_name(owner, "owner")?;
check_name(key, "key")?;
for v in values {
if v.value.is_empty() || v.value.len() > 1024 {
return Err(invalid("value", "a value has 1 to 1024 bytes"));
}
if v.label.len() > 120 {
return Err(invalid("label", "a label has at most 120 bytes"));
}
for a in &v.aliases {
if a.is_empty() || a.len() > 120 {
return Err(invalid("aliases", "an alias has 1 to 120 bytes"));
}
}
}
Ok(())
}
pub(crate) fn check_model(model: &str) -> Result<()> {
if model.is_empty() || model.len() > 200 {
return Err(invalid("model", "a model name has 1 to 200 bytes"));
}
Ok(())
}
pub(crate) fn vector_literal(v: &[f32]) -> Result<String> {
if v.len() != EMBED_DIM {
return Err(invalid("vec", format!("a vector has {EMBED_DIM} values, not {}", v.len())));
}
if v.iter().any(|x| !x.is_finite()) {
return Err(invalid("vec", "a vector's values are finite"));
}
if v.iter().all(|x| *x == 0.0) {
return Err(invalid("vec", "a vector is not all zero"));
}
let parts: Vec<String> = v.iter().map(|x| x.to_string()).collect();
Ok(format!("[{}]", parts.join(",")))
}
pub(crate) fn miss_text(query: &str) -> Option<&str> {
let q = query.trim();
if q.is_empty() {
return None;
}
let mut end = 0;
for (i, c) in q.char_indices() {
if i + c.len_utf8() > MISS_BYTES {
break;
}
end = i + c.len_utf8();
}
Some(&q[..end])
}
pub(crate) fn args_json(args: &BTreeMap<String, String>) -> String {
let members: Vec<(String, json::Value)> =
args.iter().map(|(k, v)| (k.clone(), json::Value::String(v.clone()))).collect();
String::from_utf8(json::Value::Object(members).to_jcs()).unwrap_or_default()
}
pub(crate) fn parse_args(text: &str) -> Result<BTreeMap<String, String>> {
let v = json::parse(text.as_bytes())?;
let members = v.as_object().ok_or_else(|| invalid("args", "stored arguments are not an object"))?;
let mut out = BTreeMap::new();
for (k, v) in members {
let s = v.as_str().ok_or_else(|| invalid("args", "stored argument text is not a string"))?;
out.insert(k.clone(), s.to_string());
}
Ok(out)
}
pub(crate) fn facets_json(f: &Facets) -> String {
let members: Vec<(String, json::Value)> = f
.iter()
.map(|(k, names)| {
let items = names.iter().map(|n| json::Value::String(n.clone())).collect();
(k.clone(), json::Value::Array(items))
})
.collect();
String::from_utf8(json::Value::Object(members).to_jcs()).unwrap_or_default()
}
pub(crate) fn parse_facets(text: &str) -> Result<Facets> {
let corrupt = || invalid("facets", "a stored entry has bad facets");
let v = json::parse(text.as_bytes())?;
let members = v.as_object().ok_or_else(corrupt)?;
let mut out = Facets::new();
for (k, v) in members {
let items = match v {
json::Value::Array(items) => items,
_ => return Err(corrupt()),
};
let names =
items.iter().map(|i| i.as_str().map(str::to_string).ok_or_else(corrupt)).collect::<Result<Vec<_>>>()?;
out.insert(k.clone(), names);
}
Ok(out)
}
pub(crate) fn entry_ext(
entry: CatalogEntry,
facets: &str,
extends: Option<String>,
source_name: Option<String>,
) -> Result<CatalogEntryExt> {
Ok(CatalogEntryExt { entry, facets: parse_facets(facets)?, extends, source_name })
}
pub(crate) fn canonical_examples(text: &str) -> Result<String> {
let v = json::parse(text.as_bytes())?;
if !matches!(v, json::Value::Array(_)) {
return Err(invalid("examples", "examples are a JSON array"));
}
Ok(String::from_utf8(v.to_jcs()).unwrap_or_default())
}
#[cfg(feature = "sqlite")]
pub(crate) fn aliases_json(aliases: &[String]) -> String {
let items: Vec<json::Value> = aliases.iter().map(|a| json::Value::String(a.clone())).collect();
String::from_utf8(json::Value::Array(items).to_jcs()).unwrap_or_default()
}
#[cfg(feature = "sqlite")]
pub(crate) fn parse_aliases(text: &str) -> Result<Vec<String>> {
let v = json::parse(text.as_bytes())?;
let items = match &v {
json::Value::Array(items) => items,
_ => return Err(invalid("aliases", "stored aliases are not an array")),
};
items
.iter()
.map(|i| i.as_str().map(str::to_string).ok_or_else(|| invalid("aliases", "a stored alias is not a string")))
.collect()
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn entry_from_columns(
kind: &str,
name: String,
hash: Option<String>,
label: String,
description: String,
args: &str,
examples: &str,
source: &str,
signed_by: Option<String>,
) -> Result<CatalogEntry> {
let corrupt = |what: &str| invalid("catalog", format!("a stored entry has a bad {what}"));
Ok(CatalogEntry {
kind: CatalogKind::parse(kind).ok_or_else(|| corrupt("kind"))?,
name,
hash,
label,
description,
args: parse_args(args)?,
examples: examples.to_string(),
source: CatalogSource::parse(source).ok_or_else(|| corrupt("source"))?,
signed_by,
})
}
pub(crate) fn entry_text(label: &str, description: &str) -> String {
if label.is_empty() {
description.to_string()
} else {
format!("{label}. {description}")
}
}
pub(crate) fn value_text(label: &str, value: &str) -> String {
if label.is_empty() {
value.to_string()
} else {
label.to_string()
}
}
pub(crate) struct Words {
words: Vec<String>,
}
impl Words {
pub(crate) fn new(query: &str) -> Option<Words> {
let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
if words.is_empty() {
None
} else {
Some(Words { words })
}
}
pub(crate) fn pattern(&self, i: usize, sql_exact: impl Fn(&str) -> bool) -> Option<String> {
let w = &self.words[i];
if !sql_exact(w) {
return None;
}
let mut escaped = String::with_capacity(w.len() + 2);
escaped.push('%');
for c in w.chars() {
if matches!(c, '!' | '%' | '_') {
escaped.push('!');
}
escaped.push(c);
}
escaped.push('%');
Some(escaped)
}
pub(crate) fn len(&self) -> usize {
self.words.len()
}
pub(crate) fn words(&self) -> &[String] {
&self.words
}
#[cfg(feature = "sqlite")]
pub(crate) fn total(&self, fields: &[&str]) -> Option<u32> {
let fields: Vec<String> = fields.iter().map(|f| f.to_lowercase()).collect();
let mut total = 0;
for w in &self.words {
let best = fields.iter().map(|f| field_score(f, w)).max().unwrap_or(0);
if best == 0 {
return None;
}
total += best;
}
Some(total)
}
pub(crate) fn score_of(&self, total: u32) -> f64 {
f64::from(total) / (10.0 * self.words.len() as f64)
}
}
#[cfg(feature = "sqlite")]
pub(crate) fn field_score(field: &str, word: &str) -> u32 {
if field == word {
10
} else if field.split(|c: char| !c.is_alphanumeric()).any(|p| p == word) {
8
} else if field.contains(word) {
5
} else {
0
}
}
pub(crate) fn rank(mut hits: Vec<Hit>, limit: usize) -> Vec<Hit> {
fn key(h: &Hit) -> String {
match h {
Hit::Entry { entry, .. } => entry.name.clone(),
Hit::Value { owner, key, value, .. } => format!("{owner}\u{1}{key}\u{1}{value}"),
}
}
fn score(h: &Hit) -> f64 {
match h {
Hit::Entry { score, .. } | Hit::Value { score, .. } => *score,
}
}
hits.sort_by(|a, b| {
score(b).partial_cmp(&score(a)).unwrap_or(std::cmp::Ordering::Equal).then_with(|| key(a).cmp(&key(b)))
});
hits.truncate(limit);
hits
}
pub(crate) fn as_i64(n: usize) -> i64 {
i64::try_from(n).unwrap_or(i64::MAX)
}