Xuanwo commented on code in PR #7005:
URL: https://github.com/apache/opendal/pull/7005#discussion_r2623383790


##########
core/scripts/test_wasi_fs.sh:
##########


Review Comment:
   It's better to not use scripts. We can just move those logic to github 
workflows.



##########
core/services/wasi-fs/src/lister.rs:
##########
@@ -0,0 +1,94 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::sync::Arc;
+
+use opendal_core::raw::*;
+use opendal_core::*;
+use wasi::filesystem::types::{DescriptorType, DirectoryEntryStream};
+
+use super::core::WasiFsCore;
+use super::error::parse_wasi_error;
+
+pub struct WasiFsLister {
+    stream: DirectoryEntryStream,
+    path: String,
+    returned_self: bool,
+}
+
+impl WasiFsLister {
+    pub fn new(core: Arc<WasiFsCore>, path: &str) -> Result<Self> {
+        let stream = core.read_dir(path)?;
+
+        Ok(Self {
+            stream,
+            path: path.to_string(),
+            returned_self: false,
+        })
+    }
+}
+
+/// # Safety
+///
+/// WasiFsLister only accesses WASI resources which are single-threaded in 
WASM.
+unsafe impl Sync for WasiFsLister {}
+
+impl oio::List for WasiFsLister {
+    async fn next(&mut self) -> Result<Option<oio::Entry>> {
+        if !self.returned_self {
+            self.returned_self = true;
+            let entry = oio::Entry::new(&self.path, 
Metadata::new(EntryMode::DIR));
+            return Ok(Some(entry));
+        }
+
+        // Use a loop to skip . and .. entries instead of recursion
+        loop {
+            match self.stream.read_directory_entry() {
+                Ok(Some(entry)) => {
+                    let name = entry.name;
+
+                    // Skip . and .. entries
+                    if name == "." || name == ".." {

Review Comment:
   Maybe we can just return `self` here?



##########
core/services/wasi-fs/src/writer.rs:
##########
@@ -0,0 +1,93 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::sync::Arc;
+
+use opendal_core::raw::*;
+use opendal_core::*;
+use wasi::filesystem::types::{Descriptor, DescriptorFlags, OpenFlags};
+use wasi::io::streams::OutputStream;
+
+use super::core::WasiFsCore;
+use super::error::{parse_stream_error, parse_wasi_error};
+
+pub struct WasiFsWriter {
+    file: Descriptor,
+    stream: OutputStream,
+    offset: u64,
+}
+
+impl WasiFsWriter {
+    pub fn new(core: Arc<WasiFsCore>, path: &str, args: OpWrite) -> 
Result<Self> {
+        let mut open_flags = OpenFlags::CREATE;
+
+        if !args.append() {
+            open_flags |= OpenFlags::TRUNCATE;
+        }
+
+        let file = core.open_file(path, open_flags, DescriptorFlags::WRITE)?;
+
+        let offset = if args.append() {
+            let stat = file.stat().map_err(parse_wasi_error)?;
+            stat.size
+        } else {
+            0
+        };
+
+        let stream = file.write_via_stream(offset).map_err(parse_wasi_error)?;
+
+        Ok(Self {
+            file,
+            stream,
+            offset,
+        })
+    }
+}
+
+/// # Safety
+///
+/// WasiFsWriter only accesses WASI resources which are single-threaded in 
WASM.
+unsafe impl Sync for WasiFsWriter {}
+
+impl oio::Write for WasiFsWriter {
+    async fn write(&mut self, bs: Buffer) -> Result<()> {
+        let data: Vec<u8> = bs.to_vec();
+
+        self.stream
+            .blocking_write_and_flush(&data)

Review Comment:
   We only have blocking API here? 



##########
core/services/wasi-fs/src/core.rs:
##########
@@ -0,0 +1,247 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use opendal_core::raw::*;
+use opendal_core::*;
+use wasi::filesystem::preopens::get_directories;
+use wasi::filesystem::types::{
+    Descriptor, DescriptorFlags, DescriptorStat, DescriptorType, 
DirectoryEntryStream, OpenFlags,
+    PathFlags,
+};
+
+use super::error::{parse_stream_error, parse_wasi_error};
+
+#[derive(Debug)]
+pub struct WasiFsCore {
+    /// The preopened directory descriptor we're operating within
+    root_descriptor: Descriptor,
+    /// The path within the preopened dir
+    root_path: String,
+}
+
+impl WasiFsCore {
+    pub fn new(root: &str) -> Result<Self> {
+        let mut preopens = get_directories();
+
+        if preopens.is_empty() {
+            return Err(Error::new(
+                ErrorKind::ConfigInvalid,
+                "No preopened directories available from WASI runtime",
+            ));
+        }
+
+        let (idx, preopen_path) = Self::find_preopened_dir_index(&preopens, 
root)?;
+        let (descriptor, _) = preopens.swap_remove(idx);
+
+        let root_path = if root.starts_with(&preopen_path) {
+            root.strip_prefix(&preopen_path)
+                .unwrap_or("")
+                .trim_start_matches('/')
+                .to_string()
+        } else {
+            String::new()
+        };
+
+        Ok(Self {
+            root_descriptor: descriptor,
+            root_path,
+        })
+    }
+
+    fn find_preopened_dir_index(
+        preopens: &[(Descriptor, String)],
+        root: &str,
+    ) -> Result<(usize, String)> {
+        for (idx, (_, path)) in preopens.iter().enumerate() {
+            if root.starts_with(path) || path == "/" || root == "/" || 
root.is_empty() {
+                return Ok((idx, path.clone()));
+            }
+        }
+
+        // Fall back to first preopened directory
+        if preopens.is_empty() {
+            return Err(Error::new(
+                ErrorKind::ConfigInvalid,
+                "No preopened directories",
+            ));
+        }
+
+        Ok((0, preopens[0].1.clone()))
+    }
+
+    fn build_path(&self, path: &str) -> String {
+        let path = path.trim_start_matches('/').trim_end_matches('/');
+        if self.root_path.is_empty() {
+            path.to_string()
+        } else if path.is_empty() {
+            self.root_path.clone()
+        } else {
+            format!("{}/{}", self.root_path, path)
+        }
+    }
+
+    pub fn stat(&self, path: &str) -> Result<Metadata> {
+        let abs_path = self.build_path(path);
+
+        let stat = if abs_path.is_empty() {
+            self.root_descriptor.stat().map_err(parse_wasi_error)?
+        } else {
+            self.root_descriptor
+                .stat_at(PathFlags::empty(), &abs_path)
+                .map_err(parse_wasi_error)?
+        };
+
+        Ok(Self::convert_stat(stat))
+    }
+
+    fn convert_stat(stat: DescriptorStat) -> Metadata {
+        let mode = match stat.type_ {
+            DescriptorType::Directory => EntryMode::DIR,
+            DescriptorType::RegularFile => EntryMode::FILE,
+            _ => EntryMode::Unknown,
+        };
+
+        let mut metadata = Metadata::new(mode).with_content_length(stat.size);
+
+        if let Some(mtime) = stat.data_modification_timestamp {
+            // Convert WASI timestamp (seconds + nanoseconds) to Timestamp
+            if let Ok(ts) = Timestamp::new(mtime.seconds as i64, 
mtime.nanoseconds as i32) {
+                metadata = metadata.with_last_modified(ts);
+            }
+        }
+
+        metadata
+    }
+
+    pub fn create_dir(&self, path: &str) -> Result<()> {
+        let abs_path = self.build_path(path);
+        self.root_descriptor
+            .create_directory_at(&abs_path)
+            .map_err(parse_wasi_error)
+    }
+
+    pub fn open_file(
+        &self,
+        path: &str,
+        flags: OpenFlags,
+        desc_flags: DescriptorFlags,
+    ) -> Result<Descriptor> {
+        let abs_path = self.build_path(path);
+        self.root_descriptor
+            .open_at(PathFlags::empty(), &abs_path, flags, desc_flags)
+            .map_err(parse_wasi_error)
+    }
+
+    pub fn read_dir(&self, path: &str) -> Result<DirectoryEntryStream> {
+        let abs_path = self.build_path(path);
+
+        let dir_desc = if abs_path.is_empty() {
+            // For the root, we need to open the same directory again
+            // since we can't clone the descriptor
+            self.root_descriptor
+                .read_directory()
+                .map_err(parse_wasi_error)?;
+            return self
+                .root_descriptor
+                .read_directory()
+                .map_err(parse_wasi_error);
+        } else {
+            self.root_descriptor
+                .open_at(
+                    PathFlags::empty(),
+                    &abs_path,
+                    OpenFlags::DIRECTORY,
+                    DescriptorFlags::empty(),
+                )
+                .map_err(parse_wasi_error)?
+        };
+
+        dir_desc.read_directory().map_err(parse_wasi_error)
+    }
+
+    pub fn delete_file(&self, path: &str) -> Result<()> {
+        let abs_path = self.build_path(path);
+        self.root_descriptor
+            .unlink_file_at(&abs_path)
+            .map_err(parse_wasi_error)
+    }
+
+    pub fn delete_dir(&self, path: &str) -> Result<()> {
+        let abs_path = self.build_path(path);
+        self.root_descriptor
+            .remove_directory_at(&abs_path)
+            .map_err(parse_wasi_error)
+    }
+
+    pub fn rename(&self, from: &str, to: &str) -> Result<()> {
+        let from_path = self.build_path(from);
+        let to_path = self.build_path(to);
+        self.root_descriptor
+            .rename_at(&from_path, &self.root_descriptor, &to_path)
+            .map_err(parse_wasi_error)
+    }
+
+    pub fn copy(&self, from: &str, to: &str) -> Result<()> {

Review Comment:
   We don't need to manually simulate copying if it lacks native copy support.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to