opendal_obs/services/fs/core.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::path::Path;
19use std::path::PathBuf;
20
21use uuid::Uuid;
22
23use crate::raw::*;
24use crate::*;
25
26#[derive(Debug)]
27pub struct FsCore {
28 pub root: PathBuf,
29 pub atomic_write_dir: Option<PathBuf>,
30 pub buf_pool: oio::PooledBuf,
31}
32
33impl FsCore {
34 // Synchronously build write path and ensure the parent dirs created
35 pub fn blocking_ensure_write_abs_path(&self, parent: &Path, path: &str) -> Result<PathBuf> {
36 let p = parent.join(path);
37
38 // Create dir before write path.
39 //
40 // TODO(xuanwo): There are many works to do here:
41 // - Is it safe to create dir concurrently?
42 // - Do we need to extract this logic as new util functions?
43 // - Is it better to check the parent dir exists before call mkdir?
44 let parent = PathBuf::from(&p)
45 .parent()
46 .ok_or_else(|| {
47 Error::new(
48 ErrorKind::Unexpected,
49 "path should have parent but not, it must be malformed",
50 )
51 .with_context("input", p.to_string_lossy())
52 })?
53 .to_path_buf();
54
55 std::fs::create_dir_all(parent).map_err(new_std_io_error)?;
56
57 Ok(p)
58 }
59
60 // Build write path and ensure the parent dirs created
61 pub async fn ensure_write_abs_path(&self, parent: &Path, path: &str) -> Result<PathBuf> {
62 let p = parent.join(path);
63
64 // Create dir before write path.
65 //
66 // TODO(xuanwo): There are many works to do here:
67 // - Is it safe to create dir concurrently?
68 // - Do we need to extract this logic as new util functions?
69 // - Is it better to check the parent dir exists before call mkdir?
70 let parent = PathBuf::from(&p)
71 .parent()
72 .ok_or_else(|| {
73 Error::new(
74 ErrorKind::Unexpected,
75 "path should have parent but not, it must be malformed",
76 )
77 .with_context("input", p.to_string_lossy())
78 })?
79 .to_path_buf();
80
81 tokio::fs::create_dir_all(&parent)
82 .await
83 .map_err(new_std_io_error)?;
84
85 Ok(p)
86 }
87}
88
89#[inline]
90pub fn tmp_file_of(path: &str) -> String {
91 let name = get_basename(path);
92 let uuid = Uuid::new_v4().to_string();
93
94 format!("{name}.{uuid}")
95}