Skip to main content

opendal_service_redb/
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::fmt::Debug;
19use std::sync::Arc;
20
21use super::REDB_SCHEME;
22use super::config::RedbConfig;
23use super::core::*;
24use super::deleter::RedbDeleter;
25use super::lister::RedbLister;
26use super::reader::*;
27use super::writer::RedbWriter;
28use opendal_core::raw::*;
29use opendal_core::*;
30
31/// Redb service support.
32#[doc = include_str!("docs.md")]
33#[derive(Default)]
34pub struct RedbBuilder {
35    pub(super) config: RedbConfig,
36
37    pub(super) database: Option<Arc<redb::Database>>,
38}
39
40impl Debug for RedbBuilder {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("RedbBuilder")
43            .field("config", &self.config)
44            .finish_non_exhaustive()
45    }
46}
47
48impl RedbBuilder {
49    /// Set the database for Redb.
50    ///
51    /// This method should be called when you want to
52    /// use multiple tables of one database because
53    /// Redb doesn't allow opening a database that have been opened.
54    ///
55    /// <div class="warning">
56    ///
57    /// `datadir` and `database` should not be set simultaneously.
58    /// If both are set, `database` will take precedence.
59    ///
60    /// </div>
61    pub fn database(mut self, db: Arc<redb::Database>) -> Self {
62        self.database = Some(db);
63        self
64    }
65
66    /// Set the path to the redb data directory. Will create if not exists.
67    ///
68    ///
69    /// <div class="warning">
70    ///
71    /// Opening redb database via `datadir` takes away the ability to access multiple redb tables.
72    /// If you need to access multiple redb tables, the correct solution is to
73    /// create an `Arc<redb::database>` beforehand and then share it via [`database`]
74    /// with multiple builders where every builder will open one redb table.
75    ///
76    /// </div>
77    ///
78    /// [`database`]: RedbBuilder::database
79    pub fn datadir(mut self, path: &str) -> Self {
80        self.config.datadir = Some(path.into());
81        self
82    }
83
84    /// Set the table name for Redb. Will create if not exists.
85    pub fn table(mut self, table: &str) -> Self {
86        self.config.table = if table.is_empty() {
87            None
88        } else {
89            Some(table.into())
90        };
91        self
92    }
93
94    /// Set the root for Redb.
95    pub fn root(mut self, path: &str) -> Self {
96        self.config.root = Some(path.into());
97        self
98    }
99}
100
101impl Builder for RedbBuilder {
102    type Config = RedbConfig;
103
104    fn build(self) -> Result<impl Service> {
105        let table_name = self.config.table.filter(|v| !v.is_empty()).ok_or_else(|| {
106            Error::new(ErrorKind::ConfigInvalid, "table is required but not set")
107                .with_context("service", REDB_SCHEME)
108        })?;
109
110        let (datadir, db) = if let Some(db) = self.database {
111            (None, db)
112        } else {
113            let datadir = self.config.datadir.ok_or_else(|| {
114                Error::new(ErrorKind::ConfigInvalid, "datadir is required but not set")
115                    .with_context("service", REDB_SCHEME)
116            })?;
117
118            let db = redb::Database::create(&datadir)
119                .map_err(parse_database_error)?
120                .into();
121
122            (Some(datadir), db)
123        };
124
125        create_table(&db, &table_name)?;
126
127        let root = normalize_root(&self.config.root.unwrap_or_default());
128
129        Ok(RedbBackend::new(RedbCore {
130            datadir,
131            table: table_name,
132            db,
133        })
134        .with_normalized_root(root))
135    }
136}
137
138/// Backend for Redb services.
139#[derive(Clone, Debug)]
140pub struct RedbBackend {
141    pub(crate) core: Arc<RedbCore>,
142    pub(crate) root: String,
143    pub(crate) info: ServiceInfo,
144    pub(crate) capability: Capability,
145}
146
147impl RedbBackend {
148    pub fn new(core: RedbCore) -> Self {
149        let info = ServiceInfo::new(REDB_SCHEME, "/", &core.table);
150        let capability = Capability {
151            read: true,
152            stat: true,
153            write: true,
154            write_can_empty: true,
155            delete: true,
156            list: true,
157            list_with_recursive: true,
158            ..Default::default()
159        };
160
161        Self {
162            core: Arc::new(core),
163            root: "/".to_string(),
164            info,
165            capability,
166        }
167    }
168
169    fn with_normalized_root(mut self, root: String) -> Self {
170        self.info = self.info.with_root(&root);
171        self.root = root;
172        self
173    }
174}
175
176impl Service for RedbBackend {
177    type Reader = oio::StreamReader<RedbReader>;
178    type Writer = RedbWriter;
179    type Lister = oio::HierarchyLister<RedbLister>;
180    type Deleter = oio::OneShotDeleter<RedbDeleter>;
181    type Copier = ();
182    type Composer = ();
183
184    fn info(&self) -> ServiceInfo {
185        self.info.clone()
186    }
187
188    fn capability(&self) -> Capability {
189        self.capability
190    }
191
192    async fn create_dir(
193        &self,
194        _ctx: &OperationContext,
195        _path: &str,
196        _args: OpCreateDir,
197    ) -> Result<RpCreateDir> {
198        Err(Error::new(
199            ErrorKind::Unsupported,
200            "operation is not supported",
201        ))
202    }
203
204    async fn stat(&self, _ctx: &OperationContext, path: &str, _: OpStat) -> Result<RpStat> {
205        let p = build_absolute_path(&self.root, path);
206
207        if p == build_absolute_path(&self.root, "") {
208            Ok(RpStat::new(MetadataBuilder::dir().build()))
209        } else {
210            let bs = self.core.get(&p)?;
211            match bs {
212                Some(bs) => {
213                    let metadata = if p.ends_with('/') {
214                        MetadataBuilder::dir()
215                    } else {
216                        MetadataBuilder::file(bs.len() as u64)
217                    };
218                    Ok(RpStat::new(metadata.build()))
219                }
220                None => Err(Error::new(ErrorKind::NotFound, "kv not found in redb")),
221            }
222        }
223    }
224    fn read(&self, _ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
225        let output: oio::StreamReader<RedbReader> = {
226            Ok(oio::StreamReader::new(RedbReader::new(
227                self.clone(),
228                path,
229                args,
230            )))
231        }?;
232
233        Ok(output)
234    }
235
236    fn write(&self, _ctx: &OperationContext, path: &str, _: OpWrite) -> Result<Self::Writer> {
237        let output: RedbWriter = {
238            let p = build_absolute_path(&self.root, path);
239            Ok(RedbWriter::new(self.core.clone(), p))
240        }?;
241
242        Ok(output)
243    }
244
245    fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
246        let output: oio::OneShotDeleter<RedbDeleter> = {
247            Ok(oio::OneShotDeleter::new(RedbDeleter::new(
248                self.core.clone(),
249                self.root.clone(),
250            )))
251        }?;
252
253        Ok(output)
254    }
255
256    fn list(&self, _ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
257        let prefix = build_absolute_path(&self.root, path);
258        let range = self.core.scan(&prefix)?;
259        let lister = RedbLister::new(self.root.clone(), prefix, range);
260        Ok(oio::HierarchyLister::new(lister, path, args.recursive()))
261    }
262
263    fn copy(
264        &self,
265        _ctx: &OperationContext,
266        _from: &str,
267        _to: &str,
268        _args: OpCopy,
269    ) -> Result<Self::Copier> {
270        Err(Error::new(
271            ErrorKind::Unsupported,
272            "operation is not supported",
273        ))
274    }
275
276    async fn rename(
277        &self,
278        _ctx: &OperationContext,
279        _from: &str,
280        _to: &str,
281        _args: OpRename,
282    ) -> Result<RpRename> {
283        Err(Error::new(
284            ErrorKind::Unsupported,
285            "operation is not supported",
286        ))
287    }
288
289    async fn presign(
290        &self,
291        _ctx: &OperationContext,
292        _path: &str,
293        _args: OpPresign,
294    ) -> Result<RpPresign> {
295        Err(Error::new(
296            ErrorKind::Unsupported,
297            "operation is not supported",
298        ))
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use opendal_core::raw::oio::Write as _;
306
307    #[tokio::test]
308    async fn test_create_dir_root_and_list() -> Result<()> {
309        for root in ["/", "/sub/"] {
310            let dir = tempfile::tempdir().expect("create tempdir");
311            let db_path = dir.path().join("test.redb");
312            let builder = RedbBuilder::default()
313                .datadir(db_path.to_str().expect("valid utf-8 path"))
314                .table("test");
315            let builder = if root == "/" {
316                builder
317            } else {
318                builder.root(root)
319            };
320            let op = Operator::new(builder)?.layer(layers::SimulateLayer::default());
321
322            op.create_dir("/").await?;
323
324            for entries in [
325                op.list("/").await?,
326                op.list_with("/").recursive(true).await?,
327            ] {
328                let actual: Vec<_> = entries
329                    .iter()
330                    .map(|e| (e.path(), e.metadata().mode()))
331                    .collect();
332                assert_eq!(actual, vec![("/", EntryMode::DIR)], "root {root}");
333            }
334        }
335        Ok(())
336    }
337
338    #[tokio::test]
339    async fn test_root_stat() -> Result<()> {
340        let ctx = OperationContext::default();
341        for root in ["/", "/sub/"] {
342            let dir = tempfile::tempdir().expect("create tempdir");
343            let db_path = dir.path().join("test.redb");
344            let builder = RedbBuilder::default()
345                .datadir(db_path.to_str().expect("valid utf-8 path"))
346                .table("test");
347            let builder = if root == "/" {
348                builder
349            } else {
350                builder.root(root)
351            };
352            let service = builder.build()?;
353
354            assert_eq!(
355                service
356                    .stat(&ctx, "/", OpStat::default())
357                    .await?
358                    .into_metadata()
359                    .mode(),
360                EntryMode::DIR,
361                "root {root}"
362            );
363
364            let mut writer = service.write(&ctx, "/", OpWrite::default())?;
365            writer.close().await?;
366
367            assert_eq!(
368                service
369                    .stat(&ctx, "/", OpStat::default())
370                    .await?
371                    .into_metadata()
372                    .mode(),
373                EntryMode::DIR,
374                "root {root}"
375            );
376        }
377        Ok(())
378    }
379
380    #[tokio::test]
381    async fn test_dir_marker_stat_metadata() -> Result<()> {
382        for root in ["/", "/sub/"] {
383            let dir = tempfile::tempdir().expect("create tempdir");
384            let db_path = dir.path().join("test.redb");
385            let builder = RedbBuilder::default()
386                .datadir(db_path.to_str().expect("valid utf-8 path"))
387                .table("test");
388            let builder = if root == "/" {
389                builder
390            } else {
391                builder.root(root)
392            };
393            let srv: Servicer = Arc::new(builder.build()?);
394            let op = Operator::from_parts(OperationContext::default(), srv)
395                .layer(layers::SimulateLayer::default().with_stat_dir(false));
396
397            op.create_dir("a/").await?;
398            assert_eq!(op.stat("a/").await?.mode(), EntryMode::DIR, "root {root}");
399
400            op.write("a/file.txt", "hello").await?;
401            let meta = op.stat("a/file.txt").await?;
402            assert_eq!(meta.mode(), EntryMode::FILE, "root {root}");
403            assert_eq!(meta.content_length(), 5, "root {root}");
404
405            let err = op.stat("missing/").await.unwrap_err();
406            assert_eq!(err.kind(), ErrorKind::NotFound, "root {root}");
407        }
408        Ok(())
409    }
410
411    #[test]
412    fn test_empty_table() -> Result<()> {
413        let dir = tempfile::tempdir().expect("create tempdir");
414        let db_path = dir.path().join("test.redb");
415        let db_path = db_path.to_str().expect("valid utf-8 path");
416
417        let err = RedbBuilder::default()
418            .datadir(db_path)
419            .table("")
420            .build()
421            .unwrap_err();
422        assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
423
424        let err = RedbBuilder::default()
425            .datadir(db_path)
426            .table("test")
427            .table("")
428            .build()
429            .unwrap_err();
430        assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
431
432        let err = RedbConfig::from_iter([
433            ("datadir".to_string(), db_path.to_string()),
434            ("table".to_string(), String::new()),
435        ])?
436        .into_builder()
437        .build()
438        .unwrap_err();
439        assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
440
441        Ok(())
442    }
443}