opendal/services/cacache/
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 chrono::DateTime;
22
23use crate::raw::*;
24use crate::services::CacacheConfig;
25use crate::*;
26
27use super::core::CacacheCore;
28use super::delete::CacacheDeleter;
29use super::writer::CacacheWriter;
30use super::DEFAULT_SCHEME;
31impl Configurator for CacacheConfig {
32    type Builder = CacacheBuilder;
33    fn into_builder(self) -> Self::Builder {
34        CacacheBuilder { config: self }
35    }
36}
37
38/// cacache service support.
39#[doc = include_str!("docs.md")]
40#[derive(Default)]
41pub struct CacacheBuilder {
42    config: CacacheConfig,
43}
44
45impl CacacheBuilder {
46    /// Set the path to the cacache data directory. Will create if not exists.
47    pub fn datadir(mut self, path: &str) -> Self {
48        self.config.datadir = Some(path.into());
49        self
50    }
51}
52
53impl Builder for CacacheBuilder {
54    type Config = CacacheConfig;
55
56    fn build(self) -> Result<impl Access> {
57        let datadir_path = self.config.datadir.ok_or_else(|| {
58            Error::new(ErrorKind::ConfigInvalid, "datadir is required but not set")
59                .with_context("service", Scheme::Cacache)
60        })?;
61
62        let core = CacacheCore {
63            path: datadir_path.clone(),
64        };
65
66        let info = AccessorInfo::default();
67        info.set_scheme(DEFAULT_SCHEME);
68        info.set_name(&datadir_path);
69        info.set_root("/");
70        info.set_native_capability(Capability {
71            read: true,
72            write: true,
73            delete: true,
74            stat: true,
75            rename: false,
76            list: false,
77            shared: false,
78            ..Default::default()
79        });
80
81        Ok(CacacheAccessor {
82            core: Arc::new(core),
83            info: Arc::new(info),
84        })
85    }
86}
87
88/// Backend for cacache services.
89#[derive(Debug, Clone)]
90pub struct CacacheAccessor {
91    core: Arc<CacacheCore>,
92    info: Arc<AccessorInfo>,
93}
94
95impl Access for CacacheAccessor {
96    type Reader = Buffer;
97    type Writer = CacacheWriter;
98    type Lister = ();
99    type Deleter = oio::OneShotDeleter<CacacheDeleter>;
100
101    fn info(&self) -> Arc<AccessorInfo> {
102        self.info.clone()
103    }
104
105    async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
106        let metadata = self.core.metadata(path).await?;
107
108        match metadata {
109            Some(meta) => {
110                let mut md = Metadata::new(EntryMode::FILE);
111                md.set_content_length(meta.size as u64);
112                // Convert u128 milliseconds to DateTime<Utc>
113                let millis = meta.time;
114                let secs = (millis / 1000) as i64;
115                let nanos = ((millis % 1000) * 1_000_000) as u32;
116                if let Some(dt) = DateTime::from_timestamp(secs, nanos) {
117                    md.set_last_modified(dt);
118                }
119                Ok(RpStat::new(md))
120            }
121            None => Err(Error::new(ErrorKind::NotFound, "entry not found")),
122        }
123    }
124
125    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
126        let data = self.core.get(path).await?;
127
128        match data {
129            Some(bytes) => {
130                let range = args.range();
131                let buffer = if range.is_full() {
132                    Buffer::from(bytes)
133                } else {
134                    let start = range.offset() as usize;
135                    let end = match range.size() {
136                        Some(size) => (range.offset() + size) as usize,
137                        None => bytes.len(),
138                    };
139                    Buffer::from(bytes.slice(start..end.min(bytes.len())))
140                };
141                Ok((RpRead::new(), buffer))
142            }
143            None => Err(Error::new(ErrorKind::NotFound, "entry not found")),
144        }
145    }
146
147    async fn write(&self, path: &str, _: OpWrite) -> Result<(RpWrite, Self::Writer)> {
148        Ok((
149            RpWrite::new(),
150            CacacheWriter::new(self.core.clone(), path.to_string()),
151        ))
152    }
153
154    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
155        Ok((
156            RpDelete::default(),
157            oio::OneShotDeleter::new(CacacheDeleter::new(self.core.clone())),
158        ))
159    }
160}