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-auth/src/helper/builder.rs | wasmer-auth/src/helper/builder.rs | use std::ops::Deref;
use std::sync::Arc;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use ate::prelude::*;
use crate::cmd::gather_command;
use crate::cmd::main_session_prompt;
use crate::error::*;
use crate::helper::b64_to_session;
pub struct DioBuilder {
cfg_ate: ConfAte,
url_db: url::Url,
url_auth: url::Url,
registry: Option<Arc<Registry>>,
session: Box<dyn AteSession>,
group: Option<String>,
}
impl Default for DioBuilder {
fn default() -> DioBuilder {
DioBuilder {
cfg_ate: ConfAte::default(),
url_db: url::Url::parse("ws://wasmer.sh/db").unwrap(),
url_auth: url::Url::parse("ws://wasmer.sh/auth").unwrap(),
registry: None,
session: Box::new(AteSessionUser::default()),
group: None,
}
}
}
impl DioBuilder {
pub fn cfg<'a>(&'a mut self) -> &'a mut ConfAte {
&mut self.cfg_ate
}
pub fn with_cfg_ate(mut self, cfg: ConfAte) -> Self {
self.cfg_ate = cfg;
self
}
pub fn with_url_db(mut self, url: url::Url) -> Self {
self.url_db = url;
self
}
pub fn with_url_auth(mut self, url: url::Url) -> Self {
self.url_auth = url;
self.registry = None;
self
}
pub fn with_token_string(mut self, token: String) -> Self {
self.session = Box::new(b64_to_session(token));
self
}
pub async fn with_token_path(mut self, path: String) -> Result<Self, LoginError> {
let path = shellexpand::tilde(path.as_str()).to_string();
#[cfg(feature = "enable_full")]
let token = tokio::fs::read_to_string(path).await?;
#[cfg(not(feature = "enable_full"))]
let token = std::fs::read_to_string(path)?;
self.session = Box::new(b64_to_session(token));
Ok(self)
}
pub fn with_registry(mut self, registry: Registry) -> Self {
self.registry = Some(Arc::new(registry));
self
}
pub async fn get_registry(&mut self) -> Arc<Registry> {
if self.registry.is_none() {
self.registry = Some(Arc::new(Registry::new(&self.cfg_ate).await));
}
Arc::clone(self.registry.as_ref().unwrap())
}
pub fn with_session(mut self, session: Box<dyn AteSession>) -> Self {
self.session = session;
self
}
pub async fn with_session_prompt(mut self) -> Result<Self, LoginError> {
self.session = Box::new(main_session_prompt(self.url_auth.clone()).await?);
Ok(self)
}
pub async fn with_group(mut self, group: &str) -> Result<Self, GatherError> {
let registry = self.get_registry().await;
let session = gather_command(
®istry,
group.to_string(),
self.session.clone_inner(),
self.url_auth.clone(),
)
.await?;
self.session = Box::new(session);
self.group = Some(group.to_string());
Ok(self)
}
pub fn generate_key(&self, name: &str) -> String {
match &self.group {
Some(a) => format!("{}/{}", a, name),
None => {
let identity = self.session.identity();
let comps = identity.split("@").collect::<Vec<_>>();
if comps.len() >= 2 {
let user = comps[0];
let domain = comps[1];
format!("{}/{}/{}", domain, user, name)
} else {
name.to_string()
}
}
}
}
pub async fn build(&mut self, name: &str) -> Result<Arc<DioMut>, LoginError> {
let key = ChainKey::new(self.generate_key(name));
let registry = self.get_registry().await;
let chain = registry.open(&self.url_db, &key, true).await?;
Ok(chain.dio_mut(self.session.deref()).await)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/helper/conf.rs | wasmer-auth/src/helper/conf.rs | #[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use ::ate::prelude::*;
pub fn conf_auth() -> ConfAte {
let mut cfg_ate = ConfAte::default();
cfg_ate.configured_for(ConfiguredFor::BestSecurity);
cfg_ate.log_format.meta = SerializationFormat::Json;
cfg_ate.log_format.data = SerializationFormat::Json;
cfg_ate.record_type_name = true;
cfg_ate
}
pub fn conf_cmd() -> ConfAte {
let cfg_cmd = conf_auth();
cfg_cmd
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/helper/auth.rs | wasmer-auth/src/helper/auth.rs | #[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use std::io::Write;
#[cfg(unix)]
use std::env::temp_dir;
#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use ::ate::crypto::EncryptKey;
use ::ate::prelude::*;
use crate::model::*;
pub(crate) fn compute_user_auth(user: &User) -> AteSessionUser {
let mut session = AteSessionUser::default();
for auth in user.access.iter() {
session.user.add_read_key(&auth.read);
session.user.add_private_read_key(&auth.private_read);
session.user.add_write_key(&auth.write);
}
session.user.add_uid(user.uid);
session.identity = user.email.clone();
session.broker_read = Some(user.broker_read.clone());
session.broker_write = Some(user.broker_write.clone());
session
}
pub(crate) fn compute_sudo_auth(sudo: &Sudo, session: AteSessionUser) -> AteSessionSudo {
let mut role = AteGroupRole {
purpose: AteRolePurpose::Owner,
properties: Vec::new(),
};
for auth in sudo.access.iter() {
role.add_read_key(&auth.read);
role.add_private_read_key(&auth.private_read);
role.add_write_key(&auth.write);
}
role.add_read_key(&sudo.contract_read_key);
role.add_uid(sudo.uid);
AteSessionSudo {
inner: session,
sudo: role,
}
}
pub(crate) fn complete_group_auth(
group: &Group,
inner: AteSessionInner,
) -> Result<AteSessionGroup, LoadError> {
// Create the session that we will return to the call
let mut session = AteSessionGroup::new(inner, group.name.clone());
// Add the broker keys and contract read key
session.group.broker_read = Some(group.broker_read.clone());
session.group.broker_write = Some(group.broker_write.clone());
// Enter a recursive loop that will expand its authorizations of the roles until
// it expands no more or all the roles are gained.
let mut roles = group.roles.iter().collect::<Vec<_>>();
while roles.len() > 0 {
let start = roles.len();
let mut next = Vec::new();
// Process all the roles
let shared_keys = session
.read_keys(AteSessionKeyCategory::AllKeys)
.map(|a| a.clone())
.collect::<Vec<_>>();
let super_keys = session
.private_read_keys(AteSessionKeyCategory::AllKeys)
.map(|a| a.clone())
.collect::<Vec<_>>();
for role in roles.into_iter() {
// Attempt to gain access to the role using the access rights of the super session
let mut added = false;
for read_key in super_keys.iter() {
if let Some(a) = role.access.unwrap(&read_key)? {
// Add access rights to the session
let b = session.get_or_create_group_role(&role.purpose);
b.add_read_key(&a.read);
b.add_private_read_key(&a.private_read);
b.add_write_key(&a.write);
b.add_gid(group.gid);
added = true;
break;
}
}
if added == false {
for read_key in shared_keys.iter() {
if let Some(a) = role.access.unwrap_shared(&read_key)? {
// Add access rights to the session
let b = session.get_or_create_group_role(&role.purpose);
b.add_read_key(&a.read);
b.add_private_read_key(&a.private_read);
b.add_write_key(&a.write);
b.add_gid(group.gid);
added = true;
break;
}
}
}
// If we have no successfully gained access to the role then add
// it to the try again list.
if added == false {
next.push(role);
}
}
// If we made no more progress (no more access was granted) then its
// time to give up
if next.len() >= start {
break;
}
roles = next;
}
Ok(session)
}
pub async fn load_credentials(
registry: &Registry,
username: String,
read_key: EncryptKey,
_code: Option<String>,
auth: Url,
) -> Result<AteSessionUser, AteError> {
// Prepare for the load operation
let key = PrimaryKey::from(username.clone());
let mut session = AteSessionUser::new();
session.user.add_read_key(&read_key);
// Generate a chain key that matches this username on the authentication server
let chain_key = chain_key_4hex(username.as_str(), Some("redo"));
let chain = registry.open(&auth, &chain_key, true).await?;
// Load the user
let dio = chain.dio(&session).await;
let user = dio.load::<User>(&key).await?;
// Build a new session
let mut session = AteSessionUser::new();
for access in user.access.iter() {
session.user.add_read_key(&access.read);
session.user.add_write_key(&access.write);
}
Ok(session)
}
pub fn save_token(
token: String,
token_path: String,
) -> Result<(), AteError> {
// Remove any old paths
if let Ok(old) = std::fs::canonicalize(token_path.clone()) {
let _ = std::fs::remove_file(old);
}
let _ = std::fs::remove_file(token_path.clone());
// Create the folder structure
let path = std::path::Path::new(&token_path);
let _ = std::fs::create_dir_all(path.parent().unwrap().clone());
// Create a random file that will hold the token
#[cfg(unix)]
let save_path = random_file();
#[cfg(not(unix))]
let save_path = token_path;
{
// Create the folder structure
let path = std::path::Path::new(&save_path);
let _ = std::fs::create_dir_all(path.parent().unwrap().clone());
// Create the file
let mut file = std::fs::File::create(save_path.clone())?;
// Set the permissions so no one else can read it but the current user
#[cfg(unix)]
{
let mut perms = std::fs::metadata(save_path.clone())?.permissions();
perms.set_mode(0o600);
std::fs::set_permissions(save_path.clone(), perms)?;
}
// Write the token to it
file.write_all(token.as_bytes())?;
}
// Update the token path so that it points to this temporary token
#[cfg(unix)]
symlink(save_path, token_path)?;
Ok(())
}
#[cfg(unix)]
pub fn random_file() -> String {
let mut tmp = temp_dir();
let rnd = ate::prelude::PrimaryKey::default().as_hex_string();
let file_name = format!("{}", rnd);
tmp.push(file_name);
let tmp_str = tmp.into_os_string().into_string().unwrap();
let tmp_str = shellexpand::tilde(&tmp_str).to_string();
tmp_str
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/helper/mod.rs | wasmer-auth/src/helper/mod.rs | mod auth;
mod builder;
mod conf;
mod keys;
mod misc;
pub use auth::*;
pub use builder::*;
pub use conf::*;
pub use keys::*;
pub use misc::*;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/helper/keys.rs | wasmer-auth/src/helper/keys.rs | use serde::*;
use std::fs::File;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
pub fn try_load_key<T>(key_path: String) -> Option<T>
where
T: serde::de::DeserializeOwned,
{
let path = shellexpand::tilde(&key_path).to_string();
debug!("loading key: {}", path);
let path = std::path::Path::new(&path);
File::open(path)
.ok()
.map(|file| bincode::deserialize_from(&file).unwrap())
}
pub fn load_key<T>(key_path: String, postfix: &str) -> T
where
T: serde::de::DeserializeOwned,
{
let key_path = format!("{}{}", key_path, postfix).to_string();
let path = shellexpand::tilde(&key_path).to_string();
debug!("loading key: {}", path);
let path = std::path::Path::new(&path);
let file = File::open(path).expect(format!("failed to load key at {}", key_path).as_str());
bincode::deserialize_from(&file).unwrap()
}
pub fn save_key<T>(key_path: String, key: T, postfix: &str)
where
T: Serialize,
{
let key_path = format!("{}{}", key_path, postfix).to_string();
let path = shellexpand::tilde(&key_path).to_string();
debug!("saving key: {}", path);
let path = std::path::Path::new(&path);
let _ = std::fs::create_dir_all(path.parent().unwrap().clone());
let mut file = File::create(path).unwrap();
print!("Generating secret key at {}...", key_path);
bincode::serialize_into(&mut file, &key).unwrap();
println!("Done");
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/sudo.rs | wasmer-auth/src/request/sudo.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use std::time::Duration;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SudoRequest {
pub session: AteSessionUser,
pub authenticator_code: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SudoResponse {
pub authority: AteSessionSudo,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum SudoFailed {
UserNotFound(String),
MissingToken,
WrongCode,
AccountLocked(Duration),
Unverified(String),
NoMasterKey,
InternalError(u16),
}
impl<E> From<E> for SudoFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
SudoFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/create_user.rs | wasmer-auth/src/request/create_user.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CreateUserRequest {
pub auth: String,
pub email: String,
pub secret: EncryptKey,
pub accepted_terms: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CreateUserResponse {
pub key: PrimaryKey,
pub qr_code: String,
pub qr_secret: String,
pub recovery_code: String,
pub authority: AteSessionUser,
pub message_of_the_day: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum CreateUserFailed {
AlreadyExists(String),
InvalidEmail,
NoMoreRoom,
NoMasterKey,
TermsAndConditions(String),
InternalError(u16),
}
impl<E> From<E> for CreateUserFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
CreateUserFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/login.rs | wasmer-auth/src/request/login.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use std::time::Duration;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LoginRequest {
pub email: String,
pub secret: EncryptKey,
pub verification_code: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LoginResponse {
pub user_key: PrimaryKey,
pub nominal_read: ate::crypto::AteHash,
pub nominal_write: PublicSignKey,
pub sudo_read: ate::crypto::AteHash,
pub sudo_write: PublicSignKey,
pub authority: AteSessionUser,
pub message_of_the_day: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum LoginFailed {
UserNotFound(String),
WrongPassword,
AccountLocked(Duration),
Unverified(String),
NoMasterKey,
InternalError(u16),
}
impl<E> From<E> for LoginFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
LoginFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/group_details.rs | wasmer-auth/src/request/group_details.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupDetailsRequest {
pub group: String,
pub session: Option<AteSessionGroup>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupDetailsRoleResponse {
pub purpose: AteRolePurpose,
pub name: String,
pub read: AteHash,
pub private_read: PublicEncryptKey,
pub write: PublicSignKey,
pub hidden: bool,
pub members: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupDetailsResponse {
pub key: PrimaryKey,
pub name: String,
pub roles: Vec<GroupDetailsRoleResponse>,
pub gid: u32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum GroupDetailsFailed {
GroupNotFound,
NoMasterKey,
NoAccess,
InternalError(u16),
}
impl<E> From<E> for GroupDetailsFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
GroupDetailsFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/mod.rs | wasmer-auth/src/request/mod.rs | mod create_group;
mod create_user;
mod gather;
mod group_details;
mod group_remove;
mod group_user_add;
mod group_user_remove;
mod login;
mod query;
mod reset;
mod sudo;
pub use create_group::*;
pub use create_user::*;
pub use gather::*;
pub use group_details::*;
pub use group_remove::*;
pub use group_user_add::*;
pub use group_user_remove::*;
pub use login::*;
pub use query::*;
pub use reset::*;
pub use sudo::*;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/create_group.rs | wasmer-auth/src/request/create_group.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CreateGroupRequest {
pub group: String,
pub identity: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CreateGroupResponse {
pub key: PrimaryKey,
pub session: AteSessionGroup,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum CreateGroupFailed {
AlreadyExists(String),
NoMoreRoom,
NoMasterKey,
InvalidGroupName(String),
OperatorNotFound,
OperatorBanned,
AccountSuspended,
ValidationError(String),
InternalError(u16),
}
impl<E> From<E> for CreateGroupFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
CreateGroupFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/group_user_add.rs | wasmer-auth/src/request/group_user_add.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupUserAddRequest {
pub group: String,
pub session: AteSessionGroup,
pub who_key: PublicEncryptKey,
pub who_name: String,
pub purpose: AteRolePurpose,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupUserAddResponse {
pub key: PrimaryKey,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum GroupUserAddFailed {
InvalidPurpose,
GroupNotFound,
NoMasterKey,
NoAccess,
UnknownIdentity,
InternalError(u16),
}
impl<E> From<E> for GroupUserAddFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
GroupUserAddFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/query.rs | wasmer-auth/src/request/query.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use crate::model::Advert;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct QueryRequest {
pub identity: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct QueryResponse {
pub advert: Advert,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum QueryFailed {
NotFound,
Banned,
Suspended,
InternalError(u16),
}
impl<E> From<E> for QueryFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
QueryFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/gather.rs | wasmer-auth/src/request/gather.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GatherRequest {
pub session: AteSessionInner,
pub group: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GatherResponse {
pub group_name: String,
pub gid: u32,
pub group_key: PrimaryKey,
pub authority: AteSessionGroup,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum GatherFailed {
GroupNotFound(String),
NoAccess,
NoMasterKey,
InternalError(u16),
}
impl<E> From<E> for GatherFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
GatherFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/group_remove.rs | wasmer-auth/src/request/group_remove.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupRemoveRequest {
pub group: String,
pub session: AteSessionGroup,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupRemoveResponse {
pub key: PrimaryKey,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum GroupRemoveFailed {
GroupNotFound,
NoMasterKey,
NoAccess,
InternalError(u16),
}
impl<E> From<E> for GroupRemoveFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
GroupRemoveFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/reset.rs | wasmer-auth/src/request/reset.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ResetRequest {
pub auth: String,
pub email: String,
pub new_secret: EncryptKey,
pub recovery_key: EncryptKey,
pub sudo_code: String,
pub sudo_code_2: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ResetResponse {
pub key: PrimaryKey,
pub qr_code: String,
pub qr_secret: String,
pub authority: AteSessionUser,
pub message_of_the_day: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ResetFailed {
InvalidEmail(String),
InvalidRecoveryCode,
InvalidAuthenticatorCode,
RecoveryImpossible,
NoMasterKey,
InternalError(u16),
}
impl<E> From<E> for ResetFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
ResetFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/request/group_user_remove.rs | wasmer-auth/src/request/group_user_remove.rs | #![allow(unused_imports)]
use ate::prelude::*;
use serde::*;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupUserRemoveRequest {
pub group: String,
pub session: AteSessionGroup,
pub who: AteHash,
pub purpose: AteRolePurpose,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupUserRemoveResponse {
pub key: PrimaryKey,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum GroupUserRemoveFailed {
GroupNotFound,
RoleNotFound,
NothingToRemove,
NoMasterKey,
NoAccess,
InternalError(u16),
}
impl<E> From<E> for GroupUserRemoveFailed
where
E: std::error::Error + Sized,
{
fn from(err: E) -> Self {
GroupUserRemoveFailed::InternalError(ate::utils::obscure_error(err))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/examples/client.rs | wasmer-auth/examples/client.rs | use wasmer_auth::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
struct MyData {
pi: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
ate::log_init(0, false);
let dio = DioBuilder::default()
.with_session_prompt()
.await?
.build("mychain")
.await?;
dio.store(MyData {
pi: "3.14159265359".to_string(),
})?;
dio.commit().await?;
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/lib.rs | comms/src/lib.rs | mod client;
mod hello;
#[cfg(feature = "quantum")]
mod key_exchange;
mod protocol;
mod certificate_validation;
#[cfg(feature = "dns")]
#[cfg(not(target_family = "wasm"))]
mod dns;
mod security;
pub use protocol::MessageProtocolVersion;
pub use protocol::MessageProtocolApi;
pub use protocol::StreamReadable;
pub use protocol::StreamWritable;
pub use protocol::AsyncStream;
pub use hello::HelloMetadata;
pub use hello::mesh_hello_exchange_sender;
pub use hello::mesh_hello_exchange_receiver;
#[cfg(feature = "quantum")]
pub use key_exchange::mesh_key_exchange_sender;
#[cfg(feature = "quantum")]
pub use key_exchange::mesh_key_exchange_receiver;
pub use certificate_validation::CertificateValidation;
pub use certificate_validation::add_global_certificate;
pub use certificate_validation::get_global_certificates;
pub use protocol::StreamRx;
pub use protocol::StreamTx;
pub use security::StreamSecurity;
pub use client::StreamClient;
#[cfg(feature = "dns")]
#[cfg(not(target_family = "wasm"))]
pub use dns::Dns;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/security.rs | comms/src/security.rs | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum StreamSecurity {
Unencrypted,
AnyEncryption,
ClassicEncryption,
QuantumEncryption,
DoubleEncryption,
}
impl Default
for StreamSecurity {
fn default() -> Self {
StreamSecurity::AnyEncryption
}
}
impl StreamSecurity {
pub fn classic_encryption(&self) -> bool {
match self {
StreamSecurity::ClassicEncryption |
StreamSecurity::DoubleEncryption => {
true
},
_ => false
}
}
pub fn quantum_encryption(&self, https: bool) -> bool {
match self {
StreamSecurity::AnyEncryption => {
https == false
}
StreamSecurity::QuantumEncryption |
StreamSecurity::DoubleEncryption => {
true
},
_ => false
}
}
}
impl std::str::FromStr
for StreamSecurity
{
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(
match s {
"none" | "" | "no" | "unencrypted" => StreamSecurity::Unencrypted,
"any" | "anyencryption" | "encrypted" | "any_encryption" => {
StreamSecurity::AnyEncryption
},
"classic" => StreamSecurity::ClassicEncryption,
"quantum" => StreamSecurity::QuantumEncryption,
"double" => StreamSecurity::DoubleEncryption,
a => {
return Err(format!("stream security type ({}) is not valid - try: 'none', 'any', 'classic', 'quantum' or 'double'", a))
}
}
)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/client.rs | comms/src/client.rs | use std::io;
#[allow(unused_imports)]
use std::ops::DerefMut;
use wasmer_bus_ws::prelude::*;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
use ate_crypto::KeySize;
use ate_crypto::NodeId;
use crate::HelloMetadata;
use super::protocol::StreamRx;
use super::protocol::StreamTx;
use super::CertificateValidation;
use super::certificate_validation::GLOBAL_CERTIFICATES;
pub struct StreamClient
{
rx: StreamRx,
tx: StreamTx,
hello: HelloMetadata,
}
pub use super::security::StreamSecurity;
impl StreamClient
{
pub async fn connect(connect_url: url::Url, path: &str, security: StreamSecurity, #[allow(unused)] dns_server: Option<String>, #[allow(unused)] dns_sec: bool) -> Result<Self, Box<dyn std::error::Error>>
{
let https = match connect_url.scheme() {
"https" => true,
"wss" => true,
_ => false,
};
let host = connect_url
.host()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "URL does not have a host component"))?;
let domain = match &host {
url::Host::Domain(a) => Some(*a),
url::Host::Ipv4(ip) if ip.is_loopback() => Some("localhost"),
url::Host::Ipv6(ip) if ip.is_loopback() => Some("localhost"),
_ => None
}
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "URL does not have a domain component"))?;
#[allow(unused_variables)]
let mut validation = {
let mut certs = Vec::new();
#[cfg(feature = "dns")]
#[cfg(not(target_family = "wasm"))]
{
let dns_server = dns_server.as_ref().map(|a| a.as_ref()).unwrap_or("8.8.8.8");
let mut dns = crate::Dns::connect(dns_server, dns_sec).await;
for cert in dns.dns_certs(domain).await {
certs.push(cert);
}
}
for cert in GLOBAL_CERTIFICATES.read().unwrap().iter() {
if certs.contains(cert) == false {
certs.push(cert.clone());
}
}
if certs.len() > 0 {
CertificateValidation::AllowedCertificates(certs)
} else if domain == "localhost" {
CertificateValidation::AllowAll
} else {
CertificateValidation::DenyAll
}
};
#[allow(unused_assignments)]
if domain == "localhost" || security.quantum_encryption(https) == false {
validation = CertificateValidation::AllowAll;
}
let socket = SocketBuilder::new(connect_url.clone())
.open()
.await?;
let (tx, rx) = socket.split();
let tx: Box<dyn AsyncWrite + Send + Sync + Unpin + 'static> = Box::new(tx);
let rx: Box<dyn AsyncRead + Send + Sync + Unpin + 'static> = Box::new(rx);
// We only encrypt if it actually has a certificate (otherwise
// a simple man-in-the-middle could intercept anyway)
let key_size = if security.quantum_encryption(https) == true {
Some(KeySize::Bit192)
} else {
None
};
// Say hello
let node_id = NodeId::generate_client_id();
let (mut proto, hello_metadata) = super::hello::mesh_hello_exchange_sender(
rx,
tx,
node_id,
path.to_string(),
domain.to_string(),
key_size,
)
.await?;
// If we are using wire encryption then exchange secrets
#[cfg(feature = "quantum")]
let ek = match hello_metadata.encryption {
Some(key_size) => Some(
super::key_exchange::mesh_key_exchange_sender(
proto.deref_mut(),
key_size,
validation,
)
.await?,
),
None => None,
};
#[cfg(not(feature = "quantum"))]
let ek = None;
// Create the rx and tx message streams
let (rx, tx) = proto.split(ek);
Ok(
Self {
rx,
tx,
hello: hello_metadata,
}
)
}
pub fn split(self) -> (StreamRx, StreamTx)
{
(
self.rx,
self.tx,
)
}
pub fn hello_metadata(&self) -> &HelloMetadata {
&self.hello
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/certificate_validation.rs | comms/src/certificate_validation.rs | use std::sync::RwLock;
use once_cell::sync::Lazy;
use ate_crypto::AteHash;
pub static GLOBAL_CERTIFICATES: Lazy<RwLock<Vec<AteHash>>> =
Lazy::new(|| RwLock::new(Vec::new()));
pub fn add_global_certificate(cert: &AteHash) {
GLOBAL_CERTIFICATES.write().unwrap().push(cert.clone());
}
pub fn get_global_certificates() -> Vec<AteHash> {
let mut ret = GLOBAL_CERTIFICATES.read().unwrap().clone();
ret.push(AteHash::from_hex_string("f0a961c31f83c758ff0b669cc61b0f76").unwrap());
ret
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum CertificateValidation {
DenyAll,
AllowAll,
AllowedCertificates(Vec<AteHash>),
}
impl CertificateValidation {
pub fn validate(&self, cert: &AteHash) -> bool {
match self {
CertificateValidation::DenyAll => false,
CertificateValidation::AllowAll => true,
CertificateValidation::AllowedCertificates(a) => a.contains(cert),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/hello.rs | comms/src/hello.rs | use std::io;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use ate_crypto::KeySize;
use ate_crypto::NodeId;
use ate_crypto::SerializationFormat;
use serde::{Deserialize, Serialize};
use super::protocol::MessageProtocolVersion;
use super::protocol::MessageProtocolApi;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HelloMetadata {
pub client_id: NodeId,
pub server_id: NodeId,
pub path: String,
pub encryption: Option<KeySize>,
pub wire_format: SerializationFormat,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct SenderHello {
pub id: NodeId,
pub path: String,
pub domain: String,
pub key_size: Option<KeySize>,
#[serde(default = "default_stream_protocol_version")]
pub version: MessageProtocolVersion,
}
fn default_stream_protocol_version() -> MessageProtocolVersion {
MessageProtocolVersion::V1
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct ReceiverHello {
pub id: NodeId,
pub encryption: Option<KeySize>,
pub wire_format: SerializationFormat,
#[serde(default = "default_stream_protocol_version")]
pub version: MessageProtocolVersion,
}
pub async fn mesh_hello_exchange_sender(
stream_rx: Box<dyn AsyncRead + Send + Sync + Unpin + 'static>,
stream_tx: Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>,
client_id: NodeId,
hello_path: String,
domain: String,
key_size: Option<KeySize>,
) -> tokio::io::Result<(
Box<dyn MessageProtocolApi + Send + Sync + 'static>,
HelloMetadata
)> {
// Send over the hello message and wait for a response
trace!("client sending hello");
let hello_client = SenderHello {
id: client_id,
path: hello_path.clone(),
domain,
key_size,
version: MessageProtocolVersion::default(),
};
let hello_client_bytes = serde_json::to_vec(&hello_client)?;
let mut proto = MessageProtocolVersion::V1.create(
Some(stream_rx),
Some(stream_tx)
);
proto
.write_with_fixed_16bit_header(&hello_client_bytes[..], false)
.await?;
// Read the hello message from the other side
let hello_server_bytes = proto.read_with_fixed_16bit_header().await?;
trace!("client received hello from server");
trace!("{}", String::from_utf8_lossy(&hello_server_bytes[..]));
let hello_server: ReceiverHello = serde_json::from_slice(&hello_server_bytes[..])?;
// Validate the encryption is strong enough
if let Some(needed_size) = &key_size {
match &hello_server.encryption {
None => {
return Err(io::Error::new(io::ErrorKind::ConnectionRefused, "the server encryption strength is too weak"));
}
Some(a) if *a < *needed_size => {
return Err(io::Error::new(io::ErrorKind::ConnectionRefused, "the server encryption strength is too weak"));
}
_ => {}
}
}
// Switch to the correct protocol version
let version = hello_server.version.min(hello_client.version);
proto = version.upgrade(proto);
// Upgrade the key_size if the server is bigger
trace!(
"client encryption={}",
match &hello_server.encryption {
Some(a) => a.as_str(),
None => "none",
}
);
trace!("client wire_format={}", hello_server.wire_format);
Ok((
proto,
HelloMetadata {
client_id,
server_id: hello_server.id,
path: hello_path,
encryption: hello_server.encryption,
wire_format: hello_server.wire_format,
}
))
}
pub async fn mesh_hello_exchange_receiver(
stream_rx: Box<dyn AsyncRead + Send + Sync + Unpin + 'static>,
stream_tx: Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>,
server_id: NodeId,
key_size: Option<KeySize>,
wire_format: SerializationFormat,
) -> tokio::io::Result<(
Box<dyn MessageProtocolApi + Send + Sync + 'static>,
HelloMetadata
)>
{
// Read the hello message from the other side
let mut proto = MessageProtocolVersion::V1.create(
Some(stream_rx),
Some(stream_tx)
);
let hello_client_bytes = proto
.read_with_fixed_16bit_header()
.await?;
trace!("server received hello from client");
//trace!("server received hello from client: {}", String::from_utf8_lossy(&hello_client_bytes[..]));
let hello_client: SenderHello = serde_json::from_slice(&hello_client_bytes[..])?;
// Upgrade the key_size if the client is bigger
let encryption = mesh_hello_upgrade_key(key_size, hello_client.key_size);
// Send over the hello message and wait for a response
trace!("server sending hello (wire_format={})", wire_format);
let hello_server = ReceiverHello {
id: server_id,
encryption,
wire_format,
version: MessageProtocolVersion::default(),
};
let hello_server_bytes = serde_json::to_vec(&hello_server)?;
proto
.write_with_fixed_16bit_header(&hello_server_bytes[..], false)
.await?;
// Switch to the correct protocol version
proto = hello_server.version
.min(hello_client.version)
.upgrade(proto);
Ok((
proto,
HelloMetadata {
client_id: hello_client.id,
server_id,
path: hello_client.path,
encryption,
wire_format,
}
))
}
fn mesh_hello_upgrade_key(key1: Option<KeySize>, key2: Option<KeySize>) -> Option<KeySize> {
// If both don't want encryption then who are we to argue about that?
if key1.is_none() && key2.is_none() {
return None;
}
// Wanting encryption takes priority over not wanting encyption
let key1 = match key1 {
Some(a) => a,
None => {
trace!("upgrading to {}bit shared secret", key2.unwrap());
return key2;
}
};
let key2 = match key2 {
Some(a) => a,
None => {
trace!("upgrading to {}bit shared secret", key1);
return Some(key1);
}
};
// Upgrade the key_size if the client is bigger
if key2 > key1 {
trace!("upgrading to {}bit shared secret", key2);
return Some(key2);
}
if key1 > key2 {
trace!("upgrading to {}bit shared secret", key2);
return Some(key1);
}
// They are identical
return Some(key1);
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/key_exchange.rs | comms/src/key_exchange.rs | use std::io;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use ate_crypto::KeySize;
use ate_crypto::PrivateEncryptKey;
use ate_crypto::EncryptKey;
use ate_crypto::InitializationVector;
use ate_crypto::PublicEncryptKey;
use super::protocol::MessageProtocolApi;
use super::CertificateValidation;
pub async fn mesh_key_exchange_sender(
proto: &mut (dyn MessageProtocolApi + Send + Sync + 'static),
key_size: KeySize,
validation: CertificateValidation,
) -> io::Result<EncryptKey> {
trace!("negotiating {}bit shared secret", key_size);
// Generate the encryption keys
let sk1 = PrivateEncryptKey::generate(key_size);
let pk1 = sk1.as_public_key();
let pk1_bytes = pk1.pk();
// Send our public key to the other side
trace!("client sending its public key (and strength)");
proto.write_with_fixed_32bit_header(pk1_bytes, false).await?;
// Receive one half of the secret that was just generated by the other side
let iv1_bytes = proto.read_with_fixed_32bit_header().await?;
let iv1 = InitializationVector::from(iv1_bytes);
let ek1 = match sk1.decapsulate(&iv1) {
Some(a) => a,
None => {
return Err(io::Error::new(io::ErrorKind::ConnectionRefused, "Failed to decapsulate the encryption key from the received initialization vector."));
}
};
trace!("client received the servers half of the shared secret");
// Receive the public key from the other side (which we will use in a sec)
let pk2_bytes = proto.read_with_fixed_32bit_header().await?;
trace!("client received the servers public key");
let pk2 = match PublicEncryptKey::from_bytes(pk2_bytes) {
Some(a) => a,
None => {
return Err(io::Error::new(io::ErrorKind::ConnectionRefused, "Failed to receive a public key from the other side."));
}
};
// Validate the public key against our validation rules
if validation.validate(&pk2.hash()) == false {
return Err(io::Error::new(io::ErrorKind::ConnectionRefused, "The server certificate failed the clients validation check."));
}
// Generate one half of the secret and send the IV so the other side can recreate it
let (iv2, ek2) = pk2.encapsulate();
proto.write_with_fixed_32bit_header(&iv2.bytes[..], false).await?;
trace!("client sending its half of the shared secret");
// Merge the two halfs to make one shared secret
trace!("client shared secret established");
Ok(EncryptKey::xor(&ek1, &ek2))
}
pub async fn mesh_key_exchange_receiver(
proto: &mut (dyn MessageProtocolApi + Send + Sync + 'static),
server_key: PrivateEncryptKey,
) -> io::Result<EncryptKey> {
trace!("negotiating {}bit shared secret", server_key.size());
// Receive the public key from the caller side (which we will use in a sec)
let pk1_bytes = proto.read_with_fixed_32bit_header().await?;
trace!("server received clients public key");
let pk1 = match PublicEncryptKey::from_bytes(pk1_bytes) {
Some(a) => a,
None => {
return Err(io::Error::new(io::ErrorKind::ConnectionRefused, "Failed to receive a valid public key from the sender."));
}
};
// Generate one half of the secret and send the IV so the other side can recreate it
let (iv1, ek1) = pk1.encapsulate();
trace!("server sending its half of the shared secret");
proto.write_with_fixed_32bit_header(&iv1.bytes[..], true).await?;
let sk2 = server_key;
let pk2 = sk2.as_public_key();
let pk2_bytes = pk2.pk();
// Send our public key to the other side
trace!("server sending its public key");
proto.write_with_fixed_32bit_header(pk2_bytes, false).await?;
// Receive one half of the secret that was just generated by the other side
let iv2_bytes = proto.read_with_fixed_32bit_header().await?;
let iv2 = InitializationVector::from(iv2_bytes);
let ek2 = match sk2.decapsulate(&iv2) {
Some(a) => a,
None => {
return Err(io::Error::new(io::ErrorKind::ConnectionRefused, "Failed to receive a public key from the other side."));
}
};
trace!("server received client half of the shared secret");
// Merge the two halfs to make one shared secret
trace!("server shared secret established");
Ok(EncryptKey::xor(&ek1, &ek2))
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/dns/client.rs | comms/src/dns/client.rs | use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use derivative::*;
use tokio::net::TcpStream as TokioTcpStream;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use tokio::sync::Mutex;
use {
trust_dns_client::client::*, trust_dns_client::op::DnsResponse, trust_dns_client::tcp::*,
trust_dns_proto::iocompat::AsyncIoTokioAsStd, trust_dns_proto::DnssecDnsHandle,
};
pub use {trust_dns_client::error::ClientError, trust_dns_client::rr::*};
#[derive(Derivative)]
#[derivative(Debug)]
pub enum DnsClient {
Dns {
dns_server: String,
#[derivative(Debug = "ignore")]
#[cfg(feature = "dns")]
client: Mutex<MemoizeClientHandle<AsyncClient>>,
},
DnsSec {
dns_server: String,
#[derivative(Debug = "ignore")]
#[cfg(feature = "dns")]
client: Mutex<DnssecDnsHandle<MemoizeClientHandle<AsyncClient>>>,
},
}
impl DnsClient {
pub async fn connect(dns_server: &str, dns_sec: bool) -> Self {
debug!("using DNS server: {}", dns_server);
let addr: SocketAddr = (dns_server.to_string(), 53)
.to_socket_addrs()
.unwrap()
.next()
.unwrap();
let (stream, sender) = TcpClientStream::<AsyncIoTokioAsStd<TokioTcpStream>>::new(addr);
let client = AsyncClient::new(stream, sender, None);
let (client, bg) = client.await.expect("client failed to connect");
tokio::task::spawn(bg);
let client = MemoizeClientHandle::new(client);
match dns_sec {
false => {
debug!("configured for DNSSec");
Self::Dns {
dns_server: dns_server.to_string(),
client: Mutex::new(client),
}
}
true => {
debug!("configured for plain DNS");
Self::DnsSec {
dns_server: dns_server.to_string(),
client: Mutex::new(DnssecDnsHandle::new(client.clone())),
}
}
}
}
pub async fn reconnect(&mut self) {
let (dns_server, dns_sec) = match self {
Self::Dns { dns_server, client: _ } => (dns_server.clone(), false),
Self::DnsSec { dns_server, client: _ } => (dns_server.clone(), true),
};
*self = Self::connect(dns_server.as_str(), dns_sec).await;
}
pub async fn query(
&mut self,
name: Name,
query_class: DNSClass,
query_type: RecordType,
) -> Result<DnsResponse, ClientError> {
let ret = {
match self {
Self::Dns { client: c, .. } => {
let mut c = c.lock().await;
c.query(name.clone(), query_class, query_type).await
}
Self::DnsSec { client: c, .. } => {
let mut c = c.lock().await;
c.query(name.clone(), query_class, query_type).await
}
}
};
match ret {
Ok(a) => Ok(a),
Err(_) => {
self.reconnect().await;
match self {
Self::Dns { client: c, .. } => {
let mut c = c.lock().await;
c.query(name, query_class, query_type).await
}
Self::DnsSec { client: c, .. } => {
let mut c = c.lock().await;
c.query(name, query_class, query_type).await
}
}
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/dns/mod.rs | comms/src/dns/mod.rs | mod query;
mod client;
pub use client::DnsClient as Dns; | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/dns/query.rs | comms/src/dns/query.rs | use std::net::IpAddr;
use std::str::FromStr;
use ate_crypto::AteHash;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
pub use trust_dns_client::rr::*;
impl super::Dns
{
pub async fn dns_certs(&mut self, name: &str) -> Vec<AteHash> {
match name.to_lowercase().as_str() {
"localhost" => {
return Vec::new();
}
_ => {}
};
if let Ok(_) = IpAddr::from_str(name) {
return Vec::new();
}
trace!("dns_query for {}", name);
let mut txts = Vec::new();
if let Some(response) = self
.query(Name::from_str(name).unwrap(), DNSClass::IN, RecordType::TXT)
.await
.ok()
{
for answer in response.answers() {
if let RData::TXT(ref txt) = *answer.rdata() {
txts.push(txt.to_string());
}
}
}
let prefix = "ate-cert-";
let mut certs = Vec::new();
for txt in txts {
let txt = txt.replace(" ", "");
if txt.trim().starts_with(prefix) {
let start = prefix.len();
let hash = &txt.trim()[start..];
if let Some(hash) = AteHash::from_hex_string(hash) {
trace!("found certificate({}) for {}", hash, name);
certs.push(hash);
}
}
}
trace!(
"dns_query for {} returned {} certificates",
name,
certs.len()
);
certs
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/protocol/stream.rs | comms/src/protocol/stream.rs | use std::io;
use ate_crypto::EncryptKey;
use async_trait::async_trait;
use super::MessageProtocolApi;
use super::StreamReadable;
use super::StreamWritable;
#[derive(Debug)]
pub struct StreamRx {
proto: Box<dyn MessageProtocolApi + Send + Sync + 'static>,
ek: Option<EncryptKey>,
}
impl StreamRx
{
pub(crate) fn new(proto: Box<dyn MessageProtocolApi + Send + Sync + 'static>, ek: Option<EncryptKey>) -> Self {
Self {
proto,
ek
}
}
pub async fn read(&mut self) -> io::Result<Vec<u8>>
{
let mut total_read = 0u64;
self.proto.read_buf_with_header(&self.ek, &mut total_read).await
}
}
#[async_trait]
impl StreamReadable
for StreamRx
{
async fn read(&mut self) -> io::Result<Vec<u8>>
{
StreamRx::read(&mut self).await
}
}
#[derive(Debug)]
pub struct StreamTx {
proto: Box<dyn MessageProtocolApi + Send + Sync + 'static>,
ek: Option<EncryptKey>,
}
impl StreamTx
{
pub(crate) fn new(proto: Box<dyn MessageProtocolApi + Send + Sync + 'static>, ek: Option<EncryptKey>) -> Self {
Self {
proto,
ek
}
}
pub async fn write(&mut self, data: &[u8]) -> io::Result<usize>
{
self.proto.send(&self.ek, data).await
.map(|a| a as usize)
}
pub async fn flush(&mut self) -> io::Result<()> {
self.proto.flush().await
}
pub async fn close(&mut self) -> io::Result<()> {
self.proto.send_close().await
}
pub fn wire_encryption(&self) -> Option<EncryptKey> {
self.ek.clone()
}
}
#[async_trait]
impl StreamWritable
for StreamTx
{
async fn write(&mut self, data: &[u8]) -> io::Result<usize> {
StreamTx::write(&mut self, data).await
}
async fn flush(&mut self) -> io::Result<()> {
StreamTx::flush(&mut self).await
}
async fn close(&mut self) -> io::Result<()> {
StreamTx::close(&mut self).await
}
fn wire_encryption(&self) -> Option<EncryptKey> {
StreamTx::wire_encryption(&self)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/protocol/version.rs | comms/src/protocol/version.rs | use serde::*;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use super::MessageProtocolApi;
/// Version of the stream protocol used to talk to Wasmer services
#[repr(u16)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum MessageProtocolVersion
{
V1 = 1,
V2 = 2,
V3 = 3,
}
impl Default
for MessageProtocolVersion
{
fn default() -> Self {
MessageProtocolVersion::V3
}
}
impl MessageProtocolVersion
{
pub fn min(&self, other: MessageProtocolVersion) -> MessageProtocolVersion {
let first = *self as u16;
let second = other as u16;
let min = first.min(second);
if first == min {
*self
} else {
other
}
}
pub fn upgrade(&self, mut proto: Box<dyn MessageProtocolApi + Send + Sync + 'static>) -> Box<dyn MessageProtocolApi + Send + Sync + 'static> {
let rx = proto.take_rx();
let tx = proto.take_tx();
self.create(rx, tx)
}
pub fn create(&self, rx: Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>>, tx: Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>>) -> Box<dyn MessageProtocolApi + Send + Sync + 'static>
{
match self {
MessageProtocolVersion::V1 => {
Box::new(super::v1::MessageProtocol::new(rx, tx))
}
MessageProtocolVersion::V2 => {
Box::new(super::v2::MessageProtocol::new(rx, tx))
}
MessageProtocolVersion::V3 => {
Box::new(super::v3::MessageProtocol::new(rx, tx))
}
}
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/protocol/v2.rs | comms/src/protocol/v2.rs | use std::io;
use std::ops::DerefMut;
use derivative::*;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use async_trait::async_trait;
use ate_crypto::{InitializationVector, EncryptKey};
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::MessageProtocolApi;
use super::StreamRx;
use super::StreamTx;
/// Opcodes are used to build and send the messages over the websocket
/// they must not exceed 16! as numbers above 16 are used for buffers
/// that are smaller than 239 bytes.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MessageOpCode {
#[allow(dead_code)]
Noop = 0,
NewIV = 1,
Buf16bit = 2,
Buf32bit = 3,
}
impl MessageOpCode {
fn to_u8(self) -> u8 {
self as u8
}
}
const MAX_MESSAGE_OP_CODE: u8 = 4;
const EXCESS_OP_CODE_SPACE: u8 = u8::MAX - MAX_MESSAGE_OP_CODE;
const MESSAGE_MAX_IV_REUSE: u32 = 1000;
#[derive(Derivative)]
#[derivative(Debug)]
pub struct MessageProtocol
{
iv_tx: Option<InitializationVector>,
iv_rx: Option<InitializationVector>,
iv_use_cnt: u32,
#[derivative(Debug = "ignore")]
rx: Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>>,
#[derivative(Debug = "ignore")]
tx: Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>>,
}
impl MessageProtocol
{
pub(super) fn new(rx: Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>>, tx: Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>>) -> Self {
Self {
iv_tx: None,
iv_rx: None,
iv_use_cnt: 0,
rx,
tx
}
}
fn tx_guard<'a>(&'a mut self) -> io::Result<&'a mut (dyn AsyncWrite + Send + Sync + Unpin + 'static)> {
self.tx.as_deref_mut()
.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "this protocol does not support writing"))
}
fn rx_guard<'a>(&'a mut self) -> io::Result<&'a mut (dyn AsyncRead + Send + Sync + Unpin + 'static)> {
self.rx.as_deref_mut()
.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "this protocol does not support reading"))
}
#[allow(unused_variables)]
async fn write_with_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
let tx = self.tx_guard()?;
let len = buf.len();
let op = if len < EXCESS_OP_CODE_SPACE as usize {
let len = len as u8;
let op = MAX_MESSAGE_OP_CODE + len;
vec![ op ]
} else if len < u16::MAX as usize {
let op = MessageOpCode::Buf16bit as u8;
let len = len as u16;
let len = len.to_be_bytes();
vec![op, len[0], len[1]]
} else if len < u32::MAX as usize {
let op = MessageOpCode::Buf32bit as u8;
let len = len as u32;
let len = len.to_be_bytes();
vec![op, len[0], len[1], len[2], len[3]]
} else {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u32::MAX
),
));
};
if len <= 62 {
let concatenated = [&op[..], &buf[..]].concat();
tx.write_all(&concatenated[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(concatenated.len() as u64)
} else {
let total_sent = op.len() as u64 + len as u64;
tx.write_all(&op[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
}
async fn read_u8(&mut self) -> Result<u8, tokio::io::Error> {
let mut buf = [0u8; 1];
self.read_exact(&mut buf).await?;
Ok(u8::from_be_bytes(buf))
}
async fn read_u16(&mut self) -> Result<u16, tokio::io::Error> {
let mut buf = [0u8; 2];
self.read_exact(&mut buf).await?;
Ok(u16::from_be_bytes(buf))
}
async fn read_u32(&mut self) -> Result<u32, tokio::io::Error> {
let mut buf = [0u8; 4];
self.read_exact(&mut buf).await?;
Ok(u32::from_be_bytes(buf))
}
async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), tokio::io::Error> {
let rx = self.rx_guard()?;
rx.read_exact(buf).await?;
Ok(())
}
}
#[async_trait]
impl MessageProtocolApi
for MessageProtocol
{
async fn write_with_fixed_16bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
let tx = self.tx_guard()?;
let len = buf.len();
let header = if len < u16::MAX as usize {
let len = len as u16;
len.to_be_bytes()
} else {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u16::MAX
),
));
};
let total_sent = header.len() as u64 + buf.len() as u64;
tx.write_all(&header[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
async fn write_with_fixed_32bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
let tx = self.tx_guard()?;
let len = buf.len();
let header = if len < u32::MAX as usize {
let len = len as u32;
len.to_be_bytes()
} else {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u32::MAX
),
));
};
let total_sent = header.len() as u64 + buf.len() as u64;
tx.write_all(&header[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
async fn send(
&mut self,
wire_encryption: &Option<EncryptKey>,
data: &[u8],
) -> Result<u64, tokio::io::Error> {
let mut total_sent = 0u64;
match wire_encryption {
Some(key) => {
if self.iv_tx.is_none() || self.iv_use_cnt > MESSAGE_MAX_IV_REUSE {
let iv = InitializationVector::generate();
let op = MessageOpCode::NewIV as u8;
let op = op.to_be_bytes();
let concatenated = [&op, &iv.bytes[..]].concat();
self.tx_guard()?.write_all(&concatenated[..]).await?;
self.iv_tx.replace(iv);
self.iv_use_cnt = 0;
} else {
self.iv_use_cnt += 1;
}
let iv = self.iv_tx.as_ref().unwrap();
let enc = key.encrypt_with_iv(iv, data);
total_sent += self.write_with_header(&enc[..], false).await?;
}
None => {
total_sent += self.write_with_header(data, false).await?;
}
};
Ok(total_sent)
}
async fn read_with_fixed_16bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>
{
let len = self.read_u16().await?;
if len <= 0 {
//trace!("stream_rx::16bit-header(no bytes!!)");
return Ok(vec![]);
}
//trace!("stream_rx::16bit-header(next_msg={} bytes)", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
Ok(bytes)
}
async fn read_with_fixed_32bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>
{
let len = self.read_u32().await?;
if len <= 0 {
//trace!("stream_rx::32bit-header(no bytes!!)");
return Ok(vec![]);
}
//trace!("stream_rx::32bit-header(next_msg={} bytes)", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
Ok(bytes)
}
async fn read_buf_with_header(
&mut self,
wire_encryption: &Option<EncryptKey>,
total_read: &mut u64
) -> std::io::Result<Vec<u8>>
{
// Enter a loop processing op codes and the data within it
loop {
let op = self.read_u8().await?;
*total_read += 1;
let len = if op == MessageOpCode::Noop.to_u8() {
//trace!("stream_rx::op(noop)");
continue;
} else if op == MessageOpCode::NewIV.to_u8() {
//trace!("stream_rx::op(new-iv)");
let mut iv = [0u8; 16];
self.read_exact(&mut iv).await?;
*total_read += 16;
let iv: InitializationVector = (&iv[..]).into();
self.iv_rx.replace(iv);
continue;
} else if op == MessageOpCode::Buf16bit.to_u8() {
//trace!("stream_rx::op(buf-16bit)");
let len = self.read_u16().await? as u32;
*total_read += 2;
len
} else if op == MessageOpCode::Buf32bit.to_u8() {
//trace!("stream_rx::op(buf-32bit)");
let len = self.read_u32().await? as u32;
*total_read += 4;
len
} else {
//trace!("stream_rx::op(buf-packed)");
(op as u32) - (MAX_MESSAGE_OP_CODE as u32)
};
// Now read the data
//trace!("stream_rx::buf(len={})", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
*total_read += len as u64;
// If its encrypted then we need to decrypt
if let Some(key) = wire_encryption {
// Get the initialization vector
if self.iv_rx.is_none() {
return Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "iv is missing"));
}
let iv = self.iv_rx.as_ref().unwrap();
// Decrypt the bytes
//trace!("stream_rx::decrypt(len={})", len);
bytes = key.decrypt(iv, &bytes[..]);
}
// Return the result
//trace!("stream_rx::ret(len={})", len);
return Ok(bytes);
}
}
async fn send_close(
&mut self,
) -> std::io::Result<()> {
Ok(())
}
async fn flush(
&mut self,
) -> std::io::Result<()> {
let tx = self.tx_guard()?;
tx.flush().await
}
fn rx(&mut self) -> Option<&mut (dyn AsyncRead + Send + Sync + Unpin + 'static)> {
self.rx.as_mut().map(|a| a.deref_mut())
}
fn tx(&mut self) -> Option<&mut (dyn AsyncWrite + Send + Sync + Unpin + 'static)> {
self.tx.as_mut().map(|a| a.deref_mut())
}
fn take_rx(&mut self) -> Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>> {
self.rx.take()
}
fn take_tx(&mut self) -> Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>> {
self.tx.take()
}
fn split(&mut self, ek: Option<EncryptKey>) -> (StreamRx, StreamTx) {
let rx = self.rx.take();
let tx = self.tx.take();
let rx = Box::new(Self::new(rx, None));
let tx = Box::new(Self::new(None, tx));
let rx = StreamRx::new(rx, ek.clone());
let tx = StreamTx::new(tx, ek.clone());
(rx, tx)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/protocol/api.rs | comms/src/protocol/api.rs | use std::io;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use tokio::io::ReadBuf;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use async_trait::async_trait;
use ate_crypto::EncryptKey;
use super::StreamRx;
use super::StreamTx;
#[async_trait]
pub trait MessageProtocolApi
where Self: std::fmt::Debug + Send + Sync,
{
async fn write_with_fixed_16bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error>;
async fn write_with_fixed_32bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error>;
async fn send(
&mut self,
wire_encryption: &Option<EncryptKey>,
data: &[u8],
) -> Result<u64, tokio::io::Error>;
async fn read_with_fixed_16bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>;
async fn read_with_fixed_32bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>;
async fn read_buf_with_header(
&mut self,
wire_encryption: &Option<EncryptKey>,
total_read: &mut u64
) -> std::io::Result<Vec<u8>>;
async fn send_close(
&mut self,
) -> std::io::Result<()>;
async fn flush(
&mut self,
) -> std::io::Result<()>;
fn split(&mut self, ek: Option<EncryptKey>) -> (StreamRx, StreamTx);
fn rx(&mut self) -> Option<&mut (dyn AsyncRead + Send + Sync + Unpin + 'static)>;
fn tx(&mut self) -> Option<&mut (dyn AsyncWrite + Send + Sync + Unpin + 'static)>;
fn take_rx(&mut self) -> Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>>;
fn take_tx(&mut self) -> Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>>;
}
impl AsyncRead
for dyn MessageProtocolApi + Unpin + Send + Sync
{
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let rx = match self.rx() {
Some(rx) => rx,
None => {
return Poll::Ready(Err(io::Error::new(io::ErrorKind::Unsupported, "this stream does not support reading")));
}
};
let rx = Pin::new(rx);
rx.poll_read(cx, buf)
}
}
impl AsyncWrite
for dyn MessageProtocolApi + Unpin + Send + Sync
{
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
let tx = match self.tx() {
Some(tx) => tx,
None => {
return Poll::Ready(Err(io::Error::new(io::ErrorKind::Unsupported, "this stream does not support writing")));
}
};
let tx = Pin::new(tx);
tx.poll_write(cx, buf)
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>
) -> Poll<Result<(), io::Error>> {
let tx = match self.tx() {
Some(tx) => tx,
None => {
return Poll::Ready(Err(io::Error::new(io::ErrorKind::Unsupported, "this stream does not support writing")));
}
};
let tx = Pin::new(tx);
tx.poll_flush(cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>
) -> Poll<Result<(), io::Error>> {
let tx = match self.tx() {
Some(tx) => tx,
None => {
return Poll::Ready(Err(io::Error::new(io::ErrorKind::Unsupported, "this stream does not support writing")));
}
};
let tx = Pin::new(tx);
tx.poll_shutdown(cx)
}
}
#[async_trait]
pub trait StreamReadable {
async fn read(&mut self) -> io::Result<Vec<u8>>;
}
#[async_trait]
pub trait StreamWritable {
async fn write(&mut self, data: &[u8]) -> io::Result<usize>;
async fn flush(&mut self) -> io::Result<()>;
async fn close(&mut self) -> io::Result<()>;
fn wire_encryption(&self) -> Option<EncryptKey>;
}
pub trait AsyncStream: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + Sync {}
impl<T> AsyncStream for T where T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + Sync
{}
impl std::fmt::Debug for dyn AsyncStream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("async-stream")
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/protocol/mod.rs | comms/src/protocol/mod.rs | mod v1;
mod v2;
mod v3;
mod api;
mod stream;
mod version;
pub use api::MessageProtocolApi;
pub use api::AsyncStream;
pub use api::StreamReadable;
pub use api::StreamWritable;
pub use stream::StreamRx;
pub use stream::StreamTx;
pub use version::MessageProtocolVersion; | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/protocol/v3.rs | comms/src/protocol/v3.rs | use std::io;
use std::ops::DerefMut;
use derivative::*;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use async_trait::async_trait;
use ate_crypto::{InitializationVector, EncryptKey};
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::MessageProtocolApi;
use super::StreamRx;
use super::StreamTx;
/// Opcodes are used to build and send the messages over the websocket
/// they must not exceed 16! as numbers above 16 are used for buffers
/// that are smaller than 239 bytes.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MessageOpCode {
#[allow(dead_code)]
Noop = 0,
NewIV = 1,
Buf16bit = 2,
Buf32bit = 3,
Close = 4,
}
impl MessageOpCode {
fn to_u8(self) -> u8 {
self as u8
}
}
const MAX_MESSAGE_OP_CODE: u8 = 8;
const EXCESS_OP_CODE_SPACE: u8 = u8::MAX - MAX_MESSAGE_OP_CODE;
const MESSAGE_MAX_IV_REUSE: u32 = 1000;
#[derive(Derivative)]
#[derivative(Debug)]
pub struct MessageProtocol
{
iv_tx: Option<InitializationVector>,
iv_rx: Option<InitializationVector>,
iv_use_cnt: u32,
flip_to_abort: bool,
is_closed: bool,
#[derivative(Debug = "ignore")]
rx: Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>>,
#[derivative(Debug = "ignore")]
tx: Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>>,
}
impl MessageProtocol
{
pub(super) fn new(rx: Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>>, tx: Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>>) -> Self {
Self {
iv_tx: None,
iv_rx: None,
iv_use_cnt: 0,
flip_to_abort: false,
is_closed: false,
rx,
tx
}
}
fn tx_guard<'a>(&'a mut self) -> io::Result<&'a mut (dyn AsyncWrite + Send + Sync + Unpin + 'static)> {
self.tx.as_deref_mut()
.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "this protocol does not support writing"))
}
fn rx_guard<'a>(&'a mut self) -> io::Result<&'a mut (dyn AsyncRead + Send + Sync + Unpin + 'static)> {
self.rx.as_deref_mut()
.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "this protocol does not support reading"))
}
#[allow(unused_variables)]
async fn write_with_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
let tx = self.tx_guard()?;
let len = buf.len();
let op = if len < EXCESS_OP_CODE_SPACE as usize {
let len = len as u8;
let op = MAX_MESSAGE_OP_CODE + len;
vec![ op ]
} else if len < u16::MAX as usize {
let op = MessageOpCode::Buf16bit as u8;
let len = len as u16;
let len = len.to_be_bytes();
vec![op, len[0], len[1]]
} else if len < u32::MAX as usize {
let op = MessageOpCode::Buf32bit as u8;
let len = len as u32;
let len = len.to_be_bytes();
vec![op, len[0], len[1], len[2], len[3]]
} else {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u32::MAX
),
));
};
if len <= 62 {
let concatenated = [&op[..], &buf[..]].concat();
tx.write_all(&concatenated[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(concatenated.len() as u64)
} else {
let total_sent = op.len() as u64 + len as u64;
tx.write_all(&op[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
}
async fn read_u8(&mut self) -> Result<u8, tokio::io::Error> {
let mut buf = [0u8; 1];
self.read_exact(&mut buf).await?;
Ok(u8::from_be_bytes(buf))
}
async fn read_u16(&mut self) -> Result<u16, tokio::io::Error> {
let mut buf = [0u8; 2];
self.read_exact(&mut buf).await?;
Ok(u16::from_be_bytes(buf))
}
async fn read_u32(&mut self) -> Result<u32, tokio::io::Error> {
let mut buf = [0u8; 4];
self.read_exact(&mut buf).await?;
Ok(u32::from_be_bytes(buf))
}
async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), tokio::io::Error> {
let rx = self.rx_guard()?;
rx.read_exact(buf).await?;
Ok(())
}
pub fn check_abort(&mut self) -> std::io::Result<bool>
{
if self.is_closed {
if self.flip_to_abort {
return Err(std::io::ErrorKind::BrokenPipe.into());
}
self.flip_to_abort = true;
Ok(true)
} else {
Ok(false)
}
}
}
#[async_trait]
impl MessageProtocolApi
for MessageProtocol
{
async fn write_with_fixed_16bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
if self.check_abort()? {
return Ok(0);
}
let len = buf.len();
let header = if len < u16::MAX as usize {
let len = len as u16;
len.to_be_bytes()
} else {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u16::MAX
),
));
};
let total_sent = header.len() as u64 + buf.len() as u64;
let tx = self.tx_guard()?;
tx.write_all(&header[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
async fn write_with_fixed_32bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
if self.check_abort()? {
return Ok(0);
}
let len = buf.len();
let header = if len < u32::MAX as usize {
let len = len as u32;
len.to_be_bytes()
} else {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u32::MAX
),
));
};
let total_sent = header.len() as u64 + buf.len() as u64;
let tx = self.tx_guard()?;
tx.write_all(&header[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
async fn send(
&mut self,
wire_encryption: &Option<EncryptKey>,
data: &[u8],
) -> Result<u64, tokio::io::Error> {
if self.check_abort()? {
return Ok(0);
}
let mut total_sent = 0u64;
match wire_encryption {
Some(key) => {
if self.iv_tx.is_none() || self.iv_use_cnt > MESSAGE_MAX_IV_REUSE {
let iv = InitializationVector::generate();
let op = MessageOpCode::NewIV as u8;
let op = op.to_be_bytes();
let concatenated = [&op, &iv.bytes[..]].concat();
self.tx_guard()?.write_all(&concatenated[..]).await?;
self.iv_tx.replace(iv);
self.iv_use_cnt = 0;
} else {
self.iv_use_cnt += 1;
}
let iv = self.iv_tx.as_ref().unwrap();
let enc = key.encrypt_with_iv(iv, data);
total_sent += self.write_with_header(&enc[..], false).await?;
}
None => {
total_sent += self.write_with_header(data, false).await?;
}
};
Ok(total_sent)
}
async fn read_with_fixed_16bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>
{
if self.check_abort()? {
return Ok(vec![]);
}
let len = self.read_u16().await?;
if len <= 0 {
//trace!("stream_rx::16bit-header(no bytes!!)");
return Ok(vec![]);
}
//trace!("stream_rx::16bit-header(next_msg={} bytes)", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
Ok(bytes)
}
async fn read_with_fixed_32bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>
{
if self.check_abort()? {
return Ok(vec![]);
}
let len = self.read_u32().await?;
if len <= 0 {
//trace!("stream_rx::32bit-header(no bytes!!)");
return Ok(vec![]);
}
//trace!("stream_rx::32bit-header(next_msg={} bytes)", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
Ok(bytes)
}
async fn read_buf_with_header(
&mut self,
wire_encryption: &Option<EncryptKey>,
total_read: &mut u64
) -> std::io::Result<Vec<u8>>
{
// Enter a loop processing op codes and the data within it
loop {
if self.check_abort()? {
return Ok(vec![]);
}
let op = self.read_u8().await?;
*total_read += 1;
let len = if op == MessageOpCode::Noop.to_u8() {
//trace!("stream_rx::op(noop)");
continue;
} else if op == MessageOpCode::NewIV.to_u8() {
//trace!("stream_rx::op(new-iv)");
let mut iv = [0u8; 16];
self.read_exact(&mut iv).await?;
*total_read += 16;
let iv: InitializationVector = (&iv[..]).into();
self.iv_rx.replace(iv);
continue;
} else if op == MessageOpCode::Buf16bit.to_u8() {
//trace!("stream_rx::op(buf-16bit)");
let len = self.read_u16().await? as u32;
*total_read += 2;
len
} else if op == MessageOpCode::Buf32bit.to_u8() {
//trace!("stream_rx::op(buf-32bit)");
let len = self.read_u32().await? as u32;
*total_read += 4;
len
} else if op == MessageOpCode::Close.to_u8() {
//trace!("stream_rx::op(close)");
self.is_closed = true;
continue;
} else {
//trace!("stream_rx::op(buf-packed)");
(op as u32) - (MAX_MESSAGE_OP_CODE as u32)
};
// Now read the data
//trace!("stream_rx::buf(len={})", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
*total_read += len as u64;
// If its encrypted then we need to decrypt
if let Some(key) = wire_encryption {
// Get the initialization vector
if self.iv_rx.is_none() {
return Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "iv is missing"));
}
let iv = self.iv_rx.as_ref().unwrap();
// Decrypt the bytes
//trace!("stream_rx::decrypt(len={})", len);
bytes = key.decrypt(iv, &bytes[..]);
}
// Return the result
//trace!("stream_rx::ret(len={})", len);
return Ok(bytes);
}
}
async fn send_close(
&mut self,
) -> std::io::Result<()> {
let tx = self.tx_guard()?;
let op = MessageOpCode::Close as u8;
let op = op.to_be_bytes();
tx.write_all(&op[..]).await?;
tx.flush().await?;
self.is_closed = true;
Ok(())
}
async fn flush(
&mut self,
) -> std::io::Result<()> {
let tx = self.tx_guard()?;
tx.flush().await
}
fn rx(&mut self) -> Option<&mut (dyn AsyncRead + Send + Sync + Unpin + 'static)> {
self.rx.as_mut().map(|a| a.deref_mut())
}
fn tx(&mut self) -> Option<&mut (dyn AsyncWrite + Send + Sync + Unpin + 'static)> {
self.tx.as_mut().map(|a| a.deref_mut())
}
fn take_rx(&mut self) -> Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>> {
self.rx.take()
}
fn take_tx(&mut self) -> Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>> {
self.tx.take()
}
fn split(&mut self, ek: Option<EncryptKey>) -> (StreamRx, StreamTx) {
let rx = self.rx.take();
let tx = self.tx.take();
let rx = Box::new(Self::new(rx, None));
let tx = Box::new(Self::new(None, tx));
let rx = StreamRx::new(rx, ek.clone());
let tx = StreamTx::new(tx, ek.clone());
(rx, tx)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/comms/src/protocol/v1.rs | comms/src/protocol/v1.rs | use std::io;
use std::ops::DerefMut;
use derivative::*;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use async_trait::async_trait;
use ate_crypto::{EncryptKey, InitializationVector};
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::MessageProtocolApi;
use super::StreamRx;
use super::StreamTx;
#[derive(Derivative)]
#[derivative(Debug)]
pub struct MessageProtocol
{
#[derivative(Debug = "ignore")]
rx: Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>>,
#[derivative(Debug = "ignore")]
tx: Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>>,
}
impl MessageProtocol
{
pub(super) fn new(rx: Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>>, tx: Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>>) -> Self {
Self {
rx,
tx
}
}
fn tx_guard<'a>(&'a mut self) -> io::Result<&'a mut (dyn AsyncWrite + Send + Sync + Unpin + 'static)> {
self.tx.as_deref_mut()
.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "this protocol does not support writing"))
}
fn rx_guard<'a>(&'a mut self) -> io::Result<&'a mut (dyn AsyncRead + Send + Sync + Unpin + 'static)> {
self.rx.as_deref_mut()
.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "this protocol does not support reading"))
}
async fn write_with_8bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
let tx = self.tx_guard()?;
if buf.len() > u8::MAX as usize {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u8::MAX
),
));
}
let len = buf.len() as u8;
let len_buf = len.to_be_bytes();
if len <= 63 {
let concatenated = [&len_buf[..], &buf[..]].concat();
tx.write_all(&concatenated[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(concatenated.len() as u64)
} else {
let total_sent = len_buf.len() as u64 + len as u64;
tx.write_all(&len_buf[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
}
async fn write_with_16bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
let tx = self.tx_guard()?;
if buf.len() > u16::MAX as usize {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u8::MAX
),
));
}
let len = buf.len() as u16;
let len_buf = len.to_be_bytes();
if len <= 62 {
let concatenated = [&len_buf[..], &buf[..]].concat();
tx.write_all(&concatenated[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(concatenated.len() as u64)
} else {
let total_sent = len_buf.len() as u64 + len as u64;
tx.write_all(&len_buf[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
}
async fn write_with_32bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
let tx = self.tx_guard()?;
if buf.len() > u32::MAX as usize {
return Err(tokio::io::Error::new(
tokio::io::ErrorKind::InvalidData,
format!(
"Data is too big to write (len={}, max={})",
buf.len(),
u8::MAX
),
));
}
let len = buf.len() as u32;
let len_buf = len.to_be_bytes();
if len <= 60 {
let concatenated = [&len_buf[..], &buf[..]].concat();
tx.write_all(&concatenated[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(concatenated.len() as u64)
} else {
let total_sent = len_buf.len() as u64 + len as u64;
tx.write_all(&len_buf[..]).await?;
tx.write_all(&buf[..]).await?;
if delay_flush == false {
tx.flush().await?;
}
Ok(total_sent)
}
}
async fn read_u8(&mut self) -> Result<u8, tokio::io::Error> {
let mut buf = [0u8; 1];
self.read_exact(&mut buf).await?;
Ok(u8::from_be_bytes(buf))
}
async fn read_u16(&mut self) -> Result<u16, tokio::io::Error> {
let mut buf = [0u8; 2];
self.read_exact(&mut buf).await?;
Ok(u16::from_be_bytes(buf))
}
async fn read_u32(&mut self) -> Result<u32, tokio::io::Error> {
let mut buf = [0u8; 4];
self.read_exact(&mut buf).await?;
Ok(u32::from_be_bytes(buf))
}
async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), tokio::io::Error> {
let rx = self.rx_guard()?;
rx.read_exact(buf).await?;
Ok(())
}
async fn read_with_8bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>
{
let len = self.read_u8().await?;
if len <= 0 {
//trace!("stream_rx::8bit-header(no bytes!!)");
return Ok(vec![]);
}
//trace!("stream_rx::8bit-header(next_msg={} bytes)", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
Ok(bytes)
}
}
#[async_trait]
impl MessageProtocolApi
for MessageProtocol
{
async fn write_with_fixed_16bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
self.write_with_16bit_header(buf, delay_flush).await
}
async fn write_with_fixed_32bit_header(
&mut self,
buf: &'_ [u8],
delay_flush: bool,
) -> Result<u64, tokio::io::Error> {
self.write_with_32bit_header(buf, delay_flush).await
}
async fn send(
&mut self,
wire_encryption: &Option<EncryptKey>,
data: &[u8],
) -> Result<u64, tokio::io::Error> {
let mut total_sent = 0u64;
match wire_encryption {
Some(key) => {
let enc = key.encrypt(data);
total_sent += self.write_with_8bit_header(&enc.iv.bytes, true).await?;
total_sent += self.write_with_32bit_header(&enc.data, false).await?;
}
None => {
total_sent += self.write_with_32bit_header(data, false).await?;
}
};
Ok(total_sent)
}
async fn read_with_fixed_16bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>
{
let len = self.read_u16().await?;
if len <= 0 {
//trace!("stream_rx::16bit-header(no bytes!!)");
return Ok(vec![]);
}
//trace!("stream_rx::16bit-header(next_msg={} bytes)", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
Ok(bytes)
}
async fn read_with_fixed_32bit_header(
&mut self,
) -> Result<Vec<u8>, tokio::io::Error>
{
let len = self.read_u32().await?;
if len <= 0 {
//trace!("stream_rx::32bit-header(no bytes!!)");
return Ok(vec![]);
}
//trace!("stream_rx::32bit-header(next_msg={} bytes)", len);
let mut bytes = vec![0 as u8; len as usize];
self.read_exact(&mut bytes).await?;
Ok(bytes)
}
async fn read_buf_with_header(
&mut self,
wire_encryption: &Option<EncryptKey>,
total_read: &mut u64
) -> std::io::Result<Vec<u8>>
{
match wire_encryption {
Some(key) => {
// Read the initialization vector
let iv_bytes = self.read_with_8bit_header().await?;
*total_read += 1u64;
match iv_bytes.len() {
0 => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "iv_bytes-len is zero")),
l => {
*total_read += l as u64;
let iv = InitializationVector::from(iv_bytes);
// Read the cipher text and decrypt it
let cipher_bytes = self.read_with_fixed_32bit_header().await?;
*total_read += 4u64;
match cipher_bytes.len() {
0 => Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"cipher_bytes-len is zero",
)),
l => {
*total_read += l as u64;
Ok(key.decrypt(&iv, &cipher_bytes))
}
}
}
}
}
None => {
// Read the next message
let buf = self.read_with_fixed_32bit_header().await?;
*total_read += 4u64;
match buf.len() {
0 => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "buf-len is zero")),
l => {
*total_read += l as u64;
Ok(buf)
}
}
}
}
}
async fn send_close(
&mut self,
) -> std::io::Result<()> {
Ok(())
}
async fn flush(
&mut self,
) -> std::io::Result<()> {
let tx = self.tx_guard()?;
tx.flush().await
}
fn rx(&mut self) -> Option<&mut (dyn AsyncRead + Send + Sync + Unpin + 'static)> {
self.rx.as_mut().map(|a| a.deref_mut())
}
fn tx(&mut self) -> Option<&mut (dyn AsyncWrite + Send + Sync + Unpin + 'static)> {
self.tx.as_mut().map(|a| a.deref_mut())
}
fn take_rx(&mut self) -> Option<Box<dyn AsyncRead + Send + Sync + Unpin + 'static>> {
self.rx.take()
}
fn take_tx(&mut self) -> Option<Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>> {
self.tx.take()
}
fn split(&mut self, ek: Option<EncryptKey>) -> (StreamRx, StreamTx) {
let rx = self.rx.take();
let tx = self.tx.take();
let rx = Box::new(Self::new(rx, None));
let tx = Box::new(Self::new(None, tx));
let rx = StreamRx::new(rx, ek.clone());
let tx = StreamTx::new(tx, ek.clone());
(rx, tx)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/atedb/src/flow.rs | atedb/src/flow.rs | use regex::Regex;
use std::sync::Arc;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use async_trait::async_trait;
use ate::spec::TrustMode;
use ate::{error::ChainCreationError, prelude::*};
use wasmer_auth::cmd::query_command;
use wasmer_auth::helper::conf_auth;
use wasmer_auth::request::*;
pub struct ChainFlow {
pub cfg: ConfAte,
pub regex_personal: Regex,
pub regex_group: Regex,
pub mode: TrustMode,
pub url_auth: Option<url::Url>,
pub url_db: url::Url,
pub registry: Arc<Registry>,
}
impl ChainFlow {
pub async fn new(
cfg: &ConfAte,
url_auth: Option<url::Url>,
url_db: url::Url,
mode: TrustMode,
) -> Self {
let registry = ate::mesh::Registry::new(&conf_auth())
.await
.temporal(true)
.cement();
ChainFlow {
cfg: cfg.clone(),
regex_personal: Regex::new("^([a-z0-9\\.!#$%&'*+/=?^_`{|}~-]{1,})/([a-z0-9\\.!#$%&'*+/=?^_`{|}~-]{1,})/([a-zA-Z0-9_]{1,})$").unwrap(),
regex_group: Regex::new("^([a-zA-Z0-9_\\.-]{1,})/([a-zA-Z0-9_]{1,})$").unwrap(),
mode,
url_auth,
url_db,
registry,
}
}
}
#[async_trait]
impl OpenFlow for ChainFlow {
fn hello_path(&self) -> &str {
self.url_db.path()
}
async fn message_of_the_day(
&self,
_chain: &Arc<Chain>,
) -> Result<Option<String>, ChainCreationError> {
Ok(None)
}
async fn open(
&self,
mut builder: ChainBuilder,
key: &ChainKey,
_wire_encryption: Option<KeySize>,
) -> Result<OpenAction, ChainCreationError> {
trace!("open_db: {}", key);
// Extract the identity from the supplied path (we can only create chains that are actually
// owned by the specific user)
let path = key.name.clone();
if let Some(captures) = self.regex_personal.captures(path.as_str()) {
// Build the email address using the captures
let email = format!(
"{}@{}",
captures.get(2).unwrap().as_str(),
captures.get(1).unwrap().as_str()
);
let dbname = captures.get(3).unwrap().as_str().to_string();
// Check for very naughty parameters
if email.contains("..")
|| dbname.contains("..")
|| email.contains("~")
|| dbname.contains("~")
{
return Ok(OpenAction::Deny {
reason: format!(
"The chain-key ({}) contains forbidden characters.",
key.to_string()
)
.to_string(),
});
}
// Grab the public write key from the authentication server for this user
if let Some(auth) = &self.url_auth {
let advert = match query_command(&self.registry, email.clone(), auth.clone()).await
{
Ok(a) => a.advert,
Err(err) => {
return Ok(OpenAction::Deny {
reason: format!("Failed to create the chain as the query to the authentication server failed - {}.", err.to_string()).to_string()
});
}
};
let root_key = advert.nominal_auth;
builder = builder.add_root_public_key(&root_key);
}
// Set the load integrity to match what the database will run as
builder = builder.load_integrity(self.mode);
// Prefix the name with 'redo'
let mut key_name = key.name.clone();
if key_name.starts_with("/") {
key_name = key_name[1..].to_string();
}
let key = ChainKey::new(format!("{}", key_name).to_string());
// Create the chain
let chain = builder.build().open(&key).await?;
// We have opened the chain
return match self.mode.is_centralized() {
true => {
debug!("centralized integrity for {}", key.to_string());
Ok(OpenAction::CentralizedChain { chain })
}
false => {
debug!("distributed integrity for {}", key.to_string());
Ok(OpenAction::DistributedChain { chain })
}
};
}
// The path may match a group that was created
if let Some(captures) = self.regex_group.captures(path.as_str()) {
// Get the auth
let group = captures.get(1).unwrap().as_str().to_string();
let dbname = captures.get(2).unwrap().as_str().to_string();
// Check for very naughty parameters
if group.contains("..")
|| dbname.contains("..")
|| group.contains("~")
|| dbname.contains("~")
{
return Ok(OpenAction::Deny {
reason: format!(
"The chain-key ({}) contains forbidden characters.",
key.to_string()
)
.to_string(),
});
}
let auth = match &self.url_auth {
Some(a) => a.clone(),
None => {
return Ok(OpenAction::Deny {
reason: format!("Failed to create the chain for group ({}) as the server has no authentication endpoint configured.", group)
});
}
};
// Grab the public write key from the authentication server for this group
let chain = self.registry.open_cmd(&auth).await?;
let advert: Result<GroupDetailsResponse, GroupDetailsFailed> = chain
.invoke(GroupDetailsRequest {
group,
session: None,
})
.await?;
let advert = match advert {
Ok(a) => a,
Err(GroupDetailsFailed::NoAccess) => {
return Ok(OpenAction::Deny {
reason: format!("Failed to create the chain as the caller has no access to the authorization group({}), contact the owner of the group to add this user to the delegate role of that group.", path)
});
}
Err(GroupDetailsFailed::NoMasterKey) => {
return Ok(OpenAction::Deny {
reason: format!("Failed to create the chain as the server has not yet been properly initialized.")
});
}
Err(GroupDetailsFailed::GroupNotFound) => {
return Ok(OpenAction::Deny {
reason: format!("Failed to create the chain as no authorization group exists with the same name({}), please create one and try again.", path)
});
}
Err(GroupDetailsFailed::InternalError(code)) => {
return Ok(OpenAction::Deny {
reason: format!("Failed to create the chain as the authentication group query failed due to an internal error - code={}.", code)
});
}
};
let role = match advert
.roles
.iter()
.filter(|r| r.purpose == AteRolePurpose::Delegate)
.next()
{
Some(a) => a,
None => {
return Ok(OpenAction::Deny {
reason: format!(
"Failed to create the chain as the group has no delegate role."
),
});
}
};
builder = builder.add_root_public_key(&role.write);
// Prefix the name with 'redo'
let mut key_name = key.name.clone();
if key_name.starts_with("/") {
key_name = key_name[1..].to_string();
}
let key = ChainKey::new(format!("{}", key_name).to_string());
// Create the chain
let chain = builder.build().open(&key).await?;
// We have opened the chain
return match self.mode.is_centralized() {
true => {
debug!("centralized integrity for {}", key.to_string());
Ok(OpenAction::CentralizedChain { chain })
}
false => {
debug!("distributed integrity for {}", key.to_string());
Ok(OpenAction::DistributedChain { chain })
}
};
}
// Ask the authentication server for the public key for this user
return Ok(OpenAction::Deny {
reason: format!("The chain-key ({}) does not match a valid pattern - for private datachains it must be in the format of 'gmail.com/joe.blogs/mydb' where the owner of this chain is the user joe.blogs@gmail.com. - for shared datachains you must first create a group with the same name and then use the format '[group-name]/[chain-name]'.", key.to_string()).to_string()
});
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/atedb/src/main.rs | atedb/src/main.rs | use ate::{compact::CompactMode, prelude::*, utils::load_node_list};
use std::time::Duration;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use clap::Parser;
mod flow;
use crate::flow::ChainFlow;
#[derive(Parser)]
#[clap(version = "1.4", author = "John S. <johnathan.sharratt@gmail.com>")]
struct Opts {
/// Sets the level of log verbosity, can be used multiple times
#[allow(dead_code)]
#[clap(short, long, parse(from_occurrences))]
verbose: i32,
/// Logs debug info to the console
#[clap(short, long)]
debug: bool,
/// URL where the user is authenticated
#[clap(short, long, default_value = "ws://wasmer.sh/auth")]
auth: Url,
/// Indicates no authentication server will be used meaning all new chains
/// created by clients allow anyone to write new root nodes.
#[clap(long)]
no_auth: bool,
/// Indicates if ATE will use quantum resistant wire encryption (possible values
/// are 128, 192, 256). When running in 'centralized' mode wire encryption will
/// default to 128bit however when running in 'distributed' mode wire encryption
/// will default to off unless explicitly turned on.
#[clap(long)]
wire_encryption: Option<KeySize>,
/// Disbles wire encryption which would otherwise be turned on when running in 'centralized' mode.
#[clap(long)]
no_wire_encryption: bool,
/// Trust mode that the datachain server will run under - valid values are either
/// 'distributed' or 'centralized'. When running in 'distributed' mode the
/// server itself does not need to be trusted in order to trust the data it holds
/// however it has a significant performance impact on write operations while the
/// 'centralized' mode gives much higher performance but the server needs to be
/// protected.
#[clap(short, long, default_value = "centralized")]
trust: TrustMode,
/// Determines if ATE will use DNSSec or just plain DNS
#[clap(long)]
dns_sec: bool,
/// Address that DNS queries will be sent to
#[clap(long, default_value = "8.8.8.8")]
dns_server: String,
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Parser)]
enum SubCommand {
#[clap()]
Solo(Solo),
}
/// Runs a solo ATE datachain and listens for connections from clients
#[derive(Parser)]
struct Solo {
/// Path to the log files where all the file system data is stored
#[clap(index = 1, default_value = "/opt/ate")]
logs_path: String,
/// Path to the backup and restore location of log files
#[clap(short, long)]
backup_path: Option<String>,
/// Address that the datachain server(s) are listening and that
/// this server can connect to if the chain is on another mesh node
#[clap(short, long, default_value = "ws://localhost:5000/db")]
url: url::Url,
/// Optional list of the nodes that make up this cluster
/// (if the file does not exist then it will not load)
#[clap(long)]
nodes_list: Option<String>,
/// IP address that the datachain server will isten on
#[clap(short, long, default_value = "::")]
listen: IpAddr,
/// Ensures that this datachain runs as a specific node_id
#[clap(short, long)]
node_id: Option<u32>,
/// Mode that the compaction will run under (valid modes are 'never', 'modified', 'timer', 'factor', 'size', 'factor-or-timer', 'size-or-timer')
#[clap(long, default_value = "factor-or-timer")]
compact_mode: CompactMode,
/// Time in seconds between compactions of the log file (default: 1 hour) - this argument is ignored if you select a compact_mode that has no timer
#[clap(long, default_value = "3600")]
compact_timer: u64,
/// Factor growth in the log file which will trigger compaction - this argument is ignored if you select a compact_mode that has no growth trigger
#[clap(long, default_value = "0.4")]
compact_threshold_factor: f32,
/// Size of growth in bytes in the log file which will trigger compaction (default: 100MB) - this argument is ignored if you select a compact_mode that has no growth trigger
#[clap(long, default_value = "104857600")]
compact_threshold_size: u64,
}
fn ctrl_channel() -> tokio::sync::watch::Receiver<bool> {
let (sender, receiver) = tokio::sync::watch::channel(false);
ctrlc_async::set_handler(move || {
let _ = sender.send(true);
})
.unwrap();
receiver
}
#[tokio::main(flavor = "multi_thread")]
async fn main() -> Result<(), AteError> {
let opts: Opts = Opts::parse();
//let opts = main_debug();
ate::log_init(opts.verbose, opts.debug);
let wire_encryption = match opts.wire_encryption {
Some(a) => Some(a),
None => match opts.trust.is_centralized() {
true => match opts.no_wire_encryption {
false => Some(KeySize::Bit128),
true => None,
},
false => None,
},
};
let mut conf = AteConfig::default();
conf.dns_sec = opts.dns_sec;
conf.dns_server = opts.dns_server;
let auth = match opts.no_auth {
false if opts.trust.is_centralized() => Some(opts.auth),
_ => None,
};
match opts.subcmd {
SubCommand::Solo(solo) => {
main_solo(solo, conf, auth, opts.trust, wire_encryption).await?;
}
}
info!("atedb::shutdown");
Ok(())
}
async fn main_solo(
solo: Solo,
mut cfg_ate: ConfAte,
auth: Option<url::Url>,
trust: TrustMode,
wire_encryption: Option<KeySize>,
) -> Result<(), AteError> {
// Create the chain flow and generate configuration
cfg_ate.log_path = Some(shellexpand::tilde(&solo.logs_path).to_string());
cfg_ate.backup_path = solo
.backup_path
.as_ref()
.map(|a| shellexpand::tilde(a).to_string());
cfg_ate.compact_mode = solo
.compact_mode
.with_growth_factor(solo.compact_threshold_factor)
.with_growth_size(solo.compact_threshold_size)
.with_timer_value(Duration::from_secs(solo.compact_timer));
cfg_ate.nodes = load_node_list(solo.nodes_list);
// Create the chain flow and generate configuration
let flow = ChainFlow::new(&cfg_ate, auth, solo.url.clone(), trust).await;
// Create the server and listen on the port
let mut cfg_mesh =
ConfMesh::solo_from_url(&cfg_ate, &solo.url, &solo.listen, None, solo.node_id).await?;
cfg_mesh.wire_protocol = StreamProtocol::parse(&solo.url)?;
cfg_mesh.wire_encryption = wire_encryption;
let server = create_server(&cfg_mesh).await?;
server.add_route(Box::new(flow), &cfg_ate).await?;
// Wait for ctrl-c
println!("Press ctrl-c to exit");
let mut exit = ctrl_channel();
while *exit.borrow() == false {
exit.changed().await.unwrap();
}
println!("Shutting down...");
server.shutdown().await;
println!("Goodbye!");
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/atedb/src/bin/atedump.rs | atedb/src/bin/atedump.rs | #![allow(unused_imports)]
use ascii_tree::Tree;
use async_trait::async_trait;
use ate::conf::conf_ate;
use ate::event::*;
use ate::loader::LoadData;
use ate::loader::Loader;
use ate::prelude::*;
use ate::redo::OpenFlags;
use ate::redo::RedoLog;
use ate::spec::TrustMode;
use ate::trust::ChainHeader;
use ate::utils::LoadProgress;
use clap::Parser;
use colored::*;
use fxhash::FxHashMap;
use fxhash::FxHashSet;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio::sync::mpsc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Parser)]
#[clap(version = "1.4", author = "John S. <johnathan.sharratt@gmail.com>")]
struct Opts {
/// Path to the log file to be dumped
#[clap(index = 1)]
path: String,
/// Name of the log file to be opened
#[clap(index = 2)]
name: String,
#[clap(long)]
no_compact: bool,
#[clap(long)]
no_short_names: bool,
}
pub struct DumpLoader {
tx: mpsc::Sender<LoadData>,
}
#[async_trait]
impl Loader for DumpLoader {
async fn feed_load_data(&mut self, evt: LoadData) {
self.tx.send(evt).await.unwrap();
}
}
#[derive(Default)]
struct EventNode {
name: String,
versions: Vec<AteHash>,
children: Vec<PrimaryKey>,
}
#[derive(Default)]
struct EventData {
data: Option<String>,
data_hash: Option<AteHash>,
event_hash: Option<AteHash>,
sig: Option<AteHash>,
bad_order: bool,
bad_pk: bool,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), AteError> {
let opts: Opts = Opts::parse();
ate::log_init(0, true);
// Configure
let flags = OpenFlags {
read_only: true,
truncate: false,
temporal: false,
integrity: TrustMode::Distributed,
};
let header = ChainHeader::default();
let header_bytes = SerializationFormat::Json.serialize(&header)
.map_err(SerializationError::from)?;
let mut cfg_ate = ConfAte::default();
cfg_ate.log_path = Some(opts.path);
let key = ChainKey::new(opts.name);
// Create a progress bar loader
let mut progress_loader = LoadProgress::new(std::io::stderr());
progress_loader.units = pbr::Units::Bytes;
progress_loader.msg_done = "Reading events from file...".to_string();
// Build the composite loader
let (tx, mut rx) = mpsc::channel(u32::MAX as usize);
let mut loader = Box::new(ate::loader::CompositionLoader::default());
loader.loaders.push(Box::new(progress_loader));
loader.loaders.push(Box::new(DumpLoader { tx }));
// Load the log file and dump its contents
RedoLog::open_ext(&cfg_ate, &key, flags, loader, header_bytes).await?;
// Build a tree and dump it to console
let mut hash_pk = FxHashSet::default();
let mut tree_pks = Vec::new();
let mut tree_sigs = Vec::new();
let mut tree_roots: Vec<PrimaryKey> = Vec::new();
let mut tree_event: FxHashMap<AteHash, EventData> = FxHashMap::default();
let mut tree_lookup: FxHashMap<PrimaryKey, EventNode> = FxHashMap::default();
while let Some(evt) = rx.recv().await {
let header = match evt.header.as_header() {
Ok(a) => a,
Err(err) => {
warn!("failed to read metadata - {}", err);
continue;
}
};
// Get the signature and record it for the different data nodes
if let Some(pk) = header.meta.get_public_key() {
hash_pk.insert(pk.hash());
tree_pks.push(pk.hash());
}
// Get the signature and record it for the different data nodes
if let Some(sig) = header.meta.get_signature() {
for hash in &sig.hashes {
tree_event.entry(hash.clone()).or_default().sig = Some(sig.public_key_hash);
}
tree_sigs.push(sig.clone());
continue;
}
// Build a name for the node
let name = if let Some(type_name) = header.meta.get_type_name() {
let mut name = type_name.type_name.clone();
if opts.no_short_names == false {
for short in type_name.type_name.split(":") {
name = short.to_string();
}
}
if let Some(key) = header.meta.get_data_key() {
format!("{}(key={})", name.bold(), key)
} else {
name.as_str().bold().to_string()
}
} else if let Some(tombstone) = header.meta.get_tombstone() {
if opts.no_compact == false {
tree_lookup.remove(&tombstone);
continue;
}
format!("{}({})", "tombstone".yellow(), tombstone)
} else if let Some(pk) = header.meta.get_public_key() {
format!("public-key({})", pk.hash())
} else {
"unknown".bold().to_string()
};
// Insert some data into the node
let key = match header.meta.get_data_key() {
Some(a) => a,
None => PrimaryKey::generate(),
};
let node = tree_lookup.entry(key.clone()).or_insert_with(|| {
let mut node = EventNode::default();
node.name = name.clone();
node
});
// Put the actual data in the node
if opts.no_compact == false {
node.versions.clear();
}
if header.meta.get_tombstone().is_some() {
if opts.no_compact == false {
drop(node);
tree_lookup.remove(&key);
continue;
}
}
// Put the actual data in the node
let d = tree_event.entry(header.raw.event_hash.clone()).or_default();
d.data = if header.raw.data_size > 0 {
Some(format!("{}({} bytes)", "data", header.raw.data_size))
} else {
Some(format!("{}", name))
};
d.data_hash = header.raw.data_hash;
d.event_hash = Some(header.raw.event_hash);
if let Some(sig) = &d.sig {
if hash_pk.contains(sig) == false {
d.bad_pk = true;
}
} else {
d.bad_order = true;
}
node.versions.push(header.raw.event_hash.clone());
// Put the node in the right place
match header.meta.get_parent() {
Some(a) => {
if let Some(a) = tree_lookup.get_mut(&a.vec.parent_id) {
if a.children.iter().any(|a| a.eq(&key)) == false {
a.children.push(key);
}
}
}
None => {
if tree_roots.iter().any(|a| a.eq(&key)) == false {
tree_roots.push(key);
}
}
}
}
// Turn it into ascii-tree
let mut output = String::new();
for tree_pk in tree_pks {
let tree = Tree::Node(format!("public-key({})", tree_pk.to_8hex()), Vec::default());
ascii_tree::write_tree(&mut output, &tree).unwrap();
}
for tree_sig in tree_sigs {
let no_compact = opts.no_compact;
let mut data = tree_sig
.hashes
.into_iter()
.filter_map(|d| {
if tree_event.contains_key(&d) {
match no_compact {
true => Some(format!("{}({})", "event", d.to_8hex())),
false => None,
}
} else {
Some(format!("{}({}) {}", "event", d.to_8hex(), "missing".red()))
}
})
.collect::<Vec<_>>();
if data.len() <= 0 {
continue;
}
data.insert(0, format!("sig-data({} bytes)", tree_sig.signature.len()));
let name = match hash_pk.contains(&tree_sig.public_key_hash) {
true => format!(
"signature({}) {}",
"pk-ref".green(),
tree_sig.public_key_hash.to_8hex()
),
false => format!(
"signature({}) {}",
"pk-missing".red(),
tree_sig.public_key_hash.to_8hex()
),
};
let tree = Tree::Node(name, vec![Tree::Leaf(data)]);
ascii_tree::write_tree(&mut output, &tree).unwrap();
}
for root in tree_roots.iter() {
let tree = build_tree(root, &tree_lookup, &tree_event);
if let Some(tree) = tree {
ascii_tree::write_tree(&mut output, &tree).unwrap();
}
}
print!("{}", output);
Ok(())
}
fn build_tree(
key: &PrimaryKey,
tree_lookup: &FxHashMap<PrimaryKey, EventNode>,
tree_data: &FxHashMap<AteHash, EventData>,
) -> Option<Tree> {
if let Some(node) = tree_lookup.get(&key) {
let mut children = Vec::new();
if node.versions.len() > 0 {
let versions = node
.versions
.iter()
.filter_map(|a| tree_data.get(a))
.map(|a| {
let e = a
.event_hash
.map_or_else(|| "none".to_string(), |f| f.to_8hex());
match &a.data {
Some(b) => (b.clone(), a, a.data_hash.clone(), e),
None => ("missing".to_string(), a, a.data_hash.clone(), e),
}
})
.map(|(d, a, h, e)| {
if let Some(s) = a.sig.clone() {
if a.bad_order {
format!(
"{} {}({}) evt={}",
d.yellow(),
"sig-bad-order".red(),
s.to_8hex(),
e
)
} else if a.bad_pk {
format!(
"{} {}({}) evt={}",
d.yellow(),
"sig-bad-pk".red(),
s.to_8hex(),
e
)
} else {
format!("{} {}({}) evt={}", d, "sig".green(), s.to_8hex(), e)
}
} else if let Some(h) = h {
format!(
"{} {}({}) evt={}",
d.yellow(),
"no-sig".red(),
h.to_8hex(),
e
)
} else {
format!("{} {}, evt={}", d.yellow(), "no-sig".red(), e)
}
})
.collect::<Vec<_>>();
let leaf = Tree::Leaf(versions);
children.push(leaf);
}
for c in &node.children {
if let Some(c) = build_tree(c, tree_lookup, tree_data) {
children.push(c);
}
}
Some(Tree::Node(node.name.clone(), children))
} else {
None
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/lib.rs | wasmer-instance/src/lib.rs | pub mod opt;
pub mod server;
pub mod session;
pub mod handler;
pub mod relay;
pub mod adapter;
pub mod fixed_reader;
pub use wasmer_term;
pub use wasmer_auth;
pub use wasmer_ssh;
pub use ate::utils; | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/session.rs | wasmer-instance/src/session.rs | use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::Mutex;
use std::collections::HashMap;
use tokio::sync::Mutex as AsyncMutex;
use ate::prelude::*;
use ate::comms::*;
use wasmer_deploy_cli::model::InstanceCall;
use wasmer_deploy_cli::model::InstanceCommand;
use wasmer_deploy_cli::model::InstanceHello;
use wasmer_deploy_cli::model::InstanceReply;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use wasmer_ssh::wasmer_os;
use wasmer_os::console::Console;
use tokio::sync::mpsc;
use std::future::Future;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use wasmer_os::api::ConsoleRect;
use wasmer_os::bus;
use wasmer_os::bus::*;
use wasmer_os::bus::BusError;
use wasmer_os::eval::EvalStatus;
use wasmer_os::environment::Environment;
use wasmer_os::api::System;
use wasmer_os::api::SystemAbiExt;
use wasmer_os::common::MAX_MPSC;
use wasmer_os::fd::WeakFd;
use wasmer_os::api::AsyncResult;
use wasmer_os::fd::Fd;
use wasmer_os::grammar::ast::Redirect;
use super::handler::SessionHandler;
use super::handler::SessionTx;
use super::server::SessionBasics;
pub struct Session
{
pub rx: Box<dyn StreamReadable + Send + Sync + 'static>,
pub tx: Option<Upstream>,
pub hello: HelloMetadata,
pub hello_instance: InstanceHello,
pub sock_addr: SocketAddr,
pub wire_encryption: Option<EncryptKey>,
pub rect: Arc<Mutex<ConsoleRect>>,
pub engine: Option<wasmer_os::wasmer::Engine>,
pub compiler: wasmer_os::eval::Compiler,
pub handler: Arc<SessionHandler>,
pub console: Console,
pub exit_rx: mpsc::Receiver<()>,
pub factories: HashMap<String, BusFactory>,
pub basics: SessionBasics,
pub invocations: SessionInvocations,
}
impl Session
{
pub async fn new(
rx: Box<dyn StreamReadable + Send + Sync + 'static>,
tx: Option<Upstream>,
hello: HelloMetadata,
hello_instance: InstanceHello,
sock_addr: SocketAddr,
wire_encryption: Option<EncryptKey>,
rect: Arc<Mutex<ConsoleRect>>,
engine: Option<wasmer_os::wasmer::Engine>,
compiler: wasmer_os::eval::Compiler,
basics: SessionBasics,
first_init: bool,
) -> Session
{
// Create the handler
let (exit_tx, exit_rx) = mpsc::channel(1);
let handler = SessionHandler {
tx: AsyncMutex::new(SessionTx::None),
rect: rect.clone(),
exit: exit_tx,
};
let handler = Arc::new(handler);
// Create the console
let id_str = basics.service_instance.id_str();
let prompt = (&id_str[0..9]).to_string();
let location = format!("ssh://wasmer.sh/?no_welcome&prompt={}", prompt);
let user_agent = "noagent".to_string();
let mut console = Console::new_ext(
location,
user_agent,
compiler,
handler.clone(),
None,
basics.fs.clone(),
basics.bins.clone(),
basics.reactor.clone(),
);
// If its the first init
if first_init {
console.init().await;
}
// We prepare the console which runs a few initialization steps
// that are needed before anything is invoked
console.prepare().await;
// Return the session
Session {
rx,
tx,
hello,
hello_instance,
sock_addr,
wire_encryption,
rect,
engine,
compiler,
exit_rx,
handler,
console,
factories: HashMap::default(),
basics,
invocations: SessionInvocations::default(),
}
}
pub async fn get_or_create_factory(&mut self, cmd: String) -> Option<&mut BusFactory>
{
// Check for existing
if self.factories.contains_key(&cmd) {
return Some(self.factories.get_mut(&cmd).unwrap());
}
// Create the job and context
let exec_factory = self.console.exec_factory();
let job = self.console.new_job().await?;
let ctx = exec_factory.create_context(self.console.new_spawn_context(&job));
let multiplexer = self.basics.multiplexer.clone();
// Create the process factory that used by this process to create sub-processes
let sub_process_factory = ProcessExecFactory::new(
self.console.reactor(),
self.engine.clone(),
self.compiler,
exec_factory,
ctx,
);
let bus_factory = BusFactory::new(sub_process_factory, multiplexer);
// Add the factory then return it
self.factories.insert(cmd.clone(), bus_factory);
return Some(self.factories.get_mut(&cmd).unwrap());
}
pub async fn run(mut self) -> Result<(), Box<dyn std::error::Error>>
{
// Start a queue that will send data back to the client
let (tx_reply, mut rx_reply) = mpsc::channel(MAX_MPSC);
let mut is_feeder_set = false;
// Wait for commands to come in and then process them
loop {
let invocations = self.invocations.clone();
tokio::select! {
cmd = self.rx.read() => {
let cmd = cmd?;
debug!("session read (len={})", cmd.len());
let action: InstanceCommand = serde_json::from_slice(&cmd[..])?;
debug!("session cmd ({})", action);
match action {
InstanceCommand::Shell => {
return self.shell().await;
}
InstanceCommand::Call(call) => {
// Set the handler to use the upstream via instance reply messages
if is_feeder_set == false {
is_feeder_set = true;
let mut guard = self.handler.tx.lock().await;
*guard = SessionTx::Feeder(tx_reply.clone());
}
// Invoke the call
let req = self.rx.read().await?;
self.call(call, req, tx_reply.clone()).await?;
}
}
}
reply = rx_reply.recv() => {
if let Some(reply) = reply {
let reply = bincode::serialize(&reply).unwrap();
if let Some(tx) = self.tx.as_mut() {
let _ = tx.outbox.write(&reply[..]).await;
}
}
}
_ = invocations => {
}
}
}
}
pub async fn shell(mut self) -> Result<(), Box<dyn std::error::Error>> {
info!("new connection from {}", self.sock_addr);
// Check the access code matches what was passed in
if self.hello_instance.access_token.eq_ignore_ascii_case(self.basics.service_instance.admin_token.as_str()) == false {
warn!("access denied to {} from {}", self.hello_instance.chain, self.sock_addr);
let err: CommsError = CommsErrorKind::FatalError("access denied".to_string()).into();
return Err(err.into());
}
// Set the handler to use the upstream tx directly
{
let mut guard = self.handler.tx.lock().await;
*guard = match self.tx {
Some(tx) => SessionTx::Upstream(tx),
None => SessionTx::None,
};
}
// Draw the prompt
self.console.tty_mut().draw_prompt().await;
// Enter a processing loop
loop {
let invocations = self.invocations.clone();
tokio::select! {
data = self.rx.read() => {
match data {
Ok(data) => {
let data = String::from_utf8_lossy(&data[..]);
self.console.on_data(data.into()).await;
}
Err(err) => {
info!("exiting from session ({}) - {}", self.basics.service_instance.id_str(), err);
break;
}
}
},
_ = self.exit_rx.recv() => {
info!("exiting from session ({})", self.basics.service_instance.id_str());
break;
}
_ = invocations => {
}
}
}
Ok(())
}
pub async fn eval(&mut self, binary: String, env: Environment, args: Vec<String>, redirects: Vec<Redirect>, stdin: Fd, stdout: Fd, stderr: Fd) -> Result<u32, Box<dyn std::error::Error>>
{
// Build the job and the environment
let job = self.console.new_job()
.await
.ok_or_else(|| {
let err: CommsError = CommsErrorKind::FatalError("no more job space".to_string()).into();
err
})?;
let mut ctx = self.console.new_spawn_context(&job);
ctx.stdin = stdin;
ctx.stdout = stdout;
ctx.stderr = stderr;
ctx.env = env;
ctx.extra_args = args;
ctx.extra_redirects = redirects;
let exec = self.console.exec_factory();
// Execute the binary
let mut eval = exec.eval(binary, ctx);
// Get the result and return the status code
let ret = eval.recv().await;
let ret = match ret {
Some(ret) => {
match ret.status {
EvalStatus::Executed { code, .. } => code,
_ => 1,
}
}
None => {
let err: CommsError = CommsErrorKind::FatalError("failed to evaluate binary".to_string()).into();
return Err(err.into());
}
};
Ok(ret)
}
pub async fn can_access_binary(&self, binary: &str, access_token: &str) -> bool
{
// Check the access code matches what was passed in
self.basics
.service_instance
.exports
.iter()
.await
.map_or(false, |iter| {
iter
.filter(|e| e.binary.eq_ignore_ascii_case(binary))
.any(|e| e.access_token.eq_ignore_ascii_case(access_token))
})
}
pub async fn call(&mut self, call: InstanceCall, request: Vec<u8>, tx_reply: mpsc::Sender<InstanceReply>) -> Result<(), Box<dyn std::error::Error>>
{
// Create the callbacks
let this_callback = SessionFeeder {
sys: System::default(),
tx_reply,
handle: call.handle.into(),
};
let feeder = this_callback.clone();
// Check the access code matches what was passed in
if self.basics.service_instance
.exports
.iter()
.await?
.filter(|e| e.binary.eq_ignore_ascii_case(call.binary.as_str()))
.any(|e| e.access_token.eq_ignore_ascii_case(self.hello_instance.access_token.as_str()))
== false
{
warn!("access denied to {}@{} from {}", call.binary, self.hello_instance.chain, self.sock_addr);
this_callback.error(BusError::AccessDenied);
return Ok(());
}
// Create the context
let caller_ctx = WasmCallerContext::default();
// Create the job and context
let launch_env = LaunchEnvironment {
abi: self.console.abi(),
inherit_stdin: WeakFd::null(),
inherit_stderr: self.console.stderr_fd().downgrade(),
inherit_stdout: self.console.stdout_fd().downgrade(),
inherit_log: self.console.stderr_fd().downgrade(),
};
// Invoke a call with using the console object
let bus_factory = self.get_or_create_factory(call.binary.clone())
.await
.ok_or_else(|| {
let err: CommsError = CommsErrorKind::FatalError("bus factory error - failed to create factory".to_string()).into();
err
})?;
// Now invoke it on the bus factory
let mut invoke = bus_factory.start(
call.parent.map(|a| a.into()),
call.handle.into(),
call.binary,
hash_topic(&call.topic),
call.format,
request,
caller_ctx.clone(),
launch_env
);
// Invoke the send operation
let sys = System::default();
let (abort_tx, mut abort_rx) = mpsc::channel(1);
let result = {
sys.spawn_shared(move || async move {
tokio::select! {
response = invoke.process() => {
response
}
_ = abort_rx.recv() => {
Err(BusError::Aborted)
}
}
})
};
// Add the invocation
let sessions = bus_factory.sessions();
self.invocations.push(SessionInvocation {
feeder,
result,
sessions,
_abort_tx: abort_tx,
});
Ok(())
}
}
pub struct SessionInvocation
{
feeder: SessionFeeder,
result: AsyncResult<Result<InvokeResult, BusError>>,
sessions: Arc<Mutex<HashMap<CallHandle, Box<dyn bus::Session>>>>,
_abort_tx: mpsc::Sender<()>,
}
#[derive(Default, Clone)]
pub struct SessionInvocations {
pub running: Arc<Mutex<Vec<SessionInvocation>>>,
}
impl SessionInvocations {
pub fn push(&self, invoke: SessionInvocation) {
let mut running = self.running.lock().unwrap();
running.push(invoke);
}
}
impl Future for SessionInvocations {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut running = self.running.lock().unwrap();
let mut carry = Vec::new();
for mut invoke in running.drain(..) {
let mut rx = Pin::new(&mut invoke.result.rx);
match rx.poll_recv(cx) {
Poll::Ready(Some(result)) => {
BusFeederUtils::process(&invoke.feeder, result, &invoke.sessions);
}
Poll::Ready(None) => {
BusFeederUtils::process(&invoke.feeder, Err(BusError::Aborted), &invoke.sessions);
}
Poll::Pending => {
carry.push(invoke);
}
}
}
running.append(&mut carry);
Poll::Pending
}
}
#[derive(Debug, Clone)]
pub struct SessionFeeder {
sys: System,
tx_reply: mpsc::Sender<InstanceReply>,
handle: CallHandle,
}
impl SessionFeeder {
fn send(&self, reply: InstanceReply) {
self.sys.fire_and_forget(&self.tx_reply, reply);
}
}
impl BusStatelessFeeder
for SessionFeeder {
fn feed_bytes(&self, format: SerializationFormat, data: Vec<u8>) {
trace!("feed-bytes(handle={}, data={} bytes)", self.handle, data.len());
self.send(InstanceReply::FeedBytes {
handle: self.handle,
format,
data
});
}
fn error(&self, err: BusError) {
trace!("error(handle={}, err={})", self.handle, err);
self.send(InstanceReply::Error {
handle: self.handle,
error: err
});
}
fn terminate(&self) {
trace!("terminate(handle={})", self.handle);
self.send(InstanceReply::Terminate {
handle: self.handle,
});
}
}
impl BusStatefulFeeder
for SessionFeeder {
fn handle(&self) -> CallHandle {
self.handle
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/adapter.rs | wasmer-instance/src/adapter.rs | use std::sync::Arc;
use std::path::Path;
use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;
use std::sync::Mutex;
use std::future::Future;
use std::task::Context;
use std::task::Poll;
use ate_files::accessor::FileAccessor;
use ate_files::accessor::RequestContext;
use wasmer_ssh::wasmer_os;
use wasmer_os::fs::MountedFileSystem;
use wasmer_os::bus::WasmCallerContext;
use wasmer_os::wasmer_vfs::*;
use wasmer_bus_fuse::api::FileSystemSimplified;
use wasmer_bus_fuse::api::OpenedFileSimplified;
use wasmer_bus_fuse::api::FileIOSimplified;
use wasmer_bus_fuse::api as backend;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
#[derive(Debug, Clone)]
pub struct FileAccessorAdapter
{
ctx: Arc<Mutex<Option<WasmCallerContext>>>,
inner: wasmer_deploy_cli::bus::file_system::FileSystem,
}
impl FileAccessorAdapter
{
pub fn new(accessor: &Arc<FileAccessor>) -> Self {
Self {
ctx: Arc::new(Mutex::new(None)),
inner: wasmer_deploy_cli::bus::file_system::FileSystem::new(
accessor.clone(),
RequestContext {
uid: 0,
gid: 0,
}
)
}
}
pub fn get_ctx(&self) -> WasmCallerContext
{
let guard = self.ctx.lock().unwrap();
guard.clone().unwrap_or_default()
}
fn block_on<Fut>(&self, fut: Fut) -> Result<Fut::Output>
where Fut: Future,
Fut: Send + 'static
{
let mut fut = Box::pin(fut);
tokio::task::block_in_place(move || {
let mut timer = None;
let waker = dummy_waker::dummy_waker();
let mut cx = Context::from_waker(&waker);
let mut tick_wait = 0u64;
loop {
// Attempt to process it
let fut = fut.as_mut();
if let Poll::Ready(a) = fut.poll(&mut cx) {
return Ok(a)
}
// Set the timer if there is none
if timer.is_none() {
timer.replace(std::time::Instant::now());
}
let timer = timer.as_ref().unwrap();
// Check the context to see if we need to terminate
{
let guard = self.ctx.lock().unwrap();
if let Some(ctx) = guard.as_ref() {
if ctx.should_terminate().is_some() {
return Err(FsError::Interrupted);
}
}
}
// If too much time has elapsed then fail
let elapsed = timer.elapsed();
if elapsed > std::time::Duration::from_secs(30) {
return Err(FsError::TimedOut);
}
// 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 MountedFileSystem
for FileAccessorAdapter
{
fn set_ctx(&self, ctx: &WasmCallerContext) {
let mut guard = self.ctx.lock().unwrap();
guard.replace(ctx.clone());
}
}
impl FileSystem
for FileAccessorAdapter
{
fn read_dir(&self, path: &Path) -> Result<ReadDir> {
let path = path.to_string_lossy().to_string();
let inner = self.inner.clone();
self.block_on(async move {
inner.read_dir(path).await
})?
.map_err(conv_fs_err)
.map(conv_dir)
}
fn create_dir(&self, path: &Path) -> Result<()> {
let path = path.to_string_lossy().to_string();
let inner = self.inner.clone();
self.block_on(async move {
inner.create_dir(path).await
})?
.map_err(conv_fs_err)?;
Ok(())
}
fn remove_dir(&self, path: &Path) -> Result<()> {
let path = path.to_string_lossy().to_string();
let inner = self.inner.clone();
self.block_on(async move {
inner.remove_dir(path).await
})?
.map_err(conv_fs_err)
}
fn rename(&self, from: &Path, to: &Path) -> Result<()> {
let from = from.to_string_lossy().to_string();
let to = to.to_string_lossy().to_string();
let inner = self.inner.clone();
self.block_on(async move {
inner.rename(from, to).await
})?
.map_err(conv_fs_err)
}
fn metadata(&self, path: &Path) -> Result<Metadata> {
let path = path.to_string_lossy().to_string();
let inner = self.inner.clone();
self.block_on(async move {
inner.read_metadata(path).await
})?
.map_err(conv_fs_err)
.map(conv_metadata)
}
fn symlink_metadata(&self, path: &Path) -> Result<Metadata> {
let path = path.to_string_lossy().to_string();
let inner = self.inner.clone();
self.block_on(async move {
inner.read_symlink_metadata(path).await
})?
.map_err(conv_fs_err)
.map(conv_metadata)
}
fn remove_file(&self, path: &Path) -> Result<()> {
let path = path.to_string_lossy().to_string();
let inner = self.inner.clone();
self.block_on(async move {
inner.remove_file(path).await
})?
.map_err(conv_fs_err)
}
fn new_open_options(&self) -> OpenOptions {
return OpenOptions::new(Box::new(FileAccessorOpener::new(self)));
}
}
#[derive(Debug)]
pub struct FileAccessorOpener {
fs: FileAccessorAdapter,
}
impl FileAccessorOpener {
pub fn new(fs: &FileAccessorAdapter) -> Self {
Self { fs: fs.clone() }
}
}
impl FileOpener for FileAccessorOpener {
fn open(
&mut self,
path: &Path,
conf: &OpenOptionsConfig,
) -> Result<Box<dyn VirtualFile + Send + Sync>> {
debug!("open: path={}", path.display());
let path = path.to_string_lossy().to_string();
let options = backend::OpenOptions {
read: conf.read(),
write: conf.write(),
create_new: conf.create_new(),
create: conf.create(),
append: conf.append(),
truncate: conf.truncate(),
};
let inner = self.fs.inner.clone();
let (file, io) = self.fs.block_on(async move {
let file = inner.open(path, options).await;
let io = file.io().await;
(file, io)
})?;
let io = io
.map_err(|_| FsError::BrokenPipe)?;
let of = file.clone();
let meta = self.fs.block_on(async move {
of.meta().await
})?
.map_err(conv_fs_err)?;
return Ok(Box::new(FileAccessorVirtualFile {
fs: self.fs.clone(),
of: file,
io,
meta,
dirty: conf.create_new() || conf.truncate(),
}));
}
}
#[derive(Debug)]
pub struct FileAccessorVirtualFile {
fs: FileAccessorAdapter,
of: Arc<wasmer_deploy_cli::bus::opened_file::OpenedFile>,
io: Arc<wasmer_deploy_cli::bus::file_io::FileIo>,
meta: backend::Metadata,
dirty: bool,
}
impl Drop
for FileAccessorVirtualFile
{
fn drop(&mut self) {
if self.dirty {
let _ = self.flush();
}
}
}
impl Seek for FileAccessorVirtualFile {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
let seek = match pos {
SeekFrom::Current(a) => backend::SeekFrom::Current(a),
SeekFrom::End(a) => backend::SeekFrom::End(a),
SeekFrom::Start(a) => backend::SeekFrom::Start(a),
};
let io = self.io.clone();
self.fs.block_on(async move {
io.seek(seek).await
})
.map_err(|_| conv_io_err(backend::FsError::ConnectionAborted))?
.map_err(conv_io_err)
}
}
impl Write for FileAccessorVirtualFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let buf = buf.to_vec();
let io = self.io.clone();
let ret = self.fs.block_on(async move {
io.write(buf).await
})
.map_err(|_| conv_io_err(backend::FsError::ConnectionAborted))?
.map_err(conv_io_err)
.map(|a| a as usize)?;
self.dirty = true;
Ok(ret)
}
fn flush(&mut self) -> io::Result<()> {
let io = self.io.clone();
self.fs.block_on(async move {
io.flush().await
})
.map_err(|_| conv_io_err(backend::FsError::ConnectionAborted))?
.map_err(conv_io_err)?;
self.dirty = false;
Ok(())
}
}
impl Read for FileAccessorVirtualFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let len = buf.len();
let io = self.io.clone();
let data = self.fs.block_on(async move {
io.read(len as u64).await
})
.map_err(|_| conv_io_err(backend::FsError::ConnectionAborted))?
.map_err(conv_io_err)?;
if data.len() <= 0 {
return Ok(0usize);
}
let dst = &mut buf[..data.len()];
dst.copy_from_slice(&data[..]);
Ok(data.len())
}
}
impl VirtualFile for FileAccessorVirtualFile {
fn last_accessed(&self) -> u64 {
self.meta.accessed
}
fn last_modified(&self) -> u64 {
self.meta.modified
}
fn created_time(&self) -> u64 {
self.meta.created
}
fn size(&self) -> u64 {
self.meta.len
}
fn set_len(&mut self, new_size: u64) -> Result<()> {
let of = self.of.clone();
self.fs.block_on(async move {
of.set_len(new_size).await
})?
.map_err(conv_fs_err)?;
self.dirty = true;
self.meta.len = new_size;
Ok(())
}
fn unlink(&mut self) -> Result<()> {
let of = self.of.clone();
self.fs.block_on(async move {
of.unlink().await
})?
.map_err(conv_fs_err)?;
self.dirty = false;
Ok(())
}
}
fn conv_dir(dir: backend::Dir) -> ReadDir {
ReadDir::new(
dir.data
.into_iter()
.map(|a| conv_dir_entry(a))
.collect::<Vec<_>>(),
)
}
fn conv_dir_entry(entry: backend::DirEntry) -> DirEntry {
DirEntry {
path: Path::new(entry.path.as_str()).to_owned(),
metadata: entry
.metadata
.ok_or_else(|| FsError::IOError)
.map(|a| conv_metadata(a)),
}
}
fn conv_metadata(metadata: backend::Metadata) -> Metadata {
Metadata {
ft: conv_file_type(metadata.ft),
accessed: metadata.accessed,
created: metadata.created,
modified: metadata.modified,
len: metadata.len,
}
}
fn conv_file_type(ft: backend::FileType) -> FileType {
FileType {
dir: ft.dir,
file: ft.file,
symlink: ft.symlink,
char_device: ft.char_device,
block_device: ft.block_device,
socket: ft.socket,
fifo: ft.fifo,
}
}
fn conv_io_err(err: wasmer_bus_fuse::api::FsError) -> io::Error {
err.into()
}
fn conv_fs_err(err: wasmer_bus_fuse::api::FsError) -> FsError {
use wasmer_bus_fuse::api::FsError as E;
match err {
E::BaseNotDirectory => FsError::BaseNotDirectory,
E::NotAFile => FsError::NotAFile,
E::InvalidFd => FsError::InvalidFd,
E::AlreadyExists => FsError::AlreadyExists,
E::Lock => FsError::Lock,
E::IOError => FsError::IOError,
E::AddressInUse => FsError::AddressInUse,
E::AddressNotAvailable => FsError::AddressNotAvailable,
E::BrokenPipe => FsError::BrokenPipe,
E::ConnectionAborted => FsError::ConnectionAborted,
E::ConnectionRefused => FsError::ConnectionRefused,
E::ConnectionReset => FsError::ConnectionReset,
E::Interrupted => FsError::Interrupted,
E::InvalidData => FsError::InvalidData,
E::InvalidInput => FsError::InvalidInput,
E::NotConnected => FsError::NotConnected,
E::EntityNotFound => FsError::EntityNotFound,
E::NoDevice => FsError::NoDevice,
E::PermissionDenied => FsError::PermissionDenied,
E::TimedOut => FsError::TimedOut,
E::UnexpectedEof => FsError::UnexpectedEof,
E::WouldBlock => FsError::WouldBlock,
E::WriteZero => FsError::WriteZero,
E::DirectoryNotEmpty => FsError::DirectoryNotEmpty,
E::UnknownError => FsError::UnknownError,
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/relay.rs | wasmer-instance/src/relay.rs | use ate::comms::{StreamRx, Upstream};
/// Relays a web socket connection over to another server that
/// is currently hosting this particular instance
pub struct Relay
{
pub rx: StreamRx,
pub tx: Upstream,
}
impl Relay
{
pub async fn run(self) -> Result<(), Box<dyn std::error::Error>>
{
Ok(())
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/fixed_reader.rs | wasmer-instance/src/fixed_reader.rs | use std::io;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use bytes::Bytes;
use tokio::io::AsyncRead;
use tokio::io::ReadBuf;
use ate_comms::StreamReadable;
use async_trait::async_trait;
pub struct FixedReader
{
data: Option<Bytes>,
}
impl FixedReader
{
pub fn new(data: Vec<u8>) -> FixedReader
{
FixedReader {
data: Some(Bytes::from(data))
}
}
}
impl AsyncRead
for FixedReader
{
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>>
{
if let Some(data) = self.data.take() {
if data.len() <= buf.remaining() {
buf.put_slice(&data[..]);
} else {
let end = buf.remaining();
buf.put_slice(&data[..end]);
self.data.replace(data.slice(end..));
}
}
Poll::Ready(Ok(()))
}
}
#[async_trait]
impl StreamReadable
for FixedReader
{
async fn read(&mut self) -> io::Result<Vec<u8>> {
if let Some(data) = self.data.take() {
Ok(data.to_vec())
} else {
Ok(Vec::new())
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/server.rs | wasmer-instance/src/server.rs | use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use ate::comms::RawWebRoute;
use wasmer_ssh::wasmer_os::environment::Environment;
use wasmer_ssh::wasmer_os::fd::FdMsg;
use error_chain::bail;
#[allow(unused_imports)]
use tokio::sync::mpsc;
use async_trait::async_trait;
use ate::comms::HelloMetadata;
use ate::comms::RawStreamRoute;
use ate::comms::StreamRoute;
use ate::comms::StreamRx;
use ate::comms::StreamReadable;
use ate::comms::MessageProtocolVersion;
use ate::comms::Upstream;
use ate::prelude::*;
use ate_files::repo::Repository;
use ate_files::repo::RepositorySessionFactory;
use wasmer_ssh::wasmer_os::api::System;
use wasmer_ssh::wasmer_os::api::SystemAbiExt;
use wasmer_deploy_cli::model::InstanceHello;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use percent_encoding::{percent_decode};
use wasmer_deploy_cli::model::MasterAuthority;
use wasmer_deploy_cli::model::ServiceInstance;
use wasmer_deploy_cli::model::InstanceReply;
use wasmer_deploy_cli::model::INSTANCE_ROOT_ID;
use wasmer_deploy_cli::model::MASTER_AUTHORITY_ID;
#[allow(unused_imports)]
use wasmer_deploy_cli::model::InstanceCall;
use wasmer_ssh::wasmer_os;
use wasmer_os::api::ConsoleRect;
use wasmer_os::fs::UnionFileSystem;
use wasmer_os::bin_factory::*;
use wasmer_os::reactor::Reactor;
use wasmer_os::bus::SubProcessMultiplexer;
use wasmer_os::pipe::pipe_in;
use wasmer_os::pipe::pipe_out;
use wasmer_os::fd::FdFlag;
use wasmer_os::pipe::ReceiverMode;
use wasmer_os::grammar::ast::Redirect;
use wasmer_os::grammar::ast::RedirectionType;
use wasmer_auth::cmd::impersonate_command;
use wasmer_auth::helper::b64_to_session;
use ttl_cache::TtlCache;
use tokio::sync::RwLock;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use http::StatusCode;
use crate::adapter::FileAccessorAdapter;
use crate::session::Session;
use crate::fixed_reader::FixedReader;
#[derive(Clone)]
pub struct SessionBasics {
pub fs: UnionFileSystem,
pub bins: BinFactory,
pub reactor: Arc<RwLock<Reactor>>,
pub service_instance: DaoMut<ServiceInstance>,
pub multiplexer: SubProcessMultiplexer
}
pub struct Server
{
pub system: System,
pub registry: Arc<Registry>,
pub repo: Arc<Repository>,
pub db_url: url::Url,
pub auth_url: url::Url,
pub engine: Option<wasmer_os::wasmer::Engine>,
pub compiler: wasmer_os::eval::Compiler,
pub compiled_modules: Arc<CachedCompiledModules>,
pub instance_authority: String,
pub sessions: RwLock<TtlCache<ChainKey, SessionBasics>>,
pub ttl: Duration,
}
impl Server
{
pub async fn new(
db_url: Url,
auth_url: Url,
instance_authority: String,
token_path: String,
registry: Arc<Registry>,
compiler: wasmer_os::eval::Compiler,
compiled_modules: Arc<CachedCompiledModules>,
ttl: Duration,
) -> Result<Self, Box<dyn std::error::Error>>
{
// Build a session factory that will load the session for this instance using the broker key
let session_factory = SessionFactory {
db_url: db_url.clone(),
auth_url: auth_url.clone(),
registry: registry.clone(),
token_path: token_path.clone(),
instance_authority: instance_authority.clone(),
edge_session_cache: Arc::new(tokio::sync::Mutex::new(None)),
};
let repo = Repository::new(
®istry,
db_url.clone(),
auth_url.clone(),
Box::new(session_factory),
ttl,
)
.await?;
let sessions = RwLock::new(TtlCache::new(usize::MAX));
let engine = compiler.new_engine();
Ok(Self {
system: System::default(),
db_url,
auth_url,
registry,
repo,
engine,
compiler,
compiled_modules,
instance_authority,
sessions,
ttl,
})
}
pub async fn get_or_create_session_basics(&self, key: ChainKey) -> Result<(SessionBasics, bool), CommsError> {
// Check the cache
{
let guard = self.sessions.read().await;
if let Some(ret) = guard.get(&key) {
return Ok((ret.clone(), false));
}
}
// Open the instance chain that backs this particular instance
// (this will reuse accessors across threads and calls)
let accessor = self.repo.get_accessor(&key, self.instance_authority.as_str()).await
.map_err(|err| CommsErrorKind::InternalError(err.to_string()))?;
let mut fs = wasmer_os::fs::create_root_fs(Some(Box::new(FileAccessorAdapter::new(&accessor))));
fs.solidify();
trace!("loaded file file system for {}", key);
// Load the service instance object
let _chain = accessor.chain.clone();
let chain_dio = accessor.dio.clone().as_mut().await;
trace!("loading service instance with key {}", PrimaryKey::from(INSTANCE_ROOT_ID));
let service_instance = chain_dio.load::<ServiceInstance>(&PrimaryKey::from(INSTANCE_ROOT_ID)).await?;
// Enter a write lock and check again
let mut guard = self.sessions.write().await;
if let Some(ret) = guard.get(&key) {
return Ok((ret.clone(), false));
}
// Create the bin factory
let bins = BinFactory::new(self.compiled_modules.clone());
let reactor = Arc::new(RwLock::new(Reactor::new()));
let multiplexer = SubProcessMultiplexer::new();
// Build the basics
let basics = SessionBasics {
fs,
bins,
reactor,
service_instance,
multiplexer,
};
// Cache and and return it
let ret = basics.clone();
guard.insert(key.clone(), basics, self.ttl);
Ok((ret, true))
}
pub async fn new_session(
&self,
rx: StreamRx,
tx: Upstream,
hello: HelloMetadata,
hello_instance: InstanceHello,
sock_addr: SocketAddr,
wire_encryption: Option<EncryptKey>,
) -> Result<Session, CommsError>
{
// Get or create the basics that make up a new session
let key = hello_instance.chain.clone();
let (basics, first_init) = self.get_or_create_session_basics(key.clone()).await?;
// Build the session
let rx = Box::new(rx);
let ret = Session::new(
rx,
Some(tx),
hello,
hello_instance,
sock_addr,
wire_encryption,
Arc::new(Mutex::new(ConsoleRect { cols: 80, rows: 25 })),
self.engine.clone(),
self.compiler.clone(),
basics.clone(),
first_init
).await;
Ok(ret)
}
async fn accept_internal(
&self,
rx: StreamRx,
tx: Upstream,
hello: HelloMetadata,
hello_instance: InstanceHello,
sock_addr: SocketAddr,
wire_encryption: Option<EncryptKey>,
) -> Result<(), CommsError>
{
// Create the session
let session = self.new_session(
rx,
tx,
hello,
hello_instance,
sock_addr,
wire_encryption
).await?;
// Start the background thread that will process events on the session
self.system.fork_shared(|| async move {
if let Err(err) = session.run().await {
debug!("instance session failed: {}", err);
}
});
Ok(())
}
}
#[async_trait]
impl StreamRoute
for Server
{
async fn accepted_web_socket(
&self,
mut rx: StreamRx,
_rx_proto: StreamProtocol,
tx: Upstream,
hello: HelloMetadata,
sock_addr: SocketAddr,
wire_encryption: Option<EncryptKey>,
) -> Result<(), CommsError>
{
// Read the instance hello message
let hello_buf = rx.read().await?;
let hello_instance: InstanceHello = serde_json::from_slice(&hello_buf[..])?;
debug!("accept-web-socket: {}", hello_instance);
// Accept the web connection
self.accept_internal(
rx,
tx,
hello,
hello_instance,
sock_addr,
wire_encryption
).await
}
}
#[async_trait]
impl RawStreamRoute
for Server
{
async fn accepted_raw_web_socket(
&self,
rx: Box<dyn AsyncRead + Send + Sync + Unpin + 'static>,
tx: Box<dyn AsyncWrite + Send + Sync + Unpin + 'static>,
uri: http::Uri,
headers: http::HeaderMap,
sock_addr: SocketAddr,
server_id: NodeId,
) -> Result<(), CommsError>
{
// Create the upstream
let (rx, tx) = MessageProtocolVersion::V3
.create(Some(rx), Some(tx))
.split(None);
let tx = Upstream {
id: NodeId::generate_client_id(),
outbox: tx,
wire_format: SerializationFormat::Json,
};
// Get the chain and the topic
let path = std::path::PathBuf::from(uri.path().to_string());
let chain = {
let mut path_iter = path.iter();
path_iter.next();
path_iter.next()
.map(|a| a.to_string_lossy().to_string())
.ok_or_else(|| {
CommsErrorKind::InternalError(format!("instance web_socket path is invalid - {}", uri))
})?
};
let chain = ChainKey::new(chain.clone());
// Get the authorization
if headers.contains_key(http::header::AUTHORIZATION) == false {
bail!(CommsErrorKind::Refused);
}
let auth = headers[http::header::AUTHORIZATION].clone();
debug!("accept-raw-web-socket: uri: {}", uri);
// Make a fake hello from the HTTP metadata
let hello = HelloMetadata {
client_id: NodeId::generate_client_id(),
server_id,
path: path.to_string_lossy().to_string(),
encryption: None,
wire_format: tx.wire_format,
};
let hello_instance = InstanceHello {
access_token: auth.to_str().unwrap().to_string(),
chain: chain.clone(),
};
// Accept the web connection
self.accept_internal(
rx,
tx,
hello,
hello_instance,
sock_addr,
None
).await
}
}
#[async_trait]
impl RawWebRoute
for Server
{
#[allow(unused_variables)]
async fn accepted_raw_put_request(
&self,
uri: http::Uri,
headers: http::HeaderMap,
sock_addr: SocketAddr,
server_id: NodeId,
body: Vec<u8>,
) -> Result<Vec<u8>, (Vec<u8>, StatusCode)>
{
// Get the chain and the topic
let path = std::path::PathBuf::from(uri.path().to_string());
let (chain, binary, topic) = {
let mut path_iter = path.iter().map(|a| a.to_string_lossy().to_string());
path_iter.next();
path_iter.next();
let identity = path_iter.next();
let db = path_iter.next();
let binary = path_iter.next();
let topic = path_iter.next();
if identity.is_none() || db.is_none() || binary.is_none() || topic.is_none() {
let msg = format!("The URL path is malformed").as_bytes().to_vec();
return Err((msg, StatusCode::BAD_REQUEST));
}
let identity = identity.unwrap();
let db = db.unwrap();
let binary = binary.unwrap();
let topic = topic.unwrap();
let chain = format!("{}/{}", identity, db);
(chain, binary, topic)
};
let chain = ChainKey::new(chain);
// Get the authorization
if headers.contains_key(http::header::AUTHORIZATION) == false {
let msg = format!("Missing the Authorization header").as_bytes().to_vec();
return Err((msg, StatusCode::UNAUTHORIZED));
}
let auth = headers[http::header::AUTHORIZATION].clone();
// Get and check the data format
if headers.contains_key(http::header::CONTENT_TYPE) == false {
let msg = format!("Must supply a content type in the request").as_bytes().to_vec();
return Err((msg, StatusCode::BAD_REQUEST));
}
let format = match headers[http::header::CONTENT_TYPE].to_str().unwrap() {
"text/xml" |
"application/xml" |
"application/xhtml+xml" => SerializationFormat::Xml,
"application/octet-stream" => SerializationFormat::Raw,
"application/json" |
"application/x-javascript" |
"application/ld+json" |
"text/javascript" |
"text/x-javascript" |
"text/x-json" => SerializationFormat::Json,
"text/x-yaml" |
"text/yaml" |
"text/yml" |
"application/x-yaml" |
"application/x-yml" |
"application/yaml" |
"application/yml" => SerializationFormat::Yaml,
a => {
let msg = format!("Unsupported http content type [{}]", a).as_bytes().to_vec();
return Err((msg, StatusCode::BAD_REQUEST));
}
};
debug!("accept-raw-put-request: uri: {} (format={})", uri, format);
// Make a fake hello from the HTTP metadata
let hello = HelloMetadata {
client_id: NodeId::generate_client_id(),
server_id,
path: path.to_string_lossy().to_string(),
encryption: None,
wire_format: SerializationFormat::Json,
};
let hello_instance = InstanceHello {
access_token: auth.to_str().unwrap().to_string(),
chain: chain.clone(),
};
// Get or create the basics that make up a new session
let key = hello_instance.chain.clone();
let (basics, first_init) = self.get_or_create_session_basics(key.clone())
.await
.map_err(|err| {
let msg = format!("instance call failed - {}", err).as_bytes().to_vec();
(msg, StatusCode::INTERNAL_SERVER_ERROR)
})?;
// Create a fixed reader
let rx: Box<dyn StreamReadable + Send + Sync + Unpin + 'static> = Box::new(FixedReader::new(Vec::new()));
// Build the session
let mut session = Session::new(
rx,
None,
hello,
hello_instance,
sock_addr,
None,
Arc::new(Mutex::new(ConsoleRect { cols: 80, rows: 25 })),
self.engine.clone(),
self.compiler.clone(),
basics.clone(),
first_init
).await;
// Validate we can access this binary
if session.can_access_binary(binary.as_str(), auth.to_str().unwrap()).await == false {
let msg = format!("Access Denied (Invalid Token)").as_bytes().to_vec();
return Err((msg, StatusCode::UNAUTHORIZED));
}
// Invoke the call
let (tx_reply, mut rx_reply) = mpsc::channel(1);
session.call(InstanceCall {
parent: None,
handle: fastrand::u64(..),
format,
binary,
topic,
},
body,
tx_reply,
)
.await
.map_err(|err: Box<dyn std::error::Error>| {
let msg = format!("instance call failed - {}", err).as_bytes().to_vec();
(msg, StatusCode::INTERNAL_SERVER_ERROR)
})?;
// Read the result and pump it
loop {
let invocations = session.invocations.clone();
tokio::select! {
reply = rx_reply.recv() => {
if let Some(reply) = reply {
match reply {
InstanceReply::FeedBytes { data, .. } => {
return Ok(data);
}
InstanceReply::Stderr { data } => {
trace!("{}", String::from_utf8_lossy(&data[..]));
},
InstanceReply::Stdout { data } => {
trace!("{}", String::from_utf8_lossy(&data[..]));
},
err => {
let msg = format!("Instance call failed - {}", err).as_bytes().to_vec();
return Err((msg, StatusCode::BAD_GATEWAY));
}
}
} else {
break;
}
},
_ = invocations => { }
}
}
let msg = format!("Instance call aborted before finishing").as_bytes().to_vec();
Err((msg, StatusCode::NOT_ACCEPTABLE))
}
#[allow(unused_variables)]
async fn accepted_raw_post_request(
&self,
uri: http::Uri,
headers: http::HeaderMap,
sock_addr: SocketAddr,
server_id: NodeId,
body: Vec<u8>,
) -> Result<Vec<u8>, (Vec<u8>, StatusCode)>
{
// Get the chain and the binary
let mut args = Vec::new();
let mut redirects = Vec::new();
let path = std::path::PathBuf::from(uri.path().to_string());
let (chain, binary) = {
let mut path_iter = path.iter().map(|a| a.to_string_lossy().to_string());
path_iter.next();
path_iter.next();
let identity = path_iter.next();
let db = path_iter.next();
let binary = path_iter.next();
if identity.is_none() || db.is_none() || binary.is_none() {
let msg = format!("The URL path is malformed").as_bytes().to_vec();
return Err((msg, StatusCode::BAD_REQUEST));
}
let identity = identity.unwrap();
let db = db.unwrap();
let binary = binary.unwrap();
while let Some(arg) = path_iter.next() {
let arg = percent_decode(arg.as_bytes());
let arg = arg.decode_utf8_lossy().to_string();
if let Some((lhr, mut rhs)) = arg.split_once(">") {
if let Ok(fd) = i32::from_str(lhr) {
let op = if rhs.starts_with(">") {
rhs = &rhs[1..];
RedirectionType::APPEND
} else if rhs.starts_with("|") {
rhs = &rhs[1..];
RedirectionType::CLOBBER
} else if rhs.starts_with("&") {
rhs = &rhs[1..];
RedirectionType::TOFD
} else { RedirectionType::TO };
redirects.push(Redirect {
fd,
op,
filename: rhs.to_string(),
});
continue;
}
}
args.push(arg);
}
let chain = format!("{}/{}", identity, db);
(chain, binary)
};
let chain = ChainKey::new(chain);
// Get the authorization
if headers.contains_key(http::header::AUTHORIZATION) == false {
let msg = format!("Missing the Authorization header").as_bytes().to_vec();
return Err((msg, StatusCode::UNAUTHORIZED));
}
let auth = headers[http::header::AUTHORIZATION].clone();
// Make a fake hello from the HTTP metadata
let hello = HelloMetadata {
client_id: NodeId::generate_client_id(),
server_id,
path: path.to_string_lossy().to_string(),
encryption: None,
wire_format: SerializationFormat::Json,
};
let hello_instance = InstanceHello {
access_token: auth.to_str().unwrap().to_string(),
chain: chain.clone(),
};
// Get or create the basics that make up a new session
let key = hello_instance.chain.clone();
let (basics, first_init) = self.get_or_create_session_basics(key.clone())
.await
.map_err(|err| {
debug!("instance eval failed - {}", err);
(Vec::new(), StatusCode::INTERNAL_SERVER_ERROR)
})?;
// Build the session
let rx = Box::new(FixedReader::new(Vec::new()));
let mut session = Session::new(
rx,
None,
hello,
hello_instance,
sock_addr,
None,
Arc::new(Mutex::new(ConsoleRect { cols: 80, rows: 25 })),
self.engine.clone(),
self.compiler.clone(),
basics.clone(),
first_init
).await;
// Validate we can access this binary
if session.can_access_binary(binary.as_str(), auth.to_str().unwrap()).await == false {
let msg = format!("Access Denied (Invalid Token)").as_bytes().to_vec();
return Err((msg, StatusCode::UNAUTHORIZED));
}
debug!("accept-raw-post-request: uri: {}", uri);
// Build an environment from the query string
let mut env = Environment::default();
if let Some(query) = uri.query() {
for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
env.set_var(&k, v.to_string());
}
}
// Create the stdin pipe
let (stdin, body_tx) = pipe_in(ReceiverMode::Stream, FdFlag::Stdin(false));
let _ = body_tx.send(FdMsg::Data { data: body, flag: FdFlag::Stdin(false) }).await;
let _ = body_tx.send(FdMsg::Data { data: Vec::new(), flag: FdFlag::Stdin(false) }).await;
drop(body_tx);
// Create a stdout pipe that will gather the return data
let (mut stdout, ret_rx) = pipe_out(FdFlag::Stdout(false));
let (mut stderr, err_rx) = pipe_out(FdFlag::Stdout(false));
stdout.set_ignore_flush(true);
stderr.set_ignore_flush(true);
// Evaluate the binary until its finished
let exit_code = session.eval(binary, env, args, redirects, stdin, stdout, stderr)
.await
.map_err(|err: Box<dyn std::error::Error>| {
let msg = format!("instance eval failed - {}", err).as_bytes().to_vec();
(msg, StatusCode::INTERNAL_SERVER_ERROR)
})?;
drop(session);
// Read all the data
let ret = read_to_end(ret_rx).await;
debug!("eval returned {} bytes", ret.len());
// Convert the error code to a status code
match exit_code {
0 => Ok(ret),
_ => {
let err = read_to_end(err_rx).await;
Err((err, StatusCode::INTERNAL_SERVER_ERROR))
}
}
}
}
async fn read_to_end(mut rx: mpsc::Receiver<FdMsg>) -> Vec<u8>
{
let mut ret = Vec::new();
while let Some(msg) = rx.recv().await {
match msg {
FdMsg::Data { mut data, .. } => {
ret.append(&mut data);
}
FdMsg::Flush { .. } => { }
}
}
ret
}
struct SessionFactory
{
db_url: url::Url,
auth_url: url::Url,
token_path: String,
registry: Arc<Registry>,
instance_authority: String,
edge_session_cache: Arc<tokio::sync::Mutex<Option<AteSessionGroup>>>,
}
#[async_trait]
impl RepositorySessionFactory
for SessionFactory
{
async fn create(&self, sni: String, key: ChainKey) -> Result<AteSessionType, AteError>
{
let edge_session = {
let mut edge_session_cache = self.edge_session_cache.lock().await;
if edge_session_cache.is_none() {
// First we need to get the edge session that has the rights to
// access this domain
let path = shellexpand::tilde(self.token_path.as_str()).to_string();
let session = if let Ok(token) = std::fs::read_to_string(path) {
b64_to_session(token)
} else {
let err: wasmer_auth::error::GatherError = wasmer_auth::error::GatherErrorKind::NoMasterKey.into();
return Err(err.into());
};
// Now we gather the rights to the instance domain that is capable of running these instances
let edge_session = impersonate_command(
&self.registry,
self.instance_authority.clone(),
session.clone_inner(),
self.auth_url.clone(),
).await?;
edge_session_cache.replace(edge_session);
}
edge_session_cache.clone().unwrap()
};
// Now we read the chain of trust and attempt to get the master authority object
let chain = self.registry.open(&self.db_url, &key, false).await?;
let dio = chain.dio(&edge_session).await;
let master_authority = dio.load::<MasterAuthority>(&PrimaryKey::from(MASTER_AUTHORITY_ID)).await?;
/*
- Debugging code
error!("{}", edge_session);
use std::ops::Deref;
error!("{}", master_authority.deref());
*/
// Get the private key and use it to access the authority for this chain
let access_key = if let Some(key) = edge_session
.private_read_keys(AteSessionKeyCategory::AllKeys)
.filter(|k| k.hash() == master_authority.inner_broker.ek_hash())
.next() {
key.clone()
} else {
error!("failed to get the broker key from the master edge session");
let err: wasmer_auth::error::GatherError = wasmer_auth::error::GatherErrorKind::NoMasterKey.into();
return Err(err.into());
};
let master_authority = master_authority.inner_broker.unwrap(&access_key)?;
// Build the session using the master authority
let mut chain_session = AteSessionUser::default();
chain_session.add_user_read_key(&master_authority.read);
chain_session.add_user_write_key(&master_authority.write);
chain_session.add_user_uid(0);
let mut chain_session = AteSessionGroup::new(AteSessionInner::User(chain_session), sni);
chain_session.add_group_gid(&AteRolePurpose::Observer, 0);
chain_session.add_group_gid(&AteRolePurpose::Contributor, 0);
chain_session.add_group_read_key(&AteRolePurpose::Observer, &master_authority.read);
chain_session.add_group_write_key(&AteRolePurpose::Contributor, &master_authority.write);
Ok(AteSessionType::Group(chain_session))
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/handler.rs | wasmer-instance/src/handler.rs | use async_trait::async_trait;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::Arc;
use std::sync::Mutex;
use tokio::sync::Mutex as AsyncMutex;
use wasmer_ssh::wasmer_os;
use ate::comms::*;
use wasmer_os::api::ConsoleAbi;
use wasmer_os::api::ConsoleRect;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use tokio::sync::mpsc;
use wasmer_deploy_cli::model::InstanceReply;
pub enum SessionTx {
None,
Upstream(Upstream),
Feeder(mpsc::Sender<InstanceReply>),
}
pub struct SessionHandler
{
pub tx: AsyncMutex<SessionTx>,
pub rect: Arc<Mutex<ConsoleRect>>,
pub exit: mpsc::Sender<()>,
}
impl SessionHandler
{
async fn stdout_internal(&self, data: Vec<u8>, is_err: bool) {
let mut tx = self.tx.lock().await;
if data.len() > 0 {
match tx.deref_mut() {
SessionTx::None => { }
SessionTx::Upstream(tx) => {
if let Err(err) = tx.outbox.write(&data[..]).await {
debug!("writing failed - will close the channel now - {}", err);
self.exit().await;
}
}
SessionTx::Feeder(tx) => {
let msg = if is_err {
InstanceReply::Stderr { data }
} else {
InstanceReply::Stdout { data }
};
let _ = tx.send(msg).await;
}
}
}
}
}
#[async_trait]
impl ConsoleAbi
for SessionHandler
{
async fn stdout(&self, data: Vec<u8>) {
self.stdout_internal(data, false).await;
}
async fn stderr(&self, data: Vec<u8>) {
self.stdout_internal(data, true).await;
}
async fn flush(&self) {
}
async fn log(&self, text: String) {
trace!("{}", text);
}
async fn console_rect(&self) -> ConsoleRect {
let rect = self.rect.lock().unwrap();
rect.deref().clone()
}
async fn cls(&self) {
let txt = format!("{}[2J", 27 as char);
let data = txt.as_bytes().to_vec();
self.stdout(data).await;
}
async fn exit(&self) {
{
let mut tx = self.tx.lock().await;
match tx.deref_mut() {
SessionTx::None => { }
SessionTx::Upstream(tx) => {
let _ = tx.close().await;
}
SessionTx::Feeder(tx) => {
let _ = tx.send(InstanceReply::Exit).await;
}
}
}
let _ = self.exit.send(()).await;
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/opt/session_server.rs | wasmer-instance/src/opt/session_server.rs | #[allow(unused_imports, dead_code)]
use tracing::{info, error, debug};
use ate::{prelude::*};
use clap::Parser;
use wasmer_ssh::wasmer_os;
/// Runs the session server
#[derive(Parser)]
pub struct OptsSessionServer {
/// Optional list of the nodes that make up this cluster
#[clap(long)]
pub nodes_list: Option<String>,
/// IP address that the datachain server will isten on
#[clap(short, long, default_value = "::")]
pub listen: IpAddr,
/// Port that the server will listen on for HTTP requests which are then turned into websocket
#[clap(long)]
pub port: Option<u16>,
/// Forces Wasmer to listen on a specific port for HTTPS requests with generated certificates
#[clap(long)]
pub tls_port: Option<u16>,
/// Token file to read that holds a previously created token to be used for this operation
#[clap(long, default_value = "~/wasmer/token")]
pub token_path: String,
/// Location where cached compiled modules are stored
#[clap(long, default_value = "~/wasmer/compiled")]
pub compiler_cache_path: String,
/// URL where the web data is remotely stored on a distributed commit log.
#[clap(short, long, default_value = "ws://wasmer.sh/db")]
pub db_url: url::Url,
/// URL of the authentication servers
#[clap(long, default_value = "ws://wasmer.sh/auth")]
pub auth_url: url::Url,
/// Domain name that has authority on instances
#[clap(long, default_value = "wasmer.sh")]
pub instance_authority: String,
/// Ensures that this combined server(s) runs as a specific node_id
#[clap(short, long)]
pub node_id: Option<u32>,
/// Location where the native binary files are stored
#[clap(long, default_value = "wasmer.sh/www")]
pub native_files: String,
/// Uses a local directory for native files rather than the published ate chain
#[clap(long)]
pub native_files_path: Option<String>,
/// Determines which compiler to use
#[clap(short, long, default_value = "default")]
pub compiler: wasmer_os::eval::Compiler,
/// Time-to-live for sessions that are initiated
#[clap(long, default_value = "300")]
pub ttl: u64,
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/opt/core.rs | wasmer-instance/src/opt/core.rs | #[allow(unused_imports, dead_code)]
use tracing::{info, error, debug};
use ate::prelude::*;
use clap::Parser;
use super::*;
#[derive(Parser)]
#[clap(version = "1.0", author = "Wasmer Inc <info@wasmer.io>")]
pub struct Opts {
/// Sets the level of log verbosity, can be used multiple times
#[allow(dead_code)]
#[clap(short, long, parse(from_occurrences))]
pub verbose: i32,
/// Logs debug info to the console
#[clap(short, long)]
pub debug: bool,
/// Determines if ATE will use DNSSec or just plain DNS
#[clap(long)]
pub dns_sec: bool,
/// Address that DNS queries will be sent to
#[clap(long, default_value = "8.8.8.8")]
pub dns_server: String,
/// Token file to read that holds a previously created token to be used for this operation
#[clap(long, default_value = "~/wasmer/token")]
pub token_path: String,
/// Path to the certificate file that will be used by an listening servers
/// (there must be TXT records in the host domain servers for this cert)
#[clap(long, default_value = "~/wasmer/cert")]
pub cert_path: String,
/// Path to the secret server key
#[clap(default_value = "~/wasmer/ssh.server.key")]
pub ssh_key_path: String,
/// Indicates if ATE will use quantum resistant wire encryption (possible values
/// are 128, 192, 256). When running in 'centralized' mode wire encryption will
/// default to 128bit however when running in 'distributed' mode wire encryption
/// will default to off unless explicitly turned on.
#[clap(long, default_value = "128")]
pub wire_encryption: KeySize,
#[clap(subcommand)]
pub subcmd: SubCommand,
}
#[derive(Parser)]
pub enum SubCommand {
/// Hosts the session server
#[clap()]
Run(OptsSessionServer),
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/opt/mod.rs | wasmer-instance/src/opt/mod.rs | mod core;
mod session_server;
pub use self::core::*;
pub use session_server::*; | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-instance/src/bin/wasmer-instance.rs | wasmer-instance/src/bin/wasmer-instance.rs | #![recursion_limit="256"]
use ate::mesh::MeshHashTable;
use ate::utils::load_node_list;
use wasmer_instance::server::Server;
use tokio::sync::watch;
#[allow(unused_imports, dead_code)]
use tracing::{info, error, debug, trace, warn};
use ate::prelude::*;
use std::sync::Arc;
use clap::Parser;
use tokio::sync::watch::Receiver;
use tokio::select;
use tokio::runtime::Builder;
use wasmer_ssh::wasmer_os;
use wasmer_os::bin_factory::CachedCompiledModules;
use wasmer_ssh::native_files::NativeFileType;
use ate::comms::StreamRouter;
use wasmer_auth::helper::try_load_key;
use wasmer_instance::opt::*;
fn ctrl_channel() -> Receiver<bool> {
let (sender, receiver) = tokio::sync::watch::channel(false);
ctrlc::set_handler(move || {
let _ = sender.send(true);
}).unwrap();
receiver
}
fn main() -> Result<(), Box<dyn std::error::Error>>
{
// Create the runtime
let runtime = Arc::new(Builder::new_multi_thread().enable_all().build().unwrap());
let opts: Opts = Opts::parse();
//let opts = main_debug();
ate::log_init(opts.verbose, opts.debug);
let cert: PrivateEncryptKey = match try_load_key(opts.cert_path.clone()) {
Some(a) => a,
None => {
eprintln!("Failed to load the certificate ({}) - you must generate this first!", opts.cert_path);
std::process::exit(1);
}
};
ate::mesh::add_global_certificate(&cert.hash());
let mut conf = AteConfig::default();
conf.dns_sec = opts.dns_sec.clone();
conf.dns_server = opts.dns_server.clone();
let ret = runtime.clone().block_on(async move {
match opts.subcmd {
SubCommand::Run(solo) => {
conf.nodes = load_node_list(solo.nodes_list);
let protocol = StreamProtocol::parse(&solo.inst_url)?;
let port = solo.auth_url.port().unwrap_or(protocol.default_port());
let domain = solo.auth_url.domain().unwrap_or("localhost").to_string();
let ttl = std::time::Duration::from_secs(solo.ttl);
let nodes = load_node_list(solo.nodes_list);
let mut cfg_mesh = ConfMesh::skeleton(&conf, domain, port, solo.node_id).await?;
cfg_mesh.wire_protocol = protocol;
cfg_mesh.wire_encryption = Some(opts.wire_encryption);
cfg_mesh.listen_certificate = Some(cert);
let table = MeshHashTable::new(&cfg_mesh);
let server_id = table.compute_node_id(solo.node_id)?;
let registry = Arc::new(Registry::new(&conf).await);
let native_files = if let Some(path) = solo.native_files_path.clone() {
NativeFileType::LocalFileSystem(path)
} else {
NativeFileType::AteFileSystem(solo.native_files.clone())
};
// Set the system
let (tx_exit, _) = watch::channel(false);
let sys = Arc::new(wasmer_term::system::SysSystem::new_with_runtime(
solo.native_files_path.clone(), tx_exit, runtime,
));
let sys = wasmer_ssh::system::System::new(sys, registry.clone(), solo.db_url.clone(), native_files).await;
wasmer_ssh::wasmer_os::api::set_system_abi(sys);
let mut instance_authority = solo.inst_url.domain()
.map(|a| a.to_string())
.unwrap_or_else(|| "wasmer.sh".to_string());
if instance_authority == "localhost" {
instance_authority = "wasmer.sh".to_string();
}
let compiled_modules = Arc::new(CachedCompiledModules::new(Some(solo.compiler_cache_path.clone())));
let instance_server = Server::new(
solo.db_url.clone(),
solo.auth_url.clone(),
instance_authority.clone(),
solo.token_path.clone(),
registry.clone(),
solo.compiler.clone(),
compiled_modules.clone(),
ttl,
).await?;
let mut router = ate::comms::StreamRouter::new(
cfg_mesh.wire_format.clone(),
cfg_mesh.wire_protocol.clone(),
cfg_mesh.listen_min_encryption.clone(),
cfg_mesh.listen_certificate.clone(),
server_id,
cfg_mesh.accept_timeout,
);
let route = Arc::new(instance_server);
router.add_socket_route("/sess", route.clone()).await;
router.add_socket_route("/inst", route.clone()).await;
router.add_post_route("/sess", route.clone()).await;
router.add_post_route("/inst", route.clone()).await;
router.add_put_route("/sess", route.clone()).await;
router.add_put_route("/inst", route.clone()).await;
let (_server, hard_exit) = main_web(&solo, conf, Some(router)).await?;
main_loop(Some(hard_exit)).await?;
//server.shutdown().await;
},
}
Ok(())
});
println!("Goodbye!");
ret
}
#[allow(dead_code)]
async fn main_web(solo: &OptsSessionServer, cfg_ate: ConfAte, callback: Option<StreamRouter>) -> Result<(Arc<ateweb::server::Server>, watch::Receiver<bool>), AteError>
{
let (hard_exit_tx, hard_exit_rx) = tokio::sync::watch::channel(false);
let server = main_web_ext(solo, cfg_ate, callback, hard_exit_tx).await?;
Ok((server, hard_exit_rx))
}
async fn main_web_ext(solo: &OptsSessionServer, cfg_ate: ConfAte, callback: Option<StreamRouter>, hard_exit_tx: watch::Sender<bool>) -> Result<Arc<ateweb::server::Server>, AteError>
{
let mut builder = ateweb::builder::ServerBuilder::new(solo.db_url.clone(), solo.auth_url.clone())
.add_listener(solo.listen, solo.port.unwrap_or(80u16), false)
.add_listener(solo.listen, solo.tls_port.unwrap_or(443u16), true)
.with_conf(&cfg_ate);
if let Some(callback) = callback {
builder = builder
.with_callback(callback);
}
let server = builder
.build()
.await?;
// Run the web server
{
let server = Arc::clone(&server);
TaskEngine::spawn(async move {
let ret = server.run().await;
if let Err(err) = ret {
error!("web server fatal error - {}", err);
}
let _ = hard_exit_tx.send(true);
});
}
// Done
Ok(server)
}
async fn main_loop(mut hard_exit: Option<Receiver<bool>>) -> Result<(), Box<dyn std::error::Error>>
{
// Wait for ctrl-c
eprintln!("Press ctrl-c to exit");
let mut exit = ctrl_channel();
while *exit.borrow() == false {
match hard_exit.as_mut() {
Some(hard_exit) => {
select! {
a = exit.changed() => { a?; },
a = hard_exit.changed() => {
a?;
if *hard_exit.borrow() {
info!("Hard exit");
break;
}
}
}
},
None => {
exit.changed().await.unwrap();
}
}
}
println!("Shutting down...");
Ok(())
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/process/src/prelude.rs | wasmer-bus/process/src/prelude.rs | pub use crate::api::StdioMode;
pub use crate::process::Child;
pub use crate::process::ChildStderr;
pub use crate::process::ChildStdin;
pub use crate::process::ChildStdout;
pub use crate::process::Command;
pub use crate::process::ExitStatus;
pub use crate::process::Output;
pub use crate::process::Stdio;
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/process/src/lib.rs | wasmer-bus/process/src/lib.rs | pub mod api;
pub mod prelude;
pub mod process;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/process/src/process/command.rs | wasmer-bus/process/src/process/command.rs | use std::{ffi::OsStr, io};
use super::*;
/// A process builder, providing fine-grained control
/// over how a new process should be spawned.
///
/// A default configuration can be
/// generated using `Command::new(program)`, where `program` gives a path to the
/// program to be executed. Additional builder methods allow the configuration
/// to be changed (for example, by adding arguments) prior to spawning:
///
/// ```
/// use wasi_net::Command;
///
/// let output = if cfg!(target_os = "windows") {
/// Command::new("cmd")
/// .args(&["/C", "echo hello"])
/// .output()
/// .expect("failed to execute process")
/// } else {
/// Command::new("sh")
/// .arg("-c")
/// .arg("echo hello")
/// .output()
/// .expect("failed to execute process")
/// };
///
/// let hello = output.stdout;
/// ```
///
/// `Command` can be reused to spawn multiple processes. The builder methods
/// change the command without needing to immediately spawn the process.
///
/// ```no_run
/// use wasi_net::Command;
///
/// let mut echo_hello = Command::new("sh");
/// echo_hello.arg("-c")
/// .arg("echo hello");
/// let hello_1 = echo_hello.output().expect("failed to execute process");
/// let hello_2 = echo_hello.output().expect("failed to execute process");
/// ```
///
/// Similarly, you can call builder methods after spawning a process and then
/// spawn a new process with the modified settings.
///
/// ```no_run
/// use wasi_net::Command;
///
/// let mut list_dir = Command::new("ls");
///
/// // Execute `ls` in the current directory of the program.
/// list_dir.status().expect("process failed to execute");
/// ```
#[derive(Debug, Clone)]
pub struct Command {
pub(super) path: String,
pub(super) args: Vec<String>,
pub(super) chroot: bool,
pub(super) working_dir: Option<String>,
pub(super) stdin: Option<Stdio>,
pub(super) stdout: Option<Stdio>,
pub(super) stderr: Option<Stdio>,
pub(super) pre_open: Vec<String>,
pub(super) instance: Option<CommandInstance>,
}
#[derive(Debug, Clone)]
pub struct CommandInstance
{
pub instance: String,
pub access_token: String,
}
impl Command {
/// Constructs a new `Command` for launching the program at
/// path `program`, with the following default configuration:
///
/// * No arguments to the program
/// * Inherit the current process's environment
/// * Inherit the current process's working directory
/// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
///
/// Builder methods are provided to change these defaults and
/// otherwise configure the process.
///
/// If `program` is not an absolute path, the `PATH` will be searched in
/// an OS-defined way.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// Command::new("sh")
/// .spawn()
/// .expect("sh command failed to start");
/// ```
pub fn new(path: &str) -> Command {
Command {
path: path.to_string(),
args: Vec::new(),
chroot: false,
working_dir: None,
stdin: None,
stdout: None,
stderr: None,
pre_open: Vec::new(),
instance: None,
}
}
/// Adds an argument to pass to the program.
///
/// Only one argument can be passed per use. So instead of:
///
/// ```no_run
/// # wasi_net::Command::new("sh")
/// .arg("-C /path/to/repo")
/// # ;
/// ```
///
/// usage would be:
///
/// ```no_run
/// # wasi_net::Command::new("sh")
/// .arg("-C")
/// .arg("/path/to/repo")
/// # ;
/// ```
///
/// To pass multiple arguments see [`args`].
///
/// [`args`]: Command::args
///
/// Note that the argument is not passed through a shell, but given
/// literally to the program. This means that shell syntax like quotes,
/// escaped characters, word splitting, glob patterns, substitution, etc.
/// have no effect.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// Command::new("ls")
/// .arg("-l")
/// .arg("-a")
/// .spawn()
/// .expect("ls command failed to start");
/// ```
pub fn arg(&mut self, arg: &str) -> &mut Command {
self.args.push(arg.to_string());
self
}
/// Adds multiple arguments to pass to the program.
///
/// To pass a single argument see [`arg`].
///
/// [`arg`]: Command::arg
///
/// Note that the arguments are not passed through a shell, but given
/// literally to the program. This means that shell syntax like quotes,
/// escaped characters, word splitting, glob patterns, substitution, etc.
/// have no effect.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// Command::new("ls")
/// .args(&["-l", "-a"])
/// .spawn()
/// .expect("ls command failed to start");
/// ```
pub fn args<I, S>(&mut self, args: I) -> &mut Command
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
for arg in args {
self.args.push(arg.as_ref().to_string_lossy().into_owned());
}
self
}
/// Sets the working directory for the child process.
///
/// # Platform-specific behavior
///
/// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
/// whether it should be interpreted relative to the parent's working
/// directory or relative to `current_dir`. The behavior in this case is
/// platform specific and unstable, and it's recommended to use
/// [`canonicalize`] to get an absolute program path instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// Command::new("ls")
/// .working_dir("/bin")
/// .chroot(true)
/// .spawn()
/// .expect("ls command failed to start");
/// ```
///
/// [`canonicalize`]: crate::fs::canonicalize
pub fn working_dir(&mut self, dir: &str) -> &mut Command {
self.working_dir = Some(dir.to_string());
self
}
/// Indicates that the root file system will be pivoted to a particular
/// path as if it were the root.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// Command::new("ls")
/// .working_dir("/bin")
/// .chroot(true)
/// .spawn()
/// .expect("ls command failed to start");
/// ```
pub fn chroot(&mut self, chroot: bool) -> &mut Command {
self.chroot = chroot;
self
}
/// Runs the process on a server side session
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// Command::new("ls")
/// .session("my-session", "71248123")
/// .working_dir("/bin")
/// .chroot(true)
/// .spawn()
/// .expect("ls command failed to start");
/// ```
pub fn instance(&mut self, instance: &str, access_token: &str) -> &mut Command {
self.instance = Some(CommandInstance {
instance: instance.to_string(),
access_token: access_token.to_string()
});
self
}
/// Configuration for the child process's standard input (stdin) handle.
///
/// Defaults to [`inherit`] when used with `spawn` or `status`, and
/// defaults to [`piped`] when used with `output`.
///
/// [`inherit`]: Stdio::inherit
/// [`piped`]: Stdio::piped
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::{Command, Stdio};
///
/// Command::new("ls")
/// .stdin(Stdio::null())
/// .spawn()
/// .expect("ls command failed to start");
/// ```
pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
self.stdin = Some(cfg);
self
}
/// Configuration for the child process's standard output (stdout) handle.
///
/// Defaults to [`inherit`] when used with `spawn` or `status`, and
/// defaults to [`piped`] when used with `output`.
///
/// [`inherit`]: Stdio::inherit
/// [`piped`]: Stdio::piped
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use std::process::{Command, Stdio};
///
/// Command::new("ls")
/// .stdout(Stdio::null())
/// .spawn()
/// .expect("ls command failed to start");
/// ```
pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
self.stdout = Some(cfg);
self
}
/// Configuration for the child process's standard error (stderr) handle.
///
/// Defaults to [`inherit`] when used with `spawn` or `status`, and
/// defaults to [`piped`] when used with `output`.
///
/// [`inherit`]: Stdio::inherit
/// [`piped`]: Stdio::piped
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use std::process::{Command, Stdio};
///
/// Command::new("ls")
/// .stderr(Stdio::null())
/// .spawn()
/// .expect("ls command failed to start");
/// ```
pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
self.stderr = Some(cfg);
self
}
/// Pre-opens a directory before launching the process
pub fn pre_open(&mut self, path: String) -> &mut Command {
self.pre_open.push(path);
self
}
async fn prep(&self) -> io::Result<Child> {
let stdin = self
.stdin
.as_ref()
.map(|a| a.clone())
.unwrap_or(Stdio::inherit());
let stdout = self
.stdout
.as_ref()
.map(|a| a.clone())
.unwrap_or(Stdio::inherit());
let stderr = self
.stderr
.as_ref()
.map(|a| a.clone())
.unwrap_or(Stdio::inherit());
let preopen = self.pre_open.clone();
let instance = self.instance.clone()
.map(|a| {
super::child::ChildInstance {
instance: a.instance,
access_token: a.access_token
}
});
Child::new(self, instance, stdin.mode, stdout.mode, stderr.mode, preopen).await
}
/// Executes the command as a child process, returning a handle to it.
///
/// By default, stdin, stdout and stderr are inherited from the parent.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// Command::new("ls")
/// .spawn()
/// .expect("ls command failed to start");
/// ```
pub fn spawn(&self) -> io::Result<Child> {
wasmer_bus::task::block_on(self.prep())
}
/// Executes the command as a child process to completion asynchronously
///
/// By default, stdin, stdout and stderr are inherited from the parent.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// Command::new("ls")
/// .execute()
/// .await
/// .expect("ls command failed to start");
/// ```
pub async fn execute(&self) -> io::Result<ExitStatus> {
Ok(self.prep().await?.join().await?)
}
/// Executes the command as a child process, waiting for it to finish and
/// collecting all of its output.
///
/// By default, stdout and stderr are captured (and used to provide the
/// resulting output). Stdin is not inherited from the parent and any
/// attempt by the child process to read from the stdin stream will result
/// in the stream immediately closing.
///
/// # Examples
///
/// ```should_panic
/// use wasi_net::Command;
/// use std::io::{self, Write};
/// let output = Command::new("/bin/cat")
/// .arg("file.txt")
/// .output()
/// .expect("failed to execute process");
///
/// println!("status: {}", output.status);
/// io::stdout().write_all(&output.stdout).unwrap();
/// io::stderr().write_all(&output.stderr).unwrap();
///
/// assert!(output.status.success());
/// ```
pub fn output(&mut self) -> io::Result<Output> {
if self.stdin.is_none() {
self.stdin = Some(Stdio::null());
}
if self.stdout.is_none() {
self.stdout = Some(Stdio::piped());
}
if self.stderr.is_none() {
self.stderr = Some(Stdio::piped());
}
Ok(self.spawn()?.wait_with_output()?)
}
/// Executes a command as a child process, waiting for it to finish and
/// collecting its status.
///
/// By default, stdin, stdout and stderr are inherited from the parent.
///
/// # Examples
///
/// ```should_panic
/// use wasi_net::Command;
///
/// let status = Command::new("/bin/cat")
/// .arg("file.txt")
/// .status()
/// .expect("failed to execute process");
///
/// println!("process finished with: {}", status);
///
/// assert!(status.success());
/// ```
pub fn status(&mut self) -> io::Result<ExitStatus> {
Ok(self.spawn()?.wait()?)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/process/src/process/stdio.rs | wasmer-bus/process/src/process/stdio.rs | use crate::api::*;
/// Describes what to do with a standard I/O stream for a child process when
/// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
///
/// [`stdin`]: Command::stdin
/// [`stdout`]: Command::stdout
/// [`stderr`]: Command::stderr
#[derive(Debug, Clone)]
pub struct Stdio {
pub(super) mode: StdioMode,
}
impl Stdio {
/// A new pipe should be arranged to connect the parent and child processes.
///
/// # Examples
///
/// With stdout:
///
/// ```no_run
/// use std::process::{Command, Stdio};
///
/// let output = Command::new("echo")
/// .arg("Hello, world!")
/// .stdout(Stdio::piped())
/// .output()
/// .expect("Failed to execute command");
///
/// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
/// // Nothing echoed to console
/// ```
///
/// With stdin:
///
/// ```no_run
/// use std::io::Write;
/// use std::process::{Command, Stdio};
///
/// let mut child = Command::new("rev")
/// .stdin(Stdio::piped())
/// .stdout(Stdio::piped())
/// .spawn()
/// .expect("Failed to spawn child process");
///
/// let mut stdin = child.stdin.take().expect("Failed to open stdin");
/// std::thread::spawn(move || {
/// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
/// });
///
/// let output = child.wait_with_output().expect("Failed to read stdout");
/// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
/// ```
///
/// Writing more than a pipe buffer's worth of input to stdin without also reading
/// stdout and stderr at the same time may cause a deadlock.
/// This is an issue when running any program that doesn't guarantee that it reads
/// its entire stdin before writing more than a pipe buffer's worth of output.
/// The size of a pipe buffer varies on different targets.
///
pub fn piped() -> Stdio {
Stdio {
mode: StdioMode::Piped,
}
}
/// The child inherits from the corresponding parent descriptor.
///
/// # Examples
///
/// With stdout:
///
/// ```no_run
/// use std::process::{Command, Stdio};
///
/// let output = Command::new("echo")
/// .arg("Hello, world!")
/// .stdout(Stdio::inherit())
/// .output()
/// .expect("Failed to execute command");
///
/// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
/// // "Hello, world!" echoed to console
/// ```
///
/// With stdin:
///
/// ```no_run
/// use std::process::{Command, Stdio};
/// use std::io::{self, Write};
///
/// let output = Command::new("rev")
/// .stdin(Stdio::inherit())
/// .stdout(Stdio::piped())
/// .output()
/// .expect("Failed to execute command");
///
/// print!("You piped in the reverse of: ");
/// io::stdout().write_all(&output.stdout).unwrap();
/// ```
pub fn inherit() -> Stdio {
Stdio {
mode: StdioMode::Inherit,
}
}
/// This stream will be ignored. This is the equivalent of attaching the
/// stream to `/dev/null`.
///
/// # Examples
///
/// With stdout:
///
/// ```no_run
/// use std::process::{Command, Stdio};
///
/// let output = Command::new("echo")
/// .arg("Hello, world!")
/// .stdout(Stdio::null())
/// .output()
/// .expect("Failed to execute command");
///
/// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
/// // Nothing echoed to console
/// ```
///
/// With stdin:
///
/// ```no_run
/// use std::process::{Command, Stdio};
///
/// let output = Command::new("rev")
/// .stdin(Stdio::null())
/// .stdout(Stdio::piped())
/// .output()
/// .expect("Failed to execute command");
///
/// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
/// // Ignores any piped-in input
/// ```
pub fn null() -> Stdio {
Stdio {
mode: StdioMode::Null,
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/process/src/process/child_stdin.rs | wasmer-bus/process/src/process/child_stdin.rs | use std::io;
use std::io::Write;
use super::*;
use crate::api;
#[derive(Debug)]
pub struct ChildStdin {
pub(super) context: api::ProcessClient,
}
impl ChildStdin {
pub fn new(context: api::ProcessClient) -> ChildStdin {
ChildStdin { context }
}
}
impl Write for ChildStdin {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
Ok(self
.context
.blocking_stdin(buf.to_vec())
.map_err(|err| err.into_io_error())?)
}
fn flush(&mut self) -> io::Result<()> {
Ok(self
.context
.blocking_flush()
.map_err(|err| 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/process/src/process/child_stdout.rs | wasmer-bus/process/src/process/child_stdout.rs | use bytes::*;
use std::io::Read;
use std::sync::mpsc;
use super::*;
#[derive(Debug)]
pub struct ChildStdout {
pub(super) rx: mpsc::Receiver<Vec<u8>>,
pub(super) buffer: BytesMut,
}
impl ChildStdout {
pub fn new() -> (ChildStdout, mpsc::Sender<Vec<u8>>) {
let (tx_stdout, rx_stdout) = mpsc::channel();
(
ChildStdout {
rx: rx_stdout,
buffer: BytesMut::new(),
},
tx_stdout,
)
}
}
impl Read for ChildStdout {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
loop {
if self.buffer.has_remaining() {
let max = self.buffer.remaining().min(buf.len());
buf[0..max].copy_from_slice(&self.buffer[..max]);
self.buffer.advance(max);
return Ok(max);
} else {
match self.rx.recv() {
Ok(data) => {
self.buffer.extend_from_slice(&data[..]);
}
Err(mpsc::RecvError) => {
return Ok(0usize);
}
}
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/process/src/process/child_stderr.rs | wasmer-bus/process/src/process/child_stderr.rs | pub use super::ChildStdout as ChildStderr;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/process/src/process/mod.rs | wasmer-bus/process/src/process/mod.rs | mod child;
mod child_stderr;
mod child_stdin;
mod child_stdout;
mod command;
mod exit_status;
mod output;
mod stdio;
pub use child::Child;
pub use child_stderr::ChildStderr;
pub use child_stdin::ChildStdin;
pub use child_stdout::ChildStdout;
pub use command::Command;
pub use exit_status::ExitStatus;
pub use output::Output;
pub use stdio::*;
pub use std::io::Error;
pub use std::io::ErrorKind;
pub use std::io::Result;
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/process/src/process/child.rs | wasmer-bus/process/src/process/child.rs | use std::future::Future;
use std::io::{self, Read};
use std::pin::Pin;
use std::sync::Mutex;
use std::task::Context;
use std::task::Poll;
use tokio::sync::watch;
use super::*;
use crate::api;
use crate::api::StdioMode;
/// Representation of a running or exited child process.
///
/// This structure is used to represent and manage child processes. A child
/// process is created via the [`Command`] struct, which configures the
/// spawning process and can itself be constructed using a builder-style
/// interface.
///
/// There is no implementation of [`Drop`] for child processes,
/// so if you do not ensure the `Child` has exited then it will continue to
/// run, even after the `Child` handle to the child process has gone out of
/// scope.
///
/// Calling [`wait`] (or other functions that wrap around it) will make
/// the parent process wait until the child has actually exited before
/// continuing.
///
/// # Examples
///
/// ```should_panic
/// use std::process::Command;
///
/// let mut child = Command::new("/bin/cat")
/// .arg("file.txt")
/// .spawn()
/// .expect("failed to execute child");
///
/// let ecode = child.wait()
/// .expect("failed to wait on child");
///
/// assert!(ecode.success());
/// ```
///
/// [`wait`]: Child::wait
#[derive(Debug)]
pub struct Child {
context: Option<api::ProcessClient>,
exited: watch::Receiver<Option<i32>>,
id: u32,
/// The handle for writing to the child's standard input (stdin), if it has
/// been captured. To avoid partially moving
/// the `child` and thus blocking yourself from calling
/// functions on `child` while using `stdin`,
/// you might find it helpful:
///
/// ```compile_fail,E0425
/// let stdin = child.stdin.take().unwrap();
/// ```
pub stdin: Option<ChildStdin>,
/// The handle for reading from the child's standard output (stdout), if it
/// has been captured. You might find it helpful to do
///
/// ```compile_fail,E0425
/// let stdout = child.stdout.take().unwrap();
/// ```
///
/// to avoid partially moving the `child` and thus blocking yourself from calling
/// functions on `child` while using `stdout`.
pub stdout: Option<ChildStdout>,
/// The handle for reading from the child's standard error (stderr), if it
/// has been captured. You might find it helpful to do
///
/// ```compile_fail,E0425
/// let stderr = child.stderr.take().unwrap();
/// ```
///
/// to avoid partially moving the `child` and thus blocking yourself from calling
/// functions on `child` while using `stderr`.
pub stderr: Option<ChildStderr>,
}
#[derive(Debug, Clone)]
pub struct ChildInstance
{
pub instance: String,
pub access_token: String,
}
impl Child {
// Starts the child process
pub(super) async fn new(
cmd: &Command,
instance: Option<ChildInstance>,
stdin_mode: StdioMode,
stdout_mode: StdioMode,
stderr_mode: StdioMode,
pre_open: Vec<String>,
) -> Result<Child> {
let (stdout, stdout_tx) = if stdout_mode == StdioMode::Piped {
let (a, b) = ChildStdout::new();
(Some(a), Some(b))
} else {
(None, None)
};
let (stderr, stderr_tx) = if stderr_mode == StdioMode::Piped {
let (a, b) = ChildStdout::new();
(Some(a), Some(b))
} else {
(None, None)
};
let spawn = api::Spawn {
path: cmd.path.clone(),
args: cmd.args.clone(),
chroot: cmd.chroot,
working_dir: cmd.working_dir.clone(),
stdin_mode,
stdout_mode,
stderr_mode,
pre_open: pre_open.clone(),
};
let stdout_tx = stdout_tx.map(|a| Mutex::new(a));
let on_stdout = Box::new(move |data: Vec<u8>| {
if let Some(tx) = stdout_tx.as_ref() {
let _ = tx.lock().unwrap().send(data);
}
});
let stderr_tx = stderr_tx.map(|a| Mutex::new(a));
let on_stderr = Box::new(move |data: Vec<u8>| {
if let Some(tx) = stderr_tx.as_ref() {
let _ = tx.lock().unwrap().send(data);
}
});
let (exited_tx, exited_rx) = watch::channel(None);
let on_exit = {
Box::new(move |code| {
let _ = exited_tx.send(Some(code));
})
};
let pool = if let Some(instance) = instance {
api::PoolClient::new_with_instance(WAPM_NAME, instance.instance.as_str(), instance.access_token.as_str())
} else {
api::PoolClient::new(WAPM_NAME)
};
let context = pool
.spawn(spawn, on_stdout, on_stderr, on_exit)
.await
.map_err(|err| err.into_io_error())?
.as_client()
.unwrap();
let stdin = if stdin_mode == StdioMode::Piped {
let stdin = ChildStdin::new(context.clone());
Some(stdin)
} else {
None
};
Ok(Child {
id: context.id().await.map_err(|err| err.into_io_error())?,
context: Some(context),
exited: exited_rx,
stdin,
stdout,
stderr,
})
}
/// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
/// error is returned.
///
/// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
/// especially the [`Other`] kind might change to more specific kinds in the future.
///
/// This is equivalent to sending a SIGKILL on Unix platforms.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// let mut command = Command::new("yes");
/// if let Ok(mut child) = command.spawn() {
/// child.kill().expect("command wasn't running");
/// } else {
/// println!("yes command didn't start");
/// }
/// ```
///
/// [`ErrorKind`]: io::ErrorKind
/// [`InvalidInput`]: io::ErrorKind::InvalidInput
/// [`Other`]: io::ErrorKind::Other
pub fn kill(&mut self) -> io::Result<()> {
if let Some(context) = self.context.as_ref() {
context.blocking_kill().map_err(|err| err.into_io_error())?
}
Ok(())
}
/// Returns the OS-assigned process identifier associated with this child.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// let mut command = Command::new("ls");
/// if let Ok(child) = command.spawn() {
/// println!("Child's ID is {}", child.id());
/// } else {
/// println!("ls command didn't start");
/// }
/// ```
pub fn id(&self) -> u32 {
self.id
}
/// Waits for the child to exit completely, returning the status that it
/// exited with. This function will continue to have the same return value
/// after it has been called at least once.
///
/// The stdin handle to the child process, if any, will be closed
/// before waiting. This helps avoid deadlock: it ensures that the
/// child does not block waiting for input from the parent, while
/// the parent waits for the child to exit.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// let mut command = Command::new("ls");
/// if let Ok(mut child) = command.spawn() {
/// child.wait().expect("command wasn't running");
/// println!("Child has finished its execution!");
/// } else {
/// println!("ls command didn't start");
/// }
/// ```
#[allow(unused_mut)] // this is so that the API's are compatible with std:process
pub fn wait(&mut self) -> io::Result<ExitStatus> {
let _ = wasmer_bus::task::block_on(self.exited.changed());
let code = self.exited.borrow().clone();
Ok(ExitStatus { code })
}
/// Simultaneously waits for the child to exit and collect all remaining
/// output on the stdout/stderr handles, returning an `Output`
/// instance.
///
/// The stdin handle to the child process, if any, will be closed
/// before waiting. This helps avoid deadlock: it ensures that the
/// child does not block waiting for input from the parent, while
/// the parent waits for the child to exit.
///
/// By default, stdin, stdout and stderr are inherited from the parent.
/// In order to capture the output into this `Result<Output>` it is
/// necessary to create new pipes between parent and child. Use
/// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
///
/// # Examples
///
/// ```should_panic
/// use wasi_net::{Command, Stdio};
///
/// let child = Command::new("/bin/cat")
/// .arg("file.txt")
/// .stdout(Stdio::piped())
/// .spawn()
/// .expect("failed to execute child");
///
/// let output = child
/// .wait_with_output()
/// .expect("failed to wait on child");
///
/// assert!(output.status.success());
/// ```
///
pub fn wait_with_output(&mut self) -> io::Result<Output> {
drop(self.stdin.take());
let taken = (self.stdout.take(), self.stderr.take());
let status = self.wait()?;
let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
match taken {
(None, None) => {}
(Some(mut out), None) => {
out.read_to_end(&mut stdout).unwrap();
}
(None, Some(mut err)) => {
err.read_to_end(&mut stderr).unwrap();
}
(Some(mut out), Some(mut err)) => {
out.read_to_end(&mut stdout).unwrap();
err.read_to_end(&mut stderr).unwrap();
}
}
Ok(Output {
status,
stdout,
stderr,
})
}
pub fn join(&mut self) -> ChildJoin {
let exit_wait = {
let mut exited = self.exited.clone();
Box::pin(async move {
let _ = exited.changed().await;
})
};
ChildJoin {
exited: self.exited.clone(),
exit_wait,
}
}
}
pub struct ChildJoin {
exited: watch::Receiver<Option<i32>>,
exit_wait: Pin<Box<dyn Future<Output = ()>>>,
}
impl ChildJoin {
/// Attempts to collect the exit status of the child if it has already
/// exited.
///
/// This function will not block the calling thread and will only
/// check to see if the child process has exited or not. If the child has
/// exited then on Unix the process ID is reaped. This function is
/// guaranteed to repeatedly return a successful exit status so long as the
/// child has already exited.
///
/// If the child has exited, then `Ok(Some(status))` is returned. If the
/// exit status is not available at this time then `Ok(None)` is returned.
/// If an error occurs, then that error is returned.
///
/// Note that unlike `wait`, this function will not attempt to drop stdin.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use wasi_net::Command;
///
/// let mut child = Command::new("ls").spawn().unwrap();
///
/// match child.try_wait() {
/// Ok(Some(status)) => println!("exited with: {}", status),
/// Ok(None) => {
/// println!("status not ready yet, let's really wait");
/// let res = child.wait();
/// println!("result: {:?}", res);
/// }
/// Err(e) => println!("error attempting to wait: {}", e),
/// }
/// ```
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
let waker = dummy_waker::dummy_waker();
let mut cx = Context::from_waker(&waker);
let exit_wait = self.exit_wait.as_mut();
if let Poll::Ready(_) = exit_wait.poll(&mut cx) {
let code = self.exited.borrow().clone();
return Ok(Some(ExitStatus { code }));
}
Ok(None)
}
}
/// Its also possible to .await the process
impl Future for ChildJoin {
type Output = io::Result<ExitStatus>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let exit_wait = self.exit_wait.as_mut();
match exit_wait.poll(cx) {
Poll::Ready(_) => {
let code = self.exited.borrow().clone();
let a = ExitStatus { code };
Poll::Ready(Ok(a))
}
Poll::Pending => 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/process/src/process/exit_status.rs | wasmer-bus/process/src/process/exit_status.rs | #[derive(PartialEq, Eq, Clone, Copy)]
pub struct ExitStatusError {
code: Option<i32>,
}
impl ExitStatusError {
pub fn code(&self) -> Option<i32> {
self.code.clone()
}
pub fn into_status(&self) -> ExitStatus {
ExitStatus { code: self.code }
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct ExitStatus {
pub(super) code: Option<i32>,
}
impl ExitStatus {
pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
match self.code {
Some(a) if a == 0 => return Ok(()),
Some(a) => {
return Err(ExitStatusError { code: Some(a) });
}
None => return Ok(()),
}
}
pub fn success(&self) -> bool {
self.code.unwrap_or(0) == 0
}
pub fn code(&self) -> Option<i32> {
self.code
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/process/src/process/output.rs | wasmer-bus/process/src/process/output.rs | use super::*;
#[derive(PartialEq, Eq, Clone)]
pub struct Output {
pub status: ExitStatus,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/process/src/api/mod.rs | wasmer-bus/process/src/api/mod.rs | use serde::*;
use std::fmt;
use std::{fmt::Display, sync::Arc};
use wasmer_bus::macros::*;
#[wasmer_bus(format = "bincode")]
pub trait Pool {
async fn spawn(
&self,
spawn: Spawn,
stdout: impl Fn(Vec<u8>),
stderr: impl Fn(Vec<u8>),
exit: impl Fn(i32),
) -> Arc<dyn Process>;
}
#[wasmer_bus(format = "bincode")]
pub trait Process {
async fn id(&self) -> u32;
async fn stdin(&self, data: Vec<u8>) -> usize;
async fn close_stdin(&self);
async fn kill(&self);
async fn flush(&self);
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Spawn {
pub path: String,
pub args: Vec<String>,
pub chroot: bool,
pub working_dir: Option<String>,
pub stdin_mode: StdioMode,
pub stdout_mode: StdioMode,
pub stderr_mode: StdioMode,
pub pre_open: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum StdioMode {
Piped,
Inherit,
Null,
Log,
}
impl Display for StdioMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StdioMode::Piped => write!(f, "piped"),
StdioMode::Inherit => write!(f, "inherit"),
StdioMode::Null => write!(f, "null"),
StdioMode::Log => write!(f, "log"),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/prelude.rs | wasmer-bus/mio/src/prelude.rs | pub use std::time::Duration;
pub use std::net::SocketAddr;
pub use std::net::Ipv4Addr;
pub use std::net::Ipv6Addr;
pub use super::mio::AsyncIcmpSocket;
pub use super::mio::AsyncRawSocket;
pub use super::mio::AsyncTcpListener;
pub use super::mio::AsyncTcpStream;
pub use super::mio::AsyncUdpSocket;
pub use super::mio::IcmpSocket;
pub use super::mio::RawSocket;
pub use super::mio::TcpListener;
pub use super::mio::TcpStream;
pub use super::mio::UdpSocket;
pub use super::mio::Port;
pub use ate_comms::StreamSecurity;
pub use super::mio::TokenSource;
pub use super::model::NetworkToken;
pub use ate_crypto::ChainKey;
pub use super::mio::clear_access_token;
pub use super::mio::load_access_token;
pub use super::mio::save_access_token;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/lib.rs | wasmer-bus/mio/src/lib.rs | pub mod mio;
pub mod prelude;
pub mod model;
pub(crate) mod comms; | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/blocking.rs | wasmer-bus/mio/src/mio/blocking.rs | use std::io;
use std::net::IpAddr;
use std::net::SocketAddr;
use wasmer_bus::task::block_on;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
pub struct RawSocket {
inner: super::AsyncRawSocket
}
impl RawSocket {
pub fn new(socket: super::AsyncRawSocket) -> Self {
Self {
inner: socket
}
}
pub fn send(&self, buf: Vec<u8>) -> io::Result<usize> {
block_on(self.inner.send(buf))
}
pub fn recv(&self) -> io::Result<Vec<u8>> {
block_on(self.inner.recv())
}
pub fn try_recv(&self) -> io::Result<Option<Vec<u8>>> {
self.inner.try_recv()
}
pub fn set_promiscuous(&self, promiscuous: bool) -> io::Result<bool> {
block_on(self.inner.set_promiscuous(promiscuous))
}
}
pub struct TcpListener {
inner: super::AsyncTcpListener
}
impl TcpListener {
pub fn new(socket: super::AsyncTcpListener) -> Self {
Self {
inner: socket
}
}
pub fn listen(&self, backlog: u32) -> io::Result<()> {
block_on(self.inner.listen(backlog))
}
pub fn accept(&self) -> io::Result<TcpStream> {
Ok(TcpStream::new(block_on(self.inner.accept())?))
}
pub fn local_addr(&self) -> SocketAddr {
self.inner.local_addr()
}
pub fn set_ttl(&self, ttl: u8) -> io::Result<()> {
block_on(self.inner.set_ttl(ttl))
}
pub fn ttl(&self) -> u8 {
block_on(self.inner.ttl())
}
}
pub struct TcpStream {
inner: super::AsyncTcpStream
}
impl TcpStream {
pub fn new(socket: super::AsyncTcpStream) -> Self {
Self {
inner: socket
}
}
pub fn peer_addr(&self) -> SocketAddr {
self.inner.peer_addr()
}
pub fn local_addr(&self) -> SocketAddr {
self.inner.local_addr()
}
pub fn shutdown(&self, shutdown: std::net::Shutdown) -> io::Result<()> {
block_on(self.inner.shutdown(shutdown))
}
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
block_on(self.inner.set_nodelay(nodelay))
}
pub fn nodelay(&self) -> bool {
block_on(self.inner.nodelay())
}
pub fn set_ttl(&self, ttl: u8) -> io::Result<()> {
block_on(self.inner.set_ttl(ttl))
}
pub fn ttl(&self) -> u8 {
block_on(self.inner.ttl())
}
pub fn peek(&self) -> io::Result<Vec<u8>> {
block_on(self.inner.peek())
}
pub fn recv(&self) -> io::Result<Vec<u8>> {
block_on(self.inner.recv())
}
pub fn try_recv(&self) -> io::Result<Option<Vec<u8>>> {
self.inner.try_recv()
}
pub fn send(&self, buf: Vec<u8>) -> io::Result<usize> {
block_on(self.inner.send(buf))
}
pub fn flush(&self) -> io::Result<()> {
block_on(self.inner.flush())
}
pub fn is_connected(&self) -> bool {
block_on(self.inner.is_connected())
}
}
pub struct UdpSocket {
inner: super::AsyncUdpSocket
}
impl UdpSocket {
pub fn new(socket: super::AsyncUdpSocket) -> Self {
Self {
inner: socket
}
}
pub fn recv_from(&self) -> io::Result<(Vec<u8>, SocketAddr)> {
block_on(self.inner.recv_from())
}
pub fn try_recv_from(&self) -> io::Result<Option<(Vec<u8>, SocketAddr)>> {
self.inner.try_recv_from()
}
pub fn peek_from(&self) -> io::Result<(Vec<u8>, SocketAddr)> {
block_on(self.inner.peek_from())
}
pub fn send_to(&self, buf: Vec<u8>, addr: SocketAddr) -> io::Result<usize> {
block_on(self.inner.send_to(buf, addr))
}
pub fn peer_addr(&self) -> Option<SocketAddr> {
block_on(self.inner.peer_addr())
}
pub fn local_addr(&self) -> SocketAddr {
self.inner.local_addr()
}
pub fn try_clone(&self) -> io::Result<UdpSocket> {
Ok(
UdpSocket {
inner: block_on(self.inner.try_clone())?
}
)
}
pub fn set_ttl(&self, ttl: u8) -> io::Result<()> {
block_on(self.inner.set_ttl(ttl))
}
pub fn ttl(&self) -> u8 {
block_on(self.inner.ttl())
}
pub fn connect(&self, addr: SocketAddr) {
block_on(self.inner.connect(addr))
}
pub fn send(&self, buf: Vec<u8>) -> io::Result<usize> {
block_on(self.inner.send(buf))
}
pub fn recv(&self) -> io::Result<Vec<u8>> {
block_on(self.inner.recv())
}
pub fn try_recv(&self) -> io::Result<Option<Vec<u8>>> {
self.inner.try_recv()
}
pub fn peek(&self) -> io::Result<Vec<u8>> {
block_on(self.inner.peek())
}
pub fn is_connected(&self) -> bool {
block_on(self.inner.is_connected())
}
}
pub struct IcmpSocket {
inner: super::AsyncIcmpSocket
}
impl IcmpSocket {
pub fn new(socket: super::AsyncIcmpSocket) -> Self {
Self {
inner: socket
}
}
pub fn recv_from(&self) -> io::Result<(Vec<u8>, IpAddr)> {
block_on(self.inner.recv_from())
}
pub fn peek_from(&self) -> io::Result<(Vec<u8>, IpAddr)> {
block_on(self.inner.peek_from())
}
pub fn send_to(&self, buf: Vec<u8>, addr: IpAddr) -> io::Result<usize> {
block_on(self.inner.send_to(buf, addr))
}
pub fn local_addr(&self) -> IpAddr {
self.inner.local_addr()
}
pub fn set_ttl(&self, ttl: u8) -> io::Result<()> {
block_on(self.inner.set_ttl(ttl))
}
pub fn ttl(&self) -> u8 {
block_on(self.inner.ttl())
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/raw_socket.rs | wasmer-bus/mio/src/mio/raw_socket.rs | use std::io;
use tokio::sync::Mutex;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
use crate::comms::*;
pub struct AsyncRawSocket {
socket: Mutex<Socket>,
}
impl AsyncRawSocket {
pub(crate) fn new(socket: Socket) -> Self {
Self {
socket: Mutex::new(socket)
}
}
pub async fn send(&self, buf: Vec<u8>) -> io::Result<usize> {
let socket = self.socket.lock().await;
socket
.send(buf)
.await
}
pub async fn recv(&self) -> io::Result<Vec<u8>> {
let mut socket = self.socket.lock().await;
socket
.recv()
.await
}
pub fn try_recv(&self) -> io::Result<Option<Vec<u8>>> {
if let Ok(mut socket) = self.socket.try_lock() {
socket
.try_recv()
} else {
Ok(None)
}
}
pub async fn set_promiscuous(&self, promiscuous: bool) -> io::Result<bool> {
let mut socket = self.socket.lock().await;
socket.set_promiscuous(promiscuous).await
}
pub fn blocking(self) -> super::RawSocket {
super::RawSocket::new(self)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/tcp_listener.rs | wasmer-bus/mio/src/mio/tcp_listener.rs | use std::io;
use std::net::SocketAddr;
use tokio::sync::Mutex;
use derivative::*;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
use crate::comms::*;
use super::*;
use crate::comms::Port;
#[derive(Debug)]
struct State
{
socket: Option<Socket>,
ttl: u8,
}
#[derive(Derivative)]
#[derivative(Debug)]
pub struct AsyncTcpListener
{
#[derivative(Debug = "ignore")]
port: Port,
addr: SocketAddr,
state: Mutex<State>,
}
impl AsyncTcpListener {
pub(crate) async fn new(port: Port, addr: SocketAddr) -> io::Result<AsyncTcpListener> {
let socket = port
.listen_tcp(addr)
.await?;
Ok(
Self {
port,
addr,
state: Mutex::new(State {
socket: Some(socket),
ttl: 64,
})
}
)
}
async fn _create_socket(&self) -> io::Result<Socket> {
self.port
.listen_tcp(self.addr)
.await
}
pub async fn accept(&self) -> io::Result<AsyncTcpStream> {
let mut guard = self.state.lock().await;
if let Some(mut socket) = guard.socket.take() {
let peer = socket
.accept()
.await?;
guard.socket.replace(self._create_socket().await?);
if guard.ttl != 64 {
socket.set_ttl(guard.ttl as u8)
.await?;
}
Ok(AsyncTcpStream::new(socket, self.addr, peer))
} else {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "no listening socket"))
}
}
pub async fn listen(&self, _backlog: u32) -> io::Result<()> {
let mut guard = self.state.lock().await;
guard.socket.replace(self._create_socket()
.await?);
Ok(())
}
pub fn local_addr(&self) -> SocketAddr {
self.addr.clone()
}
pub async fn set_ttl(&self, ttl: u8) -> io::Result<()> {
let mut state = self.state.lock().await;
if let Some(socket) = state.socket.as_mut() {
socket
.set_ttl(ttl)
.await?;
}
state.ttl = ttl;
Ok(())
}
pub async fn ttl(&self) -> u8 {
let state = self.state.lock().await;
state.ttl
}
pub fn blocking(self) -> super::TcpListener {
super::TcpListener::new(self)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/icmp_socket.rs | wasmer-bus/mio/src/mio/icmp_socket.rs | use std::io;
use std::net::IpAddr;
use std::net::SocketAddr;
use std::collections::VecDeque;
use tokio::sync::Mutex;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
use crate::comms::*;
#[derive(Debug)]
struct State
{
socket: Socket,
ttl: u8,
backlog: VecDeque<(Vec<u8>, IpAddr)>,
}
pub struct AsyncIcmpSocket {
state: Mutex<State>,
addr: IpAddr,
}
impl AsyncIcmpSocket {
pub(crate) fn new(socket: Socket, addr: IpAddr) -> Self {
Self {
state: Mutex::new(State {
socket,
ttl: 64,
backlog: Default::default(),
}),
addr,
}
}
pub fn local_addr(&self) -> IpAddr {
self.addr
}
pub async fn recv_from(&self) -> io::Result<(Vec<u8>, IpAddr)> {
let mut state = self.state.lock().await;
if let Some((buf, addr)) = state.backlog.pop_front() {
return Ok((buf, addr));
}
let (data, addr) = state.socket
.recv_from()
.await?;
Ok((data, addr.ip()))
}
pub async fn peek_from(&self) -> io::Result<(Vec<u8>, IpAddr)> {
let mut state = self.state.lock().await;
if let Some((data, addr)) = state.backlog.pop_front() {
state.backlog.push_front((data.clone(), addr.clone()));
return Ok((data, addr));
}
let (data, addr) = state.socket
.recv_from()
.await?;
state.backlog.push_back((data.clone(), addr.ip()));
Ok((data, addr.ip()))
}
pub async fn send_to(&self, buf: Vec<u8>, addr: IpAddr) -> io::Result<usize> {
let addr = SocketAddr::new(addr, 0);
let state = self.state.lock().await;
state.socket
.send_to(buf, addr)
.await
}
pub async fn set_ttl(&self, ttl: u8) -> io::Result<()> {
let mut state = self.state.lock().await;
state.socket
.set_ttl(ttl)
.await?;
state.ttl = ttl;
Ok(())
}
pub async fn ttl(&self) -> u8 {
let state = self.state.lock().await;
state.ttl
}
pub fn blocking(self) -> super::IcmpSocket {
super::IcmpSocket::new(self)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/port.rs | wasmer-bus/mio/src/mio/port.rs | use std::sync::Arc;
use std::io;
use std::ops::Deref;
use std::ops::DerefMut;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use ate_comms::StreamSecurity;
use tokio::sync::Mutex;
use tokio::sync::MutexGuard;
use chrono::DateTime;
use chrono::Utc;
use derivative::*;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
use wasmer_bus::task::block_on;
use ate_crypto::ChainKey;
use crate::model::IpCidr;
use crate::model::IpRoute;
use crate::model::HardwareAddress;
use crate::model::NetworkToken;
use crate::model::SwitchHello;
use crate::comms::Port as CommsPort;
use super::AsyncIcmpSocket;
use super::AsyncRawSocket;
use super::AsyncTcpListener;
use super::AsyncTcpStream;
use super::AsyncUdpSocket;
use super::IcmpSocket;
use super::RawSocket;
use super::TcpListener;
use super::TcpStream;
use super::UdpSocket;
#[derive(Debug)]
struct State {
port: CommsPort,
}
#[derive(Debug)]
struct StateGuard<'a>
{
guard: MutexGuard<'a, Option<State>>
}
impl<'a> Deref
for StateGuard<'a>
{
type Target = State;
fn deref(&self) -> &Self::Target {
self.guard.as_ref().unwrap()
}
}
impl<'a> DerefMut
for StateGuard<'a>
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.guard.as_mut().unwrap()
}
}
#[derive(Debug, Clone)]
pub enum TokenSource
{
ByPath(String),
ByValue(NetworkToken)
}
#[allow(dead_code)]
#[derive(Derivative, Clone)]
#[derivative(Debug)]
pub struct Port {
token: NetworkToken,
security: StreamSecurity,
net_url: url::Url,
state: Arc<Mutex<Option<State>>>
}
impl Port {
pub fn new(
token: TokenSource,
net_url: url::Url,
security: StreamSecurity
) -> io::Result<Self>
{
// Load the access token
let token = match token {
TokenSource::ByPath(token_path) => {
super::load_access_token(token_path)
.map_err(|err| {
io::Error::new(io::ErrorKind::PermissionDenied, format!("failed to load network access token - {}", err))
})?
.ok_or_else(|| {
io::Error::new(io::ErrorKind::PermissionDenied, format!("failed to find network access token"))
})?
},
TokenSource::ByValue(a) => a
};
Ok(Self {
token,
net_url,
security,
state: Arc::new(Mutex::new(None))
})
}
async fn get_or_create_state<'a>(&'a self) -> io::Result<StateGuard<'a>>
{
// Lock the state guard
let mut guard = self.state.lock().await;
// If the port is already set then we are good to go
if guard.is_some() {
return Ok(StateGuard {
guard
})
}
// Create the connection to the servers
let port = ate_comms::StreamClient::connect(
self.net_url.clone(),
self.net_url.path(),
self.security,
Some("8.8.8.8".to_string()),
false)
.await
.map_err(|err| {
io::Error::new(io::ErrorKind::ConnectionReset, format!("failed to connect to mesh network - {}", err))
})?;
let (rx, mut tx) = port.split();
// Send the switch hello message
let hello = SwitchHello {
chain: self.token.chain.clone(),
access_token: self.token.access_token.clone(),
version: crate::model::PORT_COMMAND_VERSION,
};
let data = serde_json::to_vec(&hello)?;
tx.write(&data[..]).await?;
// Create the port
let port = CommsPort::new(rx, tx).await?;
// Set the state
guard.replace(State {
port,
});
// Return the guard
Ok(StateGuard {
guard
})
}
/// Return: First value is the ip address, second is the netmask
pub async fn dhcp_acquire(&self) -> io::Result<(Ipv4Addr, Ipv4Addr)> {
let guard = self.get_or_create_state().await?;
let (ip, netmask) = guard.port
.dhcp_acquire()
.await?;
Ok((ip, netmask))
}
/// Return: First value is the ip address, second is the netmask
pub fn blocking_dhcp_acquire(&self) -> io::Result<(Ipv4Addr, Ipv4Addr)> {
block_on(self.dhcp_acquire())
}
pub fn token(&self) -> &NetworkToken {
&self.token
}
pub fn chain(&self) -> &ChainKey {
&self.token.chain
}
pub async fn add_ip(&self, ip: IpAddr, prefix: u8) -> io::Result<IpCidr> {
let mut guard = self.get_or_create_state().await?;
guard.port.add_ip(ip, prefix).await
}
pub fn blocking_add_ip(&self, ip: IpAddr, prefix: u8) -> io::Result<IpCidr> {
block_on(self.add_ip(ip, prefix))
}
pub async fn remove_ip(&self, ip: IpAddr) -> io::Result<Option<IpCidr>> {
let mut guard = self.get_or_create_state().await?;
guard.port.remove_ip(ip).await
}
pub fn blocking_remove_ip(&self, ip: IpAddr) -> io::Result<Option<IpCidr>> {
block_on(self.remove_ip(ip))
}
pub async fn hardware_address(&self) -> io::Result<Option<HardwareAddress>> {
let guard = self.get_or_create_state().await?;
Ok(guard.port.hardware_address().await)
}
pub fn blocking_hardware_address(&self) -> io::Result<Option<HardwareAddress>> {
block_on(self.hardware_address())
}
pub async fn ips(&self) -> io::Result<Vec<IpCidr>> {
let guard = self.get_or_create_state().await?;
Ok(guard.port.ips().await)
}
pub fn blocking_ips(&self) -> io::Result<Vec<IpCidr>> {
block_on(self.ips())
}
pub async fn clear_ips(&self) -> io::Result<()> {
let mut guard = self.get_or_create_state().await?;
guard.port.clear_ips().await
}
pub fn blocking_clear_ips(&self) -> io::Result<()> {
block_on(self.clear_ips())
}
pub async fn add_default_route(&self, gateway: IpAddr) -> io::Result<IpRoute> {
let mut guard = self.get_or_create_state().await?;
guard.port.add_default_route(gateway).await
}
pub fn blocking_add_default_route(&self, gateway: IpAddr) -> io::Result<IpRoute> {
block_on(self.add_default_route(gateway))
}
pub async fn add_route(&self, cidr: IpCidr, via_router: IpAddr, preferred_until: Option<DateTime<Utc>>, expires_at: Option<DateTime<Utc>>) -> io::Result<IpRoute> {
let mut guard = self.get_or_create_state().await?;
guard.port.add_route(cidr, via_router, preferred_until, expires_at).await
}
pub fn blocking_add_route(&self, cidr: IpCidr, via_router: IpAddr, preferred_until: Option<DateTime<Utc>>, expires_at: Option<DateTime<Utc>>) -> io::Result<IpRoute> {
block_on(self.add_route(cidr, via_router, preferred_until, expires_at))
}
pub async fn remove_route_by_address(&self, addr: IpAddr) -> io::Result<Option<IpRoute>> {
let mut guard = self.get_or_create_state().await?;
guard.port.remove_route_by_address(addr).await
}
pub fn blocking_remove_route_by_address(&self, addr: IpAddr) -> io::Result<Option<IpRoute>> {
block_on(self.remove_route_by_address(addr))
}
pub async fn remove_route_by_gateway(&self, gw_ip: IpAddr) -> io::Result<Option<IpRoute>> {
let mut guard = self.get_or_create_state().await?;
guard.port.remove_route_by_gateway(gw_ip).await
}
pub fn blocking_remove_route_by_gateway(&self, gw_ip: IpAddr) -> io::Result<Option<IpRoute>> {
block_on(self.remove_route_by_gateway(gw_ip))
}
pub async fn route_table(&self) -> io::Result<Vec<IpRoute>> {
let guard = self.get_or_create_state().await?;
Ok(guard.port.route_table().await)
}
pub fn blocking_route_table(&self) -> io::Result<Vec<IpRoute>> {
block_on(self.route_table())
}
pub async fn clear_route_table(&self) -> io::Result<()> {
let mut guard = self.get_or_create_state().await?;
guard.port.clear_route_table().await
}
pub fn blocking_clear_route_table(&self) -> io::Result<()> {
block_on(self.clear_route_table())
}
pub async fn addr_ipv4(&self) -> io::Result<Option<Ipv4Addr>> {
let guard = self.get_or_create_state().await?;
Ok(guard.port.addr_ipv4().await)
}
pub fn blocking_addr_ipv4(&self) -> io::Result<Option<Ipv4Addr>> {
block_on(self.addr_ipv4())
}
pub async fn addr_ipv6(&self) -> io::Result<Vec<Ipv6Addr>> {
let guard = self.get_or_create_state().await?;
Ok(guard.port.addr_ipv6().await)
}
pub fn blocking_addr_ipv6(&self) -> io::Result<Vec<Ipv6Addr>> {
block_on(self.addr_ipv6())
}
pub fn set_security(&mut self, security: StreamSecurity) {
self.security = security;
}
pub async fn bind_raw(
&self,
) -> io::Result<AsyncRawSocket> {
let guard = self.get_or_create_state().await?;
let socket = guard.port.bind_raw()
.await?;
Ok(
AsyncRawSocket::new(socket)
)
}
pub fn blocking_bind_raw(
&self,
) -> io::Result<RawSocket> {
Ok(RawSocket::new(block_on(self.bind_raw())?))
}
pub async fn listen_tcp(
&self,
addr: SocketAddr
) -> io::Result<AsyncTcpListener> {
let port = {
let guard = self.get_or_create_state().await?;
guard.port.clone()
};
Ok(AsyncTcpListener::new(port, addr).await?)
}
pub fn blocking_bind_tcp(
&self,
addr: SocketAddr
) -> io::Result<TcpListener> {
Ok(TcpListener::new(block_on(self.listen_tcp(addr))?))
}
pub async fn bind_udp(
&self,
addr: SocketAddr
) -> io::Result<AsyncUdpSocket> {
let (port, socket) = {
let guard = self.get_or_create_state().await?;
let port = guard.port.clone();
let socket = port
.bind_udp(addr)
.await?;
(port, socket)
};
Ok(AsyncUdpSocket::new(port, socket, addr))
}
pub fn blocking_bind_udp(
&self,
addr: SocketAddr
) -> io::Result<UdpSocket> {
Ok(UdpSocket::new(block_on(self.bind_udp(addr))?))
}
pub async fn bind_icmp(
&self,
addr: IpAddr
) -> io::Result<AsyncIcmpSocket> {
let guard = self.get_or_create_state().await?;
let port = guard.port.clone();
let socket = port
.bind_icmp(addr)
.await?;
Ok(AsyncIcmpSocket::new(socket, addr))
}
pub fn blocking_bind_icmp(
&self,
addr: IpAddr
) -> io::Result<IcmpSocket> {
Ok(IcmpSocket::new(block_on(self.bind_icmp(addr))?))
}
pub async fn connect_tcp(
&self,
addr: SocketAddr,
peer: SocketAddr,
) -> io::Result<AsyncTcpStream> {
let guard = self.get_or_create_state().await?;
let socket = guard.port
.connect_tcp(addr, peer)
.await?;
Ok(AsyncTcpStream::new(socket, addr, peer))
}
pub fn blocking_connect_tcp(
&self,
addr: SocketAddr,
peer: SocketAddr
) -> io::Result<TcpStream> {
Ok(TcpStream::new(block_on(self.connect_tcp(addr, peer))?))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/mod.rs | wasmer-bus/mio/src/mio/mod.rs | mod port;
mod blocking;
mod icmp_socket;
mod raw_socket;
mod tcp_listener;
mod tcp_stream;
mod udp_socket;
mod token;
pub use port::*;
pub use blocking::*;
pub use icmp_socket::*;
pub use raw_socket::*;
pub use tcp_listener::*;
pub use tcp_stream::*;
pub use udp_socket::*;
pub use token::*; | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/tcp_stream.rs | wasmer-bus/mio/src/mio/tcp_stream.rs | use std::io;
use std::collections::VecDeque;
use std::net::SocketAddr;
use tokio::sync::Mutex;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
use crate::comms::*;
#[derive(Debug)]
struct State
{
backlog: VecDeque<Vec<u8>>,
socket: Socket,
ttl: u8,
nodelay: bool,
shutdown: Option<std::net::Shutdown>,
}
#[derive(Debug)]
pub struct AsyncTcpStream
{
local_addr: SocketAddr,
peer_addr: SocketAddr,
state: Mutex<State>,
}
impl AsyncTcpStream {
pub(crate) fn new(socket: Socket, local_addr: SocketAddr, peer_addr: SocketAddr) -> Self {
Self {
local_addr,
peer_addr,
state: Mutex::new(State {
backlog: Default::default(),
socket,
ttl: 64,
nodelay: false,
shutdown: None,
}),
}
}
pub fn peer_addr(&self) -> SocketAddr {
self.peer_addr.clone()
}
pub fn local_addr(&self) -> SocketAddr {
self.local_addr.clone()
}
pub async fn shutdown(&self, shutdown: std::net::Shutdown) -> io::Result<()> {
let mut state = self.state.lock().await;
state.socket
.flush()
.await?;
state.shutdown = Some(shutdown);
Ok(())
}
pub async fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
let mut state = self.state.lock().await;
state.socket
.set_no_delay(nodelay)
.await?;
state.nodelay = nodelay;
Ok(())
}
pub async fn nodelay(&self) -> bool {
let state = self.state.lock().await;
state.nodelay
}
pub async fn set_ttl(&self, ttl: u8) -> io::Result<()> {
let mut state = self.state.lock().await;
state.socket
.set_ttl(ttl)
.await?;
state.ttl = ttl;
Ok(())
}
pub async fn ttl(&self) -> u8 {
let state = self.state.lock().await;
state.ttl
}
pub async fn peek(&self) -> io::Result<Vec<u8>> {
let mut state = self.state.lock().await;
if let Some(shutdown) = state.shutdown.as_ref() {
if shutdown == &std::net::Shutdown::Read || shutdown == &std::net::Shutdown::Both {
return Err(io::Error::new(io::ErrorKind::NotConnected, "reading has been shutdown for this socket"));
}
}
if let Some(buf) = state.backlog.pop_front() {
state.backlog.push_front(buf.clone());
return Ok(buf);
}
let buf = state.socket
.recv()
.await?;
state.backlog.push_back(buf.clone());
Ok(buf)
}
pub async fn recv(&self) -> io::Result<Vec<u8>> {
let mut state = self.state.lock().await;
if let Some(shutdown) = state.shutdown.as_ref() {
if shutdown == &std::net::Shutdown::Read || shutdown == &std::net::Shutdown::Both {
return Err(io::Error::new(io::ErrorKind::NotConnected, "reading has been shutdown for this socket"));
}
}
if let Some(buf) = state.backlog.pop_front() {
return Ok(buf);
}
state.socket
.recv()
.await
}
pub fn try_recv(&self) -> io::Result<Option<Vec<u8>>> {
if let Ok(mut state) = self.state.try_lock() {
if let Some(shutdown) = state.shutdown.as_ref() {
if shutdown == &std::net::Shutdown::Read || shutdown == &std::net::Shutdown::Both {
return Err(io::Error::new(io::ErrorKind::NotConnected, "reading has been shutdown for this socket"));
}
}
if let Some(buf) = state.backlog.pop_front() {
return Ok(Some(buf));
}
state.socket
.try_recv()
} else {
Ok(None)
}
}
pub async fn send(&self, buf: Vec<u8>) -> io::Result<usize> {
let state = self.state.lock().await;
if let Some(shutdown) = state.shutdown.as_ref() {
if shutdown == &std::net::Shutdown::Write || shutdown == &std::net::Shutdown::Both {
return Err(io::Error::new(io::ErrorKind::NotConnected, "writing has been shutdown for this socket"));
}
}
state.socket
.send(buf)
.await
}
pub async fn flush(&self) -> io::Result<()> {
let state = self.state.lock().await;
if let Some(shutdown) = state.shutdown.as_ref() {
if shutdown == &std::net::Shutdown::Write || shutdown == &std::net::Shutdown::Both {
return Err(io::Error::new(io::ErrorKind::NotConnected, "writing has been shutdown for this socket"));
}
}
state.socket
.flush()
.await
}
pub async fn is_connected(&self) -> bool {
let state = self.state.lock().await;
state.socket.is_connected()
}
pub fn blocking(self) -> super::TcpStream {
super::TcpStream::new(self)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/udp_socket.rs | wasmer-bus/mio/src/mio/udp_socket.rs | use std::io;
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use std::collections::VecDeque;
use tokio::sync::Mutex;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
use crate::comms::*;
use crate::comms::Port;
#[derive(Debug)]
struct State
{
socket: Socket,
ttl: u8,
backlog: VecDeque<(Vec<u8>, SocketAddr)>,
}
#[derive(Debug)]
pub struct AsyncUdpSocket
{
#[allow(dead_code)]
port: Port,
state: Mutex<State>,
addr: SocketAddr,
}
impl AsyncUdpSocket {
pub(crate) fn new(port: Port, socket: Socket, addr: SocketAddr) -> Self {
Self {
port,
state: Mutex::new(State {
socket,
ttl: 64,
backlog: Default::default(),
}),
addr,
}
}
pub async fn connect(&self, addr: SocketAddr) {
let mut state = self.state.lock().await;
state.socket
.connect(addr.clone());
}
pub async fn peer_addr(&self) -> Option<SocketAddr> {
let state = self.state.lock().await;
state.socket
.peer_addr()
.map(|a| a.clone())
}
pub fn local_addr(&self) -> SocketAddr {
self.addr.clone()
}
pub async fn recv_from(&self) -> io::Result<(Vec<u8>, SocketAddr)> {
let mut state = self.state.lock().await;
if let Some((buf, addr)) = state.backlog.pop_front() {
return Ok((buf, addr));
}
let (data, addr) = state.socket
.recv_from()
.await?;
Ok((data, addr))
}
pub fn try_recv_from(&self) -> io::Result<Option<(Vec<u8>, SocketAddr)>> {
if let Ok(mut state) = self.state.try_lock() {
if let Some((buf, addr)) = state.backlog.pop_front() {
return Ok(Some((buf, addr)));
}
state.socket
.try_recv_from()
} else {
Ok(None)
}
}
pub async fn peek_from(&self) -> io::Result<(Vec<u8>, SocketAddr)> {
let mut state = self.state.lock().await;
if let Some((data, addr)) = state.backlog.pop_front() {
state.backlog.push_front((data.clone(), addr.clone()));
return Ok((data, addr));
}
let (data, addr) = state.socket.recv_from()
.await?;
state.backlog.push_back((data.clone(), addr));
Ok((data, addr))
}
pub async fn send_to(&self, buf: Vec<u8>, addr: SocketAddr) -> io::Result<usize> {
let state = self.state.lock().await;
state.socket.send_to(buf, addr)
.await
}
pub async fn try_clone(&self) -> io::Result<Self> {
let local_addr = self.addr.clone();
let peer_addr = self.peer_addr().await;
let port = self.port.clone();
let socket = port
.bind_udp(local_addr)
.await?;
let ret = Self::new(port, socket, local_addr);
if let Some(peer_addr) = peer_addr {
ret.connect(peer_addr)
.await;
}
Ok(ret)
}
pub async fn set_ttl(&self, ttl: u8) -> io::Result<()> {
let mut state = self.state.lock().await;
state.socket
.set_ttl(ttl)
.await?;
state.ttl = ttl;
Ok(())
}
pub async fn ttl(&self) -> u8 {
let state = self.state.lock().await;
state.ttl
}
pub async fn send(&self, buf: Vec<u8>) -> io::Result<usize> {
let state = self.state.lock().await;
state.socket
.send(buf)
.await
}
pub async fn recv(&self) -> io::Result<Vec<u8>> {
let mut state = self.state.lock().await;
if let Some((buf, _)) = state.backlog.pop_front() {
return Ok(buf);
}
state.socket
.recv()
.await
}
pub fn try_recv(&self) -> io::Result<Option<Vec<u8>>> {
if let Ok(mut state) = self.state.try_lock() {
if let Some((buf, _)) = state.backlog.pop_front() {
return Ok(Some(buf));
}
state.socket
.try_recv()
} else {
Ok(None)
}
}
pub async fn peek(&self) -> io::Result<Vec<u8>> {
let mut state = self.state.lock().await;
for (buf, _) in state.backlog.iter() {
return Ok(buf.clone());
}
let data = state.socket
.recv()
.await?;
state.backlog.push_back((data.clone(), SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)));
Ok(data)
}
pub async fn is_connected(&self) -> bool {
let state = self.state.lock().await;
state.socket.is_connected()
}
pub fn blocking(self) -> super::UdpSocket {
super::UdpSocket::new(self)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/mio/token.rs | wasmer-bus/mio/src/mio/token.rs | use std::io::Write;
use ate_crypto::SerializationFormat;
use ate_crypto::error::SerializationError;
#[cfg(unix)]
use std::{
env::temp_dir,
os::unix::fs::{
PermissionsExt,
symlink
}
};
use crate::model::NetworkToken;
pub fn decode_access_token(token: String) -> Result<NetworkToken, SerializationError> {
let val = token.trim().to_string();
let bytes = base64::decode(val).unwrap();
Ok(SerializationFormat::MessagePack.deserialize(bytes)?)
}
pub fn load_access_token(token_path: String) -> Result<Option<NetworkToken>, SerializationError> {
let token_path = format!("{}.network", token_path);
let token_path = shellexpand::tilde(token_path.as_str()).to_string();
if let Ok(token) = std::fs::read_to_string(token_path) {
Ok(Some(decode_access_token(token)?))
} else {
Ok(None)
}
}
pub fn encode_access_token(token: &NetworkToken) -> Result<String, SerializationError> {
let bytes = SerializationFormat::MessagePack.serialize_ref(&token)?;
let bytes = base64::encode(bytes);
Ok(bytes)
}
pub async fn save_access_token(token_path: String, token: &NetworkToken) -> Result<(), SerializationError> {
let bytes = encode_access_token(token)?;
let token_path = format!("{}.network", token_path);
let token_path = shellexpand::tilde(token_path.as_str()).to_string();
// Remove any old paths
if let Ok(old) = std::fs::canonicalize(token_path.clone()) {
let _ = std::fs::remove_file(old);
}
let _ = std::fs::remove_file(token_path.clone());
// Create the folder structure
let path = std::path::Path::new(&token_path);
let _ = std::fs::create_dir_all(path.parent().unwrap().clone());
// Create a random file that will hold the token
#[cfg(unix)]
let save_path = random_file();
#[cfg(not(unix))]
let save_path = token_path;
{
// Create the folder structure
let path = std::path::Path::new(&save_path);
let _ = std::fs::create_dir_all(path.parent().unwrap().clone());
// Create the file
let mut file = std::fs::File::create(save_path.clone())?;
// Set the permissions so no one else can read it but the current user
#[cfg(unix)]
{
let mut perms = std::fs::metadata(save_path.clone())?.permissions();
perms.set_mode(0o600);
std::fs::set_permissions(save_path.clone(), perms)?;
}
// Write the token to it
file.write_all(bytes.as_bytes())?;
}
// Update the token path so that it points to this temporary token
#[cfg(unix)]
symlink(save_path, token_path)?;
Ok(())
}
pub async fn clear_access_token(token_path: String) {
let token_path = format!("{}.network", token_path);
let token_path = shellexpand::tilde(token_path.as_str()).to_string();
// Remove any old paths
if let Ok(old) = std::fs::canonicalize(token_path.clone()) {
let _ = std::fs::remove_file(old);
}
let _ = std::fs::remove_file(token_path.clone());
}
#[cfg(unix)]
pub fn random_file() -> String {
let mut tmp = temp_dir();
let rnd = ate_crypto::PrimaryKey::default().as_hex_string();
let file_name = format!("{}", rnd);
tmp.push(file_name);
let tmp_str = tmp.into_os_string().into_string().unwrap();
let tmp_str = shellexpand::tilde(&tmp_str).to_string();
tmp_str
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/shutdown.rs | wasmer-bus/mio/src/model/shutdown.rs | use serde::*;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum Shutdown
{
Read,
Write,
Both,
}
impl Into<std::net::Shutdown>
for Shutdown
{
fn into(self) -> std::net::Shutdown {
use Shutdown::*;
match self {
Read => std::net::Shutdown::Read,
Write => std::net::Shutdown::Write,
Both => std::net::Shutdown::Both,
}
}
}
impl From<std::net::Shutdown>
for Shutdown
{
fn from(s: std::net::Shutdown) -> Shutdown {
use Shutdown::*;
match s {
std::net::Shutdown::Read => Read,
std::net::Shutdown::Write => Write,
std::net::Shutdown::Both => Both,
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/port_response.rs | wasmer-bus/mio/src/model/port_response.rs | use std::net::SocketAddr;
use std::net::IpAddr;
use std::fmt;
use serde::*;
use super::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum PortResponse {
Nop {
handle: SocketHandle,
ty: PortNopType,
},
Received {
handle: SocketHandle,
data: Vec<u8>
},
ReceivedFrom {
handle: SocketHandle,
peer_addr: SocketAddr,
data: Vec<u8>,
},
TcpAccepted {
handle: SocketHandle,
peer_addr: SocketAddr,
},
SocketError {
handle: SocketHandle,
error: SocketError
},
DhcpDeconfigured {
handle: SocketHandle,
},
DhcpConfigured {
handle: SocketHandle,
address: IpCidr,
router: Option<IpAddr>,
dns_servers: Vec<IpAddr>,
},
CidrTable {
cidrs: Vec<IpCidr>,
},
RouteTable {
routes: Vec<IpRoute>,
},
Inited {
mac: HardwareAddress,
},
}
impl fmt::Display
for PortResponse
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortResponse::Nop {
handle,
ty,
} => write!(f, "nop(handle={}, ty={:?})", handle, ty),
PortResponse::Received {
handle,
data
} => write!(f, "received(handle={},len={})", handle, data.len()),
PortResponse::ReceivedFrom {
handle,
data,
peer_addr
} => write!(f, "received_from(handle={},len={},peer_addr={})", handle, data.len(), peer_addr),
PortResponse::TcpAccepted {
handle,
peer_addr,
} => write!(f, "tcp_accepted(handle={},peer_addr={})", handle, peer_addr),
PortResponse::SocketError {
handle,
error,
} => write!(f, "socket-error(handle={},err={})", handle, error),
PortResponse::DhcpDeconfigured {
handle,
} => write!(f, "dhcp-deconfigured(handle={})", handle),
PortResponse::DhcpConfigured {
handle,
address,
router,
dns_servers,
} => {
write!(f, "dhcp-configured(handle={},address={}", handle, address)?;
if let Some(router) = router {
write!(f, ",router={}", router)?;
}
if dns_servers.len() > 0 {
write!(f, ",dns-servers=[")?;
for dns_server in dns_servers.iter() {
write!(f, "{},", dns_server)?;
}
write!(f, "]")?;
}
write!(f, ")")
},
PortResponse::CidrTable {
cidrs,
} => {
write!(f, "cidr-table(")?;
for cidr in cidrs {
write!(f, "{}/{}", cidr.ip, cidr.prefix)?;
}
write!(f, ")")
},
PortResponse::RouteTable {
routes,
} => {
write!(f, "route-table(")?;
for route in routes {
write!(f, "{}/{}->{}", route.cidr.ip, route.cidr.prefix, route.via_router)?;
}
write!(f, ")")
},
PortResponse::Inited {
mac
} => {
write!(f, "initialized (mac={})", mac)
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/ip_cidr.rs | wasmer-bus/mio/src/model/ip_cidr.rs | use std::net::IpAddr;
use std::fmt;
use serde::*;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct IpCidr
{
pub ip: IpAddr,
pub prefix: u8,
}
impl IpCidr
{
pub fn gateway(&self) -> IpAddr {
match self.ip {
IpAddr::V4(ip) => {
let mut ip: u32 = ip.into();
ip += 1;
IpAddr::V4(ip.into())
},
IpAddr::V6(ip) => {
let mut ip: u128 = ip.into();
ip += 1;
IpAddr::V6(ip.into())
}
}
}
pub fn size(&self) -> u128 {
match self.ip {
IpAddr::V4(_) => {
let size = 32 - self.prefix;
2u128.pow(size as u32)
},
IpAddr::V6(_) => {
let size = 128 - self.prefix;
2u128.pow(size as u32)
}
}
}
pub fn broadcast(&self) -> IpAddr {
match self.ip {
IpAddr::V4(ip) => {
let mut ip: u32 = ip.into();
ip += self.size() as u32;
IpAddr::V4(ip.into())
},
IpAddr::V6(ip) => {
let mut ip: u128 = ip.into();
ip += self.size();
IpAddr::V6(ip.into())
}
}
}
}
impl fmt::Display
for IpCidr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "cidr(ip={},prefix={})", self.ip, self.prefix)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/port_command.rs | wasmer-bus/mio/src/model/port_command.rs | pub use chrono::DateTime;
pub use chrono::Utc;
use std::time::Duration;
use serde::*;
use std::net::IpAddr;
use std::net::SocketAddr;
use std::fmt;
use super::*;
pub const PORT_COMMAND_VERSION: u32 = 1;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum PortCommand {
Send {
handle: SocketHandle,
data: Vec<u8>
},
SendTo {
handle: SocketHandle,
data: Vec<u8>,
addr: SocketAddr,
},
MaySend {
handle: SocketHandle,
},
MayReceive {
handle: SocketHandle,
},
CloseHandle {
handle: SocketHandle,
},
BindRaw {
handle: SocketHandle,
},
BindUdp {
handle: SocketHandle,
local_addr: SocketAddr,
hop_limit: u8,
},
BindIcmp {
handle: SocketHandle,
local_addr: IpAddr,
hop_limit: u8,
},
BindDhcp {
handle: SocketHandle,
lease_duration: Option<Duration>,
ignore_naks: bool,
},
ConnectTcp {
handle: SocketHandle,
local_addr: SocketAddr,
peer_addr: SocketAddr,
hop_limit: u8
},
DhcpReset {
handle: SocketHandle,
},
Listen {
handle: SocketHandle,
local_addr: SocketAddr,
hop_limit: u8
},
SetHopLimit {
handle: SocketHandle,
hop_limit: u8
},
SetAckDelay {
handle: SocketHandle,
duration_ms: u32,
},
SetNoDelay {
handle: SocketHandle,
no_delay: bool,
},
SetTimeout {
handle: SocketHandle,
timeout: Option<Duration>,
},
SetKeepAlive {
handle: SocketHandle,
interval: Option<Duration>,
},
JoinMulticast {
multiaddr: IpAddr,
},
LeaveMulticast {
multiaddr: IpAddr,
},
SetHardwareAddress {
mac: HardwareAddress,
},
SetAddresses {
// Cidr - unicast address + prefix length
addrs: Vec<IpCidr>,
},
SetRoutes {
routes: Vec<IpRoute>,
},
SetPromiscuous {
handle: SocketHandle,
promiscuous: bool,
},
Init,
}
impl fmt::Display
for PortCommand
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortCommand::CloseHandle { handle } => write!(f, "close(handle={})", handle),
PortCommand::BindRaw { handle, .. } => write!(f, "bind-raw(handle={})", handle),
PortCommand::BindUdp { handle, local_addr: addr, .. } => write!(f, "bind-udp(handle={},addr={})", handle, addr),
PortCommand::BindIcmp { handle, local_addr: addr, .. } => write!(f, "bind-icmp(handle={},addr={})", handle, addr),
PortCommand::BindDhcp { handle, lease_duration, ignore_naks } => {
match lease_duration {
Some(lease_duration) => {
let lease_duration = lease_duration.as_secs_f64() / 60.0;
write!(f, "bind-dhcp(handle={},lease_duration={}m,ignore_naks={})", handle, lease_duration, ignore_naks)
},
None => write!(f, "bind-dhcp(handle={},ignore_naks={})", handle, ignore_naks)
}
},
PortCommand::ConnectTcp { handle, local_addr, peer_addr, .. } => write!(f, "connect-tcp(handle={},local_addr={},peer_addr={})", handle, local_addr, peer_addr),
PortCommand::DhcpReset { handle } => write!(f, "dhcp-reset(handle={})", handle),
PortCommand::Listen { handle, .. } => write!(f, "listen(handle={})", handle),
PortCommand::SetHopLimit { handle, hop_limit: ttl } => write!(f, "set-ttl(handle={},ttl={})", handle, ttl),
PortCommand::Send { handle, data } => write!(f, "send(handle={},len={})", handle, data.len()),
PortCommand::SendTo { handle, data, addr } => write!(f, "send-to(handle={},len={},addr={})", handle, data.len(), addr),
PortCommand::MaySend { handle } => write!(f, "may-send(handle={})", handle),
PortCommand::MayReceive { handle } => write!(f, "may-receive(handle={})", handle),
PortCommand::SetAckDelay { handle, duration_ms } => write!(f, "set-ack-delay(handle={},duration_ms={})", handle, duration_ms),
PortCommand::SetNoDelay { handle, no_delay } => write!(f, "set-keep-alive(handle={},interval={})", handle, no_delay),
PortCommand::SetPromiscuous { handle, promiscuous } => write!(f, "set-promiscuous(handle={},promiscuous={})", handle, promiscuous),
PortCommand::SetTimeout { handle, timeout } => {
match timeout {
Some(timeout) => {
let timeout = timeout.as_secs_f64() / 60.0;
write!(f, "set-no-delay(handle={},timeout={}m)", handle, timeout)
},
None => write!(f, "set-no-delay(handle={},timeout=none)", handle),
}
},
PortCommand::SetKeepAlive { handle, interval } => {
match interval {
Some(interval) => {
let interval = interval.as_secs_f64() / 60.0;
write!(f, "set-keep-alive(handle={},interval={}m)", handle, interval)
},
None => write!(f, "set-keep-alive(handle={},interval=none)", handle),
}
},
PortCommand::JoinMulticast { multiaddr } => write!(f, "join-multicast(multiaddr={})", multiaddr),
PortCommand::LeaveMulticast { multiaddr } => write!(f, "leave-multicast(multiaddr={})", multiaddr),
PortCommand::SetHardwareAddress { mac } => write!(f, "set-hardware-address(mac={})", mac),
PortCommand::SetAddresses { addrs: ips } => write!(f, "set-ip-addresses({:?})", ips),
PortCommand::SetRoutes { routes } => write!(f, "set-routes({:?})", routes),
PortCommand::Init => write!(f ,"init"),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/hardware_address.rs | wasmer-bus/mio/src/model/hardware_address.rs | use serde::*;
use std::fmt;
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HardwareAddress([u8; 6]);
impl HardwareAddress {
pub fn new() -> HardwareAddress {
HardwareAddress (
[6u8, fastrand::u8(..), fastrand::u8(..), fastrand::u8(..), fastrand::u8(..), fastrand::u8(2..)]
)
}
/// The broadcast address.
pub const BROADCAST: HardwareAddress = HardwareAddress([0xff; 6]);
/// The gateway address.
pub const GATEWAY: HardwareAddress = HardwareAddress([6u8, 0u8, 0u8, 0u8, 0u8, 1u8]);
/// Construct an Ethernet address from a sequence of octets, in big-endian.
///
/// # Panics
/// The function panics if `data` is not six octets long.
pub fn from_bytes(data: &[u8]) -> HardwareAddress {
let mut bytes = [0; 6];
bytes.copy_from_slice(data);
HardwareAddress(bytes)
}
/// Return an Ethernet address as a sequence of octets, in big-endian.
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
/// Query whether the address is an unicast address.
pub fn is_unicast(&self) -> bool {
!(self.is_broadcast() || self.is_multicast())
}
/// Query whether this address is the broadcast address.
pub fn is_broadcast(&self) -> bool {
*self == Self::BROADCAST
}
/// Query whether the "multicast" bit in the OUI is set.
pub fn is_multicast(&self) -> bool {
self.0[0] & 0x01 != 0
}
/// Query whether the "locally administered" bit in the OUI is set.
pub fn is_local(&self) -> bool {
self.0[0] & 0x02 != 0
}
}
impl fmt::Display
for HardwareAddress
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mac = hex::encode(&self.0).to_uppercase();
write!(f, "{}:{}:{}:{}:{}:{}", &mac[0..2], &mac[2..4], &mac[4..6], &mac[6..8], &mac[8..10], &mac[10..12])
}
}
impl Into<[u8; 6]>
for HardwareAddress
{
fn into(self) -> [u8; 6] {
self.0
}
}
impl From<[u8; 6]>
for HardwareAddress
{
fn from(mac: [u8; 6]) -> HardwareAddress {
HardwareAddress(mac)
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/port_nop.rs | wasmer-bus/mio/src/model/port_nop.rs | use serde::*;
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum PortNopType
{
MaySend,
MayReceive,
CloseHandle,
BindRaw,
BindIcmp,
BindDhcp,
DhcpReset,
BindUdp,
ConnectTcp,
Listen,
DhcpAcquire,
SetHopLimit,
SetAckDelay,
SetNoDelay,
SetPromiscuous,
SetTimeout,
SetKeepAlive,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/switch_hello.rs | wasmer-bus/mio/src/model/switch_hello.rs | use serde::*;
use std::fmt;
use ate_crypto::ChainKey;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SwitchHello {
pub chain: ChainKey,
pub access_token: String,
pub version: u32,
}
impl fmt::Display
for SwitchHello
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "switch-hello(key={},version={})", self.chain, self.version)
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/socket_handle.rs | wasmer-bus/mio/src/model/socket_handle.rs | use std::fmt;
use serde::*;
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SocketHandle(pub i32);
impl fmt::Display
for SocketHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "handle({})", self.0)
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/ip_route.rs | wasmer-bus/mio/src/model/ip_route.rs | use std::fmt;
use std::net::IpAddr;
use serde::*;
use chrono::DateTime;
use chrono::Utc;
use super::*;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct IpRoute
{
pub cidr: IpCidr,
pub via_router: IpAddr,
pub preferred_until: Option<DateTime<Utc>>,
pub expires_at: Option<DateTime<Utc>>
}
impl fmt::Display
for IpRoute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "route(cidr={},via={}", self.cidr, self.via_router)?;
if let Some(a) = self.preferred_until {
write!(f, ",preferred_until={}", a)?;
}
if let Some(a) = self.expires_at {
write!(f, ",expires_at={}", a)?;
}
write!(f, ")")
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/mod.rs | wasmer-bus/mio/src/model/mod.rs | mod hardware_address;
mod ip_cidr;
mod ip_protocol;
mod ip_route;
mod ip_version;
mod port_command;
mod port_nop;
mod port_response;
mod socket_error;
mod socket_handle;
mod socket_shutdown;
mod shutdown;
mod token;
mod switch_hello;
pub use hardware_address::*;
pub use ip_cidr::*;
pub use ip_protocol::*;
pub use ip_route::*;
pub use ip_version::*;
pub use port_command::*;
pub use port_nop::*;
pub use port_response::*;
pub use socket_error::*;
pub use socket_handle::*;
pub use socket_shutdown::*;
pub use shutdown::*;
pub use token::*;
pub use switch_hello::*;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/ip_version.rs | wasmer-bus/mio/src/model/ip_version.rs | use std::fmt;
use serde::*;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum IpVersion {
Ipv4,
Ipv6,
}
impl fmt::Display
for IpVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use IpVersion::*;
match self {
Ipv4 => write!(f, "ipv4"),
Ipv6 => write!(f, "ipv6"),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/socket_error.rs | wasmer-bus/mio/src/model/socket_error.rs | use std::error::Error;
use std::io;
use serde::*;
use std::fmt;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum SocketErrorKind {
NotFound,
PermissionDenied,
ConnectionRefused,
ConnectionReset,
HostUnreachable,
NetworkUnreachable,
ConnectionAborted,
NotConnected,
AddrInUse,
AddrNotAvailable,
NetworkDown,
BrokenPipe,
AlreadyExists,
WouldBlock,
NotADirectory,
IsADirectory,
DirectoryNotEmpty,
ReadOnlyFilesystem,
FilesystemLoop,
StaleNetworkFileHandle,
InvalidInput,
InvalidData,
TimedOut,
WriteZero,
StorageFull,
NotSeekable,
FilesystemQuotaExceeded,
FileTooLarge,
ResourceBusy,
ExecutableFileBusy,
Deadlock,
CrossesDevices,
TooManyLinks,
FilenameTooLong,
ArgumentListTooLong,
Interrupted,
Unsupported,
UnexpectedEof,
OutOfMemory,
Other,
Uncategorized,
}
impl SocketErrorKind
{
pub(crate) fn as_str(&self) -> &'static str {
use SocketErrorKind::*;
match *self {
AddrInUse => "address in use",
AddrNotAvailable => "address not available",
AlreadyExists => "entity already exists",
ArgumentListTooLong => "argument list too long",
BrokenPipe => "broken pipe",
ConnectionAborted => "connection aborted",
ConnectionRefused => "connection refused",
ConnectionReset => "connection reset",
CrossesDevices => "cross-device link or rename",
Deadlock => "deadlock",
DirectoryNotEmpty => "directory not empty",
ExecutableFileBusy => "executable file busy",
FileTooLarge => "file too large",
FilenameTooLong => "filename too long",
FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)",
FilesystemQuotaExceeded => "filesystem quota exceeded",
HostUnreachable => "host unreachable",
Interrupted => "operation interrupted",
InvalidData => "invalid data",
InvalidInput => "invalid input parameter",
IsADirectory => "is a directory",
NetworkDown => "network down",
NetworkUnreachable => "network unreachable",
NotADirectory => "not a directory",
NotConnected => "not connected",
NotFound => "entity not found",
NotSeekable => "seek on unseekable file",
Other => "other error",
OutOfMemory => "out of memory",
PermissionDenied => "permission denied",
ReadOnlyFilesystem => "read-only filesystem or storage medium",
ResourceBusy => "resource busy",
StaleNetworkFileHandle => "stale network file handle",
StorageFull => "no storage space",
TimedOut => "timed out",
TooManyLinks => "too many links",
Uncategorized => "uncategorized error",
UnexpectedEof => "unexpected end of file",
Unsupported => "unsupported",
WouldBlock => "operation would block",
WriteZero => "write zero",
}
}
}
impl From<io::ErrorKind>
for SocketErrorKind
{
fn from(kind: io::ErrorKind) -> SocketErrorKind {
match kind {
io::ErrorKind::NotFound => SocketErrorKind::NotFound,
io::ErrorKind::PermissionDenied => SocketErrorKind::PermissionDenied,
io::ErrorKind::ConnectionRefused => SocketErrorKind::ConnectionRefused,
io::ErrorKind::ConnectionReset => SocketErrorKind::ConnectionReset,
io::ErrorKind::ConnectionAborted => SocketErrorKind::ConnectionAborted,
io::ErrorKind::NotConnected => SocketErrorKind::NotConnected,
io::ErrorKind::AddrInUse => SocketErrorKind::AddrInUse,
io::ErrorKind::AddrNotAvailable => SocketErrorKind::AddrNotAvailable,
io::ErrorKind::BrokenPipe => SocketErrorKind::BrokenPipe,
io::ErrorKind::AlreadyExists => SocketErrorKind::AlreadyExists,
io::ErrorKind::WouldBlock => SocketErrorKind::WouldBlock,
io::ErrorKind::InvalidInput => SocketErrorKind::InvalidInput,
io::ErrorKind::InvalidData => SocketErrorKind::InvalidData,
io::ErrorKind::TimedOut => SocketErrorKind::TimedOut,
io::ErrorKind::WriteZero => SocketErrorKind::WriteZero,
io::ErrorKind::Interrupted => SocketErrorKind::Interrupted,
io::ErrorKind::Unsupported => SocketErrorKind::Unsupported,
io::ErrorKind::UnexpectedEof => SocketErrorKind::UnexpectedEof,
io::ErrorKind::OutOfMemory => SocketErrorKind::OutOfMemory,
io::ErrorKind::Other => SocketErrorKind::Other,
_ => SocketErrorKind::Other,
}
}
}
impl Into<SocketError>
for SocketErrorKind
{
fn into(self) -> SocketError {
SocketError::Simple(self)
}
}
impl Into<io::ErrorKind>
for SocketErrorKind
{
fn into(self) -> io::ErrorKind {
match self {
SocketErrorKind::NotFound => io::ErrorKind::NotFound,
SocketErrorKind::PermissionDenied => io::ErrorKind::PermissionDenied,
SocketErrorKind::ConnectionRefused => io::ErrorKind::ConnectionRefused,
SocketErrorKind::ConnectionReset => io::ErrorKind::ConnectionReset,
SocketErrorKind::ConnectionAborted => io::ErrorKind::ConnectionAborted,
SocketErrorKind::NotConnected => io::ErrorKind::NotConnected,
SocketErrorKind::AddrInUse => io::ErrorKind::AddrInUse,
SocketErrorKind::AddrNotAvailable => io::ErrorKind::AddrNotAvailable,
SocketErrorKind::BrokenPipe => io::ErrorKind::BrokenPipe,
SocketErrorKind::AlreadyExists => io::ErrorKind::AlreadyExists,
SocketErrorKind::WouldBlock => io::ErrorKind::WouldBlock,
SocketErrorKind::InvalidInput => io::ErrorKind::InvalidInput,
SocketErrorKind::InvalidData => io::ErrorKind::InvalidData,
SocketErrorKind::TimedOut => io::ErrorKind::TimedOut,
SocketErrorKind::WriteZero => io::ErrorKind::WriteZero,
SocketErrorKind::Interrupted => io::ErrorKind::Interrupted,
SocketErrorKind::Unsupported => io::ErrorKind::Unsupported,
SocketErrorKind::UnexpectedEof => io::ErrorKind::UnexpectedEof,
SocketErrorKind::OutOfMemory => io::ErrorKind::OutOfMemory,
SocketErrorKind::Other => io::ErrorKind::Other,
_ => io::ErrorKind::Other,
}
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum SocketError {
Os(i32),
Simple(SocketErrorKind),
SimpleMessage(SocketErrorKind, String),
}
impl SocketError
{
pub fn new(kind: SocketErrorKind, msg: String) -> SocketError {
SocketError::SimpleMessage(kind, msg)
}
}
impl From<io::Error>
for SocketError
{
fn from(err: io::Error) -> SocketError {
if let Some(code) = err.raw_os_error() {
return SocketError::Os(code);
}
#[allow(deprecated)]
let desc = err.description();
let kind: SocketErrorKind = err.kind().into();
if kind.as_str() == desc {
SocketError::Simple(kind)
} else {
SocketError::SimpleMessage(kind, desc.to_string())
}
}
}
impl Into<io::Error>
for SocketError
{
fn into(self) -> io::Error {
match self {
SocketError::Os(code) => io::Error::from_raw_os_error(code),
SocketError::Simple(kind) => {
let kind: io::ErrorKind = kind.into();
kind.into()
},
SocketError::SimpleMessage(kind, msg) => {
let kind: io::ErrorKind = kind.into();
io::Error::new(kind, msg.as_str())
},
}
}
}
impl fmt::Display
for SocketError
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SocketError::Os(code) => write!(f, "socket-error(os={})", code),
SocketError::Simple(kind) => write!(f, "socket-error(kind={})", kind.as_str()),
SocketError::SimpleMessage(kind, msg) => write!(f, "socket-error(kind={}, msg='{}')", kind.as_str(), msg),
}
}
}
pub type SocketResult<T> = std::result::Result<T, SocketError>; | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/ip_protocol.rs | wasmer-bus/mio/src/model/ip_protocol.rs | use std::fmt;
use serde::*;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum IpProtocol {
HopByHop,
Icmp,
Igmp,
Tcp,
Udp,
Ipv6Route,
Ipv6Frag,
Icmpv6,
Ipv6NoNxt,
Ipv6Opts,
Unknown(u8),
}
impl IpProtocol
{
pub fn is_connection_oriented(&self) -> bool {
match self {
IpProtocol::Tcp => true,
_ => false,
}
}
}
impl fmt::Display
for IpProtocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use IpProtocol::*;
match self {
HopByHop => write!(f, "hop-by-hop"),
Icmp => write!(f, "icmp"),
Igmp => write!(f, "igmp"),
Tcp => write!(f, "tcp"),
Udp => write!(f, "udp"),
Ipv6Route => write!(f, "ipv6-route"),
Ipv6Frag => write!(f, "ipv6-flag"),
Icmpv6 => write!(f, "icmpv6"),
Ipv6NoNxt => write!(f, "ipv6-no-nxt"),
Ipv6Opts => write!(f, "ipv6-opts"),
Unknown(a) => write!(f, "unknown({})", a),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/token.rs | wasmer-bus/mio/src/model/token.rs | use std::fmt;
use std::str::FromStr;
use serde::*;
use ate_crypto::ChainKey;
use ate_crypto::SerializationFormat;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NetworkToken {
pub chain: ChainKey,
pub access_token: String,
}
impl fmt::Display
for NetworkToken
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let bytes = SerializationFormat::MessagePack.serialize(self).unwrap();
let bytes = base64::encode(bytes);
write!(f, "{}", bytes)
}
}
impl FromStr
for NetworkToken
{
type Err = ate_crypto::error::SerializationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let bytes = base64::decode(s)?;
Ok(SerializationFormat::MessagePack.deserialize(bytes)?)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/model/socket_shutdown.rs | wasmer-bus/mio/src/model/socket_shutdown.rs | use std::fmt;
use serde::*;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum SocketShutdown
{
Read,
Write,
Both,
}
impl fmt::Display
for SocketShutdown {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use SocketShutdown::*;
match self {
Read => write!(f, "shutdown(read)"),
Write => write!(f, "shutdown(write)"),
Both => write!(f, "shutdown(both)"),
}
}
}
impl Into<std::net::Shutdown>
for SocketShutdown
{
fn into(self) -> std::net::Shutdown {
use SocketShutdown::*;
match self {
Read => std::net::Shutdown::Read,
Write => std::net::Shutdown::Write,
Both => std::net::Shutdown::Both,
}
}
}
impl From<std::net::Shutdown>
for SocketShutdown
{
fn from(s: std::net::Shutdown) -> SocketShutdown {
use SocketShutdown::*;
match s {
std::net::Shutdown::Read => Read,
std::net::Shutdown::Write => Write,
std::net::Shutdown::Both => Both,
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/comms/port.rs | wasmer-bus/mio/src/comms/port.rs |
use std::io;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::sync::Arc;
use std::ops::Deref;
use std::collections::BTreeMap;
#[cfg(feature = "crypto")]
use ate_crypto::EncryptKey;
use chrono::DateTime;
use chrono::Utc;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
use derivative::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use crate::model::HardwareAddress;
use crate::model::IpCidr;
use crate::model::IpRoute;
use crate::model::IpProtocol;
use crate::model::PortCommand;
use crate::model::PortResponse;
use crate::model::PortNopType;
use crate::model::SocketHandle;
pub use ate_comms::StreamRx;
pub use ate_comms::StreamTx;
use super::evt::*;
use super::socket::*;
const MAX_MPSC: usize = std::usize::MAX >> 3;
#[derive(Debug)]
pub struct SocketState
{
nop: mpsc::Sender<PortNopType>,
recv: mpsc::Sender<EventRecv>,
recv_from: mpsc::Sender<EventRecvFrom>,
error: mpsc::Sender<EventError>,
accept: mpsc::Sender<EventAccept>,
}
#[derive(Debug, Default)]
pub struct PortState
{
mac: Option<HardwareAddress>,
addresses: Vec<IpCidr>,
routes: Vec<IpRoute>,
router: Option<IpAddr>,
dns_servers: Vec<IpAddr>,
sockets: BTreeMap<i32, SocketState>,
dhcp_client: Option<Socket>,
}
#[derive(Derivative, Clone)]
#[derivative(Debug)]
pub struct Port
{
#[derivative(Debug = "ignore")]
tx: Arc<Mutex<StreamTx>>,
state: Arc<Mutex<PortState>>,
}
impl Port
{
pub async fn new(rx: StreamRx, tx: StreamTx) -> io::Result<Port>
{
let (init_tx, mut init_rx) = mpsc::channel(1);
let state = Arc::new(Mutex::new(PortState::default()));
{
let state = state.clone();
tokio::spawn(async move {
Self::run(rx, state, init_tx).await
});
}
let port = Port {
tx: Arc::new(Mutex::new(tx)),
#[cfg(feature = "crypto")]
ek,
state: Arc::clone(&state),
};
port.tx(PortCommand::Init).await?;
let mac = init_rx
.recv()
.await
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "failed to initialize the socket before it was closed."))?;
{
let mut state = state.lock().await;
state.mac.replace(mac);
}
Ok(port)
}
async fn new_socket(&self, proto: Option<IpProtocol>) -> Socket {
let mut state = self.state.lock().await;
let sockets = &mut state.sockets;
let handle = sockets.iter()
.rev()
.next()
.map(|e| e.0.clone() + 1)
.unwrap_or_else(|| 1i32);
let (tx_nop, rx_nop) = mpsc::channel(MAX_MPSC);
let (tx_recv, rx_recv) = mpsc::channel(MAX_MPSC);
let (tx_recv_from, rx_recv_from) = mpsc::channel(MAX_MPSC);
let (tx_error, rx_error) = mpsc::channel(MAX_MPSC);
let (tx_accept, rx_accept) = mpsc::channel(MAX_MPSC);
sockets.insert(handle, SocketState{
nop: tx_nop,
recv: tx_recv,
recv_from: tx_recv_from,
error: tx_error,
accept: tx_accept,
});
let handle = SocketHandle(handle);
Socket {
handle,
proto,
peer_addr: None,
tx: self.tx.clone(),
#[cfg(feature = "crypto")]
ek: self.ek.clone(),
nop: rx_nop,
recv: rx_recv,
recv_from: rx_recv_from,
error: rx_error,
accept: rx_accept,
}
}
pub async fn bind_raw(&self) -> io::Result<Socket> {
let mut socket = self.new_socket(None).await;
socket.tx(PortCommand::BindRaw {
handle: socket.handle,
}).await?;
socket.nop(PortNopType::BindRaw).await?;
Ok(socket)
}
pub async fn bind_udp(&self, local_addr: SocketAddr) -> io::Result<Socket> {
let mut socket = self.new_socket(Some(IpProtocol::Udp)).await;
socket.tx(PortCommand::BindUdp {
handle: socket.handle,
local_addr,
hop_limit: Socket::HOP_LIMIT,
}).await?;
socket.nop(PortNopType::BindUdp).await?;
Ok(socket)
}
pub async fn bind_icmp(&self, local_addr: IpAddr) -> io::Result<Socket> {
let mut socket = self.new_socket(Some(IpProtocol::Icmp)).await;
socket.tx(PortCommand::BindIcmp {
handle: socket.handle,
local_addr,
hop_limit: Socket::HOP_LIMIT,
}).await?;
socket.nop(PortNopType::BindIcmp).await?;
Ok(socket)
}
pub async fn bind_dhcp(&self) -> io::Result<Socket> {
let mut socket = self.new_socket(Some(IpProtocol::Icmp)).await;
socket.tx(PortCommand::BindDhcp {
handle: socket.handle,
lease_duration: None,
ignore_naks: false,
}).await?;
socket.nop(PortNopType::BindDhcp).await?;
Ok(socket)
}
pub async fn connect_tcp(&self, local_addr: SocketAddr, peer_addr: SocketAddr) -> io::Result<Socket> {
let mut socket = self.new_socket(Some(IpProtocol::Tcp)).await;
socket.tx(PortCommand::ConnectTcp {
handle: socket.handle,
local_addr,
peer_addr,
hop_limit: Socket::HOP_LIMIT,
}).await?;
socket.nop(PortNopType::ConnectTcp).await?;
socket.wait_till_may_send().await?;
Ok(socket)
}
pub async fn listen_tcp(&self, listen_addr: SocketAddr) -> io::Result<Socket> {
let mut socket = self.new_socket(Some(IpProtocol::Tcp)).await;
socket.tx(PortCommand::Listen {
handle: socket.handle,
local_addr: listen_addr,
hop_limit: Socket::HOP_LIMIT,
}).await?;
socket.nop(PortNopType::Listen).await?;
Ok(socket)
}
pub async fn dhcp_acquire(&self) -> io::Result<(Ipv4Addr, Ipv4Addr)> {
let mut socket = self.bind_dhcp().await?;
socket.nop(PortNopType::DhcpAcquire).await?;
let mut state = self.state.lock().await;
state.dhcp_client = Some(socket);
state.addresses
.clone()
.into_iter()
.filter_map(|cidr| {
match &cidr.ip {
IpAddr::V4(a) => {
let prefix = 32u32 - (cidr.prefix as u32);
let mask = if prefix <= 1 {
u32::MAX.into()
} else {
let mask = 2u32.pow(prefix) - 1u32;
let mask = mask ^ u32::MAX;
let mask: Ipv4Addr = mask.into();
mask.into()
};
Some((a.clone(), mask))
},
_ => None,
}
})
.next()
.ok_or_else(|| {
io::Error::new(io::ErrorKind::AddrNotAvailable, "dhcp server did not return an IP address")
})
}
pub async fn add_ip(&mut self, ip: IpAddr, prefix: u8) -> io::Result<IpCidr> {
let cidr = IpCidr {
ip,
prefix,
};
{
let mut state = self.state.lock().await;
state.addresses.push(cidr.clone());
}
self.update_ips().await?;
Ok(cidr)
}
pub async fn remove_ip(&mut self, ip: IpAddr) -> io::Result<Option<IpCidr>> {
let ret = {
let mut state = self.state.lock().await;
let ret = state.addresses.iter().filter(|cidr| cidr.ip == ip).map(|cidr| cidr.clone()).next();
state.addresses.retain(|cidr| cidr.ip != ip);
state.routes.retain(|route| route.cidr.ip != ip);
ret
};
self.update_ips().await?;
self.update_routes().await?;
Ok(ret)
}
pub async fn hardware_address(&self) -> Option<HardwareAddress> {
let state = self.state.lock().await;
state.mac
}
pub async fn ips(&self) -> Vec<IpCidr> {
let state = self.state.lock().await;
state.addresses.clone()
}
pub async fn clear_ips(&mut self) -> io::Result<()> {
{
let mut state = self.state.lock().await;
state.addresses.clear();
state.routes.clear();
}
self.update_ips().await?;
self.update_routes().await?;
Ok(())
}
async fn update_ips(&mut self) -> io::Result<()> {
let addrs = {
let state = self.state.lock().await;
state.addresses.clone()
};
self.tx(PortCommand::SetAddresses { addrs }).await
}
pub async fn add_default_route(&mut self, gateway: IpAddr) -> io::Result<IpRoute> {
let cidr = IpCidr {
ip: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
prefix: 0
};
self.add_route(cidr, gateway, None, None).await
}
pub async fn add_route(&mut self, cidr: IpCidr, via_router: IpAddr, preferred_until: Option<DateTime<Utc>>, expires_at: Option<DateTime<Utc>>) -> io::Result<IpRoute> {
let route = IpRoute {
cidr,
via_router,
preferred_until,
expires_at
};
{
let mut state = self.state.lock().await;
state.routes.push(route.clone());
}
self.update_routes().await?;
Ok(route)
}
pub async fn remove_route_by_address(&mut self, addr: IpAddr) -> io::Result<Option<IpRoute>> {
let ret = {
let mut state = self.state.lock().await;
let ret = state.routes.iter().filter(|route| route.cidr.ip == addr).map(|route| route.clone()).next();
state.routes.retain(|route| route.cidr.ip != addr);
ret
};
self.update_routes().await?;
Ok(ret)
}
pub async fn remove_route_by_gateway(&mut self, gw_ip: IpAddr) -> io::Result<Option<IpRoute>> {
let ret = {
let mut state = self.state.lock().await;
let ret = state.routes.iter().filter(|route| route.via_router == gw_ip).map(|route| route.clone()).next();
state.routes.retain(|route| route.via_router != gw_ip);
ret
};
self.update_routes().await?;
Ok(ret)
}
pub async fn route_table(&self) -> Vec<IpRoute> {
let state = self.state.lock().await;
state.routes.clone()
}
pub async fn clear_route_table(&mut self) -> io::Result<()> {
{
let mut state = self.state.lock().await;
state.routes.clear();
}
self.update_routes().await?;
Ok(())
}
async fn update_routes(&mut self) -> io::Result<()> {
let routes = {
let state = self.state.lock().await;
state.routes.clone()
};
self.tx(PortCommand::SetRoutes { routes }).await
}
pub async fn addr_ipv4(&self) -> Option<Ipv4Addr>
{
let state = self.state.lock().await;
state.addresses
.iter()
.filter_map(|cidr| {
match cidr.ip {
IpAddr::V4(a) => Some(a.clone()),
_ => None
}
})
.next()
}
pub async fn addr_ipv6(&self) -> Vec<Ipv6Addr>
{
let state = self.state.lock().await;
state.addresses
.iter()
.filter_map(|cidr| {
match &cidr.ip {
IpAddr::V6(a) => Some(a.clone()),
_ => None
}
})
.collect()
}
async fn tx(&self, cmd: PortCommand) -> io::Result<()> {
let cmd = bincode::serialize(&cmd)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
let mut tx = self.tx.lock().await;
tx.write(&cmd[..]).await?;
Ok(())
}
async fn run_evt(state: &Mutex<PortState>, init_tx: &mpsc::Sender<HardwareAddress>, evt: Vec<u8>)
{
if let Ok(evt) = bincode::deserialize::<PortResponse>(&evt[..]) {
let mut state = state.lock().await;
match evt {
PortResponse::Nop {
handle,
ty
} => {
if let Some(socket) = state.sockets.get(&handle.0) {
let _ = socket.nop.send(ty).await;
}
}
PortResponse::Received {
handle,
data
} => {
if let Some(socket) = state.sockets.get(&handle.0) {
let _ = socket.recv.send(EventRecv { data }).await;
}
}
PortResponse::ReceivedFrom {
handle,
peer_addr,
data,
} => {
if let Some(socket) = state.sockets.get(&handle.0) {
let _ = socket.recv_from.send(EventRecvFrom { peer_addr, data }).await;
}
}
PortResponse::TcpAccepted {
handle,
peer_addr,
} => {
if let Some(socket) = state.sockets.get(&handle.0) {
let _ = socket.accept.send(EventAccept { peer_addr }).await;
}
}
PortResponse::SocketError {
handle,
error,
} => {
if let Some(socket) = state.sockets.get(&handle.0) {
let _ = socket.error.send(EventError { error }).await;
}
}
PortResponse::CidrTable {
cidrs
} => {
state.addresses = cidrs;
}
PortResponse::RouteTable {
routes
} => {
state.routes = routes;
}
PortResponse::DhcpDeconfigured {
handle: _,
} => {
state.addresses.clear();
state.router = None;
state.dns_servers.clear();
}
PortResponse::DhcpConfigured {
handle: _,
address,
router,
dns_servers,
} => {
state.addresses.retain(|cidr| cidr.ip != address.ip);
state.addresses.push(address);
state.router = router;
state.dns_servers = dns_servers;
}
PortResponse::Inited {
mac,
} => {
let _ = init_tx.send(mac).await;
}
}
}
}
async fn run_exit(state: &Mutex<PortState>) {
debug!("mio port closed");
// Clearing the sockets will shut them all down
let mut state = state.lock().await;
state.dhcp_client = None;
state.sockets.clear();
}
async fn run(mut rx: StreamRx, state: Arc<Mutex<PortState>>, init_tx: mpsc::Sender<HardwareAddress>) {
while let Ok(evt) = rx.read().await {
Self::run_evt(state.deref(), &init_tx, evt).await
}
Self::run_exit(state.deref()).await
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/comms/mod.rs | wasmer-bus/mio/src/comms/mod.rs | mod evt;
mod port;
mod socket;
pub(crate) use port::*;
pub(crate) use socket::*; | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/comms/evt.rs | wasmer-bus/mio/src/comms/evt.rs | use std::net::SocketAddr;
use crate::model::SocketError;
pub struct EventRecv {
pub data: Vec<u8>
}
pub struct EventRecvFrom {
pub peer_addr: SocketAddr,
pub data: Vec<u8>,
}
pub struct EventAccept {
pub peer_addr: SocketAddr,
}
pub struct EventError {
pub error: SocketError
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/src/comms/socket.rs | wasmer-bus/mio/src/comms/socket.rs | use std::io;
use std::sync::Arc;
use std::net::SocketAddr;
#[cfg(feature = "crypto")]
use ate_crypto::EncryptKey;
use tokio::sync::mpsc;
use tokio::sync::Mutex;
use mpsc::error::TryRecvError;
use derivative::*;
use wasmer_bus_time::prelude::sleep;
use crate::model::PortCommand;
use crate::model::PortNopType;
use crate::model::SocketHandle;
use crate::model::IpProtocol;
use super::port::StreamTx;
use super::evt::*;
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Socket
{
pub(super) proto: Option<IpProtocol>,
pub(super) handle: SocketHandle,
pub(super) peer_addr: Option<SocketAddr>,
#[derivative(Debug = "ignore")]
pub(super) tx: Arc<Mutex<StreamTx>>,
#[cfg(feature = "crypto")]
pub(super) ek: Option<EncryptKey>,
pub(super) nop: mpsc::Receiver<PortNopType>,
pub(super) recv: mpsc::Receiver<EventRecv>,
pub(super) recv_from: mpsc::Receiver<EventRecvFrom>,
pub(super) error: mpsc::Receiver<EventError>,
pub(super) accept: mpsc::Receiver<EventAccept>,
}
impl Socket
{
pub(super) const HOP_LIMIT: u8 = 64;
pub async fn send(&self, data: Vec<u8>) -> io::Result<usize> {
let len = data.len();
if self.proto.map(|p| p.is_connection_oriented()).unwrap_or(true) {
self.tx(PortCommand::Send {
handle: self.handle,
data,
}).await?;
} else if let Some(peer_addr) = self.peer_addr {
self.tx(PortCommand::SendTo {
handle: self.handle,
data,
addr: peer_addr,
}).await?;
} else {
return Err(io::Error::from(io::ErrorKind::NotConnected));
}
Ok(len)
}
pub async fn send_to(&self, data: Vec<u8>, peer_addr: SocketAddr) -> io::Result<usize> {
let len = data.len();
if self.proto.map(|p| p.is_connection_oriented()).unwrap_or(true) {
return Err(io::Error::from(io::ErrorKind::Unsupported));
} else {
self.tx(PortCommand::SendTo {
handle: self.handle,
data,
addr: peer_addr,
}).await?;
}
Ok(len)
}
pub async fn recv(&mut self) -> io::Result<Vec<u8>> {
if self.proto.map(|p| p.is_connection_oriented()).unwrap_or(true)
{
tokio::select! {
evt = self.recv.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
Ok(evt.data)
},
evt = self.error.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
Err(evt.error.into())
}
}
} else if let Some(peer_addr) = self.peer_addr {
loop {
tokio::select! {
evt = self.recv_from.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
if evt.peer_addr != peer_addr {
continue;
}
return Ok(evt.data);
},
evt = self.error.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
return Err(evt.error.into());
}
}
}
} else {
Err(io::Error::from(io::ErrorKind::NotConnected))
}
}
#[allow(dead_code)]
pub fn try_recv(&mut self) -> io::Result<Option<Vec<u8>>> {
if self.proto.map(|p| p.is_connection_oriented()).unwrap_or(true)
{
match self.error.try_recv() {
Ok(evt) => { return Err(evt.error.into()); },
Err(TryRecvError::Disconnected) => { return Err(io::Error::from(io::ErrorKind::ConnectionAborted)); }
Err(TryRecvError::Empty) => { }
}
match self.recv.try_recv() {
Ok(evt) => Ok(Some(evt.data)),
Err(TryRecvError::Disconnected) => Err(io::Error::from(io::ErrorKind::ConnectionAborted)),
Err(TryRecvError::Empty) => Ok(None)
}
} else if let Some(peer_addr) = self.peer_addr {
loop {
match self.error.try_recv() {
Ok(evt) => { return Err(evt.error.into()); },
Err(TryRecvError::Disconnected) => { return Err(io::Error::from(io::ErrorKind::ConnectionAborted)); }
Err(TryRecvError::Empty) => { }
}
return match self.recv_from.try_recv() {
Ok(evt) => {
if evt.peer_addr != peer_addr {
continue;
}
Ok(Some(evt.data))
},
Err(TryRecvError::Disconnected) => Err(io::Error::from(io::ErrorKind::ConnectionAborted)),
Err(TryRecvError::Empty) => Ok(None)
};
}
} else {
Err(io::Error::from(io::ErrorKind::NotConnected))
}
}
pub async fn recv_from(&mut self) -> io::Result<(Vec<u8>, SocketAddr)> {
if let Some(peer_addr) = self.peer_addr {
tokio::select! {
evt = self.recv.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
Ok((evt.data, peer_addr))
},
evt = self.recv_from.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
Ok((evt.data, evt.peer_addr))
},
evt = self.error.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
Err(evt.error.into())
}
}
} else {
tokio::select! {
evt = self.recv_from.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
Ok((evt.data, evt.peer_addr))
},
evt = self.error.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
Err(evt.error.into())
}
}
}
}
#[allow(dead_code)]
pub fn try_recv_from(&mut self) -> io::Result<Option<(Vec<u8>, SocketAddr)>> {
if let Some(peer_addr) = self.peer_addr {
match self.error.try_recv() {
Ok(evt) => { return Err(evt.error.into()); },
Err(TryRecvError::Disconnected) => { return Err(io::Error::from(io::ErrorKind::ConnectionAborted)); }
Err(TryRecvError::Empty) => { }
}
match self.recv.try_recv() {
Ok(evt) => { return Ok(Some((evt.data, peer_addr))); },
Err(TryRecvError::Disconnected) => { return Err(io::Error::from(io::ErrorKind::ConnectionAborted)); },
Err(TryRecvError::Empty) => { }
}
match self.recv_from.try_recv() {
Ok(evt) => Ok(Some((evt.data, evt.peer_addr))),
Err(TryRecvError::Disconnected) => Err(io::Error::from(io::ErrorKind::ConnectionAborted)),
Err(TryRecvError::Empty) => Ok(None)
}
} else {
match self.error.try_recv() {
Ok(evt) => { return Err(evt.error.into()); },
Err(TryRecvError::Disconnected) => { return Err(io::Error::from(io::ErrorKind::ConnectionAborted)); }
Err(TryRecvError::Empty) => { }
}
match self.recv_from.try_recv() {
Ok(evt) => Ok(Some((evt.data, evt.peer_addr))),
Err(TryRecvError::Disconnected) => Err(io::Error::from(io::ErrorKind::ConnectionAborted)),
Err(TryRecvError::Empty) => Ok(None)
}
}
}
pub async fn accept(&mut self) -> io::Result<SocketAddr> {
tokio::select! {
evt = self.accept.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
self.peer_addr.replace(evt.peer_addr.clone());
Ok(evt.peer_addr)
},
evt = self.error.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
Err(evt.error.into())
}
}
}
pub async fn set_ttl(&mut self, ttl: u8) -> io::Result<bool> {
self.tx(PortCommand::SetHopLimit {
handle: self.handle,
hop_limit: ttl,
}).await?;
match self.nop(PortNopType::SetHopLimit).await {
Ok(()) => Ok(true),
Err(err) if err.kind() == io::ErrorKind::WouldBlock => Ok(false),
Err(err) => Err(err)
}
}
pub async fn flush(&self) -> io::Result<()> {
let mut tx = self.tx.lock().await;
tx.flush().await
}
pub async fn set_no_delay(&mut self, no_delay: bool) -> io::Result<bool> {
self.tx(PortCommand::SetNoDelay {
handle: self.handle,
no_delay,
}).await?;
match self.nop(PortNopType::SetNoDelay).await {
Ok(()) => Ok(true),
Err(err) if err.kind() == io::ErrorKind::WouldBlock => Ok(false),
Err(err) => Err(err)
}
}
pub async fn set_promiscuous(&mut self, promiscuous: bool) -> io::Result<bool> {
self.tx(PortCommand::SetPromiscuous {
handle: self.handle,
promiscuous,
}).await?;
match self.nop(PortNopType::SetPromiscuous).await {
Ok(()) => Ok(true),
Err(err) if err.kind() == io::ErrorKind::WouldBlock => Ok(false),
Err(err) => Err(err)
}
}
pub async fn may_send(&mut self) -> io::Result<bool> {
self.tx(PortCommand::MaySend {
handle: self.handle,
}).await?;
match self.nop(PortNopType::MaySend).await {
Ok(()) => Ok(true),
Err(err) if err.kind() == io::ErrorKind::WouldBlock => Ok(false),
Err(err) => Err(err)
}
}
#[allow(dead_code)]
pub async fn may_receive(&mut self) -> io::Result<bool> {
self.tx(PortCommand::MayReceive {
handle: self.handle,
}).await?;
match self.nop(PortNopType::MayReceive).await {
Ok(()) => Ok(true),
Err(err) if err.kind() == io::ErrorKind::WouldBlock => Ok(false),
Err(err) => Err(err)
}
}
pub(super) async fn nop(&mut self, ty: PortNopType) -> io::Result<()> {
loop {
tokio::select! {
tst = self.nop.recv() => {
let tst = tst.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
if tst != ty {
continue;
}
return Ok(());
},
evt = self.error.recv() => {
let evt = evt.ok_or_else(|| io::Error::from(io::ErrorKind::ConnectionAborted))?;
return Err(evt.error.into());
}
}
}
}
pub async fn wait_till_may_send(&mut self) -> io::Result<()> {
let mut time = 0u64;
loop {
time = time * 2;
time += 1;
if time > 50 {
time = 50;
}
if self.may_send().await? == true {
return Ok(());
}
sleep(std::time::Duration::from_millis(time)).await;
}
}
#[allow(dead_code)]
pub async fn wait_till_may_receive(&mut self) -> io::Result<()> {
let mut time = 0u64;
loop {
time = time * 2;
time += 1;
if time > 50 {
time = 50;
}
if self.may_receive().await? == true {
return Ok(());
}
sleep(std::time::Duration::from_millis(time)).await;
}
}
pub fn peer_addr(&self) -> Option<&SocketAddr> {
self.peer_addr.as_ref()
}
pub fn connect(&mut self, peer_addr: SocketAddr) {
self.peer_addr.replace(peer_addr);
}
pub fn is_connected(&self) -> bool {
self.proto.map(|p| p.is_connection_oriented()).unwrap_or(true) ||
self.peer_addr.is_some()
}
pub(super) async fn tx(&self, cmd: PortCommand) -> io::Result<()> {
let mut tx = self.tx.lock().await;
let cmd = bincode::serialize(&cmd)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
tx.write(&cmd[..]).await?;
Ok(())
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/mio/examples/ping.rs | wasmer-bus/mio/examples/ping.rs | use std::collections::HashMap;
use std::time::Instant;
use std::time::Duration;
use std::net::IpAddr;
use std::convert::TryInto;
use byteorder::ReadBytesExt;
use byteorder::WriteBytesExt;
use byteorder::LittleEndian;
use wasmer_bus_mio::prelude::*;
#[cfg(target_family = "wasm")]
use wasmer_bus_time::prelude::sleep;
#[cfg(not(target_family = "wasm"))]
use tokio::time::sleep;
use clap::Parser;
#[repr(C)]
struct IcmpHeader
{
ty: u8,
code: u8,
checksum: u16,
}
#[repr(C)]
struct IcmpPingPong
{
timestamp: u128,
seq: u64,
rand: u64,
}
#[repr(C)]
struct IcmpPing
{
header: IcmpHeader,
ping: IcmpPingPong
}
fn create_ping_packet(start: Instant, seq: u64) -> std::io::Result<Vec<u8>>
{
let now = Instant::now();
let icmp = IcmpPing {
header: IcmpHeader {
ty: 8, //IcmpType::Echo
code: 0,
checksum: 0,
},
ping: IcmpPingPong {
timestamp: now.duration_since(start).as_nanos(),
seq,
rand: fastrand::u64(..)
}
};
let mut pck = vec![0u8; ::std::mem::size_of::<IcmpPing>()];
let mut buf = &mut pck[..];
buf.write_u8(icmp.header.ty)?;
buf.write_u8(icmp.header.code)?;
buf.write_u16::<LittleEndian>(icmp.header.checksum)?;
buf.write_u128::<LittleEndian>(icmp.ping.timestamp)?;
buf.write_u64::<LittleEndian>(icmp.ping.seq)?;
buf.write_u64::<LittleEndian>(icmp.ping.rand)?;
calculate_checksum(&mut pck[..]);
Ok(pck)
}
fn decode_pong_packet(pck: Vec<u8>) -> std::io::Result<(IcmpHeader, Option<IcmpPingPong>)> {
let mut buf = &pck[..];
let header = IcmpHeader {
ty: buf.read_u8()?,
code: buf.read_u8()?,
checksum: buf.read_u16::<LittleEndian>()?,
};
let body = if header.ty == 0 {
Some(IcmpPingPong {
timestamp: buf.read_u128::<LittleEndian>()?,
seq: buf.read_u64::<LittleEndian>()?,
rand: buf.read_u64::<LittleEndian>()?,
})
} else {
None
};
Ok((
header, body
))
}
fn calculate_checksum(data: &mut [u8]) {
let mut f = 0;
let mut chk: u32 = 0;
while f + 2 <= data.len() {
chk += u16::from_le_bytes(data[f..f+2].try_into().unwrap()) as u32;
f += 2;
}
while chk > 0xffff {
chk = (chk & 0xffff) + (chk >> 2*8);
}
let mut chk = chk as u16;
chk = !chk & 0xffff;
data[3] = (chk >> 8) as u8;
data[2] = (chk & 0xff) as u8;
}
fn check_checksum(data: &mut [u8]) -> bool {
let d1 = data[2];
let d2 = data[3];
data[2] = 0;
data[3] = 0;
calculate_checksum(data);
d1 == data[2] && d2 == data[3]
}
#[derive(Parser)]
#[clap(version = "1.0", author = "John S. <johnathan.sharratt@gmail.com>")]
pub struct Opts {
/// Amount of echo request packets to send
#[allow(dead_code)]
#[clap(short, long, default_value = "4")]
pub count: i32,
/// Interval between successive packets sent (milliseconds)
#[allow(dead_code)]
#[clap(short, long, default_value = "1000")]
pub interval: u64,
//Maximum wait duration for an echo response packet (milliseconds)
#[allow(dead_code)]
#[clap(short, long, default_value = "5000")]
pub timeout: u64,
// IP address of destination to ping
#[allow(dead_code)]
#[clap(index = 1)]
pub destination: IpAddr,
/// Token used to access your network (if this is omitted then the token path will be probed)
#[clap(long)]
pub token: Option<String>,
/// Token file to read that holds a previously created token to be used for this operation
#[cfg(not(target_os = "wasi"))]
#[clap(long, default_value = "~/wasmer/token")]
pub token_path: String,
/// Token file to read that holds a previously created token to be used for this operation
#[cfg(target_os = "wasi")]
#[clap(long, default_value = "/.private/token")]
pub token_path: String,
}
#[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 opts: Opts = Opts::parse();
let start = Instant::now();
let destination = opts.destination;
let count = opts.count as u64;
let interval = Duration::from_millis(opts.interval);
let timeout = Duration::from_millis(opts.timeout);
let mut dups = HashMap::<u64, u32>::new();
let mut sent = 0u64;
let mut received = 0u64;
let port = Port::new(match opts.token {
Some(token) => {
let token: NetworkToken = std::str::FromStr::from_str(&token).unwrap();
TokenSource::ByValue(token)
},
None => TokenSource::ByPath(opts.token_path)
},
url::Url::parse("wss://wasmer.sh/net").unwrap(),
StreamSecurity::AnyEncryption)?;
port.dhcp_acquire().await?;
print!("connected:");
if let Ok(Some(mac)) = port.hardware_address().await {
print!(" mac={}", mac);
}
let ip = if let Ok(Some(ip)) = port.addr_ipv4().await {
print!(" ip={}", ip);
ip
} else {
panic!("no local ip address!");
};
println!("");
println!("PING {} ({}) 56(84) bytes of data", destination, destination);
let socket = port.bind_icmp(IpAddr::V4(ip)).await?;
for seq in 0..count
{
let pck = create_ping_packet(start, seq)?;
socket.send_to(pck, destination).await?;
sent += 1;
let wait = if sent < count {
interval
} else {
timeout
};
let interval_start = Instant::now();
while Instant::now() - interval_start < wait {
tokio::select! {
_ = sleep(Duration::from_millis(10)) => { },
ret = socket.recv_from() => {
let (mut pck, from) = ret?;
let pck_len = pck.len();
let checksum_ok = check_checksum(&mut pck[..]);
match decode_pong_packet(pck) {
Ok((header, pong)) => {
match (header.ty, pong) {
(0, Some(pong)) => { //IcmpType::EchoReply
let seq = pong.seq;
let duration = Duration::from_nanos(pong.timestamp as u64);
let duration = match Instant::now().duration_since(start).checked_sub(duration) {
Some(a) => a,
None => Duration::ZERO
};
print!("{} bytes from {}: icmp_seq={} ttl=64 time={}ms", pck_len, from, pong.seq, duration.as_millis());
let cur = dups.get(&seq).map(|a| a.clone()).unwrap_or(0u32);
dups.insert(seq, cur + 1);
if cur <= 0 {
received += 1;
} else if cur == 1 {
print!(" (DUP!)");
} else {
print!(" (DUP![{}])", cur);
}
if checksum_ok {
println!("")
} else {
println!(" invalid checksum!");
}
}
(0, None) => { //IcmpType::EchoReply
println!("{} bytes from {}: missing body", pck_len, from);
}
(3, _) => { //IcmpType::DestinationUnreachable
let msg = match header.code {
0 => "Destination Network Unreachable",
1 => "Destination Host Unreachable",
2 => "Protocol Unreachable",
3 => "Port Unreachable",
4 => "Fragmentation Needed",
5 => "Source Route Failed",
6 => "Destination Network Unknown",
7 => "Destination Host Unknown",
8 => "Source Host Isolated",
9 => "Destination Network Prohibited",
10 => "Destination Host Prohibited",
_ => "Destination Unreachable"
};
println!("From {} icmp_seq={} {}", from, seq, msg);
}
_ => { }
}
},
Err(_) => {
println!("{} bytes from {}: invalid packet data", pck_len, from);
}
}
}
}
}
}
println!("--- {} ping statistics ---", destination);
if sent > 0 {
println!(
"{} packets transmitted, {} received, {:.0}% packet loss, time {}ms",
sent,
received,
100.0 * (sent - received) as f64 / sent as f64,
Instant::now().duration_since(start).as_millis()
);
}
Ok(())
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/macros/src/lib.rs | wasmer-bus/macros/src/lib.rs | #![allow(
clippy::default_trait_access,
clippy::doc_markdown,
clippy::if_not_else,
clippy::items_after_statements,
clippy::module_name_repetitions,
clippy::shadow_unrelated,
clippy::similar_names,
clippy::too_many_lines
)]
extern crate proc_macro;
mod args;
mod convert;
mod method_inputs;
mod method_output;
mod parse;
mod receiver;
mod return_trait;
use crate::args::Args;
use crate::convert::convert;
use crate::parse::Item;
use proc_macro::TokenStream;
use syn::parse_macro_input;
#[proc_macro_attribute]
pub fn wasmer_bus(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as Args);
let item = parse_macro_input!(input as Item);
convert(args, item)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/macros/src/parse.rs | wasmer-bus/macros/src/parse.rs | use proc_macro2::Span;
use syn::parse::{Error, Parse, ParseStream, Result};
use syn::{Attribute, ItemImpl, ItemStruct, ItemTrait, Token};
#[derive(Clone)]
pub enum Item {
Trait(ItemTrait),
Impl(ItemImpl),
Struct(ItemStruct),
}
impl Parse for Item {
fn parse(input: ParseStream) -> Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
let mut lookahead = input.lookahead1();
while lookahead.peek(Token![unsafe]) || lookahead.peek(Token![pub]) {
let ahead = input.fork();
if lookahead.peek(Token![unsafe]) {
ahead.parse::<Token![unsafe]>()?;
}
if lookahead.peek(Token![pub]) {
ahead.parse::<Token![pub]>()?;
}
lookahead = ahead.lookahead1();
}
if lookahead.peek(Token![trait]) {
let mut item: ItemTrait = input.parse()?;
item.attrs = attrs;
Ok(Item::Trait(item))
} else if lookahead.peek(Token![struct]) {
let mut item: ItemStruct = input.parse()?;
item.attrs = attrs;
Ok(Item::Struct(item))
} else if lookahead.peek(Token![impl]) {
let mut item: ItemImpl = input.parse()?;
if item.trait_.is_none() {
return Err(Error::new(Span::call_site(), "expected a trait impl"));
}
item.attrs = attrs;
Ok(Item::Impl(item))
} else {
Err(lookahead.error())
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/macros/src/convert.rs | wasmer-bus/macros/src/convert.rs | use crate::args::Args;
use crate::parse::Item;
use convert_case::{Case, Casing};
use proc_macro2::Ident;
use quote::quote;
use syn::parse::Parser;
use syn::{
parse_quote, punctuated::Punctuated, Error, Field, FnArg, PathArguments, Token, TraitItem,
TypeParamBound, TypeTraitObject,
};
use wasmer_bus_types::SerializationFormat;
use super::method_inputs::*;
use super::method_output::*;
#[rustfmt::skip]
pub fn convert(args: Args, input: Item) -> proc_macro::TokenStream {
let format = args
.format
.map(|a| a.format_val)
.unwrap_or(SerializationFormat::Json);
// Get the span
let span = match input.clone() {
Item::Trait(input) => input.ident.span(),
Item::Impl(input) => {
let trait_path = input.trait_.expect("you can only implement WASM traits").1;
let trait_ident = trait_path.segments.last().expect("the trait path has no ident").ident.clone();
trait_ident.span()
},
_ => panic!("not yet implemented")
};
// Convert the format to an identity so that it can be directly added
let format = {
let format = format.to_string().to_case(Case::Pascal);
let format = Ident::new(format.as_str(), span);
quote! {
wasmer_bus::abi::SerializationFormat::#format
}
};
match input {
Item::Trait(input) => {
let trait_ident = input.ident.clone();
let trait_name = trait_ident.to_string();
let trait_client_name = format!("{}Client", trait_name);
let trait_client_ident = Ident::new(trait_client_name.as_str(), span);
let trait_service_name = format!("{}Service", trait_name);
let trait_service_ident = Ident::new(trait_service_name.as_str(), span);
let trait_simplified_name = format!("{}Simplified", trait_name);
let trait_simplified_ident = Ident::new(trait_simplified_name.as_str(), span);
let mut listens = Vec::new();
let mut trait_methods = Vec::new();
let mut blocking_methods = Vec::new();
let mut blocking_client_method_impls = Vec::new();
let mut trait_simplified_methods = Vec::new();
let mut client_method_impls = Vec::new();
let mut service_methods = Vec::new();
let mut service_attach_points = Vec::new();
let mut passthru_client_methods = Vec::new();
let mut passthru_simplified_methods = Vec::new();
let mut output = proc_macro2::TokenStream::new();
// We process all the methods in the trait and emit code that supports
// client and server side code
for item in input.items {
if let TraitItem::Method(method) = item {
let method_ident = method.sig.ident.clone();
let method_attrs = method.attrs;
let span = method_ident.span();
// Create a method name for blocking calls
let blocking_method_name = format!("blocking_{}", method_ident.to_string());
let blocking_method_ident = Ident::new(blocking_method_name.as_str(), span);
// Wasm bus is a fully asynchronous library and thus all its
// methods contained within must be asynchronous
let method_async = method.sig.asyncness;
if method_async.is_none() {
output.extend(Error::new(span, "all bus methods must be async").to_compile_error());
continue;
}
// Parse all the arguments of the method (if it has no self then fail)
let method_inputs = method.sig.inputs.clone();
let method_inputs: MethodInputs = parse_quote! { #method_inputs };
if method_inputs.has_self == false {
output.extend(Error::new(span, "all bus methods must be have a self reference").to_compile_error());
continue;
}
let request_name =
format!("{}_{}_request", trait_name, method_ident.to_string())
.to_case(Case::Pascal);
let request_name = Ident::new(request_name.as_str(), span);
let mut method_callbacks = Vec::new();
let mut method_lets = Vec::new();
let mut method_callback_handlers = Vec::new();
let mut method_transformed_inputs: Punctuated<_, Token![,]> = Punctuated::new();
let mut field_idents: Punctuated<_, Token![,]> = Punctuated::new();
let mut field_idents_plus: Punctuated<_, Token![,]> = Punctuated::new();
let mut fields: Punctuated<Field, Token![,]> = Punctuated::new();
for input in method_inputs.inputs {
let attrs = input.attrs.clone();
let name = input.ident.clone();
let ty = input.ty.as_ref().clone();
let span = name.span();
// If this is a callback then we need to type the input
// parameteter into an implementation that we will wrap
let (bounds, ty) = match ty.clone() {
syn::Type::ImplTrait(ty) => {
let ty = TypeTraitObject {
dyn_token: None,
bounds: ty.bounds.clone()
};
(Some(ty.bounds.clone()), syn::Type::TraitObject(ty))
},
syn::Type::TraitObject(_) => {
output.extend(Error::new(span, "callbacks must be explicit implementations and not dynamic traits - replace the 'dyn' with an 'impl'").to_compile_error());
continue;
},
ty => (None, ty)
};
if let Some(bounds) = bounds
{
// We only support a single field
let callback_fields = bounds
.clone()
.into_iter()
.filter_map(|a| {
if let TypeParamBound::Trait(a) = a {
Some(a)
} else {
None
}
})
.flat_map(|a| a.path.segments.into_iter())
.map(|a| a.arguments)
.collect::<Vec<_>>();
if callback_fields.len() != 1 {
panic!("WASM callbacks only support a single field as arguments")
}
let callback_field = callback_fields.into_iter().next().unwrap();
let callback_field_type = if let PathArguments::Parenthesized(a) = callback_field {
a.inputs
.first()
.map(|a| a.clone())
.expect("WASM callbacks only support a single argument with a type")
} else {
panic!("WASM callbacks must have a single parenthesized field");
};
let callback_name = format!(
"{}_{}_{}_callback",
trait_name,
method_ident.to_string(),
name
).to_case(Case::Pascal);
let callback_name =
Ident::new(callback_name.as_str(), span);
// Create a struct that represents this callback
output.extend(quote! {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct #callback_name ( pub #callback_field_type );
}.into_iter());
// Add code that will register a callback to a user supplied function
method_callbacks.push(quote! {
.callback(move |req: #callback_name| #name ( req.0 ) )
});
// We need a method argument that will accept in a callback implementation
// that we will invoke during callbacks
let arg: FnArg = parse_quote! {
#name : Box<dyn #ty + Send + Sync + 'static>
};
method_transformed_inputs.push(arg.clone());
// Add the callback handler to the service implementation
method_callback_handlers.push(quote! {
let #name = {
let wasm_handle = wasm_handle.clone();
Box::new(move |response: #callback_field_type| {
let response = #callback_name ( response );
let _ = wasmer_bus::abi::subcall(wasm_handle.clone(), #format, response).invoke();
})
};
});
field_idents_plus.push(name.clone());
} else {
fields.push(
Field::parse_named
.parse2(parse_quote! {
#( #attrs )* pub #name : #ty
})
.unwrap(),
);
field_idents.push(name.clone());
field_idents_plus.push(name.clone());
method_transformed_inputs.push(FnArg::Typed(input.pat_type));
method_lets.push(quote! {
let #name = wasm_req.#name;
});
}
}
// All the methods within the trait need to have a data object to pass
// via the WASM bus
output.extend(
quote! {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct #request_name {
#fields
}
}
.into_iter(),
);
// Get the return type
let method_ret = method.sig.output.clone();
let method_ret = match syn::parse::<MethodOutput>(quote!(#method_ret).into()) {
Ok(a) => a,
Err(err) => {
output.extend(err.to_compile_error());
return proc_macro::TokenStream::from(output);
}
};
// Attempt to parse the type into an object
if method_ret.is_trait() {
let svc = method_ret.ident_service();
service_attach_points.push(quote! {
{
let wasm_me = wasm_me.clone();
let call_handle = call_handle.clone();
wasmer_bus::task::respond_to(
call_handle,
#format,
#[allow(unused_variables)]
move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: #request_name| {
let wasm_me = wasm_me.clone();
#( #method_lets )*
async move {
#( #method_callback_handlers )*
match wasm_me.#method_ident(#field_idents_plus).await {
Ok(svc) => {
#svc::attach(svc, wasm_handle);
wasmer_bus::abi::RespondActionTyped::<()>::Detach
},
Err(err) => wasmer_bus::abi::RespondActionTyped::<()>::Fault(err)
}
}
},
);
}
});
}
// Otherwise the operation can be invoked arbitarily so we emit an object
// thats used to make the actual invocation
else
{
service_attach_points.push(quote! {
{
let wasm_me = wasm_me.clone();
let call_handle = call_handle.clone();
wasmer_bus::task::respond_to(
call_handle,
#format,
#[allow(unused_variables)]
move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: #request_name| {
let wasm_me = wasm_me.clone();
#( #method_lets )*
async move {
#( #method_callback_handlers )*
match wasm_me.#method_ident(#field_idents_plus).await {
Ok(res) => wasmer_bus::abi::RespondActionTyped::Response(res),
Err(err) => wasmer_bus::abi::RespondActionTyped::Fault(err)
}
}
},
);
}
});
}
// If the method returns another service then we need to add special things
// that stop the method from immediately returning
if method_ret.is_trait() {
let svc = method_ret.ident_service();
listens.push(quote! {
{
let wasm_me = wasm_me.clone();
wasmer_bus::task::listen(
#format,
#[allow(unused_variables)]
move |wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: #request_name| {
let wasm_me = wasm_me.clone();
#( #method_lets )*
async move {
#( #method_callback_handlers )*
match wasm_me.#method_ident(#field_idents_plus).await {
Ok(svc) => {
#svc::attach(svc, wasm_handle);
wasmer_bus::abi::ListenActionTyped::<()>::Detach
},
Err(err) => wasmer_bus::abi::ListenActionTyped::<()>::Fault(err)
}
}
},
);
}
});
let ret = method_ret.ident();
let ret_client = method_ret.ident_client();
trait_methods.push(quote! {
async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError>;
});
trait_simplified_methods.push(quote! {
async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError>;
});
client_method_impls.push(quote! {
pub async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError> {
let request = #request_name {
#field_idents
};
let handle = wasmer_bus::abi::call(
self.ctx.clone(),
#format,
request
)
#( #method_callbacks )*
.detach()?;
Ok(Arc::new(#ret_client::attach(handle)))
}
});
blocking_methods.push(quote! {
fn #blocking_method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError>;
});
blocking_client_method_impls.push(quote! {
pub fn #blocking_method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError> {
wasmer_bus::task::block_on(self.#method_ident(#field_idents_plus))
}
});
passthru_client_methods.push(quote! {
async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError> {
#trait_client_ident::#method_ident(self, #field_idents_plus).await
}
fn #blocking_method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError> {
#trait_client_ident::#blocking_method_ident(self, #field_idents_plus)
}
});
passthru_simplified_methods.push(quote! {
async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError> {
#trait_simplified_ident::#method_ident(self, #field_idents_plus).await
}
fn #blocking_method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<std::sync::Arc<dyn #ret>, wasmer_bus::abi::BusError> {
wasmer_bus::task::block_on(#trait_simplified_ident::#method_ident(self, #field_idents_plus))
}
});
} else {
listens.push(quote! {
{
let wasm_me = wasm_me.clone();
wasmer_bus::task::listen(
#format,
#[allow(unused_variables)]
move |_wasm_handle: wasmer_bus::abi::CallHandle, wasm_req: #request_name| {
let wasm_me = wasm_me.clone();
#( #method_lets )*
async move {
#( #method_callback_handlers )*
match wasm_me.#method_ident(#field_idents_plus).await {
Ok(res) => wasmer_bus::abi::ListenActionTyped::Response(res),
Err(err) => wasmer_bus::abi::ListenActionTyped::Fault(err)
}
}
},
);
}
});
let ret = method_ret.ident();
trait_methods.push(quote! {
async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<#ret, wasmer_bus::abi::BusError>;
});
trait_simplified_methods.push(quote! {
async fn #method_ident ( &self, #method_transformed_inputs ) -> #ret;
});
client_method_impls.push(quote! {
pub async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<#ret, wasmer_bus::abi::BusError> {
let request = #request_name {
#field_idents
};
wasmer_bus::abi::call(
self.ctx.clone(),
#format,
request
)
#( #method_callbacks )*
.invoke()
.join()?
.await
}
});
blocking_methods.push(quote! {
fn #blocking_method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<#ret, wasmer_bus::abi::BusError>;
});
blocking_client_method_impls.push(quote! {
pub fn #blocking_method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<#ret, wasmer_bus::abi::BusError> {
wasmer_bus::task::block_on(self.#method_ident(#field_idents_plus))
}
});
passthru_client_methods.push(quote! {
async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<#ret, wasmer_bus::abi::BusError> {
#trait_client_ident::#method_ident(self, #field_idents_plus).await
}
fn #blocking_method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<#ret, wasmer_bus::abi::BusError> {
#trait_client_ident::#blocking_method_ident(self, #field_idents_plus)
}
});
passthru_simplified_methods.push(quote! {
async fn #method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<#ret, wasmer_bus::abi::BusError> {
Ok(#trait_simplified_ident::#method_ident(self, #field_idents_plus).await)
}
fn #blocking_method_ident ( &self, #method_transformed_inputs ) -> std::result::Result<#ret, wasmer_bus::abi::BusError> {
Ok(wasmer_bus::task::block_on(#trait_simplified_ident::#method_ident(self, #field_idents_plus)))
}
});
}
let ret = method_ret.ident_service();
service_methods.push(quote! {
#( #method_attrs )*
async fn #method_ident ( &self, #method_transformed_inputs ) -> #ret;
});
}
}
// First of all we emit out the trait itself (unmodified) except
// for the removal of the wasmer_bus key word and replacement
// of it with the async-trait
output.extend(quote! {
#[wasmer_bus::async_trait]
pub trait #trait_ident
where Self: std::fmt::Debug + Send + Sync
{
#( #trait_methods )*
#( #blocking_methods )*
fn as_client(&self) -> Option<#trait_client_ident>;
}
#[wasmer_bus::async_trait]
pub trait #trait_simplified_ident
where Self: std::fmt::Debug + Send + Sync
{
#( #trait_simplified_methods )*
}
#[wasmer_bus::async_trait]
impl<T> #trait_ident
for T
where T: #trait_simplified_ident
{
#( #passthru_simplified_methods )*
fn as_client(&self) -> Option<#trait_client_ident> {
None
}
}
});
// Every trait also has a service implementation
output.extend(
quote! {
#[derive(Debug, Clone)]
pub struct #trait_service_ident
{
}
impl #trait_service_ident
{
#[allow(dead_code)]
pub(crate) fn attach(wasm_me: std::sync::Arc<dyn #trait_ident>, call_handle: wasmer_bus::abi::CallHandle) {
#( #service_attach_points )*
}
pub fn listen(wasm_me: std::sync::Arc<dyn #trait_ident>) {
#( #listens )*
}
pub async fn serve() {
wasmer_bus::task::serve().await;
}
}
}
);
// If there is a reference argument then we need to emit a struct
// that will represent this invokable object
output.extend(
quote! {
#[derive(Debug, Clone)]
pub struct #trait_client_ident
{
ctx: wasmer_bus::abi::CallContext,
task: Option<wasmer_bus::abi::Call>,
join: Option<wasmer_bus::abi::CallJoin<()>>,
}
impl #trait_client_ident {
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)
}
}
#( #client_method_impls )*
#( #blocking_client_method_impls )*
}
impl std::future::Future
for #trait_client_ident
{
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 #trait_ident
for #trait_client_ident
{
#( #passthru_client_methods )*
fn as_client(&self) -> Option<#trait_client_ident> {
Some(self.clone())
}
}
}
.into_iter(),
);
/*
// Convert all the code into a string literal which can be
// acquired directly for pre-build steps
let code = proc_macro::TokenStream::from(output.clone()).to_string();
output.extend(quote! {
impl #trait_name {
pub fn code() -> &'static str {
#code
}
}
});
*/
// Return the token stream
//panic!("CODE {}", proc_macro::TokenStream::from(output));
proc_macro::TokenStream::from(output)
}
_ => {
panic!("the wasm bus trait can only be used on traits");
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/macros/src/method_inputs.rs | wasmer-bus/macros/src/method_inputs.rs | use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::FnArg;
use syn::*;
pub struct MethodInputs {
pub inputs: Punctuated<MethodInput, Token![,]>,
pub has_self: bool,
}
impl Parse for MethodInputs {
fn parse(input: ParseStream) -> Result<Self> {
let args: Punctuated<FnArg, Token![,]> = Punctuated::parse_terminated(input)?;
let mut inputs: Punctuated<MethodInput, Token![,]> = Punctuated::new();
let mut has_self = false;
for arg in args {
match arg {
FnArg::Receiver(a) => {
if let Some((_, None)) = a.reference {
} else {
return Err(Error::new(
input.span(),
"all bus methods must have an immutable self reference",
));
}
if a.mutability.is_some() {
return Err(Error::new(input.span(), "bus methods can not be mutable"));
}
has_self = true;
}
FnArg::Typed(typed_arg) => match typed_arg.pat.as_ref() {
Pat::Ident(arg_name) => {
inputs.push(MethodInput::new(typed_arg.clone(), arg_name.clone()));
}
_ => {
return Err(Error::new(
input.span(),
"only named arguments are supported",
));
}
},
}
}
Ok(MethodInputs { inputs, has_self })
}
}
pub struct MethodInput {
pub attrs: Vec<Attribute>,
pub ident: Ident,
pub pat_ident: PatIdent,
pub pat_type: PatType,
pub ty_attrs: Vec<Attribute>,
pub ty: Box<Type>,
}
impl MethodInput {
fn new(pat_type: PatType, pat_ident: PatIdent) -> Self {
MethodInput {
attrs: pat_ident.attrs.clone(),
ident: pat_ident.ident.clone(),
pat_ident,
ty_attrs: pat_type.attrs.clone(),
ty: pat_type.ty.clone(),
pat_type: pat_type,
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/macros/src/args.rs | wasmer-bus/macros/src/args.rs | use proc_macro2::Span;
use std::str::FromStr;
use syn::parse::{Parse, ParseStream, Result};
use syn::{LitStr, Token};
use wasmer_bus_types::SerializationFormat;
pub struct ArgsFormat {
pub format_token: kw::format,
pub eq_token: Token![=],
pub format_val: SerializationFormat,
}
#[derive(Default)]
pub struct Args {
pub format: Option<ArgsFormat>,
}
mod kw {
syn::custom_keyword!(format);
}
impl Parse for Args {
fn parse(input: ParseStream) -> Result<Args> {
try_parse(input)
}
}
pub(crate) fn try_parse(input: ParseStream) -> Result<Args> {
let mut args = Args::default();
let lookahead = input.lookahead1();
if lookahead.peek(kw::format) {
args.format = Some(ArgsFormat {
format_token: input.parse::<kw::format>()?,
eq_token: input.parse()?,
format_val: SerializationFormat::from_str(input.parse::<LitStr>()?.value().as_str())
.map_err(|e| syn::Error::new(Span::call_site(), e))?,
});
} else {
return Err(lookahead.error());
}
Ok(args)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/macros/src/return_trait.rs | wasmer-bus/macros/src/return_trait.rs | use derivative::*;
use syn::parse::{Parse, ParseStream};
use syn::*;
#[derive(Derivative, Clone)]
#[derivative(Debug)]
pub struct ReturnTrait {
#[derivative(Debug = "ignore")]
pub path: Path,
pub ident: Ident,
#[derivative(Debug = "ignore")]
pub ty: Type,
pub client_name: String,
pub client_ident: Ident,
pub service_name: String,
pub service_ident: Ident,
}
impl Parse for ReturnTrait {
fn parse(input: ParseStream) -> Result<Self> {
input.parse::<Option<Token![->]>>()?;
let span = input.span();
let path = input.parse::<Path>()?;
let arc_segment = match path.segments.into_iter().last() {
Some(a) if a.ident == "Arc" => a,
_ => {
return Err(Error::new(
span,
"only Arc is supported as a WASM trait return type",
));
}
};
let span = arc_segment.ident.span();
let inner = match arc_segment.arguments {
PathArguments::AngleBracketed(brackets) => {
let args = brackets.args;
if args.len() != 1 {
return Err(Error::new(span, "the Arc must contain a dynamic trait"));
}
args.into_iter().last().unwrap()
}
_ => {
return Err(Error::new(span, "the Arc must contain a dynamic trait"));
}
};
let ty = match inner {
GenericArgument::Type(a) => a,
_ => {
return Err(Error::new(
span,
"bindings, lifetimes, contraints and consts are not supported",
));
}
};
let trait_bound = match ty.clone() {
Type::TraitObject(a) => a
.bounds
.into_iter()
.filter_map(|a| {
if let TypeParamBound::Trait(a) = a {
Some(a)
} else {
None
}
})
.next(),
_ => {
return Err(Error::new(span, "the Arc must contain a dynamic trait"));
}
};
let trait_bound = match trait_bound {
Some(a) => a,
None => {
return Err(Error::new(
span,
"the Arc must contain a dynamic trait without any other bounds",
));
}
};
let path = trait_bound.path;
let ident = if let Some(last) = path.segments.last() {
last.ident.clone()
} else {
return Err(Error::new(
input.span(),
"return type must be a type identifier",
));
};
let client_name = format!("{}Client", ident.to_string());
let client_ident = Ident::new(client_name.as_str(), span.clone());
let service_name = format!("{}Service", ident.to_string());
let service_ident = Ident::new(service_name.as_str(), span.clone());
let ret = ReturnTrait {
path,
ident,
ty,
client_name,
client_ident,
service_name,
service_ident,
};
Ok(ret)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/macros/src/method_output.rs | wasmer-bus/macros/src/method_output.rs | use derivative::*;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::*;
use super::return_trait::*;
#[derive(Debug, Clone)]
pub enum MethodOutput {
Trait(ReturnTrait),
Message(ReturnMessage),
Nothing,
}
impl MethodOutput {
pub fn is_trait(&self) -> bool {
if let MethodOutput::Trait(_) = self {
true
} else {
false
}
}
pub fn ident(&self) -> TokenStream {
match self {
MethodOutput::Trait(a) => {
let ident = a.ident.clone();
quote! { #ident }
}
MethodOutput::Message(a) => {
let path = a.path.clone();
quote! { #path }
}
MethodOutput::Nothing => quote! { () },
}
}
pub fn ident_client(&self) -> TokenStream {
match self {
MethodOutput::Trait(a) => {
let ident = a.client_ident.clone();
quote! { #ident }
}
MethodOutput::Message(a) => {
let path = a.path.clone();
quote! { #path }
}
MethodOutput::Nothing => quote! { () },
}
}
pub fn ident_service(&self) -> TokenStream {
match self {
MethodOutput::Trait(a) => {
let ident = a.service_ident.clone();
quote! { #ident }
}
MethodOutput::Message(a) => {
let path = a.path.clone();
quote! { #path }
}
MethodOutput::Nothing => quote! { () },
}
}
}
impl Parse for MethodOutput {
fn parse(input: ParseStream) -> Result<Self> {
{
let input_try = input.fork();
if let Ok(trait_) = input_try.parse::<ReturnTrait>() {
input.parse::<ReturnTrait>()?;
return Ok(MethodOutput::Trait(trait_));
}
}
let span = input.span();
match input.parse::<ReturnType>()? {
ReturnType::Default => Ok(MethodOutput::Nothing),
ReturnType::Type(_, b) => Ok(MethodOutput::Message(ReturnMessage::new(span, b)?)),
}
}
}
#[derive(Derivative, Clone)]
#[derivative(Debug)]
pub struct ReturnMessage {
#[derivative(Debug = "ignore")]
pub path: Path,
}
impl ReturnMessage {
fn new(span: Span, ty: Box<Type>) -> Result<Self> {
match *ty {
Type::Array(_) => Err(Error::new(span, "arrays are not supported as a return type")),
Type::ImplTrait(_) => Err(Error::new(span, "trait implementations are not supported - instead wrap the dynamic type in an Arc. e.g. Arc<dyn MyType>")),
Type::TraitObject(_) => Err(Error::new(span, "dynamic traits must be wrapped in an an Arc. e.g. Arc<dyn MyType>")),
Type::Infer(_) => Err(Error::new(span, "all return types must be strongly typed")),
Type::Tuple(_) => Err(Error::new(span, "returning tuples is not yet supported, instead make a struct that contains your named fields")),
Type::Reference(_) => Err(Error::new(span, "returning reference types is not supported - all returned objects must be owned")),
Type::Path(path) => {
if path.qself.is_some() {
return Err(Error::new(span, "return self types are not supported"));
}
let path = path.path;
if is_path_concrete(&path) == false {
return Err(Error::new(span, "only concrete types are supported as return arguments - traits must be returned in an Arc. e.g. Arc<dyn MyType> - otherwise lifetimes, bounds, etc... are all prohibited."));
}
if path.segments.is_empty() {
return Err(Error::new(span, "the return type does not return anything which is not supported by WASM bus."));
}
Ok(ReturnMessage {
path,
})
}
_ => Err(Error::new(span, "the returned type is not supported")),
}
}
}
fn is_tuple_concrete(tuple: &TypeTuple) -> bool {
for ty in tuple.elems.iter() {
if is_type_concrete(ty) == false {
return false;
}
}
true
}
fn is_path_concrete(path: &Path) -> bool {
for segment in path.segments.iter() {
match &segment.arguments {
PathArguments::None => {
continue;
}
PathArguments::Parenthesized(_) => {
return false;
}
PathArguments::AngleBracketed(angle) => {
for arg in angle.args.iter() {
match arg {
GenericArgument::Type(ty) => {
if is_type_concrete(ty) == false {
return false;
}
continue;
}
_ => {
return false;
}
}
}
}
}
}
true
}
fn is_type_concrete(ty: &Type) -> bool {
match ty {
Type::Path(path) => {
if is_path_concrete(&path.path) == false {
return false;
}
}
Type::Tuple(tuple) => {
if is_tuple_concrete(&tuple) == false {
return false;
}
}
_ => {
return false;
}
}
true
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/macros/src/receiver.rs | wasmer-bus/macros/src/receiver.rs | use proc_macro2::{Group, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
use syn::visit_mut::{self, VisitMut};
use syn::{
Block, ExprPath, Ident, Item, Macro, Pat, PatIdent, PatPath, Path, Receiver, Signature, Token,
TypePath,
};
#[allow(dead_code)]
pub fn has_self_in_sig(sig: &mut Signature) -> bool {
let mut visitor = HasSelf(false);
visitor.visit_signature_mut(sig);
visitor.0
}
#[allow(dead_code)]
pub fn has_self_in_block(block: &mut Block) -> bool {
let mut visitor = HasSelf(false);
visitor.visit_block_mut(block);
visitor.0
}
fn has_self_in_token_stream(tokens: TokenStream) -> bool {
tokens.into_iter().any(|tt| match tt {
TokenTree::Ident(ident) => ident == "Self",
TokenTree::Group(group) => has_self_in_token_stream(group.stream()),
_ => false,
})
}
#[allow(dead_code)]
pub fn mut_pat(pat: &mut Pat) -> Option<Token![mut]> {
let mut visitor = HasMutPat(None);
visitor.visit_pat_mut(pat);
visitor.0
}
fn contains_fn(tokens: TokenStream) -> bool {
tokens.into_iter().any(|tt| match tt {
TokenTree::Ident(ident) => ident == "fn",
TokenTree::Group(group) => contains_fn(group.stream()),
_ => false,
})
}
struct HasMutPat(Option<Token![mut]>);
impl VisitMut for HasMutPat {
fn visit_pat_ident_mut(&mut self, i: &mut PatIdent) {
if let Some(m) = i.mutability {
self.0 = Some(m);
} else {
visit_mut::visit_pat_ident_mut(self, i);
}
}
}
struct HasSelf(bool);
impl VisitMut for HasSelf {
fn visit_expr_path_mut(&mut self, expr: &mut ExprPath) {
self.0 |= expr.path.segments[0].ident == "Self";
visit_mut::visit_expr_path_mut(self, expr);
}
fn visit_pat_path_mut(&mut self, pat: &mut PatPath) {
self.0 |= pat.path.segments[0].ident == "Self";
visit_mut::visit_pat_path_mut(self, pat);
}
fn visit_type_path_mut(&mut self, ty: &mut TypePath) {
self.0 |= ty.path.segments[0].ident == "Self";
visit_mut::visit_type_path_mut(self, ty);
}
fn visit_receiver_mut(&mut self, _arg: &mut Receiver) {
self.0 = true;
}
fn visit_item_mut(&mut self, _: &mut Item) {
// Do not recurse into nested items.
}
fn visit_macro_mut(&mut self, mac: &mut Macro) {
if !contains_fn(mac.tokens.clone()) {
self.0 |= has_self_in_token_stream(mac.tokens.clone());
}
}
}
pub struct ReplaceSelf(pub Span);
impl ReplaceSelf {
#[cfg_attr(not(self_span_hack), allow(clippy::unused_self))]
fn prepend_underscore_to_self(&self, ident: &mut Ident) -> bool {
let modified = ident == "self";
if modified {
*ident = Ident::new("__self", ident.span());
#[cfg(self_span_hack)]
ident.set_span(self.0);
}
modified
}
fn visit_token_stream(&mut self, tokens: &mut TokenStream) -> bool {
let mut out = Vec::new();
let mut modified = false;
visit_token_stream_impl(self, tokens.clone(), &mut modified, &mut out);
if modified {
*tokens = TokenStream::from_iter(out);
}
return modified;
fn visit_token_stream_impl(
visitor: &mut ReplaceSelf,
tokens: TokenStream,
modified: &mut bool,
out: &mut Vec<TokenTree>,
) {
for tt in tokens {
match tt {
TokenTree::Ident(mut ident) => {
*modified |= visitor.prepend_underscore_to_self(&mut ident);
out.push(TokenTree::Ident(ident));
}
TokenTree::Group(group) => {
let mut content = group.stream();
*modified |= visitor.visit_token_stream(&mut content);
let mut new = Group::new(group.delimiter(), content);
new.set_span(group.span());
out.push(TokenTree::Group(new));
}
other => out.push(other),
}
}
}
}
}
impl VisitMut for ReplaceSelf {
fn visit_ident_mut(&mut self, i: &mut Ident) {
self.prepend_underscore_to_self(i);
}
fn visit_path_mut(&mut self, p: &mut Path) {
if p.segments.len() == 1 {
// Replace `self`, but not `self::function`.
self.visit_ident_mut(&mut p.segments[0].ident);
}
for segment in &mut p.segments {
self.visit_path_arguments_mut(&mut segment.arguments);
}
}
fn visit_item_mut(&mut self, i: &mut Item) {
// Visit `macro_rules!` because locally defined macros can refer to
// `self`.
//
// Visit `futures::select` and similar select macros, which commonly
// appear syntactically like an item despite expanding to an expression.
//
// Otherwise, do not recurse into nested items.
if let Item::Macro(i) = i {
if i.mac.path.is_ident("macro_rules")
|| i.mac.path.segments.last().unwrap().ident == "select"
{
self.visit_macro_mut(&mut i.mac);
}
}
}
fn visit_macro_mut(&mut self, mac: &mut Macro) {
// We can't tell in general whether `self` inside a macro invocation
// refers to the self in the argument list or a different self
// introduced within the macro. Heuristic: if the macro input contains
// `fn`, then `self` is more likely to refer to something other than the
// outer function's self argument.
if !contains_fn(mac.tokens.clone()) {
self.visit_token_stream(&mut mac.tokens);
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-bus/hello/src/lib.rs | wasmer-bus/hello/src/lib.rs | use wasmer_bus::macros::*;
#[wasmer_bus(format = "json")]
pub trait World {
async fn hello(&self) -> String;
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.