1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Default, Serialize, Deserialize)]
6pub struct ScoutConfig {
7 #[serde(default = "default_driver")]
8 pub driver: String,
9 #[serde(default)]
10 pub prefix: String,
11 #[serde(default)]
12 pub queue: bool,
13 #[serde(default)]
14 pub after_commit: bool,
15 #[serde(default)]
16 pub soft_delete: bool,
17 #[serde(default)]
18 pub identify: bool,
19 #[serde(default = "default_chunk")]
20 pub chunk_searchable: usize,
21 #[serde(default = "default_chunk")]
22 pub chunk_unsearchable: usize,
23 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
24 pub options: HashMap<String, serde_json::Value>,
25}
26
27impl ScoutConfig {
28 pub fn collection() -> Self {
29 Self {
30 driver: "collection".to_string(),
31 ..Self::default()
32 }
33 }
34
35 pub fn elasticsearch(host: impl Into<String>, api_key: Option<String>) -> Self {
36 let mut config = Self::collection();
37 config.driver = "elasticsearch".to_string();
38 config.insert("elasticsearch.host", host.into());
39 if let Some(api_key) = api_key {
40 config.insert("elasticsearch.api_key", api_key);
41 }
42 config
43 }
44
45 pub fn opensearch(host: impl Into<String>, api_key: Option<String>) -> Self {
46 let mut config = Self::collection();
47 config.driver = "opensearch".to_string();
48 config.insert("opensearch.host", host.into());
49 if let Some(api_key) = api_key {
50 config.insert("opensearch.api_key", api_key);
51 }
52 config
53 }
54
55 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
56 self.options.insert(key.into(), value.into());
57 }
58
59 pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
60 self.options.get(key)
61 }
62
63 pub fn index_name(&self, index: &str) -> crate::Result<String> {
64 crate::validate_index_name(index)?;
65 Ok(format!("{}{}", self.prefix, index))
66 }
67}
68
69fn default_driver() -> String {
70 "collection".to_string()
71}
72
73fn default_chunk() -> usize {
74 500
75}
76
77pub fn validate_index_name(index: &str) -> crate::Result<()> {
78 if index
79 .chars()
80 .any(|c| c.is_whitespace() || c == '/' || c == '\\')
81 || index.starts_with('.')
82 || index.is_empty()
83 {
84 return Err(crate::ScoutError::InvalidIndexName(index.to_string()));
85 }
86 Ok(())
87}