Skip to main content

opendal_service_mongodb/
backend.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::sync::Arc;
19
20use asyncband::once::OnceCell;
21
22use super::MONGODB_SCHEME;
23use super::config::MongodbConfig;
24use super::core::*;
25use super::deleter::MongodbDeleter;
26use super::reader::*;
27use super::writer::MongodbWriter;
28use opendal_core::raw::*;
29use opendal_core::*;
30
31#[doc = include_str!("docs.md")]
32#[derive(Debug, Default)]
33pub struct MongodbBuilder {
34    pub(super) config: MongodbConfig,
35}
36
37impl MongodbBuilder {
38    /// Set the connection_string of the MongoDB service.
39    ///
40    /// This connection string is used to connect to the MongoDB service. It typically follows the format:
41    ///
42    /// ## Format
43    ///
44    /// `mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]`
45    ///
46    /// Examples:
47    ///
48    /// - Connecting to a local MongoDB instance: `mongodb://localhost:27017`
49    /// - Using authentication: `mongodb://myUser:myPassword@localhost:27017/myAuthDB`
50    /// - Specifying authentication mechanism: `mongodb://myUser:myPassword@localhost:27017/myAuthDB?authMechanism=SCRAM-SHA-256`
51    ///
52    /// ## Options
53    ///
54    /// - `authMechanism`: Specifies the authentication method to use. Examples include `SCRAM-SHA-1`, `SCRAM-SHA-256`, and `MONGODB-AWS`.
55    /// - ... (any other options you wish to highlight)
56    ///
57    /// For more information, please refer to [MongoDB Connection String URI Format](https://docs.mongodb.com/manual/reference/connection-string/).
58    pub fn connection_string(mut self, v: &str) -> Self {
59        if !v.is_empty() {
60            self.config.connection_string = Some(v.to_string());
61        }
62        self
63    }
64    /// Set the working directory, all operations will be performed under it.
65    ///
66    /// default: "/"
67    pub fn root(mut self, root: &str) -> Self {
68        self.config.root = if root.is_empty() {
69            None
70        } else {
71            Some(root.to_string())
72        };
73
74        self
75    }
76
77    /// Set the database name of the MongoDB service to read/write.
78    pub fn database(mut self, database: &str) -> Self {
79        if !database.is_empty() {
80            self.config.database = Some(database.to_string());
81        }
82        self
83    }
84
85    /// Set the collection name of the MongoDB service to read/write.
86    pub fn collection(mut self, collection: &str) -> Self {
87        if !collection.is_empty() {
88            self.config.collection = Some(collection.to_string());
89        }
90        self
91    }
92
93    /// Set the key field name of the MongoDB service to read/write.
94    ///
95    /// Default to `key` if not specified.
96    pub fn key_field(mut self, key_field: &str) -> Self {
97        if !key_field.is_empty() {
98            self.config.key_field = Some(key_field.to_string());
99        }
100        self
101    }
102
103    /// Set the value field name of the MongoDB service to read/write.
104    ///
105    /// Default to `value` if not specified.
106    pub fn value_field(mut self, value_field: &str) -> Self {
107        if !value_field.is_empty() {
108            self.config.value_field = Some(value_field.to_string());
109        }
110        self
111    }
112}
113
114impl Builder for MongodbBuilder {
115    type Config = MongodbConfig;
116
117    fn build(self) -> Result<impl Service> {
118        let conn = match &self.config.connection_string.clone() {
119            Some(v) => v.clone(),
120            None => {
121                return Err(
122                    Error::new(ErrorKind::ConfigInvalid, "connection_string is required")
123                        .with_context("service", MONGODB_SCHEME),
124                );
125            }
126        };
127        let database = match &self.config.database.clone() {
128            Some(v) => v.clone(),
129            None => {
130                return Err(Error::new(ErrorKind::ConfigInvalid, "database is required")
131                    .with_context("service", MONGODB_SCHEME));
132            }
133        };
134        let collection = match &self.config.collection.clone() {
135            Some(v) => v.clone(),
136            None => {
137                return Err(
138                    Error::new(ErrorKind::ConfigInvalid, "collection is required")
139                        .with_context("service", MONGODB_SCHEME),
140                );
141            }
142        };
143        let key_field = match &self.config.key_field.clone() {
144            Some(v) => v.clone(),
145            None => "key".to_string(),
146        };
147        let value_field = match &self.config.value_field.clone() {
148            Some(v) => v.clone(),
149            None => "value".to_string(),
150        };
151        let root = normalize_root(
152            self.config
153                .root
154                .clone()
155                .unwrap_or_else(|| "/".to_string())
156                .as_str(),
157        );
158        Ok(MongodbBackend::new(MongodbCore {
159            connection_string: conn,
160            database,
161            collection,
162            collection_instance: OnceCell::new(),
163            key_field,
164            value_field,
165        })
166        .with_normalized_root(root))
167    }
168}
169
170/// Backend for Mongodb services.
171#[derive(Clone, Debug)]
172pub struct MongodbBackend {
173    pub(crate) core: Arc<MongodbCore>,
174    pub(crate) root: String,
175    pub(crate) info: ServiceInfo,
176    pub(crate) capability: Capability,
177}
178
179impl MongodbBackend {
180    pub fn new(core: MongodbCore) -> Self {
181        let info = ServiceInfo::new(
182            MONGODB_SCHEME,
183            "/",
184            format!("{}/{}", core.database, core.collection),
185        );
186        let capability = Capability {
187            read: true,
188            stat: true,
189            write: true,
190            write_can_empty: true,
191            delete: true,
192            shared: true,
193            ..Default::default()
194        };
195
196        Self {
197            core: Arc::new(core),
198            root: "/".to_string(),
199            info,
200            capability,
201        }
202    }
203
204    fn with_normalized_root(mut self, root: String) -> Self {
205        self.info = self.info.with_root(&root);
206        self.root = root;
207        self
208    }
209}
210
211impl Service for MongodbBackend {
212    type Reader = oio::StreamReader<MongodbReader>;
213    type Writer = MongodbWriter;
214    type Lister = ();
215    type Deleter = oio::OneShotDeleter<MongodbDeleter>;
216    type Copier = ();
217    type Composer = ();
218
219    fn info(&self) -> ServiceInfo {
220        self.info.clone()
221    }
222
223    fn capability(&self) -> Capability {
224        self.capability
225    }
226
227    async fn create_dir(
228        &self,
229        _ctx: &OperationContext,
230        _path: &str,
231        _args: OpCreateDir,
232    ) -> Result<RpCreateDir> {
233        Err(Error::new(
234            ErrorKind::Unsupported,
235            "operation is not supported",
236        ))
237    }
238
239    async fn stat(&self, _ctx: &OperationContext, path: &str, _: OpStat) -> Result<RpStat> {
240        let p = build_abs_path(&self.root, path);
241
242        if p == build_abs_path(&self.root, "") {
243            Ok(RpStat::new(MetadataBuilder::dir().build()))
244        } else {
245            match self.core.get_length(&p).await? {
246                Some(length) => Ok(RpStat::new({
247                    let metadata = MetadataBuilder::file(length as u64);
248                    metadata.build()
249                })),
250                None => Err(Error::new(ErrorKind::NotFound, "kv not found in mongodb")),
251            }
252        }
253    }
254    fn read(&self, _ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
255        let output: oio::StreamReader<MongodbReader> = {
256            Ok(oio::StreamReader::new(MongodbReader::new(
257                self.clone(),
258                path,
259                args,
260            )))
261        }?;
262
263        Ok(output)
264    }
265
266    fn write(&self, _ctx: &OperationContext, path: &str, _: OpWrite) -> Result<Self::Writer> {
267        let output: MongodbWriter = {
268            let p = build_abs_path(&self.root, path);
269            Ok(MongodbWriter::new(self.core.clone(), p))
270        }?;
271
272        Ok(output)
273    }
274
275    fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
276        let output: oio::OneShotDeleter<MongodbDeleter> = {
277            Ok(oio::OneShotDeleter::new(MongodbDeleter::new(
278                self.core.clone(),
279                self.root.clone(),
280            )))
281        }?;
282
283        Ok(output)
284    }
285
286    fn list(&self, _ctx: &OperationContext, _path: &str, _args: OpList) -> Result<Self::Lister> {
287        Err(Error::new(
288            ErrorKind::Unsupported,
289            "operation is not supported",
290        ))
291    }
292
293    fn copy(
294        &self,
295        _ctx: &OperationContext,
296        _from: &str,
297        _to: &str,
298        _args: OpCopy,
299    ) -> Result<Self::Copier> {
300        Err(Error::new(
301            ErrorKind::Unsupported,
302            "operation is not supported",
303        ))
304    }
305
306    async fn rename(
307        &self,
308        _ctx: &OperationContext,
309        _from: &str,
310        _to: &str,
311        _args: OpRename,
312    ) -> Result<RpRename> {
313        Err(Error::new(
314            ErrorKind::Unsupported,
315            "operation is not supported",
316        ))
317    }
318
319    async fn presign(
320        &self,
321        _ctx: &OperationContext,
322        _path: &str,
323        _args: OpPresign,
324    ) -> Result<RpPresign> {
325        Err(Error::new(
326            ErrorKind::Unsupported,
327            "operation is not supported",
328        ))
329    }
330}