Skip to main content

opendal_service_hf3fs/
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::ffi::CString;
19use std::os::unix::ffi::OsStrExt;
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22
23use opendal_core::raw::*;
24use opendal_core::*;
25
26use crate::HF3FS_SCHEME;
27use crate::config::Hf3fsConfig;
28use crate::driver::IoDriver;
29use crate::ffi::Api;
30use crate::reader::Hf3fsReader;
31use crate::writer::Hf3fsWriter;
32
33/// Access DeepSeek's 3FS (Fire-Flyer File System) through USRBIO for data and
34/// the mounted filesystem for metadata.
35///
36/// Requires Linux, a running 3FS FUSE client, and its compatible USRBIO shared
37/// library. The root must already exist. Reads retain shared memory while space
38/// permits; writes copy into shared memory. See the crate documentation for
39/// memory limits and failure semantics.
40#[derive(Debug, Default)]
41pub struct Hf3fsBuilder {
42    pub(crate) config: Hf3fsConfig,
43}
44
45impl Hf3fsBuilder {
46    /// Set the existing absolute directory used as the storage root.
47    pub fn root(mut self, root: &str) -> Self {
48        self.config.root = Some(root.into());
49        self
50    }
51
52    /// Set the path to the compatible `libhf3fs_api_shared.so` library.
53    /// Defaults to the system dynamic loader's search path.
54    pub fn library_path(mut self, path: &str) -> Self {
55        self.config.library_path = Some(path.into());
56        self
57    }
58
59    /// Set the positive maximum number of in-flight requests per ring.
60    /// Defaults to 32. Each operator owns one read ring and one write ring.
61    pub fn queue_depth(mut self, depth: usize) -> Self {
62        self.config.queue_depth = Some(depth);
63        self
64    }
65
66    /// Set the positive maximum request size in bytes. Defaults to 1 MiB.
67    /// Shared memory usage is approximately `3 * queue_depth * block_size`.
68    pub fn block_size(mut self, size: usize) -> Self {
69        self.config.block_size = Some(size);
70        self
71    }
72}
73
74impl Builder for Hf3fsBuilder {
75    type Config = Hf3fsConfig;
76
77    fn build(self) -> Result<impl Service> {
78        let depth = self.config.queue_depth.unwrap_or(32);
79        let block_size = self.config.block_size.unwrap_or(1024 * 1024);
80        if depth == 0
81            || depth >= i32::MAX as usize
82            || block_size == 0
83            || depth
84                .checked_mul(3)
85                .and_then(|n| n.checked_mul(block_size))
86                .is_none_or(|n| n > isize::MAX as usize)
87        {
88            return Err(Error::new(
89                ErrorKind::ConfigInvalid,
90                "invalid USRBIO queue depth or block size",
91            ));
92        }
93        let root = self
94            .config
95            .root
96            .as_deref()
97            .filter(|p| Path::new(p).is_absolute())
98            .ok_or_else(|| {
99                Error::new(ErrorKind::ConfigInvalid, "an absolute 3FS root is required")
100            })?;
101        let root = Path::new(root).canonicalize().map_err(new_std_io_error)?;
102        if !root.is_dir() {
103            return Err(Error::new(
104                ErrorKind::ConfigInvalid,
105                "3FS root must be a directory",
106            ));
107        }
108        let root_str = root
109            .to_str()
110            .ok_or_else(|| Error::new(ErrorKind::ConfigInvalid, "3FS root must be valid UTF-8"))?;
111        let api = Api::load(Path::new(
112            self.config
113                .library_path
114                .as_deref()
115                .unwrap_or("libhf3fs_api_shared.so"),
116        ))?;
117        let c_root = CString::new(root.as_os_str().as_bytes())
118            .map_err(|e| Error::new(ErrorKind::ConfigInvalid, "root contains NUL").set_source(e))?;
119        let mount = api.mount_point(&c_root)?;
120        let read = IoDriver::start(api.clone(), mount.clone(), depth, block_size, true)?;
121        let write = IoDriver::start(api.clone(), mount, depth, block_size, false)?;
122        let metadata = Arc::new(opendal_service_fs::Fs::default().root(root_str).build()?);
123        Ok(Hf3fsBackend {
124            core: Arc::new(Hf3fsCore {
125                root,
126                api,
127                read,
128                write,
129            }),
130            metadata,
131        })
132    }
133}
134
135pub(crate) struct Hf3fsCore {
136    pub root: PathBuf,
137    pub api: Arc<Api>,
138    pub read: IoDriver,
139    pub write: IoDriver,
140}
141
142impl Hf3fsCore {
143    pub fn path(&self, path: &str) -> Result<PathBuf> {
144        confined_join(&self.root, path)
145    }
146}
147
148struct Hf3fsBackend {
149    core: Arc<Hf3fsCore>,
150    metadata: Servicer,
151}
152
153impl std::fmt::Debug for Hf3fsBackend {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        f.debug_struct("Hf3fsBackend")
156            .field("root", &self.core.root)
157            .finish_non_exhaustive()
158    }
159}
160
161impl Service for Hf3fsBackend {
162    type Reader = oio::PositionReader<Hf3fsReader>;
163    type Writer = Hf3fsWriter;
164    type Lister = oio::Lister;
165    type Deleter = oio::Deleter;
166    type Copier = ();
167    type Composer = ();
168
169    fn info(&self) -> ServiceInfo {
170        ServiceInfo::new(HF3FS_SCHEME, self.core.root.to_string_lossy(), "")
171    }
172
173    fn capability(&self) -> Capability {
174        Capability {
175            stat: true,
176            read: true,
177            write: true,
178            write_can_empty: true,
179            write_can_multi: true,
180            write_with_if_not_exists: true,
181            create_dir: true,
182            list: true,
183            delete: true,
184            delete_with_recursive: true,
185            rename: true,
186            shared: true,
187            ..Default::default()
188        }
189    }
190
191    fn read(&self, _: &OperationContext, path: &str, _: OpRead) -> Result<Self::Reader> {
192        Ok(oio::PositionReader::new(Hf3fsReader {
193            core: self.core.clone(),
194            path: self.core.path(path)?,
195        })
196        .with_max_buf_size(self.core.read.block_size))
197    }
198
199    fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> Result<Self::Writer> {
200        Ok(Hf3fsWriter::new(
201            self.core.clone(),
202            self.core.path(path)?,
203            ctx.executor().clone(),
204            args,
205        ))
206    }
207
208    async fn stat(&self, ctx: &OperationContext, path: &str, args: OpStat) -> Result<RpStat> {
209        self.metadata.stat(ctx, path, args).await
210    }
211
212    async fn create_dir(
213        &self,
214        ctx: &OperationContext,
215        path: &str,
216        args: OpCreateDir,
217    ) -> Result<RpCreateDir> {
218        self.metadata.create_dir(ctx, path, args).await
219    }
220
221    fn list(&self, ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
222        self.metadata.list(ctx, path, args)
223    }
224
225    fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
226        self.metadata.delete(ctx)
227    }
228
229    fn copy(&self, _: &OperationContext, _: &str, _: &str, _: OpCopy) -> Result<Self::Copier> {
230        Err(Error::new(
231            ErrorKind::Unsupported,
232            "3FS native copy is unsupported",
233        ))
234    }
235
236    async fn presign(&self, _: &OperationContext, _: &str, _: OpPresign) -> Result<RpPresign> {
237        Err(Error::new(
238            ErrorKind::Unsupported,
239            "3FS presign is unsupported",
240        ))
241    }
242
243    async fn rename(
244        &self,
245        ctx: &OperationContext,
246        from: &str,
247        to: &str,
248        args: OpRename,
249    ) -> Result<RpRename> {
250        self.metadata.rename(ctx, from, to, args).await
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use std::ffi::OsStr;
257    use std::os::unix::ffi::OsStrExt;
258    use std::os::unix::fs::symlink;
259
260    use super::*;
261
262    #[test]
263    fn builder_rejects_invalid_config_values() {
264        let dir = tempfile::tempdir().unwrap();
265        let root = dir.path().to_str().unwrap();
266
267        let err = Hf3fsBuilder::default().build().err().unwrap();
268        assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
269
270        let err = Hf3fsBuilder::default()
271            .root("relative/path")
272            .build()
273            .err()
274            .unwrap();
275        assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
276
277        let file = dir.path().join("not-a-dir");
278        std::fs::write(&file, b"data").unwrap();
279        let err = Hf3fsBuilder::default()
280            .root(file.to_str().unwrap())
281            .build()
282            .err()
283            .unwrap();
284        assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
285
286        for builder in [
287            Hf3fsBuilder::default().root(root).queue_depth(0),
288            Hf3fsBuilder::default()
289                .root(root)
290                .queue_depth(i32::MAX as usize),
291            Hf3fsBuilder::default().root(root).block_size(0),
292            Hf3fsBuilder::default()
293                .root(root)
294                .queue_depth(4)
295                .block_size(isize::MAX as usize / 2),
296        ] {
297            let err = builder.build().err().unwrap();
298            assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
299        }
300    }
301
302    #[test]
303    fn builder_rejects_non_utf8_canonical_root() {
304        let dir = tempfile::tempdir().unwrap();
305        let raw_dir = dir.path().join(OsStr::from_bytes(b"dir-\xff"));
306        std::fs::create_dir(&raw_dir).unwrap();
307        let utf8_link = dir.path().join("utf8-link");
308        symlink(&raw_dir, &utf8_link).unwrap();
309
310        let err = Hf3fsBuilder::default()
311            .root(utf8_link.to_str().unwrap())
312            .build()
313            .err()
314            .unwrap();
315        assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
316    }
317
318    #[test]
319    fn config_from_uri_parses_root_and_options() {
320        let uri = OperatorUri::new(
321            "hf3fs:///mnt/3fs/data",
322            [
323                ("queue_depth".to_string(), "16".to_string()),
324                ("block_size".to_string(), "65536".to_string()),
325                (
326                    "library_path".to_string(),
327                    "/opt/3fs/libhf3fs_api_shared.so".to_string(),
328                ),
329            ],
330        )
331        .unwrap();
332        let cfg = Hf3fsConfig::from_uri(&uri).unwrap();
333        assert_eq!(cfg.root.as_deref(), Some("/mnt/3fs/data"));
334        assert_eq!(cfg.queue_depth, Some(16));
335        assert_eq!(cfg.block_size, Some(65536));
336        assert_eq!(
337            cfg.library_path.as_deref(),
338            Some("/opt/3fs/libhf3fs_api_shared.so")
339        );
340    }
341
342    #[test]
343    fn core_path_confines_paths_to_root() {
344        let dir = tempfile::tempdir().unwrap();
345        let api = Api::noop();
346        let (read, _read_rx, _) = IoDriver::for_test(api.clone(), 2, 4096, true);
347        let (write, _write_rx, _) = IoDriver::for_test(api.clone(), 2, 4096, false);
348        let core = Hf3fsCore {
349            root: dir.path().to_path_buf(),
350            api,
351            read,
352            write,
353        };
354
355        assert_eq!(core.path("").unwrap(), dir.path());
356        assert_eq!(core.path("/").unwrap(), dir.path());
357        assert_eq!(core.path("a/b/c").unwrap(), dir.path().join("a/b/c"));
358        assert_eq!(core.path("a/b/").unwrap(), dir.path().join("a/b"));
359
360        for invalid in ["../escape", "a/../../escape", "/absolute"] {
361            let err = core.path(invalid).unwrap_err();
362            assert_eq!(err.kind(), ErrorKind::NotFound, "path: {invalid}");
363        }
364    }
365}