Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

186464436 - multiple changes #14

Merged
merged 4 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion rust/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ fn main() {
let status = Command::new("flatc")
.arg("--rust")
.arg("-o")
.arg("src")
.arg("src/generated")
.arg("../schemas/flatbuffers/common.fbs")
.arg("../schemas/flatbuffers/client_request.fbs")
.arg("../schemas/flatbuffers/host_response.fbs")
Expand Down
2 changes: 2 additions & 0 deletions rust/tests/chatroom.rs → rust/examples/chatroom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,3 +316,5 @@ pub mod dependency_2 {
}
}
}

fn main() {}
Original file line number Diff line number Diff line change
Expand Up @@ -367,3 +367,5 @@ mod children {
}
}
}

fn main() {}
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,5 @@ impl TypedContract for Contract {
unimplemented!()
}
}

fn main() {}
2 changes: 1 addition & 1 deletion rust/src/client_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl WsApiError {
}

pub fn into_fbs_bytes(self) -> Vec<u8> {
use crate::host_response_generated::host_response::{
use crate::generated::host_response::{
finish_host_response_buffer, Error, ErrorArgs, HostResponse, HostResponseArgs,
HostResponseType,
};
Expand Down
100 changes: 75 additions & 25 deletions rust/src/client_api/client_events.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
use flatbuffers::WIPOffset;
use std::borrow::Cow;
use std::fmt::Display;

use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::client_api::TryFromFbs;
use crate::client_request_generated::client_request::{
use crate::generated::client_request::{
root_as_client_request, ClientRequestType, ContractRequest as FbsContractRequest,
ContractRequestType, DelegateRequest as FbsDelegateRequest, DelegateRequestType,
};

use crate::common_generated::common::{
use crate::delegate_interface::DelegateContext;
use crate::generated::common::{
ApplicationMessage as FbsApplicationMessage, ApplicationMessageArgs, ContractCode,
ContractCodeArgs, ContractContainer as FbsContractContainer, ContractContainerArgs,
ContractInstanceId, ContractInstanceIdArgs, ContractKey as FbsContractKey, ContractKeyArgs,
Expand All @@ -21,8 +23,7 @@ use crate::common_generated::common::{
StateUpdate, StateUpdateArgs, UpdateData as FbsUpdateData, UpdateDataArgs, UpdateDataType,
WasmContractV1, WasmContractV1Args,
};
use crate::delegate_interface::DelegateContext;
use crate::host_response_generated::host_response::{
use crate::generated::host_response::{
finish_host_response_buffer, ClientResponse as FbsClientResponse, ClientResponseArgs,
ContextUpdated as FbsContextUpdated, ContextUpdatedArgs,
ContractResponse as FbsContractResponse, ContractResponseArgs, ContractResponseType,
Expand Down Expand Up @@ -59,7 +60,7 @@ pub struct ClientError {

impl ClientError {
pub fn into_fbs_bytes(self) -> Result<Vec<u8>, Box<ClientError>> {
use crate::host_response_generated::host_response::{Error, ErrorArgs};
use crate::generated::host_response::{Error, ErrorArgs};
let mut builder = flatbuffers::FlatBufferBuilder::new();
let msg_offset = builder.create_string(&self.to_string());
let err_offset = Error::create(
Expand All @@ -79,8 +80,8 @@ impl ClientError {
Ok(builder.finished_data().to_vec())
}

pub fn kind(&self) -> ErrorKind {
(*self.kind).clone()
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
}

Expand All @@ -92,10 +93,12 @@ impl From<ErrorKind> for ClientError {
}
}

impl From<String> for ClientError {
fn from(cause: String) -> Self {
impl<T: Into<Cow<'static, str>>> From<T> for ClientError {
fn from(cause: T) -> Self {
ClientError {
kind: Box::new(ErrorKind::Unhandled { cause }),
kind: Box::new(ErrorKind::Unhandled {
cause: cause.into(),
}),
}
}
}
Expand All @@ -106,7 +109,7 @@ pub enum ErrorKind {
#[error("comm channel between client/host closed")]
ChannelClosed,
#[error("error while deserializing: {cause}")]
DeserializationError { cause: String },
DeserializationError { cause: Cow<'static, str> },
#[error("client disconnected")]
Disconnect,
#[error("failed while trying to unpack state for {0}")]
Expand All @@ -116,11 +119,13 @@ pub enum ErrorKind {
#[error("lost the connection with the protocol hanling connections")]
TransportProtocolDisconnect,
#[error("unhandled error: {cause}")]
Unhandled { cause: String },
Unhandled { cause: Cow<'static, str> },
#[error("unknown client id: {0}")]
UnknownClient(usize),
#[error(transparent)]
RequestError(#[from] RequestError),
#[error("peer should shutdown")]
Shutdown,
}

impl Display for ClientError {
Expand Down Expand Up @@ -151,7 +156,7 @@ pub enum DelegateError {
#[error("error while registering delegate {0}")]
RegisterError(DelegateKey),
#[error("execution error, cause {0}")]
ExecutionError(String),
ExecutionError(Cow<'static, str>),
#[error("missing delegate {0}")]
Missing(DelegateKey),
#[error("missing secret `{secret}` for delegate {key}")]
Expand All @@ -165,22 +170,68 @@ pub enum DelegateError {
#[non_exhaustive]
pub enum ContractError {
#[error("failed to get contract {key}, reason: {cause}")]
Get { key: ContractKey, cause: String },
Get {
key: ContractKey,
cause: Cow<'static, str>,
},
#[error("put error for contract {key}, reason: {cause}")]
Put { key: ContractKey, cause: String },
Put {
key: ContractKey,
cause: Cow<'static, str>,
},
#[error("update error for contract {key}, reason: {cause}")]
Update { key: ContractKey, cause: String },
Update {
key: ContractKey,
cause: Cow<'static, str>,
},
#[error("failed to subscribe for contract {key}, reason: {cause}")]
Subscribe { key: ContractKey, cause: String },
#[error("missing related contract: {key}")]
MissingRelated {
key: crate::contract_interface::ContractInstanceId,
Subscribe {
key: ContractKey,
cause: Cow<'static, str>,
},
// todo: actually build a stack of the involved keys
#[error("dependency contract stack overflow : {key}")]
ContractStackOverflow {
key: crate::contract_interface::ContractInstanceId,
},
#[error("missing related contract: {key}")]
MissingRelated {
key: crate::contract_interface::ContractInstanceId,
},
#[error("missing related contract: {key}")]
MissingContract {
key: crate::contract_interface::ContractInstanceId,
},
}

impl ContractError {
const EXECUTION_ERROR: &'static str = "execution error";
const INVALID_PUT: &'static str = "invalid put";

pub fn update_exec_error(key: ContractKey, additional_info: impl std::fmt::Display) -> Self {
Self::Update {
key,
cause: format!(
"{exec_err}: {additional_info}",
exec_err = Self::EXECUTION_ERROR
)
.into(),
}
}

pub fn invalid_put(key: ContractKey) -> Self {
Self::Put {
key,
cause: Self::INVALID_PUT.into(),
}
}

pub fn invalid_update(key: ContractKey) -> Self {
Self::Update {
key,
cause: Self::INVALID_PUT.into(),
}
}
}

/// A request from a client application to the host.
Expand All @@ -190,7 +241,7 @@ pub enum ContractError {
pub enum ClientRequest<'a> {
DelegateOp(#[serde(borrow)] DelegateRequest<'a>),
ContractOp(#[serde(borrow)] ContractRequest<'a>),
Disconnect { cause: Option<String> },
Disconnect { cause: Option<Cow<'static, str>> },
Authenticate { token: String },
}

Expand Down Expand Up @@ -261,7 +312,7 @@ impl ClientRequest<'_> {
client_request.client_request_as_disconnect().unwrap();
let cause = delegate_request
.cause()
.map(|cuase_msg| cuase_msg.to_string());
.map(|cause_msg| cause_msg.to_string().into());
ClientRequest::Disconnect { cause }
}
ClientRequestType::Authenticate => {
Expand Down Expand Up @@ -1319,8 +1370,8 @@ impl<T> From<ContractResponse<T>> for HostResponse<T> {
#[cfg(test)]
mod client_request_test {
use crate::client_api::{ContractRequest, TryFromFbs};
use crate::client_request_generated::client_request::root_as_client_request;
use crate::contract_interface::UpdateData;
use crate::generated::client_request::root_as_client_request;

const EXPECTED_ENCODED_CONTRACT_ID: &str = "6kVs66bKaQAC6ohr8b43SvJ95r36tc2hnG7HezmaJHF9";

Expand Down Expand Up @@ -1353,8 +1404,7 @@ mod client_request_test {
} => {
assert_eq!(
contract.to_string(),
"wasm container version 0.0.1 of contract \
Contract(D8fdVLbRyMLw5mZtPRpWMFcrXGN2z8Nq8UGcLGPFBg2W)"
"WasmContainer([api=0.0.1](D8fdVLbRyMLw5mZtPRpWMFcrXGN2z8Nq8UGcLGPFBg2W))"
);
assert_eq!(contract.unwrap_v1().data.data(), &[1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(state.to_vec(), &[1, 2, 3, 4, 5, 6, 7, 8]);
Expand Down
8 changes: 4 additions & 4 deletions rust/src/client_api/regular.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::task::Poll;
use std::{borrow::Cow, task::Poll};

use futures::{pin_mut, FutureExt, Sink, SinkExt, Stream, StreamExt};
use tokio::{
Expand Down Expand Up @@ -115,7 +115,7 @@ impl WebApi {
res.ok_or_else(|| ClientError::from(ErrorKind::ChannelClosed))?
}

pub async fn disconnect(self, cause: impl Into<String>) {
pub async fn disconnect(self, cause: impl Into<Cow<'static, str>>) {
let _ = self
.request_tx
.send(ClientRequest::Disconnect {
Expand Down Expand Up @@ -189,8 +189,8 @@ async fn process_response(
.await
.map_err(|_| Error::ChannelClosed)?;
}
Message::Ping(_) => {
conn.send(Message::Pong(vec![0, 5, 3, 9])).await?;
Message::Ping(ping) => {
conn.send(Message::Pong(ping)).await?;
}
Message::Pong(_) => {}
Message::Close(_) => return Err(Error::ConnectionClosed),
Expand Down
23 changes: 7 additions & 16 deletions rust/src/contract_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ use serde::{Deserialize, Deserializer, Serialize};
use serde_with::serde_as;

use crate::client_api::TryFromFbs;
use crate::client_request_generated::client_request::RelatedContracts as FbsRelatedContracts;
use crate::common_generated::common::{
ContractKey as FbsContractKey, UpdateData as FbsUpdateData, UpdateDataType,
};
use crate::generated::client_request::RelatedContracts as FbsRelatedContracts;
use crate::{client_api::WsApiError, code_hash::CodeHash, parameters::Parameters};

pub(crate) const CONTRACT_KEY_SIZE: usize = 32;
Expand Down Expand Up @@ -1229,18 +1229,11 @@ impl From<WrappedState> for State<'static> {

impl std::fmt::Display for WrappedState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let data: String = if self.0.len() > 8 {
let last_4 = self.0.len() - 4;
self.0[..4]
.iter()
.map(|b| char::from(*b))
.chain("...".chars())
.chain(self.0[last_4..].iter().map(|b| char::from(*b)))
.collect()
} else {
self.0.iter().copied().map(char::from).collect()
};
write!(f, "ContractState(data: [{data}])")
write!(f, "ContractState(data: [0x")?;
for b in self.0.iter().take(8) {
write!(f, "{:02x}", b)?;
}
write!(f, "...])")
}
}

Expand Down Expand Up @@ -1314,9 +1307,7 @@ impl TryInto<Vec<u8>> for WrappedContract {

impl Display for WrappedContract {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Contract(")?;
self.key.fmt(f)?;
write!(f, ")")
self.key.fmt(f)
}
}

Expand Down
2 changes: 1 addition & 1 deletion rust/src/delegate_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use blake3::{traits::digest::Digest, Hasher as Blake3};
use serde::{Deserialize, Deserializer, Serialize};
use serde_with::serde_as;

use crate::client_request_generated::client_request::{
use crate::generated::client_request::{
DelegateKey as FbsDelegateKey, InboundDelegateMsg as FbsInboundDelegateMsg,
InboundDelegateMsgType,
};
Expand Down
File renamed without changes.
17 changes: 12 additions & 5 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,18 @@ mod versioning;
pub use contract_interface::encoding as typed_contract;

#[allow(dead_code, unused_imports, clippy::all)]
pub(crate) mod client_request_generated;
#[allow(dead_code, unused_imports, clippy::all)]
pub(crate) mod common_generated;
#[allow(dead_code, unused_imports, clippy::all)]
pub(crate) mod host_response_generated;
pub(crate) mod generated {
mod client_request_generated;
pub(crate) use client_request_generated::*;
pub(crate) mod common_generated;
pub(crate) use common_generated::*;
mod host_response_generated;
pub(crate) use host_response_generated::*;
}

pub(crate) mod common_generated {
pub use super::generated::common_generated::*;
}

pub mod client_api;
#[cfg(feature = "contract")]
Expand Down
23 changes: 12 additions & 11 deletions rust/src/versioning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,17 @@ use std::sync::Arc;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use serde::{Deserialize, Serialize};

use crate::client_api::{TryFromFbs, WsApiError};
use crate::client_request_generated::client_request::{
DelegateContainer as FbsDelegateContainer, DelegateType,
use crate::{
client_api::{TryFromFbs, WsApiError},
common_generated::common::{ContractContainer as FbsContractContainer, ContractType},
contract_interface::{ContractInstanceId, ContractKey},
generated::client_request::{DelegateContainer as FbsDelegateContainer, DelegateType},
parameters::Parameters,
prelude::{
CodeHash, ContractCode, ContractWasmAPIVersion::V1, Delegate, DelegateCode, DelegateKey,
WrappedContract,
},
};
use crate::common_generated::common::{ContractContainer as FbsContractContainer, ContractType};
use crate::contract_interface::ContractInstanceId;
use crate::parameters::Parameters;
use crate::prelude::ContractWasmAPIVersion::V1;
use crate::prelude::{CodeHash, Delegate, DelegateCode, DelegateKey, WrappedContract};
use crate::{contract_interface::ContractKey, prelude::ContractCode};

/// Contains the different versions available for WASM delegates.
#[non_exhaustive]
Expand Down Expand Up @@ -192,7 +193,7 @@ impl Display for ContractWasmAPIVersion {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
ContractWasmAPIVersion::V1(contract_v1) => {
write!(f, "version 0.0.1 of contract {contract_v1}")
write!(f, "[api=0.0.1]({contract_v1})")
}
}
}
Expand Down Expand Up @@ -254,7 +255,7 @@ impl Display for ContractContainer {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
ContractContainer::Wasm(wasm_version) => {
write!(f, "wasm container {wasm_version}")
write!(f, "WasmContainer({wasm_version})")
}
}
}
Expand Down