opendal/services/mongodb/
config.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19
20use serde::Deserialize;
21use serde::Serialize;
22
23use super::backend::MongodbBuilder;
24
25/// Config for Mongodb service support.
26#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
27#[serde(default)]
28#[non_exhaustive]
29pub struct MongodbConfig {
30    /// connection string of this backend
31    pub connection_string: Option<String>,
32    /// database of this backend
33    pub database: Option<String>,
34    /// collection of this backend
35    pub collection: Option<String>,
36    /// root of this backend
37    pub root: Option<String>,
38    /// key field of this backend
39    pub key_field: Option<String>,
40    /// value field of this backend
41    pub value_field: Option<String>,
42}
43
44impl Debug for MongodbConfig {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.debug_struct("MongodbConfig")
47            .field("database", &self.database)
48            .field("collection", &self.collection)
49            .field("root", &self.root)
50            .field("key_field", &self.key_field)
51            .field("value_field", &self.value_field)
52            .finish_non_exhaustive()
53    }
54}
55
56impl crate::Configurator for MongodbConfig {
57    type Builder = MongodbBuilder;
58
59    fn from_uri(uri: &crate::types::OperatorUri) -> crate::Result<Self> {
60        let mut map = uri.options().clone();
61
62        if let Some(authority) = uri.authority() {
63            map.entry("connection_string".to_string())
64                .or_insert_with(|| format!("mongodb://{authority}"));
65        }
66
67        if let Some(path) = uri.root() {
68            if !path.is_empty() {
69                let mut segments = path.splitn(3, '/');
70                if let Some(db) = segments.next() {
71                    if !db.is_empty() {
72                        map.entry("database".to_string())
73                            .or_insert_with(|| db.to_string());
74                    }
75                }
76                if let Some(collection) = segments.next() {
77                    if !collection.is_empty() {
78                        map.entry("collection".to_string())
79                            .or_insert_with(|| collection.to_string());
80                    }
81                }
82                if let Some(rest) = segments.next() {
83                    if !rest.is_empty() {
84                        map.insert("root".to_string(), rest.to_string());
85                    }
86                }
87            }
88        }
89
90        Self::from_iter(map)
91    }
92
93    fn into_builder(self) -> Self::Builder {
94        MongodbBuilder { config: self }
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::Configurator;
102    use crate::types::OperatorUri;
103
104    #[test]
105    fn from_uri_sets_connection_string_database_collection_and_root() {
106        let uri = OperatorUri::new(
107            "mongodb://mongo.internal:27017/analytics/events/session",
108            Vec::<(String, String)>::new(),
109        )
110        .unwrap();
111
112        let cfg = MongodbConfig::from_uri(&uri).unwrap();
113        assert_eq!(
114            cfg.connection_string.as_deref(),
115            Some("mongodb://mongo.internal:27017")
116        );
117        assert_eq!(cfg.database.as_deref(), Some("analytics"));
118        assert_eq!(cfg.collection.as_deref(), Some("events"));
119        assert_eq!(cfg.root.as_deref(), Some("session"));
120    }
121}