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 Listed,
78}
79
80impl CatalogSource {
81 pub fn as_str(self) -> &'static str {
83 match self {
84 CatalogSource::Publisher => "publisher",
85 CatalogSource::Operator => "operator",
86 CatalogSource::Listed => "listed",
87 }
88 }
89
90 pub(crate) fn parse(s: &str) -> Option<CatalogSource> {
91 Some(match s {
92 "publisher" => CatalogSource::Publisher,
93 "operator" => CatalogSource::Operator,
94 "listed" => CatalogSource::Listed,
95 _ => return None,
96 })
97 }
98}
99
100#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct CatalogEntry {
106 pub kind: CatalogKind,
108 pub name: String,
110 pub hash: Option<String>,
112 pub label: String,
114 pub description: String,
116 pub args: BTreeMap<String, String>,
118 pub examples: String,
120 pub source: CatalogSource,
122 pub signed_by: Option<String>,
124}
125
126pub type Facets = BTreeMap<String, Vec<String>>;
129
130#[non_exhaustive]
136#[derive(Clone, Debug, PartialEq, Eq)]
137pub struct CatalogEntryExt {
138 pub entry: CatalogEntry,
140 pub facets: Facets,
142 pub extends: Option<String>,
144 pub source_name: Option<String>,
146}
147
148impl CatalogEntryExt {
149 pub fn new(entry: CatalogEntry) -> CatalogEntryExt {
151 CatalogEntryExt { entry, facets: Facets::new(), extends: None, source_name: None }
152 }
153}
154
155#[non_exhaustive]
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub struct FacetedEntry {
160 pub kind: CatalogKind,
162 pub name: String,
164 pub hash: Option<String>,
166 pub facets: Facets,
168 pub first_bound: Option<String>,
171 pub source_name: Option<String>,
173}
174
175pub(crate) const FACET_KEYS: &[&str] = &["domain", "frequency", "measure", "region", "thing"];
177
178pub(crate) const FACET_MAX: usize = 8;
180
181pub(crate) struct CatalogRow<'a> {
183 pub(crate) entry: &'a CatalogEntry,
184 pub(crate) facets: String,
185 pub(crate) extends: Option<&'a str>,
186 pub(crate) source_name: Option<&'a str>,
187}
188
189impl<'a> CatalogRow<'a> {
190 pub(crate) fn plain(entry: &'a CatalogEntry) -> Self {
192 CatalogRow { entry, facets: "{}".to_string(), extends: None, source_name: None }
193 }
194
195 pub(crate) fn ext(e: &'a CatalogEntryExt) -> Self {
197 CatalogRow {
198 entry: &e.entry,
199 facets: facets_json(&e.facets),
200 extends: e.extends.as_deref(),
201 source_name: e.source_name.as_deref(),
202 }
203 }
204}
205
206#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct KeyValue {
209 pub value: String,
211 pub label: String,
213 pub aliases: Vec<String>,
215}
216
217#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
219pub enum EmbedRef {
220 Entry,
222 Value,
224}
225
226impl EmbedRef {
227 pub fn as_str(self) -> &'static str {
229 match self {
230 EmbedRef::Entry => "entry",
231 EmbedRef::Value => "value",
232 }
233 }
234}
235
236#[derive(Clone, Debug, PartialEq)]
238pub struct Embedding {
239 pub ref_kind: EmbedRef,
241 pub ref_id: i64,
243 pub vec: Vec<f32>,
245}
246
247#[non_exhaustive]
249#[derive(Clone, Debug, PartialEq, Eq)]
250pub struct PendingEmbedding {
251 pub ref_kind: EmbedRef,
253 pub ref_id: i64,
255 pub text: String,
258}
259
260#[non_exhaustive]
262#[derive(Clone, Debug, PartialEq)]
263pub enum Hit {
264 Entry {
266 id: i64,
268 entry: CatalogEntry,
270 score: f64,
272 },
273 Value {
275 id: i64,
277 owner: String,
279 key: String,
281 value: String,
283 label: String,
285 aliases: Vec<String>,
287 score: f64,
289 },
290}
291
292#[non_exhaustive]
294#[derive(Clone, Debug, PartialEq, Eq)]
295pub struct Summary {
296 pub entries: Vec<SummaryEntry>,
298 pub dictionaries: Vec<Dictionary>,
300}
301
302#[non_exhaustive]
304#[derive(Clone, Debug, PartialEq, Eq)]
305pub struct SummaryEntry {
306 pub kind: CatalogKind,
308 pub name: String,
310 pub label: String,
312 pub n_cells: i64,
314}
315
316#[non_exhaustive]
318#[derive(Clone, Debug, PartialEq, Eq)]
319pub struct Dictionary {
320 pub owner: String,
322 pub key: String,
324 pub n_values: i64,
326 pub values: Vec<DictionaryValue>,
328}
329
330#[non_exhaustive]
332#[derive(Clone, Debug, PartialEq, Eq)]
333pub struct DictionaryValue {
334 pub value: String,
336 pub label: String,
338 pub n_cells: i64,
341}
342
343pub(crate) fn invalid(path: &str, detail: impl Into<String>) -> Error {
346 Error::Invalid(CoreError::new(ErrorCode::Schema, path, detail))
347}
348
349pub(crate) fn check_catalog_entry(e: &CatalogEntry) -> Result<()> {
351 check_function_name(&e.name, "name")?;
352 if let Some(h) = &e.hash {
353 check_hex(h, 64, "hash")?;
354 }
355 if e.label.len() > 120 {
356 return Err(invalid("label", "a label has at most 120 bytes"));
357 }
358 if e.description.is_empty() || e.description.len() > 1024 {
359 return Err(invalid("description", "a description has 1 to 1024 bytes"));
360 }
361 for (k, v) in &e.args {
362 check_name(k, "args")?;
363 if v.len() > 1024 {
364 return Err(invalid("args", "an argument's text has at most 1024 bytes"));
365 }
366 }
367 if args_json(&e.args).len() > 65536 {
368 return Err(invalid("args", "the arguments have at most 65536 bytes of JSON"));
369 }
370 let examples = canonical_examples(&e.examples)?;
371 if examples.len() > 65536 {
372 return Err(invalid("examples", "the examples have at most 65536 bytes of JSON"));
373 }
374 if let Some(s) = &e.signed_by {
375 if s.is_empty() || s.len() > 256 {
376 return Err(invalid("signed_by", "a key reference has 1 to 256 bytes"));
377 }
378 }
379 Ok(())
380}
381
382pub(crate) fn check_catalog_ext(e: &CatalogEntryExt) -> Result<()> {
385 check_catalog_entry(&e.entry)?;
386 check_facets(&e.facets)?;
387 check_extends(e.entry.kind, e.extends.as_deref())
388}
389
390pub(crate) fn check_facets(f: &Facets) -> Result<()> {
393 for (k, names) in f {
394 if !FACET_KEYS.contains(&k.as_str()) {
395 return Err(invalid("facets", format!("{k:?} is not a facet key")));
396 }
397 if names.is_empty() || names.len() > FACET_MAX {
398 return Err(invalid("facets", "a facet has 1 to 8 names"));
399 }
400 for n in names {
401 check_name(n, "facets")?;
402 if n.len() > 32 {
403 return Err(invalid("facets", "a facet name has at most 32 bytes"));
404 }
405 }
406 if names.windows(2).any(|w| w[0] >= w[1]) {
407 return Err(invalid("facets", "the names of a facet are ascending and unique"));
408 }
409 }
410 Ok(())
411}
412
413pub(crate) fn check_extends(kind: CatalogKind, extends: Option<&str>) -> Result<()> {
415 let Some(class) = extends else { return Ok(()) };
416 check_function_name(class, "extends")?;
417 if kind != CatalogKind::Function {
418 return Err(invalid("extends", "only a function extends a class"));
419 }
420 Ok(())
421}
422
423pub(crate) fn check_key_values(owner: &str, key: &str, values: &[KeyValue]) -> Result<()> {
425 check_function_name(owner, "owner")?;
426 check_name(key, "key")?;
427 for v in values {
428 if v.value.is_empty() || v.value.len() > 1024 {
429 return Err(invalid("value", "a value has 1 to 1024 bytes"));
430 }
431 if v.label.len() > 120 {
432 return Err(invalid("label", "a label has at most 120 bytes"));
433 }
434 for a in &v.aliases {
435 if a.is_empty() || a.len() > 120 {
436 return Err(invalid("aliases", "an alias has 1 to 120 bytes"));
437 }
438 }
439 }
440 Ok(())
441}
442
443pub(crate) fn check_model(model: &str) -> Result<()> {
444 if model.is_empty() || model.len() > 200 {
445 return Err(invalid("model", "a model name has 1 to 200 bytes"));
446 }
447 Ok(())
448}
449
450pub(crate) fn vector_literal(v: &[f32]) -> Result<String> {
452 if v.len() != EMBED_DIM {
453 return Err(invalid("vec", format!("a vector has {EMBED_DIM} values, not {}", v.len())));
454 }
455 if v.iter().any(|x| !x.is_finite()) {
456 return Err(invalid("vec", "a vector's values are finite"));
457 }
458 if v.iter().all(|x| *x == 0.0) {
459 return Err(invalid("vec", "a vector is not all zero"));
460 }
461 let parts: Vec<String> = v.iter().map(|x| x.to_string()).collect();
462 Ok(format!("[{}]", parts.join(",")))
463}
464
465pub(crate) fn miss_text(query: &str) -> Option<&str> {
468 let q = query.trim();
469 if q.is_empty() {
470 return None;
471 }
472 let mut end = 0;
473 for (i, c) in q.char_indices() {
474 if i + c.len_utf8() > MISS_BYTES {
475 break;
476 }
477 end = i + c.len_utf8();
478 }
479 Some(&q[..end])
480}
481
482pub(crate) fn args_json(args: &BTreeMap<String, String>) -> String {
486 let members: Vec<(String, json::Value)> =
487 args.iter().map(|(k, v)| (k.clone(), json::Value::String(v.clone()))).collect();
488 String::from_utf8(json::Value::Object(members).to_jcs()).unwrap_or_default()
489}
490
491pub(crate) fn parse_args(text: &str) -> Result<BTreeMap<String, String>> {
493 let v = json::parse(text.as_bytes())?;
494 let members = v.as_object().ok_or_else(|| invalid("args", "stored arguments are not an object"))?;
495 let mut out = BTreeMap::new();
496 for (k, v) in members {
497 let s = v.as_str().ok_or_else(|| invalid("args", "stored argument text is not a string"))?;
498 out.insert(k.clone(), s.to_string());
499 }
500 Ok(out)
501}
502
503pub(crate) fn facets_json(f: &Facets) -> String {
505 let members: Vec<(String, json::Value)> = f
506 .iter()
507 .map(|(k, names)| {
508 let items = names.iter().map(|n| json::Value::String(n.clone())).collect();
509 (k.clone(), json::Value::Array(items))
510 })
511 .collect();
512 String::from_utf8(json::Value::Object(members).to_jcs()).unwrap_or_default()
513}
514
515pub(crate) fn parse_facets(text: &str) -> Result<Facets> {
517 let corrupt = || invalid("facets", "a stored entry has bad facets");
518 let v = json::parse(text.as_bytes())?;
519 let members = v.as_object().ok_or_else(corrupt)?;
520 let mut out = Facets::new();
521 for (k, v) in members {
522 let items = match v {
523 json::Value::Array(items) => items,
524 _ => return Err(corrupt()),
525 };
526 let names =
527 items.iter().map(|i| i.as_str().map(str::to_string).ok_or_else(corrupt)).collect::<Result<Vec<_>>>()?;
528 out.insert(k.clone(), names);
529 }
530 Ok(out)
531}
532
533pub(crate) fn entry_ext(
535 entry: CatalogEntry,
536 facets: &str,
537 extends: Option<String>,
538 source_name: Option<String>,
539) -> Result<CatalogEntryExt> {
540 Ok(CatalogEntryExt { entry, facets: parse_facets(facets)?, extends, source_name })
541}
542
543pub(crate) fn canonical_examples(text: &str) -> Result<String> {
545 let v = json::parse(text.as_bytes())?;
546 if !matches!(v, json::Value::Array(_)) {
547 return Err(invalid("examples", "examples are a JSON array"));
548 }
549 Ok(String::from_utf8(v.to_jcs()).unwrap_or_default())
550}
551
552#[cfg(feature = "sqlite")]
554pub(crate) fn aliases_json(aliases: &[String]) -> String {
555 let items: Vec<json::Value> = aliases.iter().map(|a| json::Value::String(a.clone())).collect();
556 String::from_utf8(json::Value::Array(items).to_jcs()).unwrap_or_default()
557}
558
559#[cfg(feature = "sqlite")]
561pub(crate) fn parse_aliases(text: &str) -> Result<Vec<String>> {
562 let v = json::parse(text.as_bytes())?;
563 let items = match &v {
564 json::Value::Array(items) => items,
565 _ => return Err(invalid("aliases", "stored aliases are not an array")),
566 };
567 items
568 .iter()
569 .map(|i| i.as_str().map(str::to_string).ok_or_else(|| invalid("aliases", "a stored alias is not a string")))
570 .collect()
571}
572
573#[allow(clippy::too_many_arguments)]
575pub(crate) fn entry_from_columns(
576 kind: &str,
577 name: String,
578 hash: Option<String>,
579 label: String,
580 description: String,
581 args: &str,
582 examples: &str,
583 source: &str,
584 signed_by: Option<String>,
585) -> Result<CatalogEntry> {
586 let corrupt = |what: &str| invalid("catalog", format!("a stored entry has a bad {what}"));
587 Ok(CatalogEntry {
588 kind: CatalogKind::parse(kind).ok_or_else(|| corrupt("kind"))?,
589 name,
590 hash,
591 label,
592 description,
593 args: parse_args(args)?,
594 examples: examples.to_string(),
595 source: CatalogSource::parse(source).ok_or_else(|| corrupt("source"))?,
596 signed_by,
597 })
598}
599
600pub(crate) fn entry_text(label: &str, description: &str) -> String {
604 if label.is_empty() {
605 description.to_string()
606 } else {
607 format!("{label}. {description}")
608 }
609}
610
611pub(crate) fn value_text(label: &str, value: &str) -> String {
613 if label.is_empty() {
614 value.to_string()
615 } else {
616 label.to_string()
617 }
618}
619
620pub(crate) struct Words {
625 words: Vec<String>,
626}
627
628impl Words {
629 pub(crate) fn new(query: &str) -> Option<Words> {
630 let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
631 if words.is_empty() {
632 None
633 } else {
634 Some(Words { words })
635 }
636 }
637
638 pub(crate) fn pattern(&self, i: usize, sql_exact: impl Fn(&str) -> bool) -> Option<String> {
643 let w = &self.words[i];
644 if !sql_exact(w) {
645 return None;
646 }
647 let mut escaped = String::with_capacity(w.len() + 2);
648 escaped.push('%');
649 for c in w.chars() {
650 if matches!(c, '!' | '%' | '_') {
651 escaped.push('!');
652 }
653 escaped.push(c);
654 }
655 escaped.push('%');
656 Some(escaped)
657 }
658
659 pub(crate) fn len(&self) -> usize {
660 self.words.len()
661 }
662
663 pub(crate) fn words(&self) -> &[String] {
665 &self.words
666 }
667
668 #[cfg(feature = "sqlite")]
672 pub(crate) fn total(&self, fields: &[&str]) -> Option<u32> {
673 let fields: Vec<String> = fields.iter().map(|f| f.to_lowercase()).collect();
674 let mut total = 0;
675 for w in &self.words {
676 let best = fields.iter().map(|f| field_score(f, w)).max().unwrap_or(0);
677 if best == 0 {
678 return None;
679 }
680 total += best;
681 }
682 Some(total)
683 }
684
685 pub(crate) fn score_of(&self, total: u32) -> f64 {
687 f64::from(total) / (10.0 * self.words.len() as f64)
688 }
689}
690
691#[cfg(feature = "sqlite")]
692pub(crate) fn field_score(field: &str, word: &str) -> u32 {
696 if field == word {
697 10
698 } else if field.split(|c: char| !c.is_alphanumeric()).any(|p| p == word) {
699 8
700 } else if field.contains(word) {
701 5
702 } else {
703 0
704 }
705}
706
707pub(crate) fn rank(mut hits: Vec<Hit>, limit: usize) -> Vec<Hit> {
710 fn key(h: &Hit) -> String {
711 match h {
712 Hit::Entry { entry, .. } => entry.name.clone(),
713 Hit::Value { owner, key, value, .. } => format!("{owner}\u{1}{key}\u{1}{value}"),
714 }
715 }
716 fn score(h: &Hit) -> f64 {
717 match h {
718 Hit::Entry { score, .. } | Hit::Value { score, .. } => *score,
719 }
720 }
721 hits.sort_by(|a, b| {
722 score(b).partial_cmp(&score(a)).unwrap_or(std::cmp::Ordering::Equal).then_with(|| key(a).cmp(&key(b)))
723 });
724 hits.truncate(limit);
725 hits
726}
727
728pub(crate) fn as_i64(n: usize) -> i64 {
730 i64::try_from(n).unwrap_or(i64::MAX)
731}