repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/hello/examples/hi.rs
wasmer-bus/hello/examples/hi.rs
use std::sync::Arc; use async_trait::async_trait; use wasmer_bus_hello::*; #[derive(Debug, Default)] struct HelloService { } #[async_trait] impl WorldSimplified for HelloService { async fn hello(&self) -> String { "hello".to_string() } } #[tokio::main(flavor = "multi_thread")] async fn main() { WorldService::listen(Arc::new(HelloService::default())); WorldService::serve().await; }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/prelude.rs
wasmer-bus/reqwest/src/prelude.rs
pub use crate::api::Response; pub use crate::reqwest::header; pub use crate::reqwest::http; pub use crate::reqwest::Body; pub use crate::reqwest::Client; pub use crate::reqwest::ClientBuilder; pub use crate::reqwest::Form; pub use crate::reqwest::Mime; pub use crate::reqwest::RequestBuilder; pub use wasmer_bus; pub use wasmer_bus::abi::BusError; pub use async_trait::async_trait;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/lib.rs
wasmer-bus/reqwest/src/lib.rs
pub mod api; pub mod prelude; pub mod reqwest;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/response.rs
wasmer-bus/reqwest/src/reqwest/response.rs
use http::header::HeaderName; use http::HeaderMap; use http::HeaderValue; use http::StatusCode; use serde::de::DeserializeOwned; use serde::*; use std::io::Error; use std::io::ErrorKind; use std::io::Read; use crate::api::*; impl Response { pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> { match self.data.as_ref() { Some(data) => serde_json::from_slice(&data[..]).map_err(|e| { Error::new( ErrorKind::Other, format!( "failed to deserialize ({} bytes) into json - {}", data.len(), e ) .as_str(), ) }), None => { return Err(Error::new( ErrorKind::Other, format!("failed to deserialize into json - no data was returned by the server") .as_str(), )); } } } pub fn content_length(&self) -> Option<u64> { self.data.as_ref().map(|a| a.len() as u64) } pub fn status(&self) -> StatusCode { StatusCode::from_u16(self.status).unwrap_or(StatusCode::OK) } pub fn ok(&self) -> bool { self.ok } pub fn redirected(&self) -> bool { self.redirected } pub fn status_text(&self) -> &str { &self.status_text } pub fn headers(&self) -> HeaderMap { let mut ret = HeaderMap::new(); for (header, value) in self.headers.iter() { let val = match HeaderValue::from_str(value) { Ok(a) => a, Err(_) => { continue; } }; let parsed: HeaderName = match header.parse() { Ok(a) => a, Err(_) => { continue; } }; ret.append(parsed, val); } ret } } impl Read for Response { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { match self.data.as_ref() { Some(data) => { if self.pos >= data.len() { return Ok(0usize); } let remaining = &data[self.pos..]; let sub = remaining.len().min(buf.len()); buf[0..sub].clone_from_slice(&remaining[0..sub]); self.pos += sub; Ok(sub) } None => Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "The server returned no data", )), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/multipart.rs
wasmer-bus/reqwest/src/reqwest/multipart.rs
use std::borrow::Cow; use urlencoding::encode; pub struct Form { parts: Vec<(String, String)>, } impl Default for Form { fn default() -> Self { Self::new() } } impl Form { /// Creates a new Form without any content. pub fn new() -> Form { Form { parts: Vec::new() } } pub fn text<T, U>(mut self, name: T, value: U) -> Form where T: Into<Cow<'static, str>>, U: Into<Cow<'static, str>>, { self.parts .push((name.into().to_string(), value.into().to_string())); self } pub fn to_string(&self) -> String { let mut ret = String::new(); for n in 0..self.parts.len() { let first = n == 0; if first == false { ret += "&"; } let (name, value) = &self.parts[n]; ret += &encode(name.as_str()); ret += "="; ret += &encode(value.as_str()); } ret } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/into_url.rs
wasmer-bus/reqwest/src/reqwest/into_url.rs
use url::Url; /// A trait to try to convert some type into a `Url`. /// /// This trait is "sealed", such that only types within reqwest can /// implement it. pub trait IntoUrl: IntoUrlSealed {} impl IntoUrl for Url {} impl IntoUrl for String {} impl<'a> IntoUrl for &'a str {} impl<'a> IntoUrl for &'a String {} pub trait IntoUrlSealed { // Besides parsing as a valid `Url`, the `Url` must be a valid // `http::Uri`, in that it makes sense to use in a network request. fn into_url(self) -> std::io::Result<Url>; fn as_str(&self) -> &str; } impl IntoUrlSealed for Url { fn into_url(self) -> std::io::Result<Url> { if self.has_host() { Ok(self) } else { Err(std::io::Error::new( std::io::ErrorKind::Other, "url_bad_scheme", )) } } fn as_str(&self) -> &str { self.as_ref() } } impl<'a> IntoUrlSealed for &'a str { fn into_url(self) -> std::io::Result<Url> { Url::parse(self) .map_err(|e| { std::io::Error::new(std::io::ErrorKind::Other, format!("url_parse_error {}", e)) })? .into_url() } fn as_str(&self) -> &str { self } } impl<'a> IntoUrlSealed for &'a String { fn into_url(self) -> std::io::Result<Url> { (&**self).into_url() } fn as_str(&self) -> &str { self.as_ref() } } impl<'a> IntoUrlSealed for String { fn into_url(self) -> std::io::Result<Url> { (&*self).into_url() } fn as_str(&self) -> &str { self.as_ref() } } #[cfg(test)] mod tests { use super::*; #[test] fn into_url_file_scheme() { let err = "file:///etc/hosts".into_url().unwrap_err(); assert_eq!( err.to_string(), "builder error for url (file:///etc/hosts): URL scheme is not allowed" ); } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/client.rs
wasmer-bus/reqwest/src/reqwest/client.rs
#![allow(dead_code)] use std::collections::HashMap; use crate::api::ReqwestOptions; use super::*; pub struct Client { pub(crate) builder: ClientBuilder, } impl Client { pub fn get<U: IntoUrl>(self, url: U) -> RequestBuilder { self.request(http::Method::GET, url) } pub fn post<U: IntoUrl>(self, url: U) -> RequestBuilder { self.request(http::Method::POST, url) } pub fn put<U: IntoUrl>(self, url: U) -> RequestBuilder { self.request(http::Method::PUT, url) } pub fn patch<U: IntoUrl>(self, url: U) -> RequestBuilder { self.request(http::Method::PATCH, url) } pub fn delete<U: IntoUrl>(self, url: U) -> RequestBuilder { self.request(http::Method::DELETE, url) } pub fn head<U: IntoUrl>(self, url: U) -> RequestBuilder { self.request(http::Method::HEAD, url) } pub fn request<U: IntoUrl>(self, method: http::Method, url: U) -> RequestBuilder { RequestBuilder { method, url: url.into_url().unwrap(), client: self, headers: HashMap::default(), request: None, } } pub fn builder() -> ClientBuilder { ClientBuilder::new() } pub fn options(&self) -> ReqwestOptions { ReqwestOptions { gzip: self.builder.gzip, cors_proxy: self.builder.cors_proxy.clone(), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/error.rs
wasmer-bus/reqwest/src/reqwest/error.rs
pub type Error = std::io::Error; pub type ErrorKind = std::io::ErrorKind;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/client_builder.rs
wasmer-bus/reqwest/src/reqwest/client_builder.rs
#![allow(dead_code)] use super::*; #[derive(Debug, Default)] pub struct ClientBuilder { pub(super) gzip: bool, pub(super) cors_proxy: Option<String>, } impl ClientBuilder { pub fn new() -> Self { ClientBuilder::default() } pub fn gzip(mut self, enable: bool) -> Self { self.gzip = enable; self } pub fn cors_proxy(mut self, domain: &str) -> Self { self.cors_proxy = Some(domain.to_string()); self } pub fn build(self) -> Result<Client, Error> { Ok(Client { builder: self }) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/mod.rs
wasmer-bus/reqwest/src/reqwest/mod.rs
#![allow(unused_imports)] mod body; mod client; mod client_builder; mod error; mod into_url; mod mime; mod multipart; mod request_builder; mod response; pub(crate) use body::*; pub(crate) use client::*; pub(crate) use client_builder::*; pub(crate) use error::*; pub(crate) use into_url::*; pub(crate) use mime::*; pub(crate) use multipart::*; pub(crate) use request_builder::*; pub use ::http; pub use ::http::header; pub use body::Body; pub use client::Client; pub use client_builder::ClientBuilder; pub use mime::Mime; pub use multipart::Form; pub use request_builder::RequestBuilder; pub use response::*; pub const WAPM_NAME: &'static str = "os";
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/request_builder.rs
wasmer-bus/reqwest/src/reqwest/request_builder.rs
#![allow(dead_code)] use http::StatusCode; use std::borrow::Cow; use std::collections::HashMap; use std::io::Write; use super::*; use crate::api::ReqwestClient; use crate::api::Response; use wasmer_bus::abi::call_new; pub struct RequestBuilder { pub(crate) method: http::Method, pub(crate) url: url::Url, pub(crate) client: Client, pub(crate) headers: HashMap<String, String>, pub(crate) request: Option<Body>, } impl RequestBuilder { pub fn header<T>(mut self, header: http::header::HeaderName, value: T) -> Self where T: Into<Cow<'static, str>>, { self.headers .insert(header.to_string(), value.into().to_string()); self } pub fn multipart(self, multipart: multipart::Form) -> RequestBuilder { let mut builder = self.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); builder.request = Some(Body::from(multipart.to_string())); builder } pub fn bearer_auth<T>(self, token: T) -> RequestBuilder where T: std::fmt::Display, { let token = format!("{}", token); if token.len() <= 0 { return self; } let header_value = format!("Bearer {}", token); self.header(header::AUTHORIZATION, header_value) } pub fn send(self) -> Result<Response, std::io::Error> { let url = self.url.to_string(); let options = self.client.options(); let task = ReqwestClient::new(WAPM_NAME).blocking_make( url, self.method.to_string(), options, self.headers .iter() .map(|(a, b)| (a.clone(), b.clone())) .collect(), self.request .iter() .filter_map(|a| a.as_bytes()) .map(|a| a.to_vec()) .next(), ); let res = task.map_err(|err| err.into_io_error())?; let res = res.map_err(|err| { std::io::Error::new( std::io::ErrorKind::Other, format!("syscall error - code={}", err).as_str(), ) })?; let status = StatusCode::from_u16(res.status).map_err(|err| { std::io::Error::new( std::io::ErrorKind::Other, format!("invalid status code returned by the server - {}", err).as_str(), ) })?; Ok(Response { ok: res.ok, redirected: res.redirected, status: status.as_u16(), status_text: res.status_text, headers: res.headers, pos: 0usize, data: res.data, }) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/mime.rs
wasmer-bus/reqwest/src/reqwest/mime.rs
pub use mime_guess::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/reqwest/body.rs
wasmer-bus/reqwest/src/reqwest/body.rs
#![allow(dead_code)] use std::fmt; use std::pin::Pin; use std::task::{Context, Poll}; use bytes::Bytes; use futures_core::Stream; use http_body::Body as HttpBody; use pin_project_lite::pin_project; use super::*; /// An asynchronous request body. pub struct Body { inner: Inner, } // The `Stream` trait isn't stable, so the impl isn't public. pub(crate) struct ImplStream(Body); enum Inner { Reusable(Bytes), Streaming { body: Pin< Box< dyn HttpBody<Data = Bytes, Error = Box<dyn std::error::Error + Send + Sync>> + Send + Sync, >, >, }, } pin_project! { struct WrapStream<S> { #[pin] inner: S, } } impl Body { /// Returns a reference to the internal data of the `Body`. /// /// `None` is returned, if the underlying data is a stream. pub fn as_bytes(&self) -> Option<&[u8]> { match &self.inner { Inner::Reusable(bytes) => Some(bytes.as_ref()), Inner::Streaming { .. } => None, } } /// Wrap a futures `Stream` in a box inside `Body`. /// /// # Example /// /// ``` /// # use reqwest::Body; /// # use futures_util; /// # fn main() { /// let chunks: Vec<Result<_, ::std::io::Error>> = vec![ /// Ok("hello"), /// Ok(" "), /// Ok("world"), /// ]; /// /// let stream = futures_util::stream::iter(chunks); /// /// let body = Body::wrap_stream(stream); /// # } /// ``` /// /// # Optional /// /// This requires the `stream` feature to be enabled. #[cfg(feature = "stream")] pub fn wrap_stream<S>(stream: S) -> Body where S: futures_core::stream::TryStream + Send + Sync + 'static, S::Error: Into<Box<dyn std::error::Error + Send + Sync>>, Bytes: From<S::Ok>, { Body::stream(stream) } pub(crate) fn stream<S>(stream: S) -> Body where S: futures_core::stream::TryStream + Send + Sync + 'static, S::Error: Into<Box<dyn std::error::Error + Send + Sync>>, Bytes: From<S::Ok>, { use futures_util::TryStreamExt; let body = Box::pin(WrapStream { inner: stream.map_ok(Bytes::from).map_err(Into::into), }); Body { inner: Inner::Streaming { body }, } } pub(crate) fn empty() -> Body { Body::reusable(Bytes::new()) } pub(crate) fn reusable(chunk: Bytes) -> Body { Body { inner: Inner::Reusable(chunk), } } pub(crate) fn try_reuse(self) -> (Option<Bytes>, Self) { let reuse = match self.inner { Inner::Reusable(ref chunk) => Some(chunk.clone()), Inner::Streaming { .. } => None, }; (reuse, self) } pub(crate) fn try_clone(&self) -> Option<Body> { match self.inner { Inner::Reusable(ref chunk) => Some(Body::reusable(chunk.clone())), Inner::Streaming { .. } => None, } } pub(crate) fn into_stream(self) -> ImplStream { ImplStream(self) } #[cfg(feature = "multipart")] pub(crate) fn content_length(&self) -> Option<u64> { match self.inner { Inner::Reusable(ref bytes) => Some(bytes.len() as u64), Inner::Streaming { ref body, .. } => body.size_hint().exact(), } } } impl From<Bytes> for Body { #[inline] fn from(bytes: Bytes) -> Body { Body::reusable(bytes) } } impl From<Vec<u8>> for Body { #[inline] fn from(vec: Vec<u8>) -> Body { Body::reusable(vec.into()) } } impl From<&'static [u8]> for Body { #[inline] fn from(s: &'static [u8]) -> Body { Body::reusable(Bytes::from_static(s)) } } impl From<String> for Body { #[inline] fn from(s: String) -> Body { Body::reusable(s.into()) } } impl From<&'static str> for Body { #[inline] fn from(s: &'static str) -> Body { s.as_bytes().into() } } impl fmt::Debug for Body { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Body").finish() } } // ===== impl ImplStream ===== impl HttpBody for ImplStream { type Data = Bytes; type Error = Error; fn poll_data( mut self: Pin<&mut Self>, cx: &mut Context, ) -> Poll<Option<Result<Self::Data, Self::Error>>> { let opt_try_chunk = match self.0.inner { Inner::Streaming { ref mut body } => futures_core::ready!(Pin::new(body).poll_data(cx)) .map(|opt_chunk| { opt_chunk .map(Into::into) .map_err(|e| Error::new(ErrorKind::Other, e)) }), Inner::Reusable(ref mut bytes) => { if bytes.is_empty() { None } else { Some(Ok(std::mem::replace(bytes, Bytes::new()))) } } }; Poll::Ready(opt_try_chunk) } fn poll_trailers( self: Pin<&mut Self>, _cx: &mut Context, ) -> Poll<Result<Option<http::HeaderMap>, Self::Error>> { Poll::Ready(Ok(None)) } fn is_end_stream(&self) -> bool { match self.0.inner { Inner::Streaming { ref body, .. } => body.is_end_stream(), Inner::Reusable(ref bytes) => bytes.is_empty(), } } fn size_hint(&self) -> http_body::SizeHint { match self.0.inner { Inner::Streaming { ref body, .. } => body.size_hint(), Inner::Reusable(ref bytes) => { let mut hint = http_body::SizeHint::default(); hint.set_exact(bytes.len() as u64); hint } } } } impl Stream for ImplStream { type Item = Result<Bytes, Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { self.poll_data(cx) } } // ===== impl WrapStream ===== impl<S, D, E> HttpBody for WrapStream<S> where S: Stream<Item = Result<D, E>>, D: Into<Bytes>, E: Into<Box<dyn std::error::Error + Send + Sync>>, { type Data = Bytes; type Error = E; fn poll_data( self: Pin<&mut Self>, cx: &mut Context, ) -> Poll<Option<Result<Self::Data, Self::Error>>> { let item = futures_core::ready!(self.project().inner.poll_next(cx)?); Poll::Ready(item.map(|val| Ok(val.into()))) } fn poll_trailers( self: Pin<&mut Self>, _cx: &mut Context, ) -> Poll<Result<Option<http::HeaderMap>, Self::Error>> { Poll::Ready(Ok(None)) } } #[cfg(test)] mod tests { use super::Body; #[test] fn test_as_bytes() { let test_data = b"Test body"; let body = Body::from(&test_data[..]); assert_eq!(body.as_bytes(), Some(&test_data[..])); } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/reqwest/src/api/mod.rs
wasmer-bus/reqwest/src/api/mod.rs
use serde::*; use wasmer_bus::macros::*; #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct ReqwestOptions { pub gzip: bool, pub cors_proxy: Option<String>, } #[wasmer_bus(format = "bincode")] pub trait Reqwest { async fn make( &self, url: String, method: String, options: ReqwestOptions, headers: Vec<(String, String)>, body: Option<Vec<u8>>, ) -> Result<Response, i32>; } #[derive(Debug, Serialize, Deserialize)] pub struct Response { pub pos: usize, pub data: Option<Vec<u8>>, pub ok: bool, pub redirected: bool, pub status: u16, pub status_text: String, pub headers: Vec<(String, String)>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/deploy/src/prelude.rs
wasmer-bus/deploy/src/prelude.rs
pub use wasmer_bus; pub use wasmer_bus::abi::BusError; pub use async_trait::async_trait;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/deploy/src/lib.rs
wasmer-bus/deploy/src/lib.rs
pub mod api; pub mod prelude;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/deploy/src/api/mod.rs
wasmer-bus/deploy/src/api/mod.rs
use serde::*; use std::sync::Arc; #[allow(unused_imports)] use wasmer_bus::macros::*; #[wasmer_bus(format = "json")] pub trait Tok { async fn user_exists( &self, email: String, ) -> TokResult<bool>; async fn user_create( &self, email: String, password: String ) -> TokResult<()>; async fn login( &self, email: String, password: String, code: Option<String> ) -> Arc<dyn Session>; } #[wasmer_bus(format = "json")] pub trait Session { async fn user_details( &self ) -> TokResult<()>; } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] pub enum TokError { Unauthorized, InvalidUser, NotImplemented, InternalError(u16), } impl std::fmt::Display for TokError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { TokError::Unauthorized => write!(f, "unauthorized"), TokError::InvalidUser => write!(f, "invalid user"), TokError::NotImplemented => write!(f, "not implemented"), TokError::InternalError(code) => write!(f, "internal error ({})", code), } } } impl std::error::Error for TokError { } pub type TokResult<T> = Result<T, TokError>;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/time/src/prelude.rs
wasmer-bus/time/src/prelude.rs
pub use crate::time::sleep; pub use crate::time::timeout; pub use crate::time::Elapsed; pub use wasmer_bus; pub use wasmer_bus::abi::BusError; pub use async_trait::async_trait;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/time/src/lib.rs
wasmer-bus/time/src/lib.rs
pub mod api; pub mod prelude; pub mod time;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/time/src/time/timeout.rs
wasmer-bus/time/src/time/timeout.rs
use std::fmt::Display; use std::future::Future; use std::time::Duration; use tokio::select; use super::*; #[derive(Debug)] pub struct Elapsed { duration: Duration, } impl Display for Elapsed { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "timeout elasped (limit={}ms)", self.duration.as_millis()) } } pub async fn timeout<T>(duration: Duration, future: T) -> Result<T::Output, Elapsed> where T: Future, { select! { _ = sleep(duration) => { return Err(Elapsed { duration }) }, a = future => { return Ok(a) } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/time/src/time/sleep.rs
wasmer-bus/time/src/time/sleep.rs
#[cfg(target_os = "wasi")] pub async fn sleep(duration: std::time::Duration) { let duration_ms = duration.as_millis(); let _ = crate::api::TimeClient::new(super::WAPM_NAME) .sleep(duration_ms) .await; } #[cfg(not(target_os = "wasi"))] pub use tokio::time::sleep;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/time/src/time/mod.rs
wasmer-bus/time/src/time/mod.rs
mod sleep; mod timeout; pub use sleep::*; pub use timeout::*; #[allow(dead_code)] const WAPM_NAME: &'static str = "os";
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/time/src/api/mod.rs
wasmer-bus/time/src/api/mod.rs
use wasmer_bus::macros::*; #[wasmer_bus(format = "json")] pub trait Time { async fn sleep(&self, duration_ms: u128); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/types/src/lib.rs
wasmer-bus/types/src/lib.rs
mod error; mod format; pub use error::*; pub use format::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/types/src/error.rs
wasmer-bus/types/src/error.rs
use serde::*; use std::fmt; use std::io; #[repr(u32)] #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum BusError { Success = 0, SerializationFailed = 1, DeserializationFailed = 2, InvalidWapm = 3, FetchFailed = 4, CompileError = 5, IncorrectAbi = 6, Aborted = 7, InvalidHandle = 8, InvalidTopic = 9, MissingCallbacks = 10, Unsupported = 11, BadRequest = 12, InternalFailure = 14, MemoryAllocationFailed = 16, BusInvocationFailed = 17, AccessDenied = 18, AlreadyConsumed = 19, MemoryAccessViolation = 20, Unknown = u32::MAX, } impl From<u32> for BusError { fn from(raw: u32) -> Self { use BusError::*; match raw { 0 => Success, 1 => SerializationFailed, 2 => DeserializationFailed, 3 => InvalidWapm, 4 => FetchFailed, 5 => CompileError, 6 => IncorrectAbi, 7 => Aborted, 8 => InvalidHandle, 9 => InvalidTopic, 10 => MissingCallbacks, 11 => Unsupported, 12 => BadRequest, 14 => InternalFailure, 16 => MemoryAllocationFailed, 17 => BusInvocationFailed, 18 => AccessDenied, 19 => AlreadyConsumed, 20 => MemoryAccessViolation, _ => Unknown } } } impl BusError { pub fn into_io_error(self) -> io::Error { self.into() } } impl Into<io::Error> for BusError { fn into(self) -> io::Error { match self { BusError::InvalidHandle => io::Error::new( io::ErrorKind::ConnectionAborted, format!("connection aborted - {}", self.to_string()).as_str(), ), err => io::Error::new( io::ErrorKind::Other, format!("wasm bus error - {}", err.to_string()).as_str(), ), } } } impl fmt::Display for BusError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { BusError::Success => write!(f, "operation successful"), BusError::SerializationFailed => write!( f, "there was an error while serializing the request or response." ), BusError::DeserializationFailed => write!( f, "there was an error while deserializing the request or response." ), BusError::InvalidWapm => write!(f, "the specified WAPM module does not exist."), BusError::FetchFailed => write!(f, "failed to fetch the WAPM module."), BusError::CompileError => write!(f, "failed to compile the WAPM module."), BusError::IncorrectAbi => write!(f, "the ABI is invalid for cross module calls."), BusError::Aborted => write!(f, "the request has been aborted."), BusError::InvalidHandle => write!(f, "the handle is not valid."), BusError::InvalidTopic => write!(f, "the topic name is invalid."), BusError::MissingCallbacks => { write!(f, "some mandatory callbacks were not registered.") } BusError::Unsupported => { write!(f, "this operation is not supported on this platform.") } BusError::BadRequest => write!( f, "invalid input was supplied in the call resulting in a bad request." ), BusError::AccessDenied => write!(f, "access denied"), BusError::InternalFailure => write!(f, "an internal failure has occured"), BusError::MemoryAllocationFailed => write!(f, "memory allocation has failed"), BusError::BusInvocationFailed => write!(f, "bus invocation has failed"), BusError::AlreadyConsumed => write!(f, "result already consumed"), BusError::MemoryAccessViolation => write!(f, "memory access violation"), BusError::Unknown => write!(f, "unknown error."), } } } impl std::error::Error for BusError { }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/types/src/format.rs
wasmer-bus/types/src/format.rs
use serde::*; use std::{fmt::Display, str::FromStr}; #[cfg(feature = "enable_num_enum")] use num_enum::IntoPrimitive; #[cfg(feature = "enable_num_enum")] use num_enum::TryFromPrimitive; use crate::BusError; #[derive( Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, )] #[cfg_attr(feature = "enable_num_enum", derive(IntoPrimitive, TryFromPrimitive))] #[repr(u8)] pub enum SerializationFormat { Raw = 0, #[cfg(feature = "enable_json")] Json = 1, #[cfg(feature = "enable_mpack")] MessagePack = 2, #[cfg(feature = "enable_bincode")] Bincode = 3, #[cfg(feature = "enable_yaml")] Yaml = 4, #[cfg(feature = "enable_xml")] Xml = 5, #[cfg(feature = "enable_rkyv")] Rkyv = 6 } impl FromStr for SerializationFormat { type Err = String; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { match s { "raw" => Ok(SerializationFormat::Raw), #[cfg(feature = "enable_mpack")] "mpack" | "messagepack" => Ok(SerializationFormat::MessagePack), #[cfg(feature = "enable_bincode")] "bincode" | "bc" => Ok(SerializationFormat::Bincode), #[cfg(feature = "enable_json")] "json" => Ok(SerializationFormat::Json), #[cfg(feature = "enable_json")] "yaml" => Ok(SerializationFormat::Yaml), #[cfg(feature = "enable_yaml")] "xml" => Ok(SerializationFormat::Xml), #[cfg(feature = "enable_rkyv")] "rkyv" => Ok(SerializationFormat::Rkyv), _ => { let mut msg = "valid serialization formats are".to_string(); msg.push_str(" 'raw'"); #[cfg(feature = "enable_json")] msg.push_str(", 'json'"); #[cfg(feature = "enable_mpack")] msg.push_str(", 'mpack'"); #[cfg(feature = "enable_bincode")] msg.push_str(", 'bincode'"); #[cfg(feature = "enable_yaml")] msg.push_str(", 'yaml'"); #[cfg(feature = "enable_xml")] msg.push_str(", 'xml'"); #[cfg(feature = "enable_rkyv")] msg.push_str(", 'rkyv'"); msg.push_str("."); return Err(msg); } } } } impl Display for SerializationFormat { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { SerializationFormat::Raw => write!(f, "raw"), #[cfg(feature = "enable_mpack")] SerializationFormat::MessagePack => write!(f, "mpack"), #[cfg(feature = "enable_json")] SerializationFormat::Json => write!(f, "json"), #[cfg(feature = "enable_bincode")] SerializationFormat::Bincode => write!(f, "bincode"), #[cfg(feature = "enable_yaml")] SerializationFormat::Yaml => write!(f, "yaml"), #[cfg(feature = "enable_xml")] SerializationFormat::Xml => write!(f, "xml"), #[cfg(feature = "enable_rkyv")] SerializationFormat::Rkyv => write!(f, "rkyv"), } } } impl SerializationFormat { pub fn iter() -> std::vec::IntoIter<SerializationFormat> { vec![ SerializationFormat::Raw, #[cfg(feature = "enable_json")] SerializationFormat::Json, #[cfg(feature = "enable_mpack")] SerializationFormat::MessagePack, #[cfg(feature = "enable_bincode")] SerializationFormat::Bincode, #[cfg(feature = "enable_yaml")] SerializationFormat::Yaml, #[cfg(feature = "enable_xml")] SerializationFormat::Xml, #[cfg(feature = "enable_rkyv")] SerializationFormat::Rkyv, ] .into_iter() } #[cfg(feature = "enable_rkyv")] pub fn deserialize_ref<'a, T>(&self, data: &'a [u8]) -> Result<T, BusError> where T: serde::de::Deserialize<'a>, T: rkyv::Archive, T::Archived: rkyv::Deserialize<T, rkyv::de::deserializers::SharedDeserializeMap> { use SerializationFormat::*; Ok( match self { Raw => { let data = data.to_vec(); self.deserialize(data)? } #[cfg(feature = "enable_bincode")] Bincode => bincode::deserialize::<T>(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_mpack")] MessagePack => rmp_serde::from_read_ref(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_json")] Json => serde_json::from_slice::<T>(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_yaml")] Yaml => serde_yaml::from_slice(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_xml")] Xml => serde_xml_rs::from_reader(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_xml")] Rkyv => unsafe { rkyv::from_bytes_unchecked(data) .map_err(|_err| BusError::DeserializationFailed)? }, } ) } #[cfg(not(feature = "enable_rkyv"))] pub fn deserialize_ref<'a, T>(&self, data: &'a [u8]) -> Result<T, BusError> where T: serde::de::DeserializeOwned { use SerializationFormat::*; Ok( match self { Raw => { let data = data.to_vec(); self.deserialize(data)? } #[cfg(feature = "enable_bincode")] Bincode => bincode::deserialize::<T>(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_mpack")] MessagePack => rmp_serde::from_read_ref(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_json")] Json => serde_json::from_slice::<T>(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_yaml")] Yaml => serde_yaml::from_slice(data) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_xml")] Xml => serde_xml_rs::from_reader(data) .map_err(|_err| BusError::DeserializationFailed)?, } ) } #[cfg(feature = "enable_rkyv")] pub fn serialize_ref<T, const N: usize>(&self, data: &T) -> Result<Vec<u8>, BusError> where T: serde::Serialize, T: rkyv::Serialize<rkyv::ser::serializers::AllocSerializer<N>> { use SerializationFormat::*; Ok( match self { Raw => { // Seserializing by reference can not perform RAW deserialization return Err(BusError::SerializationFailed) } #[cfg(feature = "enable_bincode")] Bincode => bincode::serialize::<T>(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_mpack")] MessagePack => rmp_serde::to_vec(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_json")] Json => serde_json::to_vec::<T>(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_yaml")] Yaml => serde_yaml::to_vec(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_xml")] Xml => { let mut ret = Vec::new(); serde_xml_rs::to_writer(&mut ret, &data) .map_err(|_err| BusError::SerializationFailed)?; ret } Rkyv => rkyv::to_bytes(&data) .map(|ret| ret.into_vec()) .map_err(|_err| BusError::SerializationFailed)?, } ) } #[cfg(not(feature = "enable_rkyv"))] pub fn serialize_ref<T>(&self, data: &T) -> Result<Vec<u8>, BusError> where T: serde::ser::Serialize { use SerializationFormat::*; Ok( match self { Raw => { // Serializing a raw vector as a reference type is not currently supported return Err(BusError::SerializationFailed) } #[cfg(feature = "enable_json")] Json => serde_json::to_vec::<T>(data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_mpack")] MessagePack => rmp_serde::to_vec(data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_bincode")] Bincode => bincode::serialize::<T>(data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_yaml")] Yaml => serde_yaml::to_vec(data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_xml")] Xml => { let mut ret = Vec::new(); serde_xml_rs::to_writer(&mut ret, data) .map_err(|_err| BusError::SerializationFailed)?; ret } } ) } #[cfg(feature = "enable_rkyv")] pub fn deserialize<T>(&self, mut data: Vec<u8>) -> Result<T, BusError> where T: serde::de::DeserializeOwned, T: rkyv::Archive, T::Archived: rkyv::Deserialize<T, rkyv::de::deserializers::SharedDeserializeMap> { use SerializationFormat::*; Ok( match self { Raw => { if std::any::type_name::<Vec<u8>>() == std::any::type_name::<T>() { unsafe { let r = std::mem::transmute_copy(&data); std::mem::forget( std::mem::replace(&mut data, Vec::new()) ); r } } else { return Err(BusError::DeserializationFailed) } } #[cfg(feature = "enable_bincode")] Bincode => bincode::deserialize::<T>(data.as_ref()) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_mpack")] MessagePack => rmp_serde::from_read_ref(&data[..]) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_json")] Json => serde_json::from_slice::<T>(data.as_ref()) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_yaml")] Yaml => serde_yaml::from_slice(data.as_ref()) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_xml")] Xml => serde_xml_rs::from_reader(&data[..]) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_xml")] Rkyv => unsafe { rkyv::from_bytes_unchecked(&data[..]) .map_err(|_err| BusError::DeserializationFailed)? }, } ) } #[cfg(not(feature = "enable_rkyv"))] pub fn deserialize<T>(&self, mut data: Vec<u8>) -> Result<T, BusError> where T: serde::de::DeserializeOwned { use SerializationFormat::*; Ok( match self { Raw => { if std::any::type_name::<Vec<u8>>() == std::any::type_name::<T>() { unsafe { let r = std::mem::transmute_copy(&data); std::mem::forget( std::mem::replace(&mut data, Vec::new()) ); r } } else { return Err(BusError::DeserializationFailed) } } #[cfg(feature = "enable_bincode")] Bincode => bincode::deserialize::<T>(data.as_ref()) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_mpack")] MessagePack => rmp_serde::from_read_ref(&data[..]) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_json")] Json => serde_json::from_slice::<T>(data.as_ref()) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_yaml")] Yaml => serde_yaml::from_slice(data.as_ref()) .map_err(|_err| BusError::DeserializationFailed)?, #[cfg(feature = "enable_xml")] Xml => serde_xml_rs::from_reader(&data[..]) .map_err(|_err| BusError::DeserializationFailed)?, } ) } #[cfg(feature = "enable_rkyv")] pub fn serialize<T, const N: usize>(&self, mut data: T) -> Result<Vec<u8>, BusError> where T: serde::Serialize, T: rkyv::Serialize<rkyv::ser::serializers::AllocSerializer<N>> { use SerializationFormat::*; Ok( match self { Raw => { if std::any::type_name::<Vec<u8>>() == std::any::type_name::<T>() { unsafe { let r = std::mem::transmute_copy(&data); let ptr = &mut data as *mut T; let ptr = ptr as *mut (); let ptr = ptr as *mut Vec<u8>; let ptr = &mut *ptr; std::mem::forget( std::mem::replace(ptr, Vec::new()) ); r } } else { return Err(BusError::SerializationFailed) } } #[cfg(feature = "enable_bincode")] Bincode => bincode::serialize::<T>(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_mpack")] MessagePack => rmp_serde::to_vec(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_json")] Json => serde_json::to_vec::<T>(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_yaml")] Yaml => serde_yaml::to_vec(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_xml")] Xml => { let mut ret = Vec::new(); serde_xml_rs::to_writer(&mut ret, &data) .map_err(|_err| BusError::SerializationFailed)?; ret } Rkyv => rkyv::to_bytes(&data) .map(|ret| ret.into_vec()) .map_err(|_err| BusError::SerializationFailed)?, } ) } #[cfg(not(feature = "enable_rkyv"))] pub fn serialize<T>(&self, mut data: T) -> Result<Vec<u8>, BusError> where T: serde::ser::Serialize { use SerializationFormat::*; Ok( match self { Raw => { if std::any::type_name::<Vec<u8>>() == std::any::type_name::<T>() { unsafe { let r = std::mem::transmute_copy(&data); let ptr = &mut data as *mut T; let ptr = ptr as *mut (); let ptr = ptr as *mut Vec<u8>; let ptr = &mut *ptr; std::mem::forget( std::mem::replace(ptr, Vec::new()) ); r } } else { return Err(BusError::SerializationFailed) } } #[cfg(feature = "enable_json")] Json => serde_json::to_vec::<T>(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_mpack")] MessagePack => rmp_serde::to_vec(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_bincode")] Bincode => bincode::serialize::<T>(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_yaml")] Yaml => serde_yaml::to_vec(&data) .map_err(|_err| BusError::SerializationFailed)?, #[cfg(feature = "enable_xml")] Xml => { let mut ret = Vec::new(); serde_xml_rs::to_writer(&mut ret, &data) .map_err(|_err| BusError::SerializationFailed)?; ret } } ) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/prelude.rs
wasmer-bus/ws/src/prelude.rs
#[cfg(any(feature = "sys", target_family = "wasm"))] pub use crate::ws::RecvHalf; #[cfg(any(feature = "sys", target_family = "wasm"))] pub use crate::ws::SendHalf; #[cfg(any(feature = "sys", target_family = "wasm"))] pub use crate::ws::SocketBuilder; #[cfg(any(feature = "sys", target_family = "wasm"))] pub use crate::ws::WebSocket; #[cfg(target_family = "wasm")] pub use wasmer_bus; #[cfg(target_family = "wasm")] pub use wasmer_bus::abi::BusError; pub use async_trait::async_trait;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/lib.rs
wasmer-bus/ws/src/lib.rs
pub mod api; pub mod prelude; pub mod model; pub mod ws;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/model/socket_state.rs
wasmer-bus/ws/src/model/socket_state.rs
use std::fmt::{Display, Formatter, self}; #[allow(dead_code)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] pub enum SocketState { Opening, Opened, Closed, Failed, } impl Display for SocketState { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { SocketState::Opening => write!(f, "opening"), SocketState::Opened => write!(f, "opened"), SocketState::Closed => write!(f, "closed"), SocketState::Failed => write!(f, "failed"), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/model/mod.rs
wasmer-bus/ws/src/model/mod.rs
mod socket_state; mod send_result; pub use socket_state::*; pub use send_result::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/model/send_result.rs
wasmer-bus/ws/src/model/send_result.rs
use serde::*; #[allow(dead_code)] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum SendResult { Success(usize), Failed(String), }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/api/mod.rs
wasmer-bus/ws/src/api/mod.rs
use std::sync::Arc; use wasmer_bus::macros::*; use crate::model::SendResult; use crate::model::SocketState; #[wasmer_bus(format = "bincode")] pub trait SocketBuilder { async fn connect( &self, url: String, state_change: impl Fn(SocketState), receive: impl Fn(Vec<u8>), ) -> Arc<dyn WebSocket>; } #[wasmer_bus(format = "bincode")] pub trait WebSocket { async fn send(&self, data: Vec<u8>) -> SendResult; } /* #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct SocketBuilderConnectStateChangeCallback(pub SocketState); #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct SocketBuilderConnectReceiveCallback(pub Vec<u8>); #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct SocketBuilderConnectRequest { pub url: String, } #[wasmer_bus::async_trait] pub trait SocketBuilder where Self: std::fmt::Debug + Send + Sync, { async fn connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError>; fn blocking_connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError>; fn as_client(&self) -> Option<SocketBuilderClient>; } #[wasmer_bus::async_trait] pub trait SocketBuilderSimplified where Self: std::fmt::Debug + Send + Sync, { async fn connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError>; } #[wasmer_bus::async_trait] impl<T> SocketBuilder for T where T: SocketBuilderSimplified, { async fn connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError> { SocketBuilderSimplified::connect(self, url, state_change, receive).await } fn blocking_connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError> { wasmer_bus::task::block_on(SocketBuilderSimplified::connect( self, url, state_change, receive, )) } fn as_client(&self) -> Option<SocketBuilderClient> { None } } #[derive(Debug, Clone)] pub struct SocketBuilderService {} impl SocketBuilderService { #[allow(dead_code)] pub(crate) fn attach( wasm_me: std::sync::Arc<dyn SocketBuilder>, call_handle: wasmer_bus::abi::CallSmartHandle, ) { { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Bincode, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: SocketBuilderConnectRequest| { let wasm_me = wasm_me.clone(); let wasm_handle = wasmer_bus::abi::CallSmartHandle::new(wasm_handle); let url = wasm_req.url; async move { let state_change = { let wasm_handle = wasm_handle.clone(); Box::new(move |response: SocketState| { let response = SocketBuilderConnectStateChangeCallback(response); let _ = wasmer_bus::abi::subcall( wasm_handle.clone(), wasmer_bus::abi::SerializationFormat::Bincode, response, ) .invoke(); }) }; let receive = { let wasm_handle = wasm_handle.clone(); Box::new(move |response: Vec<u8>| { let response = SocketBuilderConnectReceiveCallback(response); let _ = wasmer_bus::abi::subcall( wasm_handle.clone(), wasmer_bus::abi::SerializationFormat::Bincode, response, ) .invoke(); }) }; let svc = wasm_me.connect(url, state_change, receive).await?; WebSocketService::attach(svc, wasm_handle); Ok(()) } }, true, ); } } pub fn listen(wasm_me: std::sync::Arc<dyn SocketBuilder>) { { let wasm_me = wasm_me.clone(); wasmer_bus::task::listen( wasmer_bus::abi::SerializationFormat::Bincode, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: SocketBuilderConnectRequest| { let wasm_me = wasm_me.clone(); let wasm_handle = wasmer_bus::abi::CallSmartHandle::new(wasm_handle); let url = wasm_req.url; async move { let state_change = { let wasm_handle = wasm_handle.clone(); Box::new(move |response: SocketState| { let response = SocketBuilderConnectStateChangeCallback(response); let _ = wasmer_bus::abi::subcall( wasm_handle.clone(), wasmer_bus::abi::SerializationFormat::Bincode, response, ) .invoke(); }) }; let receive = { let wasm_handle = wasm_handle.clone(); Box::new(move |response: Vec<u8>| { let response = SocketBuilderConnectReceiveCallback(response); let _ = wasmer_bus::abi::subcall( wasm_handle.clone(), wasmer_bus::abi::SerializationFormat::Bincode, response, ) .invoke(); }) }; let svc = wasm_me.connect(url, state_change, receive).await?; WebSocketService::attach(svc, wasm_handle); Ok(()) } }, ); } } pub fn serve() { wasmer_bus::task::serve(); } } #[derive(Debug, Clone)] pub struct SocketBuilderClient { ctx: wasmer_bus::abi::CallContext, task: Option<wasmer_bus::abi::Call>, join: Option<wasmer_bus::abi::CallJoin<()>>, } impl SocketBuilderClient { pub fn new(wapm: &str) -> Self { Self { ctx: wasmer_bus::abi::CallContext::NewBusCall { wapm: wapm.to_string().into(), instance: None, }, task: None, join: None, } } pub fn new_with_instance(wapm: &str, instance: &str, access_token: &str) -> Self { Self { ctx: wasmer_bus::abi::CallContext::NewBusCall { wapm: wapm.to_string().into(), instance: Some(wasmer_bus::abi::CallInstance::new(instance, access_token)), }, task: None, join: None, } } pub fn attach(handle: wasmer_bus::abi::CallSmartHandle) -> Self { Self { ctx: wasmer_bus::abi::CallContext::SubCall { parent: handle }, task: None, join: None, } } pub fn wait(self) -> Result<(), wasmer_bus::abi::BusError> { if let Some(join) = self.join { join.wait()?; } if let Some(task) = self.task { task.join()?.wait()?; } Ok(()) } pub fn try_wait(&mut self) -> Result<Option<()>, wasmer_bus::abi::BusError> { if let Some(task) = self.task.take() { self.join.replace(task.join()?); } if let Some(join) = self.join.as_mut() { join.try_wait() } else { Ok(None) } } pub async fn connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError> { let request = SocketBuilderConnectRequest { url }; let handle = wasmer_bus::abi::call( self.ctx.clone(), wasmer_bus::abi::SerializationFormat::Bincode, request, ) .callback(move |req: SocketBuilderConnectStateChangeCallback| state_change(req.0)) .callback(move |req: SocketBuilderConnectReceiveCallback| receive(req.0)) .detach()?; Ok(Arc::new(WebSocketClient::attach(handle))) } pub fn blocking_connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError> { wasmer_bus::task::block_on(self.connect(url, state_change, receive)) } } impl std::future::Future for SocketBuilderClient { type Output = Result<(), wasmer_bus::abi::BusError>; fn poll( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { if let Some(task) = self.task.take() { self.join.replace(task.join()?); } if let Some(join) = self.join.as_mut() { let join = std::pin::Pin::new(join); return join.poll(cx); } else { std::task::Poll::Ready(Ok(())) } } } #[wasmer_bus::async_trait] impl SocketBuilder for SocketBuilderClient { async fn connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError> { SocketBuilderClient::connect(self, url, state_change, receive).await } fn blocking_connect( &self, url: String, state_change: Box<dyn Fn(SocketState) + Send + Sync + 'static>, receive: Box<dyn Fn(Vec<u8>) + Send + Sync + 'static>, ) -> std::result::Result<std::sync::Arc<dyn WebSocket>, wasmer_bus::abi::BusError> { SocketBuilderClient::blocking_connect(self, url, state_change, receive) } fn as_client(&self) -> Option<SocketBuilderClient> { Some(self.clone()) } } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct WebSocketSendRequest { pub data: Vec<u8>, } #[wasmer_bus::async_trait] pub trait WebSocket where Self: std::fmt::Debug + Send + Sync, { async fn send(&self, data: Vec<u8>) -> std::result::Result<SendResult, wasmer_bus::abi::BusError>; fn blocking_send( &self, data: Vec<u8>, ) -> std::result::Result<SendResult, wasmer_bus::abi::BusError>; fn as_client(&self) -> Option<WebSocketClient>; } #[wasmer_bus::async_trait] pub trait WebSocketSimplified where Self: std::fmt::Debug + Send + Sync, { async fn send(&self, data: Vec<u8>) -> SendResult; } #[wasmer_bus::async_trait] impl<T> WebSocket for T where T: WebSocketSimplified, { async fn send( &self, data: Vec<u8>, ) -> std::result::Result<SendResult, wasmer_bus::abi::BusError> { Ok(WebSocketSimplified::send(self, data).await) } fn blocking_send( &self, data: Vec<u8>, ) -> std::result::Result<SendResult, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on(WebSocketSimplified::send( self, data, ))) } fn as_client(&self) -> Option<WebSocketClient> { None } } #[derive(Debug, Clone)] pub struct WebSocketService {} impl WebSocketService { #[allow(dead_code)] pub(crate) fn attach( wasm_me: std::sync::Arc<dyn WebSocket>, call_handle: wasmer_bus::abi::CallSmartHandle, ) { { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Bincode, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: WebSocketSendRequest| { let wasm_me = wasm_me.clone(); let wasm_handle = wasmer_bus::abi::CallSmartHandle::new(wasm_handle); let data = wasm_req.data; async move { wasm_me.send(data).await } }, ); } } pub fn listen(wasm_me: std::sync::Arc<dyn WebSocket>) { { let wasm_me = wasm_me.clone(); wasmer_bus::task::listen( wasmer_bus::abi::SerializationFormat::Bincode, #[allow(unused_variables)] move |_wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: WebSocketSendRequest| { let wasm_me = wasm_me.clone(); let data = wasm_req.data; async move { wasm_me.send(data).await } }, ); } } pub fn serve() { wasmer_bus::task::serve(); } } #[derive(Debug, Clone)] pub struct WebSocketClient { ctx: wasmer_bus::abi::CallContext, task: Option<wasmer_bus::abi::Call>, join: Option<wasmer_bus::abi::CallJoin<()>>, } impl WebSocketClient { pub fn new(wapm: &str) -> Self { Self { ctx: wasmer_bus::abi::CallContext::NewBusCall { wapm: wapm.to_string().into(), instance: None, }, task: None, join: None, } } pub fn new_with_instance(wapm: &str, instance: &str, access_token: &str) -> Self { Self { ctx: wasmer_bus::abi::CallContext::NewBusCall { wapm: wapm.to_string().into(), instance: Some(wasmer_bus::abi::CallInstance::new(instance, access_token)), }, task: None, join: None, } } pub fn attach(handle: wasmer_bus::abi::CallSmartHandle) -> Self { Self { ctx: wasmer_bus::abi::CallContext::SubCall { parent: handle }, task: None, join: None, } } pub fn wait(self) -> Result<(), wasmer_bus::abi::BusError> { if let Some(join) = self.join { join.wait()?; } if let Some(task) = self.task { task.join()?.wait()?; } Ok(()) } pub fn try_wait(&mut self) -> Result<Option<()>, wasmer_bus::abi::BusError> { if let Some(task) = self.task.take() { self.join.replace(task.join()?); } if let Some(join) = self.join.as_mut() { join.try_wait() } else { Ok(None) } } pub async fn send( &self, data: Vec<u8>, ) -> std::result::Result<SendResult, wasmer_bus::abi::BusError> { let request = WebSocketSendRequest { data }; wasmer_bus::abi::call( self.ctx.clone(), wasmer_bus::abi::SerializationFormat::Bincode, request, ) .invoke() .join()? .await } pub fn blocking_send( &self, data: Vec<u8>, ) -> std::result::Result<SendResult, wasmer_bus::abi::BusError> { wasmer_bus::task::block_on(self.send(data)) } } impl std::future::Future for WebSocketClient { type Output = Result<(), wasmer_bus::abi::BusError>; fn poll( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { if let Some(task) = self.task.take() { self.join.replace(task.join()?); } if let Some(join) = self.join.as_mut() { let join = std::pin::Pin::new(join); return join.poll(cx); } else { std::task::Poll::Ready(Ok(())) } } } #[wasmer_bus::async_trait] impl WebSocket for WebSocketClient { async fn send( &self, data: Vec<u8>, ) -> std::result::Result<SendResult, wasmer_bus::abi::BusError> { WebSocketClient::send(self, data).await } fn blocking_send( &self, data: Vec<u8>, ) -> std::result::Result<SendResult, wasmer_bus::abi::BusError> { WebSocketClient::blocking_send(self, data) } fn as_client(&self) -> Option<WebSocketClient> { Some(self.clone()) } } */
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/ws/mod.rs
wasmer-bus/ws/src/ws/mod.rs
#[cfg(target_family = "wasm")] mod wasm; #[cfg(feature = "sys")] #[cfg(not(target_family = "wasm"))] mod sys; #[cfg(target_family = "wasm")] pub use wasm::*; #[cfg(feature = "sys")] #[cfg(not(target_family = "wasm"))] pub use sys::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/ws/wasm/socket_builder.rs
wasmer-bus/ws/src/ws/wasm/socket_builder.rs
#![allow(dead_code)] use std::io::Write; use std::result::Result; use tokio::sync::mpsc; use tokio::sync::watch; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use super::*; use crate::api; use crate::model::SocketState; use wasmer_bus::abi::*; const MAX_MPSC: usize = std::usize::MAX >> 3; pub struct SocketBuilder { pub(crate) url: url::Url, } impl SocketBuilder { pub fn new(url: url::Url) -> SocketBuilder { SocketBuilder { url } } pub fn new_str(url: &str) -> Result<SocketBuilder, url::ParseError> { let url = url::Url::parse(url)?; Ok(SocketBuilder { url }) } pub fn blocking_open(self) -> Result<WebSocket, std::io::Error> { wasmer_bus::task::block_on(self.open()) } pub async fn open(self) -> Result<WebSocket, std::io::Error> { use api::SocketBuilder; let url = self.url.to_string(); let (tx_recv, rx_recv) = mpsc::channel(MAX_MPSC); let (tx_state, rx_state) = watch::channel(SocketState::Opening); let client = api::SocketBuilderClient::new(WAPM_NAME) .connect( url, Box::new(move |data: SocketState| { let _ = tx_state.send(data); }), Box::new(move |data: Vec<u8>| { wasmer_bus::task::send(&tx_recv, data); }), ) .await .map_err(|err| err.into_io_error())?; Ok(WebSocket { client, rx: rx_recv, state: rx_state, }) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/ws/wasm/mod.rs
wasmer-bus/ws/src/ws/wasm/mod.rs
#![allow(unused_imports)] mod socket_builder; mod web_socket; pub(crate) use socket_builder::*; pub(crate) use web_socket::*; pub use socket_builder::SocketBuilder; pub use web_socket::RecvHalf; pub use web_socket::SendHalf; pub use web_socket::WebSocket; pub const WAPM_NAME: &'static str = "os";
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/ws/wasm/web_socket.rs
wasmer-bus/ws/src/ws/wasm/web_socket.rs
use std::collections::VecDeque; use std::io; use std::ops::DerefMut; use std::pin::Pin; use std::sync::Arc; use std::sync::Mutex; use std::task::Context; use std::task::Poll; use std::future::Future; use std::io::Read; use std::io::Write; use bytes::Bytes; use derivative::*; use tokio::io::AsyncWrite; use tokio::io::AsyncRead; use tokio::io::ReadBuf; use tokio::sync::mpsc; use tokio::sync::watch; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use crate::model::SendResult; use crate::model::SocketState; use wasmer_bus::abi::*; #[derive(Debug)] pub struct WebSocket { pub(super) client: Arc<dyn crate::api::WebSocket>, pub(super) rx: mpsc::Receiver<Vec<u8>>, pub(super) state: watch::Receiver<SocketState>, } impl WebSocket { pub fn split(self) -> (SendHalf, RecvHalf) { ( SendHalf { client: self.client, state: self.state, sending: Arc::new(Mutex::new(Default::default())), }, RecvHalf { rx: self.rx, buffer: None, }, ) } } #[derive(Derivative, Clone)] #[derivative(Debug)] pub struct SendHalf { client: Arc<dyn crate::api::WebSocket>, state: watch::Receiver<SocketState>, #[derivative(Debug = "ignore")] sending: Arc<Mutex<VecDeque<Pin<Box<dyn Future<Output=Result<SendResult, BusError>> + Send + 'static>>>>>, } impl SendHalf { pub async fn wait_till_opened(&self) -> SocketState { let mut state = self.state.clone(); while *state.borrow() == SocketState::Opening { if let Err(_) = state.changed().await { return SocketState::Closed; } } let ret = (*state.borrow()).clone(); ret } pub async fn close(&self) -> io::Result<()> { Ok(()) } pub async fn send(&mut self, data: Vec<u8>) -> io::Result<usize> { let state = self.wait_till_opened().await; if state != SocketState::Opened { return Err(io::Error::new( io::ErrorKind::ConnectionReset, format!("connection is not open (state={})", state).as_str(), )); } self.client .send(data) .await .map_err(|err| err.into_io_error()) .map(|ret| match ret { SendResult::Success(a) => Ok(a), SendResult::Failed(err) => Err(io::Error::new(io::ErrorKind::Other, err)), })? } pub fn blocking_send(&mut self, data: Vec<u8>) -> io::Result<usize> { wasmer_bus::task::block_on(self.send(data)) } } impl AsyncWrite for SendHalf { fn poll_write( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { let buf_len = buf.len(); let buf = buf.to_vec(); let mut state = self.state.clone(); let client = self.client.clone(); let mut sending = self.sending.lock().unwrap(); sending.push_back(Box::pin(async move { while *state.borrow() == SocketState::Opening { if let Err(_) = state.changed().await { return Ok(SendResult::Failed("web socket is closed".to_string())); } } let state = *state.borrow(); if state != SocketState::Opened { return Ok(SendResult::Failed(format!("connection is not open (state={})", state))); } client.send(buf).await })); Poll::Ready(Ok(buf_len)) } fn poll_flush( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), io::Error>> { let mut sending = self.sending.lock().unwrap(); while let Some(mut fut) = sending.pop_front() { let fut_pinned = fut.as_mut(); match fut_pinned.poll(cx) { Poll::Pending => { sending.push_front(fut); return Poll::Pending; } Poll::Ready(Err(err)) => { return Poll::Ready(Err(err.into_io_error())); } Poll::Ready(Ok(_)) => { } } } Poll::Ready(Ok(())) } fn poll_shutdown( self: Pin<&mut Self>, _cx: &mut Context<'_> ) -> Poll<Result<(), io::Error>> { Poll::Ready(Ok(())) } } #[derive(Debug)] pub struct RecvHalf { rx: mpsc::Receiver<Vec<u8>>, buffer: Option<Bytes>, } impl RecvHalf { pub async fn recv(&mut self) -> Option<Vec<u8>> { self.rx.recv().await } pub fn blocking_recv(&mut self) -> Option<Vec<u8>> { wasmer_bus::task::block_on(self.rx.recv()) } } impl AsyncRead for RecvHalf { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { if let Some(stream) = self.buffer.take() { if stream.len() <= buf.remaining() { buf.put_slice(&stream[..]); } else { let end = buf.remaining(); buf.put_slice(&stream[..end]); self.buffer.replace(stream.slice(end..)); } return Poll::Ready(Ok(())); } match self.rx.poll_recv(cx) { Poll::Pending => Poll::Pending, Poll::Ready(Some(data)) => { if data.len() <= buf.remaining() { buf.put_slice(&data[..]); } else { let end = buf.remaining(); buf.put_slice(&data[..end]); self.buffer.replace(Bytes::from(data).slice(end..)); } Poll::Ready(Ok(())) }, Poll::Ready(None) => { Poll::Ready(Err(io::Error::new(io::ErrorKind::NotConnected, "web socket connection has closed"))) } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/ws/sys/socket_builder.rs
wasmer-bus/ws/src/ws/sys/socket_builder.rs
use std::result::Result; use tokio::net::TcpStream; use tokio_tungstenite::MaybeTlsStream; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use super::*; pub struct SocketBuilder { pub(crate) url: url::Url, } impl SocketBuilder { pub fn new(url: url::Url) -> SocketBuilder { SocketBuilder { url } } pub fn new_str(url: &str) -> Result<SocketBuilder, url::ParseError> { let url = url::Url::parse(url)?; Ok(SocketBuilder { url }) } pub fn blocking_open(self) -> Result<WebSocket<MaybeTlsStream<TcpStream>>, std::io::Error> { tokio::task::block_in_place(move || { tokio::runtime::Handle::current().block_on(async move { self.open().await }) }) } pub async fn open(self) -> Result<WebSocket<MaybeTlsStream<TcpStream>>, std::io::Error> { Ok(super::web_socket::connect(self.url.as_str()).await?) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/ws/sys/mod.rs
wasmer-bus/ws/src/ws/sys/mod.rs
#![allow(unused_imports)] mod socket_builder; mod web_socket; pub(crate) use socket_builder::*; pub(crate) use web_socket::*; pub use socket_builder::SocketBuilder; pub use web_socket::RecvHalf; pub use web_socket::SendHalf; pub use web_socket::WebSocket;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/ws/src/ws/sys/web_socket.rs
wasmer-bus/ws/src/ws/sys/web_socket.rs
use std::io; use std::pin::Pin; use std::sync::Arc; use std::task::Context; use std::task::Poll; use bytes::Bytes; use async_trait::async_trait; use futures::stream::SplitSink; use futures::stream::SplitStream; use futures::SinkExt; use futures_util::StreamExt; use tokio::sync::Mutex; use tokio::net::TcpStream; use tokio::io::AsyncWrite; use tokio::io::AsyncRead; use tokio::io::ReadBuf; use tokio_tungstenite::{client_async_tls_with_config, tungstenite::protocol::Message}; use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use crate::model::*; pub(crate) async fn connect(url: &str) -> Result<WebSocket<MaybeTlsStream<TcpStream>>, io::Error> { let request = url::Url::parse(url).unwrap(); let host = request .host() .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "URL does not have a host component"))?; let port = request .port() .or_else(|| match request.scheme() { "wss" => Some(443), "ws" => Some(80), _ => None, }) .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "URL does not have a port component"))?; let addr = format!("{}:{}", host, port); let socket = TcpStream::connect(addr).await?; socket.set_nodelay(true)?; let (ws_stream, _) = client_async_tls_with_config(request, socket, None, None).await .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; let (sink, stream) = ws_stream.split(); Ok(WebSocket::new(sink, stream)) } #[derive(Debug)] pub struct WebSocket<S> where S: AsyncRead + AsyncWrite + Unpin { sink: SplitSink<WebSocketStream<S>, Message>, stream: SplitStream<WebSocketStream<S>>, } impl<S> WebSocket<S> where S: AsyncRead + AsyncWrite + Unpin { pub fn new(sink: SplitSink<WebSocketStream<S>, Message>, stream: SplitStream<WebSocketStream<S>>) -> Self { Self { sink, stream } } pub fn split(self) -> (SendHalf<S>, RecvHalf<S>) { ( SendHalf::new(self.sink), RecvHalf::new(self.stream) ) } } #[derive(Debug)] pub struct SendHalf<S> where S: AsyncRead + AsyncWrite + Unpin { sink: SplitSink<WebSocketStream<S>, Message>, } impl<S> SendHalf<S> where S: AsyncRead + AsyncWrite + Unpin { pub fn new(sink: SplitSink<WebSocketStream<S>, Message>) -> Self { Self { sink, } } pub async fn wait_till_opened(&self) -> SocketState { SocketState::Opened } pub async fn close(&mut self) -> io::Result<()> { let _ = self.sink.flush().await; self.sink.close().await .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; Ok(()) } pub async fn send(&mut self, data: Vec<u8>) -> io::Result<usize> { let data_len = data.len(); self.sink .send(Message::binary(data)) .await .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; Ok(data_len) } pub fn blocking_send(&mut self, data: Vec<u8>) -> io::Result<usize> { wasmer_bus::task::block_on(self.send(data)) } } impl<S> AsyncWrite for SendHalf<S> where S: AsyncRead + AsyncWrite + Unpin { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { match self.sink.poll_ready_unpin(cx) { Poll::Pending => Poll::Pending, Poll::Ready(Ok(_)) => { match self.sink.start_send_unpin(Message::Binary(buf.to_vec())) { Ok(_) => Poll::Ready(Ok(buf.len())), Err(err) => { return Poll::Ready(Err( io::Error::new(io::ErrorKind::BrokenPipe, err.to_string()) )); } } } Poll::Ready(Err(err)) => { return Poll::Ready(Err( io::Error::new(io::ErrorKind::BrokenPipe, err.to_string()) )); } } } fn poll_flush( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), io::Error>> { match self.sink.poll_flush_unpin(cx) { Poll::Pending => Poll::Pending, Poll::Ready(Ok(_)) => Poll::Ready(Ok(())), Poll::Ready(Err(err)) => { Poll::Ready(Err( io::Error::new(io::ErrorKind::BrokenPipe, err.to_string()) )) } } } fn poll_shutdown( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), io::Error>> { match self.sink.poll_flush_unpin(cx) { Poll::Pending => { return Poll::Pending; }, _ => { } } match self.sink.poll_close_unpin(cx) { Poll::Pending => Poll::Pending, Poll::Ready(Ok(a)) => Poll::Ready(Ok(a)), Poll::Ready(Err(err)) => { Poll::Ready(Err( io::Error::new(io::ErrorKind::Other, err.to_string()) )) } } } } #[derive(Debug)] pub struct RecvHalf<S> where S: AsyncRead + AsyncWrite + Unpin { stream: SplitStream<WebSocketStream<S>>, buffer: Option<Bytes>, } impl<S> RecvHalf<S> where S: AsyncRead + AsyncWrite + Unpin { pub fn new(stream: SplitStream<WebSocketStream<S>>) -> Self { Self { stream, buffer: None, } } pub async fn recv(&mut self) -> Option<Vec<u8>> { match self.stream.next().await { Some(Ok(Message::Binary(msg))) => { Some(msg) } Some(a) => { debug!("received invalid msg: {:?}", a); None } None => None } } pub fn blocking_recv(&mut self) -> Option<Vec<u8>> { let fut = self.stream.next(); tokio::task::block_in_place(move || { tokio::runtime::Handle::current().block_on(async move { match fut.await { Some(Ok(Message::Binary(msg))) => { Some(msg) } Some(a) => { debug!("received invalid msg: {:?}", a); None } None => None, } }) }) } } impl<S> AsyncRead for RecvHalf<S> where S: AsyncRead + AsyncWrite + Unpin { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { if let Some(stream) = self.buffer.take() { if stream.len() <= buf.remaining() { buf.put_slice(&stream[..]); } else { let end = buf.remaining(); buf.put_slice(&stream[..end]); self.buffer.replace(stream.slice(end..)); } return Poll::Ready(Ok(())); } match self.stream.poll_next_unpin(cx) { Poll::Pending => Poll::Pending, Poll::Ready(None) => { Poll::Ready(Err(tokio::io::Error::new( tokio::io::ErrorKind::BrokenPipe, format!("Failed to receive data from websocket"), ))) }, Poll::Ready(Some(Err(err))) => { Poll::Ready(Err(tokio::io::Error::new( tokio::io::ErrorKind::BrokenPipe, format!( "Failed to receive data from websocket - {}", err.to_string() ), ))) }, Poll::Ready(Some(Ok(Message::Binary(stream)))) => { if stream.len() <= buf.remaining() { buf.put_slice(&stream[..]); } else { let end = buf.remaining(); buf.put_slice(&stream[..end]); self.buffer.replace(Bytes::from(stream).slice(end..)); } Poll::Ready(Ok(())) }, Poll::Ready(Some(Ok(Message::Close(_)))) => { Poll::Ready(Err(io::Error::new( io::ErrorKind::NotConnected, "web socket connection has closed" ))) }, Poll::Ready(Some(Ok(_))) => { Poll::Ready(Err(tokio::io::Error::new( tokio::io::ErrorKind::BrokenPipe, format!("Failed to receive data from websocket as the message was the wrong type") ))) }, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/webgl/src/prelude.rs
wasmer-bus/webgl/src/prelude.rs
pub use wasmer_bus; pub use wasmer_bus::abi::BusError; pub use super::api; pub use super::api::glenum; pub use super::error::WebGlError; pub use super::webgl::*; pub use async_trait::async_trait;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/webgl/src/lib.rs
wasmer-bus/webgl/src/lib.rs
pub mod api; pub mod prelude; pub mod webgl; pub mod error;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/webgl/src/webgl.rs
wasmer-bus/webgl/src/webgl.rs
use std::sync::Arc; pub use wasmer_bus::prelude::BusError; pub use super::api::glenum::*; use super::api; use super::error::WebGlError; #[derive(Debug, Clone)] pub struct WebGl { raster: Arc<dyn api::Raster>, ctx: Arc<dyn api::RenderingContext>, } impl WebGl { pub fn new() -> Result<WebGl, WebGlError> { let webgl = api::WebGlClient::new("os"); let ctx = webgl.blocking_context() .map_err(convert_err)?; let raster = ctx.blocking_raster() .map_err(convert_err)?; Ok( WebGl { raster, ctx } ) } pub fn create_program(&self) -> Program { Program { program: self.ctx.blocking_create_program().unwrap() } } pub fn create_buffer(&self) -> Buffer { Buffer { buffer: self.ctx.blocking_create_buffer().unwrap() } } pub fn create_vertex_array(&self) -> VertexArray { VertexArray { vertex_array: self.ctx.blocking_create_vertex_array().unwrap() } } pub fn create_texture(&self) -> Texture { Texture { texture: self.ctx.blocking_create_texture().unwrap() } } pub fn clear_color(&self, red: f32, green: f32, blue: f32, alpha: f32) { self.raster.blocking_clear_color(red, green, blue, alpha).unwrap(); } pub fn clear(&self, bit: BufferBit) { self.raster.blocking_clear(bit).unwrap(); } pub fn clear_depth(&self, value: f32) { self.raster.blocking_clear_depth(value).unwrap(); } pub fn draw_arrays(&self, mode: Primitives, first: i32, count: i32) { self.raster.blocking_draw_arrays(mode, first, count).unwrap(); } pub fn draw_elements(&self, mode: Primitives, count: i32, kind: DataType, offset: u32) { self.raster.blocking_draw_elements(mode, count, kind, offset).unwrap(); } pub fn enable(&self, flag: Flag) { self.raster.blocking_enable(flag).unwrap(); } pub fn disable(&self, flag: Flag) { self.raster.blocking_disable(flag).unwrap(); } pub fn cull_face(&self, culling: Culling) { self.raster.blocking_cull_face(culling).unwrap(); } pub fn depth_mask(&self, val: bool) { self.raster.blocking_depth_mask(val).unwrap(); } pub fn depth_funct(&self, val: DepthTest) { self.raster.blocking_depth_funct(val).unwrap(); } pub fn viewport(&self, x: i32, y: i32, width: u32, height: u32) { self.raster.blocking_viewport(x, y, width, height).unwrap(); } pub fn buffer_data(&self, kind: BufferKind, data: Vec<u8>, draw: DrawMode) { self.raster.blocking_buffer_data(kind, data, draw).unwrap(); } pub fn buffer_data_f32(&self, kind: BufferKind, data: &[f32], draw: DrawMode) { let data = data.iter().flat_map(|a| a.to_ne_bytes()).collect(); self.buffer_data(kind, data, draw); } pub fn unbind_buffer(&self, kind: BufferKind) { self.raster.blocking_unbind_buffer(kind).unwrap(); } pub fn read_pixels(&self, x: u32, y: u32, width: u32, height: u32, format: PixelFormat, kind: PixelType) -> Result<Vec<u8>, WebGlError> { self.raster.blocking_read_pixels(x, y, width, height, format, kind) .map_err(convert_err) } pub fn pixel_storei(&self, storage: PixelStorageMode, value: i32) { self.raster.blocking_pixel_storei(storage, value).unwrap(); } pub fn generate_mipmap(&self) { self.raster.blocking_generate_mipmap().unwrap(); } pub fn generate_mipmap_cube(&self) { self.raster.blocking_generate_mipmap_cube().unwrap(); } pub fn tex_image2d(&self, target: TextureBindPoint, level: u8, width: u32, height: u32, format: PixelFormat, kind: PixelType, pixels: &[u8]) { let pixels = pixels.to_vec(); self.raster.blocking_tex_image2d(target, level, width, height, format, kind, pixels).unwrap(); } pub fn tex_sub_image2d(&self, target: TextureBindPoint, level: u8, xoffset: u32, yoffset: u32, width: u32, height: u32, format: PixelFormat, kind: PixelType, pixels: Vec<u8>) { let pixels = pixels.to_vec(); self.raster.blocking_tex_sub_image2d(target, level, xoffset, yoffset, width, height, format, kind, pixels).unwrap(); } pub fn compressed_tex_image2d(&self, target: TextureBindPoint, level: u8, compression: TextureCompression, width: u32, height: u32, pixels: Vec<u8>) { let pixels = pixels.to_vec(); self.raster.blocking_compressed_tex_image2d(target, level, compression, width, height, pixels).unwrap(); } pub fn unbind_texture(&self, active: u32) { self.raster.blocking_unbind_texture(active).unwrap(); } pub fn unbind_texture_cube(&self, active: u32) { self.raster.blocking_unbind_texture_cube(active).unwrap(); } pub fn blend_equation(&self, eq: BlendEquation) { self.raster.blocking_blend_equation(eq).unwrap(); } pub fn blend_func(&self, b1: BlendMode, b2: BlendMode) { self.raster.blocking_blend_func(b1, b2).unwrap(); } pub fn blend_color(&self, red: f32, green: f32, blue: f32, alpha: f32) { self.raster.blocking_blend_color(red, green, blue, alpha).unwrap(); } pub fn tex_parameteri(&self, kind: TextureKind, pname: TextureParameter, val: i32) { self.raster.blocking_tex_parameteri(kind, pname, val).unwrap(); } pub fn tex_parameterfv(&self, kind: TextureKind, pname: TextureParameter, val: f32) { self.raster.blocking_tex_parameterfv(kind, pname, val).unwrap(); } pub fn draw_buffers(&self, buffers: &[ColorBuffer]) { let buffers = buffers.to_vec(); self.raster.blocking_draw_buffers(buffers).unwrap(); } pub fn create_framebuffer(&self) -> FrameBuffer { FrameBuffer { framebuffer: self.raster.blocking_create_framebuffer().unwrap() } } pub fn unbind_framebuffer(&self, buffer: Buffers) { self.raster.blocking_unbind_framebuffer(buffer).unwrap(); } pub fn unbind_vertex_array(&self) { self.raster.blocking_unbind_vertex_array().unwrap(); } pub async fn sync(&self) { self.raster.sync().await.unwrap(); } } #[derive(Debug, Clone)] pub struct Buffer { buffer: Arc<dyn api::Buffer>, } impl Buffer { pub fn bind(&self, kind: BufferKind) { self.buffer.blocking_bind_buffer(kind).unwrap(); } } #[derive(Debug, Clone)] pub struct VertexArray { vertex_array: Arc<dyn api::VertexArray>, } impl VertexArray { pub fn bind(&self) { self.vertex_array.blocking_bind_vertex_array().unwrap(); } pub fn unbind(&self) { self.vertex_array.blocking_unbind_vertex_array().unwrap(); } } #[derive(Debug, Clone)] pub struct Texture { texture: Arc<dyn api::Texture>, } impl Texture { pub fn active_texture(&self, active: u32) { self.texture.blocking_active_texture(active).unwrap(); } pub fn bind_texture(&self, target: TextureKind) { self.texture.blocking_bind_texture(target).unwrap(); } pub fn bind_texture_cube(&self, target: TextureKind) { self.texture.blocking_bind_texture_cube(target).unwrap(); } pub fn framebuffer_texture2d(&self, target: Buffers, attachment: Buffers, textarget: TextureBindPoint, level: i32) { self.texture.blocking_framebuffer_texture2d(target, attachment, textarget, level).unwrap(); } } #[derive(Debug, Clone)] pub struct FrameBuffer { framebuffer: Arc<dyn api::FrameBuffer>, } impl FrameBuffer { pub fn bind_framebuffer(&self, buffer: Buffers) { self.framebuffer.blocking_bind_framebuffer(buffer).unwrap(); } } #[derive(Debug, Clone)] pub struct Program { program: Arc<dyn api::Program>, } impl Program { pub fn create_shader(&self, kind: ShaderKind) -> Shader { Shader { shader: self.program.blocking_create_shader(kind).unwrap() } } pub fn link(&self) -> Result<(), WebGlError> { self.program.blocking_link_program() .map_err(convert_err)? .map_err(|err| WebGlError::LinkError(err)) } pub fn use_program(&self) { self.program.blocking_use_program().unwrap(); } pub fn get_attrib_location(&self, name: &str) -> ProgramLocation { ProgramLocation { location: self.program.blocking_get_attrib_location(name.to_string()).unwrap() } } pub fn get_uniform_location(&self, name: &str) -> UniformLocation { UniformLocation { location: self.program.blocking_get_uniform_location(name.to_string()).unwrap() } } } #[derive(Debug, Clone)] pub struct UniformLocation { location: Arc<dyn api::UniformLocation>, } impl UniformLocation { pub fn uniform_matrix_4fv(&self, transpose: bool, value: [[f32; 4]; 4]) { self.location.blocking_uniform_matrix_4fv(transpose, value).unwrap(); } pub fn uniform_matrix_3fv(&self, transpose: bool, value: [[f32; 3]; 3]) { self.location.blocking_uniform_matrix_3fv(transpose, value).unwrap(); } pub fn uniform_matrix_2fv(&self, transpose: bool, value: [[f32; 2]; 2]) { self.location.blocking_uniform_matrix_2fv(transpose, value).unwrap(); } pub fn uniform_1i(&self, value: i32) { self.location.blocking_uniform_1i(value).unwrap(); } pub fn uniform_1f(&self, value: f32) { self.location.blocking_uniform_1f(value).unwrap(); } pub fn uniform_2f(&self, v1: f32, v2: f32) { let value = (v1, v2); self.location.blocking_uniform_2f(value).unwrap(); } pub fn uniform_3f(&self, v1: f32, v2: f32, v3: f32) { let value = (v1, v2, v3); self.location.blocking_uniform_3f(value).unwrap(); } pub fn uniform_4f(&self, v1: f32, v2: f32, v3: f32, v4: f32) { let value = (v1, v2, v3, v4); self.location.blocking_uniform_4f(value).unwrap(); } } #[derive(Debug, Clone)] pub struct ProgramLocation { location: Arc<dyn api::ProgramLocation>, } impl ProgramLocation { pub fn bind(&self) { self.location.blocking_bind_program_location().unwrap(); } pub fn vertex_attrib_pointer(&self, size: AttributeSize, kind: DataType, normalized: bool, stride: u32, offset: u32) { self.location.blocking_vertex_attrib_pointer(size, kind, normalized, stride, offset).unwrap(); } pub fn enable(&self) { self.location.blocking_enable_vertex_attrib_array().unwrap(); } } #[derive(Debug, Clone)] pub struct Shader { shader: Arc<dyn api::Shader>, } impl Shader { pub fn set_source(&self, source: &str) { let source = source.to_string(); self.shader.blocking_shader_source(source).unwrap(); } pub fn compile(&self) -> Result<(), WebGlError> { self.shader.blocking_shader_compile() .map_err(convert_err)? .map_err(|err| WebGlError::CompileError(err)) } pub fn attach(&self) -> Result<(), WebGlError> { self.shader.blocking_attach_shader() .map_err(convert_err)? .map_err(|err| WebGlError::LinkError(err)) } } fn convert_err(err: BusError) -> WebGlError { WebGlError::IO(err.into_io_error()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/webgl/src/error.rs
wasmer-bus/webgl/src/error.rs
use std::fmt; #[derive(Debug)] pub enum WebGlError { IO(std::io::Error), CompileError(String), LinkError(String), } impl fmt::Display for WebGlError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { WebGlError::IO(err) => { fmt::Display::fmt(err, f) } WebGlError::CompileError(err) => { write!(f, "compile error - {}", err) } WebGlError::LinkError(err) => { write!(f, "link error - {}", err) } } } } impl std::error::Error for WebGlError { }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/webgl/src/api/mod.rs
wasmer-bus/webgl/src/api/mod.rs
use std::sync::Arc; #[allow(unused_imports)] use wasmer_bus::macros::*; pub mod glenum; pub use glenum::*; #[wasmer_bus(format = "bincode")] pub trait WebGl { async fn context(&self) -> Arc<dyn RenderingContext>; } #[wasmer_bus(format = "bincode")] pub trait RenderingContext { async fn raster(&self) -> Arc<dyn Raster>; async fn create_program(&self) -> Arc<dyn Program>; async fn create_buffer(&self) -> Arc<dyn Buffer>; async fn create_vertex_array(&self) -> Arc<dyn VertexArray>; async fn create_texture(&self) -> Arc<dyn Texture>; } #[wasmer_bus(format = "bincode")] pub trait Buffer { async fn bind_buffer(&self, kind: BufferKind); } #[wasmer_bus(format = "bincode")] pub trait Texture { async fn active_texture(&self, active: u32); async fn bind_texture(&self, target: TextureKind); async fn bind_texture_cube(&self, target: TextureKind); async fn framebuffer_texture2d(&self, target: Buffers, attachment: Buffers, textarget: TextureBindPoint, level: i32); } #[wasmer_bus(format = "bincode")] pub trait Raster { async fn clear_color(&self, red: f32, green: f32, blue: f32, alpha: f32); async fn clear(&self, bit: BufferBit); async fn clear_depth(&self, value: f32); async fn draw_arrays(&self, mode: Primitives, first: i32, count: i32); async fn draw_elements(&self, mode: Primitives, count: i32, kind: DataType, offset: u32); async fn enable(&self, flag: Flag); async fn disable(&self, flag: Flag); async fn cull_face(&self, culling: Culling); async fn depth_mask(&self, val: bool); async fn depth_funct(&self, val: DepthTest); async fn viewport(&self, x: i32, y: i32, width: u32, height: u32); async fn buffer_data(&self, kind: BufferKind, data: Vec<u8>, draw: DrawMode); async fn unbind_buffer(&self, kind: BufferKind); async fn read_pixels(&self, x: u32, y: u32, width: u32, height: u32, format: PixelFormat, kind: PixelType) -> Vec<u8>; async fn pixel_storei(&self, storage: PixelStorageMode, value: i32); async fn generate_mipmap(&self); async fn generate_mipmap_cube(&self); async fn tex_image2d(&self, target: TextureBindPoint, level: u8, width: u32, height: u32, format: PixelFormat, kind: PixelType, pixels: Vec<u8>); async fn tex_sub_image2d(&self, target: TextureBindPoint, level: u8, xoffset: u32, yoffset: u32, width: u32, height: u32, format: PixelFormat, kind: PixelType, pixels: Vec<u8>); async fn compressed_tex_image2d(&self, target: TextureBindPoint, level: u8, compression: TextureCompression, width: u32, height: u32, pixels: Vec<u8>); async fn unbind_texture(&self, active: u32); async fn unbind_texture_cube(&self, active: u32); async fn blend_equation(&self, eq: BlendEquation); async fn blend_func(&self, b1: BlendMode, b2: BlendMode); async fn blend_color(&self, red: f32, green: f32, blue: f32, alpha: f32); async fn tex_parameteri(&self, kind: TextureKind, pname: TextureParameter, param: i32); async fn tex_parameterfv(&self, kind: TextureKind, pname: TextureParameter, param: f32); async fn draw_buffers(&self, buffers: Vec<ColorBuffer>); async fn create_framebuffer(&self) -> Arc<dyn FrameBuffer>; async fn unbind_framebuffer(&self, buffer: Buffers); async fn unbind_vertex_array(&self); async fn sync(&self); } #[wasmer_bus(format = "bincode")] pub trait FrameBuffer { async fn bind_framebuffer(&self, buffer: Buffers); } #[wasmer_bus(format = "bincode")] pub trait Program { async fn create_shader(&self, kind: ShaderKind) -> Arc<dyn Shader>; async fn link_program(&self) -> Result<(), String>; async fn use_program(&self); async fn get_attrib_location(&self, name: String) -> Arc<dyn ProgramLocation>; async fn get_uniform_location(&self, name: String) -> Arc<dyn UniformLocation>; async fn get_program_parameter(&self, pname: ShaderParameter) -> Arc<dyn ProgramParameter>; } #[wasmer_bus(format = "bincode")] pub trait ProgramParameter { } #[wasmer_bus(format = "bincode")] pub trait ProgramLocation { async fn bind_program_location(&self); async fn vertex_attrib_pointer(&self, size: AttributeSize, kind: DataType, normalized: bool, stride: u32, offset: u32); async fn enable_vertex_attrib_array(&self); } #[wasmer_bus(format = "bincode")] pub trait VertexArray { async fn bind_vertex_array(&self); async fn unbind_vertex_array(&self); } #[wasmer_bus(format = "bincode")] pub trait UniformLocation { async fn uniform_matrix_4fv(&self, transpose: bool, value: [[f32; 4]; 4]); async fn uniform_matrix_3fv(&self, transpose: bool, value: [[f32; 3]; 3]); async fn uniform_matrix_2fv(&self, transpose: bool, value: [[f32; 2]; 2]); async fn uniform_1i(&self, value: i32); async fn uniform_1f(&self, value: f32); async fn uniform_2f(&self, value: (f32, f32)); async fn uniform_3f(&self, value: (f32, f32, f32)); async fn uniform_4f(&self, value: (f32, f32, f32, f32)); } #[wasmer_bus(format = "bincode")] pub trait Shader { async fn shader_source(&self, source: String); async fn shader_compile(&self) -> Result<(), String>; async fn attach_shader(&self) -> Result<(), String>; }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/webgl/src/api/glenum.rs
wasmer-bus/webgl/src/api/glenum.rs
use serde::*; /// Constants passed to WebGLRenderingContext.vertexAttribPointer() #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum AttributeSize { One = 1, Two = 2, Three = 3, Four = 4, } /// Constants passed to WebGLRenderingContext.createShader() #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum ShaderKind { /// Passed to createShader to define a fragment shader. Fragment = 0x8B30, /// Passed to createShader to define a vertex shader Vertex = 0x8B31, } /// Constants passed to WebGLRenderingContext.createShader() #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum ShaderParameter { /// Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error CompileStatus = 0x8B81, /// Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise. DeleteStatus = 0x8B80, /// Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error. LinkStatus = 0x8B82, /// Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found. ValidateStatus = 0x8B83, /// Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred. AttachedShaders = 0x8B85, /// Passed to getProgramParameter to get the number of attributes active in a program. ActiveAttributes = 0x8B89, /// Passed to getProgramParamter to get the number of uniforms active in a program. ActiveUniforms = 0x8B86, /// The maximum number of entries possible in the vertex attribute list. MaxVertexAttribs = 0x8869, /// MaxVertexUniformVectors = 0x8DFB, /// MaxVaryingVectors = 0x8DFC, /// MaxCombinedTextureImageUnits = 0x8B4D, /// MaxVertexTextureImageUnits = 0x8B4C, /// Implementation dependent number of maximum texture units. At least 8. MaxTextureImageUnits = 0x8872, /// MaxFragmentUniformVectors = 0x8DFD, /// ShaderType = 0x8B4F, /// ShadingLanguageVersion = 0x8B8C, /// CurrentProgram = 0x8B8D, } /// Passed to bindBuffer or bufferData to specify the type of buffer being used. #[derive(Debug, Copy, Clone, Serialize, Deserialize)] pub enum BufferKind { /// to store vertex attributes Array = 0x8892, /// to store vertex array indices ElementArray = 0x8893, } #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum DrawMode { /// Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often. Static = 0x88E4, /// Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often. Dynamic = 0x88E8, /// Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often. Stream = 0x88E0, } #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum BufferParameter { /// Passed to getBufferParameter to get a buffer's size. Size = 0x8764, /// Passed to getBufferParameter to get the hint for the buffer passed in when it was created. Usage = 0x8765, } #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum DataType { I8 = 0x1400, U8 = 0x1401, I16 = 0x1402, U16 = 0x1403, I32 = 0x1404, U32 = 0x1405, Float = 0x1406, } #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum Flag { /// Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method. Blend = 0x0BE2, /// Passed to enable/disable to turn on/off the depth test. Can also be used with getParameter to query the depth test. DepthTest = 0x0B71, /// Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method. Dither = 0x0BD0, /// Passed to enable/disable to turn on/off the polygon offset. Useful for rendering hidden-line images, decals, and or solids with highlighted edges. Can also be used with getParameter to query the scissor test. PolygonOffsetFill = 0x8037, /// Passed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels. SampleAlphaToCoverage = 0x809E, /// Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling. SampleCoverage = 0x80A0, /// Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test. ScissorTest = 0x0C11, /// Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test. StencilTest = 0x0B90, } #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum BufferBit { /// Passed to clear to clear the current depth buffer. Depth = 0x00000100, /// Passed to clear to clear the current stencil buffer. Stencil = 0x00000400, /// Passed to clear to clear the current color buffer. Color = 0x00004000, } /// Passed to drawElements or drawArrays to draw primitives. #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum Primitives { /// Passed to drawElements or drawArrays to draw single points. Points = 0x0000, /// Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it. Lines = 0x0001, /// Passed to drawElements or drawArrays to draw lines. Each set of two vertices is treated as a separate line segment. LineLoop = 0x0002, /// Passed to drawElements or drawArrays to draw a connected group of line segments from the first vertex to the last. LineStrip = 0x0003, /// Passed to drawElements or drawArrays to draw triangles. Each set of three vertices creates a separate triangle. Triangles = 0x0004, /// Passed to drawElements or drawArrays to draw a connected group of triangles. TriangleStrip = 0x0005, /// Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan. TriangleFan = 0x0006, } /// Constants passed to WebGLRenderingContext.blendFunc() or WebGLRenderingContext.blendFuncSeparate() to specify the blending mode (for both, RBG and alpha, or separately). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum BlendMode { /// Passed to blendFunc or blendFuncSeparate to turn off a component. Zero = 0, /// Passed to blendFunc or blendFuncSeparate to turn on a component. One = 1, /// Passed to blendFunc or blendFuncSeparate to multiply a component by the source elements color. SrcColor = 0x0300, /// Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source elements color. OneMinusSrcColor = 0x0301, /// Passed to blendFunc or blendFuncSeparate to multiply a component by the source's alpha. SrcAlpha = 0x0302, /// Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source's alpha. OneMinusSrcAlpha = 0x0303, /// Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's alpha. DstAlpha = 0x0304, /// Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's alpha. OneMinusDstAlpha = 0x0305, /// Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's color. DstColor = 0x0306, /// Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's color. OneMinusDstColor = 0x0307, /// Passed to blendFunc or blendFuncSeparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha. SrcAlphaSaturate = 0x0308, /// Passed to blendFunc or blendFuncSeparate to specify a constant color blend function. ConstantColor = 0x8001, /// Passed to blendFunc or blendFuncSeparate to specify one minus a constant color blend function. OneMinusConstantColor = 0x8002, /// Passed to blendFunc or blendFuncSeparate to specify a constant alpha blend function. ConstantAlpha = 0x8003, /// Passed to blendFunc or blendFuncSeparate to specify one minus a constant alpha blend function. OneMinusConstantAlpha = 0x8004, } /// Constants passed to WebGLRenderingContext.blendEquation() /// or WebGLRenderingContext.blendEquationSeparate() to control /// how the blending is calculated (for both, RBG and alpha, or separately). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum BlendEquation { /// Passed to blendEquation or blendEquationSeparate to set an addition blend function. FuncAdd = 0x8006, /// Passed to blendEquation or blendEquationSeparate to specify a subtraction blend function (source - destination). FuncSubstract = 0x800A, /// Passed to blendEquation or blendEquationSeparate to specify a reverse subtraction blend function (destination - source). FuncReverseSubtract = 0x800B, } /// Constants passed to WebGLRenderingContext.getParameter() to specify what information to return. #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum Parameter { /// Passed to getParameter to get the current RGB blend function. same as BlendEquationRgb BlendEquation = 0x8009, /// Passed to getParameter to get the current alpha blend function. Same as BLEND_EQUATION BlendEquationAlpha = 0x883D, /// Passed to getParameter to get the current destination RGB blend function. BlendDstRgb = 0x80C8, /// Passed to getParameter to get the current destination RGB blend function. BlendSrcRgb = 0x80C9, /// Passed to getParameter to get the current destination alpha blend function. BlendDstAlpha = 0x80CA, /// Passed to getParameter to get the current source alpha blend function. BlendSrcAlpha = 0x80CB, /// Passed to getParameter to return a the current blend color. BlendColor = 0x8005, /// Passed to getParameter to get the array buffer binding. ArrayBufferBinding = 0x8894, /// Passed to getParameter to get the current element array buffer. ElementArrayBufferBinding = 0x8895, /// Passed to getParameter to get the current lineWidth (set by the lineWidth method). LineWidth = 0x0B21, /// Passed to getParameter to get the current size of a point drawn with gl.POINTS AliasedPointSizeRange = 0x846D, /// Passed to getParameter to get the range of available widths for a line. Returns a length-2 array with the lo value at 0, and hight at 1. AliasedLineWidthRange = 0x846E, /// Passed to getParameter to get the current value of cullFace. Should return FRONT, BACK, or FRONT_AND_BACK CullFaceMode = 0x0B45, /// Passed to getParameter to determine the current value of frontFace. Should return CW or CCW. FrontFace = 0x0B46, /// Passed to getParameter to return a length-2 array of floats giving the current depth range. DepthRange = 0x0B70, /// Passed to getParameter to determine if the depth write mask is enabled. DepthWritemask = 0x0B72, /// Passed to getParameter to determine the current depth clear value. DepthClearValue = 0x0B73, /// Passed to getParameter to get the current depth function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL. DepthFunc = 0x0B74, /// Passed to getParameter to get the value the stencil will be cleared to. StencilClearValue = 0x0B91, /// Passed to getParameter to get the current stencil function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL. StencilFunc = 0x0B92, /// Passed to getParameter to get the current stencil fail function. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. StencilFail = 0x0B94, /// Passed to getParameter to get the current stencil fail function should the depth buffer test fail. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. StencilPassDepthFail = 0x0B95, /// Passed to getParameter to get the current stencil fail function should the depth buffer test pass. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. StencilPassDepthPass = 0x0B96, /// Passed to getParameter to get the reference value used for stencil tests. StencilRef = 0x0B97, /// StencilValueMask = 0x0B93, /// StencilWritemask = 0x0B98, /// StencilBackFunc = 0x8800, /// StencilBackFail = 0x8801, /// StencilBackPassDepthFail = 0x8802, /// StencilBackPassDepthPass = 0x8803, /// StencilBackRef = 0x8CA3, /// StencilBackValueMask = 0x8CA4, /// StencilBackWritemask = 0x8CA5, /// Returns an Int32Array with four elements for the current viewport dimensions. Viewport = 0x0BA2, /// Returns an Int32Array with four elements for the current scissor box dimensions. ScissorBox = 0x0C10, /// ColorClearValue = 0x0C22, /// ColorWritemask = 0x0C23, /// UnpackAlignment = 0x0CF5, /// PackAlignment = 0x0D05, /// MaxTextureSize = 0x0D33, /// MaxViewportDims = 0x0D3A, /// SubpixelBits = 0x0D50, /// RedBits = 0x0D52, /// GreenBits = 0x0D53, /// BlueBits = 0x0D54, /// AlphaBits = 0x0D55, /// DepthBits = 0x0D56, /// StencilBits = 0x0D57, /// PolygonOffsetUnits = 0x2A00, /// PolygonOffsetFactor = 0x8038, /// TextureBinding2d = 0x8069, /// SampleBuffers = 0x80A8, /// Samples = 0x80A9, /// SampleCoverageValue = 0x80AA, /// SampleCoverageInvert = 0x80AB, /// CompressedTextureFormats = 0x86A3, /// Vendor = 0x1F00, /// Renderer = 0x1F01, /// Version = 0x1F02, /// ImplementationColorReadType = 0x8B9A, /// ImplementationColorReadFormat = 0x8B9B, /// BrowserDefaultWebgl = 0x9244, /// TextureBindingCubeMap = 0x8514, /// MaxCubeMapTextureSize = 0x851C, } /// Constants passed to WebGLRenderingContext.getVertexAttrib(). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum VertexAttrib { /// Passed to getVertexAttrib to read back the current vertex attribute. Current = 0x8626, /// ArrayEnabled = 0x8622, /// ArraySize = 0x8623, /// ArrayStride = 0x8624, /// ArrayType = 0x8625, /// ArrayNormalized = 0x886A, /// ArrayPointer = 0x8645, /// ArrayBufferBinding = 0x889F, } /// Constants passed to WebGLRenderingContext.cullFace(). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum Culling { /// Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method. CullFace = 0x0B44, /// Passed to cullFace to specify that only front faces should be drawn. Front = 0x0404, /// Passed to cullFace to specify that only back faces should be drawn. Back = 0x0405, /// Passed to cullFace to specify that front and back faces should be drawn. FrontAndBack = 0x0408, } /// Constants returned from WebGLRenderingContext.getError(). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum Error { /// Returned from getError. NoError = 0, /// Returned from getError. InvalidEnum = 0x0500, /// Returned from getError. InvalidValue = 0x0501, /// Returned from getError. InvalidOperation = 0x0502, /// Returned from getError. OutOfMemory = 0x0505, /// Returned from getError. ContextLostWebgl = 0x9242, } /// Constants passed to WebGLRenderingContext.frontFace(). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum FrontFaceDirection { /// Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction CW = 0x0900, /// Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction CCW = 0x0901, } /// Constants passed to WebGLRenderingContext.depthFunc(). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum DepthTest { /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn. Never = 0x0200, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn. Always = 0x0207, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value. Less = 0x0201, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value. Equal = 0x0202, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value. Lequal = 0x0203, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value. Greater = 0x0204, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value. Gequal = 0x0206, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value. Notequal = 0x0205, } /// Constants passed to WebGLRenderingContext.stencilFunc(). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum StencilTest { /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn. Never = 0x0200, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn. Always = 0x0207, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value. Less = 0x0201, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value. Equal = 0x0202, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value. Lequal = 0x0203, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value. Greater = 0x0204, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value. Gequal = 0x0206, /// Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value. Notequal = 0x0205, } /// Constants passed to WebGLRenderingContext.stencilOp(). #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum StencilAction { /// Keep = 0x1E00, /// Replace = 0x1E01, /// Incr = 0x1E02, /// Decr = 0x1E03, /// Invert = 0x150A, /// IncrWrap = 0x8507, /// DecrWrap = 0x8508, } #[derive(Debug, Copy, Clone, Serialize, Deserialize)] pub enum PixelType { /// UnsignedByte = 0x1401, /// UnsignedShort4444 = 0x8033, /// UnsignedShort5551 = 0x8034, /// UnsignedShort565 = 0x8363, /// UnsignedShort = 0x1403, /// UnsignedInt = 0x1405, /// UnsignedInt24 = 0x84FA, /// Float = 0x1406, } #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum PixelFormat { /// DepthComponent = 0x1902, /// Alpha = 0x1906, /// Rgb = 0x1907, /// Rgba = 0x1908, /// Luminance = 0x1909, /// LuminanceAlpha = 0x190A, } /// Constants passed to WebGLRenderingContext.hint() #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum Hint { /// There is no preference for this behavior. DontCare = 0x1100, /// The most efficient behavior should be used. Fastest = 0x1101, /// The most correct or the highest quality option should be used. Nicest = 0x1102, /// Hint for the quality of filtering when generating mipmap images with WebGLRenderingContext.generateMipmap(). GenerateMipmapHint = 0x8192, } /// WebGLRenderingContext.texParameter[fi]() or WebGLRenderingContext.bindTexture() "target" parameter #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum TextureKind { /// Texture2d = 0x0DE1, /// TextureCubeMap = 0x8513, } /// WebGLRenderingContext.texParameter[fi]() "pname" parameter #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum TextureParameter { /// TextureMagFilter = 0x2800, /// TextureMinFilter = 0x2801, /// TextureWrapS = 0x2802, /// TextureWrapT = 0x2803, /// BorderColor = 0x1004, /// WebGL 2.0 only TextureWrapR = 32882, } /// WebGLRenderingContext.texImage2D() "target" parameter #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum TextureBindPoint { /// Texture2d = 0x0DE1, /// TextureCubeMapPositiveX = 0x8515, /// TextureCubeMapNegativeX = 0x8516, /// TextureCubeMapPositiveY = 0x8517, /// TextureCubeMapNegativeY = 0x8518, /// TextureCubeMapPositiveZ = 0x8519, /// TextureCubeMapNegativeZ = 0x851A, } /// WebGLRenderingContext.texParameter[fi]() "param" parameter #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum TextureMagFilter { /// Nearest = 0x2600, /// Linear = 0x2601, } /// WebGLRenderingContext.texParameter[fi]() "param" parameter #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum TextureMinFilter { /// Nearest = 0x2600, /// Linear = 0x2601, /// NearestMipmapNearest = 0x2700, /// LinearMipmapNearest = 0x2701, /// NearestMipmapLinear = 0x2702, /// LinearMipmapLinear = 0x2703, } /// WebGLRenderingContext.texParameter[fi]() "param" parameter #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum TextureWrap { /// Repeat = 0x2901, /// ClampToEdge = 0x812F, /// MirroredRepeat = 0x8370, } /// Constants passed to WebGLRenderingContext.hint() #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum Buffers { /// Framebuffer = 0x8D40, /// Renderbuffer = 0x8D41, /// Rgba4 = 0x8056, /// Rgb5A1 = 0x8057, /// Rgb565 = 0x8D62, /// DepthComponent16 = 0x81A5, /// StencilIndex = 0x1901, /// StencilIndex8 = 0x8D48, /// DepthStencil = 0x84F9, /// RenderbufferWidth = 0x8D42, /// RenderbufferHeight = 0x8D43, /// RenderbufferInternalFormat = 0x8D44, /// RenderbufferRedSize = 0x8D50, /// RenderbufferGreenSize = 0x8D51, /// RenderbufferBlueSize = 0x8D52, /// RenderbufferAlphaSize = 0x8D53, /// RenderbufferDepthSize = 0x8D54, /// RenderbufferStencilSize = 0x8D55, /// FramebufferAttachmentObjectType = 0x8CD0, /// FramebufferAttachmentObjectName = 0x8CD1, /// FramebufferAttachmentTextureLevel = 0x8CD2, /// FramebufferAttachmentTextureCubeMapFace = 0x8CD3, /// ColorAttachment0 = 0x8CE0, /// DepthAttachment = 0x8D00, /// StencilAttachment = 0x8D20, /// DepthStencilAttachment = 0x821A, /// None = 0, /// FramebufferComplete = 0x8CD5, /// FramebufferIncompleteAttachment = 0x8CD6, /// FramebufferIncompleteMissingAttachment = 0x8CD7, /// FramebufferIncompleteDimensions = 0x8CD9, /// FramebufferUnsupported = 0x8CDD, /// FramebufferBinding = 0x8CA6, /// RenderbufferBinding = 0x8CA7, /// MaxRenderbufferSize = 0x84E8, /// InvalidFramebufferOperation = 0x0506, } /// Constants passed to WebGLRenderingContext.hint() #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum PixelStorageMode { /// UnpackFlipYWebgl = 0x9240, /// UnpackPremultiplyAlphaWebgl = 0x9241, /// UnpackColorspaceConversionWebgl = 0x9243, /// Packing of pixel data into memory. /// Can be 1, 2, 4, 8 defaults to 4 PackAlignment = 0x0D05, /// Unpacking of pixel data from memory /// Can be 1, 2, 4, 8 defaults to 4 UnpackAlignment = 0x0CF5, } /// #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum ShaderPrecision { /// LowFloat = 0x8DF0, /// MediumFloat = 0x8DF1, /// HighFloat = 0x8DF2, /// LowInt = 0x8DF3, /// MediumInt = 0x8DF4, /// HighInt = 0x8DF5, } /// Constants passed to WebGLRenderingContext.hint() #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum UniformType { /// FloatVec2 = 0x8B50, /// FloatVec3 = 0x8B51, /// FloatVec4 = 0x8B52, /// IntVec2 = 0x8B53, /// IntVec3 = 0x8B54, /// IntVec4 = 0x8B55, /// Bool = 0x8B56, /// BoolVec2 = 0x8B57, /// BoolVec3 = 0x8B58, /// BoolVec4 = 0x8B59, /// FloatMat2 = 0x8B5A, /// FloatMat3 = 0x8B5B, /// FloatMat4 = 0x8B5C, /// Sampler2d = 0x8B5E, /// SamplerCube = 0x8B60, } /// #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum TextureCompression { /// A DXT1-compressed image in an RGB image format. RgbDxt1 = 0x83F0, /// A DXT1-compressed image in an RGB image format with a simple on/off alpha value. RgbaDxt1 = 0x83F1, /// A DXT3-compressed image in an RGBA image format. /// Compared to a 32-bit RGBA texture, it offers 4:1 compression. RgbaDxt3 = 0x83F2, /// A DXT5-compressed image in an RGBA image format. /// It also provides a 4:1 compression, /// but differs to the DXT3 compression in how the alpha compression is done. RgbaDxt5 = 0x83F3, } /// #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum ColorBuffer { None = 0, Back = 0x0405, ColorAttachment0 = 0x8CE0, ColorAttachment1 = 0x8CE1, ColorAttachment2 = 0x8CE2, ColorAttachment3 = 0x8CE3, ColorAttachment4 = 0x8CE4, ColorAttachment5 = 0x8CE5, ColorAttachment6 = 0x8CE6, ColorAttachment7 = 0x8CE7, ColorAttachment8 = 0x8CE8, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/webgl/examples/triangle.rs
wasmer-bus/webgl/examples/triangle.rs
use wasmer_bus_webgl::prelude::*; fn main() -> Result<(), WebGlError> { let context = WebGl::new()?; let program = context .create_program(); let vert_shader = compile_shader( &program, ShaderKind::Vertex, r##"#version 300 es in vec4 position; void main() { gl_Position = position; } "##, )?; let frag_shader = compile_shader( &program, ShaderKind::Fragment, r##"#version 300 es precision highp float; out vec4 outColor; void main() { outColor = vec4(1, 1, 1, 1); } "##, )?; link_program(&program, &vert_shader, &frag_shader)?; program.use_program(); let vertices: [f32; 9] = [-0.7, -0.7, 0.0, 0.7, -0.7, 0.0, 0.0, 0.7, 0.0]; let position_attribute_location = program .get_attrib_location("position"); let buffer = context.create_buffer(); buffer.bind(BufferKind::Array); context.buffer_data_f32(BufferKind::Array, &vertices[..], DrawMode::Static); let vao = context .create_vertex_array(); vao.bind(); position_attribute_location.vertex_attrib_pointer(AttributeSize::Three, DataType::Float, false, 0, 0); position_attribute_location.enable(); vao.bind(); let vert_count = (vertices.len() / 3) as i32; draw(&context, vert_count); std::thread::sleep(std::time::Duration::from_secs(4)); Ok(()) } #[allow(dead_code)] fn draw(context: &WebGl, vert_count: i32) { context.clear_color(0.0, 0.0, 0.4, 1.0); context.clear(BufferBit::Color); context.draw_arrays(Primitives::Triangles, 0, vert_count); } #[allow(dead_code)] fn compile_shader( program: &Program, shader_type: ShaderKind, source: &str, ) -> Result<Shader, WebGlError> { let shader = program.create_shader(shader_type); shader.set_source(source); shader.compile()?; Ok(shader) } #[allow(dead_code)] pub fn link_program( program: &Program, vert_shader: &Shader, frag_shader: &Shader, ) -> Result<(), WebGlError> { vert_shader.attach()?; frag_shader.attach()?; program.link()?; Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/prelude.rs
wasmer-bus/lib/src/prelude.rs
pub use crate::abi::call; pub use crate::abi::call_new; pub use crate::abi::subcall; pub use crate::abi::Call; #[cfg(feature = "rt")] pub use crate::task::listen; #[cfg(feature = "rt")] pub use crate::task::respond_to; #[cfg(feature = "macros")] pub use wasmer_bus_macros::*; pub use crate::abi::BusError; pub use crate::abi::CallHandle; pub use crate::abi::WasmBusSession; pub use async_trait::async_trait;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/lib.rs
wasmer-bus/lib/src/lib.rs
pub mod abi; pub mod engine; pub mod prelude; pub mod task; pub use async_trait::async_trait; #[cfg(feature = "macros")] pub mod macros { pub use wasmer_bus_macros::*; pub use async_trait::async_trait; }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/unsupported.rs
wasmer-bus/lib/src/abi/unsupported.rs
#![allow(unused_variables)] use std::time::Duration; use super::*; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; #[allow(dead_code)] pub fn bus_poll_once(timeout: Duration) -> usize { panic!("unsupported on this platform"); } pub fn bus_open_local( name: &str, resuse: bool, ) -> Result<BusHandle, BusError> { panic!("unsupported on this platform"); } pub fn bus_open_remote( name: &str, resuse: bool, instance: &str, token: &str, ) -> Result<BusHandle, BusError> { panic!("unsupported on this platform"); } pub fn bus_call( bid: BusHandle, topic_hash: u128, request: &[u8], format: SerializationFormat ) -> Result<CallHandle, BusError> { panic!("unsupported on this platform"); } pub fn bus_subcall( parent: CallHandle, topic_hash: u128, request: &[u8], format: SerializationFormat ) -> Result<CallHandle, BusError> { panic!("unsupported on this platform"); } pub fn call_close(handle: CallHandle) { panic!("unsupported on this platform"); } pub fn call_fault(handle: CallHandle, error: BusError) { panic!("unsupported on this platform"); } pub fn call_reply( handle: CallHandle, response: &[u8], format: SerializationFormat ) { panic!("unsupported on this platform"); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/respond_to.rs
wasmer-bus/lib/src/abi/respond_to.rs
use derivative::*; use std::collections::HashMap; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use std::sync::Mutex; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasmer_bus_types::SerializationFormat; use crate::abi::BusError; use crate::abi::CallHandle; pub enum RespondAction { Response(Vec<u8>), Fault(BusError), Detach } pub enum RespondActionTyped<T> { Response(T), Fault(BusError), Detach } type CallbackHandler = Arc< dyn Fn(CallHandle, Vec<u8>) -> Pin<Box<dyn Future<Output = RespondAction> + Send>> + Send + Sync, >; #[derive(Derivative, Clone)] #[derivative(Debug)] pub struct RespondToService { pub(crate) format: SerializationFormat, #[derivative(Debug = "ignore")] pub(crate) callbacks: Arc<Mutex<HashMap<CallHandle, CallbackHandler>>>, } impl RespondToService { pub fn new(format: SerializationFormat) -> RespondToService { RespondToService { format, callbacks: Default::default(), } } pub fn add( &self, handle: CallHandle, callback: Arc< dyn Fn( CallHandle, Vec<u8>, ) -> Pin<Box<dyn Future<Output = RespondAction> + Send>> + Send + Sync, >, ) { let mut callbacks = self.callbacks.lock().unwrap(); callbacks.insert(handle, callback); } pub fn remove(&self, handle: &CallHandle) -> Option<CallbackHandler> { let mut callbacks = self.callbacks.lock().unwrap(); callbacks.remove(handle) } pub async fn process(&self, callback_handle: CallHandle, handle: CallHandle, request: Vec<u8>, format: SerializationFormat) { let callback = { let callbacks = self.callbacks.lock().unwrap(); if let Some(callback) = callbacks.get(&callback_handle) { Arc::clone(callback) } else { crate::abi::syscall::call_fault(handle, BusError::InvalidHandle); return; } }; let mut leak = false; let res = callback.as_ref()(handle, request); match res.await { RespondAction::Response(a) => { crate::abi::syscall::call_reply(handle, &a[..], format); } RespondAction::Fault(err) => { crate::abi::syscall::call_fault(handle, err); } RespondAction::Detach => { leak = true; } } if leak == false { crate::engine::BusEngine::close(&handle, "request was processed (by listener)"); } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/reply.rs
wasmer-bus/lib/src/abi/reply.rs
use serde::*; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use super::*; #[derive(Debug)] #[must_use = "you must reply to the caller by invoking 'reply'"] pub struct Reply<RES, REQ> where REQ: de::DeserializeOwned, RES: Serialize, { scope: CallSmartHandle, format: SerializationFormat, request: REQ, _marker2: PhantomData<RES>, } impl<RES, REQ> Reply<RES, REQ> where REQ: de::DeserializeOwned, RES: Serialize, { pub fn id(&self) -> u64 { self.scope.cid().id } pub fn reply(self, response: RES) { super::reply(self.scope.cid(), self.format, response) } } pub trait FireAndForget<REQ> where REQ: de::DeserializeOwned, { fn take(self) -> REQ; } impl<REQ> FireAndForget<REQ> for Reply<(), REQ> where REQ: de::DeserializeOwned, { fn take(self) -> REQ { self.request } } impl<RES, REQ> Deref for Reply<RES, REQ> where REQ: de::DeserializeOwned, RES: Serialize, { type Target = REQ; fn deref(&self) -> &Self::Target { &self.request } } impl<RES, REQ> DerefMut for Reply<RES, REQ> where REQ: de::DeserializeOwned, RES: Serialize, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.request } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/call.rs
wasmer-bus/lib/src/abi/call.rs
use derivative::*; use serde::*; use std::borrow::Cow; use std::collections::HashMap; use std::future::Future; use std::marker::PhantomData; use std::ops::*; use std::pin::Pin; use std::sync::Arc; use std::sync::Mutex; use std::task::{ Context, Poll }; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; #[cfg(feature = "rt")] use crate::task::init_reactors; use super::*; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum CallbackResult { InvalidTopic, Success, Error, } pub trait CallOps where Self: Send + Sync, { fn data(&self, data: Vec<u8>, format: SerializationFormat); fn callback(&self, topic_hash: u128, data: Vec<u8>, format: SerializationFormat) -> CallbackResult; fn error(&self, error: BusError); fn topic_hash(&self) -> u128; } #[derive(Debug)] pub(crate) struct CallResult { pub data: Vec<u8>, pub format: SerializationFormat, } #[derive(Debug)] pub struct CallState { pub(crate) result: Option<Result<CallResult, BusError>>, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct CallInstance { pub(crate) instance: Cow<'static, str>, pub(crate) access_token: Cow<'static, str>, } impl CallInstance { pub fn new(instance: &str, access_token: &str) -> CallInstance { CallInstance { instance: instance.to_string().into(), access_token: access_token.to_string().into(), } } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum CallContext { NewBusCall { wapm: Cow<'static, str>, instance: Option<CallInstance>, }, OwnedSubCall { parent: CallSmartHandle, }, SubCall { parent: CallHandle, } } /// When this object is destroyed it will kill the call on the bus #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct CallSmartHandle { inside: Arc<CallSmartPointerInside>, } impl CallSmartHandle { pub fn new(handle: CallHandle) -> CallSmartHandle { CallSmartHandle { inside: Arc::new( CallSmartPointerInside { handle } ) } } pub fn cid(&self) -> CallHandle { self.inside.handle } } /// When this object is destroyed it will kill the call on the bus #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] struct CallSmartPointerInside { handle: CallHandle, } impl Drop for CallSmartPointerInside { fn drop(&mut self) { crate::abi::syscall::call_close(self.handle); crate::engine::BusEngine::close(&self.handle, "call closed"); } } #[derive(Derivative, Clone)] #[derivative(Debug)] #[must_use = "you must 'wait' or 'await' to actually send this call to other modules"] pub struct Call { pub(crate) ctx: CallContext, pub(crate) topic_hash: u128, #[derivative(Debug = "ignore")] pub(crate) callbacks: HashMap<u128, Arc<dyn Fn(Vec<u8>, SerializationFormat) -> CallbackResult + Send + Sync + 'static>>, pub(crate) handle: Option<CallHandle>, pub(crate) state: Arc<Mutex<CallState>>, } impl Call { pub fn new_call( wapm: Cow<'static, str>, topic_hash: u128, instance: Option<CallInstance>, ) -> Call { Call { ctx: CallContext::NewBusCall { wapm, instance }, state: Arc::new(Mutex::new(CallState { result: None, })), callbacks: Default::default(), handle: None, topic_hash, } } pub fn new_subcall( parent: CallHandle, topic_hash: u128, ) -> Call { Call { ctx: CallContext::SubCall { parent }, state: Arc::new(Mutex::new(CallState { result: None, })), callbacks: Default::default(), handle: None, topic_hash, } } pub fn handle(&self) -> Option<CallHandle> { self.handle.clone() } } impl CallOps for Call { fn data(&self, data: Vec<u8>, format: SerializationFormat) { let mut state = self.state.lock().unwrap(); state.result = Some(Ok(CallResult { data, format })); if let Some(scope) = self.handle.as_ref() { crate::engine::BusEngine::close(scope, "call has finished (with data)"); } } fn callback(&self, topic_hash: u128, data: Vec<u8>, format: SerializationFormat) -> CallbackResult { if let Some(funct) = self.callbacks.get(&topic_hash) { funct(data, format) } else { CallbackResult::InvalidTopic } } fn error(&self, error: BusError) { { let mut state = self.state.lock().unwrap(); state.result = Some(Err(error)); } if let Some(scope) = self.handle.as_ref() { crate::engine::BusEngine::close(scope, "call has failed"); } } fn topic_hash(&self) -> u128 { self.topic_hash } } #[derive(Debug)] #[must_use = "you must 'invoke' the builder for it to actually call anything"] pub struct CallBuilder { call: Option<Call>, format: SerializationFormat, request: Data, } impl CallBuilder { pub fn new(call: Call, request: Data, format: SerializationFormat) -> CallBuilder { CallBuilder { call: Some(call), format, request, } } } impl CallBuilder { /// Upon receiving a particular message from the service that is /// invoked this callback will take some action pub fn callback<C, F>(mut self, callback: F) -> Self where C: Serialize + de::DeserializeOwned + Send + Sync + 'static, F: Fn(C), F: Send + Sync + 'static, { self.call .as_mut() .unwrap() .register_callback(callback); self } // Invokes the call and detaches it so that it can be // using a contextual session pub fn detach(mut self) -> Result<CallHandle, BusError> { let mut call = self.call.take().unwrap(); let handle = self.invoke_internal(&mut call)?; Ok(handle) } /// Invokes the call with the specified callbacks pub fn invoke(mut self) -> Call { let mut call = self.call.take().unwrap(); match self.invoke_internal(&mut call) { Ok(scope) => { call.handle.replace(scope); }, Err(err) => { call.error(err); } } call } fn invoke_internal(&self, call: &mut Call) -> Result<CallHandle, BusError> { let handle = match &self.request { Data::Prepared(req) => { match &call.ctx { CallContext::NewBusCall { wapm, instance } => { #[cfg(feature = "rt")] init_reactors(); if let Some(ref instance) = instance { crate::abi::syscall::bus_open_remote( wapm.as_ref(), true, &instance.instance, &instance.access_token, ) } else { crate::abi::syscall::bus_open_local( wapm.as_ref(), true, ) }.and_then(|bid| { crate::abi::syscall::bus_call( bid, call.topic_hash, &req[..], self.format, ) }) }, CallContext::OwnedSubCall { parent } => { crate::abi::syscall::bus_subcall( parent.cid(), call.topic_hash, &req[..], self.format, ) }, CallContext::SubCall { parent } => { crate::abi::syscall::bus_subcall( parent.clone(), call.topic_hash, &req[..], self.format, ) }, } } Data::Error(err) => { return Err(err.clone()); } }; if let Ok(scope) = &handle { let mut state = crate::engine::BusEngine::write(); state.handles.insert(scope.clone()); state.calls.insert(scope.clone(), Arc::new(call.clone())); call.handle.replace(scope.clone()); } handle } } impl Call { /// Upon receiving a particular message from the service that is /// invoked this callback will take some action /// /// Note: This must be called before the invoke or things will go wrong /// hence there is a builder that invokes this in the right order fn register_callback<C, F>(&mut self, callback: F) where C: Serialize + de::DeserializeOwned + Send + Sync + 'static, F: Fn(C), F: Send + Sync + 'static, { let topic = std::any::type_name::<C>(); let topic_hash = crate::engine::hash_topic(&topic.into()); let callback = move |data, format: SerializationFormat| { if let Ok(data) = format.deserialize(data) { callback(data); CallbackResult::Success } else { debug!("deserialization failed during callback (format={}, topic={})", format, topic); CallbackResult::Error } }; self.callbacks.insert(topic_hash, Arc::new(callback)); } /// Returns the result of the call pub fn join<T>(self) -> Result<CallJoin<T>, BusError> where T: de::DeserializeOwned, { match self.handle.clone() { Some(scope) => { Ok(CallJoin::new(self, scope)) }, None => { trace!("must invoke the call before attempting to join on it"); Err(BusError::BusInvocationFailed) } } } } #[derive(Debug, Clone)] #[must_use = "this `Call` only does something when you consume it"] pub struct CallJoin<T> where T: de::DeserializeOwned, { call: Call, scope: CallHandle, _marker1: PhantomData<T>, } impl<T> CallJoin<T> where T: de::DeserializeOwned, { fn new(call: Call, scope: CallHandle) -> CallJoin<T> { CallJoin { call, scope, _marker1: PhantomData, } } /// Waits for the call to complete and returns the response from /// the server #[cfg(feature = "rt")] pub fn wait(self) -> Result<T, BusError> { crate::task::block_on(self) } #[cfg(not(feature = "rt"))] pub fn wait(self) -> Result<T, BusError> { Err(BusError::Unsupported) } /// Spawns the work on a background thread #[cfg(feature = "rt")] pub fn spawn(self) where T: Send + 'static, { crate::task::spawn(self); } #[cfg(not(feature = "rt"))] pub fn spawn(self) where T: Send + 'static, { panic!("spawning of calls is not supported on this platform"); } /// Tries to get the result of the call to the server but will not /// block the execution pub fn try_wait(&mut self) -> Result<Option<T>, BusError> where T: de::DeserializeOwned, { let response = { let mut state = self.call.state.lock().unwrap(); state.result.take() }; match response { Some(Ok(res)) => { let res = res.format.deserialize(res.data); match res { Ok(data) => Ok(Some(data)), Err(err) => Err(err), } } Some(Err(err)) => Err(err), None => Ok(None), } } } impl<T> Future for CallJoin<T> where T: de::DeserializeOwned, { type Output = Result<T, BusError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let response = { let mut state = self.call.state.lock().unwrap(); state.result.take() }; match response { Some(Ok(res)) => { let res = res.format.deserialize(res.data); match res { Ok(data) => Poll::Ready(Ok(data)), Err(err) => Poll::Ready(Err(err)), } } Some(Err(err)) => Poll::Ready(Err(err)), None => { crate::engine::BusEngine::subscribe(&self.scope, cx); Poll::Pending } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/session.rs
wasmer-bus/lib/src/abi/session.rs
use super::CallHandle; #[derive(Debug, Clone)] #[must_use = "the session must be consumed to tell the server when it needs to free resources"] pub struct WasmBusSession { handle: CallHandle, } impl WasmBusSession { pub fn new(handle: CallHandle) -> WasmBusSession { WasmBusSession { handle } } pub fn handle(&self) -> CallHandle { self.handle } pub fn close(mut self) { self.close_internal("session closed by user"); } fn close_internal(&mut self, reason: &'static str) { crate::engine::BusEngine::close(&self.handle, reason); } } impl Drop for WasmBusSession { fn drop(&mut self) { self.close_internal("session was dropped"); } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/mod.rs
wasmer-bus/lib/src/abi/mod.rs
mod call; mod data; mod finish; mod handle; mod listen; mod reply; mod respond_to; mod session; #[cfg(target_os = "wasi")] pub(crate) mod syscall; #[cfg(not(target_os = "wasi"))] pub(crate) mod unsupported; #[cfg(not(target_os = "wasi"))] pub(crate) use unsupported as syscall; use std::any::type_name; use std::borrow::Cow; pub use call::*; pub use data::*; pub use finish::*; pub use handle::*; pub use listen::*; pub use reply::*; pub use respond_to::*; use serde::Serialize; pub use session::*; pub use wasmer_bus_types::*; pub const MAX_BUS_POLL_EVENTS: usize = 50; pub fn call<T>( ctx: CallContext, format: SerializationFormat, request: T, ) -> CallBuilder where T: Serialize, { match ctx { CallContext::NewBusCall { wapm, instance } => { call_new(wapm, instance, format, request) }, CallContext::OwnedSubCall { parent } => { subcall(parent.cid(), format, request) }, CallContext::SubCall { parent } => { subcall(parent, format, request) } } } pub fn call_new<T>( wapm: Cow<'static, str>, instance: Option<CallInstance>, format: SerializationFormat, request: T, ) -> CallBuilder where T: Serialize, { let topic = type_name::<T>(); let topic_hash = crate::engine::hash_topic(&topic.into()); let call = Call::new_call(wapm, topic_hash, instance); let req = match format.serialize(request) { Ok(req) => Data::Prepared(req), Err(err) => Data::Error(err), }; CallBuilder::new(call, req, format) } pub fn subcall<T>( parent: CallHandle, format: SerializationFormat, request: T, ) -> CallBuilder where T: Serialize, { let topic = type_name::<T>(); let topic_hash = crate::engine::hash_topic(&topic.into()); let call = Call::new_subcall(parent, topic_hash); let req = match format.serialize(request) { Ok(req) => Data::Prepared(req), Err(err) => Data::Error(err), }; CallBuilder::new(call, req, format) } pub(self) fn reply<RES>(handle: CallHandle, format: SerializationFormat, response: RES) where RES: Serialize, { match format.serialize(response) { Ok(res) => { syscall::call_reply(handle, &res[..], format); } Err(_err) => syscall::call_fault(handle, BusError::SerializationFailed), } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/listen.rs
wasmer-bus/lib/src/abi/listen.rs
use derivative::*; use std::future::Future; use std::pin::Pin; use std::sync::Arc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasmer_bus_types::SerializationFormat; use crate::abi::BusError; use super::CallHandle; pub enum ListenAction { Response(Vec<u8>), Fault(BusError), Detach } pub enum ListenActionTyped<T> { Response(T), Fault(BusError), Detach } #[derive(Derivative, Clone)] #[derivative(Debug)] pub struct ListenService { pub(crate) format: SerializationFormat, #[derivative(Debug = "ignore")] pub(crate) callback: Arc< dyn Fn( CallHandle, Vec<u8>, ) -> Pin<Box<dyn Future<Output = ListenAction> + Send>> + Send + Sync, >, } impl ListenService { pub fn new( format: SerializationFormat, callback: Arc< dyn Fn( CallHandle, Vec<u8>, ) -> Pin<Box<dyn Future<Output = ListenAction> + Send>> + Send + Sync, >, ) -> ListenService { ListenService { format, callback, } } pub async fn process(&self, handle: CallHandle, request: Vec<u8>, format: SerializationFormat) { let callback = Arc::clone(&self.callback); let res = callback.as_ref()(handle, request); let mut leak = false; match res.await { ListenAction::Response(a) => { crate::abi::syscall::call_reply(handle, &a[..], format); } ListenAction::Fault(err) => { crate::abi::syscall::call_fault(handle, err); } ListenAction::Detach => { leak = true; } } if leak == false { crate::engine::BusEngine::close(&handle, "request was processed (by listener)"); } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/data.rs
wasmer-bus/lib/src/abi/data.rs
use super::BusError; #[repr(C)] #[derive(Debug)] #[must_use = "this `Data` may be an `Error` variant, which should be handled"] pub enum Data { Prepared(Vec<u8>), Error(BusError), }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/finish.rs
wasmer-bus/lib/src/abi/finish.rs
use derivative::*; use std::sync::Arc; use std::sync::Mutex; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use super::*; pub trait FinishOps where Self: Send + Sync, { fn process(&self, data: Vec<u8>, format: SerializationFormat) -> Result<Vec<u8>, BusError>; fn topic(&self) -> &str; } #[derive(Derivative, Clone)] #[derivative(Debug)] #[must_use = "you must 'wait' or 'await' to receive any calls from other modules"] pub struct Finish { pub(crate) topic: Cow<'static, str>, pub(crate) handle: CallHandle, #[derivative(Debug = "ignore")] pub(crate) callback: Arc<Mutex<Box<dyn FnMut(Vec<u8>, SerializationFormat) -> Result<Vec<u8>, BusError> + Send>>>, } impl FinishOps for Finish { fn process(&self, data: Vec<u8>, format: SerializationFormat) -> Result<Vec<u8>, BusError> { let mut callback = self.callback.lock().unwrap(); callback.as_mut()(data, format) } fn topic(&self) -> &str { self.topic.as_ref() } } impl Finish { pub fn id(&self) -> u64 { self.handle.id } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/syscall.rs
wasmer-bus/lib/src/abi/syscall.rs
use super::*; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; fn convert_format(a: wasi::BusDataFormat) -> SerializationFormat { use SerializationFormat::*; match a { wasi::BUS_DATA_FORMAT_BINCODE => Bincode, wasi::BUS_DATA_FORMAT_MESSAGE_PACK => MessagePack, wasi::BUS_DATA_FORMAT_JSON => Json, wasi::BUS_DATA_FORMAT_YAML => Yaml, wasi::BUS_DATA_FORMAT_XML => Xml, wasi::BUS_DATA_FORMAT_RAW | _ => Raw } } fn convert_format_back(a: SerializationFormat) -> wasi::BusDataFormat { use SerializationFormat::*; match a { Bincode => wasi::BUS_DATA_FORMAT_BINCODE, MessagePack => wasi::BUS_DATA_FORMAT_MESSAGE_PACK, Json => wasi::BUS_DATA_FORMAT_JSON, Yaml => wasi::BUS_DATA_FORMAT_YAML, Xml => wasi::BUS_DATA_FORMAT_XML, Raw => wasi::BUS_DATA_FORMAT_RAW } } fn convert_err(val: wasi::BusError) -> BusError { use BusError::*; match val { wasi::BUS_ERROR_SUCCESS => Success, wasi::BUS_ERROR_SERIALIZATION => SerializationFailed, wasi::BUS_ERROR_DESERIALIZATION => DeserializationFailed, wasi::BUS_ERROR_INVALID_WAPM => InvalidWapm, wasi::BUS_ERROR_FETCH_WAPM => FetchFailed, wasi::BUS_ERROR_COMPILE_ERROR => CompileError, wasi::BUS_ERROR_INVALID_ABI => IncorrectAbi, wasi::BUS_ERROR_ABORTED => Aborted, wasi::BUS_ERROR_INVALID_HANDLE => InvalidHandle, wasi::BUS_ERROR_INVALID_TOPIC => InvalidTopic, wasi::BUS_ERROR_MISSING_CALLBACK => MissingCallbacks, wasi::BUS_ERROR_UNSUPPORTED => Unsupported, wasi::BUS_ERROR_BAD_REQUEST => BadRequest, wasi::BUS_ERROR_ACCESS_DENIED => AccessDenied, wasi::BUS_ERROR_INTERNAL_FAILURE => InternalFailure, wasi::BUS_ERROR_MEMORY_ALLOCATION_FAILED => MemoryAllocationFailed, wasi::BUS_ERROR_BUS_INVOCATION_FAILED => BusInvocationFailed, wasi::BUS_ERROR_ALREADY_CONSUMED => AlreadyConsumed, wasi::BUS_ERROR_MEMORY_ACCESS_VIOLATION => MemoryAccessViolation, wasi::BUS_ERROR_UNKNOWN_ERROR | _ => Unknown, } } fn convert_err_back(val: BusError) -> wasi::BusError { use BusError::*; match val { Success => wasi::BUS_ERROR_SUCCESS, SerializationFailed => wasi::BUS_ERROR_SERIALIZATION, DeserializationFailed => wasi::BUS_ERROR_DESERIALIZATION, InvalidWapm => wasi::BUS_ERROR_INVALID_WAPM, FetchFailed => wasi::BUS_ERROR_FETCH_WAPM, CompileError => wasi::BUS_ERROR_COMPILE_ERROR, IncorrectAbi => wasi::BUS_ERROR_INVALID_ABI, Aborted => wasi::BUS_ERROR_ABORTED, InvalidHandle => wasi::BUS_ERROR_INVALID_HANDLE, InvalidTopic => wasi::BUS_ERROR_INVALID_TOPIC, MissingCallbacks => wasi::BUS_ERROR_MISSING_CALLBACK, Unsupported => wasi::BUS_ERROR_UNSUPPORTED, BadRequest => wasi::BUS_ERROR_BAD_REQUEST, AccessDenied => wasi::BUS_ERROR_ACCESS_DENIED, InternalFailure => wasi::BUS_ERROR_INTERNAL_FAILURE, MemoryAllocationFailed => wasi::BUS_ERROR_MEMORY_ALLOCATION_FAILED, BusInvocationFailed => wasi::BUS_ERROR_BUS_INVOCATION_FAILED, AlreadyConsumed => wasi::BUS_ERROR_ALREADY_CONSUMED, MemoryAccessViolation => wasi::BUS_ERROR_MEMORY_ACCESS_VIOLATION, Unknown => wasi::BUS_ERROR_UNKNOWN_ERROR } } fn convert_hash(hash: wasi::Hash) -> u128 { #[repr(C)] union HashUnion { h1: (u64, u64), h2: u128, } unsafe { let hash = HashUnion { h1: (hash.b0, hash.b1) }; hash.h2 } } fn convert_hash_back(hash: u128) -> wasi::Hash { #[repr(C)] union HashUnion { h1: (u64, u64), h2: u128, } unsafe { let hash = HashUnion { h2: hash }; wasi::Hash { b0: hash.h1.0, b1: hash.h1.1, } } } fn read_file_descriptor(fd: u32) -> Result<Vec<u8>, ()> { use std::os::wasi::io::FromRawFd; use std::io::Read; let fd = fd as std::os::wasi::io::RawFd; let mut file = unsafe { std::fs::File::from_raw_fd(fd) }; let mut req = Vec::new(); if let Err(err) = file.read_to_end(&mut req) { warn!("failed to read call request data - {}", err); return Err(()); } Ok(req) } pub fn bus_poll_once(timeout: std::time::Duration) -> usize { let timeout = timeout.as_nanos() as wasi::Timestamp; // Read all the events let mut events = [wasi::BusEvent { tag: wasi::BUS_EVENT_TYPE_NOOP.raw(), u: wasi::BusEventU { noop: 0 } }; MAX_BUS_POLL_EVENTS]; let events = unsafe { let events_len = events.len(); let events_ptr = events.as_mut_ptr(); match wasi::bus_poll(timeout, events_ptr, events_len) { Ok(nevents) => { // No more events to process if nevents <= 0 { return 0; } &events[..nevents] }, Err(err) => { debug!("failed to poll the bus for events - {}", err.message()); return 0; } } }; let nevents = events.len(); // Process the event for event in events { match event.tag.into() { wasi::BUS_EVENT_TYPE_NOOP => { } wasi::BUS_EVENT_TYPE_EXIT => { // The process these calls relate to has exited unsafe { let bid = event.u.exit.bid; let code = event.u.exit.rval; debug!("sub-process ({}) exited with code: {}", bid, code); } } wasi::BUS_EVENT_TYPE_CALL => { let handle: CallHandle = unsafe { event.u.call.cid.into() }; let topic_hash = unsafe { convert_hash(event.u.call.topic_hash) }; let request = unsafe { match read_file_descriptor(event.u.call.fd) { Ok(a) => a, Err(()) => { continue; } } }; let parent: Option<CallHandle> = unsafe { match event.u.call.parent.tag.into() { wasi::OPTION_SOME => Some(event.u.call.parent.u.some.into()), wasi::OPTION_NONE | _ => None, } }; let format = unsafe { convert_format(event.u.call.format) }; trace!( "wasmer_bus_start (parent={:?}, handle={}, request={} bytes)", parent, handle, request.len() ); if let Err(err) = crate::engine::BusEngine::start(topic_hash, parent, handle, request, format) { call_fault(handle.into(), err); } } wasi::BUS_EVENT_TYPE_RESULT => { let handle: CallHandle = unsafe { event.u.result.cid.into() }; let response = unsafe { match read_file_descriptor(event.u.result.fd) { Ok(a) => a, Err(()) => { continue; } } }; let format = unsafe { convert_format(event.u.result.format) }; crate::engine::BusEngine::result(handle, response, format); } wasi::BUS_EVENT_TYPE_FAULT => { let handle: CallHandle = unsafe { event.u.fault.cid.into() }; let error = unsafe { convert_err(event.u.fault.fault) }; crate::engine::BusEngine::error(handle, error); } wasi::BUS_EVENT_TYPE_CLOSE => { let handle: CallHandle = unsafe { event.u.close.cid.into() }; crate::engine::BusEngine::close(&handle, "os_notification"); } a => { debug!("unknown bus event type ({})", a.raw()); } } } // Returns the number of events that were processed nevents } pub fn bus_open_local( name: &str, resuse: bool, ) -> Result<BusHandle, BusError> { let reuse = if resuse { wasi::BOOL_TRUE } else { wasi::BOOL_FALSE }; let ret = unsafe { wasi::bus_open_local( name, reuse ) }; ret .map(|a| a.into()) .map_err(convert_err) } pub fn bus_open_remote( name: &str, resuse: bool, instance: &str, token: &str, ) -> Result<BusHandle, BusError> { let reuse = if resuse { wasi::BOOL_TRUE } else { wasi::BOOL_FALSE }; let ret = unsafe { wasi::bus_open_remote( name, reuse, instance, token ) }; ret .map(|a| a.into()) .map_err(convert_err) } pub fn bus_call( bid: BusHandle, topic_hash: u128, request: &[u8], format: SerializationFormat ) -> Result<CallHandle, BusError> { let bid: wasi::Bid = bid.into(); let format = convert_format_back(format); let topic_hash = convert_hash_back(topic_hash); let ret = unsafe { wasi::bus_call( bid, &topic_hash, format, request ) }; ret .map(|a| a.into()) .map_err(convert_err) } pub fn bus_subcall( parent: CallHandle, topic_hash: u128, request: &[u8], format: SerializationFormat ) -> Result<CallHandle, BusError> { let parent = parent.into(); let format = convert_format_back(format); let topic_hash = convert_hash_back(topic_hash); let ret = unsafe { wasi::bus_subcall( parent, &topic_hash, format, request ) }; ret .map(|a| a.into()) .map_err(convert_err) } pub fn call_close(handle: CallHandle) { unsafe { wasi::call_close(handle.into()); } } pub fn call_fault(handle: CallHandle, error: BusError) { unsafe { let error = convert_err_back(error); wasi::call_fault( handle.into(), error ); } } pub fn call_reply( handle: CallHandle, response: &[u8], format: SerializationFormat ) { let format = convert_format_back(format); unsafe { if let Err(err) = wasi::call_reply( handle.into(), format, response ) { debug!("call reply ({}) failed - {}", handle, err.message()) } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/abi/handle.rs
wasmer-bus/lib/src/abi/handle.rs
use serde::*; use std::fmt; #[repr(C)] #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct CallHandle { pub id: u64, } impl From<u64> for CallHandle { fn from(val: u64) -> CallHandle { CallHandle { id: val } } } impl Into<u64> for CallHandle { fn into(self) -> u64 { self.id } } impl fmt::Display for CallHandle { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "call_handle={}", self.id) } } #[repr(C)] #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct BusHandle { pub id: u32, } impl From<u32> for BusHandle { fn from(val: u32) -> BusHandle { BusHandle { id: val } } } impl Into<u32> for BusHandle { fn into(self) -> u32 { self.id } } impl fmt::Display for BusHandle { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "bus_handle={}", self.id) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/task/helper.rs
wasmer-bus/lib/src/task/helper.rs
use cooked_waker::ViaRawPointer; use cooked_waker::Wake; use cooked_waker::WakeRef; use cooked_waker::IntoWaker; use serde::*; use std::any::type_name; use std::future::Future; use std::pin::Pin; use std::task::Context; use std::task::Poll; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use tokio::sync::mpsc; use crate::abi::BusError; use crate::abi::CallHandle; use crate::abi::ListenAction; use crate::abi::ListenActionTyped; use crate::abi::RespondAction; use crate::abi::RespondActionTyped; use crate::abi::SerializationFormat; use crate::engine::BusEngine; pub fn block_on<F>(task: F) -> F::Output where F: Future, { let mut task = Box::pin(task); let waker = DummyWaker.into_waker(); let mut cx = Context::from_waker(&waker); loop { let pinned_task = Pin::new(&mut task); match pinned_task.poll(&mut cx) { Poll::Ready(ret) => { return ret; }, Poll::Pending => { #[cfg(not(feature = "rt"))] { std::thread::sleep(std::time::Duration::from_millis(5)); continue; } #[cfg(feature = "rt")] return tokio::task::block_in_place(move || { tokio::runtime::Handle::current().block_on(async move { task.await }) }); } } } } #[derive(Debug, Clone)] struct DummyWaker; impl WakeRef for DummyWaker { fn wake_by_ref(&self) { } } impl Wake for DummyWaker { fn wake(self) { } } unsafe impl ViaRawPointer for DummyWaker { type Target = (); fn into_raw(self) -> *mut () { std::mem::forget(self); std::ptr::null_mut() } unsafe fn from_raw(_ptr: *mut ()) -> Self { DummyWaker } } pub fn spawn<F>(task: F) where F: Future + Send + 'static, F::Output: Send + 'static, { let mut task = Box::pin(task); let waker = DummyWaker.into_waker(); let mut cx = Context::from_waker(&waker); let pinned_task = Pin::new(&mut task); if let Poll::Pending = pinned_task.poll(&mut cx) { tokio::task::spawn(task); } } pub fn send<T>(sender: &mpsc::Sender<T>, message: T) where T: Send + 'static { if let Err(mpsc::error::TrySendError::Full(message)) = sender.try_send(message) { let sender = sender.clone(); tokio::task::spawn(async move { let _ = sender.send(message).await; }); } } /// Initializes the reactors so that they may process call events and /// inbound invocations pub(crate) fn init_reactors() { BusEngine::init_reactors(); } struct NeverEnding { } impl Future for NeverEnding { type Output = (); fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> { Poll::Pending } } /// Starts a thread that will serve BUS requests pub async fn serve() { // Make sure the reactors are attached init_reactors(); // Now run at least one poll operation as requests may have come in // whlie the reactors were not attached crate::abi::syscall::bus_poll_once(std::time::Duration::from_millis(0)); // Enter the main processing loop // We just wait forever (which basically turns the current thread into // an async processing unit) let never_ending = NeverEnding {}; never_ending.await } pub fn listen<RES, REQ, F, Fut>(format: SerializationFormat, callback: F) where REQ: de::DeserializeOwned, RES: Serialize, F: Fn(CallHandle, REQ) -> Fut, F: Send + Sync + 'static, Fut: Future<Output = ListenActionTyped<RES>> + Send + 'static, { init_reactors(); let topic = type_name::<REQ>(); BusEngine::listen_internal( format, topic.to_string(), move |handle, req| { let req = match format.deserialize(req) { Ok(a) => a, Err(err) => { debug!("failed to deserialize the request object (type={}, format={}) - {}", type_name::<REQ>(), format, err); return Err(BusError::DeserializationFailed); } }; let res = callback(handle, req); Ok(async move { match res.await { ListenActionTyped::Response(res) => { let res = format.serialize(res) .map_err(|err| { debug!( "failed to serialize the response object (type={}, format={}) - {}", type_name::<RES>(), format, err ); BusError::SerializationFailed }); match res { Ok(res) => ListenAction::Response(res), Err(err) => ListenAction::Fault(err) } } ListenActionTyped::Fault(err) => { ListenAction::Fault(err) } ListenActionTyped::Detach => { ListenAction::Detach } } }) }, ); } pub fn respond_to<RES, REQ, F, Fut>( parent: CallHandle, format: SerializationFormat, callback: F, ) where REQ: de::DeserializeOwned, RES: Serialize, F: Fn(CallHandle, REQ) -> Fut, F: Send + Sync + 'static, Fut: Future<Output = RespondActionTyped<RES>> + Send + 'static, { let topic = type_name::<REQ>(); BusEngine::respond_to_internal( format, topic.to_string(), parent, move |handle, req| { let req = match format.deserialize(req) { Ok(a) => a, Err(err) => { debug!("failed to deserialize the request object (type={}, format={}) - {}", type_name::<REQ>(), format, err); return Err(BusError::DeserializationFailed); } }; let res = callback(handle, req); Ok(async move { match res.await { RespondActionTyped::Response(res) => { let res = format.serialize(res) .map_err(|err| { debug!( "failed to serialize the response object (type={}, format={}) - {}", type_name::<RES>(), format, err ); BusError::SerializationFailed }); match res { Ok(res) => RespondAction::Response(res), Err(err) => RespondAction::Fault(err) } }, RespondActionTyped::Fault(err) => RespondAction::Fault(err), RespondActionTyped::Detach => RespondAction::Detach } }) }, ); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/task/mod.rs
wasmer-bus/lib/src/task/mod.rs
mod helper; pub use helper::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/engine/engine.rs
wasmer-bus/lib/src/engine/engine.rs
#![allow(dead_code)] use once_cell::sync::Lazy; #[allow(unused_imports, dead_code)] use std::any::type_name; use std::borrow::Cow; use std::convert::TryInto; #[allow(unused_imports)] use std::future::Future; use std::sync::RwLock; use std::sync::RwLockReadGuard; use std::sync::RwLockWriteGuard; use std::sync::{Arc, MutexGuard}; use std::task::{Context, Waker}; use std::{collections::HashMap, collections::HashSet, sync::Mutex}; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use crate::abi::*; static GLOBAL_ENGINE: Lazy<BusEngine> = Lazy::new(|| BusEngine::default()); #[derive(Default)] pub struct BusEngineState { pub handles: HashSet<CallHandle>, pub calls: HashMap<CallHandle, Arc<dyn CallOps>>, pub children: HashMap<CallHandle, Vec<CallHandle>>, pub listening: HashMap<u128, ListenService>, pub respond_to: HashMap<u128, RespondToService>, pub initialized_reactors: bool, } #[derive(Default)] pub struct BusEngine { state: RwLock<BusEngineState>, wakers: Mutex<HashMap<CallHandle, Waker>>, } // Function that hashes the topic using SHA256 pub(crate) fn hash_topic(topic: &Cow<'static, str>) -> u128 { use sha2::{Sha256, Digest}; let mut hasher = Sha256::new(); hasher.update(&topic.bytes().collect::<Vec<_>>()); let hash: [u8; 16] = hasher.finalize()[..16].try_into().unwrap(); u128::from_le_bytes(hash) } impl BusEngine { pub(crate) fn read<'a>() -> RwLockReadGuard<'a, BusEngineState> { GLOBAL_ENGINE.state.read().unwrap() } pub(crate) fn write<'a>() -> RwLockWriteGuard<'a, BusEngineState> { GLOBAL_ENGINE.state.write().unwrap() } pub(crate) fn try_write<'a>() -> Option<RwLockWriteGuard<'a, BusEngineState>> { GLOBAL_ENGINE.state.try_write().ok() } fn wakers<'a>() -> MutexGuard<'a, HashMap<CallHandle, Waker>> { GLOBAL_ENGINE.wakers.lock().unwrap() } // If we don't have a runtime we can't start anything #[cfg(not(feature = "rt"))] pub fn start( _topic_hash: u128, _parent: Option<CallHandle>, _handle: CallHandle, _request: Vec<u8>, _format: SerializationFormat, ) -> Result<(), BusError> { Err(BusError::Unsupported) } // This function will block #[cfg(feature = "rt")] pub fn start( topic_hash: u128, parent: Option<CallHandle>, handle: CallHandle, request: Vec<u8>, format: SerializationFormat, ) -> Result<(), BusError> { let state = BusEngine::read(); if let Some(parent) = parent { if let Some(parent) = state.calls.get(&parent) { // If the callback is registered then process it and finish the call if parent.callback(topic_hash, request, format) != CallbackResult::InvalidTopic { // The topic exists at least - so lets close the handle syscall::call_close(handle); return Ok(()); } else { return Err(BusError::InvalidTopic); } } if let Some(respond_to) = state.respond_to.get(&topic_hash) { let respond_to = respond_to.clone(); drop(state); let mut state = BusEngine::write(); if state.handles.contains(&handle) == false { state.handles.insert(handle); drop(state); crate::task::spawn(async move { respond_to.process(parent, handle, request, format).await; }); return Ok(()); } else { return Err(BusError::InvalidHandle); } } else { return Err(BusError::InvalidHandle); } } else if let Some(listen) = state.listening.get(&topic_hash) { let listen = listen.clone(); drop(state); let mut state = BusEngine::write(); if state.handles.contains(&handle) == false { state.handles.insert(handle); drop(state); crate::task::spawn(async move { listen.process(handle, request, format).await; }); return Ok(()); } else { return Err(BusError::InvalidHandle); } } else { return Err(BusError::InvalidTopic); } } // This function will block pub fn finish_callback( topic_hash: u128, handle: CallHandle, response: Vec<u8>, format: SerializationFormat, ) { { let state = BusEngine::read(); if let Some(call) = state.calls.get(&handle) { let call = Arc::clone(call); drop(state); trace!( "wasmer_bus_callback (handle={}, response={} bytes)", handle.id, response.len() ); call.callback(topic_hash, response, format); } else { trace!( "wasmer_bus_callback (handle={}, response={} bytes, orphaned)", handle.id, response.len(), ); } }; let mut wakers = Self::wakers(); if let Some(waker) = wakers.remove(&handle) { drop(wakers); waker.wake(); } } // This function will block pub fn result( handle: CallHandle, response: Vec<u8>, format: SerializationFormat, ) { { let mut state = BusEngine::write(); if let Some(call) = state.calls.remove(&handle) { drop(state); trace!( "wasmer_bus_finish (handle={}, response={} bytes)", handle.id, response.len() ); call.data(response, format); } else { trace!( "wasmer_bus_finish (handle={}, response={} bytes, orphaned)", handle.id, response.len() ); } }; let mut wakers = Self::wakers(); if let Some(waker) = wakers.remove(&handle) { drop(wakers); waker.wake(); } } pub fn error(handle: CallHandle, err: BusError) { { let mut state = BusEngine::write(); if let Some(call) = state.calls.remove(&handle) { drop(state); trace!( "wasmer_bus_err (handle={}, error={})", handle.id, err, ); call.error(err); } else { trace!( "wasmer_bus_err (handle={}, error={}, orphaned)", handle.id, err ); } } { let mut wakers = Self::wakers(); if let Some(waker) = wakers.remove(&handle) { drop(wakers); waker.wake(); } } } pub fn subscribe(handle: &CallHandle, cx: &mut Context<'_>) { let waker = cx.waker().clone(); let mut wakers = Self::wakers(); wakers.insert(handle.clone(), waker); } pub fn add_callback(handle: CallHandle, child: CallHandle) { let mut state = BusEngine::write(); let children = state.children .entry(handle) .or_insert(Vec::new()); children.push(child); } pub fn close(handle: &CallHandle, reason: &'static str) { let mut children = Vec::new(); { let mut delayed_drop1 = Vec::new(); let mut delayed_drop2 = Vec::new(); { let mut state = BusEngine::write(); state.handles.remove(handle); if let Some(mut c) = state.children.remove(handle) { children.append(&mut c); } if let Some(drop_me) = state.calls.remove(handle) { trace!( "wasmer_bus_drop (handle={}, reason='{}')", handle.id, reason ); delayed_drop2.push(drop_me); } else { trace!( "wasmer_bus_drop (handle={}, reason='{}', orphaned)", handle.id, reason ); } for respond_to in state.respond_to.values_mut() { if let Some(drop_me) = respond_to.remove(handle) { delayed_drop1.push(drop_me); } } } } for child in children { Self::close(&child, reason); } let mut wakers = Self::wakers(); wakers.remove(handle); } pub(crate) fn listen_internal<F, Fut>( format: SerializationFormat, topic: String, callback: F, ) where F: Fn(CallHandle, Vec<u8>) -> Result<Fut, BusError>, F: Send + Sync + 'static, Fut: Future<Output = ListenAction>, Fut: Send + 'static, { let topic_hash = crate::engine::hash_topic(&topic.into()); { let mut state = BusEngine::write(); state.listening.insert( topic_hash, ListenService::new( format, Arc::new(move |handle, req| { let res = callback(handle, req); Box::pin(async move { match res { Ok(res) => res.await, Err(err) => ListenAction::Fault(err) } }) }), ), ); } } pub(crate) fn respond_to_internal<F, Fut>( format: SerializationFormat, topic: String, parent: CallHandle, callback: F, ) where F: Fn(CallHandle, Vec<u8>) -> Result<Fut, BusError>, F: Send + Sync + 'static, Fut: Future<Output = RespondAction>, Fut: Send + 'static, { let topic_hash = crate::engine::hash_topic(&topic.into()); { let mut state = BusEngine::write(); if state.respond_to.contains_key(&topic_hash) == false { state .respond_to .insert(topic_hash, RespondToService::new(format)); } let respond_to = state.respond_to.get_mut(&topic_hash).unwrap(); respond_to.add( parent, Arc::new(move |handle, req| { let res = callback(handle, req); Box::pin(async move { match res { Ok(res) => res.await, Err(err) => RespondAction::Fault(err) } }) }), ); } } /// Initializes the reactors so that the system may handle requests in the /// wasmer runtime #[cfg(all(target_os = "wasi", target_vendor = "wasmer"))] pub(crate) fn init_reactors() { // fast path { let engine = GLOBAL_ENGINE.state.read().unwrap(); if engine.initialized_reactors == true { return; } } // slow path let mut engine = GLOBAL_ENGINE.state.write().unwrap(); if engine.initialized_reactors == true { return; } engine.initialized_reactors = true; /* * Reactors are not yet working! * // Start a reactor std::thread::reactor(move || { loop { if crate::abi::syscall::bus_poll_once(std::time::Duration::from_millis(0)) <= 0 { break; } } }); */ // Start the thread std::thread::spawn(move || { loop { crate::abi::syscall::bus_poll_once(std::time::Duration::from_secs(60)); } }); } /// When not running the wasmer runtime there is no need for reactors as /// it can not receive any BUS events #[cfg(not(all(target_os = "wasi", target_vendor = "wasmer")))] pub(crate) fn init_reactors() { } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/lib/src/engine/mod.rs
wasmer-bus/lib/src/engine/mod.rs
mod engine; pub(crate) use engine::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/tty/src/prelude.rs
wasmer-bus/tty/src/prelude.rs
#[cfg(any(feature = "sys", target_family = "wasm"))] pub use crate::tty::Tty; #[cfg(target_family = "wasm")] pub use wasmer_bus; #[cfg(target_family = "wasm")] pub use wasmer_bus::abi::BusError; pub use async_trait::async_trait;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/tty/src/lib.rs
wasmer-bus/tty/src/lib.rs
pub mod api; pub mod prelude; pub mod tty;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/tty/src/api.rs
wasmer-bus/tty/src/api.rs
use serde::*; use std::sync::Arc; use wasmer_bus::macros::*; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TtyRect { pub cols: u32, pub rows: u32, } #[wasmer_bus(format = "bincode")] pub trait Tty { async fn stdin( &self, recv: impl Fn(Vec<u8>), flush: impl Fn(()), ) -> Arc<dyn Stdin>; async fn stdout( &self, ) -> Arc<dyn Stdout>; async fn stderr( &self, ) -> Arc<dyn Stderr>; async fn rect( &self, ) -> TtyRect; } #[wasmer_bus(format = "bincode")] pub trait Stdin { } #[wasmer_bus(format = "bincode")] pub trait Stdout { async fn write(&self, data: Vec<u8>) -> WriteResult; async fn flush(&self); } #[wasmer_bus(format = "bincode")] pub trait Stderr { async fn write(&self, data: Vec<u8>) -> WriteResult; async fn flush(&self); } #[allow(dead_code)] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum WriteResult { Success(usize), Failed(String), }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/tty/src/tty/mod.rs
wasmer-bus/tty/src/tty/mod.rs
#[cfg(feature = "sys")] #[cfg(not(target_family = "wasm"))] mod sys; #[cfg(target_family = "wasm")] mod wasm; #[cfg(feature = "sys")] #[cfg(not(target_family = "wasm"))] pub use sys::*; #[cfg(target_family = "wasm")] pub use wasm::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/tty/src/tty/wasm.rs
wasmer-bus/tty/src/tty/wasm.rs
#![allow(dead_code)] use crate::api; use std::io; use std::{result::Result, sync::Arc}; use tokio::sync::mpsc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; pub const WAPM_NAME: &'static str = "os"; const MAX_MPSC: usize = std::usize::MAX >> 3; pub struct Tty { client: api::TtyClient, } impl Tty { pub async fn stdin() -> Result<Stdin, std::io::Error> { let (tx_data, rx_data) = mpsc::channel(MAX_MPSC); let (tx_flush, rx_flush) = mpsc::channel(MAX_MPSC); let client = api::TtyClient::new(WAPM_NAME) .stdin( Box::new(move |data: Vec<u8>| { let _ = wasmer_bus::task::block_on( tx_data.send(data) ); }), Box::new(move |_| { let _ = wasmer_bus::task::block_on( tx_flush.send(()) ); }), ) .await .map_err(|err| err.into_io_error())?; Ok(Stdin { rx_data, rx_flush, client, }) } pub fn blocking_stdin() -> Result<BlockingStdin, std::io::Error> { let (tx_data, rx_data) = mpsc::channel(MAX_MPSC); let (tx_flush, rx_flush) = mpsc::channel(MAX_MPSC); let client = api::TtyClient::new(WAPM_NAME) .blocking_stdin( Box::new(move |data: Vec<u8>| { let _ = wasmer_bus::task::block_on( tx_data.send(data) ); }), Box::new(move |_| { let _ = wasmer_bus::task::block_on( tx_flush.send(()) ); }), ) .map_err(|err| err.into_io_error())?; Ok(BlockingStdin { rx_data, rx_flush, client, }) } pub async fn stdout() -> Result<Stdout, io::Error> { let client = api::TtyClient::new(WAPM_NAME) .stdout() .await .map_err(|err| err.into_io_error())?; Ok(Stdout { client }) } pub async fn stderr() -> Result<Stderr, io::Error> { let client = api::TtyClient::new(WAPM_NAME) .stderr() .await .map_err(|err| err.into_io_error())?; Ok(Stderr { client }) } pub async fn rect() -> Result<TtyRect, io::Error> { let rect = api::TtyClient::new(WAPM_NAME) .rect() .await .map_err(|err| err.into_io_error())?; Ok(TtyRect { rows: rect.rows, cols: rect.cols, }) } pub fn blocking_rect() -> Result<TtyRect, io::Error> { let rect = api::TtyClient::new(WAPM_NAME) .blocking_rect() .map_err(|err| err.into_io_error())?; Ok(TtyRect { rows: rect.rows, cols: rect.cols, }) } } pub struct TtyRect { pub cols: u32, pub rows: u32, } pub struct Stdin { rx_data: mpsc::Receiver<Vec<u8>>, rx_flush: mpsc::Receiver<()>, client: Arc<dyn api::Stdin>, } impl Stdin { pub async fn read(&mut self) -> Option<Vec<u8>> { if let Some(data) = self.rx_data.recv().await { if data.len() > 0 { return Some(data); } } None } pub async fn wait_for_flush(&mut self) -> Option<()> { self.rx_flush.recv().await } } pub struct BlockingStdin { rx_data: mpsc::Receiver<Vec<u8>>, rx_flush: mpsc::Receiver<()>, client: Arc<dyn api::Stdin>, } impl BlockingStdin { pub fn read(&mut self) -> Option<Vec<u8>> { if let Some(data) = wasmer_bus::task::block_on(self.rx_data.recv()) { if data.len() > 0 { return Some(data); } } None } pub fn wait_for_flush(&mut self) -> Option<()> { wasmer_bus::task::block_on(self.rx_flush.recv()) } } pub struct Stdout { client: Arc<dyn api::Stdout>, } impl Stdout { pub async fn write(&mut self, data: Vec<u8>) -> Result<usize, io::Error> { self.client .write(data) .await .map_err(|err| err.into_io_error()) .map(|ret| match ret { api::WriteResult::Success(a) => Ok(a), api::WriteResult::Failed(err) => Err(io::Error::new(io::ErrorKind::Other, err)), })? } pub async fn print(&mut self, text: String) -> Result<(), io::Error> { let data = text.as_bytes().to_vec(); self.write(data).await?; self.flush().await } pub async fn println(&mut self, text: String) -> Result<(), io::Error> { let data = [text.as_bytes(), "\r\n".as_bytes()].concat(); self.write(data).await?; self.flush().await } pub async fn flush(&mut self) -> Result<(), io::Error> { self.client .flush() .await .map_err(|err| err.into_io_error())?; Ok(()) } } pub struct Stderr { client: Arc<dyn api::Stderr>, } impl Stderr { pub async fn write(&mut self, data: Vec<u8>) -> Result<usize, io::Error> { self.client .write(data) .await .map_err(|err| err.into_io_error()) .map(|ret| match ret { api::WriteResult::Success(a) => Ok(a), api::WriteResult::Failed(err) => Err(io::Error::new(io::ErrorKind::Other, err)), })? } pub async fn flush(&mut self) -> Result<(), io::Error> { self.client .flush() .await .map_err(|err| err.into_io_error())?; Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/tty/src/tty/sys.rs
wasmer-bus/tty/src/tty/sys.rs
#![allow(dead_code)] use libc::{tcsetattr, termios, winsize, ECHO, ICANON, ICRNL, IEXTEN, ISIG, IXON, OPOST, TCSANOW, TIOCGWINSZ}; use std::os::unix::io::AsRawFd; use std::result::Result; use tokio::{io, io::AsyncReadExt, io::AsyncWriteExt}; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; const MAX_MPSC: usize = std::usize::MAX >> 3; pub struct Tty {} impl Tty { pub async fn stdin() -> Result<Stdin, std::io::Error> { let tty = tokio::fs::File::open("/dev/tty").await?; let fd = tty.as_raw_fd(); let termios = Self::termios(fd)?; Ok(Stdin { tty, tty_fd: fd, termios, }) } pub fn blocking_stdin() -> Result<BlockingStdin, std::io::Error> { let tty = std::fs::File::open("/dev/tty")?; let fd = tty.as_raw_fd(); let termios = Self::termios(fd)?; Ok(BlockingStdin { tty, tty_fd: fd, termios, }) } fn termios(fd: i32) -> Result<termios, std::io::Error> { let mut termios = std::mem::MaybeUninit::<termios>::uninit(); io_result(unsafe { ::libc::tcgetattr(fd, termios.as_mut_ptr()) })?; let termios = unsafe { termios.assume_init() }; let mut new_termios = termios.clone(); new_termios.c_lflag &= !ECHO; new_termios.c_lflag &= !ICANON; new_termios.c_lflag &= !ISIG; new_termios.c_lflag &= !IXON; new_termios.c_lflag &= !IEXTEN; new_termios.c_lflag &= !ICRNL; new_termios.c_lflag &= !OPOST; unsafe { tcsetattr(fd, TCSANOW, &new_termios) }; Ok(termios) } pub async fn stdout() -> Result<Stdout, io::Error> { let stdout = tokio::io::stdout(); Ok(Stdout { stdout }) } pub async fn stderr() -> Result<Stderr, io::Error> { let stderr = tokio::io::stdout(); Ok(Stderr { stderr }) } pub async fn rect() -> Result<TtyRect, io::Error> { let tty = tokio::fs::File::open("/dev/tty").await?; let fd = tty.as_raw_fd(); let mut winsize = std::mem::MaybeUninit::<winsize>::uninit(); io_result(unsafe { ::libc::ioctl(fd, TIOCGWINSZ, winsize.as_mut_ptr()) })?; let winsize = unsafe { winsize.assume_init() }; Ok( TtyRect { cols: winsize.ws_col as u32, rows: winsize.ws_row as u32, } ) } pub fn blocking_rect() -> Result<TtyRect, io::Error> { let tty = std::fs::File::open("/dev/tty")?; let fd = tty.as_raw_fd(); let mut winsize = std::mem::MaybeUninit::<winsize>::uninit(); io_result(unsafe { ::libc::ioctl(fd, TIOCGWINSZ, winsize.as_mut_ptr()) })?; let winsize = unsafe { winsize.assume_init() }; Ok( TtyRect { cols: winsize.ws_col as u32, rows: winsize.ws_row as u32, } ) } } pub struct TtyRect { pub cols: u32, pub rows: u32, } pub struct Stdin { tty: tokio::fs::File, tty_fd: i32, termios: termios, } pub struct BlockingStdin { tty: std::fs::File, tty_fd: i32, termios: termios, } impl Stdin { pub async fn read(&mut self) -> Option<Vec<u8>> { let mut buffer = [0; 1024]; if let Ok(read) = self.tty.read(&mut buffer[..]).await { if read == 0 { return None; } let ret = (&buffer[0..read]).to_vec(); Some(ret) } else { None } } pub async fn wait_for_flush(&mut self) -> Option<()> { None } } impl Drop for Stdin { fn drop(&mut self) { unsafe { tcsetattr(self.tty_fd, TCSANOW, &self.termios) }; } } pub struct Stdout { stdout: io::Stdout, } impl Stdout { pub async fn write(&mut self, data: Vec<u8>) -> Result<usize, io::Error> { self.stdout.write_all(&data[..]).await?; Ok(data.len()) } pub async fn print(&mut self, text: String) -> Result<(), io::Error> { let data = text.as_bytes().to_vec(); self.write(data).await?; self.flush().await } pub async fn println(&mut self, text: String) -> Result<(), io::Error> { let data = [text.as_bytes(), "\r\n".as_bytes()].concat(); self.write(data).await?; self.flush().await } pub async fn flush(&mut self) -> Result<(), io::Error> { self.stdout.flush().await?; Ok(()) } } pub struct Stderr { stderr: io::Stdout, } impl Stderr { pub async fn write(&mut self, data: Vec<u8>) -> Result<usize, io::Error> { self.stderr.write_all(&data[..]).await?; Ok(data.len()) } pub async fn flush(&mut self) -> Result<(), io::Error> { self.stderr.flush().await?; Ok(()) } } pub fn io_result(ret: libc::c_int) -> std::io::Result<()> { match ret { 0 => Ok(()), _ => Err(std::io::Error::last_os_error()), } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/tty/examples/passthru.rs
wasmer-bus/tty/examples/passthru.rs
use wasmer_bus_tty::prelude::*; #[cfg(target_family = "wasm")] fn main() -> Result<(), Box<dyn std::error::Error>> { wasmer_bus::task::block_on(main_async()) } #[cfg(not(target_family = "wasm"))] #[tokio::main(flavor = "multi_thread")] async fn main() -> Result<(), Box<dyn std::error::Error>> { main_async().await?; std::process::exit(0); } async fn main_async() -> Result<(), Box<dyn std::error::Error>> { let mut stdin = Tty::stdin().await?; let mut stdout = Tty::stdout().await?; loop { if let Some(data) = stdin.read().await { if data.len() == 1 && data[0] == 120u8 { break; } stdout.write(data).await?; stdout.flush().await?; } else { break; } } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/fuse/src/prelude.rs
wasmer-bus/fuse/src/prelude.rs
pub use crate::fuse::Dir; pub use crate::fuse::FileSystem; pub use crate::fuse::FsError; pub use crate::fuse::FsResult; pub use crate::fuse::Metadata; pub use crate::fuse::OpenOptions; pub use crate::fuse::OpenOptionsConfig; pub use crate::fuse::VirtualFile; pub use async_trait::async_trait; pub use wasmer_bus; pub use wasmer_bus::abi::BusError;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/fuse/src/lib.rs
wasmer-bus/fuse/src/lib.rs
pub mod api; pub mod fuse; pub mod prelude;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/fuse/src/api/mod.rs
wasmer-bus/fuse/src/api/mod.rs
use serde::*; use std::io; use std::sync::Arc; #[allow(unused_imports)] use wasmer_bus::macros::*; #[wasmer_bus(format = "json")] pub trait Fuse { async fn mount(&self, name: String) -> Arc<dyn FileSystem>; } #[wasmer_bus(format = "json")] pub trait FileSystem { async fn init(&self) -> FsResult<()>; async fn read_dir(&self, path: String) -> FsResult<Dir>; async fn create_dir(&self, path: String) -> FsResult<Metadata>; async fn remove_dir(&self, path: String) -> FsResult<()>; async fn rename(&self, from: String, to: String) -> FsResult<()>; async fn remove_file(&self, path: String) -> FsResult<()>; async fn read_metadata(&self, path: String) -> FsResult<Metadata>; async fn read_symlink_metadata(&self, path: String) -> FsResult<Metadata>; async fn open(&self, path: String, options: OpenOptions) -> Arc<dyn OpenedFile>; } #[wasmer_bus(format = "json")] pub trait OpenedFile { async fn meta(&self) -> FsResult<Metadata>; async fn unlink(&self) -> FsResult<()>; async fn set_len(&self, len: u64) -> FsResult<()>; async fn io(&self) -> Arc<dyn FileIO>; } #[wasmer_bus(format = "bincode")] pub trait FileIO { async fn seek(&self, from: SeekFrom) -> FsResult<u64>; async fn flush(&self) -> FsResult<()>; async fn write(&self, data: Vec<u8>) -> FsResult<u64>; async fn read(&self, len: u64) -> FsResult<Vec<u8>>; } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct OpenOptions { pub read: bool, pub write: bool, pub create_new: bool, pub create: bool, pub append: bool, pub truncate: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum SeekFrom { Start(u64), End(i64), Current(i64), } #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct FileType { pub dir: bool, pub file: bool, pub symlink: bool, pub char_device: bool, pub block_device: bool, pub socket: bool, pub fifo: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Metadata { pub ft: FileType, pub accessed: u64, pub created: u64, pub modified: u64, pub len: u64, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DirEntry { pub path: String, pub metadata: Option<Metadata>, } #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct Dir { pub data: Vec<DirEntry>, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] pub enum FsError { BaseNotDirectory, NotAFile, InvalidFd, AlreadyExists, Lock, IOError, AddressInUse, AddressNotAvailable, BrokenPipe, ConnectionAborted, ConnectionRefused, ConnectionReset, Interrupted, InvalidData, InvalidInput, NotConnected, EntityNotFound, NoDevice, PermissionDenied, TimedOut, UnexpectedEof, WouldBlock, WriteZero, DirectoryNotEmpty, UnknownError, } impl std::fmt::Display for FsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { FsError::BaseNotDirectory => write!(f, "base is not a directory"), FsError::NotAFile => write!(f, "not a file"), FsError::InvalidFd => write!(f, "invalid file descriptor"), FsError::AlreadyExists => write!(f, "alreadt existed"), FsError::Lock => write!(f, "lock failed"), FsError::IOError => write!(f, "fs io error"), FsError::AddressInUse => write!(f, "address in use"), FsError::AddressNotAvailable => write!(f, "address not available"), FsError::BrokenPipe => write!(f, "pipe is broken"), FsError::ConnectionAborted => write!(f, "connection aborted"), FsError::ConnectionRefused => write!(f, "connection refused"), FsError::ConnectionReset => write!(f, "connection reset"), FsError::Interrupted => write!(f, "interrupted"), FsError::InvalidData => write!(f, "invalid data"), FsError::InvalidInput => write!(f, "invalid input"), FsError::NotConnected => write!(f, "not connected"), FsError::EntityNotFound => write!(f, "entity not found"), FsError::NoDevice => write!(f, "no device"), FsError::PermissionDenied => write!(f, "permission denied"), FsError::TimedOut => write!(f, "timeout has elapsed"), FsError::UnexpectedEof => write!(f, "unexpected eof of file"), FsError::WouldBlock => write!(f, "call would block"), FsError::WriteZero => write!(f, "write zero"), FsError::DirectoryNotEmpty => write!(f, "directory is not empty"), FsError::UnknownError => write!(f, "unknown error"), } } } impl From<io::Error> for FsError { fn from(io_error: io::Error) -> Self { match io_error.kind() { io::ErrorKind::AddrInUse => FsError::AddressInUse, io::ErrorKind::AddrNotAvailable => FsError::AddressNotAvailable, io::ErrorKind::AlreadyExists => FsError::AlreadyExists, io::ErrorKind::BrokenPipe => FsError::BrokenPipe, io::ErrorKind::ConnectionAborted => FsError::ConnectionAborted, io::ErrorKind::ConnectionRefused => FsError::ConnectionRefused, io::ErrorKind::ConnectionReset => FsError::ConnectionReset, io::ErrorKind::Interrupted => FsError::Interrupted, io::ErrorKind::InvalidData => FsError::InvalidData, io::ErrorKind::InvalidInput => FsError::InvalidInput, io::ErrorKind::NotConnected => FsError::NotConnected, io::ErrorKind::NotFound => FsError::EntityNotFound, io::ErrorKind::PermissionDenied => FsError::PermissionDenied, io::ErrorKind::TimedOut => FsError::TimedOut, io::ErrorKind::UnexpectedEof => FsError::UnexpectedEof, io::ErrorKind::WouldBlock => FsError::WouldBlock, io::ErrorKind::WriteZero => FsError::WriteZero, io::ErrorKind::Other => FsError::IOError, _ => FsError::UnknownError, } } } impl Into<io::ErrorKind> for FsError { fn into(self) -> io::ErrorKind { match self { FsError::AddressInUse => io::ErrorKind::AddrInUse, FsError::AddressNotAvailable => io::ErrorKind::AddrNotAvailable, FsError::AlreadyExists => io::ErrorKind::AlreadyExists, FsError::BrokenPipe => io::ErrorKind::BrokenPipe, FsError::ConnectionAborted => io::ErrorKind::ConnectionAborted, FsError::ConnectionRefused => io::ErrorKind::ConnectionRefused, FsError::ConnectionReset => io::ErrorKind::ConnectionReset, FsError::Interrupted => io::ErrorKind::Interrupted, FsError::InvalidData => io::ErrorKind::InvalidData, FsError::InvalidInput => io::ErrorKind::InvalidInput, FsError::NotConnected => io::ErrorKind::NotConnected, FsError::EntityNotFound => io::ErrorKind::NotFound, FsError::PermissionDenied => io::ErrorKind::PermissionDenied, FsError::TimedOut => io::ErrorKind::TimedOut, FsError::UnexpectedEof => io::ErrorKind::UnexpectedEof, FsError::WouldBlock => io::ErrorKind::WouldBlock, FsError::WriteZero => io::ErrorKind::WriteZero, FsError::IOError => io::ErrorKind::Other, _ => io::ErrorKind::Other, } } } impl Into<io::Error> for FsError { fn into(self) -> io::Error { let kind: io::ErrorKind = self.into(); kind.into() } } impl Into<Box<dyn std::error::Error>> for FsError { fn into(self) -> Box<dyn std::error::Error> { let kind: io::ErrorKind = self.into(); let err: io::Error = kind.into(); Box::new(err) } } pub type FsResult<T> = Result<T, FsError>; /* #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FuseMountRequest { pub name: String, } #[wasmer_bus::async_trait] pub trait Fuse where Self: std::fmt::Debug + Send + Sync, { async fn mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError>; fn blocking_mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError>; fn as_client(&self) -> Option<FuseClient>; } #[wasmer_bus::async_trait] pub trait FuseSimplified where Self: std::fmt::Debug + Send + Sync, { async fn mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError>; } #[wasmer_bus::async_trait] impl<T> Fuse for T where T: FuseSimplified, { async fn mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError> { FuseSimplified::mount(self, name).await } fn blocking_mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError> { wasmer_bus::task::block_on(FuseSimplified::mount(self, name)) } fn as_client(&self) -> Option<FuseClient> { None } } #[derive(Debug, Clone)] pub struct FuseService {} impl FuseService { #[allow(dead_code)] pub(crate) fn attach( wasm_me: std::sync::Arc<dyn Fuse>, call_handle: wasmer_bus::abi::CallHandle, ) { { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FuseMountRequest| { let wasm_me = wasm_me.clone(); let name = wasm_req.name; async move { match wasm_me.mount(name).await { Ok(svc) => { FileSystemService::attach(svc, wasm_handle); wasmer_bus::abi::RespondActionTyped::<()>::Detach }, Err(err) => wasmer_bus::abi::RespondActionTyped::<()>::Fault(err) } } }, ); } } pub fn listen(wasm_me: std::sync::Arc<dyn Fuse>) { { let wasm_me = wasm_me.clone(); wasmer_bus::task::listen( wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FuseMountRequest| { let wasm_me = wasm_me.clone(); let name = wasm_req.name; async move { match wasm_me.mount(name).await { Ok(svc) => { FileSystemService::attach(svc, wasm_handle); wasmer_bus::abi::ListenActionTyped::<()>::Detach }, Err(err) => wasmer_bus::abi::ListenActionTyped::<()>::Fault(err) } } }, ); } } pub fn serve() { wasmer_bus::task::serve(); } } #[derive(Debug, Clone)] pub struct FuseClient { ctx: wasmer_bus::abi::CallContext, task: Option<wasmer_bus::abi::Call>, join: Option<wasmer_bus::abi::CallJoin<()>>, } impl FuseClient { pub fn new(wapm: &str) -> Self { Self { ctx: wasmer_bus::abi::CallContext::NewBusCall { wapm: wapm.to_string().into(), instance: None, }, task: None, join: None, } } pub fn new_with_instance(wapm: &str, instance: &str, access_token: &str) -> Self { Self { ctx: wasmer_bus::abi::CallContext::NewBusCall { wapm: wapm.to_string().into(), instance: Some(wasmer_bus::abi::CallInstance::new(instance, access_token)), }, task: None, join: None, } } pub fn attach(handle: wasmer_bus::abi::CallHandle) -> Self { let handle = wasmer_bus::abi::CallSmartHandle::new(handle); Self { ctx: wasmer_bus::abi::CallContext::OwnedSubCall { parent: handle }, task: None, join: None, } } pub fn wait(self) -> Result<(), wasmer_bus::abi::BusError> { if let Some(join) = self.join { join.wait()?; } if let Some(task) = self.task { task.join()?.wait()?; } Ok(()) } pub fn try_wait(&mut self) -> Result<Option<()>, wasmer_bus::abi::BusError> { if let Some(task) = self.task.take() { self.join.replace(task.join()?); } if let Some(join) = self.join.as_mut() { join.try_wait() } else { Ok(None) } } pub async fn mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError> { let request = FuseMountRequest { name }; let handle = wasmer_bus::abi::call( self.ctx.clone(), wasmer_bus::abi::SerializationFormat::Json, request, ) .detach()?; Ok(Arc::new(FileSystemClient::attach(handle))) } pub fn blocking_mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError> { wasmer_bus::task::block_on(self.mount(name)) } } impl std::future::Future for FuseClient { type Output = Result<(), wasmer_bus::abi::BusError>; fn poll( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { if let Some(task) = self.task.take() { self.join.replace(task.join()?); } if let Some(join) = self.join.as_mut() { let join = std::pin::Pin::new(join); return join.poll(cx); } else { std::task::Poll::Ready(Ok(())) } } } #[wasmer_bus::async_trait] impl Fuse for FuseClient { async fn mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError> { FuseClient::mount(self, name).await } fn blocking_mount( &self, name: String, ) -> std::result::Result<std::sync::Arc<dyn FileSystem>, wasmer_bus::abi::BusError> { FuseClient::blocking_mount(self, name) } fn as_client(&self) -> Option<FuseClient> { Some(self.clone()) } } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemInitRequest {} #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemReadDirRequest { pub path: String, } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemCreateDirRequest { pub path: String, } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemRemoveDirRequest { pub path: String, } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemRenameRequest { pub from: String, pub to: String, } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemRemoveFileRequest { pub path: String, } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemReadMetadataRequest { pub path: String, } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemReadSymlinkMetadataRequest { pub path: String, } #[derive(Debug, Clone, serde :: Serialize, serde :: Deserialize)] pub struct FileSystemOpenRequest { pub path: String, pub options: OpenOptions, } #[wasmer_bus::async_trait] pub trait FileSystem where Self: std::fmt::Debug + Send + Sync, { async fn init(&self) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError>; async fn read_dir( &self, path: String, ) -> std::result::Result<FsResult<Dir>, wasmer_bus::abi::BusError>; async fn create_dir( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError>; async fn remove_dir( &self, path: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError>; async fn rename( &self, from: String, to: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError>; async fn remove_file( &self, path: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError>; async fn read_metadata( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError>; async fn read_symlink_metadata( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError>; async fn open( &self, path: String, options: OpenOptions, ) -> std::result::Result<std::sync::Arc<dyn OpenedFile>, wasmer_bus::abi::BusError>; fn blocking_init(&self) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError>; fn blocking_read_dir( &self, path: String, ) -> std::result::Result<FsResult<Dir>, wasmer_bus::abi::BusError>; fn blocking_create_dir( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError>; fn blocking_remove_dir( &self, path: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError>; fn blocking_rename( &self, from: String, to: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError>; fn blocking_remove_file( &self, path: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError>; fn blocking_read_metadata( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError>; fn blocking_read_symlink_metadata( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError>; fn blocking_open( &self, path: String, options: OpenOptions, ) -> std::result::Result<std::sync::Arc<dyn OpenedFile>, wasmer_bus::abi::BusError>; fn as_client(&self) -> Option<FileSystemClient>; } #[wasmer_bus::async_trait] pub trait FileSystemSimplified where Self: std::fmt::Debug + Send + Sync, { async fn init(&self) -> FsResult<()>; async fn read_dir(&self, path: String) -> FsResult<Dir>; async fn create_dir(&self, path: String) -> FsResult<Metadata>; async fn remove_dir(&self, path: String) -> FsResult<()>; async fn rename(&self, from: String, to: String) -> FsResult<()>; async fn remove_file(&self, path: String) -> FsResult<()>; async fn read_metadata(&self, path: String) -> FsResult<Metadata>; async fn read_symlink_metadata(&self, path: String) -> FsResult<Metadata>; async fn open( &self, path: String, options: OpenOptions, ) -> std::result::Result<std::sync::Arc<dyn OpenedFile>, wasmer_bus::abi::BusError>; } #[wasmer_bus::async_trait] impl<T> FileSystem for T where T: FileSystemSimplified, { async fn init(&self) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError> { Ok(FileSystemSimplified::init(self).await) } fn blocking_init(&self) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on(FileSystemSimplified::init(self))) } async fn read_dir( &self, path: String, ) -> std::result::Result<FsResult<Dir>, wasmer_bus::abi::BusError> { Ok(FileSystemSimplified::read_dir(self, path).await) } fn blocking_read_dir( &self, path: String, ) -> std::result::Result<FsResult<Dir>, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on(FileSystemSimplified::read_dir( self, path, ))) } async fn create_dir( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError> { Ok(FileSystemSimplified::create_dir(self, path).await) } fn blocking_create_dir( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on(FileSystemSimplified::create_dir( self, path, ))) } async fn remove_dir( &self, path: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError> { Ok(FileSystemSimplified::remove_dir(self, path).await) } fn blocking_remove_dir( &self, path: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on(FileSystemSimplified::remove_dir( self, path, ))) } async fn rename( &self, from: String, to: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError> { Ok(FileSystemSimplified::rename(self, from, to).await) } fn blocking_rename( &self, from: String, to: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on(FileSystemSimplified::rename( self, from, to, ))) } async fn remove_file( &self, path: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError> { Ok(FileSystemSimplified::remove_file(self, path).await) } fn blocking_remove_file( &self, path: String, ) -> std::result::Result<FsResult<()>, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on(FileSystemSimplified::remove_file( self, path, ))) } async fn read_metadata( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError> { Ok(FileSystemSimplified::read_metadata(self, path).await) } fn blocking_read_metadata( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on( FileSystemSimplified::read_metadata(self, path), )) } async fn read_symlink_metadata( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError> { Ok(FileSystemSimplified::read_symlink_metadata(self, path).await) } fn blocking_read_symlink_metadata( &self, path: String, ) -> std::result::Result<FsResult<Metadata>, wasmer_bus::abi::BusError> { Ok(wasmer_bus::task::block_on( FileSystemSimplified::read_symlink_metadata(self, path), )) } async fn open( &self, path: String, options: OpenOptions, ) -> std::result::Result<std::sync::Arc<dyn OpenedFile>, wasmer_bus::abi::BusError> { FileSystemSimplified::open(self, path, options).await } fn blocking_open( &self, path: String, options: OpenOptions, ) -> std::result::Result<std::sync::Arc<dyn OpenedFile>, wasmer_bus::abi::BusError> { wasmer_bus::task::block_on(FileSystemSimplified::open(self, path, options)) } fn as_client(&self) -> Option<FileSystemClient> { None } } #[derive(Debug, Clone)] pub struct FileSystemService {} impl FileSystemService { #[allow(dead_code)] pub(crate) fn attach( wasm_me: std::sync::Arc<dyn FileSystem>, call_handle: wasmer_bus::abi::CallHandle, ) { { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemInitRequest| { let wasm_me = wasm_me.clone(); async move { match wasm_me.init().await { Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res), Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err) } } }, ); } { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemReadDirRequest| { let wasm_me = wasm_me.clone(); let path = wasm_req.path; async move { match wasm_me.read_dir(path).await { Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res), Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err) } } }, ); } { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemCreateDirRequest| { let wasm_me = wasm_me.clone(); let path = wasm_req.path; async move { match wasm_me.create_dir(path).await { Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res), Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err) } } }, ); } { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemRemoveDirRequest| { let wasm_me = wasm_me.clone(); let path = wasm_req.path; async move { match wasm_me.remove_dir(path).await { Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res), Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err) } } }, ); } { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemRenameRequest| { let wasm_me = wasm_me.clone(); let from = wasm_req.from; let to = wasm_req.to; async move { match wasm_me.rename(from, to).await { Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res), Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err) } } }, ); } { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemRemoveFileRequest| { let wasm_me = wasm_me.clone(); let path = wasm_req.path; async move { match wasm_me.remove_file(path).await { Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res), Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err) } } }, ); } { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemReadMetadataRequest| { let wasm_me = wasm_me.clone(); let path = wasm_req.path; async move { match wasm_me.read_metadata(path).await { Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res), Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err) } } }, ); } { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemReadSymlinkMetadataRequest| { let wasm_me = wasm_me.clone(); let path = wasm_req.path; async move { match wasm_me.read_symlink_metadata(path).await { Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res), Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err) } } }, ); } { let wasm_me = wasm_me.clone(); let call_handle = call_handle.clone(); wasmer_bus::task::respond_to( call_handle, wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemOpenRequest| { let wasm_me = wasm_me.clone(); let path = wasm_req.path; let options = wasm_req.options; async move { match wasm_me.open(path, options).await { Ok(svc) => { OpenedFileService::attach(svc, wasm_handle); wasmer_bus::abi::RespondActionTyped::<()>::Detach }, Err(err) => wasmer_bus::abi::RespondActionTyped::<()>::Fault(err) } } }, ); } } pub fn listen(wasm_me: std::sync::Arc<dyn FileSystem>) { { let wasm_me = wasm_me.clone(); wasmer_bus::task::listen( wasmer_bus::abi::SerializationFormat::Json, #[allow(unused_variables)] move |_wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: FileSystemInitRequest| { let wasm_me = wasm_me.clone(); async move { match wasm_me.init().await { Ok(res) => wasmer_bus::abi::ListenActionTyped::Response(res), Err(err) => wasmer_bus::abi::ListenActionTyped::Fault(err)
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
true
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/fuse/src/fuse/mod.rs
wasmer-bus/fuse/src/fuse/mod.rs
#![allow(dead_code)] use std::io; use std::path::Path; use std::sync::Arc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use crate::api; pub use crate::api::Dir; pub use crate::api::FsError; pub use crate::api::FsResult; pub use crate::api::Metadata; #[derive(Clone)] pub struct FileSystem { fs: Arc<dyn api::FileSystem>, } impl FileSystem { pub async fn mount(wapm: &str, name: &str) -> FsResult<FileSystem> { let fs = api::FuseClient::new(wapm) .mount(name.to_string()) .await .map_err(|err| { debug!("mount failed - {}", err); FsError::IOError })?; fs.init().await.map_err(|err| { debug!("mount init failed - {}", err); FsError::IOError })??; Ok(FileSystem { fs }) } pub async fn mount_instance( instance: &str, access_token: &str, wapm: &str, name: &str, ) -> FsResult<FileSystem> { let fs = api::FuseClient::new_with_instance(wapm, instance, access_token) .mount(name.to_string()) .await .map_err(|err| { debug!("mount_instance failed - {}", err); FsError::IOError })?; fs.init().await.map_err(|err| { debug!("mount init failed - {}", err); FsError::IOError })??; Ok(FileSystem { fs }) } pub async fn read_dir(&self, path: &Path) -> FsResult<Dir> { trace!("read_dir: path={}", path.display()); self.fs .read_dir(path.to_string_lossy().to_string()) .await .map_err(|err| { debug!("read_dir failed - {}", err); FsError::IOError })? } pub async fn create_dir(&self, path: &Path) -> FsResult<Metadata> { trace!("create_dir: path={}", path.display()); self.fs .create_dir(path.to_string_lossy().to_string()) .await .map_err(|err| { debug!("create_dir failed - {}", err); FsError::IOError })? } pub async fn remove_dir(&self, path: &Path) -> FsResult<()> { trace!("remove_dir: path={}", path.display()); self.fs .remove_dir(path.to_string_lossy().to_string()) .await .map_err(|err| { debug!("remove_dir failed - {}", err); FsError::IOError })? } pub async fn rename(&self, from: &Path, to: &Path) -> FsResult<()> { trace!("rename: from={}, to={}", from.display(), to.display()); self.fs .rename( from.to_string_lossy().to_string(), to.to_string_lossy().to_string(), ) .await .map_err(|err| { debug!("rename failed - {}", err); FsError::IOError })? } pub async fn metadata(&self, path: &Path) -> FsResult<Metadata> { trace!("metadata: path={}", path.display()); self.fs .read_metadata(path.to_string_lossy().to_string()) .await .map_err(|err| { debug!("metadata failed - {}", err); FsError::IOError })? } pub async fn symlink_metadata(&self, path: &Path) -> FsResult<Metadata> { trace!("symlink_metadata: path={}", path.display()); self.fs .read_symlink_metadata(path.to_string_lossy().to_string()) .await .map_err(|err| { debug!("symlink_metadata failed - {}", err); FsError::IOError })? } pub async fn remove_file(&self, path: &Path) -> FsResult<()> { trace!("remove_file: path={}", path.display()); self.fs .remove_file(path.to_string_lossy().to_string()) .await .map_err(|err| { debug!("remove_file failed - {}", err); FsError::IOError })? } pub fn new_open_options(&self) -> OpenOptions { OpenOptions::new(self.clone()) } } pub struct OpenOptionsConfig { read: bool, write: bool, create_new: bool, create: bool, append: bool, truncate: bool, } pub struct OpenOptions { fs: FileSystem, conf: OpenOptionsConfig, } impl OpenOptions { pub fn new(fs: FileSystem) -> Self { Self { fs, conf: OpenOptionsConfig { read: false, write: false, create_new: false, create: false, append: false, truncate: false, }, } } pub fn set_options(&mut self, options: OpenOptionsConfig) -> &mut Self { self.conf = options; self } pub fn read(&mut self, read: bool) -> &mut Self { self.conf.read = read; self } pub fn write(&mut self, write: bool) -> &mut Self { self.conf.write = write; self } pub fn append(&mut self, append: bool) -> &mut Self { self.conf.append = append; self } pub fn truncate(&mut self, truncate: bool) -> &mut Self { self.conf.truncate = truncate; self } pub fn create(&mut self, create: bool) -> &mut Self { self.conf.create = create; self } pub fn create_new(&mut self, create_new: bool) -> &mut Self { self.conf.create_new = create_new; self } pub async fn open(&mut self, path: &Path) -> FsResult<VirtualFile> { debug!("open: path={}", path.display()); let fd = self .fs .fs .open( path.to_string_lossy().to_string(), api::OpenOptions { read: self.conf.read, write: self.conf.write, create_new: self.conf.create_new, create: self.conf.create, append: self.conf.append, truncate: self.conf.truncate, }, ) .await .map_err(|err| { debug!("open failed - {}", err); FsError::IOError })?; let meta = fd.meta().await.map_err(|_| FsError::IOError)??; Ok(VirtualFile { io: fd.io().await.map_err(|_| FsError::IOError)?, fs: self.fs.clone(), fd, meta, }) } } pub struct VirtualFile { fs: FileSystem, fd: Arc<dyn api::OpenedFile>, io: Arc<dyn api::FileIO>, meta: Metadata, } impl io::Seek for VirtualFile { fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { let seek = match pos { io::SeekFrom::Current(a) => api::SeekFrom::Current(a), io::SeekFrom::End(a) => api::SeekFrom::End(a), io::SeekFrom::Start(a) => api::SeekFrom::Start(a), }; self.io .blocking_seek(seek) .map_err(|err| err.into_io_error())? .map_err(|err| err.into()) } } impl io::Write for VirtualFile { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.io .blocking_write(buf.to_vec()) .map_err(|err| err.into_io_error())? .map_err(|err| err.into()) .map(|a| a as usize) } fn flush(&mut self) -> io::Result<()> { self.io .blocking_flush() .map_err(|err| err.into_io_error())? .map_err(|err| err.into()) } } impl io::Read for VirtualFile { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let data: Result<_, io::Error> = self .io .blocking_read(buf.len() as u64) .map_err(|err| err.into_io_error())? .map_err(|err| err.into()); let data = data?; if data.len() <= 0 { return Ok(0usize); } let dst = &mut buf[..data.len()]; dst.copy_from_slice(&data[..]); Ok(data.len()) } } impl VirtualFile { pub fn last_accessed(&self) -> u64 { self.meta.accessed } pub fn last_modified(&self) -> u64 { self.meta.modified } pub fn created_time(&self) -> u64 { self.meta.created } pub fn size(&self) -> u64 { self.meta.len } pub async fn set_len(&mut self, new_size: u64) -> FsResult<()> { let result: FsResult<()> = self .fd .set_len(new_size) .await .map_err(|_| FsError::IOError)?; result?; self.meta.len = new_size; Ok(()) } pub async fn unlink(&mut self) -> FsResult<()> { self.fd.unlink().await.map_err(|_| FsError::IOError)? } pub async fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { let seek = match pos { io::SeekFrom::Current(a) => api::SeekFrom::Current(a), io::SeekFrom::End(a) => api::SeekFrom::End(a), io::SeekFrom::Start(a) => api::SeekFrom::Start(a), }; self.io .seek(seek) .await .map_err(|err| err.into_io_error())? .map_err(|err| err.into()) } pub async fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.io .write(buf.to_vec()) .await .map_err(|err| err.into_io_error())? .map_err(|err| err.into()) .map(|a| a as usize) } pub async fn flush(&mut self) -> io::Result<()> { self.io .flush() .await .map_err(|err| err.into_io_error())? .map_err(|err| err.into()) } pub async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let data: Result<_, io::Error> = self .io .read(buf.len() as u64) .await .map_err(|err| err.into_io_error())? .map_err(|err| err.into()); let data = data?; if data.len() <= 0 { return Ok(0usize); } let dst = &mut buf[..data.len()]; dst.copy_from_slice(&data[..]); Ok(data.len()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/fuse/examples/find.rs
wasmer-bus/fuse/examples/find.rs
use std::{collections::VecDeque, path::Path}; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use tracing_subscriber::fmt::SubscriberBuilder; use wasmer_bus_fuse::prelude::*; //use tracing_subscriber::EnvFilter; use tracing::metadata::LevelFilter; #[tokio::main(flavor = "multi_thread")] async fn main() -> Result<(), Box<dyn std::error::Error>> { SubscriberBuilder::default() .with_writer(std::io::stderr) .with_max_level(LevelFilter::DEBUG) //.with_env_filter(EnvFilter::from_default_env()) .init(); let args: Vec<String> = std::env::args().collect(); let program = args[0].clone(); if args.len() != 3 && args.len() != 5 { eprintln!( "usage: {} <db-name> <filename> [instance] [access-code]", program ); return Ok(()); } let name = args[1].clone(); let file = args[2].clone(); let fs = if args.len() == 5 { let instance = args[3].clone(); let access_code = args[4].clone(); FileSystem::mount_instance(instance.as_str(), access_code.as_str(), "tok", &name) .await .map_err(conv_err)? } else { FileSystem::mount("tok", &name).await.map_err(conv_err)? }; find(&fs, "/", &file).await.map_err(conv_err)?; Ok(()) } async fn find(fs: &FileSystem, path: &str, file: &str) -> FsResult<()> { let mut work = VecDeque::new(); work.push_back(path.to_string()); while let Some(path) = work.pop_front() { let dir = fs.read_dir(Path::new(path.as_str())).await?; for entry in dir.data { if let Some(meta) = entry.metadata { if meta.ft.file && entry.path == file { println!("{}{}", path, entry.path); } if meta.ft.dir { let sub = format!("{}{}/", path, entry.path); work.push_back(sub); } } } } Ok(()) } fn conv_err(err: FsError) -> Box<dyn std::error::Error> { error!("{}", err); let err: std::io::Error = err.into(); err.into() }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/prelude.rs
files/src/prelude.rs
pub use crate::error::FileSystemError; pub use crate::error::FileSystemErrorKind; pub use crate::api::FileApi; pub use crate::api::FileKind; pub use crate::api::FileSpec; pub use crate::attr::FileAttr; pub use crate::attr::SetAttr; pub use crate::accessor::FileAccessor; pub use crate::accessor::RequestContext; pub use crate::dir::Directory; pub use crate::file::FileState; pub use crate::file::RegularFile; pub use crate::fixed::FixedFile; pub use crate::handle::DirectoryEntry; pub use crate::handle::OpenHandle; pub use crate::model::*; pub use crate::symlink::SymLink;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/attr.rs
files/src/attr.rs
use super::prelude::*; #[derive(Debug, Clone)] pub struct FileAttr { pub ino: u64, pub size: u64, pub blksize: u32, pub accessed: u64, pub updated: u64, pub created: u64, pub kind: FileKind, pub mode: u32, pub uid: u32, pub gid: u32, } impl FileAttr { pub fn new(spec: &FileSpec, uid: u32, gid: u32) -> FileAttr { let size = spec.size(); let blksize = PAGE_SIZE as u64; FileAttr { ino: spec.ino(), size, accessed: spec.accessed(), updated: spec.updated(), created: spec.created(), kind: spec.kind(), mode: spec.mode(), uid, gid, blksize: blksize as u32, } } } impl FileAccessor { pub fn spec_as_attr_reverse(&self, spec: &FileSpec, req: &RequestContext) -> FileAttr { let uid = self.reverse_uid(spec.uid(), req); let gid = self.reverse_gid(spec.gid(), req); FileAttr::new(spec, uid, gid) } } #[derive(Debug, Clone, Default, Eq, PartialEq)] pub struct SetAttr { /// set file or directory mode. pub mode: Option<u32>, /// set file or directory uid. pub uid: Option<u32>, /// set file or directory gid. pub gid: Option<u32>, /// set file or directory size. pub size: Option<u64>, /// the lock_owner argument. pub lock_owner: Option<u64>, /// set file or directory atime. pub accessed: Option<u64>, /// set file or directory mtime. pub updated: Option<u64>, /// set file or directory ctime. pub created: Option<u64>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/lib.rs
files/src/lib.rs
pub mod accessor; pub mod api; pub mod attr; pub mod codes; pub mod dir; pub mod error; pub mod file; pub mod fixed; pub mod handle; pub mod model; pub mod prelude; pub mod symlink; pub mod repo;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/fixed.rs
files/src/fixed.rs
#![allow(unused_imports)] use super::api::FileKind; use super::model::*; use crate::api::FileApi; use async_trait::async_trait; use ate::prelude::PrimaryKey; use serde::*; #[derive(Debug, Clone)] pub struct FixedFile { ino: u64, #[allow(dead_code)] kind: FileKind, uid: u32, gid: u32, size: u64, mode: u32, name: String, created: u64, updated: u64, } impl FixedFile { pub fn new(ino: u64, name: String, kind: FileKind) -> FixedFile { FixedFile { ino, kind, uid: 0, gid: 0, size: 0, mode: 0, name: name, created: 0, updated: 0, } } pub fn uid(mut self, val: u32) -> FixedFile { self.uid = val; self } pub fn gid(mut self, val: u32) -> FixedFile { self.gid = val; self } #[allow(dead_code)] pub fn mode(mut self, val: u32) -> FixedFile { self.mode = val; self } #[allow(dead_code)] pub fn size(mut self, val: u64) -> FixedFile { self.size = val; self } #[allow(dead_code)] pub fn created(mut self, val: u64) -> FixedFile { self.created = val; self } #[allow(dead_code)] pub fn updated(mut self, val: u64) -> FixedFile { self.updated = val; self } } #[async_trait] impl FileApi for FixedFile { fn kind(&self) -> FileKind { FileKind::FixedFile } fn ino(&self) -> u64 { self.ino } fn uid(&self) -> u32 { self.uid } fn gid(&self) -> u32 { self.gid } fn size(&self) -> u64 { self.size } fn mode(&self) -> u32 { self.mode } fn name(&self) -> String { self.name.clone() } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/symlink.rs
files/src/symlink.rs
use super::api::FileKind; use super::model::*; use crate::api::FileApi; use async_trait::async_trait; use ate::prelude::*; #[derive(Debug)] pub struct SymLink { pub ino: u64, pub created: u64, pub updated: u64, pub uid: u32, pub gid: u32, pub mode: u32, pub name: String, pub link: Option<String>, } impl SymLink { pub fn new(inode: Dao<Inode>, created: u64, updated: u64) -> SymLink { SymLink { uid: inode.dentry.uid, gid: inode.dentry.gid, mode: inode.dentry.mode, name: inode.dentry.name.clone(), ino: inode.key().as_u64(), link: inode.link.clone(), created, updated, } } pub fn new_mut(inode: DaoMut<Inode>, created: u64, updated: u64) -> SymLink { SymLink { uid: inode.dentry.uid, gid: inode.dentry.gid, mode: inode.dentry.mode, name: inode.dentry.name.clone(), ino: inode.key().as_u64(), link: inode.link.clone(), created, updated, } } } #[async_trait] impl FileApi for SymLink { fn kind(&self) -> FileKind { FileKind::SymLink } fn ino(&self) -> u64 { self.ino } fn uid(&self) -> u32 { self.uid } fn gid(&self) -> u32 { self.gid } fn mode(&self) -> u32 { self.mode } fn name(&self) -> String { self.name.clone() } fn created(&self) -> u64 { self.created } fn updated(&self) -> u64 { self.updated } fn accessed(&self) -> u64 { self.updated } fn link(&self) -> Option<String> { self.link.clone() } fn size(&self) -> u64 { match &self.link { Some(a) => a.len() as u64, None => 0, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/repo.rs
files/src/repo.rs
use async_trait::async_trait; use ate::prelude::*; use wasmer_auth::error::GatherError; use bytes::Bytes; use derivative::*; use std::sync::Arc; use std::sync::RwLock; use std::time::Duration; use tokio::sync::Mutex; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use ttl_cache::TtlCache; use crate::prelude::*; #[derive(Derivative)] #[derivative(Debug)] pub struct Repository { pub registry: Arc<Registry>, pub db_url: url::Url, pub auth_url: url::Url, #[derivative(Debug = "ignore")] pub sessions: RwLock<TtlCache<String, AteSessionType>>, #[derivative(Debug = "ignore")] pub chains: Mutex<TtlCache<ChainKey, Arc<FileAccessor>>>, #[derivative(Debug = "ignore")] pub session_factory: Box<dyn RepositorySessionFactory + 'static>, pub ttl: Duration, } impl Repository { pub async fn new( registry: &Arc<Registry>, db_url: url::Url, auth_url: url::Url, session_factory: Box<dyn RepositorySessionFactory + 'static>, ttl: Duration, ) -> Result<Arc<Repository>, AteError> { let ret = Repository { registry: Arc::clone(registry), db_url, auth_url, session_factory, sessions: RwLock::new(TtlCache::new(usize::MAX)), chains: Mutex::new(TtlCache::new(usize::MAX)), ttl, }; let ret = Arc::new(ret); Ok(ret) } } impl Repository { pub async fn get_session(&self, sni: &String, key: ChainKey) -> Result<AteSessionType, GatherError> { // Check the cache let cache_key = format!("{}-{}", sni, key); { let guard = self.sessions.read().unwrap(); if let Some(ret) = guard.get(&cache_key) { return Ok(ret.clone()); } } // Create the session let session = self.session_factory.create(sni.clone(), key).await?; // Enter a write lock and check again let mut guard = self.sessions.write().unwrap(); if let Some(ret) = guard.get(&cache_key) { return Ok(ret.clone()); } // Cache and and return it guard.insert(cache_key.clone(), session.clone(), self.ttl); Ok(session) } pub async fn get_accessor(&self, key: &ChainKey, sni: &str) -> Result<Arc<FileAccessor>, GatherError> { // Get the session trace!("perf-checkpoint: get_session"); let sni = sni.to_string(); let session = self.get_session(&sni, key.clone()).await?; // Now get the chain for this host trace!("perf-checkpoint: open start (db_url={})", self.db_url); let chain = { let mut chains = self.chains.lock().await; if let Some(ret) = chains.remove(key) { trace!("perf-checkpoint: open cache_hit"); chains.insert(key.clone(), Arc::clone(&ret), self.ttl); ret } else { trace!("perf-checkpoint: open chain"); let chain = self.registry.open(&self.db_url, &key, false).await?; let accessor = Arc::new( FileAccessor::new( chain.as_arc(), Some(sni), session, TransactionScope::Local, TransactionScope::Local, false, false, ) .await, ); chains.insert(key.clone(), Arc::clone(&accessor), self.ttl); accessor } }; Ok(chain) } pub async fn get_file(&self, key: &ChainKey, sni: &str, path: &str) -> Result<Option<Bytes>, FileSystemError> { let path = path.to_string(); let context = RequestContext::default(); trace!("perf-checkpoint: get_accessor (key={}, sni={})", key, sni); let chain = self.get_accessor(key, sni).await?; trace!("perf-checkpoint: search (path={})", path); Ok(match chain.search(&context, path.as_str()).await { Ok(Some(a)) => { let flags = crate::codes::O_RDONLY as u32; trace!("perf-checkpoint: open (ino={}, flags={})", a.ino, flags); let oh = match chain.open(&context, a.ino, flags).await { Ok(a) => Some(a), Err(FileSystemError(FileSystemErrorKind::IsDirectory, _)) => None, Err(err) => { return Err(err.into()); } }; trace!("perf-checkpoint: read_from_handle"); match oh { Some(oh) => Some(chain.read(&context, a.ino, oh.fh, 0, u32::MAX).await?), None => None, } } Ok(None) => None, Err(FileSystemError(FileSystemErrorKind::IsDirectory, _)) | Err(FileSystemError(FileSystemErrorKind::DoesNotExist, _)) | Err(FileSystemError(FileSystemErrorKind::NoEntry, _)) => None, Err(err) => { return Err(err.into()); } }) } pub async fn set_file( &self, key: &ChainKey, sni: &str, path: &str, data: &[u8], ) -> Result<u64, FileSystemError> { let path = path.to_string(); let context = RequestContext::default(); let chain = self.get_accessor(key, sni).await?; let file = chain.touch(&context, path.as_str()).await?; let flags = (crate::codes::O_RDWR as u32) | (crate::codes::O_TRUNC as u32); let oh = chain.open(&context, file.ino, flags).await?; chain .fallocate(&context, file.ino, oh.fh, 0, 0, flags) .await?; let written = chain .write(&context, file.ino, oh.fh, 0, data, flags) .await?; chain.sync(&context, file.ino, oh.fh, 0).await?; Ok(written) } pub async fn house_keeping(&self) { let mut lock = self.chains.lock().await; lock.iter(); // this will run the remove_expired function } } #[async_trait] pub trait RepositorySessionFactory where Self: Send + Sync { async fn create(&self, sni: String, key: ChainKey) -> Result<AteSessionType, AteError>; }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/accessor.rs
files/src/accessor.rs
use error_chain::bail; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use bytes::Bytes; use std::sync::Arc; use std::sync::Mutex; use tokio::sync::Mutex as AsyncMutex; use crate::fixed::FixedFile; use ::ate::chain::*; use ::ate::crypto::*; use ::ate::dio::Dao; use ::ate::dio::DaoObj; use ::ate::dio::Dio; use ::ate::header::PrimaryKey; use ::ate::prelude::AteRolePurpose; use ::ate::prelude::ReadOption; use ::ate::prelude::*; use ::ate::{crypto::DerivedEncryptKey, prelude::TransactionScope}; use super::api::*; use super::codes::*; use super::error::*; use super::handle::*; use super::model::*; use super::prelude::*; use fxhash::FxHashMap; #[derive(Debug)] pub struct FileAccessor where Self: Send + Sync, { pub chain: Arc<Chain>, pub dio: Arc<Dio>, pub no_auth: bool, pub is_www: bool, pub scope_meta: TransactionScope, pub scope_io: TransactionScope, pub group: Option<String>, pub session: AteSessionType, pub open_handles: Mutex<FxHashMap<u64, Arc<OpenHandle>>>, pub elapsed: std::time::Instant, pub last_elapsed: seqlock::SeqLock<u64>, pub commit_lock: tokio::sync::Mutex<()>, pub impersonate_uid: bool, pub force_sudo: bool, pub init_flag: AsyncMutex<bool>, } #[derive(Debug, Clone, Copy)] pub struct RequestContext { pub uid: u32, pub gid: u32, } impl Default for RequestContext { fn default() -> RequestContext { RequestContext { uid: 0u32, gid: 0u32, } } } impl FileAccessor { pub async fn new( chain: Arc<Chain>, group: Option<String>, session: AteSessionType, scope_io: TransactionScope, scope_meta: TransactionScope, no_auth: bool, impersonate_uid: bool, ) -> FileAccessor { let is_www = chain.key().to_string().ends_with("/www"); let dio = chain.dio(&session).await; FileAccessor { chain, dio, no_auth, is_www, group, session, scope_meta, scope_io, open_handles: Mutex::new(FxHashMap::default()), elapsed: std::time::Instant::now(), last_elapsed: seqlock::SeqLock::new(0), commit_lock: tokio::sync::Mutex::new(()), impersonate_uid, force_sudo: false, init_flag: AsyncMutex::new(false), } } pub fn with_force_sudo(mut self, val: bool) -> Self { self.force_sudo = val; self } pub fn session_context(&self) -> RequestContext { RequestContext { uid: self.session.uid().unwrap_or_default(), gid: self.session.gid().unwrap_or_default(), } } pub async fn init(&self, req: &RequestContext) -> Result<DaoMut<Inode>> { let dio = self.dio_mut_meta().await; let root = match dio.load::<Inode>(&PrimaryKey::from(1)).await { Ok(a) => a, Err(LoadError(LoadErrorKind::NotFound(_), _)) => { info!("creating-root-node"); let mode = 0o770; let uid = self.translate_uid(req.uid, req); let gid = self.translate_gid(req.gid, req); let root = Inode::new("/".to_string(), mode, uid, gid, FileKind::Directory); match dio.store_with_key(root, PrimaryKey::from(1)) { Ok(mut root) => { self.updwasmer_auth(mode, uid, gid, root.auth_mut())?; root } Err(err) => { error!("{}", err); bail!(FileSystemErrorKind::InvalidArguments); } } } Err(err) => { bail!(err); } }; debug!("init"); // All good self.tick().await?; self.commit().await?; dio.commit().await?; // Disable any more root nodes from being created (only the single root node is allowed) self.chain.single().await.disable_new_roots(); Ok(root) } pub fn get_group_read_key<'a>(&'a self, gid: u32) -> Option<&'a EncryptKey> { let purpose = if self.is_www { AteRolePurpose::WebServer } else { AteRolePurpose::Observer }; self.session .role(&purpose) .iter() .filter(|g| g.gid() == Some(gid)) .flat_map(|r| r.read_keys()) .next() } pub fn get_group_write_key<'a>(&'a self, gid: u32) -> Option<&'a PrivateSignKey> { let purpose = if self.is_www { AteRolePurpose::WebServer } else { AteRolePurpose::Contributor }; self.session .role(&purpose) .iter() .filter(|g| g.gid() == Some(gid)) .flat_map(|r| r.write_keys()) .next() } pub fn get_user_read_key<'a>(&'a self, uid: u32) -> Option<&'a EncryptKey> { if self.session.uid() == Some(uid) { if self.force_sudo { self.session.read_keys(AteSessionKeyCategory::SudoKeys).next() } else { match &self.session { AteSessionType::User(a) => a.user.read_keys().next(), AteSessionType::Sudo(a) => a.inner.user.read_keys().next(), AteSessionType::Group(a) => match &a.inner { AteSessionInner::User(a) => a.user.read_keys().next(), AteSessionInner::Sudo(a) => a.inner.user.read_keys().next(), AteSessionInner::Nothing => None, }, AteSessionType::Nothing => None, } } } else { None } } pub fn get_user_write_key<'a>(&'a self, uid: u32) -> Option<&'a PrivateSignKey> { if self.session.uid() == Some(uid) { if self.force_sudo { self.session.write_keys(AteSessionKeyCategory::SudoKeys).next() } else { match &self.session { AteSessionType::User(a) => a.user.write_keys().next(), AteSessionType::Sudo(a) => a.inner.user.write_keys().next(), AteSessionType::Group(a) => match &a.inner { AteSessionInner::User(a) => a.user.write_keys().next(), AteSessionInner::Sudo(a) => a.inner.user.write_keys().next(), AteSessionInner::Nothing => None, }, AteSessionType::Nothing => None, } } } else { None } } pub async fn load(&self, inode: u64) -> Result<Dao<Inode>> { let dao = self.dio.load::<Inode>(&PrimaryKey::from(inode)).await?; Ok(dao) } pub async fn load_mut(&self, inode: u64) -> Result<DaoMut<Inode>> { let dio = self.dio.trans(self.scope_meta).await; let dao = dio.load::<Inode>(&PrimaryKey::from(inode)).await?; Ok(dao) } pub async fn load_mut_io(&self, inode: u64) -> Result<DaoMut<Inode>> { let dio = self.dio.trans(self.scope_io).await; let dao = dio.load::<Inode>(&PrimaryKey::from(inode)).await?; Ok(dao) } pub async fn create_open_handle( &self, inode: u64, req: &RequestContext, flags: i32, ) -> Result<OpenHandle> { let mut writable = false; if flags & O_TRUNC != 0 || flags & O_RDWR != 0 || flags & O_WRONLY != 0 { self.access_internal(&req, inode, 0o2).await?; writable = true; } if flags & O_RDWR != 0 || flags & O_RDONLY != 0 { self.access_internal(&req, inode, 0o4).await?; } let data = self.load(inode).await?; let created = data.when_created(); let updated = data.when_updated(); let read_only = flags & O_RDONLY != 0; let uid = data.dentry.uid; let gid = data.dentry.gid; let mut dirty = false; let mut children = Vec::new(); if data.kind == FileKind::Directory { let fixed = FixedFile::new(data.key().as_u64(), ".".to_string(), FileKind::Directory) .uid(uid) .gid(gid) .created(created) .updated(updated); children.push(FileSpec::FixedFile(fixed)); let fixed = FixedFile::new(data.key().as_u64(), "..".to_string(), FileKind::Directory) .uid(uid) .gid(gid) .created(created) .updated(updated); children.push(FileSpec::FixedFile(fixed)); match writable { true => { let mut data = self.load_mut_io(inode).await?; let mut data = data.as_mut(); for child in data.children.iter_mut_ext(true, true).await? { let child_spec = Inode::as_file_spec_mut( child.key().as_u64(), child.when_created(), child.when_updated(), child, ) .await; children.push(child_spec); } } false => { for child in data.children.iter_ext(true, true).await? { let child_spec = Inode::as_file_spec( child.key().as_u64(), child.when_created(), child.when_updated(), child, ) .await; children.push(child_spec); } } } } let spec = match writable { true => { let data = self.load_mut_io(inode).await?; Inode::as_file_spec_mut(data.key().as_u64(), created, updated, data).await } false => Inode::as_file_spec(data.key().as_u64(), created, updated, data).await, }; if flags & O_TRUNC != 0 { spec.fallocate(0).await?; dirty = true; } let mut open = OpenHandle { inode, read_only, fh: fastrand::u64(..), attr: FileAttr::new(&spec, uid, gid), kind: spec.kind(), spec: spec, children: Vec::new(), dirty: seqlock::SeqLock::new(dirty), }; for child in children.into_iter() { let (uid, gid) = match self.impersonate_uid { true => { let uid = self.reverse_uid(child.uid(), req); let gid = self.reverse_gid(child.gid(), req); (uid, gid) } false => (child.uid(), child.gid()), }; open.add_child(&child, uid, gid); } Ok(open) } } impl FileAccessor { pub async fn dio_mut_io(&self) -> Arc<DioMut> { let ret = self.dio.trans(self.scope_io).await; ret.auto_cancel(); ret } pub async fn dio_mut_meta(&self) -> Arc<DioMut> { let ret = self.dio.trans(self.scope_meta).await; ret.auto_cancel(); ret } pub async fn mknod_internal( &self, req: &RequestContext, parent: u64, name: &str, mode: u32, ) -> Result<DaoMut<Inode>> { let key = PrimaryKey::from(parent); let dio = self.dio_mut_meta().await; let mut data = dio.load::<Inode>(&key).await?; if data.kind != FileKind::Directory { trace!("create parent={} not-a-directory", parent); bail!(FileSystemErrorKind::NotDirectory); } if let Some(_) = data .children .iter() .await? .filter(|c| *c.dentry.name == *name) .next() { trace!("create parent={} name={}: already-exists", parent, name); bail!(FileSystemErrorKind::DoesNotExist); } let uid = self.translate_uid(req.uid, req); let gid = self.translate_gid(req.gid, req); let child = Inode::new(name.to_string(), mode, uid, gid, FileKind::RegularFile); let mut child = data.as_mut().children.push(child)?; self.updwasmer_auth(mode, uid, gid, child.auth_mut())?; return Ok(child); } pub async fn tick(&self) -> Result<()> { let secs = self.elapsed.elapsed().as_secs(); if secs > self.last_elapsed.read() { let _ = self.commit_lock.lock().await; if secs > self.last_elapsed.read() { *self.last_elapsed.lock_write() = secs; self.commit_internal().await?; } } Ok(()) } pub async fn commit(&self) -> Result<()> { let _ = self.commit_lock.lock().await; self.commit_internal().await?; Ok(()) } pub async fn sync_all(&self) -> Result<()> { self.tick().await?; self.commit().await?; self.chain.sync().await?; Ok(()) } pub async fn commit_internal(&self) -> Result<()> { trace!("commit"); let open_handles = { let lock = self.open_handles.lock().unwrap(); lock.values() .filter(|a| a.dirty.read()) .map(|v| { *v.dirty.lock_write() = false; Arc::clone(v) }) .collect::<Vec<_>>() }; for open in open_handles { open.spec.commit().await?; } Ok(()) } pub fn updwasmer_auth( &self, mode: u32, uid: u32, gid: u32, mut auth: DaoAuthGuard<'_>, ) -> Result<()> { let inner_key = { match &auth.read { ReadOption::Inherit => None, ReadOption::Everyone(old) => match old.clone() { Some(a) => Some(a), None => { let keysize = match self.get_group_read_key(gid) { Some(a) => a.size(), None => match self.get_user_read_key(uid) { Some(a) => a.size(), None => KeySize::Bit192, }, }; Some(EncryptKey::generate(keysize)) } }, ReadOption::Specific(hash, derived) => { let key = match self .session .read_keys(AteSessionKeyCategory::AllKeys) .filter(|k| k.hash() == *hash) .next() { Some(a) => a.clone(), None => { bail!(FileSystemErrorKind::NoAccess); } }; Some(derived.transmute(&key)?) } } }; if mode & 0o004 != 0 { auth.read = ReadOption::Everyone(inner_key); } else { let new_key = { if mode & 0o040 != 0 { self.get_group_read_key(gid) .or_else(|| self.get_user_read_key(uid)) } else { self.get_user_read_key(uid) } }; if let Some(new_key) = new_key { let inner_key = match inner_key { Some(a) => a.clone(), None => EncryptKey::generate(new_key.size()), }; auth.read = ReadOption::Specific( new_key.hash(), DerivedEncryptKey::reverse(&new_key, &inner_key), ); } else if self.no_auth == false { if mode & 0o040 != 0 { error!( "Session does not have the required group or user ({}) read key embedded within it", gid ); } else { error!( "Session does not have the required user ({}) read key embedded within it", uid ); } debug!("...we have...{}", self.session); bail!(FileSystemErrorKind::NoAccess); } else { auth.read = ReadOption::Inherit; } } if mode & 0o002 != 0 { auth.write = WriteOption::Everyone; } else { let new_key = { if mode & 0o020 != 0 { self.get_group_write_key(gid) .or_else(|| self.get_user_write_key(uid)) } else { self.get_user_write_key(uid) } }; if let Some(key) = new_key { auth.write = WriteOption::Specific(key.hash()); } else if self.no_auth == false { if mode & 0o020 != 0 { error!("Session does not have the required group or user ({}) write key embedded within it", gid); } else { error!( "Session does not have the required user ({}) write key embedded within it", uid ); } debug!("...we have...{}", self.session); bail!(FileSystemErrorKind::NoAccess); } else { auth.write = WriteOption::Inherit; } } Ok(()) } pub fn translate_uid(&self, uid: u32, req: &RequestContext) -> u32 { if uid == 0 || uid == req.uid { return self.session.uid().unwrap_or_else(|| uid); } uid } pub fn translate_gid(&self, gid: u32, req: &RequestContext) -> u32 { if gid == 0 || gid == req.gid { return self.session.gid().unwrap_or_else(|| gid); } gid } pub fn reverse_uid(&self, uid: u32, req: &RequestContext) -> u32 { if self.session.uid() == Some(uid) { return req.uid; } uid } pub fn reverse_gid(&self, gid: u32, req: &RequestContext) -> u32 { if self.session.gid() == Some(gid) { return req.gid; } gid } pub async fn access_internal(&self, req: &RequestContext, inode: u64, mask: u32) -> Result<()> { self.tick().await?; trace!("access inode={} mask={:#02x}", inode, mask); let dao = self.load(inode).await?; if (dao.dentry.mode & mask) != 0 { trace!("access mode={:#02x} - ok", dao.dentry.mode); return Ok(()); } let uid = self.translate_uid(req.uid, &req); if uid == dao.dentry.uid { trace!("access has_user"); let mask_shift = mask << 6; if (dao.dentry.mode & mask_shift) != 0 { trace!("access mode={:#02x} - ok", dao.dentry.mode); return Ok(()); } } let gid = self.translate_gid(req.gid, &req); if gid == dao.dentry.gid && self.session.gid() == Some(gid) { trace!("access has_group"); let mask_shift = mask << 3; if (dao.dentry.mode & mask_shift) != 0 { trace!("access mode={:#02x} - ok", dao.dentry.mode); return Ok(()); } } if dao.dentry.uid == 0 { trace!("access mode={:#02x} - ok", dao.dentry.mode); return Ok(()); } if req.uid == 0 { trace!("access mode={:#02x} - ok", dao.dentry.mode); return Ok(()); } trace!("access mode={:#02x} - EACCES", dao.dentry.mode); bail!(FileSystemErrorKind::NoAccess); } pub async fn getattr( &self, req: &RequestContext, inode: u64, fh: Option<u64>, _flags: u32, ) -> Result<FileAttr> { self.tick().await?; trace!("getattr inode={}", inode); if let Some(fh) = fh { let lock = self.open_handles.lock().unwrap(); if let Some(open) = lock.get(&fh) { return Ok(open.attr.clone()); } } let dao = self.load(inode).await?; let spec = Inode::as_file_spec(inode, dao.when_created(), dao.when_updated(), dao).await; Ok(match self.impersonate_uid { true => self.spec_as_attr_reverse(&spec, &req), false => FileAttr::new(&spec, spec.uid(), spec.gid()), }) } pub async fn setattr( &self, req: &RequestContext, inode: u64, _fh: Option<u64>, set_attr: SetAttr, ) -> Result<FileAttr> { self.tick().await?; trace!("setattr inode={}", inode); let key = PrimaryKey::from(inode); let dio = self.dio_mut_meta().await; let mut dao = dio.load::<Inode>(&key).await?; let mut changed = false; if let Some(uid) = set_attr.uid { let new_uid = self.translate_uid(uid, req); if dao.dentry.uid != new_uid { let mut dao = dao.as_mut(); dao.dentry.uid = new_uid; changed = true; } } if let Some(gid) = set_attr.gid { let new_gid = self.translate_gid(gid, req); if dao.dentry.gid != new_gid { let mut dao = dao.as_mut(); dao.dentry.gid = new_gid; changed = true; } } if let Some(mode) = set_attr.mode { if dao.dentry.mode != mode { let mut dao = dao.as_mut(); dao.dentry.mode = mode; dao.dentry.uid = self.translate_uid(req.uid, req); changed = true; } } if changed == true { self.updwasmer_auth( dao.dentry.mode, dao.dentry.uid, dao.dentry.gid, dao.auth_mut(), )?; dio.commit().await?; } let spec = Inode::as_file_spec(inode, dao.when_created(), dao.when_updated(), dao.into()).await; Ok(self.spec_as_attr_reverse(&spec, req)) } pub async fn opendir( &self, req: &RequestContext, inode: u64, flags: u32, ) -> Result<Arc<OpenHandle>> { self.tick().await?; debug!("wasmer-dfs::opendir inode={}", inode); let open = self.create_open_handle(inode, req, flags as i32).await?; if open.attr.kind != FileKind::Directory { debug!("wasmer-dfs::opendir not-a-directory"); bail!(FileSystemErrorKind::NotDirectory); } let fh = open.fh; let handle = Arc::new(open); self.open_handles .lock() .unwrap() .insert(fh, Arc::clone(&handle)); Ok(handle) } pub async fn releasedir( &self, _req: &RequestContext, inode: u64, fh: u64, _flags: u32, ) -> Result<()> { self.tick().await?; debug!("wasmer-dfs::releasedir inode={}", inode); let open = self.open_handles.lock().unwrap().remove(&fh); if let Some(open) = open { open.spec.commit().await? } Ok(()) } pub async fn lookup( &self, req: &RequestContext, parent: u64, name: &str, ) -> Result<Option<FileAttr>> { self.tick().await?; let open = self.create_open_handle(parent, req, O_RDONLY).await?; if open.attr.kind != FileKind::Directory { debug!("wasmer-dfs::lookup parent={} not-a-directory", parent); bail!(FileSystemErrorKind::NotDirectory); } if let Some(entry) = open .children .iter() .filter(|c| c.name.as_str() == name) .next() { debug!("wasmer-dfs::lookup parent={} name={}: found", parent, name); return Ok(Some(entry.attr.clone())); } debug!("wasmer-dfs::lookup parent={} name={}: not found", parent, name); Ok(None) } pub async fn root(&self, req: &RequestContext) -> Result<Option<FileAttr>> { match self.getattr(req, 1u64, None, 0u32).await { Ok(a) => Ok(Some(a)), Err(FileSystemError(FileSystemErrorKind::DoesNotExist, _)) | Err(FileSystemError(FileSystemErrorKind::NoAccess, _)) | Err(FileSystemError(FileSystemErrorKind::NoEntry, _)) => Ok(None), Err(err) => Err(err), } } pub async fn search(&self, req: &RequestContext, path: &str) -> Result<Option<FileAttr>> { let mut ret = match self.root(req).await? { Some(a) => a, None => { return Ok(None); } }; if path == "/" { return Ok(Some(ret)); } for comp in path.split("/") { if comp.len() <= 0 { continue; } ret = match self.lookup(req, ret.ino, comp).await? { Some(a) => a, None => { return Ok(None); } } } Ok(Some(ret)) } pub async fn touch(&self, req: &RequestContext, path: &str) -> Result<FileAttr> { let mut ret = self.getattr(req, 1u64, None, 0u32).await?; let comps = path .split("/") .map(|a| a.to_string()) .filter(|a| a.len() > 0) .collect::<Vec<_>>(); let comps_len = comps.len(); let mut n = 0usize; for comp in comps { n += 1usize; let parent = ret.ino; ret = match self.lookup(req, parent, comp.as_str()).await? { Some(a) => a, None if n < comps_len => self.mkdir(req, parent, comp.as_str(), 0o770).await?, None => self.mknod(req, parent, comp.as_str(), 0o660).await?, }; } trace!("touching {}", path); Ok(ret) } pub async fn forget(&self, _req: &RequestContext, _inode: u64, _nlookup: u64) { let _ = self.tick().await; } pub async fn fsync( &self, _req: &RequestContext, inode: u64, _fh: u64, _datasync: bool, ) -> Result<()> { self.tick().await?; debug!("wasmer-dfs::fsync inode={}", inode); Ok(()) } pub async fn flush( &self, _req: &RequestContext, inode: u64, fh: u64, _lock_owner: u64, ) -> Result<()> { self.tick().await?; self.commit().await?; debug!("wasmer-dfs::flush inode={}", inode); let open = { let lock = self.open_handles.lock().unwrap(); match lock.get(&fh) { Some(open) => Some(Arc::clone(&open)), _ => None, } }; if let Some(open) = open { open.spec.commit().await? } self.chain.flush().await?; Ok(()) } pub async fn sync( &self, req: &RequestContext, inode: u64, fh: u64, lock_owner: u64, ) -> Result<()> { self.flush(req, inode, fh, lock_owner).await?; self.chain.sync().await?; Ok(()) } pub async fn access(&self, req: &RequestContext, inode: u64, mask: u32) -> Result<()> { self.access_internal(req, inode, mask).await } pub async fn mkdir( &self, req: &RequestContext, parent: u64, name: &str, mode: u32, ) -> Result<FileAttr> { self.tick().await?; debug!("wasmer-dfs::mkdir parent={}", parent); let dio = self.dio.trans(self.scope_meta).await; let mut data = dio.load::<Inode>(&PrimaryKey::from(parent)).await?; if data.kind != FileKind::Directory { bail!(FileSystemErrorKind::NotDirectory); } let uid = self.translate_uid(req.uid, req); let gid = self.translate_gid(req.gid, req); let child = Inode::new(name.to_string(), mode, uid, gid, FileKind::Directory); let mut child = data.as_mut().children.push(child)?; self.updwasmer_auth(mode, uid, gid, child.auth_mut())?; dio.commit().await?; let child_spec = Inode::as_file_spec( child.key().as_u64(), child.when_created(), child.when_updated(), child.into(), ) .await; Ok(self.spec_as_attr_reverse(&child_spec, req)) } pub async fn rmdir(&self, req: &RequestContext, parent: u64, name: &str) -> Result<()> { self.tick().await?; debug!("wasmer-dfs::rmdir parent={}", parent); let open = self.create_open_handle(parent, req, O_RDONLY).await?; if open.attr.kind != FileKind::Directory { debug!("wasmer-dfs::rmdir parent={} not-a-directory", parent); bail!(FileSystemErrorKind::NotDirectory); } if let Some(entry) = open .children .iter() .filter(|c| c.name.as_str() == name) .next() { debug!("wasmer-dfs::rmdir parent={} name={}: found", parent, name); let dio = self.dio.trans(self.scope_meta).await; dio.delete(&PrimaryKey::from(entry.inode)).await?; dio.commit().await?; return Ok(()); } debug!("wasmer-dfs::rmdir parent={} name={}: not found", parent, name); bail!(FileSystemErrorKind::NoEntry); } pub async fn interrupt(&self, _req: &RequestContext, unique: u64) -> Result<()> { self.tick().await?; debug!("wasmer-dfs::interrupt unique={}", unique); Ok(()) } pub async fn mknod( &self, req: &RequestContext, parent: u64, name: &str, mode: u32, ) -> Result<FileAttr> { self.tick().await?; debug!("wasmer-dfs::mknod parent={} name={}", parent, name); let dao = self.mknod_internal(&req, parent, name, mode).await?; dao.trans().commit().await?; let spec = Inode::as_file_spec( dao.key().as_u64(), dao.when_created(), dao.when_updated(), dao.into(), ) .await; Ok(self.spec_as_attr_reverse(&spec, &req)) } pub async fn create( &self, req: &RequestContext, parent: u64, name: &str, mode: u32, ) -> Result<Arc<OpenHandle>> { self.tick().await?; debug!("wasmer-dfs::create parent={} name={}", parent, name); let data = self.mknod_internal(req, parent, name, mode).await?; data.trans().commit().await?; let spec = Inode::as_file_spec_mut( data.key().as_u64(), data.when_created(), data.when_updated(), data.into(), ) .await; let attr = self.spec_as_attr_reverse(&spec, req); let open = OpenHandle { inode: spec.ino(), read_only: false, fh: fastrand::u64(..), kind: spec.kind(), spec: spec, attr: attr.clone(), children: Vec::new(), dirty: seqlock::SeqLock::new(false), }; let fh = open.fh; let handle = Arc::new(open); self.open_handles .lock() .unwrap() .insert(fh, Arc::clone(&handle)); Ok(handle) } pub async fn unlink(&self, _req: &RequestContext, parent: u64, name: &str) -> Result<()> { self.tick().await?; debug!("wasmer-dfs::unlink parent={} name={}", parent, name); let parent_key = PrimaryKey::from(parent); let data_parent = self.dio.load::<Inode>(&parent_key).await?; if data_parent.kind != FileKind::Directory { debug!("wasmer-dfs::unlink parent={} not-a-directory", parent); bail!(FileSystemErrorKind::NotDirectory); } if let Some(data) = data_parent .children .iter() .await?
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
true
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/codes.rs
files/src/codes.rs
pub const EXIT_FAILURE: i32 = 1; pub const EXIT_SUCCESS: i32 = 0; pub const RAND_MAX: i32 = 2147483647; pub const EOF: i32 = -1; pub const SEEK_SET: i32 = 0; pub const SEEK_CUR: i32 = 1; pub const SEEK_END: i32 = 2; pub const EDEADLK: i32 = 35; pub const ENAMETOOLONG: i32 = 36; pub const ENOLCK: i32 = 37; pub const ENOSYS: i32 = 38; pub const ENOTEMPTY: i32 = 39; pub const ELOOP: i32 = 40; pub const ENOMSG: i32 = 42; pub const EIDRM: i32 = 43; pub const ECHRNG: i32 = 44; pub const EL2NSYNC: i32 = 45; pub const EL3HLT: i32 = 46; pub const EL3RST: i32 = 47; pub const ELNRNG: i32 = 48; pub const EUNATCH: i32 = 49; pub const ENOCSI: i32 = 50; pub const EL2HLT: i32 = 51; pub const EBADE: i32 = 52; pub const EBADR: i32 = 53; pub const EXFULL: i32 = 54; pub const ENOANO: i32 = 55; pub const EBADRQC: i32 = 56; pub const EBADSLT: i32 = 57; pub const EMULTIHOP: i32 = 72; pub const EOVERFLOW: i32 = 75; pub const ENOTUNIQ: i32 = 76; pub const EBADFD: i32 = 77; pub const EBADMSG: i32 = 74; pub const EREMCHG: i32 = 78; pub const ELIBACC: i32 = 79; pub const ELIBBAD: i32 = 80; pub const ELIBSCN: i32 = 81; pub const ELIBMAX: i32 = 82; pub const ELIBEXEC: i32 = 83; pub const EILSEQ: i32 = 84; pub const ERESTART: i32 = 85; pub const ESTRPIPE: i32 = 86; pub const EUSERS: i32 = 87; pub const ENOTSOCK: i32 = 88; pub const EDESTADDRREQ: i32 = 89; pub const EMSGSIZE: i32 = 90; pub const EPROTOTYPE: i32 = 91; pub const ENOPROTOOPT: i32 = 92; pub const EPROTONOSUPPORT: i32 = 93; pub const ESOCKTNOSUPPORT: i32 = 94; pub const EOPNOTSUPP: i32 = 95; pub const EPFNOSUPPORT: i32 = 96; pub const EAFNOSUPPORT: i32 = 97; pub const EADDRINUSE: i32 = 98; pub const EADDRNOTAVAIL: i32 = 99; pub const ENETDOWN: i32 = 100; pub const ENETUNREACH: i32 = 101; pub const ENETRESET: i32 = 102; pub const ECONNABORTED: i32 = 103; pub const ECONNRESET: i32 = 104; pub const ENOBUFS: i32 = 105; pub const EISCONN: i32 = 106; pub const ENOTCONN: i32 = 107; pub const ESHUTDOWN: i32 = 108; pub const ETOOMANYREFS: i32 = 109; pub const ETIMEDOUT: i32 = 110; pub const ECONNREFUSED: i32 = 111; pub const EHOSTDOWN: i32 = 112; pub const EHOSTUNREACH: i32 = 113; pub const EALREADY: i32 = 114; pub const EINPROGRESS: i32 = 115; pub const ESTALE: i32 = 116; pub const EDQUOT: i32 = 122; pub const ENOMEDIUM: i32 = 123; pub const EMEDIUMTYPE: i32 = 124; pub const ECANCELED: i32 = 125; pub const ENOKEY: i32 = 126; pub const EKEYEXPIRED: i32 = 127; pub const EKEYREVOKED: i32 = 128; pub const EKEYREJECTED: i32 = 129; pub const EOWNERDEAD: i32 = 130; pub const ENOTRECOVERABLE: i32 = 131; pub const EHWPOISON: i32 = 133; pub const ERFKILL: i32 = 132; pub const O_APPEND: i32 = 1024; pub const O_CREAT: i32 = 64; pub const O_EXCL: i32 = 128; pub const O_NOCTTY: i32 = 256; pub const O_NONBLOCK: i32 = 2048; pub const O_SYNC: i32 = 1052672; pub const O_RSYNC: i32 = 1052672; pub const O_DSYNC: i32 = 4096; pub const O_FSYNC: i32 = 0x101000; pub const O_NOATIME: i32 = 0o1000000; pub const O_PATH: i32 = 0o10000000; pub const O_TMPFILE: i32 = 0o20000000 | O_DIRECTORY; pub const O_ASYNC: i32 = 0x2000; pub const O_NDELAY: i32 = 0x800; pub const O_TRUNC: i32 = 512; pub const O_CLOEXEC: i32 = 0x80000; pub const EBFONT: i32 = 59; pub const ENOSTR: i32 = 60; pub const ENODATA: i32 = 61; pub const ETIME: i32 = 62; pub const ENOSR: i32 = 63; pub const ENONET: i32 = 64; pub const ENOPKG: i32 = 65; pub const EREMOTE: i32 = 66; pub const ENOLINK: i32 = 67; pub const EADV: i32 = 68; pub const ESRMNT: i32 = 69; pub const ECOMM: i32 = 70; pub const EPROTO: i32 = 71; pub const EDOTDOT: i32 = 73; pub const O_DIRECT: i32 = 0x4000; pub const O_DIRECTORY: i32 = 0x10000; pub const O_NOFOLLOW: i32 = 0x20000; pub const O_RDONLY: i32 = 0; pub const O_WRONLY: i32 = 1; pub const O_RDWR: i32 = 2;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/error.rs
files/src/error.rs
use ate::error::*; use error_chain::error_chain; error_chain! { types { FileSystemError, FileSystemErrorKind, ResultExt, Result; } links { AteError(::ate::error::AteError, ::ate::error::AteErrorKind); LoginError(::wasmer_auth::error::LoginError, ::wasmer_auth::error::LoginErrorKind); CreateError(::wasmer_auth::error::CreateError, ::wasmer_auth::error::CreateErrorKind); GatherError(::wasmer_auth::error::GatherError, ::wasmer_auth::error::GatherErrorKind); } foreign_links { IO(tokio::io::Error); } errors { NotDirectory { description("the entry is not a directory") display("the entry is not a directory") } IsDirectory { description("the entry is a directory") display("the entry is a directory") } DoesNotExist { description("the entry does not exist") display("the entry does not exist") } NoAccess { description("no access allowed to this entry"), display("no access allowed to this entry") } PermissionDenied { description("missing permissions for this operation"), display("missing permissions for this operation") } ReadOnly { description("read only"), display("read only") } InvalidArguments { description("invalid arguments were supplied"), display("invalid arguments were supplied") } NoEntry { description("the entry does not exist"), display("the entry does not exist"), } AlreadyExists { description("an entry with this name already exists") display("an entry with this name already exists") } NotImplemented { description("the function is not implemented"), display("the function is not implemented") } } } impl From<LoadError> for FileSystemError { fn from(err: LoadError) -> FileSystemError { FileSystemError::from_kind(err.0.into()) } } impl From<LoadErrorKind> for FileSystemErrorKind { fn from(err: LoadErrorKind) -> FileSystemErrorKind { match err { LoadErrorKind::NotFound(_) => FileSystemErrorKind::NoEntry, LoadErrorKind::SerializationError(err) => err.into(), LoadErrorKind::TransformationError(err) => err.into(), err => FileSystemErrorKind::AteError(AteErrorKind::LoadError(err)), } } } impl From<TransformError> for FileSystemError { fn from(err: TransformError) -> FileSystemError { FileSystemError::from_kind(err.0.into()) } } impl From<TransformErrorKind> for FileSystemErrorKind { fn from(err: TransformErrorKind) -> FileSystemErrorKind { match err { TransformErrorKind::MissingReadKey(_) => FileSystemErrorKind::NoAccess, err => FileSystemErrorKind::AteError(AteErrorKind::TransformError(err)), } } } impl From<SerializationError> for FileSystemError { fn from(err: SerializationError) -> FileSystemError { FileSystemError::from_kind(err.0.into()) } } impl From<SerializationErrorKind> for FileSystemErrorKind { fn from(err: SerializationErrorKind) -> FileSystemErrorKind { match err { err => FileSystemErrorKind::AteError(AteErrorKind::SerializationError(err)), } } } impl From<CommitError> for FileSystemError { fn from(err: CommitError) -> FileSystemError { FileSystemError::from_kind(err.0.into()) } } impl From<CommitErrorKind> for FileSystemErrorKind { fn from(err: CommitErrorKind) -> FileSystemErrorKind { match err { CommitErrorKind::CommsError(CommsErrorKind::ReadOnly) => FileSystemErrorKind::NoAccess, CommitErrorKind::ReadOnly => FileSystemErrorKind::NoAccess, CommitErrorKind::SerializationError(err) => err.into(), CommitErrorKind::TransformError(err) => err.into(), err => FileSystemErrorKind::AteError(AteErrorKind::CommitError(err)), } } } impl From<FileSystemError> for AteError { fn from(err: FileSystemError) -> AteError { AteErrorKind::ServiceError(err.to_string()).into() } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/file.rs
files/src/file.rs
#![allow(dead_code)] use super::api::FileKind; use super::model::*; use crate::api::FileApi; use async_trait::async_trait; use ate::prelude::*; use bytes::Bytes; use error_chain::bail; use fxhash::FxHashMap; use seqlock::SeqLock; use std::io::Cursor; use std::ops::Deref; use tokio::sync::Mutex; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use crate::error::*; const CACHED_BUNDLES: usize = 10; // Number of cached bundles per open file const CACHED_PAGES: usize = 80; // Number of cached pages per open file const ZERO_PAGE: [u8; super::model::PAGE_SIZE] = [0 as u8; super::model::PAGE_SIZE]; // Page full of zeros pub struct RegularFile { pub ino: u64, pub created: u64, pub updated: u64, pub uid: u32, pub gid: u32, pub mode: u32, pub name: String, pub size: SeqLock<u64>, pub state: Mutex<FileState>, } impl RegularFile { pub async fn new(inode: Dao<Inode>, created: u64, updated: u64) -> RegularFile { RegularFile { uid: inode.dentry.uid, gid: inode.dentry.gid, mode: inode.dentry.mode, name: inode.dentry.name.clone(), ino: inode.key().as_u64(), size: SeqLock::new(inode.size), created, updated, state: Mutex::new(FileState::Immutable { inode, bundles: Box::new(array_init::array_init(|_| None)), pages: Box::new(array_init::array_init(|_| None)), }), } } pub async fn new_mut(inode: DaoMut<Inode>, created: u64, updated: u64) -> RegularFile { RegularFile { uid: inode.dentry.uid, gid: inode.dentry.gid, mode: inode.dentry.mode, name: inode.dentry.name.clone(), ino: inode.key().as_u64(), size: SeqLock::new(inode.size), created, updated, state: Mutex::new(FileState::Mutable { inode, dirty: false, bundles: Box::new(array_init::array_init(|_| None)), pages: Box::new(array_init::array_init(|_| None)), }), } } } pub enum FileState { Immutable { inode: Dao<Inode>, bundles: Box<[Option<Dao<PageBundle>>; CACHED_BUNDLES]>, pages: Box<[Option<Dao<Page>>; CACHED_PAGES]>, }, Mutable { dirty: bool, inode: DaoMut<Inode>, bundles: Box<[Option<DaoMut<PageBundle>>; CACHED_BUNDLES]>, pages: Box<[Option<DaoMutGuardOwned<Page>>; CACHED_PAGES]>, }, } impl FileState { fn __inode(&self) -> &Inode { match self { FileState::Immutable { inode, bundles: _, pages: _, } => inode.deref(), FileState::Mutable { dirty: _, inode, bundles: _, pages: _, } => inode.deref(), } } pub fn get_size(&self) -> Result<u64> { Ok(self.__inode().size) } pub fn set_size(&mut self, val: u64) -> Result<()> { let (dirty, inode, _, _) = match self { FileState::Mutable { dirty, inode, bundles, pages, } => (dirty, inode, bundles, pages), FileState::Immutable { inode: _, bundles: _, pages: _, } => { bail!(FileSystemErrorKind::NoAccess); } }; inode.as_mut().size = val; *dirty = true; Ok(()) } pub async fn read_page( &mut self, mut offset: u64, mut size: u64, ret: &mut Cursor<&mut Vec<u8>>, ) -> Result<()> { // Compute the strides let stride_page = super::model::PAGE_SIZE as u64; let stride_bundle = super::model::PAGES_PER_BUNDLE as u64 * stride_page; // First we index into the right bundle let index = offset / stride_bundle; if index >= self.__inode().bundles.len() as u64 { FileState::write_zeros(ret, size).await?; return Ok(()); } let bundle = self.__inode().bundles[index as usize]; offset = offset - (index * stride_bundle); // If its a hole then just write zeros let bundle = match bundle { Some(a) => a, None => { FileState::write_zeros(ret, size).await?; return Ok(()); } }; // There is code for read-only inodes ... and code for writable inodes match self { FileState::Mutable { dirty: _, inode, bundles, pages, } => { // Use the cache-line to load the bundle let dio = inode.trans(); let cache_index = bundle.as_u64() as usize % CACHED_BUNDLES; let cache_line = &mut bundles[cache_index]; let bundle = match cache_line { Some(b) if *b.key() == bundle => { // Cache-hit b } _ => { // Cache-miss - load the bundle into the cacheline and return its pages let dao = dio.load::<PageBundle>(&bundle).await?; cache_line.replace(dao); cache_line.as_mut().unwrap() } }; // Next we index into the right page let index = offset / stride_page; if index >= bundle.pages.len() as u64 { FileState::write_zeros(ret, size).await?; return Ok(()); } let page = bundle.pages[index as usize]; offset = offset - (index * stride_page); // If its a hole then just write zeros let page = match page { Some(a) => a, None => { FileState::write_zeros(ret, size).await?; return Ok(()); } }; // Use the cache-line to load the page let cache_index = page.as_u64() as usize % CACHED_PAGES; let cache_line = &mut pages[cache_index]; let page = match cache_line { Some(b) if *b.key() == page => { // Cache-hit b } _ => { // Cache-miss - load the bundle into the cacheline and return its pages let dao = dio.load::<Page>(&page).await?; cache_line.replace(dao.as_mut_owned()); cache_line.as_mut().unwrap() } }; // Read the bytes from the page let buf = &page.buf; let sub_next = size.min(buf.len() as u64 - offset); if sub_next > 0 { let mut reader = Cursor::new(&buf[offset as usize..(offset + sub_next) as usize]); tokio::io::copy(&mut reader, ret).await?; size = size - sub_next; } } FileState::Immutable { inode, bundles, pages, } => { // Use the cache-line to load the bundle let dio = inode.dio(); let cache_index = bundle.as_u64() as usize % CACHED_BUNDLES; let cache_line = &mut bundles[cache_index]; let bundle = match cache_line { Some(b) if *b.key() == bundle => { // Cache-hit b } _ => { // Cache-miss - load the bundle into the cacheline and return its pages let dao = dio.load::<PageBundle>(&bundle).await?; cache_line.replace(dao); cache_line.as_mut().unwrap() } }; // Next we index into the right page let index = offset / stride_page; if index >= bundle.pages.len() as u64 { FileState::write_zeros(ret, size).await?; return Ok(()); } let page = bundle.pages[index as usize]; offset = offset - (index * stride_page); // If its a hole then just write zeros let page = match page { Some(a) => a, None => { FileState::write_zeros(ret, size).await?; return Ok(()); } }; // Use the cache-line to load the page let cache_index = page.as_u64() as usize % CACHED_PAGES; let cache_line = &mut pages[cache_index]; let page = match cache_line { Some(b) if *b.key() == page => { // Cache-hit b } _ => { // Cache-miss - load the bundle into the cacheline and return its pages let dao = dio.load::<Page>(&page).await?; cache_line.replace(dao); cache_line.as_mut().unwrap() } }; // Read the bytes from the page let buf = &page.buf; let sub_next = size.min(buf.len() as u64 - offset); if sub_next > 0 { let mut reader = Cursor::new(&buf[offset as usize..(offset + sub_next) as usize]); tokio::io::copy(&mut reader, ret).await?; size = size - sub_next; } } }; // Finish off the last bit with zeros and return the result FileState::write_zeros(ret, size).await?; Ok(()) } pub async fn write_zeros(ret: &mut Cursor<&mut Vec<u8>>, size: u64) -> Result<()> { if size <= 0 { return Ok(()); } let offset = super::model::PAGE_SIZE as u64 - size; let mut reader = Cursor::new(&ZERO_PAGE); reader.set_position(offset); tokio::io::copy(&mut reader, ret).await?; Ok(()) } pub async fn write_page(&mut self, mut offset: u64, reader: &mut Cursor<&[u8]>) -> Result<()> { let (dirty, inode, bundles, pages) = match self { FileState::Mutable { dirty, inode, bundles, pages, } => (dirty, inode, bundles, pages), FileState::Immutable { inode: _, bundles: _, pages: _, } => { bail!(FileSystemErrorKind::NoAccess); } }; *dirty = true; // Compute the strides let dio = inode.trans(); let inode_key = inode.key().clone(); let stride_page = super::model::PAGE_SIZE as u64; let stride_bundle = super::model::PAGES_PER_BUNDLE as u64 * stride_page; // Expand the bundles until we have enough of them to cover this write offset let index = offset / stride_bundle; if inode.bundles.len() <= index as usize { let mut guard = inode.as_mut(); while guard.bundles.len() <= index as usize { guard.bundles.push(None); } drop(guard); dio.commit().await?; } offset = offset - (index * stride_bundle); // If the bundle is a hole then we need to fill it let bundle = match inode.bundles[index as usize] { Some(a) => a, None => { // Create the bundle let mut bundle = dio.store(PageBundle { pages: Vec::new() })?; bundle.attach_orphaned(&inode_key)?; let key = bundle.key().clone(); // Replace the cache-line with this new one (if something was left behind then commit it) // (in the next section we will commit the row out of this match statement) let cache_index = bundle.key().as_u64() as usize % CACHED_BUNDLES; let cache_line = &mut bundles[cache_index]; cache_line.replace(bundle); // Write the entry to the inode and return its reference inode.as_mut().bundles.insert(index as usize, Some(key)); dio.commit().await?; key } }; // Use the cache-line to load the bundle let cache_index = bundle.as_u64() as usize % CACHED_BUNDLES; let cache_line = &mut bundles[cache_index]; let bundle = match cache_line { Some(b) if *b.key() == bundle => { // Cache-hit b } _ => { // Cache-miss - load the bundle into the cacheline and return its pages let dao = dio.load::<PageBundle>(&bundle).await?; cache_line.replace(dao); cache_line.as_mut().unwrap() } }; // Expand the page until we have enough of them to cover this write offset let index = offset / stride_page; if bundle.pages.len() <= index as usize { let mut guard = bundle.as_mut(); while guard.pages.len() <= super::model::PAGES_PER_BUNDLE as usize { guard.pages.push(None); } while guard.pages.len() <= index as usize { guard.pages.push(None); } drop(guard); dio.commit().await?; } offset = offset - (index * stride_page); // If the page is a hole then we need to fill it let bundle_key = bundle.key().clone(); let page_ref = bundle.pages[index as usize]; let page = match page_ref { Some(a) => a.clone(), None => { // Create the page (and commit it for reference integrity) let mut page = dio.store(Page { buf: Vec::new() })?; page.attach_orphaned(&bundle_key)?; let key = page.key().clone(); // Replace the cache-line with this new one (if something was left behind then commit it) // (in the next section we will commit the row out of this match statement) let cache_index = page.key().as_u64() as usize % CACHED_BUNDLES; let cache_line = &mut pages[cache_index]; cache_line.replace(page.as_mut_owned()); // Write the entry to the inode and return its reference bundle.as_mut().pages.insert(index as usize, Some(key)); dio.commit().await?; key } }; // Use the cache-line to load the page let cache_index = page.as_u64() as usize % CACHED_BUNDLES; let cache_line = &mut pages[cache_index]; let page = match cache_line { Some(b) if *b.key() == page => { // Cache-hit b } _ => { // Cache-miss - load the page into the cacheline and return its pages let dao = dio.load::<Page>(&page).await?; let dao = dao.as_mut_owned(); cache_line.replace(dao); cache_line.as_mut().unwrap() } }; // Expand the buffer until it has bytes at the spot we are writing while page.buf.len() < offset as usize { page.buf.push(0); } // Write to the page let mut writer = Cursor::new(&mut page.buf); writer.set_position(offset); tokio::io::copy(reader, &mut writer).await?; Ok(()) } pub async fn commit(&mut self) -> Result<()> { let (dirty, inode, _, pages) = match self { FileState::Mutable { dirty, inode, bundles, pages, } => (dirty, inode, bundles, pages), FileState::Immutable { inode: _, bundles: _, pages: _, } => { return Ok(()); } }; if *dirty { for page in pages.iter_mut() { page.take(); } let dio = inode.trans(); dio.commit().await?; *dirty = false; } Ok(()) } pub async fn set_xattr(&mut self, name: &str, value: &str) -> Result<()> { match self { FileState::Mutable { dirty: _, inode, bundles: _, pages: _, } => { inode .as_mut() .xattr .insert(name.to_string(), value.to_string()) .await? } FileState::Immutable { inode: _, bundles: _, pages: _, } => { bail!(FileSystemErrorKind::NoAccess); } }; Ok(()) } pub async fn remove_xattr(&mut self, name: &str) -> Result<bool> { let name = name.to_string(); let ret = match self { FileState::Mutable { dirty: _, inode, bundles: _, pages: _, } => inode.as_mut().xattr.delete(&name).await?, FileState::Immutable { inode: _, bundles: _, pages: _, } => { bail!(FileSystemErrorKind::NoAccess); } }; Ok(ret) } pub async fn get_xattr(&self, name: &str) -> Result<Option<String>> { let name = name.to_string(); let ret = match self { FileState::Mutable { dirty: _, inode, bundles: _, pages: _, } => inode.xattr.get(&name).await?.map(|a| a.deref().clone()), FileState::Immutable { inode, bundles: _, pages: _, } => inode.xattr.get(&name).await?.map(|a| a.deref().clone()), }; Ok(ret) } pub async fn list_xattr(&self) -> Result<FxHashMap<String, String>> { let mut ret = FxHashMap::default(); match self { FileState::Mutable { dirty: _, inode, bundles: _, pages: _, } => { for (k, v) in inode.xattr.iter().await? { ret.insert(k, v.deref().clone()); } } FileState::Immutable { inode, bundles: _, pages: _, } => { for (k, v) in inode.xattr.iter().await? { ret.insert(k, v.deref().clone()); } } } Ok(ret) } } #[async_trait] impl FileApi for RegularFile { fn kind(&self) -> FileKind { FileKind::RegularFile } fn ino(&self) -> u64 { self.ino } fn uid(&self) -> u32 { self.uid } fn gid(&self) -> u32 { self.gid } fn size(&self) -> u64 { self.size.read() } fn mode(&self) -> u32 { self.mode } fn name(&self) -> String { self.name.clone() } fn created(&self) -> u64 { self.created } fn updated(&self) -> u64 { self.updated } fn accessed(&self) -> u64 { self.updated } async fn fallocate(&self, size: u64) -> Result<()> { let mut lock = self.state.lock().await; lock.set_size(size)?; *self.size.lock_write() = size; Ok(()) } async fn read(&self, mut offset: u64, mut size: u64) -> Result<Bytes> { // Clip the read to the correct size (or return EOF) let mut state = self.state.lock().await; let file_size = state.get_size()?; if offset >= file_size { //return Err(libc::EOF.into()); return Ok(Bytes::from(Vec::new())); } size = size.min(file_size - offset); if size <= 0 { return Ok(Bytes::from(Vec::new())); } // Prepare let stride_page = super::model::PAGE_SIZE as u64; let mut ret = Vec::with_capacity(size as usize); let mut cursor = Cursor::new(&mut ret); // Read the data (under a lock) while size > 0 { let sub_offset = offset % stride_page; let sub_size = size.min(stride_page - sub_offset); if sub_size > 0 { state.read_page(offset, sub_size, &mut cursor).await?; } // Move the data pointers and offsets size = size - sub_size; offset = offset + sub_size; } Ok(Bytes::from(ret)) } async fn write(&self, mut offset: u64, data: &[u8]) -> Result<u64> { // Validate let mut size = data.len(); if size <= 0 { return Ok(0); } // Prepare let stride_page = super::model::PAGE_SIZE; // Update the inode let mut state = self.state.lock().await; let end = offset + data.len() as u64; if end > state.get_size()? { state.set_size(end)?; } // Write the data (under a lock) let mut data_offset = 0 as usize; while size > 0 { let sub_offset = offset % stride_page as u64; let sub_size = size.min(stride_page - sub_offset as usize); if sub_size > 0 { let mut reader = Cursor::new(&data[data_offset..(data_offset + sub_size) as usize]); state.write_page(offset, &mut reader).await?; } // Move the data pointers and offsets size = size - sub_size; offset = offset + sub_size as u64; data_offset = data_offset + sub_size as usize; } // Update the size of the file if it has grown in side (do this update lock to prevent race conditions) *self.size.lock_write() = state.get_size()?; // Success Ok(data.len() as u64) } async fn commit(&self) -> Result<()> { let mut state = self.state.lock().await; state.commit().await?; Ok(()) } async fn set_xattr(&mut self, name: &str, value: &str) -> Result<()> { let mut state = self.state.lock().await; state.set_xattr(name, value).await } async fn remove_xattr(&mut self, name: &str) -> Result<bool> { let mut state = self.state.lock().await; state.remove_xattr(name).await } async fn get_xattr(&self, name: &str) -> Result<Option<String>> { let state = self.state.lock().await; state.get_xattr(name).await } async fn list_xattr(&self) -> Result<FxHashMap<String, String>> { let state = self.state.lock().await; state.list_xattr().await } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/api.rs
files/src/api.rs
use super::dir::Directory; use super::file::RegularFile; use super::fixed::FixedFile; use super::symlink::SymLink; use async_trait::async_trait; use bytes::Bytes; use enum_dispatch::enum_dispatch; use fxhash::FxHashMap; use serde::*; use crate::error::*; #[enum_dispatch(FileApi)] pub enum FileSpec { //Custom, //NamedPipe, //CharDevice, //BlockDevice, Directory, RegularFile, SymLink, //Socket, FixedFile, } #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum FileKind { Directory, RegularFile, FixedFile, SymLink, } #[async_trait] #[enum_dispatch] pub trait FileApi { fn ino(&self) -> u64; fn name(&self) -> String; fn kind(&self) -> FileKind; fn uid(&self) -> u32 { 0 } fn gid(&self) -> u32 { 0 } fn size(&self) -> u64 { 0 } fn mode(&self) -> u32 { 0 } fn accessed(&self) -> u64 { 0 } fn created(&self) -> u64 { 0 } fn updated(&self) -> u64 { 0 } async fn fallocate(&self, _size: u64) -> Result<()> { Ok(()) } async fn read(&self, _offset: u64, _size: u64) -> Result<Bytes> { Ok(Bytes::from(Vec::new())) } async fn write(&self, _offset: u64, _data: &[u8]) -> Result<u64> { Ok(0) } fn link(&self) -> Option<String> { None } async fn commit(&self) -> Result<()> { Ok(()) } async fn set_xattr(&mut self, _name: &str, _value: &str) -> Result<()> { Err(FileSystemErrorKind::NotImplemented.into()) } async fn remove_xattr(&mut self, _name: &str) -> Result<bool> { Ok(false) } async fn get_xattr(&self, _name: &str) -> Result<Option<String>> { Ok(None) } async fn list_xattr(&self) -> Result<FxHashMap<String, String>> { Ok(FxHashMap::default()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/model.rs
files/src/model.rs
use super::api::*; use super::dir::Directory; use super::file::RegularFile; use super::fixed::FixedFile; use super::symlink::SymLink; use ate::prelude::*; use fxhash::FxHashMap; use serde::*; pub const PAGES_PER_BUNDLE: usize = 1024; pub const PAGE_SIZE: usize = 131072; pub const WEB_CONFIG_ID: u64 = 0xb709d79e5cf6dd64u64; /// Represents a block of data #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Page { pub buf: Vec<u8>, } /// Represents a bundle of 1024 pages #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PageBundle { pub pages: Vec<Option<PrimaryKey>>, } #[derive(Debug, Default, Serialize, Deserialize, Clone)] pub struct Dentry { pub parent: Option<u64>, pub name: String, pub mode: u32, pub uid: u32, pub gid: u32, pub xattr: FxHashMap<String, String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Inode { pub kind: FileKind, pub dentry: Dentry, pub size: u64, pub bundles: Vec<Option<PrimaryKey>>, pub children: DaoVec<Inode>, pub link: Option<String>, pub xattr: DaoMap<String, String>, } impl Inode { pub fn new(name: String, mode: u32, uid: u32, gid: u32, kind: FileKind) -> Inode { Inode { kind, dentry: Dentry { name, mode, parent: None, uid, gid, xattr: FxHashMap::default(), }, size: 0, bundles: Vec::default(), children: DaoVec::new(), link: None, xattr: DaoMap::default(), } } pub async fn as_file_spec(ino: u64, created: u64, updated: u64, dao: Dao<Inode>) -> FileSpec { match dao.kind { FileKind::Directory => FileSpec::Directory(Directory::new(dao, created, updated)), FileKind::RegularFile => { FileSpec::RegularFile(RegularFile::new(dao, created, updated).await) } FileKind::SymLink => FileSpec::SymLink(SymLink::new(dao, created, updated)), FileKind::FixedFile => FileSpec::FixedFile( FixedFile::new(ino, dao.dentry.name.clone(), FileKind::RegularFile) .created(created) .updated(updated), ), } } pub async fn as_file_spec_mut( ino: u64, created: u64, updated: u64, dao: DaoMut<Inode>, ) -> FileSpec { match dao.kind { FileKind::Directory => FileSpec::Directory(Directory::new_mut(dao, created, updated)), FileKind::RegularFile => { FileSpec::RegularFile(RegularFile::new_mut(dao, created, updated).await) } FileKind::SymLink => FileSpec::SymLink(SymLink::new_mut(dao, created, updated)), FileKind::FixedFile => FileSpec::FixedFile( FixedFile::new(ino, dao.dentry.name.clone(), FileKind::RegularFile) .created(created) .updated(updated), ), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/dir.rs
files/src/dir.rs
use super::api::FileKind; use super::model::*; use crate::api::FileApi; use async_trait::async_trait; use error_chain::bail; use fxhash::FxHashMap; use std::ops::Deref; use ate::prelude::*; use crate::error::*; #[derive(Debug)] pub struct Directory { pub state: DirectoryState, pub key: PrimaryKey, pub created: u64, pub updated: u64, } #[derive(Debug)] pub enum DirectoryState { Immutable { inode: Dao<Inode> }, Mutable { inode: DaoMut<Inode> }, } impl Directory { pub fn new(inode: Dao<Inode>, created: u64, updated: u64) -> Directory { Directory { key: inode.key().clone(), state: DirectoryState::Immutable { inode }, created, updated, } } pub fn new_mut(inode: DaoMut<Inode>, created: u64, updated: u64) -> Directory { Directory { key: inode.key().clone(), state: DirectoryState::Mutable { inode }, created, updated, } } } #[async_trait] impl FileApi for Directory { fn kind(&self) -> FileKind { FileKind::Directory } fn ino(&self) -> u64 { self.key.as_u64() } fn uid(&self) -> u32 { match &self.state { DirectoryState::Immutable { inode } => inode.dentry.uid, DirectoryState::Mutable { inode } => inode.dentry.uid, } } fn gid(&self) -> u32 { match &self.state { DirectoryState::Immutable { inode } => inode.dentry.gid, DirectoryState::Mutable { inode } => inode.dentry.gid, } } fn size(&self) -> u64 { 0 } fn mode(&self) -> u32 { match &self.state { DirectoryState::Immutable { inode } => inode.dentry.mode, DirectoryState::Mutable { inode } => inode.dentry.mode, } } fn name(&self) -> String { match &self.state { DirectoryState::Immutable { inode } => inode.dentry.name.clone(), DirectoryState::Mutable { inode } => inode.dentry.name.clone(), } } fn created(&self) -> u64 { self.created } fn updated(&self) -> u64 { self.updated } fn accessed(&self) -> u64 { self.updated } async fn set_xattr(&mut self, name: &str, value: &str) -> Result<()> { match &mut self.state { DirectoryState::Immutable { inode: _ } => bail!(FileSystemErrorKind::NoAccess), DirectoryState::Mutable { inode } => { inode .as_mut() .xattr .insert(name.to_string(), value.to_string()) .await? } }; Ok(()) } async fn remove_xattr(&mut self, name: &str) -> Result<bool> { let name = name.to_string(); let ret = match &mut self.state { DirectoryState::Immutable { inode: _ } => bail!(FileSystemErrorKind::NoAccess), DirectoryState::Mutable { inode } => inode.as_mut().xattr.delete(&name).await?, }; Ok(ret) } async fn get_xattr(&self, name: &str) -> Result<Option<String>> { let name = name.to_string(); let ret = match &self.state { DirectoryState::Immutable { inode } => { inode.xattr.get(&name).await?.map(|a| a.deref().clone()) } DirectoryState::Mutable { inode } => { inode.xattr.get(&name).await?.map(|a| a.deref().clone()) } }; Ok(ret) } async fn list_xattr(&self) -> Result<FxHashMap<String, String>> { let mut ret = FxHashMap::default(); match &self.state { DirectoryState::Mutable { inode } => { for (k, v) in inode.xattr.iter().await? { ret.insert(k, v.deref().clone()); } } DirectoryState::Immutable { inode } => { for (k, v) in inode.xattr.iter().await? { ret.insert(k, v.deref().clone()); } } }; Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/files/src/handle.rs
files/src/handle.rs
#[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use derivative::*; use super::api::*; use super::attr::*; #[derive(Derivative)] #[derivative(Debug)] pub struct OpenHandle where Self: Send + Sync, { pub dirty: seqlock::SeqLock<bool>, pub inode: u64, pub fh: u64, #[derivative(Debug = "ignore")] pub spec: FileSpec, pub kind: FileKind, pub attr: FileAttr, pub read_only: bool, pub children: Vec<DirectoryEntry>, } #[derive(Debug)] pub struct DirectoryEntry where Self: Send + Sync, { pub inode: u64, pub kind: FileKind, pub attr: FileAttr, pub name: String, pub uid: u32, pub gid: u32, } impl OpenHandle { pub fn add_child(&mut self, spec: &FileSpec, uid: u32, gid: u32) { self.children.push(DirectoryEntry { inode: spec.ino(), kind: spec.kind(), name: spec.name(), attr: FileAttr::new(spec, uid, gid), uid, gid, }); } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/build.rs
wasmer-os/build.rs
extern crate build_deps; fn main() { build_deps::rerun_if_changed_paths( "static/bin/*" ).unwrap(); build_deps::rerun_if_changed_paths( "static/dev/*" ).unwrap(); build_deps::rerun_if_changed_paths( "static/etc/*" ).unwrap(); build_deps::rerun_if_changed_paths( "static/tmp/*" ).unwrap(); build_deps::rerun_if_changed_paths( "static/*" ).unwrap(); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/stdout.rs
wasmer-os/src/stdout.rs
#![allow(unused_imports)] #![allow(dead_code)] use std::io::Write; use std::ops::{Deref, DerefMut}; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use super::cconst::*; use super::common::*; use super::fd::*; use super::tty::*; #[derive(Debug, Clone)] pub struct Stdout { pub fd: Fd, } impl Deref for Stdout { type Target = Fd; fn deref(&self) -> &Self::Target { &self.fd } } impl DerefMut for Stdout { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.fd } } impl Stdout { pub fn new(mut fd: Fd) -> Stdout { fd.flag = FdFlag::Stdout(fd.is_tty()); Stdout { fd } } pub fn fd(&self) -> Fd { self.fd.clone() } pub async fn draw(&mut self, data: &str) { if let Err(err) = self.fd.write(data.as_bytes()).await { warn!("stdout-err: {}", err); } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/tty.rs
wasmer-os/src/tty.rs
#![allow(unused_imports)] #![allow(dead_code)] use core::sync::atomic::AtomicBool; use core::sync::atomic::Ordering; use derivative::*; use std::io::Write; use std::sync::Arc; use std::sync::Mutex; use tokio::sync::Mutex as AsyncMutex; use tokio::sync::RwLock; use tokio::sync::mpsc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use super::cconst::*; use super::common::*; use super::err; use super::fd::*; use super::job::*; use super::reactor::*; use super::stdout::*; use super::pipe::*; use super::api::*; #[derive(Debug, Clone)] pub enum TtyMode { Null, Console, StdIn(Job), } struct TtyInnerAsync { pub line: String, pub paragraph: String, pub cursor_pos: usize, pub cursor_history: usize, pub history: Vec<String>, pub mode: TtyMode, pub echo: bool, pub prompt: String, pub prompt_color: String, pub cols: u32, pub rows: u32, } #[derive(Debug)] struct TtyInnerSync { pub buffering: AtomicBool, } impl TtyInnerAsync { pub fn reset_line(&mut self) { self.line.clear(); self.cursor_pos = 0; } pub fn reset_history_cursor(&mut self) { self.cursor_history = 0; } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum TtyOuter { Normal, Mobile, SSH, } impl TtyOuter { pub fn is_mobile(&self) -> bool { use TtyOuter::*; match self { Normal => false, Mobile => true, SSH => false } } } #[derive(Derivative, Clone)] #[derivative(Debug)] pub struct Tty { #[derivative(Debug = "ignore")] inner_async: Arc<AsyncMutex<TtyInnerAsync>>, inner_sync: Arc<TtyInnerSync>, stdout: Stdout, stderr: Fd, log: Fd, outer: TtyOuter, } impl Tty { pub fn new(stdout: Stdout, stderr: Fd, log: Fd, outer: TtyOuter) -> Tty { let mut stdout = stdout.clone(); stdout.set_flag(FdFlag::Stdout(true)); Tty { inner_async: Arc::new(AsyncMutex::new(TtyInnerAsync { line: String::new(), paragraph: String::new(), cursor_pos: 0, cursor_history: 0, history: Vec::new(), mode: TtyMode::Console, echo: true, prompt: "$".to_string(), prompt_color: "$".to_string(), cols: 1, rows: 1, })), inner_sync: Arc::new(TtyInnerSync { buffering: AtomicBool::new(true), }), stdout, stderr, log, outer, } } pub fn channel(abi: &Arc<dyn ConsoleAbi>, unfinished_line: &Arc<AtomicBool>, outer: TtyOuter) -> Tty { let (stdio, mut stdio_rx) = pipe_out(FdFlag::None); let mut stdout = stdio.clone(); let mut stderr = stdio.clone(); let mut log = stdio.clone(); stdout.set_flag(FdFlag::Stdout(true)); stderr.set_flag(FdFlag::Stderr(true)); log.set_flag(FdFlag::Log); let stdout = Stdout::new(stdout); let tty = Tty::new(stdout, stderr, log, outer); // Stdout, Stderr and Logging (this is serialized in order for a good reason!) let unfinished_line = unfinished_line.clone(); let system = System::default(); { let abi = abi.clone(); let work = async move { while let Some(msg) = stdio_rx.recv().await { match msg { FdMsg::Data { data, flag } => match flag { FdFlag::Log => { let txt = String::from_utf8_lossy(&data[..]); let mut txt = txt.as_ref(); while txt.ends_with("\n") || txt.ends_with("\r") { txt = &txt[..(txt.len() - 1)]; } abi.log(txt.to_string()).await; } _ => { let text = String::from_utf8_lossy(&data[..])[..].replace("\n", "\r\n"); match flag { FdFlag::Stderr(_) => abi.stderr(text.as_bytes().to_vec()).await, _ => abi.stdout(text.as_bytes().to_vec()).await, }; let is_unfinished = is_cleared_line(&text) == false; unfinished_line.store(is_unfinished, Ordering::Release); } }, FdMsg::Flush { tx } => { let _ = tx.send(()).await; } } } info!("main IO loop exited"); }; #[cfg(target_family = "wasm")] system.fork_local(work); #[cfg(not(target_family = "wasm"))] system.fork_shared(move || work); } tty } pub fn stdout(&self) -> Stdout { self.stdout.clone() } pub fn fd_stdout(&self) -> Fd { self.stdout.fd.clone() } pub fn stderr(&self) -> Fd { self.stderr.clone() } pub fn log(&self) -> Fd { self.log.clone() } pub async fn reset_line(&self) { self.inner_async.lock().await.reset_line(); } pub async fn get_selected_history(&self) -> Option<String> { let inner = self.inner_async.lock().await; if inner.cursor_history > inner.history.len() { return None; } let cursor_history = inner.history.len() - inner.cursor_history; inner.history.get(cursor_history).map(|a| a.clone()) } pub async fn restore_selected_history(&mut self) { let cursor_history = { let mut inner = self.inner_async.lock().await; if inner.cursor_history > inner.history.len() { inner.reset_line(); debug!("restore-history-over"); return; } inner.history.len() - inner.cursor_history }; self.set_cursor_to_start().await; self.draw_undo().await; let right = { let mut inner = self.inner_async.lock().await; let last = inner.history.get(cursor_history).map(|a| a.clone()); if let Some(last) = last { debug!("restore-history: pos={} val={}", cursor_history, last); inner.cursor_pos = last.len(); inner.line = last.clone(); last as String } else { inner.reset_line(); debug!("restore-history: pos={} miss", cursor_history); String::new() } }; self.draw(right.as_str()).await } pub async fn record_history(&self, cmd: String) { if cmd.len() <= 0 { return; } let mut inner = self.inner_async.lock().await; debug!("add-history: {}", cmd); inner.history.retain(|c| c.ne(&cmd)); inner.history.push(cmd); } pub async fn get_paragraph(&self) -> String { let mut inner = self.inner_async.lock().await; if inner.line.len() <= 0 { return String::new(); } if inner.paragraph.len() > 0 { inner.paragraph += " "; } let line = inner.line.clone(); inner.paragraph += line.as_str(); inner.paragraph.clone() } pub async fn reset_history_cursor(&self) { let mut inner = self.inner_async.lock().await; inner.reset_history_cursor(); } pub async fn reset_paragraph(&self) { let mut inner = self.inner_async.lock().await; inner.paragraph.clear(); } pub async fn set_bounds(&self, cols: u32, rows: u32) { let mut inner = self.inner_async.lock().await; inner.cols = cols; inner.rows = rows; } pub async fn backspace(&mut self) { let echo = { let inner = self.inner_async.lock().await; if inner.cursor_pos <= 0 { return; } inner.echo }; if echo { self.draw(Tty::TERM_CURSOR_LEFT).await; self.draw_undo().await; } let right = { let mut inner = self.inner_async.lock().await; let left = inner.line[..inner.cursor_pos - 1].to_string(); let right = inner.line[inner.cursor_pos..].to_string(); inner.line = format!("{}{}", left, right); inner.cursor_pos -= 1; right }; if echo { self.draw_fixed(right.as_str()).await } } pub async fn delete(&mut self) { let echo = { let inner = self.inner_async.lock().await; if inner.cursor_pos >= inner.line.len() { return; } inner.echo }; if echo { self.draw_undo().await; } let right = { let mut inner = self.inner_async.lock().await; let left = inner.line[..inner.cursor_pos].to_string(); let right = inner.line[inner.cursor_pos + 1..].to_string(); inner.line = format!("{}{}", left, right); right }; if echo { self.draw_fixed(right.as_str()).await } } pub async fn cursor_left(&mut self) { let echo = { let mut inner = self.inner_async.lock().await; if inner.cursor_pos <= 0 { return; } inner.cursor_pos -= 1; inner.echo }; if echo { self.draw(Tty::TERM_CURSOR_LEFT).await; } } pub async fn cursor_right(&mut self) { let echo = { let mut inner = self.inner_async.lock().await; if inner.cursor_pos >= inner.line.len() { return; } inner.cursor_pos += 1; inner.echo }; if echo { self.draw(Tty::TERM_CURSOR_RIGHT).await; } } pub async fn cursor_up(&mut self) { let _echo = { let mut inner = self.inner_async.lock().await; if inner.cursor_history < inner.history.len() { inner.cursor_history += 1; } inner.echo }; self.restore_selected_history().await; } pub async fn cursor_down(&mut self) { let _echo = { let mut inner = self.inner_async.lock().await; if inner.cursor_history > 0 { inner.cursor_history -= 1; } inner.echo }; self.restore_selected_history().await; } pub async fn enter_mode(&self, mut mode: TtyMode, reactor: &Arc<RwLock<Reactor>>) { self.set_buffering(true); let last_mode = { let mut inner = self.inner_async.lock().await; std::mem::swap(&mut inner.mode, &mut mode); mode }; let mut reactor = reactor.write().await; match last_mode { TtyMode::StdIn(job) => { reactor.close_job(job, std::num::NonZeroU32::new(err::ERR_TERMINATED).unwrap()); } _ => {} } } pub fn set_buffering(&self, on: bool) { debug!("set_buffering on={}", on); self.inner_sync.buffering.store(on, Ordering::Relaxed); } pub fn is_buffering(&self) -> bool { self.inner_sync.buffering.load(Ordering::Relaxed) } pub async fn set_prompt(&self, prompt: String, prompt_color: String) { let mut inner = self.inner_async.lock().await; inner.prompt = prompt; inner.prompt_color = prompt_color; } pub async fn mode(&self) -> TtyMode { let inner = self.inner_async.lock().await; inner.mode.clone() } pub async fn echo(&mut self, data: &str) { let echo = self.inner_async.lock().await.echo; if echo { self.draw(data).await; } } pub async fn set_echo(&mut self, echo: bool) { self.inner_async.lock().await.echo = echo; } pub async fn add(&mut self, data: &str) { let echo = self.inner_async.lock().await.echo; if echo { self.draw_undo().await; } let right = { let mut inner = self.inner_async.lock().await; let cursor_pos = inner.cursor_pos; inner.line.insert_str(cursor_pos, data); inner.cursor_pos += data.len(); let right = if inner.cursor_pos < inner.line.len() { Some(inner.line[inner.cursor_pos..].to_string()) } else { None }; right }; if echo { let mut chars = String::new(); chars += Tty::TERM_WRAPAROUND; chars += data; if let Some(right) = right { chars += Tty::TERM_CURSOR_SAVE; chars += right.as_str(); chars += Tty::TERM_CURSOR_RESTORE; } self.draw(chars.as_str()).await; } } pub async fn draw_prompt(&mut self) { let prompt_color = self.inner_async.lock().await.prompt_color.clone(); let mut chars = String::new(); chars += Tty::TERM_DELETE_BELOW; chars += Tty::TERM_DELETE_LINE; chars += Tty::TERM_WRAPAROUND; chars += prompt_color.as_str(); self.draw(chars.as_str()).await; } pub async fn draw_welcome(&mut self) { let welcome = match self.outer { TtyOuter::Normal => Tty::WELCOME, TtyOuter::SSH => Tty::WELCOME_MEDIUM, TtyOuter::Mobile => Tty::WELCOME_SMALL }; let mut data = welcome .replace("\\x1B", "\x1B") .replace("\\r", "\r") .replace("\\n", "\n"); data.insert_str(0, Tty::TERM_NO_WRAPAROUND); self.draw(data.as_str()).await; } pub async fn set_cursor_to_start(&mut self) { let shift_left = { let mut inner = self.inner_async.lock().await; let pos = inner.cursor_pos; inner.cursor_pos = 0; pos }; let chars = std::iter::repeat(Tty::TERM_CURSOR_LEFT) .take(shift_left) .collect::<String>(); if chars.len() > 0 { self.draw(chars.as_str()).await } } pub async fn set_cursor_to_end(&mut self) { let shift_right = { let mut inner = self.inner_async.lock().await; let pos = inner.cursor_pos; if inner.line.len() > 0 { inner.cursor_pos = inner.line.len(); inner.line.len() - pos } else { inner.cursor_pos = 0; 0 } }; let chars = std::iter::repeat(Tty::TERM_CURSOR_RIGHT) .take(shift_right) .collect::<String>(); if chars.len() > 0 { self.draw(chars.as_str()).await } } pub async fn draw_undo(&mut self) -> String { let mut chars = String::new(); chars += Tty::TERM_CURSOR_SAVE; chars += Tty::TERM_DELETE_RIGHT; chars += Tty::TERM_CURSOR_RESTORE; chars += Tty::TERM_DELETE_BELOW; chars += Tty::TERM_CURSOR_RESTORE; self.draw(chars.as_str()).await; let inner = self.inner_async.lock().await; inner.line[inner.cursor_pos..].to_string() } pub async fn draw_fixed(&mut self, data: &str) { let mut chars = String::new(); chars += Tty::TERM_CURSOR_SAVE; chars += Tty::TERM_WRAPAROUND; chars += data; chars += Tty::TERM_CURSOR_RESTORE; self.stdout.draw(chars.as_str()).await; } pub async fn draw(&mut self, data: &str) { self.stdout.draw(data).await; } pub async fn flush_async(&mut self) -> std::io::Result<()> { self.stdout.flush_async().await } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/fd.rs
wasmer-os/src/fd.rs
#![allow(dead_code)] #![allow(unused_imports)] use bytes::{Buf, BytesMut}; use core::sync::atomic::AtomicBool; use core::sync::atomic::Ordering; use std::io::prelude::*; use std::io::SeekFrom; use std::num::NonZeroU32; use std::ops::Deref; use std::sync::atomic::AtomicI32; use std::sync::atomic::AtomicU32; use std::sync::Mutex; use std::sync::Weak; use std::{ pin::Pin, sync::Arc, task::{self, Context, Poll, Waker}, }; use tokio::io::{self, AsyncRead, AsyncWrite, ReadBuf}; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TryRecvError; use tokio::sync::mpsc::error::TrySendError; use tokio::sync::Mutex as AsyncMutex; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use super::bus::WasmCallerContext; use super::common::*; use super::err::*; use super::pipe::*; use super::poll::*; use super::reactor::*; use super::state::*; use crate::wasmer_vfs::{FileDescriptor, VirtualFile}; use crate::wasmer_wasi::{types as wasi_types, WasiFile, WasiFsError}; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum FdFlag { None, Stdin(bool), // bool indicates if the terminal is TTY Stdout(bool), // bool indicates if the terminal is TTY Stderr(bool), // bool indicates if the terminal is TTY Log, } impl FdFlag { pub fn is_tty(&self) -> bool { match self { FdFlag::Stdin(tty) => tty.clone(), FdFlag::Stdout(tty) => tty.clone(), FdFlag::Stderr(tty) => tty.clone(), _ => false, } } pub fn is_stdin(&self) -> bool { match self { FdFlag::Stdin(_) => true, _ => false, } } pub fn is_stdout(&self) -> bool { match self { FdFlag::Stdout(_) => true, _ => false, } } pub fn is_stderr(&self) -> bool { match self { FdFlag::Stderr(_) => true, _ => false, } } } impl std::fmt::Display for FdFlag { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { FdFlag::None => write!(f, "none"), FdFlag::Stdin(tty) => write!(f, "stdin(tty={})", tty), FdFlag::Stdout(tty) => write!(f, "stdout(tty={})", tty), FdFlag::Stderr(tty) => write!(f, "stderr(tty={})", tty), FdFlag::Log => write!(f, "log"), } } } #[derive(Debug, Clone)] pub enum FdMsg { Data { data: Vec<u8>, flag: FdFlag }, Flush { tx: mpsc::Sender<()> }, } impl FdMsg { pub fn new(data: Vec<u8>, flag: FdFlag) -> FdMsg { FdMsg::Data { data, flag } } pub fn flush() -> (mpsc::Receiver<()>, FdMsg) { let (tx, rx) = mpsc::channel(1); let msg = FdMsg::Flush { tx }; (rx, msg) } pub fn len(&self) -> usize { match self { FdMsg::Data { data, .. } => data.len(), FdMsg::Flush { .. } => 0usize, } } } #[derive(Debug, Clone)] pub struct Fd { pub(crate) flag: FdFlag, pub(crate) ctx: WasmCallerContext, pub(crate) closed: Arc<AtomicBool>, pub(crate) blocking: Arc<AtomicBool>, pub(crate) sender: Option<Arc<mpsc::Sender<FdMsg>>>, pub(crate) receiver: Option<Arc<AsyncMutex<ReactorPipeReceiver>>>, pub(crate) flip_to_abort: bool, pub(crate) ignore_flush: bool, } impl Fd { pub fn new( tx: Option<mpsc::Sender<FdMsg>>, rx: Option<mpsc::Receiver<FdMsg>>, mode: ReceiverMode, flag: FdFlag, ) -> Fd { let rx = rx.map(|rx| { Arc::new(AsyncMutex::new(ReactorPipeReceiver { rx, buffer: BytesMut::new(), mode, cur_flag: flag, })) }); Fd { flag, ctx: WasmCallerContext::default(), closed: Arc::new(AtomicBool::new(false)), blocking: Arc::new(AtomicBool::new(true)), sender: tx.map(|a| Arc::new(a)), receiver: rx, flip_to_abort: false, ignore_flush: false, } } pub fn combine(fd1: &Fd, fd2: &Fd) -> Fd { let mut ret = Fd { flag: fd1.flag, ctx: fd1.ctx.clone(), closed: fd1.closed.clone(), blocking: Arc::new(AtomicBool::new(fd1.blocking.load(Ordering::Relaxed))), sender: None, receiver: None, flip_to_abort: false, ignore_flush: false, }; if let Some(a) = fd1.sender.as_ref() { ret.sender = Some(a.clone()); } else if let Some(a) = fd2.sender.as_ref() { ret.sender = Some(a.clone()); } if let Some(a) = fd1.receiver.as_ref() { ret.receiver = Some(a.clone()); } else if let Some(a) = fd2.receiver.as_ref() { ret.receiver = Some(a.clone()); } ret } pub fn set_blocking(&self, blocking: bool) { self.blocking.store(blocking, Ordering::Relaxed); } pub fn forced_exit(&self, exit_code: NonZeroU32) { self.ctx.terminate(exit_code); } pub fn close(&self) { self.closed.store(true, Ordering::Release); } pub fn is_tty(&self) -> bool { self.flag.is_tty() } pub fn flag(&self) -> FdFlag { self.flag } pub fn set_flag(&mut self, flag: FdFlag) -> FdFlag { self.flag = flag; flag } pub fn set_ignore_flush(&mut self, val: bool) { self.ignore_flush = val; } pub fn is_closed(&self) -> bool { self.closed.load(Ordering::Acquire) } pub fn is_readable(&self) -> bool { self.receiver.is_some() } pub fn is_writable(&self) -> bool { self.sender.is_some() } fn check_closed(&self) -> io::Result<()> { if self.is_closed() { return Err(std::io::ErrorKind::BrokenPipe.into()); } Ok(()) } pub async fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.write_vec(buf.to_vec()).await } pub fn try_write(&mut self, buf: &[u8]) -> io::Result<Option<usize>> { self.try_send(FdMsg::new(buf.to_vec(), self.flag)) } pub async fn write_vec(&mut self, buf: Vec<u8>) -> io::Result<usize> { self.check_closed()?; if let Some(sender) = self.sender.as_mut() { let buf_len = buf.len(); let msg = FdMsg::new(buf, self.flag); if let Err(_err) = sender.send(msg).await { return Err(std::io::ErrorKind::BrokenPipe.into()); } Ok(buf_len) } else { return Err(std::io::ErrorKind::BrokenPipe.into()); } } pub(crate) async fn write_clear_line(&mut self) { let _ = self.write("\r\x1b[0K\r".as_bytes()).await; let _ = self.flush_async().await; } pub fn poll(&self) -> PollResult { poll_fd( self.receiver.as_ref(), self.sender.as_ref().map(|a| a.deref()), ) } pub async fn flush_async(&mut self) -> io::Result<()> { if self.ignore_flush { return Ok(()); } let (mut rx, msg) = FdMsg::flush(); if let Some(sender) = self.sender.as_mut() { if let Err(_err) = sender.send(msg).await { return Err(std::io::ErrorKind::BrokenPipe.into()); } } else { return Err(std::io::ErrorKind::BrokenPipe.into()); } rx.recv().await; Ok(()) } pub fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<FdMsg>> { if let Err(err) = self.check_closed() { return Poll::Ready(Err(err)); } if let Some(receiver) = self.receiver.as_mut() { let mut guard = receiver.blocking_lock(); if guard.buffer.has_remaining() { let mut buffer = BytesMut::new(); std::mem::swap(&mut guard.buffer, &mut buffer); return Poll::Ready(Ok(FdMsg::new(buffer.to_vec(), guard.cur_flag))); } if guard.mode == ReceiverMode::Message(true) { guard.mode = ReceiverMode::Message(false); return Poll::Ready(Ok(FdMsg::new(Vec::new(), guard.cur_flag))); } let msg = match guard .rx .poll_recv(cx) { Poll::Ready(Some(msg)) => msg, Poll::Ready(None) => { FdMsg::new(Vec::new(), guard.cur_flag) }, Poll::Pending => {return Poll::Pending; } }; if let FdMsg::Data { flag, .. } = &msg { guard.cur_flag = flag.clone(); } if msg.len() <= 0 { drop(guard); drop(receiver); if self.flip_to_abort { return Poll::Ready(Err(std::io::ErrorKind::BrokenPipe.into())); } self.flip_to_abort = true; } Poll::Ready(Ok(msg)) } else { if self.flip_to_abort { return Poll::Ready(Err(std::io::ErrorKind::BrokenPipe.into())); } self.flip_to_abort = true; Poll::Ready(Ok(FdMsg::new(Vec::new(), self.flag))) } } pub async fn read_async(&mut self) -> io::Result<FdMsg> { self.check_closed()?; if let Some(receiver) = self.receiver.as_mut() { let mut receiver = receiver.lock().await; if receiver.buffer.has_remaining() { let mut buffer = BytesMut::new(); std::mem::swap(&mut receiver.buffer, &mut buffer); return Ok(FdMsg::new(buffer.to_vec(), receiver.cur_flag)); } if receiver.mode == ReceiverMode::Message(true) { receiver.mode = ReceiverMode::Message(false); return Ok(FdMsg::new(Vec::new(), receiver.cur_flag)); } let msg = receiver .rx .recv() .await .unwrap_or_else(|| { FdMsg::new(Vec::new(), receiver.cur_flag) }); if let FdMsg::Data { flag, .. } = &msg { receiver.cur_flag = flag.clone(); } if msg.len() <= 0 { if self.flip_to_abort { return Err(std::io::ErrorKind::BrokenPipe.into()); } self.flip_to_abort = true; } Ok(msg) } else { if self.flip_to_abort { return Err(std::io::ErrorKind::BrokenPipe.into()); } self.flip_to_abort = true; return Ok(FdMsg::new(Vec::new(), self.flag)); } } fn try_send(&mut self, msg: FdMsg) -> io::Result<Option<usize>> { if let Some(sender) = self.sender.as_mut() { let buf_len = msg.len(); // Try and send the data match sender.try_send(msg) { Ok(_) => { return Ok(Some(buf_len)); } Err(TrySendError::Closed(_)) => { return Ok(Some(0)); } Err(TrySendError::Full(_)) => { // Check for a forced exit if self.ctx.should_terminate().is_some() { return Err(std::io::ErrorKind::Interrupted.into()); } // Maybe we are closed - if not then yield and try again if self.closed.load(Ordering::Acquire) { return Ok(Some(0usize)); } // We fail as this would have blocked Ok(None) } } } else { return Ok(Some(0usize)); } } fn blocking_send(&mut self, msg: FdMsg) -> io::Result<usize> { if let Some(sender) = self.sender.as_mut() { let buf_len = msg.len(); let mut wait_time = 0u64; let mut msg = Some(msg); loop { // Try and send the data match sender.try_send(msg.take().unwrap()) { Ok(_) => { return Ok(buf_len); } Err(TrySendError::Full(returned_msg)) => { msg = Some(returned_msg); } Err(TrySendError::Closed(_)) => { return Ok(0); } } // If we are none blocking then we are done if self.blocking.load(Ordering::Relaxed) == false { return Err(std::io::ErrorKind::WouldBlock.into()); } // Check for a forced exit if self.ctx.should_terminate().is_some() { return Err(std::io::ErrorKind::Interrupted.into()); } // Maybe we are closed - if not then yield and try again if self.closed.load(Ordering::Acquire) { return Ok(0usize); } // Linearly increasing wait time wait_time += 1; let wait_time = u64::min(wait_time / 10, 20); std::thread::park_timeout(std::time::Duration::from_millis(wait_time)); } } else { return Ok(0usize); } } fn blocking_recv<T>(&mut self, receiver: &mut mpsc::Receiver<T>) -> io::Result<Option<T>> { let mut tick_wait = 0u64; loop { // Try and receive the data match receiver.try_recv() { Ok(a) => { return Ok(Some(a)); } Err(TryRecvError::Empty) => {} Err(TryRecvError::Disconnected) => { if self.flip_to_abort { return Err(std::io::ErrorKind::BrokenPipe.into()); } self.flip_to_abort = true; return Ok(None); } } // If we are none blocking then we are done if self.blocking.load(Ordering::Relaxed) == false { return Err(std::io::ErrorKind::WouldBlock.into()); } // Check for a forced exit if self.ctx.should_terminate().is_some() { return Err(std::io::ErrorKind::Interrupted.into()); } // Maybe we are closed - if not then yield and try again if self.closed.load(Ordering::Acquire) { if self.flip_to_abort { return Err(std::io::ErrorKind::BrokenPipe.into()); } self.flip_to_abort = true; return Ok(None); } // Linearly increasing wait time tick_wait += 1; let wait_time = u64::min(tick_wait / 10, 20); std::thread::park_timeout(std::time::Duration::from_millis(wait_time)); } } } impl Seek for Fd { fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> { Ok(0u64) } } impl Write for Fd { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.blocking_send(FdMsg::new(buf.to_vec(), self.flag)) } fn flush(&mut self) -> io::Result<()> { if self.ignore_flush { return Ok(()); } let (mut rx, msg) = FdMsg::flush(); self.blocking_send(msg)?; self.blocking_recv(&mut rx)?; Ok(()) } } impl Read for Fd { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if let Some(receiver) = self.receiver.as_mut() { let mut tick_wait = 0u64; loop { // Make an attempt to read the data if let Ok(mut receiver) = receiver.try_lock() { // If we have any data then lets go! if receiver.buffer.has_remaining() { let max = receiver.buffer.remaining().min(buf.len()); buf[0..max].copy_from_slice(&receiver.buffer[..max]); receiver.buffer.advance(max); return Ok(max); } // Otherwise lets get some more data match receiver.rx.try_recv() { Ok(msg) => { if let FdMsg::Data { data, flag } = msg { //error!("on_stdin {}", data.iter().map(|byte| format!("\\u{{{:04X}}}", byte).to_owned()).collect::<Vec<String>>().join("")); receiver.cur_flag = flag; receiver.buffer.extend_from_slice(&data[..]); if receiver.mode == ReceiverMode::Message(false) { receiver.mode = ReceiverMode::Message(true); } } } Err(mpsc::error::TryRecvError::Empty) => {} Err(mpsc::error::TryRecvError::Disconnected) => { if self.flip_to_abort { return Err(std::io::ErrorKind::BrokenPipe.into()); } self.flip_to_abort = true; return Ok(0usize); } } } // If we are none blocking then we are done if self.blocking.load(Ordering::Relaxed) == false { return Err(std::io::ErrorKind::WouldBlock.into()); } // Check for a forced exit if self.ctx.should_terminate().is_some() { return Err(std::io::ErrorKind::Interrupted.into()); } // Maybe we are closed - if not then yield and try again if self.closed.load(Ordering::Acquire) { if self.flip_to_abort { return Err(std::io::ErrorKind::BrokenPipe.into()); } self.flip_to_abort = true; std::thread::yield_now(); return Ok(0usize); } // Linearly increasing wait time tick_wait += 1; let wait_time = u64::min(tick_wait / 10, 20); std::thread::park_timeout(std::time::Duration::from_millis(wait_time)); } } else { if self.flip_to_abort { return Err(std::io::ErrorKind::BrokenPipe.into()); } self.flip_to_abort = true; return Ok(0usize); } } } impl VirtualFile for Fd { fn last_accessed(&self) -> u64 { 0 } fn last_modified(&self) -> u64 { 0 } fn created_time(&self) -> u64 { 0 } fn size(&self) -> u64 { 0 } fn set_len(&mut self, _new_size: wasi_types::__wasi_filesize_t) -> Result<(), WasiFsError> { Ok(()) } fn unlink(&mut self) -> Result<(), WasiFsError> { Ok(()) } fn bytes_available_read(&self) -> Result<Option<usize>, WasiFsError> { if self.ctx.should_terminate().is_some() { return Err(WasiFsError::Interrupted); } let ret = self.poll(); if ret.is_closed { if self.flip_to_abort { return Err(WasiFsError::BrokenPipe); } return Ok(Some(0usize)); } if ret.can_read { Ok(Some(ret.bytes_available_read)) } else { Ok(None) } } fn bytes_available_write(&self) -> Result<Option<usize>, WasiFsError> { if self.ctx.should_terminate().is_some() { return Err(WasiFsError::Interrupted); } let ret = self.poll(); if ret.is_closed { if self.flip_to_abort { return Err(WasiFsError::BrokenPipe); } return Ok(Some(0usize)); } if ret.can_write { Ok(Some(4096usize)) } else { Ok(None) } } } #[derive(Debug, Clone)] pub struct WeakFd { pub(crate) flag: FdFlag, pub(crate) ctx: WasmCallerContext, pub(crate) closed: Weak<AtomicBool>, pub(crate) blocking: Weak<AtomicBool>, pub(crate) sender: Option<Weak<mpsc::Sender<FdMsg>>>, pub(crate) receiver: Option<Weak<AsyncMutex<ReactorPipeReceiver>>>, pub(crate) flip_to_abort: bool, pub(crate) ignore_flush: bool, } impl WeakFd { pub fn null() -> WeakFd { WeakFd { flag: FdFlag::None, ctx: WasmCallerContext::default(), closed: Weak::new(), blocking: Weak::new(), sender: None, receiver: None, flip_to_abort: false, ignore_flush: false, } } pub fn upgrade(&self) -> Option<Fd> { let closed = match self.closed.upgrade() { Some(a) => a, None => { return None; } }; let blocking = match self.blocking.upgrade() { Some(a) => a, None => { return None; } }; let sender = self.sender.iter().filter_map(|a| a.upgrade()).next(); let receiver = self.receiver.iter().filter_map(|a| a.upgrade()).next(); Some(Fd { flag: self.flag, ctx: self.ctx.clone(), closed, blocking, sender, receiver, flip_to_abort: self.flip_to_abort, ignore_flush: self.ignore_flush, }) } } impl Fd { pub fn downgrade(&self) -> WeakFd { let closed = Arc::downgrade(&self.closed); let blocking = Arc::downgrade(&self.blocking); let sender = self.sender.iter().map(|a| Arc::downgrade(&a)).next(); let receiver = self.receiver.iter().map(|a| Arc::downgrade(&a)).next(); WeakFd { flag: self.flag, ctx: self.ctx.clone(), closed, blocking, sender, receiver, flip_to_abort: self.flip_to_abort, ignore_flush: self.ignore_flush, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/lib.rs
wasmer-os/src/lib.rs
pub mod api; pub mod builtins; pub mod bus; pub mod eval; pub mod fs; pub mod bin_factory; pub mod cconst; pub mod common; pub mod console; pub mod environment; pub mod err; pub mod fd; pub mod job; pub mod pipe; pub mod poll; pub mod reactor; pub mod state; pub mod stdio; pub mod stdout; pub mod tty; pub mod wasi; pub mod wizard_executor; // Re-exports pub use wasmer_os_grammar as grammar; pub use grammar::ast; pub use wasmer; #[cfg(feature = "wasmer-compiler")] pub use wasmer_compiler; #[cfg(feature = "wasmer-compiler-cranelift")] pub use wasmer_compiler_cranelift; #[cfg(feature = "wasmer-compiler-llvm")] pub use wasmer_compiler_llvm; #[cfg(feature = "wasmer-compiler-singlepass")] pub use wasmer_compiler_singlepass; pub use wasmer_vfs; pub use wasmer_wasi; #[cfg(all(not(feature = "sys"), not(feature = "js")))] compile_error!("At least the `sys` or the `js` feature must be enabled. Please, pick one.");
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/wasi.rs
wasmer-os/src/wasi.rs
#![allow(unused, dead_code)] use super::reactor::Reactor; use chrono::prelude::*; use core::sync::atomic::{AtomicUsize, Ordering}; use once_cell::sync::Lazy; use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; use std::sync::RwLock as StdRwLock; use tokio::sync::watch; use tokio::sync::RwLock; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; /* use crate::wasmer_wasi::{ iterate_poll_events, types::*, PollEvent, PollEventBuilder, PollEventIter, PollEventSet, WasiEnv, WasiProxy, WasmPtr, }; */ use crate::wasmer_vfs::{FsError, VirtualFile}; use crate::wasmer_wasi::{types::*, WasiEnv}; use super::fd::*; #[derive(Debug)] pub struct WasiTerm { terminate: watch::Receiver<Option<i32>>, reactor: Arc<RwLock<Reactor>>, } impl WasiTerm { pub fn new( reactor: &Arc<RwLock<Reactor>>, terminate: watch::Receiver<Option<i32>>, ) -> WasiTerm { WasiTerm { terminate, reactor: reactor.clone(), } } pub fn idle(&self) { ::std::thread::yield_now(); } } /* impl WasiProxy for WasiTerm { fn args_get( &self, env: &WasiEnv, argv: WasmPtr<WasmPtr<u8>, Array>, argv_buf: WasmPtr<u8>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::args_get(env, argv, argv_buf) } fn args_sizes_get( &self, env: &WasiEnv, argc: WasmPtr<u32>, argv_buf_size: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::args_sizes_get(env, argc, argv_buf_size) } fn clock_res_get( &self, env: &WasiEnv, clock_id: __wasi_clockid_t, ) -> Result<__wasi_timestamp_t, __wasi_errno_t> { self.tick(env); wasmer_wasi::native::clock_res_get(env, clock_id) } fn clock_time_get( &self, env: &WasiEnv, _clock_id: __wasi_clockid_t, _precision: __wasi_timestamp_t, ) -> Result<__wasi_timestamp_t, __wasi_errno_t> { self.tick(env); let time: DateTime<Local> = Local::now(); Ok(time.timestamp_nanos() as __wasi_timestamp_t) } fn environ_get( &self, env: &WasiEnv, environ: WasmPtr<WasmPtr<u8>, Array>, environ_buf: WasmPtr<u8>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::environ_get(env, environ, environ_buf) } fn environ_sizes_get( &self, env: &WasiEnv, environ_count: WasmPtr<u32>, environ_buf_size: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::environ_sizes_get(env, environ_count, environ_buf_size) } fn fd_advise( &self, env: &WasiEnv, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, advice: __wasi_advice_t, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_advise(env, fd, offset, len, advice) } fn fd_allocate( &self, env: &WasiEnv, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_allocate(env, fd, offset, len) } fn fd_close(&self, env: &WasiEnv, fd: __wasi_fd_t) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_close(env, fd) } fn fd_datasync(&self, env: &WasiEnv, fd: __wasi_fd_t) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_datasync(env, fd) } fn fd_fdstat_get( &self, env: &WasiEnv, fd: __wasi_fd_t, buf_ptr: WasmPtr<__wasi_fdstat_t>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_fdstat_get(env, fd, buf_ptr) } fn fd_fdstat_set_flags( &self, env: &WasiEnv, fd: __wasi_fd_t, flags: __wasi_fdflags_t, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_fdstat_set_flags(env, fd, flags) } fn fd_fdstat_set_rights( &self, env: &WasiEnv, fd: __wasi_fd_t, fs_rights_base: __wasi_rights_t, fs_rights_inheriting: __wasi_rights_t, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_fdstat_set_rights(env, fd, fs_rights_base, fs_rights_inheriting) } fn fd_filestat_get( &self, env: &WasiEnv, fd: __wasi_fd_t, buf: WasmPtr<__wasi_filestat_t>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_filestat_get(env, fd, buf) } fn fd_filestat_set_size( &self, env: &WasiEnv, fd: __wasi_fd_t, st_size: __wasi_filesize_t, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_filestat_set_size(env, fd, st_size) } fn fd_filestat_set_times( &self, env: &WasiEnv, fd: __wasi_fd_t, st_atim: __wasi_timestamp_t, st_mtim: __wasi_timestamp_t, fst_flags: __wasi_fstflags_t, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_filestat_set_times(env, fd, st_atim, st_mtim, fst_flags) } fn fd_pread( &self, env: &WasiEnv, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t>, iovs_len: u32, offset: __wasi_filesize_t, nread: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_pread(env, fd, iovs, iovs_len, offset, nread) } fn fd_prestat_get( &self, env: &WasiEnv, fd: __wasi_fd_t, buf: WasmPtr<__wasi_prestat_t>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_prestat_get(env, fd, buf) } fn fd_prestat_dir_name( &self, env: &WasiEnv, fd: __wasi_fd_t, path: WasmPtr<u8>, path_len: u32, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_prestat_dir_name(env, fd, path, path_len) } fn fd_pwrite( &self, env: &WasiEnv, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, Array>, iovs_len: u32, offset: __wasi_filesize_t, nwritten: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_pwrite(env, fd, iovs, iovs_len, offset, nwritten) } fn fd_read( &self, env: &WasiEnv, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, Array>, iovs_len: u32, nread: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); let ret = wasmer_wasi::native::fd_read(env, fd, iovs, iovs_len, nread); ret } fn fd_readdir( &self, env: &WasiEnv, fd: __wasi_fd_t, buf: WasmPtr<u8>, buf_len: u32, cookie: __wasi_dircookie_t, bufused: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_readdir(env, fd, buf, buf_len, cookie, bufused) } fn fd_renumber(&self, env: &WasiEnv, from: __wasi_fd_t, to: __wasi_fd_t) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_renumber(env, from, to) } fn fd_seek( &self, env: &WasiEnv, fd: __wasi_fd_t, offset: __wasi_filedelta_t, whence: __wasi_whence_t, newoffset: WasmPtr<__wasi_filesize_t>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_seek(env, fd, offset, whence, newoffset) } fn fd_sync(&self, env: &WasiEnv, fd: __wasi_fd_t) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_sync(env, fd) } fn fd_tell( &self, env: &WasiEnv, fd: __wasi_fd_t, offset: WasmPtr<__wasi_filesize_t>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_tell(env, fd, offset) } fn fd_write( &self, env: &WasiEnv, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, Array>, iovs_len: u32, nwritten: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_write(env, fd, iovs, iovs_len, nwritten) } fn path_create_directory( &self, env: &WasiEnv, fd: __wasi_fd_t, path: WasmPtr<u8>, path_len: u32, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_create_directory(env, fd, path, path_len) } fn path_filestat_get( &self, env: &WasiEnv, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr<u8>, path_len: u32, buf: WasmPtr<__wasi_filestat_t>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_filestat_get(env, fd, flags, path, path_len, buf) } fn path_filestat_set_times( &self, env: &WasiEnv, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr<u8>, path_len: u32, st_atim: __wasi_timestamp_t, st_mtim: __wasi_timestamp_t, fst_flags: __wasi_fstflags_t, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_filestat_set_times( env, fd, flags, path, path_len, st_atim, st_mtim, fst_flags, ) } fn path_link( &self, env: &WasiEnv, old_fd: __wasi_fd_t, old_flags: __wasi_lookupflags_t, old_path: WasmPtr<u8>, old_path_len: u32, new_fd: __wasi_fd_t, new_path: WasmPtr<u8>, new_path_len: u32, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_link( env, old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len, ) } fn path_open( &self, env: &WasiEnv, dirfd: __wasi_fd_t, dirflags: __wasi_lookupflags_t, path: WasmPtr<u8>, path_len: u32, o_flags: __wasi_oflags_t, fs_rights_base: __wasi_rights_t, fs_rights_inheriting: __wasi_rights_t, fs_flags: __wasi_fdflags_t, fd: WasmPtr<__wasi_fd_t>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_open( env, dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd, ) } fn path_readlink( &self, env: &WasiEnv, dir_fd: __wasi_fd_t, path: WasmPtr<u8>, path_len: u32, buf: WasmPtr<u8>, buf_len: u32, buf_used: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_readlink(env, dir_fd, path, path_len, buf, buf_len, buf_used) } fn path_remove_directory( &self, env: &WasiEnv, fd: __wasi_fd_t, path: WasmPtr<u8>, path_len: u32, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_remove_directory(env, fd, path, path_len) } fn path_rename( &self, env: &WasiEnv, old_fd: __wasi_fd_t, old_path: WasmPtr<u8>, old_path_len: u32, new_fd: __wasi_fd_t, new_path: WasmPtr<u8>, new_path_len: u32, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_rename( env, old_fd, old_path, old_path_len, new_fd, new_path, new_path_len, ) } fn path_symlink( &self, env: &WasiEnv, old_path: WasmPtr<u8>, old_path_len: u32, fd: __wasi_fd_t, new_path: WasmPtr<u8>, new_path_len: u32, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_symlink(env, old_path, old_path_len, fd, new_path, new_path_len) } fn path_unlink_file( &self, env: &WasiEnv, fd: __wasi_fd_t, path: WasmPtr<u8>, path_len: u32, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::path_unlink_file(env, fd, path, path_len) } fn poll_oneoff( &self, env: &WasiEnv, in_: WasmPtr<__wasi_subscription_t>, out_: WasmPtr<__wasi_event_t>, nsubscriptions: u32, nevents: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::poll_oneoff_impl(env, in_, out_, nsubscriptions, nevents) } fn poll( &self, env: &WasiEnv, files: &[&dyn VirtualFile + Send + Sync], events: &[PollEventSet], seen_events: &mut [PollEventSet], ) -> Result<u32, FsError> { self.tick(env); /* let mut fds = { let reactor = self.spin_read_lock(env); let fds = files .iter() .enumerate() .filter_map(|(_i, s)| s.get_fd().map(|rfd| rfd.fd())) .map(|fd| reactor.fd(fd.into())) .collect::<Vec<_>>(); if !(fds.len() == files.len() && files.len() == events.len() && events.len() == seen_events.len()) { return Err(FsError::InvalidInput); } fds }; let mut ret = 0; for n in 0..fds.len() { let mut builder = PollEventBuilder::new(); let poll_result = fds[n].poll(); for event in iterate_poll_events(events[n]) { match event { PollEvent::PollIn if poll_result.can_read => { builder = builder.add(PollEvent::PollIn); } PollEvent::PollOut if poll_result.can_write => { builder = builder.add(PollEvent::PollOut); } PollEvent::PollHangUp if poll_result.is_closed => { builder = builder.add(PollEvent::PollHangUp); } PollEvent::PollInvalid if poll_result.is_closed => { builder = builder.add(PollEvent::PollInvalid); } PollEvent::PollError if poll_result.is_closed => { builder = builder.add(PollEvent::PollError); } _ => {} } } let revents = builder.build(); if revents != 0 { ret += 1; } seen_events[n] = revents; } Ok(ret) */ wasmer_wasi::native::poll(env, files, events, seen_events) } fn proc_exit(&self, env: &WasiEnv, code: __wasi_exitcode_t) { self.tick(env); wasmer_wasi::native::proc_exit(env, code) } fn proc_raise(&self, env: &WasiEnv, sig: __wasi_signal_t) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::proc_raise(env, sig) } fn random_get(&self, env: &WasiEnv, buf: u32, buf_len: u32) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::random_get(env, buf, buf_len) } fn sched_yield(&self, env: &WasiEnv) -> __wasi_errno_t { self.tick(env); self.idle(); __WASI_ESUCCESS } fn sock_recv( &self, env: &WasiEnv, sock: __wasi_fd_t, ri_data: WasmPtr<__wasi_iovec_t, Array>, ri_data_len: u32, _ri_flags: __wasi_riflags_t, ro_datalen: WasmPtr<u32>, _ro_flags: WasmPtr<__wasi_roflags_t>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_read(env, sock, ri_data, ri_data_len, ro_datalen) } fn sock_send( &self, env: &WasiEnv, sock: __wasi_fd_t, si_data: WasmPtr<__wasi_ciovec_t>, si_data_len: u32, _si_flags: __wasi_siflags_t, so_datalen: WasmPtr<u32>, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_write(env, sock, si_data, si_data_len, so_datalen) } fn sock_shutdown( &self, env: &WasiEnv, sock: __wasi_fd_t, _how: __wasi_sdflags_t, ) -> __wasi_errno_t { self.tick(env); wasmer_wasi::native::fd_close(env, sock) } } */
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/environment.rs
wasmer-os/src/environment.rs
#![allow(dead_code)] #![allow(unused_variables)] use std::collections::hash_map::Entry; use std::collections::HashMap; use std::env; #[derive(Debug, Clone, Default)] pub struct Val { pub var_eq: Option<String>, pub export: bool, pub readonly: bool, } #[derive(Debug, Clone, Default)] pub struct Environment { vars: HashMap<String, Val>, } impl Environment { pub fn set_var(&mut self, key: &str, val: String) { self.set_vareq_with_key(key.to_string(), format!("{}={}", key, val)); } pub fn set_vareq(&mut self, var_eq: String) { let key: String = self.parse_key(&var_eq); self.set_vareq_with_key(key, var_eq); } pub fn set_vareq_with_key(&mut self, key: String, var_eq: String) { match self.vars.entry(key) { Entry::Occupied(mut o) => { let v = o.get_mut(); if !v.readonly { v.var_eq = Some(var_eq); } } Entry::Vacant(o) => { o.insert(Val { var_eq: Some(var_eq), ..Default::default() }); } } } pub fn unset(&mut self, key: &str) { if let Entry::Occupied(o) = self.vars.entry(key.to_string()) { if !o.get().readonly { o.remove(); } } } pub fn export(&mut self, key: &str) { self.vars .entry(key.to_string()) .or_insert(Val { ..Default::default() }) .export = true; } pub fn readonly(&mut self, key: &str) { self.vars .entry(key.to_string()) .or_insert(Val { ..Default::default() }) .readonly = true; } pub fn get(&self, key: &str) -> Option<String> { let entry = self.vars.get(key)?; return if let Some(var_eq) = &entry.var_eq { let mut split = var_eq.as_bytes().split(|b| *b == b'='); let _entry_key = split.next().unwrap(); if let Some(value) = split.next() { Some(String::from_utf8_lossy(value).to_string()) } else { Some(String::new()) } } else { None }; } pub fn into_exported(self) -> Vec<String> { self.vars .into_iter() .filter(|(_, v)| v.export && v.var_eq.is_some()) .map(|(_, v)| v.var_eq.unwrap()) .collect() } pub fn iter(&self) -> impl Iterator<Item = (&String, &Val)> { self.vars.iter() } pub fn parse_key(&self, var_eq: &String) -> String { let mut split = var_eq.as_bytes().split(|b| *b == b'='); String::from_utf8_lossy(split.next().unwrap()).to_string() } } pub fn empty() -> Environment { Environment { vars: HashMap::new(), } } pub fn from_system() -> Environment { let mut e = empty(); env::vars().for_each(|(k, v)| { e.set_var(&k, v); e.export(&k); }); e }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/stdio.rs
wasmer-os/src/stdio.rs
#![allow(unused_imports)] #![allow(dead_code)] use std::fmt; use std::future::Future; use tokio::io::{self}; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace}; use crate::fs::UnionFileSystem; use super::common::*; use super::fd::*; use super::state::*; use super::tty::*; #[derive(Debug, Clone)] pub struct Stdio { pub stdin: Fd, pub stdout: Fd, pub stderr: Fd, pub log: Fd, pub tty: Tty, } impl Stdio { pub fn println(&self, data: String) -> impl Future<Output = io::Result<usize>> { let mut stdout = self.stdout.clone(); async move { stdout.write(data.as_bytes()).await } } pub fn eprintln(&self, data: String) -> impl Future<Output = io::Result<usize>> { let mut stderr = self.stderr.clone(); async move { stderr.write(data.as_bytes()).await } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/poll.rs
wasmer-os/src/poll.rs
#![allow(unused_imports)] #![allow(dead_code)] use std::sync::Arc; use std::sync::Mutex; use tokio::sync::mpsc; use tokio::sync::Mutex as AsyncMutex; use tokio::sync::RwLock; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use super::err::*; use super::fd::*; use super::pipe::*; use super::reactor::*; #[derive(Debug)] pub struct PollResult { pub can_read: bool, pub can_write: bool, pub is_closed: bool, pub bytes_available_read: usize, } pub fn poll_fd( rx: Option<&Arc<AsyncMutex<ReactorPipeReceiver>>>, tx: Option<&mpsc::Sender<FdMsg>>, ) -> PollResult { let mut bytes_available_read = 0usize; let can_write = if let Some(fd) = tx { match fd.try_reserve() { Ok(_permit) => { true } Err(mpsc::error::TrySendError::Full(())) => { false } Err(mpsc::error::TrySendError::Closed(())) => { return PollResult { can_read: false, can_write: false, is_closed: true, bytes_available_read: 0 }; } } } else { false }; let can_read = if let Some(fd) = rx { match fd.try_lock() { Ok(mut fd) => { if fd.buffer.is_empty() == false { bytes_available_read += fd.buffer.len(); true } else { match fd.rx.try_recv() { Ok(msg) => { match msg { FdMsg::Data { data, flag } => { fd.cur_flag = flag; fd.buffer.extend_from_slice(&data[..]); if fd.mode == ReceiverMode::Message(false) { fd.mode = ReceiverMode::Message(true); } bytes_available_read += fd.buffer.len(); true } FdMsg::Flush { tx } => { let _ = tx.try_send(()); false } } } Err(mpsc::error::TryRecvError::Empty) => { false } Err(mpsc::error::TryRecvError::Disconnected) => { return PollResult { can_read: false, can_write: false, is_closed: true, bytes_available_read: 0 }; } } } }, Err(_) => { false } } } else { false }; let ret = PollResult { can_read, can_write, is_closed: rx.is_some() || tx.is_some(), bytes_available_read, }; ret }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/state.rs
wasmer-os/src/state.rs
#![allow(unused_imports)] #![allow(dead_code)] use bytes::{Buf, BytesMut}; use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::AtomicBool; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::sync::watch; use tokio::sync::Mutex as AsyncMutex; use crate::common::*; use crate::fd::*; use super::environment::Environment; use super::eval::Process; use super::eval::*; use super::fd::*; use super::fs::*; use super::poll::*; use super::reactor::*; use super::tty::*; pub struct ConsoleState { pub path: String, pub user: String, pub env: Environment, pub last_return: u32, pub unfinished_line: Arc<AtomicBool>, pub rootfs: UnionFileSystem, } impl ConsoleState { pub fn new(root: UnionFileSystem, unfinished_line: Arc<AtomicBool>) -> ConsoleState { ConsoleState { path: "/".to_string(), user: "wasmer.sh".to_string(), env: Environment::default(), last_return: 0, unfinished_line, rootfs: root, } } pub fn clear_mounts(&mut self) { self.rootfs.clear(); } pub fn compute_prompt(&self, need_more_text: bool, color: bool) -> String { let prompt_symbol = { if need_more_text { ">".to_string() } else { "$".to_string() } }; if color { format!( "{}{}{}:{}{}{}{} {}", Tty::COL_GREEN, self.user, Tty::COL_WHITE, Tty::COL_BLUE, self.path, Tty::COL_WHITE, prompt_symbol, Tty::COL_RESET ) } else { format!("{}:{}{} ", self.user, self.path, prompt_symbol) } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-os/src/wizard_executor.rs
wasmer-os/src/wizard_executor.rs
use std::sync::Arc; use crate::api::ConsoleAbi; use crate::api::WizardAbi; use crate::api::WizardAction; use crate::api::WizardPrompt; pub struct WizardExecutor { wizard: Box<dyn WizardAbi + Send + Sync + 'static>, prompts: Vec<WizardPrompt>, responses: Vec<String>, } pub enum WizardExecutorAction { More { echo: bool }, Done, } impl WizardExecutor { pub fn new(wizard: Box<dyn WizardAbi + Send + Sync + 'static>) -> Self { Self { wizard, prompts: Vec::new(), responses: Vec::new(), } } pub fn token(&self) -> Option<String> { self.wizard.token() } pub async fn feed( &mut self, abi: &Arc<dyn ConsoleAbi>, data: Option<String>, ) -> WizardExecutorAction { if let Some(data) = data { self.responses.push(data); abi.stdout("\r\n".to_string().into_bytes()).await; } if let Some(prompt) = self.prompts.pop() { abi.stdout(text_to_bytes(prompt.prompt)).await; WizardExecutorAction::More { echo: prompt.echo } } else { let responses = self.responses.drain(..).collect(); match self.wizard.process(responses).await { WizardAction::Challenge { name, instructions, mut prompts, } => { if name.len() > 0 { abi.stdout(text_to_bytes(name)).await; abi.stdout("\r\n".to_string().into_bytes()).await; } if instructions.len() > 0 { abi.stdout(text_to_bytes(instructions)).await; abi.stdout("\r\n".to_string().into_bytes()).await; } prompts.reverse(); self.prompts.append(&mut prompts); if let Some(prompt) = self.prompts.pop() { abi.stdout(text_to_bytes(prompt.prompt)).await; WizardExecutorAction::More { echo: prompt.echo } } else { WizardExecutorAction::More { echo: false } } } WizardAction::Shell => WizardExecutorAction::Done, WizardAction::Terminate { with_message } => { if let Some(msg) = with_message { abi.stdout(text_to_bytes(msg)).await; abi.stdout("\r\n".to_string().into_bytes()).await; } abi.exit().await; WizardExecutorAction::More { echo: false } } } } } } fn text_to_bytes(txt: String) -> Vec<u8> { txt.replace("\\", "\\\\").replace("\n", "\r\n").into_bytes() }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false