You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by "JMLX42 (via GitHub)" <gi...@apache.org> on 2025/12/13 17:06:18 UTC
[PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
JMLX42 opened a new pull request, #7005:
URL: https://github.com/apache/opendal/pull/7005
## Summary
Adds a new `wasi-fs` backend that implements filesystem access via the `wasi:filesystem` interface for WebAssembly components running in WASI Preview 2 runtimes (wasmtime, wasmer).
Closes #7004
## AI Assistance Disclosure
This implementation was developed with assistance from Claude (Anthropic). The AI helped with:
- Researching OpenDAL service patterns and WASI Preview 2 APIs
- Designing the implementation architecture
- Writing the initial implementation code
- Code review and iteration
## Design Decisions
### 1. Crate Architecture
**Decision:** Split crate under `core/services/wasi-fs/` (not inline in core)
**Rationale:** Follows OpenDAL's modern service pattern (RFC 6828). Services are being migrated to separate crates for minimal compile-time impact and independent versioning.
### 2. WASI Bindings Approach
**Decision:** Use the `wasi` crate (v0.14.7) with pre-generated bindings
**Rationale:**
- Pre-generated bindings avoid build complexity of running `wit-bindgen` during compilation
- Well-maintained by Bytecode Alliance, stays in sync with WASI spec
- Simpler dependency management than checking in WIT files
### 3. Async Model
**Decision:** Wrap synchronous WASI calls directly in async methods
**Rationale:**
- WASI Preview 2 filesystem operations are fundamentally synchronous from the component's perspective
- The WASI runtime handles actual I/O scheduling, so blocking in the component doesn't block the host thread
- No `spawn_blocking` needed since there's no separate thread pool in WASM
### 4. Preopened Directory Handling
**Decision:** Match root path to preopened directories from host runtime
**Rationale:**
- Most flexible for users - they specify the desired root path
- Builder iterates preopened directories and finds the best match
- Falls back to first preopened directory if root is `/` or not specified
- Provides clear error messages if no matching preopened directory exists
### 5. Platform Restriction
**Decision:** Entire crate guarded by `#![cfg(all(target_arch = "wasm32", target_os = "wasi"))]`
**Rationale:**
- Crate only makes sense on `wasm32-wasip2` target
- Compiles to nothing on native targets (intentional)
- Feature flag can be safely enabled without conditional compilation issues
## Implementation
### Files Created
```
core/services/wasi-fs/
├── Cargo.toml # Crate manifest with wasi 0.14.7 dependency
└── src/
├── lib.rs # Module exports + auto-registration via #[ctor::ctor]
├── config.rs # WasiFsConfig (root path option)
├── backend.rs # WasiFsBuilder + WasiFsBackend (Access impl)
├── core.rs # Core WASI filesystem operations
├── reader.rs # oio::Read implementation
├── writer.rs # oio::Write implementation
├── lister.rs # oio::List implementation
├── deleter.rs # oio::OneShotDelete implementation
├── error.rs # WASI ErrorCode → OpenDAL ErrorKind mapping
└── docs.md # Service documentation
```
### Capabilities
| Capability | Supported |
|------------|-----------|
| stat | ✅ |
| read | ✅ |
| write | ✅ |
| create_dir | ✅ |
| delete | ✅ |
| list | ✅ |
| copy | ✅ (via read+write) |
| rename | ✅ |
| append | ✅ |
| atomic_write | ❌ |
### Limitations
- **No atomic writes**: `abort()` returns error since WASI doesn't provide atomic file operations
- **No file locking**: Not supported by WASI filesystem interface
- **Platform-specific**: Only compiles for `wasm32-wasip2` target
## Test Plan
- [x] `cargo check` passes on native target
- [x] `cargo check --features services-wasi-fs` passes
- [x] `cargo fmt --all` passes
- [ ] Manual testing with wasmtime (requires WASM component build)
## Usage Example
```rust
use opendal::services::WasiFs;
use opendal::Operator;
let builder = WasiFs::default().root("/data");
let op = Operator::new(builder)?.finish();
let content = op.read("hello.txt").await?;
op.write("output.txt", "Hello, WASI!").await?;
```
```bash
# Runtime invocation
wasmtime run --dir /host/path::/guest/path component.wasm
```
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on code in PR #7005:
URL: https://github.com/apache/opendal/pull/7005#discussion_r2642783472
##########
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:
OK I'll remove the custom copy impl.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on code in PR #7005:
URL: https://github.com/apache/opendal/pull/7005#discussion_r2642770655
##########
core/scripts/test_wasi_fs.sh:
##########
Review Comment:
> It's better to not use scripts. We can just move those logic to github workflows.
@Xuanwo you mean inlining the script into the github workflow?
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on PR #7005:
URL: https://github.com/apache/opendal/pull/7005#issuecomment-3649669668
## WASI Usability Investigation
While implementing integration tests, I discovered a fundamental architectural issue with using the wasi-fs service.
### The Problem
The wasi-fs service implementation is correct - `WasiFsCore` works perfectly with blocking WASI Preview 2 APIs. However, **there's no way to use it through OpenDAL's public API** because the entire Operator infrastructure depends on tokio:
1. **Async `Operator`** - Requires tokio runtime to poll futures
2. **`blocking::Operator`** - Requires `tokio::runtime::Handle` to call `block_on`:
```rust
// From core/core/src/blocking/operator.rs
pub struct Operator {
handle: tokio::runtime::Handle, // Requires tokio!
op: AsyncOperator,
}
impl Operator {
pub fn new(op: AsyncOperator) -> Result<Self> {
Ok(Self {
handle: Handle::try_current() // Needs tokio runtime
.map_err(|_| Error::new(...))?,
op,
})
}
}
```
Tokio doesn't compile for `wasm32-wasip2`:
```
error: Only features sync,macros,io-util,rt,time are supported on wasm.
```
### Current State
- ✅ `WasiFsCore` - Works (synchronous, uses WASI Preview 2 APIs directly)
- ❌ `Operator` - Cannot be used (requires async runtime)
- ❌ `blocking::Operator` - Cannot be used (requires tokio handle)
### Possible Solutions
1. **Expose `WasiFsCore` as public API** - Simple but breaks consistency with other services
2. **WASI-specific Operator** - New operator type that doesn't require tokio
3. **Alternative async runtime for WASI** - Use `smol` or `async-executor` instead of tokio
4. **Native blocking trait methods** - Let wasi-fs implement blocking methods directly without wrapping
### Questions for Maintainers
- Is WASI support a priority for OpenDAL?
- What's the preferred approach to make wasi-fs actually usable?
- Should we hold this PR until there's a path to usability?
The service implementation is complete and correct, but without a usable API, it's effectively dead code.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on code in PR #7005:
URL: https://github.com/apache/opendal/pull/7005#discussion_r2642865479
##########
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:
Fixed in 681baa1b - removed the unnecessary check and simplified the match expression.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on PR #7005:
URL: https://github.com/apache/opendal/pull/7005#issuecomment-3649687839
## Update: WASIp3 is Now Available
After further investigation, **WASI 0.3 (WASIp3) with native async support is now available**:
- **Wasmtime v39.0.0** (November 20, 2025) includes initial WASIp3 support
- Native async is implemented via the "cooperative multithreading component model proposal"
- The Component Model now supports `future<T>` and `stream<T>` types natively
### What This Means
Instead of building workarounds for WASIp2's lack of async, the wasi-fs service could be updated to target WASIp3:
| Approach | Target | Async Support | Operator Compatibility |
|----------|--------|---------------|----------------------|
| Current | WASIp2 (`wasm32-wasip2`) | None - blocking only | ❌ Requires tokio |
| Updated | WASIp3 | Native async in Component Model | ✅ Could work with standard Operator |
### Recommendation
Consider updating wasi-fs to target WASIp3 instead of building a separate `WasiBlockingOperator`. This would:
1. Use the standard `Operator` API (no special WASI path)
2. Leverage native async support in the Component Model
3. Align with the future direction of WASI
The tradeoff is that WASIp3 is newer, so runtime support may be less widespread than WASIp2. However, Wasmtime (the most common WASI runtime) already supports it.
**References:**
- [Wasmtime v39.0.0 Release Notes](https://github.com/bytecodealliance/wasmtime/releases/tag/v39.0.0)
- [Looking Ahead to WASIp3 - Fermyon](https://www.fermyon.com/blog/looking-ahead-to-wasip3)
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on code in PR #7005:
URL: https://github.com/apache/opendal/pull/7005#discussion_r2642853027
##########
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:
Thanks for the review! I investigated the WASI Preview 2 specification.
From the [wasi-filesystem WIT spec](https://github.com/WebAssembly/wasi-filesystem/blob/main/wit/types.wit), the `read-directory` function explicitly states:
> "On filesystems where directories contain entries referring to themselves and their parents, often named `.` and `..` respectively, **these entries are omitted**."
This is different from Preview 1 which included them. So:
1. The `.` and `..` check is actually dead code - they'll never be returned
2. The `returned_self` approach is necessary since we won't get `.` from WASI
3. The suggestion to "return self here" won't work because `.` never appears
I'll remove the unnecessary `.`/`..` check but keep the `returned_self` logic.
---
*Disclosure: This analysis was performed with assistance from Claude Code (AI).*
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "Xuanwo (via GitHub) via commits" <co...@opendal.apache.org>.
Xuanwo commented on PR #7005:
URL: https://github.com/apache/opendal/pull/7005#issuecomment-7091093241
> Note: This triage comment is AI-assisted.
Thanks, @JMLX42, for exploring WASI filesystem support in OpenDAL. As you found, the async `Operator` cannot run on `wasm32-wasip2` today, and this PR has no runnable Wasmtime read/write tests, so the service is effectively dead code for users.
We're closing this PR rather than carrying it forward. A fresh proposal or PR would be welcome once WASIp3 async support is usable and can be covered by real Wasmtime behavior tests. #7004 stays open to track future WASIp3 interest.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on code in PR #7005:
URL: https://github.com/apache/opendal/pull/7005#discussion_r2642893946
##########
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:
Yes, WASI Preview 2 only provides blocking APIs - this is a platform limitation.
### Comparison
| | Standard OpenDAL | WASIp2 (current) | WASIp3 (future) |
|--|------------------|------------------|-----------------|
| **Async Runtime** | tokio | None (blocking only) | Component Model native (`future<T>`, `stream<T>`) |
| **Operator** | `Operator` | Needs `WasiOperator` (blocking) | `WasiOperator` (async) |
| **Compiles for wasm32-wasip2** | ❌ | ✅ | N/A |
| **Compiles for wasm32-wasip3** | ❌ | ✅ | ✅ |
### Current State (WASIp2)
To make wasi-fs usable at the Operator level today, OpenDAL would need a `WasiOperator` that doesn't depend on tokio. This operator would use blocking calls internally since that's all WASIp2 offers.
### Future Enhancement (WASIp3)
WASI 0.3 (available in Wasmtime v39+) introduces native async support via `future<T>` and `stream<T>` in the Component Model. A future `WasiOperator` could leverage WASIp3's async primitives instead of blocking calls, aligning with OpenDAL's async-first architecture without requiring tokio.
---
*Disclosure: This response was drafted with assistance from Claude Code (AI).*
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on code in PR #7005:
URL: https://github.com/apache/opendal/pull/7005#discussion_r2642811532
##########
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:
> OK I'll remove the custom copy impl.
Just to add a bit more context:
1. WASI doesn't have native copy (no `copy_file_range` equivalent)
2. OpenDAL doesn't provide a copy fallback - if a backend doesn't support copy, users get an error
3. The `fs` service uses `tokio::fs::copy` which delegates to the OS (which *may* use `copy_file_range` on Linux or a read/write loop internally - but that's the OS's responsibility, not OpenDAL's)
IMHO, if point 3 stands for `fs`, it does sort of stand for `wasi` too. But the lack of customizable buffer size is a problem all by itself. Which is a good enough a reason to keep this a user level job and remove `copy()`.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "JMLX42 (via GitHub)" <gi...@apache.org>.
JMLX42 commented on code in PR #7005:
URL: https://github.com/apache/opendal/pull/7005#discussion_r2642827873
##########
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:
Fixed in 01f2bec9e0ac425687d741f8543b656733277a4d
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): Add wasi-fs backend using wasi:filesystem interface [opendal]
Posted by "Xuanwo (via GitHub) via commits" <co...@opendal.apache.org>.
Xuanwo closed pull request #7005: feat(services): Add wasi-fs backend using wasi:filesystem interface
URL: https://github.com/apache/opendal/pull/7005
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org