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
149/// 校验索引名。所有驱动在写入 / 建索引 / 删索引前都应先过这里。
150///
151/// 除空白、路径分隔符与前导点外,还拒绝**会被后端解释成多索引表达式或通配符**
152/// 的字符:`*` `?` `,` `+`,以及前导 `-` / `_`。这条边界很要紧——
153/// Elasticsearch 把 `_all` 当「全部索引」,而 `_all` 里没有需要百分号编码的字符,
154/// 会原样进到 `DELETE /_all`;ES 7.x 与 OpenSearch 默认
155/// `action.destructive_requires_name=false`,一次调用就能删掉整个集群的索引。
156/// 前导 `_` 同时也是 ES 保留给系统索引的前缀。
157pub 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/// RFC 3986 路径段百分号编码:仅保留 unreserved 字符,其余逐字节转 `%XX`
172/// (含 UTF-8 多字节)。所有 HTTP 引擎的 index/id 进入 URL 前统一编码,
173/// 防止 `?`/`#`/`&` 截断路径与 `%2F` 绕过 `/` 校验。
174#[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        // `_all` 与通配符会被 ES 展开成多索引表达式:delete_index("_all")
213        // 在 ES 7.x / OpenSearch 默认配置下会删掉集群里所有索引。
214        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        // 非前导位置的同名字符仍然合法,别把正常名字一起禁掉
220        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}