1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Default, Serialize, Deserialize)]
11pub struct ScoutConfig {
12 #[serde(default = "default_driver")]
13 pub driver: String,
14 #[serde(default)]
17 pub prefix: String,
18 #[serde(default)]
21 pub queue: bool,
22 #[serde(default)]
24 pub after_commit: bool,
25 #[serde(default)]
31 pub soft_delete: bool,
32 #[serde(default)]
34 pub identify: bool,
35 #[serde(default = "default_chunk")]
37 pub chunk_searchable: usize,
38 #[serde(default = "default_chunk")]
40 pub chunk_unsearchable: usize,
41 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
45 pub options: HashMap<String, serde_json::Value>,
46}
47
48impl ScoutConfig {
49 pub fn collection() -> Self {
50 Self {
51 driver: "collection".to_string(),
52 ..Self::default()
53 }
54 }
55
56 pub fn elasticsearch(host: impl Into<String>, api_key: Option<String>) -> Self {
57 let mut config = Self::collection();
58 config.driver = "elasticsearch".to_string();
59 config.insert("elasticsearch.host", host.into());
60 if let Some(api_key) = api_key {
61 config.insert("elasticsearch.api_key", api_key);
62 }
63 config
64 }
65
66 pub fn opensearch(host: impl Into<String>, api_key: Option<String>) -> Self {
67 let mut config = Self::collection();
68 config.driver = "opensearch".to_string();
69 config.insert("opensearch.host", host.into());
70 if let Some(api_key) = api_key {
71 config.insert("opensearch.api_key", api_key);
72 }
73 config
74 }
75
76 pub fn meilisearch(host: impl Into<String>, api_key: impl Into<String>) -> Self {
77 let mut config = Self::collection();
78 config.driver = "meilisearch".to_string();
79 config.insert("meilisearch.host", host.into());
80 config.insert("meilisearch.api_key", api_key.into());
81 config
82 }
83
84 pub fn typesense(host: impl Into<String>, api_key: impl Into<String>) -> Self {
85 let mut config = Self::collection();
86 config.driver = "typesense".to_string();
87 config.insert("typesense.host", host.into());
88 config.insert("typesense.api_key", api_key.into());
89 config
90 }
91
92 pub fn algolia(app_id: impl Into<String>, api_key: impl Into<String>) -> Self {
93 let mut config = Self::collection();
94 config.driver = "algolia".to_string();
95 config.insert("algolia.app_id", app_id.into());
96 config.insert("algolia.api_key", api_key.into());
97 config
98 }
99
100 pub fn database(url: impl Into<String>, fields: Vec<String>) -> Self {
101 let mut config = Self::collection();
102 config.driver = "database".to_string();
103 config.insert("database.url", url.into());
104 config.insert("database.fields", serde_json::json!(fields));
105 config
106 }
107
108 pub fn null() -> Self {
109 Self {
110 driver: "null".to_string(),
111 ..Self::collection()
112 }
113 }
114
115 pub fn xunsearch(host: impl Into<String>, project: impl Into<String>) -> Self {
116 let mut config = Self::collection();
117 config.driver = "xunsearch".to_string();
118 config.insert("xunsearch.host", host.into());
119 config.insert("xunsearch.project", project.into());
120 config
121 }
122
123 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
124 self.options.insert(key.into(), value.into());
125 }
126
127 pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
128 self.options.get(key)
129 }
130
131 pub fn index_name(&self, index: &str) -> crate::Result<String> {
136 crate::validate_index_name(index)?;
137 Ok(format!("{}{}", self.prefix, index))
138 }
139}
140
141fn default_driver() -> String {
142 "collection".to_string()
143}
144
145fn default_chunk() -> usize {
146 500
147}
148
149pub fn validate_index_name(index: &str) -> crate::Result<()> {
158 let bad = index.is_empty()
159 || index.starts_with('.')
160 || index.starts_with('-')
161 || index.starts_with('_')
162 || index
163 .chars()
164 .any(|c| c.is_whitespace() || matches!(c, '/' | '\\' | '*' | '?' | ',' | '+'));
165 if bad {
166 return Err(crate::ScoutError::InvalidIndexName(index.to_string()));
167 }
168 Ok(())
169}
170
171#[cfg(any(
175 feature = "elasticsearch",
176 feature = "meilisearch",
177 feature = "typesense",
178 feature = "algolia"
179))]
180pub(crate) fn percent_encode(s: &str) -> String {
181 let mut out = String::with_capacity(s.len());
182 for &b in s.as_bytes() {
183 match b {
184 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
185 out.push(b as char)
186 }
187 _ => out.push_str(&format!("%{:02X}", b)),
188 }
189 }
190 out
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 #[test]
198 fn validate_index_name_accepts_valid() {
199 assert!(validate_index_name("books").is_ok());
200 assert!(validate_index_name("a-b_c.d~中文").is_ok());
201 }
202
203 #[test]
204 fn validate_index_name_rejects_invalid() {
205 for bad in ["", " ", "a b", "a/b", "a\\b", ".hidden", "\t", "\n"] {
206 assert!(validate_index_name(bad).is_err(), "should reject {:?}", bad);
207 }
208 }
209
210 #[test]
211 fn validate_index_name_rejects_wildcards_and_reserved_prefixes() {
212 for bad in [
215 "_all", "_cat", "*", "a*", "a,b", "books*", "a?b", "+a", "-a", "_hidden",
216 ] {
217 assert!(validate_index_name(bad).is_err(), "should reject {:?}", bad);
218 }
219 for good in ["my_index", "a-b", "books-2024", "c#1", "a~b", "中文索引"] {
221 assert!(validate_index_name(good).is_ok(), "should accept {:?}", good);
222 }
223 }
224}