diff --git a/Cargo.lock b/Cargo.lock index c930fa36cb57..c852ee9b8368 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4197,7 +4197,6 @@ dependencies = [ name = "wasi-common" version = "42.0.0" dependencies = [ - "anyhow", "async-trait", "bitflags 2.9.4", "cap-fs-ext", @@ -4220,6 +4219,7 @@ dependencies = [ "tracing-subscriber", "wasi-common", "wasmtime", + "wasmtime-environ", "wiggle", "windows-sys 0.61.2", ] @@ -5063,7 +5063,6 @@ dependencies = [ name = "wasmtime-wasi" version = "42.0.0" dependencies = [ - "anyhow", "async-trait", "bitflags 2.9.4", "bytes", @@ -5098,7 +5097,6 @@ dependencies = [ name = "wasmtime-wasi-config" version = "42.0.0" dependencies = [ - "anyhow", "test-programs-artifacts", "tokio", "wasmtime", @@ -5109,7 +5107,6 @@ dependencies = [ name = "wasmtime-wasi-http" version = "42.0.0" dependencies = [ - "anyhow", "async-trait", "base64", "bytes", @@ -5141,7 +5138,6 @@ dependencies = [ name = "wasmtime-wasi-io" version = "42.0.0" dependencies = [ - "anyhow", "async-trait", "bytes", "futures", @@ -5152,7 +5148,6 @@ dependencies = [ name = "wasmtime-wasi-keyvalue" version = "42.0.0" dependencies = [ - "anyhow", "test-programs-artifacts", "tokio", "wasmtime", @@ -5163,7 +5158,6 @@ dependencies = [ name = "wasmtime-wasi-nn" version = "42.0.0" dependencies = [ - "anyhow", "cap-std", "libtest-mimic", "openvino", @@ -5318,13 +5312,13 @@ dependencies = [ name = "wiggle" version = "42.0.0" dependencies = [ - "anyhow", "bitflags 2.9.4", "proptest", "thiserror 2.0.17", "tokio", "tracing", "wasmtime", + "wasmtime-environ", "wiggle-macro", "wiggle-test", "witx", @@ -5334,11 +5328,11 @@ dependencies = [ name = "wiggle-generate" version = "42.0.0" dependencies = [ - "anyhow", "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.106", + "wasmtime-environ", "witx", ] @@ -5357,12 +5351,12 @@ dependencies = [ name = "wiggle-test" version = "0.0.0" dependencies = [ - "anyhow", "env_logger 0.11.5", "proptest", "thiserror 2.0.17", "tracing", "tracing-subscriber", + "wasmtime", "wiggle", ] diff --git a/crates/wasi-common/Cargo.toml b/crates/wasi-common/Cargo.toml index c0cfd179670b..fcde029fad4a 100644 --- a/crates/wasi-common/Cargo.toml +++ b/crates/wasi-common/Cargo.toml @@ -16,7 +16,6 @@ include = ["src/**/*", "tests/**/*", "witx", "README.md", "LICENSE", "build.rs"] workspace = true [dependencies] -anyhow = { workspace = true, features = ['std'] } thiserror = { workspace = true } wiggle = { workspace = true } tracing = { workspace = true } @@ -25,6 +24,7 @@ cap-rand = { workspace = true } bitflags = { workspace = true } log = { workspace = true } async-trait = { workspace = true } +wasmtime-environ = { workspace = true } # Optional, enabled by wasmtime feature: wasmtime = { workspace = true, optional = true, features = ['runtime'] } diff --git a/crates/wasi-common/src/error.rs b/crates/wasi-common/src/error.rs index 11b43ecd4952..a4e52a4efad0 100644 --- a/crates/wasi-common/src/error.rs +++ b/crates/wasi-common/src/error.rs @@ -1,5 +1,5 @@ //! wasi-common uses an [`Error`] type which represents either a preview 1 [`Errno`] enum, on -//! [`anyhow::Error`] for trapping execution. +//! [`wasmtime_environ::error::Error`] for trapping execution. //! //! The user can construct an [`Error`] out of an [`Errno`] using the `From`/`Into` traits. //! They may also use [`Error::trap`] to construct an error that traps execution. The contents diff --git a/crates/wasi-common/src/lib.rs b/crates/wasi-common/src/lib.rs index d1dd6771ec06..98caebc4e9c6 100644 --- a/crates/wasi-common/src/lib.rs +++ b/crates/wasi-common/src/lib.rs @@ -98,6 +98,8 @@ pub use sched::{Poll, WasiSched}; pub use string_array::{StringArray, StringArrayError}; pub use table::Table; +pub(crate) use wasmtime_environ::error::Error as EnvError; + // The only difference between these definitions for sync vs async is whether // the wasmtime::Funcs generated are async (& therefore need an async Store and an executor to run) // or whether they have an internal "dummy executor" that expects the implementation of all @@ -109,11 +111,12 @@ macro_rules! define_wasi { ($async_mode:tt $($bounds:tt)*) => { use wasmtime::Linker; + use wasmtime_environ::error::Result as EnvResult; pub fn add_to_linker( linker: &mut Linker, get_cx: impl Fn(&mut T) -> &mut U + Send + Sync + Copy + 'static, - ) -> anyhow::Result<()> + ) -> EnvResult<()> where U: Send + crate::snapshots::preview_0::wasi_unstable::WasiUnstable + crate::snapshots::preview_1::wasi_snapshot_preview1::WasiSnapshotPreview1, @@ -156,7 +159,7 @@ macro_rules! define_wasi { /// CLI; this would not be suitable for use in multi-tenant embeddings. #[cfg_attr(docsrs, doc(cfg(feature = "exit")))] #[cfg(feature = "exit")] -pub fn maybe_exit_on_error(e: anyhow::Error) -> anyhow::Error { +pub fn maybe_exit_on_error(e: EnvError) -> EnvError { use std::process; use wasmtime::Trap; diff --git a/crates/wasi-common/src/snapshots/preview_0.rs b/crates/wasi-common/src/snapshots/preview_0.rs index 0eda28832518..5320ddc57dff 100644 --- a/crates/wasi-common/src/snapshots/preview_0.rs +++ b/crates/wasi-common/src/snapshots/preview_0.rs @@ -5,7 +5,7 @@ use crate::sched::{ }; use crate::snapshots::preview_1::types as snapshot1_types; use crate::snapshots::preview_1::wasi_snapshot_preview1::WasiSnapshotPreview1 as Snapshot1; -use crate::{ErrorExt, WasiCtx}; +use crate::{EnvError, ErrorExt, WasiCtx}; use cap_std::time::Duration; use std::collections::HashSet; use wiggle::{GuestMemory, GuestPtr}; @@ -1004,7 +1004,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx { &mut self, memory: &mut GuestMemory<'_>, status: types::Exitcode, - ) -> anyhow::Error { + ) -> EnvError { Snapshot1::proc_exit(self, memory, status).await } @@ -1013,7 +1013,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx { _memory: &mut GuestMemory<'_>, _sig: types::Signal, ) -> Result<(), Error> { - Err(Error::trap(anyhow::Error::msg("proc_raise unsupported"))) + Err(Error::trap(EnvError::msg("proc_raise unsupported"))) } async fn sched_yield(&mut self, memory: &mut GuestMemory<'_>) -> Result<(), Error> { @@ -1038,7 +1038,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx { _ri_data: types::IovecArray, _ri_flags: types::Riflags, ) -> Result<(types::Size, types::Roflags), Error> { - Err(Error::trap(anyhow::Error::msg("sock_recv unsupported"))) + Err(Error::trap(EnvError::msg("sock_recv unsupported"))) } async fn sock_send( @@ -1048,7 +1048,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx { _si_data: types::CiovecArray, _si_flags: types::Siflags, ) -> Result { - Err(Error::trap(anyhow::Error::msg("sock_send unsupported"))) + Err(Error::trap(EnvError::msg("sock_send unsupported"))) } async fn sock_shutdown( @@ -1057,7 +1057,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx { _fd: types::Fd, _how: types::Sdflags, ) -> Result<(), Error> { - Err(Error::trap(anyhow::Error::msg("sock_shutdown unsupported"))) + Err(Error::trap(EnvError::msg("sock_shutdown unsupported"))) } } diff --git a/crates/wasi-common/src/snapshots/preview_1.rs b/crates/wasi-common/src/snapshots/preview_1.rs index feb87bb5d325..395cf49a9d8f 100644 --- a/crates/wasi-common/src/snapshots/preview_1.rs +++ b/crates/wasi-common/src/snapshots/preview_1.rs @@ -1,5 +1,5 @@ use crate::{ - I32Exit, SystemTimeSpec, WasiCtx, + EnvError, I32Exit, SystemTimeSpec, WasiCtx, dir::{DirEntry, OpenResult, ReaddirCursor, ReaddirEntity, TableDirExt}, file::{ Advice, FdFlags, FdStat, FileAccessMode, FileEntry, FileType, Filestat, OFlags, RiFlags, @@ -101,9 +101,7 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx { let now = self.clocks.system()?.now(precision).into_std(); let d = now .duration_since(std::time::SystemTime::UNIX_EPOCH) - .map_err(|_| { - Error::trap(anyhow::Error::msg("current time before unix epoch")) - })?; + .map_err(|_| Error::trap(EnvError::msg("current time before unix epoch")))?; Ok(d.as_nanos().try_into()?) } types::Clockid::Monotonic => { @@ -1135,12 +1133,12 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx { &mut self, _memory: &mut GuestMemory<'_>, status: types::Exitcode, - ) -> anyhow::Error { + ) -> EnvError { // Check that the status is within WASI's range. if status < 126 { I32Exit(status as i32).into() } else { - anyhow::Error::msg("exit with invalid exit status outside of [0..126)") + EnvError::msg("exit with invalid exit status outside of [0..126)") } } @@ -1149,7 +1147,7 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx { _memory: &mut GuestMemory<'_>, _sig: types::Signal, ) -> Result<(), Error> { - Err(Error::trap(anyhow::Error::msg("proc_raise unsupported"))) + Err(Error::trap(EnvError::msg("proc_raise unsupported"))) } async fn sched_yield(&mut self, _memory: &mut GuestMemory<'_>) -> Result<(), Error> { diff --git a/crates/wasi-common/src/snapshots/preview_1/error.rs b/crates/wasi-common/src/snapshots/preview_1/error.rs index b2164390cd78..538f8b91d0b6 100644 --- a/crates/wasi-common/src/snapshots/preview_1/error.rs +++ b/crates/wasi-common/src/snapshots/preview_1/error.rs @@ -1,3 +1,5 @@ +use wasmtime_environ::error::format_err; + pub use super::types::{Errno, Error}; pub trait ErrorExt { @@ -217,7 +219,7 @@ impl From for Error { std::io::ErrorKind::AlreadyExists => Errno::Exist.into(), std::io::ErrorKind::InvalidInput => Errno::Inval.into(), std::io::ErrorKind::WouldBlock => Errno::Again.into(), - _ => Error::trap(anyhow::anyhow!(err).context("Unknown OS error")), + _ => Error::trap(format_err!(err).context("Unknown OS error")), }, } } diff --git a/crates/wasi-common/src/sync/sched/windows.rs b/crates/wasi-common/src/sync/sched/windows.rs index a8e8580c5be1..a6f4f1fb4f8d 100644 --- a/crates/wasi-common/src/sync/sched/windows.rs +++ b/crates/wasi-common/src/sync/sched/windows.rs @@ -9,7 +9,7 @@ // taken the time to improve it. See bug #2880. use crate::sched::subscription::{RwEventFlags, Subscription}; -use crate::{Error, ErrorExt, file::WasiFile, sched::Poll}; +use crate::{EnvError, Error, ErrorExt, file::WasiFile, sched::Poll}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; use std::sync::{LazyLock, Mutex}; use std::thread; @@ -70,7 +70,7 @@ pub async fn poll_oneoff_<'a>( if !stdin_read_subs.is_empty() { let state = STDIN_POLL .lock() - .map_err(|_| Error::trap(anyhow::Error::msg("failed to take lock of STDIN_POLL")))? + .map_err(|_| Error::trap(EnvError::msg("failed to take lock of STDIN_POLL")))? .poll(waitmode)?; for readsub in stdin_read_subs.into_iter() { match state { @@ -82,7 +82,7 @@ pub async fn poll_oneoff_<'a>( PollState::Error(ref e) => { // Unfortunately, we need to deliver the Error to each of the // subscriptions, but there is no Clone on std::io::Error. So, we convert it to the - // kind, and then back to std::io::Error, and finally to anyhow::Error. + // kind, and then back to std::io::Error, and finally to EnvError. // When its time to turn this into an errno elsewhere, the error kind will // be inspected. let ekind = e.kind(); @@ -164,7 +164,7 @@ impl StdinPoll { // Clean up possibly unread result from previous poll. Ok(_) | Err(TryRecvError::Empty) => {} Err(TryRecvError::Disconnected) => { - return Err(Error::trap(anyhow::Error::msg( + return Err(Error::trap(EnvError::msg( "StdinPoll notify_rx channel closed", ))); } @@ -173,25 +173,25 @@ impl StdinPoll { // Notify the worker thread to poll stdin self.request_tx .send(()) - .map_err(|_| Error::trap(anyhow::Error::msg("request_tx channel closed")))?; + .map_err(|_| Error::trap(EnvError::msg("request_tx channel closed")))?; // Wait for the worker thread to send a readiness notification match wait_mode { WaitMode::Timeout(timeout) => match self.notify_rx.recv_timeout(timeout) { Ok(r) => Ok(r), Err(RecvTimeoutError::Timeout) => Ok(PollState::TimedOut), - Err(RecvTimeoutError::Disconnected) => Err(Error::trap(anyhow::Error::msg( + Err(RecvTimeoutError::Disconnected) => Err(Error::trap(EnvError::msg( "StdinPoll notify_rx channel closed", ))), }, WaitMode::Infinite => self .notify_rx .recv() - .map_err(|_| Error::trap(anyhow::Error::msg("StdinPoll notify_rx channel closed"))), + .map_err(|_| Error::trap(EnvError::msg("StdinPoll notify_rx channel closed"))), WaitMode::Immediate => match self.notify_rx.try_recv() { Ok(r) => Ok(r), Err(TryRecvError::Empty) => Ok(PollState::NotReady), - Err(TryRecvError::Disconnected) => Err(Error::trap(anyhow::Error::msg( + Err(TryRecvError::Disconnected) => Err(Error::trap(EnvError::msg( "StdinPoll notify_rx channel closed", ))), }, diff --git a/crates/wasi-common/src/table.rs b/crates/wasi-common/src/table.rs index 40069636786e..cd817d38c368 100644 --- a/crates/wasi-common/src/table.rs +++ b/crates/wasi-common/src/table.rs @@ -1,4 +1,4 @@ -use crate::{Error, ErrorExt}; +use crate::{EnvError, Error, ErrorExt}; use std::any::Any; use std::collections::HashMap; use std::sync::{Arc, RwLock}; @@ -37,7 +37,7 @@ impl Table { // NOTE: The performance of this new key calculation could be very bad once keys wrap // around. if inner.map.len() == u32::MAX as usize { - return Err(Error::trap(anyhow::Error::msg("table has no free keys"))); + return Err(Error::trap(EnvError::msg("table has no free keys"))); } loop { let key = inner.next_key; diff --git a/crates/wasi-common/tests/all/async_.rs b/crates/wasi-common/tests/all/async_.rs index 115059d021d8..34372e3c685f 100644 --- a/crates/wasi-common/tests/all/async_.rs +++ b/crates/wasi-common/tests/all/async_.rs @@ -52,7 +52,7 @@ async fn run(path: &str, inherit_stdio: bool) -> Result<()> { Ok(()) }; - r.map_err(move |trap: anyhow::Error| { + r.map_err(move |trap: EnvError| { let stdout = stdout .try_into_inner() .expect("sole ref to stdout") diff --git a/crates/wasi-common/tests/all/main.rs b/crates/wasi-common/tests/all/main.rs index b11d8fcc5c45..7b5106855c48 100644 --- a/crates/wasi-common/tests/all/main.rs +++ b/crates/wasi-common/tests/all/main.rs @@ -1,8 +1,8 @@ -use anyhow::Result; use std::path::Path; use tempfile::TempDir; use wasi_common::pipe::WritePipe; use wasmtime::{Linker, Module, Store}; +use wasmtime_environ::error::{Error as EnvError, Result}; pub fn prepare_workspace(exe_name: &str) -> Result { let prefix = format!("wasi_common_{exe_name}_"); diff --git a/crates/wasi-common/tests/all/sync.rs b/crates/wasi-common/tests/all/sync.rs index 4245cf8d4d7d..768d1f62ffb5 100644 --- a/crates/wasi-common/tests/all/sync.rs +++ b/crates/wasi-common/tests/all/sync.rs @@ -43,7 +43,7 @@ fn run(path: &str, inherit_stdio: bool) -> Result<()> { Ok(()) }; - r.map_err(move |trap: anyhow::Error| { + r.map_err(move |trap: EnvError| { let stdout = stdout .try_into_inner() .expect("sole ref to stdout") diff --git a/crates/wasi-config/Cargo.toml b/crates/wasi-config/Cargo.toml index 81bd61ef7184..b2e0a7987555 100644 --- a/crates/wasi-config/Cargo.toml +++ b/crates/wasi-config/Cargo.toml @@ -12,7 +12,6 @@ description = "Wasmtime implementation of the wasi-config API" workspace = true [dependencies] -anyhow = { workspace = true } wasmtime = { workspace = true, features = ["runtime", "component-model"] } [dev-dependencies] diff --git a/crates/wasi-config/src/lib.rs b/crates/wasi-config/src/lib.rs index 186fad8ebcc2..5f7443cb6cb6 100644 --- a/crates/wasi-config/src/lib.rs +++ b/crates/wasi-config/src/lib.rs @@ -66,8 +66,8 @@ #![deny(missing_docs)] -use anyhow::Result; use std::collections::HashMap; +use wasmtime::Result; use wasmtime::component::HasData; mod gen_ { diff --git a/crates/wasi-config/tests/main.rs b/crates/wasi-config/tests/main.rs index ec798025ed58..38b29e1d87d8 100644 --- a/crates/wasi-config/tests/main.rs +++ b/crates/wasi-config/tests/main.rs @@ -1,8 +1,8 @@ -use anyhow::{Result, anyhow}; use test_programs_artifacts::{CONFIG_GET_COMPONENT, foreach_config}; use wasmtime::{ - Store, + Result, Store, component::{Component, Linker, ResourceTable}, + format_err, }; use wasmtime_wasi::p2::{add_to_linker_async, bindings::Command}; use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView}; @@ -41,7 +41,7 @@ async fn run_wasi(path: &str, ctx: Ctx) -> Result<()> { .wasi_cli_run() .call_run(&mut store) .await? - .map_err(|()| anyhow!("command returned with failing exit status")) + .map_err(|()| format_err!("command returned with failing exit status")) } macro_rules! assert_test_exists { diff --git a/crates/wasi-http/Cargo.toml b/crates/wasi-http/Cargo.toml index 8e46aa4e512d..f2c25fce70ef 100644 --- a/crates/wasi-http/Cargo.toml +++ b/crates/wasi-http/Cargo.toml @@ -21,7 +21,6 @@ p3 = ["wasmtime-wasi/p3", "dep:tokio-util"] component-model-async = ["futures/alloc", "wasmtime/component-model-async"] [dependencies] -anyhow = { workspace = true } async-trait = { workspace = true } bytes = { workspace = true } futures = { workspace = true, default-features = false } diff --git a/crates/wasi-http/src/body.rs b/crates/wasi-http/src/body.rs index 0f3cb755b53a..f93b6a59b3b0 100644 --- a/crates/wasi-http/src/body.rs +++ b/crates/wasi-http/src/body.rs @@ -1,7 +1,6 @@ //! Implementation of the `wasi:http/types` interface's various body types. use crate::{bindings::http::types, types::FieldMap}; -use anyhow::anyhow; use bytes::Bytes; use http_body::{Body, Frame}; use http_body_util::BodyExt; @@ -11,6 +10,7 @@ use std::mem; use std::task::{Context, Poll}; use std::{pin::Pin, sync::Arc, time::Duration}; use tokio::sync::{mpsc, oneshot}; +use wasmtime::format_err; use wasmtime_wasi::p2::{InputStream, OutputStream, Pollable, StreamError}; use wasmtime_wasi::runtime::{AbortOnDropJoinHandle, poll_noop}; @@ -164,7 +164,7 @@ enum StreamEnd { pub struct HostIncomingBodyStream { state: IncomingBodyStreamState, buffer: Bytes, - error: Option, + error: Option, } impl HostIncomingBodyStream { @@ -613,7 +613,7 @@ impl OutputStream for BodyWriteStream { if let Some(written) = self.written.as_ref() { if !written.update(len) { let total = written.written(); - return Err(StreamError::LastOperationFailed(anyhow!( + return Err(StreamError::LastOperationFailed(format_err!( self.context.as_body_size_error(total) ))); } @@ -626,7 +626,7 @@ impl OutputStream for BodyWriteStream { // called. The call to `check_write` always guarantees that there's // at least one capacity if a write is allowed. Err(mpsc::error::TrySendError::Full(_)) => { - Err(StreamError::Trap(anyhow!("write exceeded budget"))) + Err(StreamError::Trap(format_err!("write exceeded budget"))) } // Hyper is gone so this stream is now closed. diff --git a/crates/wasi-http/src/error.rs b/crates/wasi-http/src/error.rs index 9c0a562b4189..4279bd8483f3 100644 --- a/crates/wasi-http/src/error.rs +++ b/crates/wasi-http/src/error.rs @@ -12,17 +12,17 @@ pub type HttpResult = Result; /// Modeled after [`TrappableError`](wasmtime_wasi::TrappableError). #[repr(transparent)] pub struct HttpError { - err: anyhow::Error, + err: wasmtime::Error, } impl HttpError { /// Create a new `HttpError` that represents a trap. - pub fn trap(err: impl Into) -> HttpError { + pub fn trap(err: impl Into) -> HttpError { HttpError { err: err.into() } } /// Downcast this error to an [`ErrorCode`]. - pub fn downcast(self) -> anyhow::Result { + pub fn downcast(self) -> wasmtime::Result { self.err.downcast() } diff --git a/crates/wasi-http/src/handler.rs b/crates/wasi-http/src/handler.rs index 0f6335eae977..de875b0b533e 100644 --- a/crates/wasi-http/src/handler.rs +++ b/crates/wasi-http/src/handler.rs @@ -3,7 +3,6 @@ #[cfg(feature = "p3")] use crate::p3; -use anyhow::{Result, anyhow}; use futures::stream::{FuturesUnordered, StreamExt}; use std::collections::VecDeque; use std::collections::btree_map::{BTreeMap, Entry}; @@ -21,7 +20,7 @@ use std::time::{Duration, Instant}; use tokio::sync::Notify; use wasmtime::AsContextMut; use wasmtime::component::Accessor; -use wasmtime::{Store, StoreContextMut}; +use wasmtime::{Result, Store, StoreContextMut, format_err}; /// Alternative p2 bindings generated with `exports: { default: async | store }` /// so we can use `TypedFunc::call_concurrent` with both p2 and p3 instances. @@ -174,7 +173,7 @@ pub trait HandlerState: 'static + Sync + Send { fn max_instance_concurrent_reuse_count(&self) -> usize; /// Called when a worker exits with an error. - fn handle_worker_error(&self, error: anyhow::Error); + fn handle_worker_error(&self, error: wasmtime::Error); } struct ProxyHandlerInner { @@ -446,9 +445,9 @@ where accessor.with(|mut access| write_profile(access.as_context_mut())); if timed_out { - Err(anyhow!("guest timed out")) + Err(format_err!("guest timed out")) } else { - anyhow::Ok(()) + wasmtime::error::Ok(()) } })); @@ -499,7 +498,7 @@ where if sleep.as_mut().poll(cx).is_ready() { // Deadline has been reached; kill the instance with an // error. - return Poll::Ready(Err(anyhow!("guest timed out"))); + return Poll::Ready(Err(format_err!("guest timed out"))); } } diff --git a/crates/wasi-http/src/lib.rs b/crates/wasi-http/src/lib.rs index fe50030bb33f..bcda1fe9605e 100644 --- a/crates/wasi-http/src/lib.rs +++ b/crates/wasi-http/src/lib.rs @@ -65,7 +65,7 @@ //! A standalone example of doing all this looks like: //! //! ```no_run -//! use anyhow::bail; +//! use wasmtime::bail; //! use hyper::server::conn::http1; //! use std::sync::Arc; //! use tokio::net::TcpListener; @@ -292,7 +292,7 @@ use wasmtime::component::{HasData, Linker}; /// } /// } /// ``` -pub fn add_to_linker_async(l: &mut wasmtime::component::Linker) -> anyhow::Result<()> +pub fn add_to_linker_async(l: &mut wasmtime::component::Linker) -> wasmtime::Result<()> where T: WasiHttpView + wasmtime_wasi::WasiView + 'static, { @@ -307,7 +307,7 @@ where /// example to avoid re-adding the same interfaces twice. pub fn add_only_http_to_linker_async( l: &mut wasmtime::component::Linker, -) -> anyhow::Result<()> +) -> wasmtime::Result<()> where T: WasiHttpView + 'static, { @@ -368,7 +368,7 @@ impl HasData for WasiHttp { /// } /// } /// ``` -pub fn add_to_linker_sync(l: &mut Linker) -> anyhow::Result<()> +pub fn add_to_linker_sync(l: &mut Linker) -> wasmtime::Result<()> where T: WasiHttpView + wasmtime_wasi::WasiView + 'static, { @@ -381,7 +381,7 @@ where /// /// This is useful when using [`wasmtime_wasi::p2::add_to_linker_sync`] for /// example to avoid re-adding the same interfaces twice. -pub fn add_only_http_to_linker_sync(l: &mut Linker) -> anyhow::Result<()> +pub fn add_only_http_to_linker_sync(l: &mut Linker) -> wasmtime::Result<()> where T: WasiHttpView + 'static, { diff --git a/crates/wasi-http/src/p3/body.rs b/crates/wasi-http/src/p3/body.rs index c804307f78cf..e4e9f28547ac 100644 --- a/crates/wasi-http/src/p3/body.rs +++ b/crates/wasi-http/src/p3/body.rs @@ -1,6 +1,5 @@ use crate::p3::bindings::http::types::{ErrorCode, Fields, Trailers}; use crate::p3::{WasiHttp, WasiHttpCtxView}; -use anyhow::Context as _; use bytes::Bytes; use core::iter; use core::num::NonZeroUsize; @@ -18,6 +17,7 @@ use wasmtime::component::{ Access, Destination, FutureConsumer, FutureReader, Resource, Source, StreamConsumer, StreamProducer, StreamReader, StreamResult, }; +use wasmtime::error::Context as _; use wasmtime::{AsContextMut, StoreContextMut}; /// The concrete type behind a `wasi:http/types.body` resource. diff --git a/crates/wasi-http/src/p3/host/handler.rs b/crates/wasi-http/src/p3/host/handler.rs index 44f2c6aff038..6bf52e0445a1 100644 --- a/crates/wasi-http/src/p3/host/handler.rs +++ b/crates/wasi-http/src/p3/host/handler.rs @@ -2,7 +2,6 @@ use crate::p3::bindings::http::handler::{Host, HostWithStore}; use crate::p3::bindings::http::types::{ErrorCode, Request, Response}; use crate::p3::body::{Body, BodyExt as _}; use crate::p3::{HttpError, HttpResult, WasiHttp, WasiHttpCtxView}; -use anyhow::Context as _; use core::task::{Context, Poll, Waker}; use http_body_util::BodyExt as _; use std::sync::Arc; @@ -10,6 +9,7 @@ use tokio::sync::oneshot; use tokio::task::{self, JoinHandle}; use tracing::debug; use wasmtime::component::{Accessor, Resource}; +use wasmtime::error::Context as _; /// A wrapper around [`JoinHandle`], which will [`JoinHandle::abort`] the task /// when dropped diff --git a/crates/wasi-http/src/p3/host/types.rs b/crates/wasi-http/src/p3/host/types.rs index 9a81b051eec6..35fdbdfdc713 100644 --- a/crates/wasi-http/src/p3/host/types.rs +++ b/crates/wasi-http/src/p3/host/types.rs @@ -6,7 +6,6 @@ use crate::p3::bindings::http::types::{ }; use crate::p3::body::{Body, HostBodyStreamProducer}; use crate::p3::{HeaderResult, HttpError, RequestOptionsResult, WasiHttp, WasiHttpCtxView}; -use anyhow::Context as _; use core::mem; use core::pin::Pin; use core::task::{Context, Poll, ready}; @@ -16,6 +15,7 @@ use tokio::sync::oneshot; use wasmtime::component::{ Access, FutureProducer, FutureReader, Resource, ResourceTable, StreamReader, }; +use wasmtime::error::Context as _; use wasmtime::{AsContextMut, StoreContextMut}; fn get_fields<'a>( diff --git a/crates/wasi-http/src/p3/proxy.rs b/crates/wasi-http/src/p3/proxy.rs index 74c2eb156472..eb08baa7d5a3 100644 --- a/crates/wasi-http/src/p3/proxy.rs +++ b/crates/wasi-http/src/p3/proxy.rs @@ -1,8 +1,8 @@ use crate::p3::WasiHttpView; use crate::p3::bindings::Proxy; use crate::p3::bindings::http::types::{ErrorCode, Request, Response}; -use anyhow::Context as _; use wasmtime::component::{Accessor, TaskExit}; +use wasmtime::error::Context as _; impl Proxy { /// Call `wasi:http/handler#handle` on [Proxy] getting a [Response] back. diff --git a/crates/wasi-http/src/p3/request.rs b/crates/wasi-http/src/p3/request.rs index 00c56e787e23..63072ff8e8b7 100644 --- a/crates/wasi-http/src/p3/request.rs +++ b/crates/wasi-http/src/p3/request.rs @@ -484,12 +484,12 @@ pub async fn default_send_request( mod tests { use super::*; use crate::p3::DefaultWasiHttpCtx; - use anyhow::Result; use core::future::Future; use core::pin::pin; use core::str::FromStr; use core::task::{Context, Poll, Waker}; use http_body_util::{BodyExt, Empty, Full}; + use wasmtime::Result; use wasmtime::{Engine, Store}; use wasmtime_wasi::{ResourceTable, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView}; diff --git a/crates/wasi-http/src/p3/response.rs b/crates/wasi-http/src/p3/response.rs index 5a835023ed51..b0a33efe7fbf 100644 --- a/crates/wasi-http/src/p3/response.rs +++ b/crates/wasi-http/src/p3/response.rs @@ -2,13 +2,13 @@ use crate::get_content_length; use crate::p3::bindings::http::types::ErrorCode; use crate::p3::body::{Body, GuestBody}; use crate::p3::{WasiHttpCtxView, WasiHttpView}; -use anyhow::Context as _; use bytes::Bytes; use http::{HeaderMap, StatusCode}; use http_body_util::BodyExt as _; use http_body_util::combinators::UnsyncBoxBody; use std::sync::Arc; use wasmtime::AsContextMut; +use wasmtime::error::Context as _; /// The concrete type behind a `wasi:http/types.response` resource. pub struct Response { diff --git a/crates/wasi-http/src/types.rs b/crates/wasi-http/src/types.rs index 61f4d0a9d118..253aad1ac303 100644 --- a/crates/wasi-http/src/types.rs +++ b/crates/wasi-http/src/types.rs @@ -5,13 +5,13 @@ use crate::{ bindings::http::types::{self, ErrorCode, Method, Scheme}, body::{HostIncomingBody, HyperIncomingBody, HyperOutgoingBody}, }; -use anyhow::bail; use bytes::Bytes; use http_body_util::BodyExt; use hyper::body::Body; use hyper::header::HeaderName; use std::any::Any; use std::time::Duration; +use wasmtime::bail; use wasmtime::component::{Resource, ResourceTable}; use wasmtime_wasi::p2::Pollable; use wasmtime_wasi::runtime::AbortOnDropJoinHandle; @@ -548,7 +548,7 @@ impl HostIncomingRequest { mut parts: http::request::Parts, scheme: Scheme, body: Option, - ) -> anyhow::Result { + ) -> wasmtime::Result { let authority = match parts.uri.authority() { Some(authority) => authority.to_string(), None => match parts.headers.get(http::header::HOST) { @@ -673,7 +673,7 @@ pub type FieldMap = hyper::HeaderMap; /// A handle to a future incoming response. pub type FutureIncomingResponseHandle = - AbortOnDropJoinHandle>>; + AbortOnDropJoinHandle>>; /// A response that is in the process of being received. #[derive(Debug)] @@ -694,7 +694,7 @@ pub enum HostFutureIncomingResponse { /// The response is ready. /// /// An outer error will trap while the inner error gets returned to the guest. - Ready(anyhow::Result>), + Ready(wasmtime::Result>), /// The response has been consumed. Consumed, } @@ -706,7 +706,7 @@ impl HostFutureIncomingResponse { } /// Create a new `HostFutureIncomingResponse` that is ready. - pub fn ready(result: anyhow::Result>) -> Self { + pub fn ready(result: wasmtime::Result>) -> Self { Self::Ready(result) } @@ -716,7 +716,7 @@ impl HostFutureIncomingResponse { } /// Unwrap the response, panicking if it is not ready. - pub fn unwrap_ready(self) -> anyhow::Result> { + pub fn unwrap_ready(self) -> wasmtime::Result> { match self { Self::Ready(res) => res, Self::Pending(_) | Self::Consumed => { diff --git a/crates/wasi-http/src/types_impl.rs b/crates/wasi-http/src/types_impl.rs index 802e405e92b9..23d6979b2c87 100644 --- a/crates/wasi-http/src/types_impl.rs +++ b/crates/wasi-http/src/types_impl.rs @@ -7,10 +7,10 @@ use crate::types::{ HostOutgoingRequest, HostOutgoingResponse, HostResponseOutparam, remove_forbidden_headers, }; use crate::{HttpError, HttpResult, WasiHttpImpl, WasiHttpView, get_content_length}; -use anyhow::{Context, anyhow}; use std::any::Any; use std::str::FromStr; use wasmtime::component::{Resource, ResourceTable, ResourceTableError}; +use wasmtime::{error::Context as _, format_err}; use wasmtime_wasi::p2::{DynInputStream, DynOutputStream, DynPollable}; impl crate::bindings::http::types::Host for WasiHttpImpl @@ -559,7 +559,7 @@ where _status: u16, _headers: Resource, ) -> HttpResult<()> { - Err(HttpError::trap(anyhow!("not implemented"))) + Err(HttpError::trap(format_err!("not implemented"))) } } diff --git a/crates/wasi-http/tests/all/http_server.rs b/crates/wasi-http/tests/all/http_server.rs index ce10353c7bac..956c2097fc25 100644 --- a/crates/wasi-http/tests/all/http_server.rs +++ b/crates/wasi-http/tests/all/http_server.rs @@ -1,4 +1,3 @@ -use anyhow::{Context, Result}; use http::header::CONTENT_LENGTH; use hyper::service::service_fn; use hyper::{Request, Response}; @@ -7,6 +6,7 @@ use std::net::{SocketAddr, TcpStream}; use std::thread::JoinHandle; use tokio::net::TcpListener; use tracing::{debug, trace, warn}; +use wasmtime::{Result, error::Context as _}; use wasmtime_wasi_http::io::TokioIo; async fn test( diff --git a/crates/wasi-http/tests/all/p2.rs b/crates/wasi-http/tests/all/p2.rs index bdf0946cea6f..6c7dbf4dd619 100644 --- a/crates/wasi-http/tests/all/p2.rs +++ b/crates/wasi-http/tests/all/p2.rs @@ -1,6 +1,5 @@ use crate::body; use crate::http_server::Server; -use anyhow::{Context, Result, anyhow}; use futures::{FutureExt, channel::oneshot, future, stream}; use http_body::Frame; use http_body_util::{BodyExt, Collected, Empty, StreamBody, combinators::BoxBody}; @@ -9,8 +8,10 @@ use sha2::{Digest, Sha256}; use std::{collections::HashMap, iter, net::Ipv4Addr, str, sync::Arc}; use tokio::task; use wasmtime::{ - Config, Engine, Store, + Config, Engine, Result, Store, component::{Component, Linker, ResourceTable}, + error::Context as _, + format_err, }; use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView, p2::pipe::MemoryOutputPipe}; use wasmtime_wasi_http::{ @@ -123,7 +124,7 @@ async fn run_wasi_http( send_request: Option, rejected_authority: Option, early_drop: bool, -) -> anyhow::Result>, ErrorCode>> { +) -> wasmtime::Result>, ErrorCode>> { let stdout = MemoryOutputPipe::new(4096); let stderr = MemoryOutputPipe::new(4096); let table = ResourceTable::new(); @@ -178,7 +179,7 @@ async fn run_wasi_http( .call_handle(&mut store, req, out) .await?; - Ok::<_, anyhow::Error>(()) + Ok::<_, wasmtime::Error>(()) }); if let Some(r) = receiver { @@ -207,7 +208,7 @@ async fn run_wasi_http( } #[test_log::test(tokio::test)] -async fn wasi_http_proxy_tests() -> anyhow::Result<()> { +async fn wasi_http_proxy_tests() -> wasmtime::Result<()> { let req = hyper::Request::builder() .header("custom-forbidden-header", "yes") .uri("http://example.com:8080/test-path") @@ -263,7 +264,7 @@ async fn do_wasi_http_hash_all(override_send_request: bool) -> Result<()> { move |request: http::request::Parts| { if let (Method::GET, Some(body)) = (request.method, bodies.get(request.uri.path())) { - Ok::<_, anyhow::Error>(hyper::Response::new(body::full(Bytes::copy_from_slice( + Ok::<_, wasmtime::Error>(hyper::Response::new(body::full(Bytes::copy_from_slice( body.as_bytes(), )))) } else { @@ -318,7 +319,7 @@ async fn do_wasi_http_hash_all(override_send_request: bool) -> Result<()> { // Help rustc with type inference: if false { - return Ok::<_, anyhow::Error>(()); + return Ok::<_, wasmtime::Error>(()); } } } @@ -360,17 +361,17 @@ async fn do_wasi_http_hash_all(override_send_request: bool) -> Result<()> { for line in body.lines() { let (url, hash) = line .split_once(": ") - .ok_or_else(|| anyhow!("expected string of form `: `; got {line}"))?; + .ok_or_else(|| format_err!("expected string of form `: `; got {line}"))?; let path = url .strip_prefix(&prefix) - .ok_or_else(|| anyhow!("expected string with prefix {prefix}; got {url}"))?; + .ok_or_else(|| format_err!("expected string with prefix {prefix}; got {url}"))?; let mut hasher = Sha256::new(); hasher.update( bodies .get(path) - .ok_or_else(|| anyhow!("unexpected path: {path}"))?, + .ok_or_else(|| format_err!("unexpected path: {path}"))?, ); use base64::Engine; @@ -446,7 +447,7 @@ async fn wasi_http_double_echo() -> Result<()> { if let (&Method::POST, "/echo") = (request.method(), request.uri().path()) { - Ok::<_, anyhow::Error>(hyper::Response::new( + Ok::<_, wasmtime::Error>(hyper::Response::new( request.into_body().boxed(), )) } else { @@ -467,7 +468,7 @@ async fn wasi_http_double_echo() -> Result<()> { // Help rustc with type inference: if false { - return Ok::<_, anyhow::Error>(()); + return Ok::<_, wasmtime::Error>(()); } } } diff --git a/crates/wasi-http/tests/all/p2/async_.rs b/crates/wasi-http/tests/all/p2/async_.rs index 8d94a011df0a..87caa9b3b722 100644 --- a/crates/wasi-http/tests/all/p2/async_.rs +++ b/crates/wasi-http/tests/all/p2/async_.rs @@ -16,7 +16,7 @@ async fn run(path: &str, server: &Server) -> Result<()> { wasmtime_wasi_http::add_only_http_to_linker_async(&mut linker)?; let command = Command::instantiate_async(&mut store, &component, &linker).await?; let result = command.wasi_cli_run().call_run(&mut store).await?; - result.map_err(|()| anyhow::anyhow!("run returned an error")) + result.map_err(|()| wasmtime::format_err!("run returned an error")) } #[test_log::test(tokio::test(flavor = "multi_thread"))] diff --git a/crates/wasi-http/tests/all/p2/sync.rs b/crates/wasi-http/tests/all/p2/sync.rs index 849cf405648a..5ac57caa427e 100644 --- a/crates/wasi-http/tests/all/p2/sync.rs +++ b/crates/wasi-http/tests/all/p2/sync.rs @@ -15,7 +15,7 @@ fn run(path: &str, server: &Server) -> Result<()> { wasmtime_wasi_http::add_only_http_to_linker_sync(&mut linker)?; let command = Command::instantiate(&mut store, &component, &linker)?; let result = command.wasi_cli_run().call_run(&mut store)?; - result.map_err(|()| anyhow::anyhow!("run returned an error")) + result.map_err(|()| wasmtime::format_err!("run returned an error")) } #[test_log::test] diff --git a/crates/wasi-http/tests/all/p3/mod.rs b/crates/wasi-http/tests/all/p3/mod.rs index 9dcc165b1334..b1d8273f180a 100644 --- a/crates/wasi-http/tests/all/p3/mod.rs +++ b/crates/wasi-http/tests/all/p3/mod.rs @@ -1,6 +1,4 @@ use crate::http_server::Server; -use anyhow::Result; -use anyhow::{Context as _, anyhow}; use bytes::Bytes; use flate2::Compression; use flate2::write::{DeflateDecoder, DeflateEncoder}; @@ -15,8 +13,8 @@ use test_programs_artifacts::*; use tokio::{fs, try_join}; use wasm_compose::composer::ComponentComposer; use wasm_compose::config::{Config, Dependency, Instantiation, InstantiationArg}; -use wasmtime::Store; use wasmtime::component::{Component, Linker, ResourceTable}; +use wasmtime::{Result, Store, error::Context as _, format_err}; use wasmtime_wasi::p3::bindings::Command; use wasmtime_wasi::{TrappableError, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView}; use wasmtime_wasi_http::p3::bindings::Proxy; @@ -116,7 +114,7 @@ impl WasiHttpView for Ctx { } } -async fn run_cli(path: &str, server: &Server) -> anyhow::Result<()> { +async fn run_cli(path: &str, server: &Server) -> wasmtime::Result<()> { let engine = test_programs_artifacts::engine(|config| { config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable); config.async_support(true); @@ -145,14 +143,14 @@ async fn run_cli(path: &str, server: &Server) -> anyhow::Result<()> { .context("failed to call `wasi:cli/run#run`")? .context("guest trapped")? .0 - .map_err(|()| anyhow!("`wasi:cli/run#run` failed")) + .map_err(|()| format_err!("`wasi:cli/run#run` failed")) } async fn run_http + 'static>( component_filename: &str, req: http::Request + Send + Sync + 'static>, request_body_tx: oneshot::Sender>, -) -> anyhow::Result>, Option>> { +) -> wasmtime::Result>, Option>> { let engine = test_programs_artifacts::engine(|config| { config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable); config.async_support(true); @@ -195,7 +193,7 @@ async fn run_http + 'static>( let res = rx.await?; let (parts, body) = res.into_parts(); let body = body.collect().await.context("failed to collect body")?; - anyhow::Ok(http::Response::from_parts(parts, body)) + wasmtime::error::Ok(http::Response::from_parts(parts, body)) } )?; @@ -203,55 +201,55 @@ async fn run_http + 'static>( } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_get() -> anyhow::Result<()> { +async fn p3_http_outbound_request_get() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_GET_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_timeout() -> anyhow::Result<()> { +async fn p3_http_outbound_request_timeout() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_TIMEOUT_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_post() -> anyhow::Result<()> { +async fn p3_http_outbound_request_post() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_POST_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_large_post() -> anyhow::Result<()> { +async fn p3_http_outbound_request_large_post() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_LARGE_POST_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_put() -> anyhow::Result<()> { +async fn p3_http_outbound_request_put() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_PUT_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_invalid_version() -> anyhow::Result<()> { +async fn p3_http_outbound_request_invalid_version() -> wasmtime::Result<()> { let server = Server::http2(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_INVALID_VERSION_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_invalid_header() -> anyhow::Result<()> { +async fn p3_http_outbound_request_invalid_header() -> wasmtime::Result<()> { let server = Server::http2(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_INVALID_HEADER_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_unknown_method() -> anyhow::Result<()> { +async fn p3_http_outbound_request_unknown_method() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_UNKNOWN_METHOD_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_unsupported_scheme() -> anyhow::Result<()> { +async fn p3_http_outbound_request_unsupported_scheme() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli( P3_HTTP_OUTBOUND_REQUEST_UNSUPPORTED_SCHEME_COMPONENT, @@ -261,31 +259,31 @@ async fn p3_http_outbound_request_unsupported_scheme() -> anyhow::Result<()> { } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_invalid_port() -> anyhow::Result<()> { +async fn p3_http_outbound_request_invalid_port() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_INVALID_PORT_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_invalid_dnsname() -> anyhow::Result<()> { +async fn p3_http_outbound_request_invalid_dnsname() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_INVALID_DNSNAME_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_response_build() -> anyhow::Result<()> { +async fn p3_http_outbound_request_response_build() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_RESPONSE_BUILD_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_content_length() -> anyhow::Result<()> { +async fn p3_http_outbound_request_content_length() -> wasmtime::Result<()> { let server = Server::http1(3)?; run_cli(P3_HTTP_OUTBOUND_REQUEST_CONTENT_LENGTH_COMPONENT, &server).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_http_outbound_request_missing_path_and_query() -> anyhow::Result<()> { +async fn p3_http_outbound_request_missing_path_and_query() -> wasmtime::Result<()> { let server = Server::http1(1)?; run_cli( P3_HTTP_OUTBOUND_REQUEST_MISSING_PATH_AND_QUERY_COMPONENT, @@ -295,7 +293,7 @@ async fn p3_http_outbound_request_missing_path_and_query() -> anyhow::Result<()> } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn wasi_http_proxy_tests() -> anyhow::Result<()> { +async fn wasi_http_proxy_tests() -> wasmtime::Result<()> { let req = http::Request::builder() .uri("http://example.com:8080/test-path") .method(http::Method::GET); diff --git a/crates/wasi-io/Cargo.toml b/crates/wasi-io/Cargo.toml index 70e379ea6a8f..56530c6fd313 100644 --- a/crates/wasi-io/Cargo.toml +++ b/crates/wasi-io/Cargo.toml @@ -15,7 +15,6 @@ workspace = true [dependencies] wasmtime = { workspace = true, features = ["component-model", "async", "runtime"] } -anyhow = { workspace = true } bytes = { workspace = true } async-trait = { workspace = true } futures = { workspace = true } @@ -24,7 +23,5 @@ futures = { workspace = true } default = [ "std" ] std = [ "bytes/std", - "anyhow/std", "wasmtime/std", ] - diff --git a/crates/wasi-io/src/impls.rs b/crates/wasi-io/src/impls.rs index fe366e59b533..cd3a1a705e27 100644 --- a/crates/wasi-io/src/impls.rs +++ b/crates/wasi-io/src/impls.rs @@ -4,18 +4,18 @@ use crate::streams::{DynInputStream, DynOutputStream, StreamError, StreamResult} use alloc::collections::BTreeMap; use alloc::string::String; use alloc::vec::Vec; -use anyhow::{Result, anyhow}; use core::future::Future; use core::pin::Pin; use core::task::{Context, Poll}; use wasmtime::component::{Resource, ResourceTable}; +use wasmtime::{Result, format_err}; impl poll::Host for ResourceTable { async fn poll(&mut self, pollables: Vec>) -> Result> { type ReadylistIndex = u32; if pollables.is_empty() { - return Err(anyhow!("empty poll list")); + return Err(format_err!("empty poll list")); } let mut table_futures: BTreeMap)> = BTreeMap::new(); diff --git a/crates/wasi-io/src/poll.rs b/crates/wasi-io/src/poll.rs index 1173ec2bb24e..7187db2a0328 100644 --- a/crates/wasi-io/src/poll.rs +++ b/crates/wasi-io/src/poll.rs @@ -1,8 +1,8 @@ use alloc::boxed::Box; -use anyhow::Result; use core::any::Any; use core::future::Future; use core::pin::Pin; +use wasmtime::Result; use wasmtime::component::{Resource, ResourceTable}; pub type DynFuture<'a> = Pin + Send + 'a>>; diff --git a/crates/wasi-io/src/streams.rs b/crates/wasi-io/src/streams.rs index bebd20a6a94e..9b630a7e8eb6 100644 --- a/crates/wasi-io/src/streams.rs +++ b/crates/wasi-io/src/streams.rs @@ -1,7 +1,7 @@ use crate::poll::Pollable; use alloc::boxed::Box; -use anyhow::Result; use bytes::Bytes; +use wasmtime::Result; /// `Pollable::ready()` for `InputStream` and `OutputStream` may return /// prematurely due to `io::ErrorKind::WouldBlock`. @@ -76,22 +76,22 @@ pub trait InputStream: Pollable { /// Representation of the `error` resource type in the `wasi:io/error` /// interface. /// -/// This is currently `anyhow::Error` to retain full type information for +/// This is currently `wasmtime::Error` to retain full type information for /// errors. -pub type Error = anyhow::Error; +pub type Error = wasmtime::Error; pub type StreamResult = Result; #[derive(Debug)] pub enum StreamError { Closed, - LastOperationFailed(anyhow::Error), - Trap(anyhow::Error), + LastOperationFailed(wasmtime::Error), + Trap(wasmtime::Error), } impl StreamError { pub fn trap(msg: &str) -> StreamError { - StreamError::Trap(anyhow::anyhow!("{msg}")) + StreamError::Trap(wasmtime::format_err!("{msg}")) } } diff --git a/crates/wasi-keyvalue/Cargo.toml b/crates/wasi-keyvalue/Cargo.toml index 860e37a79d41..686e69910f6c 100644 --- a/crates/wasi-keyvalue/Cargo.toml +++ b/crates/wasi-keyvalue/Cargo.toml @@ -12,7 +12,6 @@ description = "Wasmtime implementation of the wasi-keyvalue API" workspace = true [dependencies] -anyhow = { workspace = true } wasmtime = { workspace = true, features = ["runtime", "component-model", "std"] } [dev-dependencies] diff --git a/crates/wasi-keyvalue/src/lib.rs b/crates/wasi-keyvalue/src/lib.rs index 9e4e95655df8..764287e2d60e 100644 --- a/crates/wasi-keyvalue/src/lib.rs +++ b/crates/wasi-keyvalue/src/lib.rs @@ -81,8 +81,8 @@ mod generated { } use self::generated::wasi::keyvalue; -use anyhow::Result; use std::collections::HashMap; +use wasmtime::Result; use wasmtime::component::{HasData, Resource, ResourceTable, ResourceTableError}; #[doc(hidden)] diff --git a/crates/wasi-keyvalue/tests/main.rs b/crates/wasi-keyvalue/tests/main.rs index a9529441d936..21d7ad4d6345 100644 --- a/crates/wasi-keyvalue/tests/main.rs +++ b/crates/wasi-keyvalue/tests/main.rs @@ -1,8 +1,8 @@ -use anyhow::{Result, anyhow}; use test_programs_artifacts::{KEYVALUE_MAIN_COMPONENT, foreach_keyvalue}; use wasmtime::{ - Store, + Result, Store, component::{Component, Linker, ResourceTable}, + format_err, }; use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView, p2::bindings::Command}; use wasmtime_wasi_keyvalue::{WasiKeyValue, WasiKeyValueCtx, WasiKeyValueCtxBuilder}; @@ -40,7 +40,7 @@ async fn run_wasi(path: &str, ctx: Ctx) -> Result<()> { .wasi_cli_run() .call_run(&mut store) .await? - .map_err(|()| anyhow!("command returned with failing exit status")) + .map_err(|()| format_err!("command returned with failing exit status")) } macro_rules! assert_test_exists { diff --git a/crates/wasi-nn/Cargo.toml b/crates/wasi-nn/Cargo.toml index 36859a29dfa1..7bc7e0f75bc5 100644 --- a/crates/wasi-nn/Cargo.toml +++ b/crates/wasi-nn/Cargo.toml @@ -17,7 +17,6 @@ workspace = true [dependencies] # These dependencies are necessary for the WITX-generation macros to work: -anyhow = { workspace = true, features = ['std'] } wiggle = { workspace = true, features = ["wasmtime"] } # This dependency is necessary for the WIT-generation macros to work: diff --git a/crates/wasi-nn/src/backend/mod.rs b/crates/wasi-nn/src/backend/mod.rs index 608725408bb4..8ea57c195e63 100644 --- a/crates/wasi-nn/src/backend/mod.rs +++ b/crates/wasi-nn/src/backend/mod.rs @@ -115,7 +115,7 @@ impl Id { #[derive(Debug, Error)] pub enum BackendError { #[error("Failed while accessing backend")] - BackendAccess(#[from] anyhow::Error), + BackendAccess(#[from] wasmtime::Error), #[error("Failed while accessing guest module")] GuestAccess(#[from] GuestError), #[error("The backend expects {0} buffers, passed {1}")] @@ -128,7 +128,7 @@ pub enum BackendError { /// Read a file into a byte vector. #[allow(dead_code, reason = "not used on all platforms")] -fn read(path: &Path) -> anyhow::Result> { +fn read(path: &Path) -> wasmtime::Result> { let mut file = File::open(path)?; let mut buffer = vec![]; file.read_to_end(&mut buffer)?; diff --git a/crates/wasi-nn/src/backend/onnx.rs b/crates/wasi-nn/src/backend/onnx.rs index 6ee5835c70f8..7aaa6bf4ecec 100644 --- a/crates/wasi-nn/src/backend/onnx.rs +++ b/crates/wasi-nn/src/backend/onnx.rs @@ -112,14 +112,14 @@ impl OnnxExecutionContext { if i < list.len() { i } else { - return Err(BackendError::BackendAccess(anyhow::anyhow!( + return Err(BackendError::BackendAccess(wasmtime::format_err!( "incorrect tensor index: {i} >= {}", list.len() ))); } } Id::Name(n) => list.iter().position(|s| s.shape.name == n).ok_or_else(|| { - BackendError::BackendAccess(anyhow::anyhow!("unknown tensor name: {n}")) + BackendError::BackendAccess(wasmtime::format_err!("unknown tensor name: {n}")) })?, }; Ok(index) @@ -168,12 +168,12 @@ impl BackendExecutionContext for OnnxExecutionContext { if idx < self.inputs.len() { idx } else { - return Err(BackendError::BackendAccess(anyhow::anyhow!( - "Input index out of range: {idx}" - ))); + return Err(BackendError::BackendAccess( + wasmtime::format_err!("Input index out of range: {idx}"), + )); } } else { - return Err(BackendError::BackendAccess(anyhow::anyhow!( + return Err(BackendError::BackendAccess(wasmtime::format_err!( "Unknown input tensor name: {}", input.name ))); @@ -249,7 +249,7 @@ impl BackendExecutionContext for OnnxExecutionContext { if let Some(tensor) = &output.tensor { Ok(tensor.clone()) } else { - Err(BackendError::BackendAccess(anyhow::anyhow!( + Err(BackendError::BackendAccess(wasmtime::format_err!( "missing output tensor: {}; has `compute` been called?", output.shape.name ))) @@ -259,7 +259,7 @@ impl BackendExecutionContext for OnnxExecutionContext { impl From for BackendError { fn from(e: ort::Error) -> Self { - BackendError::BackendAccess(anyhow::anyhow!("{e}")) + BackendError::BackendAccess(wasmtime::format_err!("{e}")) } } @@ -300,9 +300,9 @@ impl Shape { }) } - fn matches(&self, tensor: &Tensor) -> anyhow::Result<()> { + fn matches(&self, tensor: &Tensor) -> wasmtime::Result<()> { if self.dimensions.len() != tensor.dimensions.len() { - return Err(anyhow::anyhow!( + return Err(wasmtime::format_err!( "input tensor cardinality does not match model: {:?} != {:?}", self.dimensions, tensor.dimensions @@ -311,7 +311,7 @@ impl Shape { for (&shape_dim, &tensor_dim) in self.dimensions.iter().zip(tensor.dimensions.iter()) { let tensor_dim = tensor_dim as i64; if !is_dynamic_dimension(shape_dim) && shape_dim != tensor_dim { - return Err(anyhow::anyhow!( + return Err(wasmtime::format_err!( "input tensor dimensions do not match model: {:?} != {:?}", self.dimensions, tensor.dimensions @@ -320,7 +320,7 @@ impl Shape { } } if self.ty != tensor.ty { - return Err(anyhow::anyhow!( + return Err(wasmtime::format_err!( "input tensor type does not match model: {:?} != {:?}", self.ty, tensor.ty @@ -337,7 +337,7 @@ fn convert_value_type(vt: &ValueType) -> Result<(Vec, TensorType), BackendE let ty = (*ty).try_into()?; Ok((dimensions, ty)) } - _ => Err(BackendError::BackendAccess(anyhow::anyhow!( + _ => Err(BackendError::BackendAccess(wasmtime::format_err!( "unsupported input type: {vt:?}" ))), } @@ -345,7 +345,7 @@ fn convert_value_type(vt: &ValueType) -> Result<(Vec, TensorType), BackendE fn convert_i64(i: &i64) -> Result { u32::try_from(*i).map_err(|d| -> BackendError { - anyhow::anyhow!("unable to convert dimension to u32: {d}").into() + wasmtime::format_err!("unable to convert dimension to u32: {d}").into() }) } @@ -358,7 +358,7 @@ impl TryFrom for TensorType { TensorElementType::Uint8 => Ok(TensorType::U8), TensorElementType::Int32 => Ok(TensorType::I32), TensorElementType::Int64 => Ok(TensorType::I64), - _ => Err(BackendError::BackendAccess(anyhow::anyhow!( + _ => Err(BackendError::BackendAccess(wasmtime::format_err!( "unsupported tensor type: {ty:?}" ))), } @@ -376,7 +376,7 @@ fn to_input_value(slot: &TensorSlot) -> Result<[SessionInputValue<'_>; 1], Backe .map(|d| *d as i64) // TODO: fewer conversions .collect(); let ort_tensor = OrtTensor::::from_array((dimensions, data)).map_err(|e| { - BackendError::BackendAccess(anyhow::anyhow!( + BackendError::BackendAccess(wasmtime::format_err!( "failed to create ONNX session input: {e}" )) })?; @@ -387,7 +387,7 @@ fn to_input_value(slot: &TensorSlot) -> Result<[SessionInputValue<'_>; 1], Backe } }, None => { - return Err(BackendError::BackendAccess(anyhow::anyhow!( + return Err(BackendError::BackendAccess(wasmtime::format_err!( "missing input tensor: {}", slot.shape.name ))); diff --git a/crates/wasi-nn/src/backend/openvino.rs b/crates/wasi-nn/src/backend/openvino.rs index 3e013ee7136e..ef6fc2b38a23 100644 --- a/crates/wasi-nn/src/backend/openvino.rs +++ b/crates/wasi-nn/src/backend/openvino.rs @@ -198,13 +198,13 @@ impl BackendExecutionContext for OpenvinoExecutionContext { impl From for BackendError { fn from(e: InferenceError) -> Self { - BackendError::BackendAccess(anyhow::Error::new(e)) + BackendError::BackendAccess(wasmtime::Error::new(e)) } } impl From for BackendError { fn from(e: SetupError) -> Self { - BackendError::BackendAccess(anyhow::Error::new(e)) + BackendError::BackendAccess(wasmtime::Error::new(e)) } } diff --git a/crates/wasi-nn/src/backend/pytorch.rs b/crates/wasi-nn/src/backend/pytorch.rs index 0d48577533cb..1cdf2e1b8c54 100644 --- a/crates/wasi-nn/src/backend/pytorch.rs +++ b/crates/wasi-nn/src/backend/pytorch.rs @@ -117,7 +117,7 @@ impl BackendExecutionContext for PytorchExecutionContext { Id::Index(i) => { // Check if id_type is already set and if it matches the current id type if let Some(Id::Name(_)) = self.id_type { - return Err(BackendError::BackendAccess(anyhow::anyhow!( + return Err(BackendError::BackendAccess(wasmtime::format_err!( "Cannot mix u32 and str indexes" ))); } @@ -135,7 +135,7 @@ impl BackendExecutionContext for PytorchExecutionContext { Id::Name(_) => { // Check if id_type is already set and if it matches the current id type if let Some(Id::Index(_)) = self.id_type { - return Err(BackendError::BackendAccess(anyhow::anyhow!( + return Err(BackendError::BackendAccess(wasmtime::format_err!( "Cannot mix u32 and str indexes" ))); } @@ -144,7 +144,7 @@ impl BackendExecutionContext for PytorchExecutionContext { self.id_type = Some(Id::Name(String::new())); // Provide a str value for Name } if self.inputs.get(0).is_some() { - return Err(BackendError::BackendAccess(anyhow::anyhow!( + return Err(BackendError::BackendAccess(wasmtime::format_err!( "The pytorch backend does not support multiple named inputs" ))); } else { @@ -214,7 +214,7 @@ impl BackendExecutionContext for PytorchExecutionContext { // WITX-style compute with previously set inputs None => { if self.inputs.is_empty() { - return Err(BackendError::BackendAccess(anyhow::anyhow!( + return Err(BackendError::BackendAccess(wasmtime::format_err!( "No inputs provided for inference" ))); } @@ -310,6 +310,6 @@ impl TryFrom for TensorType { impl From for BackendError { fn from(e: TchError) -> Self { - BackendError::BackendAccess(anyhow::Error::new(e)) + BackendError::BackendAccess(wasmtime::Error::new(e)) } } diff --git a/crates/wasi-nn/src/backend/winml.rs b/crates/wasi-nn/src/backend/winml.rs index 43a840f39714..c1e2af0a9902 100644 --- a/crates/wasi-nn/src/backend/winml.rs +++ b/crates/wasi-nn/src/backend/winml.rs @@ -118,7 +118,7 @@ impl WinMLExecutionContext { if i < list.Size()? { i } else { - return Err(BackendError::BackendAccess(anyhow::anyhow!( + return Err(BackendError::BackendAccess(wasmtime::format_err!( "incorrect tensor index: {i} >= {}", list.Size()? ))); @@ -128,7 +128,9 @@ impl WinMLExecutionContext { .into_iter() .position(|d| d.Name().unwrap() == name) .ok_or_else(|| { - BackendError::BackendAccess(anyhow::anyhow!("unknown tensor name: {name}")) + BackendError::BackendAccess(wasmtime::format_err!( + "unknown tensor name: {name}" + )) })? as u32, }; Ok(index) @@ -165,7 +167,7 @@ impl BackendExecutionContext for WinMLExecutionContext { .into_iter() .position(|d| d.Name().unwrap() == input.name) .ok_or_else(|| { - BackendError::BackendAccess(anyhow::anyhow!( + BackendError::BackendAccess(wasmtime::format_err!( "Unknown input tensor name: {}", input.name )) @@ -235,7 +237,7 @@ impl BackendExecutionContext for WinMLExecutionContext { ); tensor } else { - return Err(BackendError::BackendAccess(anyhow::Error::msg( + return Err(BackendError::BackendAccess(wasmtime::Error::msg( "Output is not ready.", ))); } @@ -243,7 +245,7 @@ impl BackendExecutionContext for WinMLExecutionContext { } /// Read a file into a byte vector. -fn read(path: &Path) -> anyhow::Result> { +fn read(path: &Path) -> wasmtime::Result> { let mut file = File::open(path)?; let mut buffer = vec![]; file.read_to_end(&mut buffer)?; @@ -252,7 +254,7 @@ fn read(path: &Path) -> anyhow::Result> { impl From for BackendError { fn from(e: windows::core::Error) -> Self { - BackendError::BackendAccess(anyhow::Error::new(e)) + BackendError::BackendAccess(wasmtime::Error::new(e)) } } @@ -265,7 +267,7 @@ fn dimensions_as_u32(dimensions: &IVectorView) -> Result, BackendE fn convert_i64(i: i64) -> Result { u32::try_from(i).map_err(|d| -> BackendError { - anyhow::anyhow!("unable to convert dimension to u32: {d}").into() + wasmtime::format_err!("unable to convert dimension to u32: {d}").into() }) } diff --git a/crates/wasi-nn/src/lib.rs b/crates/wasi-nn/src/lib.rs index 497650cd2b16..b826f6ababfe 100644 --- a/crates/wasi-nn/src/lib.rs +++ b/crates/wasi-nn/src/lib.rs @@ -5,17 +5,17 @@ pub mod witx; use crate::backend::{BackendError, Id, NamedTensor as BackendNamedTensor}; use crate::wit::generated_::wasi::nn::tensor::TensorType; -use anyhow::anyhow; use core::fmt; pub use registry::{GraphRegistry, InMemoryRegistry}; use std::path::Path; use std::sync::Arc; +use wasmtime::format_err; /// Construct an in-memory registry from the available backends and a list of /// `(, )`. This assumes graphs can be loaded /// from a local directory, which is a safe assumption currently for the current /// model types. -pub fn preload(preload_graphs: &[(String, String)]) -> anyhow::Result<(Vec, Registry)> { +pub fn preload(preload_graphs: &[(String, String)]) -> wasmtime::Result<(Vec, Registry)> { let mut backends = backend::list(); let mut registry = InMemoryRegistry::new(); for (kind, path) in preload_graphs { @@ -23,9 +23,9 @@ pub fn preload(preload_graphs: &[(String, String)]) -> anyhow::Result<(Vec); impl InMemoryRegistry { @@ -18,7 +18,7 @@ impl InMemoryRegistry { /// from a directory. The name used in the registry is the directory's last /// suffix: if the backend can find the files it expects in `/my/model/foo`, /// the registry will contain a new graph named `foo`. - pub fn load(&mut self, backend: &mut dyn BackendFromDir, path: &Path) -> anyhow::Result<()> { + pub fn load(&mut self, backend: &mut dyn BackendFromDir, path: &Path) -> wasmtime::Result<()> { if !path.is_dir() { bail!( "preload directory is not a valid directory: {}", @@ -28,7 +28,7 @@ impl InMemoryRegistry { let name = path .file_name() .map(|s| s.to_string_lossy()) - .ok_or(anyhow!("no file name in path"))?; + .ok_or(format_err!("no file name in path"))?; let graph = backend.load_from_dir(path, ExecutionTarget::Cpu)?; self.0.insert(name.into_owned(), graph); diff --git a/crates/wasi-nn/src/wit.rs b/crates/wasi-nn/src/wit.rs index 65c32fb1d884..32e668e277f3 100644 --- a/crates/wasi-nn/src/wit.rs +++ b/crates/wasi-nn/src/wit.rs @@ -16,11 +16,11 @@ //! [`types`]: crate::wit::types use crate::{Backend, Registry}; -use anyhow::anyhow; use std::collections::HashMap; use std::hash::Hash; use std::{fmt, str::FromStr}; use wasmtime::component::{HasData, Resource, ResourceTable}; +use wasmtime::format_err; /// Capture the state necessary for calling into the backend ML libraries. pub struct WasiNnCtx { @@ -59,7 +59,7 @@ impl<'a> WasiNnView<'a> { #[derive(Debug)] pub struct Error { code: ErrorCode, - data: anyhow::Error, + data: wasmtime::Error, } /// Construct an [`Error`] resource and immediately return it. @@ -152,7 +152,7 @@ pub use generated_::Ml as ML; pub fn add_to_linker( l: &mut wasmtime::component::Linker, f: fn(&mut T) -> WasiNnView<'_>, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { generated::graph::add_to_linker::<_, HasWasiNnView>(l, f)?; generated::tensor::add_to_linker::<_, HasWasiNnView>(l, f)?; generated::inference::add_to_linker::<_, HasWasiNnView>(l, f)?; @@ -189,7 +189,7 @@ impl generated::graph::Host for WasiNnView<'_> { bail!( self, ErrorCode::InvalidEncoding, - anyhow!("unable to find a backend for this encoding") + format_err!("unable to find a backend for this encoding") ); } } @@ -209,7 +209,7 @@ impl generated::graph::Host for WasiNnView<'_> { bail!( self, ErrorCode::NotFound, - anyhow!("failed to find graph with name: {name}") + format_err!("failed to find graph with name: {name}") ); } } @@ -334,7 +334,7 @@ impl generated::errors::HostError for WasiNnView<'_> { } ErrorCode::TooLarge => Ok(generated::errors::ErrorCode::TooLarge), ErrorCode::NotFound => Ok(generated::errors::ErrorCode::NotFound), - ErrorCode::Trap => Err(anyhow!(error.data.to_string())), + ErrorCode::Trap => Err(format_err!(error.data.to_string())), } } diff --git a/crates/wasi-nn/src/witx.rs b/crates/wasi-nn/src/witx.rs index 7aae53be0c82..3a03b41dbfaa 100644 --- a/crates/wasi-nn/src/witx.rs +++ b/crates/wasi-nn/src/witx.rs @@ -111,7 +111,7 @@ mod generated { fn nn_errno_from_wasi_nn_error( &mut self, e: WasiNnError, - ) -> anyhow::Result { + ) -> wasmtime::Result { tracing::debug!("host error: {:?}", e); match e { WasiNnError::BackendError(_) => Ok(types::NnErrno::RuntimeError), diff --git a/crates/wasi-nn/tests/check/mod.rs b/crates/wasi-nn/tests/check/mod.rs index 32e175cdff7a..c6218e28c688 100644 --- a/crates/wasi-nn/tests/check/mod.rs +++ b/crates/wasi-nn/tests/check/mod.rs @@ -31,7 +31,7 @@ pub fn artifacts_dir() -> PathBuf { } /// Retrieve the bytes at the `from` URL and place them in the `to` file. -fn download(from: &str, to: &Path) -> anyhow::Result<()> { +fn download(from: &str, to: &Path) -> wasmtime::Result<()> { let mut curl = Command::new("curl"); curl.arg("--location").arg(from).arg("--output").arg(to); println!("> downloading: {:?}", &curl); diff --git a/crates/wasi-nn/tests/check/onnx.rs b/crates/wasi-nn/tests/check/onnx.rs index 61ce907f2724..ffe941189550 100644 --- a/crates/wasi-nn/tests/check/onnx.rs +++ b/crates/wasi-nn/tests/check/onnx.rs @@ -1,6 +1,6 @@ use super::{DOWNLOAD_LOCK, artifacts_dir, download}; -use anyhow::{Context, Result}; use std::{env, fs}; +use wasmtime::{Result, error::Context as _}; /// Return `Ok` if we find the cached MobileNet test artifacts; this will /// download the artifacts if necessary. diff --git a/crates/wasi-nn/tests/check/openvino.rs b/crates/wasi-nn/tests/check/openvino.rs index d75034ed9a7d..bc41cd5b754f 100644 --- a/crates/wasi-nn/tests/check/openvino.rs +++ b/crates/wasi-nn/tests/check/openvino.rs @@ -1,6 +1,6 @@ use super::{DOWNLOAD_LOCK, artifacts_dir, download}; -use anyhow::{Context, Result, bail}; use std::fs; +use wasmtime::{Result, bail, error::Context as _}; /// Return `Ok` if we find a working OpenVINO installation. pub fn is_installed() -> Result<()> { diff --git a/crates/wasi-nn/tests/check/pytorch.rs b/crates/wasi-nn/tests/check/pytorch.rs index 5f9b2daa1199..72d981891971 100644 --- a/crates/wasi-nn/tests/check/pytorch.rs +++ b/crates/wasi-nn/tests/check/pytorch.rs @@ -1,6 +1,6 @@ use super::{DOWNLOAD_LOCK, artifacts_dir, download}; -use anyhow::{Context, Result}; use std::{env, fs}; +use wasmtime::{Result, error::Context as _}; /// Return `Ok` if we find the cached MobileNet test artifacts; this will /// download the artifacts if necessary. diff --git a/crates/wasi-nn/tests/check/winml.rs b/crates/wasi-nn/tests/check/winml.rs index a02a331169ac..0d7ca82cb9ee 100644 --- a/crates/wasi-nn/tests/check/winml.rs +++ b/crates/wasi-nn/tests/check/winml.rs @@ -1,4 +1,4 @@ -use anyhow::{Result, anyhow}; +use wasmtime::{Result, format_err}; use windows::AI::MachineLearning::{LearningModelDevice, LearningModelDeviceKind}; /// Return `Ok` if we can use WinML. @@ -10,6 +10,9 @@ pub fn is_available() -> Result<()> { ) }) { Ok(_) => Ok(()), - Err(e) => Err(anyhow!("WinML learning device is not available: {:?}", e)), + Err(e) => Err(format_err!( + "WinML learning device is not available: {:?}", + e + )), } } diff --git a/crates/wasi-nn/tests/exec/wit.rs b/crates/wasi-nn/tests/exec/wit.rs index 268dc92fa6ab..61ce65bfb648 100644 --- a/crates/wasi-nn/tests/exec/wit.rs +++ b/crates/wasi-nn/tests/exec/wit.rs @@ -1,9 +1,8 @@ use super::PREOPENED_DIR_NAME; use crate::check::artifacts_dir; -use anyhow::{Result, anyhow}; use std::path::Path; use wasmtime::component::{Component, Linker, ResourceTable}; -use wasmtime::{Config, Engine, Store}; +use wasmtime::{Config, Engine, Result, Store, format_err}; use wasmtime_wasi::p2::bindings::sync::Command; use wasmtime_wasi::{DirPerms, FilePerms, WasiCtx, WasiCtxView}; use wasmtime_wasi_nn::wit::WasiNnView; @@ -24,7 +23,7 @@ pub fn run(path: &str, backend: Backend, preload_model: bool) -> Result<()> { let mut store = Store::new(&engine, Ctx::new(&artifacts_dir(), preload_model, backend)?); let command = Command::instantiate(&mut store, &module, &linker)?; let result = command.wasi_cli_run().call_run(&mut store)?; - result.map_err(|_| anyhow!("failed to run command")) + result.map_err(|_| format_err!("failed to run command")) } /// The host state for running wasi-nn component tests. diff --git a/crates/wasi-nn/tests/exec/witx.rs b/crates/wasi-nn/tests/exec/witx.rs index b5611c941d97..5d4fa3b00f56 100644 --- a/crates/wasi-nn/tests/exec/witx.rs +++ b/crates/wasi-nn/tests/exec/witx.rs @@ -1,7 +1,7 @@ use super::PREOPENED_DIR_NAME; use crate::check::artifacts_dir; -use anyhow::Result; use std::path::Path; +use wasmtime::Result; use wasmtime::{Config, Engine, Linker, Module, Store}; use wasmtime_wasi::p1::WasiP1Ctx; use wasmtime_wasi::{DirPerms, FilePerms, WasiCtxBuilder}; diff --git a/crates/wasi-nn/tests/test-programs.rs b/crates/wasi-nn/tests/test-programs.rs index 3d8d49478e5f..98b0339b972e 100644 --- a/crates/wasi-nn/tests/test-programs.rs +++ b/crates/wasi-nn/tests/test-programs.rs @@ -16,10 +16,10 @@ mod check; mod exec; -use anyhow::Result; use libtest_mimic::{Arguments, Trial}; use std::{borrow::Cow, env}; use test_programs_artifacts::*; +use wasmtime::Result; use wasmtime_wasi_nn::{Backend, backend}; fn main() -> Result<()> { @@ -137,7 +137,7 @@ fn nn_witx_image_classification_onnx() -> Result<()> { } #[cfg(not(feature = "onnx"))] fn nn_witx_image_classification_onnx() -> Result<()> { - anyhow::bail!("this test requires the `onnx` feature") + wasmtime::bail!("this test requires the `onnx` feature") } #[cfg(all(feature = "winml", target_os = "windows"))] @@ -149,7 +149,7 @@ fn nn_witx_image_classification_winml_named() -> Result<()> { } #[cfg(not(all(feature = "winml", target_os = "windows")))] fn nn_witx_image_classification_winml_named() -> Result<()> { - anyhow::bail!("this test requires the `winml` feature and only runs on windows") + wasmtime::bail!("this test requires the `winml` feature and only runs on windows") } #[cfg(feature = "pytorch")] @@ -160,7 +160,7 @@ fn nn_witx_image_classification_pytorch() -> Result<()> { } #[cfg(not(feature = "pytorch"))] fn nn_witx_image_classification_pytorch() -> Result<()> { - anyhow::bail!("this test requires the `pytorch` feature") + wasmtime::bail!("this test requires the `pytorch` feature") } fn nn_wit_image_classification_openvino() -> Result<()> { @@ -193,7 +193,7 @@ fn nn_wit_image_classification_onnx() -> Result<()> { } #[cfg(not(feature = "onnx"))] fn nn_wit_image_classification_onnx() -> Result<()> { - anyhow::bail!("this test requires the `onnx` feature") + wasmtime::bail!("this test requires the `onnx` feature") } #[cfg(feature = "pytorch")] @@ -208,7 +208,7 @@ fn nn_wit_image_classification_pytorch() -> Result<()> { } #[cfg(not(feature = "pytorch"))] fn nn_wit_image_classification_pytorch() -> Result<()> { - anyhow::bail!("this test requires the `pytorch` feature") + wasmtime::bail!("this test requires the `pytorch` feature") } #[cfg(all(feature = "winml", target_os = "windows"))] @@ -220,7 +220,7 @@ fn nn_wit_image_classification_winml_named() -> Result<()> { } #[cfg(not(all(feature = "winml", target_os = "windows")))] fn nn_wit_image_classification_winml_named() -> Result<()> { - anyhow::bail!("this test requires the `winml` feature and only runs on windows") + wasmtime::bail!("this test requires the `winml` feature and only runs on windows") } /// Helper for keeping track of what tests should do when pre-test checks fail. diff --git a/crates/wasi/Cargo.toml b/crates/wasi/Cargo.toml index f4b0ad525ec3..9b2f95ca5d5f 100644 --- a/crates/wasi/Cargo.toml +++ b/crates/wasi/Cargo.toml @@ -18,7 +18,6 @@ workspace = true [dependencies] wasmtime = { workspace = true, features = ["runtime", "std"] } wasmtime-wasi-io = { workspace = true, features = ["std"] } -anyhow = { workspace = true } wiggle = { workspace = true, optional = true, features = ["wasmtime"] } tokio = { workspace = true, features = ["time", "sync", "io-std", "io-util", "rt", "rt-multi-thread", "net"] } bytes = { workspace = true } diff --git a/crates/wasi/src/cli.rs b/crates/wasi/src/cli.rs index a4a570395549..018e068d60d3 100644 --- a/crates/wasi/src/cli.rs +++ b/crates/wasi/src/cli.rs @@ -266,9 +266,9 @@ impl StdoutStream for Arc { mod test { use crate::cli::{AsyncStdoutStream, StdinStream, StdoutStream}; use crate::p2::{self, OutputStream}; - use anyhow::Result; use bytes::Bytes; use tokio::io::AsyncReadExt; + use wasmtime::Result; #[test] fn memory_stdin_stream() { diff --git a/crates/wasi/src/cli/file.rs b/crates/wasi/src/cli/file.rs index 9cbd702601fd..80e6d9455259 100644 --- a/crates/wasi/src/cli/file.rs +++ b/crates/wasi/src/cli/file.rs @@ -48,14 +48,14 @@ impl OutputStream for OutputFile { fn write(&mut self, bytes: Bytes) -> StreamResult<()> { (&*self.file) .write_all(&bytes) - .map_err(|e| StreamError::LastOperationFailed(anyhow::anyhow!(e))) + .map_err(|e| StreamError::LastOperationFailed(wasmtime::format_err!(e))) } fn flush(&mut self) -> StreamResult<()> { use std::io::Write; self.file .flush() - .map_err(|e| StreamError::LastOperationFailed(anyhow::anyhow!(e))) + .map_err(|e| StreamError::LastOperationFailed(wasmtime::format_err!(e))) } fn check_write(&mut self) -> StreamResult { @@ -124,7 +124,7 @@ impl InputStream for InputFile { let bytes_read = self .file .read(&mut buf) - .map_err(|e| StreamError::LastOperationFailed(anyhow::anyhow!(e)))?; + .map_err(|e| StreamError::LastOperationFailed(wasmtime::format_err!(e)))?; if bytes_read == 0 { return Err(StreamError::Closed); } diff --git a/crates/wasi/src/cli/stdout.rs b/crates/wasi/src/cli/stdout.rs index 2626d1613abf..9d0a213e528c 100644 --- a/crates/wasi/src/cli/stdout.rs +++ b/crates/wasi/src/cli/stdout.rs @@ -78,7 +78,7 @@ impl OutputStream for StdioOutputStream { StdioOutputStream::Stdout => std::io::stdout().write_all(&bytes), StdioOutputStream::Stderr => std::io::stderr().write_all(&bytes), } - .map_err(|e| p2::StreamError::LastOperationFailed(anyhow::anyhow!(e))) + .map_err(|e| p2::StreamError::LastOperationFailed(wasmtime::format_err!(e))) } fn flush(&mut self) -> p2::StreamResult<()> { @@ -86,7 +86,7 @@ impl OutputStream for StdioOutputStream { StdioOutputStream::Stdout => std::io::stdout().flush(), StdioOutputStream::Stderr => std::io::stderr().flush(), } - .map_err(|e| p2::StreamError::LastOperationFailed(anyhow::anyhow!(e))) + .map_err(|e| p2::StreamError::LastOperationFailed(wasmtime::format_err!(e))) } fn check_write(&mut self) -> p2::StreamResult { diff --git a/crates/wasi/src/ctx.rs b/crates/wasi/src/ctx.rs index b74df57dd0f1..3fa8d3c836a9 100644 --- a/crates/wasi/src/ctx.rs +++ b/crates/wasi/src/ctx.rs @@ -4,7 +4,6 @@ use crate::filesystem::{Dir, WasiFilesystemCtx}; use crate::random::WasiRandomCtx; use crate::sockets::{SocketAddrCheck, SocketAddrUse, WasiSocketsCtx}; use crate::{DirPerms, FilePerms, OpenMode}; -use anyhow::Result; use cap_rand::RngCore; use cap_std::ambient_authority; use std::future::Future; @@ -13,6 +12,7 @@ use std::net::SocketAddr; use std::path::Path; use std::pin::Pin; use tokio::io::{stderr, stdin, stdout}; +use wasmtime::Result; /// Builder-style structure used to create a [`WasiCtx`]. /// diff --git a/crates/wasi/src/error.rs b/crates/wasi/src/error.rs index f92317c1fef7..35865ab5a33f 100644 --- a/crates/wasi/src/error.rs +++ b/crates/wasi/src/error.rs @@ -23,7 +23,7 @@ impl std::error::Error for I32Exit {} /// either: /// /// * A custom error type `T` -/// * A trap, represented as `anyhow::Error` +/// * A trap, represented as `wasmtime::Error` /// /// This error is created through either the `::trap` constructor representing a /// full-fledged trap or the `From` constructor which is intended to be used @@ -43,19 +43,19 @@ impl std::error::Error for I32Exit {} /// `bindgen!` macro. #[repr(transparent)] pub struct TrappableError { - err: anyhow::Error, + err: wasmtime::Error, _marker: marker::PhantomData, } impl TrappableError { - pub fn trap(err: impl Into) -> TrappableError { + pub fn trap(err: impl Into) -> TrappableError { TrappableError { err: err.into(), _marker: marker::PhantomData, } } - pub fn downcast(self) -> anyhow::Result + pub fn downcast(self) -> wasmtime::Result where T: Error + Send + Sync + 'static, { diff --git a/crates/wasi/src/filesystem.rs b/crates/wasi/src/filesystem.rs index 0d640e40ab13..8b55b2cae6f5 100644 --- a/crates/wasi/src/filesystem.rs +++ b/crates/wasi/src/filesystem.rs @@ -1,12 +1,12 @@ use crate::clocks::Datetime; use crate::runtime::{AbortOnDropJoinHandle, spawn_blocking}; -use anyhow::Context as _; use cap_fs_ext::{FileTypeExt as _, MetadataExt as _}; use fs_set_times::SystemTimeSpec; use std::collections::hash_map; use std::sync::Arc; use tracing::debug; use wasmtime::component::{HasData, Resource, ResourceTable}; +use wasmtime::error::Context as _; /// A helper struct which implements [`HasData`] for the `wasi:filesystem` APIs. /// diff --git a/crates/wasi/src/p0.rs b/crates/wasi/src/p0.rs index 48c82a48cdc7..ef37ae43a161 100644 --- a/crates/wasi/src/p0.rs +++ b/crates/wasi/src/p0.rs @@ -12,14 +12,14 @@ use wiggle::{GuestError, GuestMemory, GuestPtr}; pub fn add_to_linker_async( linker: &mut wasmtime::Linker, f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { wasi_unstable::add_to_linker(linker, f) } pub fn add_to_linker_sync( linker: &mut wasmtime::Linker, f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { sync::add_wasi_unstable_to_linker(linker, f) } @@ -38,8 +38,8 @@ wiggle::from_witx!({ }); mod sync { - use anyhow::Result; use std::future::Future; + use wasmtime::Result; wiggle::wasmtime_integration!({ witx: ["witx/p0/wasi_unstable.witx"], @@ -550,7 +550,7 @@ impl wasi_unstable::WasiUnstable for T { &mut self, memory: &mut GuestMemory<'_>, status: types::Exitcode, - ) -> anyhow::Error { + ) -> wasmtime::Error { Snapshot1::proc_exit(self, memory, status) } @@ -585,7 +585,7 @@ impl wasi_unstable::WasiUnstable for T { _ri_data: types::IovecArray, _ri_flags: types::Riflags, ) -> Result<(types::Size, types::Roflags), Error> { - Err(Error::trap(anyhow::Error::msg("sock_recv unsupported"))) + Err(Error::trap(wasmtime::Error::msg("sock_recv unsupported"))) } fn sock_send( @@ -595,7 +595,7 @@ impl wasi_unstable::WasiUnstable for T { _si_data: types::CiovecArray, _si_flags: types::Siflags, ) -> Result { - Err(Error::trap(anyhow::Error::msg("sock_send unsupported"))) + Err(Error::trap(wasmtime::Error::msg("sock_send unsupported"))) } fn sock_shutdown( @@ -604,7 +604,9 @@ impl wasi_unstable::WasiUnstable for T { _fd: types::Fd, _how: types::Sdflags, ) -> Result<(), Error> { - Err(Error::trap(anyhow::Error::msg("sock_shutdown unsupported"))) + Err(Error::trap(wasmtime::Error::msg( + "sock_shutdown unsupported", + ))) } } diff --git a/crates/wasi/src/p1.rs b/crates/wasi/src/p1.rs index 0eea9cd8979a..cda806f4af96 100644 --- a/crates/wasi/src/p1.rs +++ b/crates/wasi/src/p1.rs @@ -76,7 +76,6 @@ use crate::p2::bindings::{ }; use crate::p2::{FsError, IsATTY}; use crate::{ResourceTable, WasiCtx, WasiCtxView, WasiView}; -use anyhow::{Context, bail}; use std::collections::{BTreeMap, BTreeSet, HashSet, btree_map}; use std::mem::{self, size_of, size_of_val}; use std::slice; @@ -84,6 +83,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use system_interface::fs::FileIoExt; use wasmtime::component::Resource; +use wasmtime::{bail, error::Context as _}; use wasmtime_wasi_io::{ bindings::wasi::io::streams, streams::{StreamError, StreamResult}, @@ -718,7 +718,7 @@ enum FdWrite { pub fn add_to_linker_async( linker: &mut wasmtime::Linker, f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { crate::p1::wasi_snapshot_preview1::add_to_linker(linker, f) } @@ -792,7 +792,7 @@ pub fn add_to_linker_async( pub fn add_to_linker_sync( linker: &mut wasmtime::Linker, f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { sync::add_wasi_snapshot_preview1_to_linker(linker, f) } @@ -815,8 +815,8 @@ wiggle::from_witx!({ }); pub(crate) mod sync { - use anyhow::Result; use std::future::Future; + use wasmtime::Result; wiggle::wasmtime_integration!({ witx: ["witx/p1/wasi_snapshot_preview1.witx"], @@ -945,7 +945,7 @@ impl From for filesystem::Advice { } impl TryFrom for types::Filetype { - type Error = anyhow::Error; + type Error = wasmtime::Error; fn try_from(ty: filesystem::DescriptorType) -> Result { match ty { @@ -2552,10 +2552,10 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiP1Ctx { &mut self, _memory: &mut GuestMemory<'_>, status: types::Exitcode, - ) -> anyhow::Error { + ) -> wasmtime::Error { // Check that the status is within WASI's range. if status >= 126 { - return anyhow::Error::msg("exit with invalid exit status outside of [0..126)"); + return wasmtime::Error::msg("exit with invalid exit status outside of [0..126)"); } crate::I32Exit(status as i32).into() } diff --git a/crates/wasi/src/p2/filesystem.rs b/crates/wasi/src/p2/filesystem.rs index 608349dcbeeb..e01129710f16 100644 --- a/crates/wasi/src/p2/filesystem.rs +++ b/crates/wasi/src/p2/filesystem.rs @@ -3,10 +3,10 @@ use crate::filesystem::File; use crate::p2::bindings::filesystem::types; use crate::p2::{InputStream, OutputStream, Pollable, StreamError, StreamResult}; use crate::runtime::AbortOnDropJoinHandle; -use anyhow::anyhow; use bytes::{Bytes, BytesMut}; use std::io; use std::mem; +use wasmtime::format_err; pub type FsResult = Result; @@ -287,7 +287,7 @@ impl OutputStream for FileOutputStream { OutputState::Closed => return Err(StreamError::Closed), OutputState::Waiting(_) | OutputState::Error(_) => { // a write is pending - this call was not permitted - return Err(StreamError::Trap(anyhow!( + return Err(StreamError::Trap(format_err!( "write not permitted: check_write not called first" ))); } diff --git a/crates/wasi/src/p2/host/clocks.rs b/crates/wasi/src/p2/host/clocks.rs index 95dee36fcf6a..f4ec0d99fe2a 100644 --- a/crates/wasi/src/p2/host/clocks.rs +++ b/crates/wasi/src/p2/host/clocks.rs @@ -47,7 +47,7 @@ impl TryFrom for Datetime { } impl wall_clock::Host for WasiClocksCtxView<'_> { - fn now(&mut self) -> anyhow::Result { + fn now(&mut self) -> wasmtime::Result { let now = self.ctx.wall_clock.now(); Ok(Datetime { seconds: now.as_secs(), @@ -55,7 +55,7 @@ impl wall_clock::Host for WasiClocksCtxView<'_> { }) } - fn resolution(&mut self) -> anyhow::Result { + fn resolution(&mut self) -> wasmtime::Result { let res = self.ctx.wall_clock.resolution(); Ok(Datetime { seconds: res.as_secs(), @@ -67,7 +67,7 @@ impl wall_clock::Host for WasiClocksCtxView<'_> { fn subscribe_to_duration( table: &mut wasmtime::component::ResourceTable, duration: tokio::time::Duration, -) -> anyhow::Result> { +) -> wasmtime::Result> { let sleep = if duration.is_zero() { table.push(Deadline::Past)? } else if let Some(deadline) = tokio::time::Instant::now().checked_add(duration) { @@ -84,15 +84,15 @@ fn subscribe_to_duration( } impl monotonic_clock::Host for WasiClocksCtxView<'_> { - fn now(&mut self) -> anyhow::Result { + fn now(&mut self) -> wasmtime::Result { Ok(self.ctx.monotonic_clock.now()) } - fn resolution(&mut self) -> anyhow::Result { + fn resolution(&mut self) -> wasmtime::Result { Ok(self.ctx.monotonic_clock.resolution()) } - fn subscribe_instant(&mut self, when: Instant) -> anyhow::Result> { + fn subscribe_instant(&mut self, when: Instant) -> wasmtime::Result> { let clock_now = self.ctx.monotonic_clock.now(); let duration = if when > clock_now { Duration::from_nanos(when - clock_now) @@ -105,7 +105,7 @@ impl monotonic_clock::Host for WasiClocksCtxView<'_> { fn subscribe_duration( &mut self, duration: WasiDuration, - ) -> anyhow::Result> { + ) -> wasmtime::Result> { subscribe_to_duration(self.table, Duration::from_nanos(duration)) } } diff --git a/crates/wasi/src/p2/host/env.rs b/crates/wasi/src/p2/host/env.rs index 0ca8d1c703ac..550f9938bafd 100644 --- a/crates/wasi/src/p2/host/env.rs +++ b/crates/wasi/src/p2/host/env.rs @@ -2,13 +2,13 @@ use crate::cli::WasiCliCtxView; use crate::p2::bindings::cli::environment; impl environment::Host for WasiCliCtxView<'_> { - fn get_environment(&mut self) -> anyhow::Result> { + fn get_environment(&mut self) -> wasmtime::Result> { Ok(self.ctx.environment.clone()) } - fn get_arguments(&mut self) -> anyhow::Result> { + fn get_arguments(&mut self) -> wasmtime::Result> { Ok(self.ctx.arguments.clone()) } - fn initial_cwd(&mut self) -> anyhow::Result> { + fn initial_cwd(&mut self) -> wasmtime::Result> { Ok(self.ctx.initial_cwd.clone()) } } diff --git a/crates/wasi/src/p2/host/exit.rs b/crates/wasi/src/p2/host/exit.rs index 3e5253f4b8e5..76cb8dcfe945 100644 --- a/crates/wasi/src/p2/host/exit.rs +++ b/crates/wasi/src/p2/host/exit.rs @@ -3,15 +3,15 @@ use crate::cli::WasiCliCtxView; use crate::p2::bindings::cli::exit; impl exit::Host for WasiCliCtxView<'_> { - fn exit(&mut self, status: Result<(), ()>) -> anyhow::Result<()> { + fn exit(&mut self, status: Result<(), ()>) -> wasmtime::Result<()> { let status = match status { Ok(()) => 0, Err(()) => 1, }; - Err(anyhow::anyhow!(I32Exit(status))) + Err(wasmtime::format_err!(I32Exit(status))) } - fn exit_with_code(&mut self, status_code: u8) -> anyhow::Result<()> { - Err(anyhow::anyhow!(I32Exit(status_code.into()))) + fn exit_with_code(&mut self, status_code: u8) -> wasmtime::Result<()> { + Err(wasmtime::format_err!(I32Exit(status_code.into()))) } } diff --git a/crates/wasi/src/p2/host/filesystem.rs b/crates/wasi/src/p2/host/filesystem.rs index 7e10d6d665a1..1bd63d3b3f62 100644 --- a/crates/wasi/src/p2/host/filesystem.rs +++ b/crates/wasi/src/p2/host/filesystem.rs @@ -19,14 +19,14 @@ impl preopens::Host for WasiFilesystemCtxView<'_> { } impl types::Host for WasiFilesystemCtxView<'_> { - fn convert_error_code(&mut self, err: FsError) -> anyhow::Result { + fn convert_error_code(&mut self, err: FsError) -> wasmtime::Result { err.downcast() } fn filesystem_error_code( &mut self, - err: Resource, - ) -> anyhow::Result> { + err: Resource, + ) -> wasmtime::Result> { let err = self.table.get(&err)?; // Currently `err` always comes from the stream implementation which @@ -303,7 +303,7 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> { Ok(fd) } - fn drop(&mut self, fd: Resource) -> anyhow::Result<()> { + fn drop(&mut self, fd: Resource) -> wasmtime::Result<()> { // The Drop will close the file/dir, but if the close syscall // blocks the thread, I will face god and walk backwards into hell. // tokio::fs::File just uses std::fs::File's Drop impl to close, so @@ -436,7 +436,7 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> { &mut self, a: Resource, b: Resource, - ) -> anyhow::Result { + ) -> wasmtime::Result { let descriptor_a = self.table.get(&a)?; let descriptor_b = self.table.get(&b)?; descriptor_a.is_same_object(descriptor_b).await @@ -470,7 +470,7 @@ impl HostDirectoryEntryStream for WasiFilesystemCtxView<'_> { readdir.next() } - fn drop(&mut self, stream: Resource) -> anyhow::Result<()> { + fn drop(&mut self, stream: Resource) -> wasmtime::Result<()> { self.table.delete(stream)?; Ok(()) } diff --git a/crates/wasi/src/p2/host/filesystem/sync.rs b/crates/wasi/src/p2/host/filesystem/sync.rs index f20a986bf98c..c0e974fd6d48 100644 --- a/crates/wasi/src/p2/host/filesystem/sync.rs +++ b/crates/wasi/src/p2/host/filesystem/sync.rs @@ -7,14 +7,14 @@ use crate::runtime::in_tokio; use wasmtime::component::Resource; impl sync_filesystem::Host for WasiFilesystemCtxView<'_> { - fn convert_error_code(&mut self, err: FsError) -> anyhow::Result { + fn convert_error_code(&mut self, err: FsError) -> wasmtime::Result { Ok(async_filesystem::Host::convert_error_code(self, err)?.into()) } fn filesystem_error_code( &mut self, err: Resource, - ) -> anyhow::Result> { + ) -> wasmtime::Result> { Ok(async_filesystem::Host::filesystem_error_code(self, err)?.map(|e| e.into())) } } @@ -191,7 +191,7 @@ impl sync_filesystem::HostDescriptor for WasiFilesystemCtxView<'_> { }) } - fn drop(&mut self, fd: Resource) -> anyhow::Result<()> { + fn drop(&mut self, fd: Resource) -> wasmtime::Result<()> { async_filesystem::HostDescriptor::drop(self, fd) } @@ -277,7 +277,7 @@ impl sync_filesystem::HostDescriptor for WasiFilesystemCtxView<'_> { &mut self, a: Resource, b: Resource, - ) -> anyhow::Result { + ) -> wasmtime::Result { in_tokio(async { async_filesystem::HostDescriptor::is_same_object(self, a, b).await }) } fn metadata_hash( @@ -317,7 +317,7 @@ impl sync_filesystem::HostDirectoryEntryStream for WasiFilesystemCtxView<'_> { fn drop( &mut self, stream: Resource, - ) -> anyhow::Result<()> { + ) -> wasmtime::Result<()> { async_filesystem::HostDirectoryEntryStream::drop(self, stream) } } diff --git a/crates/wasi/src/p2/host/instance_network.rs b/crates/wasi/src/p2/host/instance_network.rs index 9029181d0a46..c985d40645cf 100644 --- a/crates/wasi/src/p2/host/instance_network.rs +++ b/crates/wasi/src/p2/host/instance_network.rs @@ -4,7 +4,7 @@ use crate::sockets::WasiSocketsCtxView; use wasmtime::component::Resource; impl instance_network::Host for WasiSocketsCtxView<'_> { - fn instance_network(&mut self) -> Result, anyhow::Error> { + fn instance_network(&mut self) -> Result, wasmtime::Error> { let network = Network { socket_addr_check: self.ctx.socket_addr_check.clone(), allow_ip_name_lookup: self.ctx.allowed_network_uses.ip_name_lookup, diff --git a/crates/wasi/src/p2/host/io.rs b/crates/wasi/src/p2/host/io.rs index 1baa67e01d63..4ab4e8b09b08 100644 --- a/crates/wasi/src/p2/host/io.rs +++ b/crates/wasi/src/p2/host/io.rs @@ -20,13 +20,13 @@ impl From for streams::StreamError { } impl streams::Host for ResourceTable { - fn convert_stream_error(&mut self, err: StreamError) -> anyhow::Result { + fn convert_stream_error(&mut self, err: StreamError) -> wasmtime::Result { Ok(AsyncHost::convert_stream_error(self, err)?.into()) } } impl streams::HostOutputStream for ResourceTable { - fn drop(&mut self, stream: Resource) -> anyhow::Result<()> { + fn drop(&mut self, stream: Resource) -> wasmtime::Result<()> { in_tokio(async { AsyncHostOutputStream::drop(self, stream).await }) } @@ -58,7 +58,10 @@ impl streams::HostOutputStream for ResourceTable { }) } - fn subscribe(&mut self, stream: Resource) -> anyhow::Result> { + fn subscribe( + &mut self, + stream: Resource, + ) -> wasmtime::Result> { Ok(AsyncHostOutputStream::subscribe(self, stream)?) } @@ -99,7 +102,7 @@ impl streams::HostOutputStream for ResourceTable { } impl streams::HostInputStream for ResourceTable { - fn drop(&mut self, stream: Resource) -> anyhow::Result<()> { + fn drop(&mut self, stream: Resource) -> wasmtime::Result<()> { in_tokio(async { AsyncHostInputStream::drop(self, stream).await }) } @@ -119,7 +122,7 @@ impl streams::HostInputStream for ResourceTable { in_tokio(async { AsyncHostInputStream::blocking_skip(self, stream, len).await }) } - fn subscribe(&mut self, stream: Resource) -> anyhow::Result> { + fn subscribe(&mut self, stream: Resource) -> wasmtime::Result> { AsyncHostInputStream::subscribe(self, stream) } } diff --git a/crates/wasi/src/p2/host/network.rs b/crates/wasi/src/p2/host/network.rs index e0fd31f47722..0d0b06559be6 100644 --- a/crates/wasi/src/p2/host/network.rs +++ b/crates/wasi/src/p2/host/network.rs @@ -5,17 +5,17 @@ use crate::p2::bindings::sockets::network::{ }; use crate::sockets::WasiSocketsCtxView; use crate::sockets::util::{from_ipv4_addr, from_ipv6_addr, to_ipv4_addr, to_ipv6_addr}; -use anyhow::Error; use rustix::io::Errno; use std::io; +use wasmtime::Error; use wasmtime::component::Resource; impl network::Host for WasiSocketsCtxView<'_> { - fn convert_error_code(&mut self, error: SocketError) -> anyhow::Result { + fn convert_error_code(&mut self, error: SocketError) -> wasmtime::Result { error.downcast() } - fn network_error_code(&mut self, err: Resource) -> anyhow::Result> { + fn network_error_code(&mut self, err: Resource) -> wasmtime::Result> { let err = self.table.get(&err)?; if let Some(err) = err.downcast_ref::() { @@ -27,7 +27,7 @@ impl network::Host for WasiSocketsCtxView<'_> { } impl crate::p2::bindings::sockets::network::HostNetwork for WasiSocketsCtxView<'_> { - fn drop(&mut self, this: Resource) -> Result<(), anyhow::Error> { + fn drop(&mut self, this: Resource) -> Result<(), wasmtime::Error> { self.table.delete(this)?; Ok(()) diff --git a/crates/wasi/src/p2/host/random.rs b/crates/wasi/src/p2/host/random.rs index aac8457a9fa3..86bf5d374ef5 100644 --- a/crates/wasi/src/p2/host/random.rs +++ b/crates/wasi/src/p2/host/random.rs @@ -3,33 +3,33 @@ use crate::random::WasiRandomCtx; use cap_rand::{Rng, distributions::Standard}; impl random::Host for WasiRandomCtx { - fn get_random_bytes(&mut self, len: u64) -> anyhow::Result> { + fn get_random_bytes(&mut self, len: u64) -> wasmtime::Result> { Ok((&mut self.random) .sample_iter(Standard) .take(len as usize) .collect()) } - fn get_random_u64(&mut self) -> anyhow::Result { + fn get_random_u64(&mut self) -> wasmtime::Result { Ok(self.random.sample(Standard)) } } impl insecure::Host for WasiRandomCtx { - fn get_insecure_random_bytes(&mut self, len: u64) -> anyhow::Result> { + fn get_insecure_random_bytes(&mut self, len: u64) -> wasmtime::Result> { Ok((&mut self.insecure_random) .sample_iter(Standard) .take(len as usize) .collect()) } - fn get_insecure_random_u64(&mut self) -> anyhow::Result { + fn get_insecure_random_u64(&mut self) -> wasmtime::Result { Ok(self.insecure_random.sample(Standard)) } } impl insecure_seed::Host for WasiRandomCtx { - fn insecure_seed(&mut self) -> anyhow::Result<(u64, u64)> { + fn insecure_seed(&mut self) -> wasmtime::Result<(u64, u64)> { let seed: u128 = self.insecure_random_seed; Ok((seed as u64, (seed >> 64) as u64)) } diff --git a/crates/wasi/src/p2/host/tcp.rs b/crates/wasi/src/p2/host/tcp.rs index a0ac1ee9fa63..47d638dd4b6c 100644 --- a/crates/wasi/src/p2/host/tcp.rs +++ b/crates/wasi/src/p2/host/tcp.rs @@ -123,7 +123,7 @@ impl crate::p2::host::tcp::tcp::HostTcpSocket for WasiSocketsCtxView<'_> { Ok(socket.remote_address()?.into()) } - fn is_listening(&mut self, this: Resource) -> Result { + fn is_listening(&mut self, this: Resource) -> Result { let socket = self.table.get(&this)?; Ok(socket.is_listening()) @@ -132,7 +132,7 @@ impl crate::p2::host::tcp::tcp::HostTcpSocket for WasiSocketsCtxView<'_> { fn address_family( &mut self, this: Resource, - ) -> Result { + ) -> Result { let socket = self.table.get(&this)?; Ok(socket.address_family().into()) } @@ -240,7 +240,7 @@ impl crate::p2::host::tcp::tcp::HostTcpSocket for WasiSocketsCtxView<'_> { Ok(()) } - fn subscribe(&mut self, this: Resource) -> anyhow::Result> { + fn subscribe(&mut self, this: Resource) -> wasmtime::Result> { wasmtime_wasi_io::poll::subscribe(self.table, this) } @@ -262,7 +262,7 @@ impl crate::p2::host::tcp::tcp::HostTcpSocket for WasiSocketsCtxView<'_> { Ok(()) } - fn drop(&mut self, this: Resource) -> Result<(), anyhow::Error> { + fn drop(&mut self, this: Resource) -> Result<(), wasmtime::Error> { // As in the filesystem implementation, we assume closing a socket // doesn't block. let dropped = self.table.delete(this)?; diff --git a/crates/wasi/src/p2/host/udp.rs b/crates/wasi/src/p2/host/udp.rs index c9ce15a403eb..1ef83503994b 100644 --- a/crates/wasi/src/p2/host/udp.rs +++ b/crates/wasi/src/p2/host/udp.rs @@ -6,11 +6,11 @@ use crate::sockets::util::{is_valid_address_family, is_valid_remote_address}; use crate::sockets::{ MAX_UDP_DATAGRAM_SIZE, SocketAddrUse, SocketAddressFamily, UdpSocket, WasiSocketsCtxView, }; -use anyhow::anyhow; use async_trait::async_trait; use std::net::SocketAddr; use tokio::io::Interest; use wasmtime::component::Resource; +use wasmtime::format_err; use wasmtime_wasi_io::poll::DynPollable; impl udp::Host for WasiSocketsCtxView<'_> {} @@ -52,7 +52,9 @@ impl udp::HostUdpSocket for WasiSocketsCtxView<'_> { .any(|c| c.is::() || c.is::()); if has_active_streams { - return Err(SocketError::trap(anyhow!("UDP streams not dropped yet"))); + return Err(SocketError::trap(format_err!( + "UDP streams not dropped yet" + ))); } let socket = self.table.get_mut(&this)?; @@ -113,7 +115,7 @@ impl udp::HostUdpSocket for WasiSocketsCtxView<'_> { fn address_family( &mut self, this: Resource, - ) -> Result { + ) -> Result { let socket = self.table.get(&this)?; Ok(socket.address_family().into()) } @@ -159,11 +161,11 @@ impl udp::HostUdpSocket for WasiSocketsCtxView<'_> { Ok(()) } - fn subscribe(&mut self, this: Resource) -> anyhow::Result> { + fn subscribe(&mut self, this: Resource) -> wasmtime::Result> { wasmtime_wasi_io::poll::subscribe(self.table, this) } - fn drop(&mut self, this: Resource) -> Result<(), anyhow::Error> { + fn drop(&mut self, this: Resource) -> Result<(), wasmtime::Error> { // As in the filesystem implementation, we assume closing a socket // doesn't block. let dropped = self.table.delete(this)?; @@ -243,11 +245,11 @@ impl udp::HostIncomingDatagramStream for WasiSocketsCtxView<'_> { fn subscribe( &mut self, this: Resource, - ) -> anyhow::Result> { + ) -> wasmtime::Result> { wasmtime_wasi_io::poll::subscribe(self.table, this) } - fn drop(&mut self, this: Resource) -> Result<(), anyhow::Error> { + fn drop(&mut self, this: Resource) -> Result<(), wasmtime::Error> { // As in the filesystem implementation, we assume closing a socket // doesn't block. let dropped = self.table.delete(this)?; @@ -337,12 +339,12 @@ impl udp::HostOutgoingDatagramStream for WasiSocketsCtxView<'_> { stream.send_state = SendState::Idle; } SendState::Permitted(_) => { - return Err(SocketError::trap(anyhow::anyhow!( + return Err(SocketError::trap(wasmtime::format_err!( "unpermitted: argument exceeds permitted size" ))); } SendState::Idle | SendState::Waiting => { - return Err(SocketError::trap(anyhow::anyhow!( + return Err(SocketError::trap(wasmtime::format_err!( "unpermitted: must call check-send first" ))); } @@ -377,11 +379,11 @@ impl udp::HostOutgoingDatagramStream for WasiSocketsCtxView<'_> { fn subscribe( &mut self, this: Resource, - ) -> anyhow::Result> { + ) -> wasmtime::Result> { wasmtime_wasi_io::poll::subscribe(self.table, this) } - fn drop(&mut self, this: Resource) -> Result<(), anyhow::Error> { + fn drop(&mut self, this: Resource) -> Result<(), wasmtime::Error> { // As in the filesystem implementation, we assume closing a socket // doesn't block. let dropped = self.table.delete(this)?; diff --git a/crates/wasi/src/p2/ip_name_lookup.rs b/crates/wasi/src/p2/ip_name_lookup.rs index b8cc63986dac..3fa0e7433afa 100644 --- a/crates/wasi/src/p2/ip_name_lookup.rs +++ b/crates/wasi/src/p2/ip_name_lookup.rs @@ -3,11 +3,11 @@ use crate::p2::bindings::sockets::ip_name_lookup::{Host, HostResolveAddressStrea use crate::p2::bindings::sockets::network::{ErrorCode, IpAddress, Network}; use crate::runtime::{AbortOnDropJoinHandle, spawn_blocking}; use crate::sockets::WasiSocketsCtxView; -use anyhow::Result; use std::mem; use std::net::ToSocketAddrs; use std::pin::Pin; use std::vec; +use wasmtime::Result; use wasmtime::component::Resource; use wasmtime_wasi_io::poll::{DynPollable, Pollable, subscribe}; diff --git a/crates/wasi/src/p2/mod.rs b/crates/wasi/src/p2/mod.rs index 25974c6fae32..a11b3c830469 100644 --- a/crates/wasi/src/p2/mod.rs +++ b/crates/wasi/src/p2/mod.rs @@ -311,7 +311,7 @@ pub use wasmtime_wasi_io::streams::{ /// } /// } /// ``` -pub fn add_to_linker_async(linker: &mut Linker) -> anyhow::Result<()> { +pub fn add_to_linker_async(linker: &mut Linker) -> wasmtime::Result<()> { let options = bindings::LinkOptions::default(); add_to_linker_with_options_async(linker, &options) } @@ -320,7 +320,7 @@ pub fn add_to_linker_async(linker: &mut Linker) -> anyhow::Resul pub fn add_to_linker_with_options_async( linker: &mut Linker, options: &bindings::LinkOptions, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { add_async_io_to_linker(linker)?; add_nonblocking_to_linker(linker, options)?; @@ -335,7 +335,7 @@ pub fn add_to_linker_with_options_async( fn add_nonblocking_to_linker<'a, T: WasiView, O>( linker: &mut Linker, options: &'a O, -) -> anyhow::Result<()> +) -> wasmtime::Result<()> where bindings::sockets::network::LinkOptions: From<&'a O>, bindings::cli::exit::LinkOptions: From<&'a O>, @@ -371,7 +371,7 @@ where /// present in the `wasi:http/proxy` world. pub fn add_to_linker_proxy_interfaces_async( linker: &mut Linker, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { add_async_io_to_linker(linker)?; add_proxy_interfaces_nonblocking(linker) } @@ -381,12 +381,12 @@ pub fn add_to_linker_proxy_interfaces_async( #[doc(hidden)] pub fn add_to_linker_proxy_interfaces_sync( linker: &mut Linker, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { add_sync_wasi_io(linker)?; add_proxy_interfaces_nonblocking(linker) } -fn add_proxy_interfaces_nonblocking(linker: &mut Linker) -> anyhow::Result<()> { +fn add_proxy_interfaces_nonblocking(linker: &mut Linker) -> wasmtime::Result<()> { use crate::p2::bindings::{cli, clocks, random}; let l = linker; @@ -455,7 +455,7 @@ fn add_proxy_interfaces_nonblocking(linker: &mut Linker) -> anyh /// ``` pub fn add_to_linker_sync( linker: &mut wasmtime::component::Linker, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { let options = bindings::sync::LinkOptions::default(); add_to_linker_with_options_sync(linker, &options) } @@ -464,7 +464,7 @@ pub fn add_to_linker_sync( pub fn add_to_linker_with_options_sync( linker: &mut wasmtime::component::Linker, options: &bindings::sync::LinkOptions, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { add_nonblocking_to_linker(linker, options)?; add_sync_wasi_io(linker)?; @@ -479,7 +479,7 @@ pub fn add_to_linker_with_options_sync( /// [`add_to_linker_proxy_interfaces_sync`]. fn add_sync_wasi_io( linker: &mut wasmtime::component::Linker, -) -> anyhow::Result<()> { +) -> wasmtime::Result<()> { let l = linker; wasmtime_wasi_io::bindings::wasi::io::error::add_to_linker::(l, |t| t.ctx().table)?; bindings::sync::io::poll::add_to_linker::(l, |t| t.ctx().table)?; @@ -499,7 +499,7 @@ impl HasData for HasIo { // that's not possible with these two traits in separate crates. For now this // is some small duplication but if this gets worse over time then we'll want // to massage this. -fn add_async_io_to_linker(l: &mut Linker) -> anyhow::Result<()> { +fn add_async_io_to_linker(l: &mut Linker) -> wasmtime::Result<()> { wasmtime_wasi_io::bindings::wasi::io::error::add_to_linker::(l, |t| t.ctx().table)?; wasmtime_wasi_io::bindings::wasi::io::poll::add_to_linker::(l, |t| t.ctx().table)?; wasmtime_wasi_io::bindings::wasi::io::streams::add_to_linker::(l, |t| t.ctx().table)?; diff --git a/crates/wasi/src/p2/pipe.rs b/crates/wasi/src/p2/pipe.rs index 96b94f40cb36..9b5f60303de1 100644 --- a/crates/wasi/src/p2/pipe.rs +++ b/crates/wasi/src/p2/pipe.rs @@ -7,13 +7,13 @@ //! Some convenience constructors are included for common backing types like `Vec` and `String`, //! but the virtual pipes can be instantiated with any `Read` or `Write` type. //! -use anyhow::anyhow; use bytes::Bytes; use std::pin::{Pin, pin}; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use tokio::io::{self, AsyncRead, AsyncWrite}; use tokio::sync::mpsc; +use wasmtime::format_err; use wasmtime_wasi_io::{ poll::Pollable, streams::{InputStream, OutputStream, StreamError}, @@ -99,7 +99,7 @@ impl OutputStream for MemoryOutputPipe { fn write(&mut self, bytes: Bytes) -> Result<(), StreamError> { let mut buf = self.buffer.lock().unwrap(); if bytes.len() > self.capacity - buf.len() { - return Err(StreamError::Trap(anyhow!( + return Err(StreamError::Trap(format_err!( "write beyond capacity of MemoryOutputPipe" ))); } @@ -240,7 +240,7 @@ impl InputStream for AsyncReadStream { Err(e) } Err(TryRecvError::Empty) => Ok(Bytes::new()), - Err(TryRecvError::Disconnected) => Err(StreamError::Trap(anyhow!( + Err(TryRecvError::Disconnected) => Err(StreamError::Trap(format_err!( "AsyncReadStream sender died - should be impossible" ))), } diff --git a/crates/wasi/src/p2/poll.rs b/crates/wasi/src/p2/poll.rs index 9cbee5f96005..e96472e4a7d8 100644 --- a/crates/wasi/src/p2/poll.rs +++ b/crates/wasi/src/p2/poll.rs @@ -1,7 +1,7 @@ use crate::runtime::in_tokio; use wasmtime_wasi_io::{bindings::wasi::io::poll as async_poll, poll::DynPollable}; -use anyhow::Result; +use wasmtime::Result; use wasmtime::component::{Resource, ResourceTable}; impl crate::p2::bindings::sync::io::poll::Host for ResourceTable { diff --git a/crates/wasi/src/p2/stdio.rs b/crates/wasi/src/p2/stdio.rs index 3184e0062370..ffad53f7ddd0 100644 --- a/crates/wasi/src/p2/stdio.rs +++ b/crates/wasi/src/p2/stdio.rs @@ -13,21 +13,21 @@ pub enum IsATTY { } impl stdin::Host for WasiCliCtxView<'_> { - fn get_stdin(&mut self) -> Result, anyhow::Error> { + fn get_stdin(&mut self) -> Result, wasmtime::Error> { let stream = self.ctx.stdin.p2_stream(); Ok(self.table.push(stream)?) } } impl stdout::Host for WasiCliCtxView<'_> { - fn get_stdout(&mut self) -> Result, anyhow::Error> { + fn get_stdout(&mut self) -> Result, wasmtime::Error> { let stream = self.ctx.stdout.p2_stream(); Ok(self.table.push(stream)?) } } impl stderr::Host for WasiCliCtxView<'_> { - fn get_stderr(&mut self) -> Result, anyhow::Error> { + fn get_stderr(&mut self) -> Result, wasmtime::Error> { let stream = self.ctx.stderr.p2_stream(); Ok(self.table.push(stream)?) } @@ -38,20 +38,20 @@ pub struct TerminalOutput; impl terminal_input::Host for WasiCliCtxView<'_> {} impl terminal_input::HostTerminalInput for WasiCliCtxView<'_> { - fn drop(&mut self, r: Resource) -> anyhow::Result<()> { + fn drop(&mut self, r: Resource) -> wasmtime::Result<()> { self.table.delete(r)?; Ok(()) } } impl terminal_output::Host for WasiCliCtxView<'_> {} impl terminal_output::HostTerminalOutput for WasiCliCtxView<'_> { - fn drop(&mut self, r: Resource) -> anyhow::Result<()> { + fn drop(&mut self, r: Resource) -> wasmtime::Result<()> { self.table.delete(r)?; Ok(()) } } impl terminal_stdin::Host for WasiCliCtxView<'_> { - fn get_terminal_stdin(&mut self) -> anyhow::Result>> { + fn get_terminal_stdin(&mut self) -> wasmtime::Result>> { if self.ctx.stdin.is_terminal() { let fd = self.table.push(TerminalInput)?; Ok(Some(fd)) @@ -61,7 +61,7 @@ impl terminal_stdin::Host for WasiCliCtxView<'_> { } } impl terminal_stdout::Host for WasiCliCtxView<'_> { - fn get_terminal_stdout(&mut self) -> anyhow::Result>> { + fn get_terminal_stdout(&mut self) -> wasmtime::Result>> { if self.ctx.stdout.is_terminal() { let fd = self.table.push(TerminalOutput)?; Ok(Some(fd)) @@ -71,7 +71,7 @@ impl terminal_stdout::Host for WasiCliCtxView<'_> { } } impl terminal_stderr::Host for WasiCliCtxView<'_> { - fn get_terminal_stderr(&mut self) -> anyhow::Result>> { + fn get_terminal_stderr(&mut self) -> wasmtime::Result>> { if self.ctx.stderr.is_terminal() { let fd = self.table.push(TerminalOutput)?; Ok(Some(fd)) diff --git a/crates/wasi/src/p2/tcp.rs b/crates/wasi/src/p2/tcp.rs index 019c3c6b1f00..67edf98ba868 100644 --- a/crates/wasi/src/p2/tcp.rs +++ b/crates/wasi/src/p2/tcp.rs @@ -4,7 +4,6 @@ use crate::p2::{ }; use crate::runtime::AbortOnDropJoinHandle; use crate::sockets::TcpSocket; -use anyhow::Result; use io_lifetimes::AsSocketlike; use rustix::io::Errno; use std::io; @@ -12,6 +11,7 @@ use std::mem; use std::net::Shutdown; use std::sync::Arc; use tokio::sync::Mutex; +use wasmtime::Result; impl TcpSocket { pub(crate) fn p2_streams(&mut self) -> SocketResult<(DynInputStream, DynOutputStream)> { @@ -191,7 +191,7 @@ impl TcpWriter { WriteState::Ready => {} WriteState::Closed => return Err(StreamError::Closed), WriteState::Writing(_) | WriteState::Closing(_) | WriteState::Error(_) => { - return Err(StreamError::Trap(anyhow::anyhow!( + return Err(StreamError::Trap(wasmtime::format_err!( "unpermitted: must call check_write first" ))); } @@ -354,7 +354,7 @@ fn try_lock_for_stream(mutex: &Mutex) -> Result(mutex: &Mutex) -> SocketResult> { mutex.try_lock().map_err(|_| { - SocketError::trap(anyhow::anyhow!( + SocketError::trap(wasmtime::format_err!( "concurrent access to resource not supported" )) }) diff --git a/crates/wasi/src/p2/write_stream.rs b/crates/wasi/src/p2/write_stream.rs index e29d343520ca..658571e3a62f 100644 --- a/crates/wasi/src/p2/write_stream.rs +++ b/crates/wasi/src/p2/write_stream.rs @@ -1,9 +1,9 @@ use crate::p2::{OutputStream, Pollable, StreamError}; -use anyhow::anyhow; use bytes::Bytes; use std::pin::pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; +use wasmtime::format_err; #[derive(Debug)] struct WorkerState { @@ -11,7 +11,7 @@ struct WorkerState { items: std::collections::VecDeque, write_budget: usize, flush_pending: bool, - error: Option, + error: Option, write_ready_changed: Option, } @@ -169,7 +169,7 @@ impl OutputStream for AsyncWriteStream { let mut state = self.worker.state(); state.check_error()?; if state.flush_pending { - return Err(StreamError::Trap(anyhow!( + return Err(StreamError::Trap(format_err!( "write not permitted while flush pending" ))); } @@ -178,7 +178,7 @@ impl OutputStream for AsyncWriteStream { state.write_budget = remaining_budget; state.items.push_back(bytes); } - None => return Err(StreamError::Trap(anyhow!("write exceeded budget"))), + None => return Err(StreamError::Trap(format_err!("write exceeded budget"))), } drop(state); self.worker.new_work.notify_one(); diff --git a/crates/wasi/src/p3/cli/host.rs b/crates/wasi/src/p3/cli/host.rs index 2b413cc1eebf..29b4fbc56e20 100644 --- a/crates/wasi/src/p3/cli/host.rs +++ b/crates/wasi/src/p3/cli/host.rs @@ -7,7 +7,6 @@ use crate::p3::bindings::cli::{ terminal_stdin, terminal_stdout, }; use crate::p3::cli::{TerminalInput, TerminalOutput}; -use anyhow::{Context as _, anyhow}; use bytes::BytesMut; use core::pin::Pin; use core::task::{Context, Poll}; @@ -18,7 +17,7 @@ use wasmtime::component::{ Access, Accessor, Destination, FutureReader, Resource, Source, StreamConsumer, StreamProducer, StreamReader, StreamResult, }; -use wasmtime::{AsContextMut as _, StoreContextMut}; +use wasmtime::{AsContextMut as _, StoreContextMut, error::Context as _, format_err}; struct InputStreamProducer { rx: Pin>, @@ -206,7 +205,7 @@ impl stdin::HostWithStore for WasiCli { }, ); let future = FutureReader::new(&mut store, async { - anyhow::Ok(match result_rx.await { + wasmtime::error::Ok(match result_rx.await { Ok(err) => Err(err), Err(_) => Ok(()), }) @@ -287,10 +286,10 @@ impl exit::Host for WasiCliCtxView<'_> { Ok(()) => 0, Err(()) => 1, }; - Err(anyhow!(I32Exit(status))) + Err(format_err!(I32Exit(status))) } fn exit_with_code(&mut self, status_code: u8) -> wasmtime::Result<()> { - Err(anyhow!(I32Exit(status_code.into()))) + Err(format_err!(I32Exit(status_code.into()))) } } diff --git a/crates/wasi/src/p3/cli/mod.rs b/crates/wasi/src/p3/cli/mod.rs index 5989e9c5a634..fb8230d3646e 100644 --- a/crates/wasi/src/p3/cli/mod.rs +++ b/crates/wasi/src/p3/cli/mod.rs @@ -71,7 +71,7 @@ where pub fn add_to_linker_with_options( linker: &mut Linker, exit_options: &exit::LinkOptions, -) -> anyhow::Result<()> +) -> wasmtime::Result<()> where T: WasiCliView + 'static, { diff --git a/crates/wasi/src/p3/filesystem/host.rs b/crates/wasi/src/p3/filesystem/host.rs index 682fffb75259..0c4e0c294bda 100644 --- a/crates/wasi/src/p3/filesystem/host.rs +++ b/crates/wasi/src/p3/filesystem/host.rs @@ -7,7 +7,6 @@ use crate::p3::bindings::filesystem::types::{ use crate::p3::filesystem::{FilesystemError, FilesystemResult, preopens}; use crate::p3::{DEFAULT_BUFFER_CAPACITY, FallibleIteratorProducer}; use crate::{DirPerms, FilePerms}; -use anyhow::Context as _; use bytes::BytesMut; use core::pin::Pin; use core::task::{Context, Poll, ready}; @@ -22,6 +21,7 @@ use wasmtime::component::{ Access, Accessor, Destination, FutureReader, Resource, ResourceTable, Source, StreamConsumer, StreamProducer, StreamReader, StreamResult, }; +use wasmtime::error::Context as _; fn get_descriptor<'a>( table: &'a ResourceTable, @@ -495,7 +495,7 @@ impl types::HostDescriptorWithStore for WasiFilesystem { return Ok(( StreamReader::new(&mut store, iter::empty()), FutureReader::new(&mut store, async { - anyhow::Ok(Err(ErrorCode::NotPermitted)) + wasmtime::error::Ok(Err(ErrorCode::NotPermitted)) }), )); } @@ -636,7 +636,7 @@ impl types::HostDescriptorWithStore for WasiFilesystem { return Ok(( StreamReader::new(&mut store, iter::empty()), FutureReader::new(&mut store, async { - anyhow::Ok(Err(ErrorCode::NotPermitted)) + wasmtime::error::Ok(Err(ErrorCode::NotPermitted)) }), )); } @@ -819,7 +819,7 @@ impl types::HostDescriptorWithStore for WasiFilesystem { let table = store.get().table; let fd = get_descriptor(table, &fd)?.clone(); let other = get_descriptor(table, &other)?.clone(); - anyhow::Ok((fd, other)) + wasmtime::error::Ok((fd, other)) })?; fd.is_same_object(&other).await } diff --git a/crates/wasi/src/p3/sockets/host/types/mod.rs b/crates/wasi/src/p3/sockets/host/types/mod.rs index 60c152dab48d..81fa1b8da26f 100644 --- a/crates/wasi/src/p3/sockets/host/types/mod.rs +++ b/crates/wasi/src/p3/sockets/host/types/mod.rs @@ -8,7 +8,7 @@ mod tcp; mod udp; impl Host for WasiSocketsCtxView<'_> { - fn convert_error_code(&mut self, error: SocketError) -> anyhow::Result { + fn convert_error_code(&mut self, error: SocketError) -> wasmtime::Result { error.downcast() } } diff --git a/crates/wasi/src/p3/sockets/host/types/tcp.rs b/crates/wasi/src/p3/sockets/host/types/tcp.rs index 1eb5a2d72adf..2125b62ea5f1 100644 --- a/crates/wasi/src/p3/sockets/host/types/tcp.rs +++ b/crates/wasi/src/p3/sockets/host/types/tcp.rs @@ -6,7 +6,6 @@ use crate::p3::bindings::sockets::types::{ }; use crate::p3::sockets::{SocketError, SocketResult, WasiSockets}; use crate::sockets::{NonInheritedOptions, SocketAddrUse, SocketAddressFamily, WasiSocketsCtxView}; -use anyhow::Context as _; use bytes::BytesMut; use core::iter; use core::pin::Pin; @@ -21,6 +20,7 @@ use wasmtime::component::{ Access, Accessor, Destination, FutureReader, Resource, ResourceTable, Source, StreamConsumer, StreamProducer, StreamReader, StreamResult, }; +use wasmtime::error::Context as _; use wasmtime::{AsContextMut as _, StoreContextMut}; fn get_socket<'a>( @@ -331,7 +331,7 @@ impl HostTcpSocketWithStore for WasiSockets { None => Ok(( StreamReader::new(&mut store, iter::empty()), FutureReader::new(&mut store, async { - anyhow::Ok(Err(ErrorCode::InvalidState)) + wasmtime::error::Ok(Err(ErrorCode::InvalidState)) }), )), } diff --git a/crates/wasi/src/p3/sockets/host/types/udp.rs b/crates/wasi/src/p3/sockets/host/types/udp.rs index 96982d30885f..b37c6bcec0bd 100644 --- a/crates/wasi/src/p3/sockets/host/types/udp.rs +++ b/crates/wasi/src/p3/sockets/host/types/udp.rs @@ -5,9 +5,9 @@ use crate::p3::bindings::sockets::types::{ }; use crate::p3::sockets::{SocketResult, WasiSockets}; use crate::sockets::{MAX_UDP_DATAGRAM_SIZE, SocketAddrUse, UdpSocket, WasiSocketsCtxView}; -use anyhow::Context; use std::net::SocketAddr; use wasmtime::component::{Accessor, Resource, ResourceTable}; +use wasmtime::error::Context as _; fn get_socket<'a>( table: &'a ResourceTable, diff --git a/crates/wasi/tests/all/p1.rs b/crates/wasi/tests/all/p1.rs index 3b95112e43bb..04cf2a3bc7d9 100644 --- a/crates/wasi/tests/all/p1.rs +++ b/crates/wasi/tests/all/p1.rs @@ -1,7 +1,7 @@ use crate::store::Ctx; -use anyhow::Result; use std::path::Path; use test_programs_artifacts::*; +use wasmtime::Result; use wasmtime::{Linker, Module}; use wasmtime_wasi::p1::{WasiP1Ctx, add_to_linker_async}; diff --git a/crates/wasi/tests/all/p2/api.rs b/crates/wasi/tests/all/p2/api.rs index 659ededcfa5d..cf3da0fabb24 100644 --- a/crates/wasi/tests/all/p2/api.rs +++ b/crates/wasi/tests/all/p2/api.rs @@ -1,7 +1,7 @@ -use anyhow::Result; use std::io::Write; use std::sync::Mutex; use std::time::Duration; +use wasmtime::Result; use wasmtime::Store; use wasmtime::component::{Component, Linker, ResourceTable}; use wasmtime_wasi::p2::add_to_linker_async; @@ -86,7 +86,7 @@ async fn p2_api_time() -> Result<()> { .wasi_cli_run() .call_run(&mut store) .await? - .map_err(|()| anyhow::anyhow!("command returned with failing exit status")) + .map_err(|()| wasmtime::format_err!("command returned with failing exit status")) } #[test_log::test(tokio::test(flavor = "multi_thread"))] @@ -108,7 +108,7 @@ async fn p2_api_read_only() -> Result<()> { .wasi_cli_run() .call_run(&mut store) .await? - .map_err(|()| anyhow::anyhow!("command returned with failing exit status")) + .map_err(|()| wasmtime::format_err!("command returned with failing exit status")) } #[expect( diff --git a/crates/wasi/tests/all/p2/async_.rs b/crates/wasi/tests/all/p2/async_.rs index 737af190779d..0e1ec3833f98 100644 --- a/crates/wasi/tests/all/p2/async_.rs +++ b/crates/wasi/tests/all/p2/async_.rs @@ -1,7 +1,7 @@ use crate::store::{Ctx, MyWasiCtx}; -use anyhow::Result; use std::path::Path; use test_programs_artifacts::*; +use wasmtime::Result; use wasmtime::component::{Component, Linker}; use wasmtime_wasi::p2::add_to_linker_async; use wasmtime_wasi::p2::bindings::Command; @@ -30,7 +30,7 @@ async fn run(path: &str, inherit_stdio: bool) -> Result<()> { .wasi_cli_run() .call_run(&mut store) .await? - .map_err(|()| anyhow::anyhow!("run returned a failure")) + .map_err(|()| wasmtime::format_err!("run returned a failure")) } foreach_p1!(assert_test_exists); diff --git a/crates/wasi/tests/all/p2/sync.rs b/crates/wasi/tests/all/p2/sync.rs index 9cab6bac8624..f00be13698d8 100644 --- a/crates/wasi/tests/all/p2/sync.rs +++ b/crates/wasi/tests/all/p2/sync.rs @@ -30,7 +30,7 @@ fn run(path: &str, inherit_stdio: bool) -> Result<()> { command .wasi_cli_run() .call_run(&mut store)? - .map_err(|()| anyhow::anyhow!("run returned a failure"))?; + .map_err(|()| wasmtime::format_err!("run returned a failure"))?; } Ok(()) } diff --git a/crates/wasi/tests/all/p3/mod.rs b/crates/wasi/tests/all/p3/mod.rs index 7c9535f0a571..b6cd01e7a597 100644 --- a/crates/wasi/tests/all/p3/mod.rs +++ b/crates/wasi/tests/all/p3/mod.rs @@ -1,9 +1,8 @@ use crate::store::{Ctx, MyWasiCtx}; -use anyhow::{Context as _, anyhow}; use std::path::Path; use test_programs_artifacts::*; -use wasmtime::Result; use wasmtime::component::{Component, Linker}; +use wasmtime::{Result, error::Context as _, format_err}; use wasmtime_wasi::p3::bindings::Command; async fn run(path: &str) -> Result<()> { @@ -42,128 +41,128 @@ async fn run_allow_blocking_current_thread( .context("failed to call `wasi:cli/run#run`")? .context("guest trapped")? .0 - .map_err(|()| anyhow!("`wasi:cli/run#run` failed")) + .map_err(|()| format_err!("`wasi:cli/run#run` failed")) } foreach_p3!(assert_test_exists); #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_cli() -> anyhow::Result<()> { +async fn p3_cli() -> wasmtime::Result<()> { run(P3_CLI_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_clocks_sleep() -> anyhow::Result<()> { +async fn p3_clocks_sleep() -> wasmtime::Result<()> { run(P3_CLOCKS_SLEEP_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_filesystem_file_read_write() -> anyhow::Result<()> { +async fn p3_filesystem_file_read_write() -> wasmtime::Result<()> { run(P3_FILESYSTEM_FILE_READ_WRITE_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_filesystem_file_read_write_blocking() -> anyhow::Result<()> { +async fn p3_filesystem_file_read_write_blocking() -> wasmtime::Result<()> { run_allow_blocking_current_thread(P3_FILESYSTEM_FILE_READ_WRITE_COMPONENT, true).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_random_imports() -> anyhow::Result<()> { +async fn p3_random_imports() -> wasmtime::Result<()> { run(P3_RANDOM_IMPORTS_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_ip_name_lookup() -> anyhow::Result<()> { +async fn p3_sockets_ip_name_lookup() -> wasmtime::Result<()> { run(P3_SOCKETS_IP_NAME_LOOKUP_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_tcp_bind() -> anyhow::Result<()> { +async fn p3_sockets_tcp_bind() -> wasmtime::Result<()> { run(P3_SOCKETS_TCP_BIND_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_tcp_connect() -> anyhow::Result<()> { +async fn p3_sockets_tcp_connect() -> wasmtime::Result<()> { run(P3_SOCKETS_TCP_CONNECT_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_tcp_listen() -> anyhow::Result<()> { +async fn p3_sockets_tcp_listen() -> wasmtime::Result<()> { run(P3_SOCKETS_TCP_LISTEN_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_tcp_sample_application() -> anyhow::Result<()> { +async fn p3_sockets_tcp_sample_application() -> wasmtime::Result<()> { run(P3_SOCKETS_TCP_SAMPLE_APPLICATION_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_tcp_sockopts() -> anyhow::Result<()> { +async fn p3_sockets_tcp_sockopts() -> wasmtime::Result<()> { run(P3_SOCKETS_TCP_SOCKOPTS_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_tcp_states() -> anyhow::Result<()> { +async fn p3_sockets_tcp_states() -> wasmtime::Result<()> { run(P3_SOCKETS_TCP_STATES_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_tcp_streams() -> anyhow::Result<()> { +async fn p3_sockets_tcp_streams() -> wasmtime::Result<()> { run(P3_SOCKETS_TCP_STREAMS_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_udp_bind() -> anyhow::Result<()> { +async fn p3_sockets_udp_bind() -> wasmtime::Result<()> { run(P3_SOCKETS_UDP_BIND_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_udp_connect() -> anyhow::Result<()> { +async fn p3_sockets_udp_connect() -> wasmtime::Result<()> { run(P3_SOCKETS_UDP_CONNECT_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_udp_receive() -> anyhow::Result<()> { +async fn p3_sockets_udp_receive() -> wasmtime::Result<()> { run(P3_SOCKETS_UDP_RECEIVE_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_udp_sample_application() -> anyhow::Result<()> { +async fn p3_sockets_udp_sample_application() -> wasmtime::Result<()> { run(P3_SOCKETS_UDP_SAMPLE_APPLICATION_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_udp_send() -> anyhow::Result<()> { +async fn p3_sockets_udp_send() -> wasmtime::Result<()> { run(P3_SOCKETS_UDP_SEND_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_udp_sockopts() -> anyhow::Result<()> { +async fn p3_sockets_udp_sockopts() -> wasmtime::Result<()> { run(P3_SOCKETS_UDP_SOCKOPTS_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_sockets_udp_states() -> anyhow::Result<()> { +async fn p3_sockets_udp_states() -> wasmtime::Result<()> { run(P3_SOCKETS_UDP_STATES_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_readdir() -> anyhow::Result<()> { +async fn p3_readdir() -> wasmtime::Result<()> { run(P3_READDIR_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_readdir_blocking() -> anyhow::Result<()> { +async fn p3_readdir_blocking() -> wasmtime::Result<()> { run_allow_blocking_current_thread(P3_READDIR_COMPONENT, true).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_file_write() -> anyhow::Result<()> { +async fn p3_file_write() -> wasmtime::Result<()> { run(P3_FILE_WRITE_COMPONENT).await } #[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn p3_file_write_blocking() -> anyhow::Result<()> { +async fn p3_file_write_blocking() -> wasmtime::Result<()> { run_allow_blocking_current_thread(P3_FILE_WRITE_COMPONENT, true).await } diff --git a/crates/wasi/tests/all/store.rs b/crates/wasi/tests/all/store.rs index f96b7cb561c1..219b77ec8484 100644 --- a/crates/wasi/tests/all/store.rs +++ b/crates/wasi/tests/all/store.rs @@ -1,5 +1,5 @@ -use anyhow::Result; use tempfile::TempDir; +use wasmtime::Result; use wasmtime::component::ResourceTable; use wasmtime::{Engine, Store}; use wasmtime_wasi::{ diff --git a/crates/wiggle/Cargo.toml b/crates/wiggle/Cargo.toml index ccaa918e8fd3..88c12e2fc641 100644 --- a/crates/wiggle/Cargo.toml +++ b/crates/wiggle/Cargo.toml @@ -21,13 +21,16 @@ wiggle-macro = { workspace = true } tracing = { workspace = true } bitflags = { workspace = true } wasmtime = { workspace = true, optional = true } -anyhow = { workspace = true } +wasmtime-environ = { workspace = true } [dev-dependencies] wiggle-test = { path = "test-helpers" } proptest = "1.0.0" tokio = { version = "1", features = ["rt-multi-thread","time", "macros"] } -wasmtime = { workspace = true } +# Explicitly enable default features so that tests pass even testing only this +# crate in isolation and we can't accidentally rely on cargo feature resolution +# to enable the runtime and compiler. +wasmtime = { workspace = true, features = ["default"] } [[test]] name = "atoms_async" diff --git a/crates/wiggle/generate/Cargo.toml b/crates/wiggle/generate/Cargo.toml index 1d459fa5f18a..6b47defbe510 100644 --- a/crates/wiggle/generate/Cargo.toml +++ b/crates/wiggle/generate/Cargo.toml @@ -20,5 +20,5 @@ witx = "0.9.1" quote = { workspace = true } proc-macro2 = { workspace = true } heck = { workspace = true } -anyhow = { workspace = true } +wasmtime-environ = { workspace = true } syn = { workspace = true, features = ["full"] } diff --git a/crates/wiggle/generate/src/codegen_settings.rs b/crates/wiggle/generate/src/codegen_settings.rs index f6cacb25d519..132cee9c2656 100644 --- a/crates/wiggle/generate/src/codegen_settings.rs +++ b/crates/wiggle/generate/src/codegen_settings.rs @@ -1,9 +1,9 @@ use crate::config::{AsyncConf, ErrorConf, ErrorConfField, TracingConf}; -use anyhow::{Error, anyhow}; use proc_macro2::{Ident, TokenStream}; use quote::quote; use std::collections::HashMap; use std::rc::Rc; +use wasmtime_environ::error::{Error, format_err}; use witx::{Document, Id, InterfaceFunc, Module, NamedType, TypeRef}; pub use crate::config::Asyncness; @@ -58,13 +58,13 @@ impl ErrorTransform { ErrorConfField::Trappable(field) => if let Some(abi_type) = doc.typename(&Id::new(ident.to_string())) { Ok(ErrorType::Generated(TrappableErrorType { abi_type, rich_type: field.rich_error.clone() })) } else { - Err(anyhow!("No witx typename \"{}\" found", ident.to_string())) + Err(format_err!("No witx typename \"{}\" found", ident.to_string())) }, ErrorConfField::User(field) => if let Some(abi_type) = doc.typename(&Id::new(ident.to_string())) { if let Some(ident) = field.rich_error.get_ident() { if let Some(prior_def) = richtype_identifiers.insert(ident.clone(), field.err_loc) { - return Err(anyhow!( + return Err(format_err!( "duplicate rich type identifier of {ident:?} not allowed. prior definition at {prior_def:?}", )); } @@ -74,13 +74,13 @@ impl ErrorTransform { method_fragment: ident.to_string() })) } else { - return Err(anyhow!( + return Err(format_err!( "rich error type must be identifier for now - TODO add ability to provide a corresponding identifier: {:?}", field.err_loc )) } } - else { Err(anyhow!("No witx typename \"{}\" found", ident.to_string())) } + else { Err(format_err!("No witx typename \"{}\" found", ident.to_string())) } } ).collect::, Error>>()?; Ok(Self { m }) diff --git a/crates/wiggle/generate/src/funcs.rs b/crates/wiggle/generate/src/funcs.rs index 7b6528208ce7..fce3bd97b5be 100644 --- a/crates/wiggle/generate/src/funcs.rs +++ b/crates/wiggle/generate/src/funcs.rs @@ -100,7 +100,7 @@ fn _define_func( ctx: #ctx_type (impl #(#bounds)+*), memory: &mut wiggle::GuestMemory<'_>, #(#abi_params),* - ) -> wiggle::anyhow::Result<#abi_ret> { + ) -> wiggle::error::Result<#abi_ret> { use std::convert::TryFrom as _; #traced_body } @@ -128,7 +128,7 @@ fn _define_func( ctx: #ctx_type (impl #(#bounds)+*), memory: &mut wiggle::GuestMemory<'_>, #(#abi_params),* - ) -> wiggle::anyhow::Result<#abi_ret> { + ) -> wiggle::error::Result<#abi_ret> { use std::convert::TryFrom as _; #traced_body } diff --git a/crates/wiggle/generate/src/lib.rs b/crates/wiggle/generate/src/lib.rs index 8e1ccdf625e2..646dd61e520d 100644 --- a/crates/wiggle/generate/src/lib.rs +++ b/crates/wiggle/generate/src/lib.rs @@ -43,7 +43,7 @@ pub fn generate(doc: &witx::Document, settings: &CodegenSettings) -> TokenStream let methodname = names::user_error_conversion_method(&errtype); Some(quote! { fn #methodname(&mut self, e: super::#user_typename) - -> wiggle::anyhow::Result<#abi_typename>; + -> wiggle::error::Result<#abi_typename>; }) } ErrorType::Generated(_) => None, diff --git a/crates/wiggle/generate/src/module_trait.rs b/crates/wiggle/generate/src/module_trait.rs index 07370973088e..73b18731b11d 100644 --- a/crates/wiggle/generate/src/module_trait.rs +++ b/crates/wiggle/generate/src/module_trait.rs @@ -29,7 +29,7 @@ pub fn define_module_trait(m: &Module, settings: &CodegenSettings) -> TokenStrea }); let mut result = match f.results.len() { - 0 if f.noreturn => quote!(wiggle::anyhow::Error), + 0 if f.noreturn => quote!(wiggle::error::Error), 0 => quote!(()), 1 => { let (ok, err) = match &**f.results[0].tref.type_() { diff --git a/crates/wiggle/generate/src/types/error.rs b/crates/wiggle/generate/src/types/error.rs index 9f0d51f7a031..bbd8f3f5eb73 100644 --- a/crates/wiggle/generate/src/types/error.rs +++ b/crates/wiggle/generate/src/types/error.rs @@ -15,7 +15,7 @@ pub(super) fn define_error( quote! { #[derive(Debug)] pub struct #rich_error { - inner: anyhow::Error, + inner: wiggle::error::Error, } impl std::fmt::Display for #rich_error { @@ -30,10 +30,10 @@ pub(super) fn define_error( } impl #rich_error { - pub fn trap(inner: anyhow::Error) -> #rich_error { + pub fn trap(inner: wiggle::error::Error) -> #rich_error { Self { inner } } - pub fn downcast(self) -> Result<#abi_error, anyhow::Error> { + pub fn downcast(self) -> Result<#abi_error, wiggle::error::Error> { self.inner.downcast() } pub fn downcast_ref(&self) -> Option<&#abi_error> { @@ -46,7 +46,7 @@ pub(super) fn define_error( impl From<#abi_error> for #rich_error { fn from(abi: #abi_error) -> #rich_error { - #rich_error { inner: anyhow::Error::from(abi) } + #rich_error { inner: wiggle::error::Error::from(abi) } } } } diff --git a/crates/wiggle/generate/src/wasmtime.rs b/crates/wiggle/generate/src/wasmtime.rs index 31bbf4c0bad4..722654a0a67c 100644 --- a/crates/wiggle/generate/src/wasmtime.rs +++ b/crates/wiggle/generate/src/wasmtime.rs @@ -56,7 +56,7 @@ pub fn link_module( pub fn #func_name( linker: &mut wiggle::wasmtime_crate::Linker, get_cx: impl Fn(&mut T) -> #u + Send + Sync + Copy + 'static, - ) -> wiggle::anyhow::Result<()> + ) -> wiggle::error::Result<()> where T: 'static, U: #ctx_bound #send_bound @@ -126,7 +126,7 @@ fn generate_func( let ctx = get_cx(caller.data_mut()); (wiggle::GuestMemory::Shared(m.data()), ctx) } - _ => wiggle::anyhow::bail!("missing required memory export"), + _ => wiggle::error::bail!("missing required memory export"), }; Ok(<#ret_ty>::from(#abi_func(ctx, &mut mem #(, #arg_names)*) #await_ ?)) }; @@ -150,7 +150,7 @@ fn generate_func( linker.func_wrap( #module_str, #field_str, - move |mut caller: wiggle::wasmtime_crate::Caller<'_, T> #(, #arg_decls)*| -> wiggle::anyhow::Result<#ret_ty> { + move |mut caller: wiggle::wasmtime_crate::Caller<'_, T> #(, #arg_decls)*| -> wiggle::error::Result<#ret_ty> { let result = async { #body }; #block_with(result)? }, @@ -163,7 +163,7 @@ fn generate_func( linker.func_wrap( #module_str, #field_str, - move |mut caller: wiggle::wasmtime_crate::Caller<'_, T> #(, #arg_decls)*| -> wiggle::anyhow::Result<#ret_ty> { + move |mut caller: wiggle::wasmtime_crate::Caller<'_, T> #(, #arg_decls)*| -> wiggle::error::Result<#ret_ty> { #body }, )?; diff --git a/crates/wiggle/src/error.rs b/crates/wiggle/src/guest_error.rs similarity index 100% rename from crates/wiggle/src/error.rs rename to crates/wiggle/src/guest_error.rs diff --git a/crates/wiggle/src/lib.rs b/crates/wiggle/src/lib.rs index ced4953979b6..1888a1ff218a 100644 --- a/crates/wiggle/src/lib.rs +++ b/crates/wiggle/src/lib.rs @@ -1,14 +1,14 @@ -use anyhow::{Result, bail}; use std::borrow::Cow; use std::cell::UnsafeCell; use std::fmt; use std::mem; use std::ops::Range; use std::str; +use wasmtime_environ::error::{Result, bail}; pub use wiggle_macro::from_witx; -pub use anyhow; +pub use wasmtime_environ::error; pub use wiggle_macro::wasmtime_integration; pub use bitflags; @@ -16,13 +16,13 @@ pub use bitflags; #[cfg(feature = "wiggle_metadata")] pub use witx; -mod error; +mod guest_error; mod guest_type; mod region; pub use tracing; -pub use error::GuestError; +pub use guest_error::GuestError; pub use guest_type::{GuestErrorType, GuestType, GuestTypeTransparent}; pub use region::Region; diff --git a/crates/wiggle/test-helpers/Cargo.toml b/crates/wiggle/test-helpers/Cargo.toml index df2212e5f264..002c70a7ac63 100644 --- a/crates/wiggle/test-helpers/Cargo.toml +++ b/crates/wiggle/test-helpers/Cargo.toml @@ -20,8 +20,11 @@ proptest = "1.0.0" wiggle = { path = "..", features = ["tracing_log"] } [dev-dependencies] -anyhow = { workspace = true } thiserror = { workspace = true } tracing = { workspace = true } tracing-subscriber = { version = "0.3.1", default-features = false, features = ['fmt'] } env_logger = { workspace = true } +# Explicitly enable default features so that tests pass even testing only this +# crate in isolation and we can't accidentally rely on cargo feature resolution +# to enable the runtime and compiler. +wasmtime = { workspace = true, features = ["default"] } diff --git a/crates/wiggle/test-helpers/examples/tracing.rs b/crates/wiggle/test-helpers/examples/tracing.rs index 2d48d4156fa9..6e2d47286ffa 100644 --- a/crates/wiggle/test-helpers/examples/tracing.rs +++ b/crates/wiggle/test-helpers/examples/tracing.rs @@ -1,5 +1,5 @@ -use anyhow::Result; use wiggle::GuestMemory; +use wiggle::error::Result; use wiggle_test::{HostMemory, WasiCtx, impl_errno}; /// The `errors` argument to the wiggle gives us a hook to map a rich error diff --git a/crates/wiggle/tests/errors.rs b/crates/wiggle/tests/errors.rs index 7e228be1a81d..2416cc0146be 100644 --- a/crates/wiggle/tests/errors.rs +++ b/crates/wiggle/tests/errors.rs @@ -1,7 +1,7 @@ /// Execute the wiggle guest conversion code to exercise it mod convert_just_errno { - use anyhow::Result; use wiggle::GuestMemory; + use wiggle::error::Result; use wiggle_test::{HostMemory, WasiCtx, impl_errno}; /// The `errors` argument to the wiggle gives us a hook to map a rich error @@ -93,8 +93,8 @@ mod convert_just_errno { /// we use two distinct error types. mod convert_multiple_error_types { pub use super::convert_just_errno::RichError; - use anyhow::Result; use wiggle::GuestMemory; + use wiggle::error::Result; use wiggle_test::{WasiCtx, impl_errno}; /// Test that we can map multiple types of errors. @@ -152,7 +152,7 @@ mod convert_multiple_error_types { fn bar(&mut self, _: &mut GuestMemory<'_>, _: u32) -> Result<(), AnotherRichError> { unimplemented!() } - fn baz(&mut self, _: &mut GuestMemory<'_>, _: u32) -> anyhow::Error { + fn baz(&mut self, _: &mut GuestMemory<'_>, _: u32) -> wiggle::error::Error { unimplemented!() } } diff --git a/crates/wiggle/tests/wasi.rs b/crates/wiggle/tests/wasi.rs index 0c798cda8274..7900d75d1600 100644 --- a/crates/wiggle/tests/wasi.rs +++ b/crates/wiggle/tests/wasi.rs @@ -385,7 +385,7 @@ impl<'a> crate::wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx<'a> { &mut self, _memory: &mut GuestMemory<'_>, _rval: types::Exitcode, - ) -> anyhow::Error { + ) -> wiggle::error::Error { unimplemented!("proc_exit") }