1use std::collections::BTreeMap;
16
17use datumesh_core::json;
18use datumesh_core::lexical::{check_function_name, check_hex, check_name};
19use datumesh_core::{Error as CoreError, ErrorCode};
20
21use crate::error::{Error, Result};
22
23pub const FIND_MISSES_CAP: usize = 100_000;
25
26pub(crate) const MISS_BYTES: usize = 512;
28
29pub(crate) const EMBED_DIM: usize = 384;
31
32pub(crate) const SUMMARY_VALUES: usize = 50;
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum CatalogKind {
38 Class,
40 Method,
42 Function,
44}
45
46impl CatalogKind {
47 pub fn as_str(self) -> &'static str {
49 match self {
50 CatalogKind::Class => "class",
51 CatalogKind::Method => "method",
52 CatalogKind::Function => "function",
53 }
54 }
55
56 pub(crate) fn parse(s: &str) -> Option<CatalogKind> {
57 Some(match s {
58 "class" => CatalogKind::Class,
59 "method" => CatalogKind::Method,
60 "function" => CatalogKind::Function,
61 _ => return None,
62 })
63 }
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69pub enum CatalogSource {
70 Publisher,
72 Operator,
74}
75
76impl CatalogSource {
77 pub fn as_str(self) -> &'static str {
79 match self {
80 CatalogSource::Publisher => "publisher",
81 CatalogSource::Operator => "operator",
82 }
83 }
84
85 pub(crate) fn parse(s: &str) -> Option<CatalogSource> {
86 Some(match s {
87 "publisher" => CatalogSource::Publisher,
88 "operator" => CatalogSource::Operator,
89 _ => return None,
90 })
91 }
92}
93
94#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct CatalogEntry {
100 pub kind: CatalogKind,
102 pub name: String,
104 pub hash: Option<String>,
106 pub label: String,
108 pub description: String,
110 pub args: BTreeMap<String, String>,
112 pub examples: String,
114 pub source: CatalogSource,
116 pub signed_by: Option<String>,
118}
119
120#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct KeyValue {
123 pub value: String,
125 pub label: String,
127 pub aliases: Vec<String>,
129}
130
131#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
133pub enum EmbedRef {
134 Entry,
136 Value,
138}
139
140impl EmbedRef {
141 pub fn as_str(self) -> &'static str {
143 match self {
144 EmbedRef::Entry => "entry",
145 EmbedRef::Value => "value",
146 }
147 }
148}
149
150#[derive(Clone, Debug, PartialEq)]
152pub struct Embedding {
153 pub ref_kind: EmbedRef,
155 pub ref_id: i64,
157 pub vec: Vec<f32>,
159}
160
161#[non_exhaustive]
163#[derive(Clone, Debug, PartialEq, Eq)]
164pub struct PendingEmbedding {
165 pub ref_kind: EmbedRef,
167 pub ref_id: i64,
169 pub text: String,
172}
173
174#[non_exhaustive]
176#[derive(Clone, Debug, PartialEq)]
177pub enum Hit {
178 Entry {
180 id: i64,
182 entry: CatalogEntry,
184 score: f64,
186 },
187 Value {
189 id: i64,
191 owner: String,
193 key: String,
195 value: String,
197 label: String,
199 aliases: Vec<String>,
201 score: f64,
203 },
204}
205
206#[non_exhaustive]
208#[derive(Clone, Debug, PartialEq, Eq)]
209pub struct Summary {
210 pub entries: Vec<SummaryEntry>,
212 pub dictionaries: Vec<Dictionary>,
214}
215
216#[non_exhaustive]
218#[derive(Clone, Debug, PartialEq, Eq)]
219pub struct SummaryEntry {
220 pub kind: CatalogKind,
222 pub name: String,
224 pub label: String,
226 pub n_cells: i64,
228}
229
230#[non_exhaustive]
232#[derive(Clone, Debug, PartialEq, Eq)]
233pub struct Dictionary {
234 pub owner: String,
236 pub key: String,
238 pub n_values: i64,
240 pub values: Vec<DictionaryValue>,
242}
243
244#[non_exhaustive]
246#[derive(Clone, Debug, PartialEq, Eq)]
247pub struct DictionaryValue {
248 pub value: String,
250 pub label: String,
252 pub n_cells: i64,
255}
256
257pub(crate) fn invalid(path: &str, detail: impl Into<String>) -> Error {
260 Error::Invalid(CoreError::new(ErrorCode::Schema, path, detail))
261}
262
263pub(crate) fn check_catalog_entry(e: &CatalogEntry) -> Result<()> {
265 check_function_name(&e.name, "name")?;
266 if let Some(h) = &e.hash {
267 check_hex(h, 64, "hash")?;
268 }
269 if e.label.len() > 120 {
270 return Err(invalid("label", "a label has at most 120 bytes"));
271 }
272 if e.description.is_empty() || e.description.len() > 1024 {
273 return Err(invalid("description", "a description has 1 to 1024 bytes"));
274 }
275 for (k, v) in &e.args {
276 check_name(k, "args")?;
277 if v.len() > 1024 {
278 return Err(invalid("args", "an argument's text has at most 1024 bytes"));
279 }
280 }
281 if args_json(&e.args).len() > 65536 {
282 return Err(invalid("args", "the arguments have at most 65536 bytes of JSON"));
283 }
284 let examples = canonical_examples(&e.examples)?;
285 if examples.len() > 65536 {
286 return Err(invalid("examples", "the examples have at most 65536 bytes of JSON"));
287 }
288 if let Some(s) = &e.signed_by {
289 if s.is_empty() || s.len() > 256 {
290 return Err(invalid("signed_by", "a key reference has 1 to 256 bytes"));
291 }
292 }
293 Ok(())
294}
295
296pub(crate) fn check_key_values(owner: &str, key: &str, values: &[KeyValue]) -> Result<()> {
298 check_function_name(owner, "owner")?;
299 check_name(key, "key")?;
300 for v in values {
301 if v.value.is_empty() || v.value.len() > 1024 {
302 return Err(invalid("value", "a value has 1 to 1024 bytes"));
303 }
304 if v.label.len() > 120 {
305 return Err(invalid("label", "a label has at most 120 bytes"));
306 }
307 for a in &v.aliases {
308 if a.is_empty() || a.len() > 120 {
309 return Err(invalid("aliases", "an alias has 1 to 120 bytes"));
310 }
311 }
312 }
313 Ok(())
314}
315
316pub(crate) fn check_model(model: &str) -> Result<()> {
317 if model.is_empty() || model.len() > 200 {
318 return Err(invalid("model", "a model name has 1 to 200 bytes"));
319 }
320 Ok(())
321}
322
323pub(crate) fn vector_literal(v: &[f32]) -> Result<String> {
325 if v.len() != EMBED_DIM {
326 return Err(invalid("vec", format!("a vector has {EMBED_DIM} values, not {}", v.len())));
327 }
328 if v.iter().any(|x| !x.is_finite()) {
329 return Err(invalid("vec", "a vector's values are finite"));
330 }
331 if v.iter().all(|x| *x == 0.0) {
332 return Err(invalid("vec", "a vector is not all zero"));
333 }
334 let parts: Vec<String> = v.iter().map(|x| x.to_string()).collect();
335 Ok(format!("[{}]", parts.join(",")))
336}
337
338pub(crate) fn miss_text(query: &str) -> Option<&str> {
341 let q = query.trim();
342 if q.is_empty() {
343 return None;
344 }
345 let mut end = 0;
346 for (i, c) in q.char_indices() {
347 if i + c.len_utf8() > MISS_BYTES {
348 break;
349 }
350 end = i + c.len_utf8();
351 }
352 Some(&q[..end])
353}
354
355pub(crate) fn args_json(args: &BTreeMap<String, String>) -> String {
359 let members: Vec<(String, json::Value)> =
360 args.iter().map(|(k, v)| (k.clone(), json::Value::String(v.clone()))).collect();
361 String::from_utf8(json::Value::Object(members).to_jcs()).unwrap_or_default()
362}
363
364pub(crate) fn parse_args(text: &str) -> Result<BTreeMap<String, String>> {
366 let v = json::parse(text.as_bytes())?;
367 let members = v.as_object().ok_or_else(|| invalid("args", "stored arguments are not an object"))?;
368 let mut out = BTreeMap::new();
369 for (k, v) in members {
370 let s = v.as_str().ok_or_else(|| invalid("args", "stored argument text is not a string"))?;
371 out.insert(k.clone(), s.to_string());
372 }
373 Ok(out)
374}
375
376pub(crate) fn canonical_examples(text: &str) -> Result<String> {
378 let v = json::parse(text.as_bytes())?;
379 if !matches!(v, json::Value::Array(_)) {
380 return Err(invalid("examples", "examples are a JSON array"));
381 }
382 Ok(String::from_utf8(v.to_jcs()).unwrap_or_default())
383}
384
385#[cfg(feature = "sqlite")]
387pub(crate) fn aliases_json(aliases: &[String]) -> String {
388 let items: Vec<json::Value> = aliases.iter().map(|a| json::Value::String(a.clone())).collect();
389 String::from_utf8(json::Value::Array(items).to_jcs()).unwrap_or_default()
390}
391
392#[cfg(feature = "sqlite")]
394pub(crate) fn parse_aliases(text: &str) -> Result<Vec<String>> {
395 let v = json::parse(text.as_bytes())?;
396 let items = match &v {
397 json::Value::Array(items) => items,
398 _ => return Err(invalid("aliases", "stored aliases are not an array")),
399 };
400 items
401 .iter()
402 .map(|i| i.as_str().map(str::to_string).ok_or_else(|| invalid("aliases", "a stored alias is not a string")))
403 .collect()
404}
405
406#[allow(clippy::too_many_arguments)]
408pub(crate) fn entry_from_columns(
409 kind: &str,
410 name: String,
411 hash: Option<String>,
412 label: String,
413 description: String,
414 args: &str,
415 examples: &str,
416 source: &str,
417 signed_by: Option<String>,
418) -> Result<CatalogEntry> {
419 let corrupt = |what: &str| invalid("catalog", format!("a stored entry has a bad {what}"));
420 Ok(CatalogEntry {
421 kind: CatalogKind::parse(kind).ok_or_else(|| corrupt("kind"))?,
422 name,
423 hash,
424 label,
425 description,
426 args: parse_args(args)?,
427 examples: examples.to_string(),
428 source: CatalogSource::parse(source).ok_or_else(|| corrupt("source"))?,
429 signed_by,
430 })
431}
432
433pub(crate) fn entry_text(label: &str, description: &str) -> String {
437 if label.is_empty() {
438 description.to_string()
439 } else {
440 format!("{label}. {description}")
441 }
442}
443
444pub(crate) fn value_text(label: &str, value: &str) -> String {
446 if label.is_empty() {
447 value.to_string()
448 } else {
449 label.to_string()
450 }
451}
452
453pub(crate) struct Words {
458 words: Vec<String>,
459}
460
461impl Words {
462 pub(crate) fn new(query: &str) -> Option<Words> {
463 let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
464 if words.is_empty() {
465 None
466 } else {
467 Some(Words { words })
468 }
469 }
470
471 pub(crate) fn pattern(&self, i: usize, sql_exact: impl Fn(&str) -> bool) -> Option<String> {
476 let w = &self.words[i];
477 if !sql_exact(w) {
478 return None;
479 }
480 let mut escaped = String::with_capacity(w.len() + 2);
481 escaped.push('%');
482 for c in w.chars() {
483 if matches!(c, '!' | '%' | '_') {
484 escaped.push('!');
485 }
486 escaped.push(c);
487 }
488 escaped.push('%');
489 Some(escaped)
490 }
491
492 pub(crate) fn len(&self) -> usize {
493 self.words.len()
494 }
495
496 pub(crate) fn score(&self, fields: &[&str]) -> Option<f64> {
498 let fields: Vec<String> = fields.iter().map(|f| f.to_lowercase()).collect();
499 let mut total = 0.0;
500 for w in &self.words {
501 let best = fields.iter().map(|f| field_score(f, w)).fold(0.0_f64, f64::max);
502 if best == 0.0 {
503 return None;
504 }
505 total += best;
506 }
507 Some(total / self.words.len() as f64)
508 }
509}
510
511fn field_score(field: &str, word: &str) -> f64 {
514 if field == word {
515 1.0
516 } else if field.split(|c: char| !c.is_alphanumeric()).any(|p| p == word) {
517 0.8
518 } else if field.contains(word) {
519 0.5
520 } else {
521 0.0
522 }
523}
524
525pub(crate) fn entry_fields(e: &CatalogEntry) -> Vec<&str> {
527 let mut f = vec![e.name.as_str(), e.label.as_str(), e.description.as_str()];
528 for (k, v) in &e.args {
529 f.push(k);
530 f.push(v);
531 }
532 f
533}
534
535pub(crate) fn rank(mut hits: Vec<Hit>, limit: usize) -> Vec<Hit> {
538 fn key(h: &Hit) -> String {
539 match h {
540 Hit::Entry { entry, .. } => entry.name.clone(),
541 Hit::Value { owner, key, value, .. } => format!("{owner}\u{1}{key}\u{1}{value}"),
542 }
543 }
544 fn score(h: &Hit) -> f64 {
545 match h {
546 Hit::Entry { score, .. } | Hit::Value { score, .. } => *score,
547 }
548 }
549 hits.sort_by(|a, b| {
550 score(b).partial_cmp(&score(a)).unwrap_or(std::cmp::Ordering::Equal).then_with(|| key(a).cmp(&key(b)))
551 });
552 hits.truncate(limit);
553 hits
554}
555
556pub(crate) fn as_i64(n: usize) -> i64 {
558 i64::try_from(n).unwrap_or(i64::MAX)
559}