Skip to main content

rust_scout/
config.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5/// 驱动配置。
6///
7/// 字段对齐 `webman-scout` 的 Scout 配置形状,其中一部分目前**只是配置占位、
8/// 驱动不会读取**(见各字段说明)。真正生效的是 `driver`、`options` 和
9/// 各后端构造器写入的连接参数。
10#[derive(Debug, Clone, Default, Serialize, Deserialize)]
11pub struct ScoutConfig {
12    #[serde(default = "default_driver")]
13    pub driver: String,
14    /// 索引名前缀。**尚未生效**:只有 [`ScoutConfig::index_name`] 会读它,
15    /// 而各驱动都直接使用传入的索引名、不经过该方法。设置它不会给索引加前缀。
16    #[serde(default)]
17    pub prefix: String,
18    /// 队列开关。配置占位,当前无写入队列实现(`queue` 与
19    /// `after_commit` 都属此列)。
20    #[serde(default)]
21    pub queue: bool,
22    /// 提交后同步。配置占位,见 [`ScoutConfig::queue`]。
23    #[serde(default)]
24    pub after_commit: bool,
25    /// 软删除开关。配置占位;软删除能力由 [`Engine::soft_delete`] 与
26    /// [`SearchBuilder::with_trashed`] 控制,与此字段无关。
27    ///
28    /// [`Engine::soft_delete`]: crate::Engine::soft_delete
29    /// [`SearchBuilder::with_trashed`]: crate::SearchBuilder::with_trashed
30    #[serde(default)]
31    pub soft_delete: bool,
32    /// 模型 id 识别开关。配置占位,当前无效。
33    #[serde(default)]
34    pub identify: bool,
35    /// 批量写入分块大小。配置占位;批量接口由调用方自行分块。
36    #[serde(default = "default_chunk")]
37    pub chunk_searchable: usize,
38    /// 批量删除分块大小。配置占位,见 [`ScoutConfig::chunk_searchable`]。
39    #[serde(default = "default_chunk")]
40    pub chunk_unsearchable: usize,
41    /// 驱动专属参数,**会被读取**:键形如 `elasticsearch.host` /
42    /// `database.url` / `algolia.app_id`,由 [`EngineManager`](crate::EngineManager)
43    /// 在构造驱动时取用。
44    #[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    /// 校验索引名并拼上 [`prefix`](ScoutConfig::prefix)。
132    ///
133    /// 注意:各驱动**不经过**这里,它们直接用传入的索引名。本方法目前只有
134    /// 调用方自己用得到,`prefix` 字段因此不会自动生效。
135    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<()> {
150    if index
151        .chars()
152        .any(|c| c.is_whitespace() || c == '/' || c == '\\')
153        || index.starts_with('.')
154        || index.is_empty()
155    {
156        return Err(crate::ScoutError::InvalidIndexName(index.to_string()));
157    }
158    Ok(())
159}
160
161/// RFC 3986 路径段百分号编码:仅保留 unreserved 字符,其余逐字节转 `%XX`
162/// (含 UTF-8 多字节)。所有 HTTP 引擎的 index/id 进入 URL 前统一编码,
163/// 防止 `?`/`#`/`&` 截断路径与 `%2F` 绕过 `/` 校验。
164#[cfg(any(
165    feature = "elasticsearch",
166    feature = "meilisearch",
167    feature = "typesense",
168    feature = "algolia"
169))]
170pub(crate) fn percent_encode(s: &str) -> String {
171    let mut out = String::with_capacity(s.len());
172    for &b in s.as_bytes() {
173        match b {
174            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
175                out.push(b as char)
176            }
177            _ => out.push_str(&format!("%{:02X}", b)),
178        }
179    }
180    out
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn validate_index_name_accepts_valid() {
189        assert!(validate_index_name("books").is_ok());
190        assert!(validate_index_name("a-b_c.d~中文").is_ok());
191    }
192
193    #[test]
194    fn validate_index_name_rejects_invalid() {
195        for bad in ["", " ", "a b", "a/b", "a\\b", ".hidden", "\t", "\n"] {
196            assert!(validate_index_name(bad).is_err(), "should reject {:?}", bad);
197        }
198    }
199}