From 990d704401da34172eebb4bcc792e479a6aabd3e Mon Sep 17 00:00:00 2001 From: Al Liu Date: Tue, 11 Jun 2024 18:06:17 +0800 Subject: [PATCH] Remove DynError (#1123) --- Cargo.lock | 313 ++++++++++++++++-- crates/core/src/bin/freenet.rs | 8 +- crates/core/src/client_events/websocket.rs | 13 +- crates/core/src/config.rs | 2 +- crates/core/src/contract/executor.rs | 31 +- .../src/contract/executor/mock_runtime.rs | 6 +- crates/core/src/contract/executor/runtime.rs | 17 +- crates/core/src/contract/handler.rs | 19 +- crates/core/src/lib.rs | 2 - crates/core/src/node.rs | 6 +- .../src/node/network_bridge/p2p_protoc.rs | 4 +- crates/core/src/node/op_state_manager.rs | 2 +- crates/core/src/node/p2p_impl.rs | 4 +- crates/core/src/node/testing_impl.rs | 18 +- .../core/src/node/testing_impl/in_memory.rs | 4 +- crates/core/src/node/testing_impl/network.rs | 2 +- crates/core/src/operations/connect.rs | 6 +- crates/core/src/operations/get.rs | 6 +- crates/core/src/operations/put.rs | 2 +- crates/core/src/operations/subscribe.rs | 2 +- crates/core/src/ring.rs | 11 +- crates/core/src/server.rs | 14 +- crates/core/src/server/app_packaging.rs | 32 +- crates/core/src/topology/meter.rs | 3 +- crates/core/src/tracing.rs | 23 +- crates/core/src/tracing/aof.rs | 14 +- .../core/src/transport/connection_handler.rs | 96 +++--- .../core/src/wasm_runtime/contract_store.rs | 4 +- .../core/src/wasm_runtime/delegate_store.rs | 5 +- crates/core/src/wasm_runtime/error.rs | 6 +- crates/core/src/wasm_runtime/state_store.rs | 14 +- crates/core/src/wasm_runtime/store.rs | 4 +- crates/fdev/src/build.rs | 61 ++-- crates/fdev/src/commands.rs | 10 +- crates/fdev/src/commands/v1.rs | 2 +- crates/fdev/src/inspect.rs | 2 +- crates/fdev/src/main.rs | 2 +- crates/fdev/src/network_metrics_server.rs | 2 +- crates/fdev/src/new_package.rs | 10 +- crates/fdev/src/testing/network.rs | 11 +- crates/fdev/src/util.rs | 11 +- crates/fdev/src/wasm_runtime.rs | 2 +- crates/fdev/src/wasm_runtime/commands.rs | 7 +- crates/fdev/src/wasm_runtime/state.rs | 2 +- crates/fdev/src/wasm_runtime/state/v1.rs | 2 +- crates/fdev/src/wasm_runtime/user_events.rs | 6 +- modules/identity-management/Cargo.lock | 7 + modules/identity-management/Cargo.toml | 1 + modules/identity-management/src/bin/tool.rs | 9 +- 49 files changed, 527 insertions(+), 313 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0b7ae33ff..8693f6f7c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -600,9 +600,9 @@ checksum = "a2698f953def977c68f935bb0dfa959375ad4638570e969e2f1e9f433cbf1af6" [[package]] name = "cc" -version = "1.0.98" +version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41c270e7540d725e65ac7f1b212ac8ce349719624d7bcff99f8e2e488e8cf03f" +checksum = "96c51067fd44124faa7f870b4b1c969379ad32b2ba805aa959430ceaa384f695" [[package]] name = "cfg-if" @@ -703,9 +703,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" +checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" [[package]] name = "colorchoice" @@ -1213,6 +1213,17 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "displaydoc" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + [[package]] name = "document-features" version = "0.2.8" @@ -2061,12 +2072,12 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" dependencies = [ "bytes", - "futures-core", + "futures-util", "http 1.1.0", "http-body 1.0.0", "pin-project-lite", @@ -2080,9 +2091,9 @@ checksum = "08a397c49fec283e3d6211adbe480be95aae5f304cfb923e9970e08956d5168a" [[package]] name = "httparse" -version = "1.8.0" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" +checksum = "9f3935c160d00ac752e09787e6e6bfc26494c2183cc922f1bc678a60d4733bc2" [[package]] name = "httpdate" @@ -2206,6 +2217,124 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f8ac670d7422d7f76b32e17a5db556510825b29ec9154f235977c9caba61036" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -2224,12 +2353,14 @@ dependencies = [ [[package]] name = "idna" -version = "0.5.0" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +checksum = "4716a3a0933a1d01c2f72450e89596eb51dd34ef3c211ccd875acdf1f8fe47ed" dependencies = [ - "unicode-bidi", - "unicode-normalization", + "icu_normalizer", + "icu_properties", + "smallvec", + "utf8_iter", ] [[package]] @@ -2472,6 +2603,12 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +[[package]] +name = "litemap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" + [[package]] name = "litrs" version = "0.4.1" @@ -3465,14 +3602,14 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.4" +version = "1.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" +checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.6", - "regex-syntax 0.8.3", + "regex-automata 0.4.7", + "regex-syntax 0.8.4", ] [[package]] @@ -3486,13 +3623,13 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" +checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.3", + "regex-syntax 0.8.4", ] [[package]] @@ -3503,9 +3640,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" +checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" [[package]] name = "region" @@ -4458,6 +4595,17 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + [[package]] name = "system-configuration" version = "0.5.1" @@ -4597,6 +4745,16 @@ dependencies = [ "time-core", ] +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinyvec" version = "1.6.0" @@ -4777,7 +4935,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.11", + "winnow 0.6.13", ] [[package]] @@ -5114,12 +5272,12 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" +checksum = "f7c25da092f0a868cdf09e8674cd3b7ef3a7d92a24253e663a2fb85e2496de56" dependencies = [ "form_urlencoded", - "idna 0.5.0", + "idna 1.0.0", "percent-encoding", "serde", ] @@ -5136,11 +5294,23 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" @@ -5551,9 +5721,9 @@ dependencies = [ [[package]] name = "wide" -version = "0.7.23" +version = "0.7.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1134eff459f1063780b94cc78b704e2212cac12abd554e4268f5b8f9dfcc1883" +checksum = "8a040b111774ab63a19ef46bbc149398ab372b4ccdcfd719e9814dbd7dfd76c8" dependencies = [ "bytemuck", "safe_arch", @@ -5798,9 +5968,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.11" +version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c52728401e1dc672a56e81e593e912aa54c78f40246869f78359a2bf24d29d" +checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" dependencies = [ "memchr", ] @@ -5825,6 +5995,18 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + [[package]] name = "wyz" version = "0.5.1" @@ -5860,6 +6042,30 @@ dependencies = [ "lzma-sys", ] +[[package]] +name = "yoke" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.7.34" @@ -5880,8 +6086,51 @@ dependencies = [ "syn 2.0.66", ] +[[package]] +name = "zerofrom" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", + "synstructure", +] + [[package]] name = "zeroize" version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" + +[[package]] +name = "zerovec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb2cc8827d6c0994478a15c53f374f46fbd41bea663d809b14744bc42e6b109c" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97cf56601ee5052b4417d90c8755c6683473c926039908196cf35d99f893ebe7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] diff --git a/crates/core/src/bin/freenet.rs b/crates/core/src/bin/freenet.rs index c6e7ffabf..3f27bb661 100644 --- a/crates/core/src/bin/freenet.rs +++ b/crates/core/src/bin/freenet.rs @@ -6,14 +6,14 @@ use freenet::{ }; use std::{net::SocketAddr, sync::Arc}; -async fn run(config: Config) -> Result<(), anyhow::Error> { +async fn run(config: Config) -> anyhow::Result<()> { match config.mode { OperationMode::Local => run_local(config).await, OperationMode::Network => run_network(config).await, } } -async fn run_local(config: Config) -> Result<(), anyhow::Error> { +async fn run_local(config: Config) -> anyhow::Result<()> { tracing::info!("Starting freenet node in local mode"); let port = config.ws_api.port; let ip = config.ws_api.address; @@ -27,12 +27,12 @@ async fn run_local(config: Config) -> Result<(), anyhow::Error> { .map_err(anyhow::Error::msg) } -async fn run_network(config: Config) -> Result<(), anyhow::Error> { +async fn run_network(config: Config) -> anyhow::Result<()> { tracing::info!("Starting freenet node in network mode"); run_network_node(config).await } -fn main() -> Result<(), anyhow::Error> { +fn main() -> anyhow::Result<()> { freenet::config::set_logger(None); let config = ConfigArgs::parse().build()?; let rt = tokio::runtime::Builder::new_multi_thread() diff --git a/crates/core/src/client_events/websocket.rs b/crates/core/src/client_events/websocket.rs index 8a4655567..c84d43ba9 100644 --- a/crates/core/src/client_events/websocket.rs +++ b/crates/core/src/client_events/websocket.rs @@ -27,7 +27,6 @@ use crate::{ client_events::AuthToken, server::{ClientConnection, HostCallbackResult}, util::EncodingProtocol, - DynError, }; use super::{ClientError, ClientEventsProxy, ClientId, HostResult, OpenRequest}; @@ -224,7 +223,7 @@ async fn websocket_interface( mut auth_token: Option, encoding_protoc: EncodingProtocol, ws: WebSocket, -) -> Result<(), DynError> { +) -> anyhow::Result<()> { let (mut response_rx, client_id) = new_client_connection(&request_sender).await?; let (mut tx, mut rx) = ws.split(); let contract_updates: Arc)>>> = @@ -246,7 +245,7 @@ async fn websocket_interface( active_listeners.push_back((key, listener)); } Err(err @ mpsc::error::TryRecvError::Disconnected) => { - return Err(Box::new(err) as DynError) + return Err(anyhow::anyhow!(err)) } } } @@ -345,7 +344,7 @@ async fn process_client_request( request_sender: &mpsc::Sender, auth_token: &mut Option, encoding_protoc: EncodingProtocol, -) -> Result, Option> { +) -> Result, Option> { let msg = match msg { Ok(Message::Binary(data)) => data, Ok(Message::Text(data)) => data.into_bytes(), @@ -401,7 +400,7 @@ async fn process_host_response( client_id: ClientId, encoding_protoc: EncodingProtocol, tx: &mut SplitSink, -) -> Result, DynError> { +) -> anyhow::Result> { match msg { Some(HostCallbackResult::Result { id, result }) => { debug_assert_eq!(id, client_id); @@ -452,7 +451,9 @@ async fn process_host_response( tx.send(Message::Binary(result_error)).await?; tx.send(Message::Close(None)).await?; tracing::warn!("node shut down while handling responses for {client_id}"); - Err(format!("node shut down while handling responses for {client_id}").into()) + Err(anyhow::anyhow!( + "node shut down while handling responses for {client_id}" + )) } } } diff --git a/crates/core/src/config.rs b/crates/core/src/config.rs index 99c9303d5..7d5ff083d 100644 --- a/crates/core/src/config.rs +++ b/crates/core/src/config.rs @@ -125,7 +125,7 @@ impl ConfigArgs { match config_args { Some((filename, ext)) => { - let path = dir.join(&filename).with_extension(&ext); + let path = dir.join(filename).with_extension(&ext); tracing::info!("Reading configuration file: {path:?}",); match ext.as_str() { "toml" => { diff --git a/crates/core/src/contract/executor.rs b/crates/core/src/contract/executor.rs index 5182d825c..37214b4e0 100644 --- a/crates/core/src/contract/executor.rs +++ b/crates/core/src/contract/executor.rs @@ -36,7 +36,6 @@ use crate::wasm_runtime::{ use crate::{ client_events::{ClientId, HostResult}, operations::{self, Operation}, - DynError, }; use super::storages::Storage; @@ -45,7 +44,7 @@ pub(super) mod mock_runtime; pub(super) mod runtime; #[derive(Debug)] -pub struct ExecutorError(Either, DynError>); +pub struct ExecutorError(Either, anyhow::Error>); enum InnerOpError { Upsert(ContractKey), @@ -55,13 +54,13 @@ enum InnerOpError { impl std::error::Error for ExecutorError {} impl ExecutorError { - pub fn other(error: impl Into) -> Self { + pub fn other(error: impl Into) -> Self { Self(Either::Right(error.into())) } /// Call this when an unreachable path is reached but need to avoid panics. fn internal_error() -> Self { - ExecutorError(Either::Right("internal error".into())) + ExecutorError(Either::Right(anyhow::anyhow!("internal error"))) } fn request(error: impl Into) -> Self { @@ -107,19 +106,19 @@ impl ExecutorError { Some(InnerOpError::Upsert(key)) => { return ExecutorError::request(StdContractError::update_exec_error(key, e)) } - _ => return ExecutorError::other(format!("execution error: {e}")), + _ => return ExecutorError::other(anyhow::anyhow!("execution error: {e}")), }, RuntimeInnerError::WasmExportError(e) => match op { Some(InnerOpError::Upsert(key)) => { return ExecutorError::request(StdContractError::update_exec_error(key, e)) } - _ => return ExecutorError::other(format!("execution error: {e}")), + _ => return ExecutorError::other(anyhow::anyhow!("execution error: {e}")), }, RuntimeInnerError::WasmInstantiationError(e) => match op { Some(InnerOpError::Upsert(key)) => { return ExecutorError::request(StdContractError::update_exec_error(key, e)) } - _ => return ExecutorError::other(format!("execution error: {e}")), + _ => return ExecutorError::other(anyhow::anyhow!("execution error: {e}")), }, _ => {} } @@ -225,7 +224,7 @@ enum CallbackError { } impl ExecutorToEventLoopChannel { - async fn send_to_event_loop(&mut self, message: T) -> Result + async fn send_to_event_loop(&mut self, message: T) -> anyhow::Result where T: ComposeNetworkMessage, Op: Operation + Send + 'static, @@ -257,7 +256,7 @@ impl ExecutorToEventLoopChannel { .response_for_rx .recv() .await - .ok_or_else(|| ExecutorError::other("channel closed"))?; + .ok_or_else(|| ExecutorError::other(anyhow::anyhow!("channel closed")))?; if op_result.id() != &transaction { self.end.completed.insert(*op_result.id(), op_result); return Err(CallbackError::MissingResult); @@ -267,13 +266,13 @@ impl ExecutorToEventLoopChannel { } impl ExecutorToEventLoopChannel { - pub async fn transaction_from_executor(&mut self) -> Result { + pub async fn transaction_from_executor(&mut self) -> anyhow::Result { let tx = self .end .waiting_for_op_rx .recv() .await - .ok_or("channel closed")?; + .ok_or(anyhow::anyhow!("channel closed"))?; Ok(tx) } @@ -463,11 +462,11 @@ pub struct Executor { impl Executor { pub async fn new( state_store: StateStore, - ctrl_handler: impl FnOnce() -> Result<(), DynError>, + ctrl_handler: impl FnOnce() -> anyhow::Result<()>, mode: OperationMode, runtime: R, event_loop_channel: Option>, - ) -> Result { + ) -> anyhow::Result { ctrl_handler()?; Ok(Self { @@ -498,7 +497,7 @@ impl Executor { SecretsStore, StateStore, ), - DynError, + anyhow::Error, > { const MAX_SIZE: i64 = 10 * 1024 * 1024; const MAX_MEM_CACHE: u32 = 10_000_000; @@ -521,7 +520,9 @@ impl Executor { M: ComposeNetworkMessage, { let Some(ch) = &mut self.event_loop_channel else { - return Err(ExecutorError::other("missing event loop channel")); + return Err(ExecutorError::other(anyhow::anyhow!( + "missing event loop channel" + ))); }; let transaction = ch .send_to_event_loop(request) diff --git a/crates/core/src/contract/executor/mock_runtime.rs b/crates/core/src/contract/executor/mock_runtime.rs index 5b53d9c9b..92c66a32d 100644 --- a/crates/core/src/contract/executor/mock_runtime.rs +++ b/crates/core/src/contract/executor/mock_runtime.rs @@ -8,7 +8,7 @@ impl Executor { pub async fn new_mock( identifier: &str, event_loop_channel: ExecutorToEventLoopChannel, - ) -> Result { + ) -> anyhow::Result { let data_dir = Self::test_data_dir(identifier); let contracts_data_dir = data_dir.join("contracts"); @@ -56,7 +56,7 @@ impl ContractExecutor for Executor { .await .map_err(ExecutorError::other)? else { - return Err(ExecutorError::other(format!( + return Err(ExecutorError::other(anyhow::anyhow!( "missing state and/or parameters for contract {key}" ))); }; @@ -68,7 +68,7 @@ impl ContractExecutor for Executor { None }; let Ok(state) = self.state_store.get(&key).await else { - return Err(ExecutorError::other(format!( + return Err(ExecutorError::other(anyhow::anyhow!( "missing state for contract {key}" ))); }; diff --git a/crates/core/src/contract/executor/runtime.rs b/crates/core/src/contract/executor/runtime.rs index 949be4866..623c04696 100644 --- a/crates/core/src/contract/executor/runtime.rs +++ b/crates/core/src/contract/executor/runtime.rs @@ -153,7 +153,7 @@ impl Executor { pub async fn from_config( config: Arc, event_loop_channel: Option>, - ) -> Result { + ) -> anyhow::Result { let (contract_store, delegate_store, secret_store, state_store) = Self::get_stores(&config).await?; let rt = Runtime::build(contract_store, delegate_store, secret_store, false).unwrap(); @@ -246,7 +246,7 @@ impl Executor { } Err(RequestError::Disconnect.into()) } - _ => Err(ExecutorError::other("not supported")), + _ => Err(ExecutorError::other(anyhow::anyhow!("not supported"))), } } @@ -272,8 +272,9 @@ impl Executor { fetch_contract: contract, } => self.perform_contract_get(contract, key).await, ContractRequest::Subscribe { key, summary } => { - let updates = - updates.ok_or_else(|| ExecutorError::other("missing update channel"))?; + let updates = updates.ok_or_else(|| { + ExecutorError::other(anyhow::anyhow!("missing update channel")) + })?; self.register_contract_notifier(key, cli_id, updates, summary)?; // by default a subscribe op has an implicit get let res = self.perform_contract_get(false, key).await?; @@ -287,7 +288,7 @@ impl Executor { } Ok(res) } - _ => Err(ExecutorError::other("not supported")), + _ => Err(ExecutorError::other(anyhow::anyhow!("not supported"))), } } @@ -381,13 +382,13 @@ impl Executor { Err(err) => { tracing::error!("failed executing delegate `{key}`: {err}"); - Err(ExecutorError::other(format!( + Err(ExecutorError::other(anyhow::anyhow!( "uncontrolled error while executing `{key}`" ))) } } } - _ => Err(ExecutorError::other("not supported")), + _ => Err(ExecutorError::other(anyhow::anyhow!("not supported"))), } } @@ -719,7 +720,7 @@ impl Executor { async fn get_local_contract( &self, id: &ContractInstanceId, - ) -> Result, Either, DynError>> { + ) -> Result, Either, anyhow::Error>> { let Ok(contract) = self.state_store.get(&(*id).into()).await else { return Err(Either::Right( StdContractError::MissingRelated { key: *id }.into(), diff --git a/crates/core/src/contract/handler.rs b/crates/core/src/contract/handler.rs index 8dcfc8634..bf9f3c802 100644 --- a/crates/core/src/contract/handler.rs +++ b/crates/core/src/contract/handler.rs @@ -18,7 +18,7 @@ use super::{ use crate::client_events::HostResult; use crate::config::Config; use crate::message::Transaction; -use crate::{client_events::ClientId, wasm_runtime::Runtime, DynError}; +use crate::{client_events::ClientId, wasm_runtime::Runtime}; pub(crate) struct ClientResponsesReceiver(UnboundedReceiver<(ClientId, HostResult)>); @@ -60,7 +60,7 @@ pub(crate) trait ContractHandler { contract_handler_channel: ContractHandlerChannel, executor_request_sender: ExecutorToEventLoopChannel, builder: Self::Builder, - ) -> impl Future> + Send + ) -> impl Future> + Send where Self: Sized + 'static; @@ -82,7 +82,7 @@ impl ContractHandler for NetworkContractHandler { channel: ContractHandlerChannel, executor_request_sender: ExecutorToEventLoopChannel, config: Self::Builder, - ) -> Result + ) -> anyhow::Result where Self: Sized + 'static, { @@ -108,7 +108,7 @@ impl ContractHandler for NetworkContractHandler { channel: ContractHandlerChannel, executor_request_sender: ExecutorToEventLoopChannel, identifier: Self::Builder, - ) -> Result + ) -> anyhow::Result where Self: Sized + 'static, { @@ -203,12 +203,12 @@ static EV_ID: AtomicU64 = AtomicU64::new(0); impl ContractHandlerChannel { pub async fn relay_transaction_result_to_client( &mut self, - ) -> Result<(ClientId, Transaction), DynError> { + ) -> anyhow::Result<(ClientId, Transaction)> { self.end .wait_for_res_rx .recv() .await - .ok_or_else(|| "channel dropped".into()) + .ok_or_else(|| anyhow::anyhow!("channel dropped")) } } @@ -386,7 +386,7 @@ pub mod test { use crate::config::GlobalExecutor; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn channel_test() -> Result<(), anyhow::Error> { + async fn channel_test() -> anyhow::Result<()> { let (send_halve, mut rcv_halve, _) = contract_handler_channel(); let contract = ContractContainer::Wasm(ContractWasmAPIVersion::V1(WrappedContract::new( @@ -441,7 +441,6 @@ pub(super) mod in_memory { }, ContractHandler, ContractHandlerChannel, ContractHandlerHalve, }; - use crate::DynError; pub(crate) struct MemoryContractHandler { channel: ContractHandlerChannel, @@ -471,7 +470,7 @@ pub(super) mod in_memory { channel: ContractHandlerChannel, executor_request_sender: ExecutorToEventLoopChannel, identifier: Self::Builder, - ) -> Result + ) -> anyhow::Result where Self: Sized + 'static, { @@ -488,7 +487,7 @@ pub(super) mod in_memory { } #[test] - fn serialization() -> Result<(), anyhow::Error> { + fn serialization() -> anyhow::Result<()> { use freenet_stdlib::prelude::WrappedContract; let bytes = crate::util::test::random_bytes_1kb(); let mut gen = arbitrary::Unstructured::new(&bytes); diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 8f64b58be..5be996f88 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -29,8 +29,6 @@ pub mod util; /// WASM code execution runtime, tailored for the contract and delegate APIs. mod wasm_runtime; -type DynError = Box; - /// Exports to build a running local node. pub mod local_node { use super::*; diff --git a/crates/core/src/node.rs b/crates/core/src/node.rs index faa2d9da3..37e275682 100644 --- a/crates/core/src/node.rs +++ b/crates/core/src/node.rs @@ -66,7 +66,7 @@ pub(crate) mod testing_impl; pub struct Node(NodeP2P); impl Node { - pub async fn run(self) -> Result<(), anyhow::Error> { + pub async fn run(self) -> anyhow::Result<()> { self.0.run_node().await?; Ok(()) } @@ -281,7 +281,7 @@ impl NodeConfig { pub async fn build( self, clients: [BoxedClient; CLIENTS], - ) -> Result { + ) -> anyhow::Result { let event_register = { #[cfg(feature = "trace-ot")] { @@ -313,7 +313,7 @@ impl NodeConfig { /// Returns all specified gateways for this peer. Returns an error if the peer is not a gateway /// and no gateways are specified. - fn get_gateways(&self) -> Result, anyhow::Error> { + fn get_gateways(&self) -> anyhow::Result> { let gateways: Vec = self .gateways .iter() diff --git a/crates/core/src/node/network_bridge/p2p_protoc.rs b/crates/core/src/node/network_bridge/p2p_protoc.rs index 2916d5a3f..e272ed98d 100644 --- a/crates/core/src/node/network_bridge/p2p_protoc.rs +++ b/crates/core/src/node/network_bridge/p2p_protoc.rs @@ -111,7 +111,7 @@ impl P2pConnManager { config: &NodeConfig, op_manager: Arc, event_listener: impl NetEventRegister + Clone, - ) -> Result { + ) -> anyhow::Result { let listen_port = config.network_listener_port; let listener_ip = config.network_listener_ip; @@ -142,7 +142,7 @@ impl P2pConnManager { mut executor_listener: ExecutorToEventLoopChannel, cli_response_sender: ClientResponsesSender, mut node_controller: Receiver, - ) -> Result<(), anyhow::Error> { + ) -> anyhow::Result<()> { use ConnMngrActions::*; tracing::info!(%self.listening_port, %self.listening_ip, %self.is_gateway, key = %self.key_pair.public(), "Openning network listener"); diff --git a/crates/core/src/node/op_state_manager.rs b/crates/core/src/node/op_state_manager.rs index eb21c7211..fa410e42e 100644 --- a/crates/core/src/node/op_state_manager.rs +++ b/crates/core/src/node/op_state_manager.rs @@ -61,7 +61,7 @@ impl OpManager { ch_outbound: ContractHandlerChannel, config: &NodeConfig, event_register: ER, - ) -> Result { + ) -> anyhow::Result { let ring = Ring::new( config, notification_channel.clone(), diff --git a/crates/core/src/node/p2p_impl.rs b/crates/core/src/node/p2p_impl.rs index cf51ce6af..26b04cacb 100644 --- a/crates/core/src/node/p2p_impl.rs +++ b/crates/core/src/node/p2p_impl.rs @@ -37,7 +37,7 @@ pub(super) struct NodeP2P { } impl NodeP2P { - pub(super) async fn run_node(self) -> Result<(), anyhow::Error> { + pub(super) async fn run_node(self) -> anyhow::Result<()> { if self.should_try_connect { connect::initial_join_procedure( self.op_manager.clone(), @@ -66,7 +66,7 @@ impl NodeP2P { clients: [BoxedClient; CLIENTS], event_register: ER, ch_builder: CH::Builder, - ) -> Result + ) -> anyhow::Result where CH: ContractHandler + Send + 'static, ER: NetEventRegister + Clone, diff --git a/crates/core/src/node/testing_impl.rs b/crates/core/src/node/testing_impl.rs index 3940b356b..60ae65284 100644 --- a/crates/core/src/node/testing_impl.rs +++ b/crates/core/src/node/testing_impl.rs @@ -528,7 +528,7 @@ impl SimNetwork { seed: u64, max_contract_num: usize, iterations: usize, - ) -> Vec>> + ) -> Vec>> where R: RandomEventGenerator + Send + 'static, { @@ -679,7 +679,7 @@ impl SimNetwork { label: impl Into, event_id: EventId, await_for: Option, - ) -> Result<(), anyhow::Error> { + ) -> anyhow::Result<()> { let label = label.into(); let pos = self .labels @@ -719,7 +719,7 @@ impl SimNetwork { /// Checks that all peers in the network have acquired at least one connection to any /// other peers. - pub fn check_connectivity(&self, time_out: Duration) -> Result<(), anyhow::Error> { + pub fn check_connectivity(&self, time_out: Duration) -> anyhow::Result<()> { self.connectivity(time_out, 1.0) } @@ -729,11 +729,11 @@ impl SimNetwork { &self, time_out: Duration, percent: f64, - ) -> Result<(), anyhow::Error> { + ) -> anyhow::Result<()> { self.connectivity(time_out, percent) } - fn connectivity(&self, time_out: Duration, percent: f64) -> Result<(), anyhow::Error> { + fn connectivity(&self, time_out: Duration, percent: f64) -> anyhow::Result<()> { let num_nodes = self.number_of_nodes; let mut connected = HashSet::new(); let elapsed = Instant::now(); @@ -796,7 +796,7 @@ impl SimNetwork { /// /// - at least 50% of the peers have more than the minimum connections /// - the average number of connections per peer is above the mean between max and min connections - pub fn network_connectivity_quality(&self) -> Result<(), anyhow::Error> { + pub fn network_connectivity_quality(&self) -> anyhow::Result<()> { const HIGHER_THAN_MIN_THRESHOLD: f64 = 0.5; let num_nodes = self.number_of_nodes; let min_connections_threshold = (num_nodes as f64 * HIGHER_THAN_MIN_THRESHOLD) as usize; @@ -912,7 +912,7 @@ fn pretty_print_connections( } #[test] -fn group_locations_test() -> Result<(), anyhow::Error> { +fn group_locations_test() -> anyhow::Result<()> { let locations = vec![0.5356, 0.5435, 0.5468, 0.5597, 0.6745, 0.7309, 0.7412]; let mut grouped: Vec<_> = group_locations_in_buckets(locations.clone(), 1).collect(); @@ -961,7 +961,7 @@ where client_wait_for_transaction: ContractHandlerChannel, } -async fn run_node(mut config: RunnerConfig) -> Result<(), anyhow::Error> +async fn run_node(mut config: RunnerConfig) -> anyhow::Result<()> where NB: NetworkBridge + NetworkBridgeExt, UsrEv: ClientEventsProxy + Send + 'static, @@ -1024,7 +1024,7 @@ async fn run_event_listener( client_wait_for_transaction: mut wait_for_event, .. }: RunnerConfig, -) -> Result<(), anyhow::Error> +) -> anyhow::Result<()> where NB: NetworkBridge + NetworkBridgeExt, UsrEv: ClientEventsProxy + Send + 'static, diff --git a/crates/core/src/node/testing_impl/in_memory.rs b/crates/core/src/node/testing_impl/in_memory.rs index 127745bce..84e43bdd8 100644 --- a/crates/core/src/node/testing_impl/in_memory.rs +++ b/crates/core/src/node/testing_impl/in_memory.rs @@ -22,7 +22,7 @@ impl Builder { self, user_events: UsrEv, parent_span: tracing::Span, - ) -> Result<(), anyhow::Error> + ) -> anyhow::Result<()> where UsrEv: ClientEventsProxy + Send + 'static, ER: NetEventRegister + Clone, @@ -96,7 +96,7 @@ where &mut self, contracts: Vec<(ContractContainer, WrappedState, bool)>, contract_subscribers: HashMap>, - ) -> Result<(), anyhow::Error> { + ) -> anyhow::Result<()> { use crate::contract::ContractHandlerEvent; for (contract, state, subscription) in contracts { let key: ContractKey = contract.key(); diff --git a/crates/core/src/node/testing_impl/network.rs b/crates/core/src/node/testing_impl/network.rs index 0a3aed555..5f4dda104 100644 --- a/crates/core/src/node/testing_impl/network.rs +++ b/crates/core/src/node/testing_impl/network.rs @@ -66,7 +66,7 @@ impl NetworkPeer { &self, identifier: String, clients: [BoxedClient; CLIENTS], - ) -> Result { + ) -> anyhow::Result { let event_register = { #[cfg(feature = "trace-ot")] { diff --git a/crates/core/src/operations/connect.rs b/crates/core/src/operations/connect.rs index 889b97ea6..404a98c26 100644 --- a/crates/core/src/operations/connect.rs +++ b/crates/core/src/operations/connect.rs @@ -1131,7 +1131,7 @@ mod test { /// Given a network of one node and one gateway test that both are connected. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn one_node_connects_to_gw() -> Result<(), anyhow::Error> { + async fn one_node_connects_to_gw() -> anyhow::Result<()> { const NUM_NODES: usize = 1usize; const NUM_GW: usize = 1usize; const MAX_HTL: usize = 1usize; @@ -1156,7 +1156,7 @@ mod test { /// Once a gateway is left without remaining open slots, ensure forwarding connects #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn forward_connection_to_node() -> Result<(), anyhow::Error> { + async fn forward_connection_to_node() -> anyhow::Result<()> { const NUM_NODES: usize = 3usize; const NUM_GW: usize = 1usize; const MAX_HTL: usize = 2usize; @@ -1190,7 +1190,7 @@ mod test { /// Given a network of N peers all good connectivity #[tokio::test(flavor = "multi_thread")] - async fn network_should_achieve_good_connectivity() -> Result<(), anyhow::Error> { + async fn network_should_achieve_good_connectivity() -> anyhow::Result<()> { // crate::config::set_logger(); const NUM_NODES: usize = 10usize; const NUM_GW: usize = 2usize; diff --git a/crates/core/src/operations/get.rs b/crates/core/src/operations/get.rs index 48488cea5..d9c1126b4 100644 --- a/crates/core/src/operations/get.rs +++ b/crates/core/src/operations/get.rs @@ -869,7 +869,7 @@ mod test { use crate::node::testing_impl::{NodeSpecification, SimNetwork}; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn successful_get_op_between_nodes() -> Result<(), anyhow::Error> { + async fn successful_get_op_between_nodes() -> anyhow::Result<()> { const NUM_NODES: usize = 1usize; const NUM_GW: usize = 1usize; @@ -924,7 +924,7 @@ mod test { } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn contract_not_found() -> Result<(), anyhow::Error> { + async fn contract_not_found() -> anyhow::Result<()> { const NUM_NODES: usize = 2usize; const NUM_GW: usize = 1usize; @@ -961,7 +961,7 @@ mod test { } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn contract_found_after_retry() -> Result<(), anyhow::Error> { + async fn contract_found_after_retry() -> anyhow::Result<()> { // crate::config::set_logger(); const NUM_NODES: usize = 2usize; const NUM_GW: usize = 1usize; diff --git a/crates/core/src/operations/put.rs b/crates/core/src/operations/put.rs index c4d3bbbd1..110f71b13 100644 --- a/crates/core/src/operations/put.rs +++ b/crates/core/src/operations/put.rs @@ -931,7 +931,7 @@ mod test { use crate::node::testing_impl::{NodeSpecification, SimNetwork}; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn successful_put_op_between_nodes() -> Result<(), anyhow::Error> { + async fn successful_put_op_between_nodes() -> anyhow::Result<()> { const NUM_NODES: usize = 2usize; const NUM_GW: usize = 1usize; diff --git a/crates/core/src/operations/subscribe.rs b/crates/core/src/operations/subscribe.rs index 44f305345..decf496d0 100644 --- a/crates/core/src/operations/subscribe.rs +++ b/crates/core/src/operations/subscribe.rs @@ -515,7 +515,7 @@ mod test { use crate::node::testing_impl::{NodeSpecification, SimNetwork}; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn successful_subscribe_op_between_nodes() -> Result<(), anyhow::Error> { + async fn successful_subscribe_op_between_nodes() -> anyhow::Result<()> { const NUM_NODES: usize = 4usize; const NUM_GW: usize = 1usize; diff --git a/crates/core/src/ring.rs b/crates/core/src/ring.rs index 00080a267..e860e98a2 100644 --- a/crates/core/src/ring.rs +++ b/crates/core/src/ring.rs @@ -43,7 +43,6 @@ use crate::{ node::{self, EventLoopNotificationsSender, NodeConfig, PeerId}, operations::connect, router::Router, - DynError, }; #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -255,7 +254,7 @@ impl Ring { event_loop_notifier: EventLoopNotificationsSender, event_register: ER, is_gateway: bool, - ) -> Result, anyhow::Error> { + ) -> anyhow::Result> { let (live_tx_tracker, missing_candidate_rx) = LiveTransactionTracker::new(); let peer_pub_key = config.key_pair.public().clone(); @@ -772,7 +771,7 @@ impl Ring { notifier: EventLoopNotificationsSender, live_tx_tracker: LiveTransactionTracker, mut missing_candidates: sync::mpsc::Receiver, - ) -> Result<(), DynError> { + ) -> anyhow::Result<()> { #[cfg(not(test))] const CONNECTION_AGE_THRESOLD: Duration = Duration::from_secs(60 * 5); #[cfg(test)] @@ -798,7 +797,7 @@ impl Ring { let mut live_tx = None; let mut pending_conn_adds = VecDeque::new(); - 'outer: loop { + loop { if self.get_peer_key().is_none() { tokio::time::sleep(Duration::from_secs(1)).await; continue; @@ -811,7 +810,7 @@ impl Ring { Err(sync::mpsc::error::TryRecvError::Empty) => break, Err(sync::mpsc::error::TryRecvError::Disconnected) => { tracing::debug!("Shutting down connection maintenance"); - break 'outer Err("finished".into()); + anyhow::bail!("finished"); } } } @@ -906,7 +905,7 @@ impl Ring { ideal_location: Location, skip_list: &[&PeerId], notifier: &EventLoopNotificationsSender, - ) -> Result, DynError> { + ) -> anyhow::Result> { use crate::message::InnerMessage; let Some(query_target) = self.routing(ideal_location, None, skip_list) else { return Ok(None); diff --git a/crates/core/src/server.rs b/crates/core/src/server.rs index 6d1ca69f2..2a2d06ec2 100644 --- a/crates/core/src/server.rs +++ b/crates/core/src/server.rs @@ -62,21 +62,17 @@ pub mod local_node { use crate::{ client_events::{websocket::WebSocketProxy, ClientEventsProxy, OpenRequest}, contract::{Executor, ExecutorError}, - DynError, }; use super::{http_gateway::HttpGateway, serve}; - pub async fn run_local_node( - mut executor: Executor, - socket: SocketAddr, - ) -> Result<(), DynError> { + pub async fn run_local_node(mut executor: Executor, socket: SocketAddr) -> anyhow::Result<()> { match socket.ip() { IpAddr::V4(ip) if !ip.is_loopback() => { - return Err(format!("invalid ip: {ip}, expecting localhost").into()) + anyhow::bail!("invalid ip: {ip}, expecting localhost") } IpAddr::V6(ip) if !ip.is_loopback() => { - return Err(format!("invalid ip: {ip}, expecting localhost").into()) + anyhow::bail!("invalid ip: {ip}, expecting localhost") } _ => {} } @@ -138,7 +134,7 @@ pub mod local_node { } continue; } - _ => Err(ExecutorError::other("not supported")), + _ => Err(ExecutorError::other(anyhow::anyhow!("not supported"))), }; match res { @@ -187,7 +183,7 @@ pub mod network_node { use super::{http_gateway::HttpGateway, serve}; - pub async fn run_network_node(config: Config) -> Result<(), anyhow::Error> { + pub async fn run_network_node(config: Config) -> anyhow::Result<()> { let ws_socket = (config.ws_api.address, config.ws_api.port).into(); let (gw, gw_router) = HttpGateway::as_router(&ws_socket); let (ws_proxy, ws_router) = WebSocketProxy::as_router(gw_router); diff --git a/crates/core/src/server/app_packaging.rs b/crates/core/src/server/app_packaging.rs index 6a9f545c1..02f6ffb7a 100644 --- a/crates/core/src/server/app_packaging.rs +++ b/crates/core/src/server/app_packaging.rs @@ -8,12 +8,10 @@ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use tar::{Archive, Builder}; use xz2::read::{XzDecoder, XzEncoder}; -use crate::DynError; - #[derive(Debug, thiserror::Error)] pub enum WebContractError { #[error("unpacking error: {0}")] - UnpackingError(DynError), + UnpackingError(anyhow::Error), #[error("{0}")] StoringError(std::io::Error), #[error("file not found: {0}")] @@ -64,9 +62,9 @@ impl WebApp { let mut decoded_web = self.decode_web(); for e in decoded_web .entries() - .map_err(|e| WebContractError::UnpackingError(Box::new(e)))? + .map_err(|e| WebContractError::UnpackingError(anyhow::anyhow!(e)))? { - let mut e = e.map_err(|e| WebContractError::UnpackingError(Box::new(e)))?; + let mut e = e.map_err(|e| WebContractError::UnpackingError(anyhow::anyhow!(e)))?; if e.path() .ok() .filter(|p| p.to_string_lossy() == path) @@ -74,7 +72,7 @@ impl WebApp { { let mut bytes = vec![]; e.read_to_end(&mut bytes) - .map_err(|e| WebContractError::UnpackingError(Box::new(e)))?; + .map_err(|e| WebContractError::UnpackingError(anyhow::anyhow!(e)))?; return Ok(bytes); } } @@ -98,29 +96,31 @@ impl<'a> TryFrom<&'a [u8]> for WebApp { let metadata_size = state .read_u64::() - .map_err(|e| WebContractError::UnpackingError(Box::new(e)))?; + .map_err(|e| WebContractError::UnpackingError(anyhow::anyhow!(e)))?; if metadata_size > MAX_METADATA_SIZE { - return Err(WebContractError::UnpackingError( - format!("Exceeded metadata size of 1kB: {} bytes", metadata_size).into(), - )); + return Err(WebContractError::UnpackingError(anyhow::anyhow!( + "Exceeded metadata size of 1kB: {} bytes", + metadata_size + ))); } let mut metadata = vec![0; metadata_size as usize]; state .read_exact(&mut metadata) - .map_err(|e| WebContractError::UnpackingError(Box::new(e)))?; + .map_err(|e| WebContractError::UnpackingError(anyhow::anyhow!(e)))?; let web_size = state .read_u64::() - .map_err(|e| WebContractError::UnpackingError(Box::new(e)))?; + .map_err(|e| WebContractError::UnpackingError(anyhow::anyhow!(e)))?; if web_size > MAX_WEB_SIZE { - return Err(WebContractError::UnpackingError( - format!("Exceeded packed web size of 100MB: {} bytes", web_size).into(), - )); + return Err(WebContractError::UnpackingError(anyhow::anyhow!( + "Exceeded packed web size of 100MB: {} bytes", + web_size + ))); } let mut web = vec![0; web_size as usize]; state .read_exact(&mut web) - .map_err(|e| WebContractError::UnpackingError(Box::new(e)))?; + .map_err(|e| WebContractError::UnpackingError(anyhow::anyhow!(e)))?; Ok(Self { metadata, web }) } diff --git a/crates/core/src/topology/meter.rs b/crates/core/src/topology/meter.rs index 8cfa60729..d0de315ff 100644 --- a/crates/core/src/topology/meter.rs +++ b/crates/core/src/topology/meter.rs @@ -228,7 +228,6 @@ impl ResourceTotals { // Tests #[cfg(test)] mod tests { - use crate::DynError; use super::*; @@ -288,7 +287,7 @@ mod tests { } #[test] - fn test_meter_report() -> Result<(), DynError> { + fn test_meter_report() -> anyhow::Result<()> { let mut meter = Meter::new_with_window_size(100); // Report some usage and test that the total and attributed usage are updated diff --git a/crates/core/src/tracing.rs b/crates/core/src/tracing.rs index 8d6a19d3c..d59797149 100644 --- a/crates/core/src/tracing.rs +++ b/crates/core/src/tracing.rs @@ -17,7 +17,6 @@ use crate::{ operations::{connect, get::GetMsg, put::PutMsg, subscribe::SubscribeMsg}, ring::{Location, PeerKeyLocation, Ring}, router::RouteEvent, - DynError, }; #[cfg(feature = "trace-ot")] @@ -41,7 +40,7 @@ pub(crate) trait NetEventRegister: std::any::Any + Send + Sync + 'static { ) -> BoxFuture<'a, ()>; fn notify_of_time_out(&mut self, tx: Transaction) -> BoxFuture<()>; fn trait_clone(&self) -> Box; - fn get_router_events(&self, number: usize) -> BoxFuture, DynError>>; + fn get_router_events(&self, number: usize) -> BoxFuture>>; } #[cfg(feature = "trace-ot")] @@ -81,7 +80,7 @@ impl NetEventRegister for CombinedRegister { .boxed() } - fn get_router_events(&self, number: usize) -> BoxFuture, DynError>> { + fn get_router_events(&self, number: usize) -> BoxFuture>> { async move { for reg in &self.0 { let events = reg.get_router_events(number).await?; @@ -460,7 +459,7 @@ impl NetEventRegister for EventRegister { async {}.boxed() } - fn get_router_events(&self, number: usize) -> BoxFuture, DynError>> { + fn get_router_events(&self, number: usize) -> BoxFuture>> { async move { aof::LogFile::get_router_events(number, &self.log_file).await }.boxed() } } @@ -826,10 +825,7 @@ mod opentelemetry_tracer { .boxed() } - fn get_router_events( - &self, - _number: usize, - ) -> BoxFuture, DynError>> { + fn get_router_events(&self, _number: usize) -> BoxFuture>> { async { Ok(vec![]) }.boxed() } } @@ -934,9 +930,7 @@ pub(crate) mod tracer { use tracing::level_filters::LevelFilter; use tracing_subscriber::{Layer, Registry}; - use crate::DynError; - - pub fn init_tracer(level: Option) -> Result<(), DynError> { + pub fn init_tracer(level: Option) -> anyhow::Result<()> { let default_filter = if cfg!(any(test, debug_assertions)) { LevelFilter::DEBUG } else { @@ -1245,16 +1239,13 @@ pub(super) mod test { async {}.boxed() } - fn get_router_events( - &self, - _number: usize, - ) -> BoxFuture, DynError>> { + fn get_router_events(&self, _number: usize) -> BoxFuture>> { async { Ok(vec![]) }.boxed() } } #[tokio::test] - async fn test_get_connections() -> Result<(), anyhow::Error> { + async fn test_get_connections() -> anyhow::Result<()> { use crate::ring::Location; let peer_id = PeerId::random(); let loc = Location::try_from(0.5)?; diff --git a/crates/core/src/tracing/aof.rs b/crates/core/src/tracing/aof.rs index a7e73867e..df1c437a6 100644 --- a/crates/core/src/tracing/aof.rs +++ b/crates/core/src/tracing/aof.rs @@ -8,7 +8,7 @@ use std::path::{Path, PathBuf}; use tokio::sync::Mutex; -use super::{DynError, EventKind, NetLogMessage, RouteEvent, NEW_RECORDS_TS}; +use super::{EventKind, NetLogMessage, RouteEvent, NEW_RECORDS_TS}; static FILE_LOCK: Mutex<()> = Mutex::const_new(()); @@ -283,7 +283,7 @@ impl LogFile { pub async fn get_router_events( max_event_number: usize, event_log_path: &Path, - ) -> Result, DynError> { + ) -> anyhow::Result> { const MAX_EVENT_HISTORY: usize = 10_000; let event_num = max_event_number.min(MAX_EVENT_HISTORY); @@ -296,7 +296,7 @@ impl LogFile { async fn get_router_events_in( event_num: usize, file: &mut (impl AsyncRead + AsyncSeek + Unpin), - ) -> Result, DynError> { + ) -> anyhow::Result> { let new_records_ts = NEW_RECORDS_TS .get() .expect("set on initialization") @@ -351,7 +351,7 @@ impl LogFile { } } } - Ok::<_, DynError>(filtered) + Ok::<_, anyhow::Error>(filtered) }) .await??; @@ -406,7 +406,7 @@ mod tests { use super::*; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn read_write() -> Result<(), DynError> { + async fn read_write() -> anyhow::Result<()> { NEW_RECORDS_TS.get_or_init(SystemTime::now); crate::config::set_logger(Some(LevelFilter::TRACE)); let temp_dir = tempfile::tempdir()?; @@ -453,7 +453,7 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn read_write_small() -> Result<(), DynError> { + async fn read_write_small() -> anyhow::Result<()> { NEW_RECORDS_TS.get_or_init(SystemTime::now); crate::config::set_logger(Some(LevelFilter::TRACE)); let temp_dir = tempfile::tempdir()?; @@ -500,7 +500,7 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn read_write_truncate() -> Result<(), DynError> { + async fn read_write_truncate() -> anyhow::Result<()> { NEW_RECORDS_TS.get_or_init(SystemTime::now); crate::config::set_logger(Some(LevelFilter::TRACE)); let temp_dir = tempfile::tempdir()?; diff --git a/crates/core/src/transport/connection_handler.rs b/crates/core/src/transport/connection_handler.rs index f8f6991ae..476b656b8 100644 --- a/crates/core/src/transport/connection_handler.rs +++ b/crates/core/src/transport/connection_handler.rs @@ -863,7 +863,7 @@ mod test { use tracing::info; use super::*; - use crate::{transport::packet_data::MAX_DATA_SIZE, DynError}; + use crate::transport::packet_data::MAX_DATA_SIZE; #[allow(clippy::type_complexity)] static CHANNELS: OnceLock< @@ -986,7 +986,7 @@ mod test { async fn set_peer_connection( packet_drop_policy: PacketDropPolicy, - ) -> Result<(TransportPublicKey, OutboundConnectionHandler, SocketAddr), DynError> { + ) -> anyhow::Result<(TransportPublicKey, OutboundConnectionHandler, SocketAddr)> { set_peer_connection_in(packet_drop_policy, false) .await .map(|(pk, (o, _), s)| (pk, o, s)) @@ -1000,7 +1000,7 @@ mod test { mpsc::Receiver, SocketAddr, ), - DynError, + anyhow::Error, > { set_peer_connection_in(packet_drop_policy, true) .await @@ -1016,7 +1016,7 @@ mod test { (OutboundConnectionHandler, mpsc::Receiver), SocketAddr, ), - DynError, + anyhow::Error, > { static PORT: AtomicU16 = AtomicU16::new(25000); @@ -1066,7 +1066,7 @@ mod test { async fn run_test( config: TestConfig, generators: Vec, - ) -> Result<(), DynError> { + ) -> anyhow::Result<()> { assert_eq!(generators.len(), config.peers); let mut peer_keys_and_addr = vec![]; let mut peer_conns = vec![]; @@ -1118,8 +1118,8 @@ mod test { peer_conn.send(test_gen_cp.gen_msg()).await?; let msg = tokio::select! { _ = to.tick() => { - return Err::<_, DynError>( - format!("timeout waiting for messages, total time: {:.2}", start.elapsed().as_secs_f64()).into() + return Err::<_, anyhow::Error>( + anyhow::anyhow!("timeout waiting for messages, total time: {:.2}", start.elapsed().as_secs_f64()) ); } msg = peer_conn.recv() => { @@ -1145,7 +1145,7 @@ mod test { }); } let results = conns.try_collect::>().await?; - Ok::<_, DynError>((results, test_generator)) + Ok::<_, anyhow::Error>((results, test_generator)) }); tasks.push(peer); } @@ -1167,7 +1167,7 @@ mod test { } #[tokio::test] - async fn simulate_nat_traversal() -> Result<(), DynError> { + async fn simulate_nat_traversal() -> anyhow::Result<()> { // crate::config::set_logger(); let (peer_a_pub, mut peer_a, peer_a_addr) = set_peer_connection(Default::default()).await?; let (peer_b_pub, mut peer_b, peer_b_addr) = set_peer_connection(Default::default()).await?; @@ -1175,13 +1175,13 @@ mod test { let peer_b = tokio::spawn(async move { let peer_a_conn = peer_b.connect(peer_a_pub, peer_a_addr).await; let _ = tokio::time::timeout(Duration::from_secs(500), peer_a_conn).await??; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { let peer_b_conn = peer_a.connect(peer_b_pub, peer_b_addr).await; let _ = tokio::time::timeout(Duration::from_secs(500), peer_b_conn).await??; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, peer_b)?; @@ -1191,7 +1191,7 @@ mod test { } #[tokio::test] - async fn simulate_nat_traversal_drop_first_packets_for_all() -> Result<(), DynError> { + async fn simulate_nat_traversal_drop_first_packets_for_all() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); let (peer_a_pub, mut peer_a, peer_a_addr) = set_peer_connection(PacketDropPolicy::Range(0..1)).await?; @@ -1201,13 +1201,13 @@ mod test { let peer_b = tokio::spawn(async move { let peer_a_conn = peer_b.connect(peer_a_pub, peer_a_addr).await; let _ = tokio::time::timeout(Duration::from_secs(500), peer_a_conn).await??; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { let peer_b_conn = peer_a.connect(peer_b_pub, peer_b_addr).await; let _ = tokio::time::timeout(Duration::from_secs(500), peer_b_conn).await??; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, peer_b)?; @@ -1217,7 +1217,7 @@ mod test { } #[tokio::test] - async fn simulate_nat_traversal_drop_first_packets_of_peerb() -> Result<(), DynError> { + async fn simulate_nat_traversal_drop_first_packets_of_peerb() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); let (peer_a_pub, mut peer_a, peer_a_addr) = set_peer_connection(Default::default()).await?; let (peer_b_pub, mut peer_b, peer_b_addr) = @@ -1227,14 +1227,14 @@ mod test { let peer_a_conn = peer_b.connect(peer_a_pub, peer_a_addr).await; let mut conn = tokio::time::timeout(Duration::from_secs(500), peer_a_conn).await??; let _ = tokio::time::timeout(Duration::from_secs(3), conn.recv()).await; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { let peer_b_conn = peer_a.connect(peer_b_pub, peer_b_addr).await; let mut conn = tokio::time::timeout(Duration::from_secs(500), peer_b_conn).await??; let _ = tokio::time::timeout(Duration::from_secs(3), conn.recv()).await; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, peer_b)?; @@ -1244,7 +1244,7 @@ mod test { } #[tokio::test] - async fn simulate_nat_traversal_drop_packet_ranges_of_peerb_killed() -> Result<(), DynError> { + async fn simulate_nat_traversal_drop_packet_ranges_of_peerb_killed() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); let (peer_a_pub, mut peer_a, peer_a_addr) = set_peer_connection(Default::default()).await?; let (peer_b_pub, mut peer_b, peer_b_addr) = @@ -1255,7 +1255,7 @@ mod test { let mut conn = tokio::time::timeout(Duration::from_secs(500), peer_a_conn).await??; let _ = tokio::time::timeout(Duration::from_secs(3), conn.recv()).await; conn.send("some data").await.unwrap(); - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { @@ -1269,7 +1269,7 @@ mod test { tokio::time::sleep(Duration::from_secs(10)).await; // conn should be broken as the remote peer cannot receive message and ping conn.recv().await.unwrap_err(); - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, peer_b)?; @@ -1280,7 +1280,7 @@ mod test { } #[tokio::test] - async fn simulate_nat_traversal_drop_packet_ranges_of_peerb() -> Result<(), DynError> { + async fn simulate_nat_traversal_drop_packet_ranges_of_peerb() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); let (peer_a_pub, mut peer_a, peer_a_addr) = set_peer_connection(Default::default()).await?; let (peer_b_pub, mut peer_b, peer_b_addr) = @@ -1296,7 +1296,7 @@ mod test { // although we drop some packets, we still alive conn.send("some data").await.unwrap(); - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { @@ -1313,7 +1313,7 @@ mod test { // conn should not be broken let b = conn.recv().await.unwrap(); assert_eq!(&b[8..], b"some data"); - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, peer_b)?; @@ -1324,7 +1324,7 @@ mod test { } #[tokio::test] - async fn simulate_gateway_connection() -> Result<(), DynError> { + async fn simulate_gateway_connection() -> anyhow::Result<()> { let (_peer_a_pub, mut peer_a, _peer_a_addr) = set_peer_connection(Default::default()).await?; let (gw_pub, mut gw_conn, gw_addr) = set_gateway_connection(Default::default()).await?; @@ -1333,14 +1333,14 @@ mod test { let gw_conn = gw_conn.recv(); let _ = tokio::time::timeout(Duration::from_secs(10), gw_conn) .await? - .ok_or("no connection")?; - Ok::<_, DynError>(()) + .ok_or(anyhow::anyhow!("no connection"))?; + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { let peer_b_conn = peer_a.connect(gw_pub, gw_addr).await; let _ = tokio::time::timeout(Duration::from_secs(500), peer_b_conn).await??; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, gw)?; @@ -1350,7 +1350,7 @@ mod test { } #[tokio::test] - async fn simulate_gateway_connection_drop_first_packets_of_gateway() -> Result<(), DynError> { + async fn simulate_gateway_connection_drop_first_packets_of_gateway() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); let (_peer_a_pub, mut peer_a, _peer_a_addr) = set_peer_connection(Default::default()).await?; @@ -1361,14 +1361,14 @@ mod test { let gw_conn = gw_conn.recv(); let _ = tokio::time::timeout(Duration::from_secs(10), gw_conn) .await? - .ok_or("no connection")?; - Ok::<_, DynError>(()) + .ok_or(anyhow::anyhow!("no connection"))?; + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { let peer_b_conn = peer_a.connect(gw_pub, gw_addr).await; let _ = tokio::time::timeout(Duration::from_secs(500), peer_b_conn).await??; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, gw)?; @@ -1378,7 +1378,7 @@ mod test { } #[tokio::test] - async fn simulate_gateway_connection_drop_first_packets_for_all() -> Result<(), DynError> { + async fn simulate_gateway_connection_drop_first_packets_for_all() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); let (_peer_a_pub, mut peer_a, _peer_a_addr) = set_peer_connection(PacketDropPolicy::Range(0..1)).await?; @@ -1389,14 +1389,14 @@ mod test { let gw_conn = gw_conn.recv(); let _ = tokio::time::timeout(Duration::from_secs(10), gw_conn) .await? - .ok_or("no connection")?; - Ok::<_, DynError>(()) + .ok_or(anyhow::anyhow!("no connection"))?; + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { let peer_b_conn = peer_a.connect(gw_pub, gw_addr).await; let _ = tokio::time::timeout(Duration::from_secs(10), peer_b_conn).await??; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, gw)?; @@ -1406,7 +1406,7 @@ mod test { } #[tokio::test] - async fn simulate_gateway_connection_drop_first_packets_of_peer() -> Result<(), DynError> { + async fn simulate_gateway_connection_drop_first_packets_of_peer() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); let (_peer_a_pub, mut peer_a, _peer_a_addr) = set_peer_connection(PacketDropPolicy::Range(0..1)).await?; @@ -1416,14 +1416,14 @@ mod test { let gw_conn = gw_conn.recv(); let _ = tokio::time::timeout(Duration::from_secs(10), gw_conn) .await? - .ok_or("no connection")?; - Ok::<_, DynError>(()) + .ok_or(anyhow::anyhow!("no connection"))?; + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { let peer_b_conn = peer_a.connect(gw_pub, gw_addr).await; let _ = tokio::time::timeout(Duration::from_secs(10), peer_b_conn).await??; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, gw)?; @@ -1433,7 +1433,7 @@ mod test { } #[tokio::test] - async fn simulate_send_short_message() -> Result<(), DynError> { + async fn simulate_send_short_message() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); #[derive(Clone, Copy)] struct TestData(&'static str, usize); @@ -1466,7 +1466,7 @@ mod test { /// This one is the maximum size (1324 currently) of a short message from user side /// by using public send API can be directly sent #[tokio::test] - async fn simulate_send_max_short_message() -> Result<(), DynError> { + async fn simulate_send_max_short_message() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::ERROR)); let (peer_a_pub, mut peer_a, peer_a_addr) = set_peer_connection(Default::default()).await?; let (peer_b_pub, mut peer_b, peer_b_addr) = set_peer_connection(Default::default()).await?; @@ -1479,7 +1479,7 @@ mod test { .await .unwrap(); conn.send(data).await?; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { @@ -1487,7 +1487,7 @@ mod test { let mut conn = tokio::time::timeout(Duration::from_secs(500), peer_b_conn).await??; let msg = conn.recv().await?; assert!(msg.len() <= MAX_DATA_SIZE); - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, peer_b)?; @@ -1518,7 +1518,7 @@ mod test { .await .unwrap(); conn.outbound_short_message(data).await?; - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let peer_a = tokio::spawn(async move { @@ -1527,19 +1527,19 @@ mod test { tokio::time::timeout(Duration::from_secs(500), peer_b_conn).await??; let msg = conn.recv().await?; assert!(msg.len() <= MAX_DATA_SIZE); - Ok::<_, DynError>(()) + Ok::<_, anyhow::Error>(()) }); let (a, b) = tokio::try_join!(peer_a, peer_b)?; a?; b?; - Result::<(), DynError>::Ok(()) + Result::<(), anyhow::Error>::Ok(()) }) .unwrap(); } #[tokio::test] - async fn simulate_send_streamed_message() -> Result<(), DynError> { + async fn simulate_send_streamed_message() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE)); #[derive(Clone, Copy)] struct TestData(&'static str); @@ -1573,7 +1573,7 @@ mod test { // #[ignore] #[tokio::test(flavor = "multi_thread", worker_threads = 5)] // #[tokio::test] - async fn simulate_packet_dropping() -> Result<(), DynError> { + async fn simulate_packet_dropping() -> anyhow::Result<()> { // crate::config::set_logger(Some(tracing::level_filters::LevelFilter::INFO)); #[derive(Clone, Copy)] struct TestData(&'static str); diff --git a/crates/core/src/wasm_runtime/contract_store.rs b/crates/core/src/wasm_runtime/contract_store.rs index 3e7418308..75324ecad 100644 --- a/crates/core/src/wasm_runtime/contract_store.rs +++ b/crates/core/src/wasm_runtime/contract_store.rs @@ -141,7 +141,9 @@ impl ContractStore { // save on disc let version = APIVersion::from(contract); - let output: Vec = code.to_bytes_versioned(version)?; + let output: Vec = code + .to_bytes_versioned(version) + .map_err(|e| anyhow::anyhow!(e))?; let mut file = File::create(key_path)?; file.write_all(output.as_slice())?; diff --git a/crates/core/src/wasm_runtime/delegate_store.rs b/crates/core/src/wasm_runtime/delegate_store.rs index 03649c4b9..29b777acd 100644 --- a/crates/core/src/wasm_runtime/delegate_store.rs +++ b/crates/core/src/wasm_runtime/delegate_store.rs @@ -120,7 +120,10 @@ impl DelegateStore { // save on disc let version = APIVersion::from(delegate.clone()); - let output: Vec = delegate.code().to_bytes_versioned(version)?; + let output: Vec = delegate + .code() + .to_bytes_versioned(version) + .map_err(|e| anyhow::anyhow!(e))?; let mut file = File::create(delegate_path)?; file.write_all(output.as_slice())?; diff --git a/crates/core/src/wasm_runtime/error.rs b/crates/core/src/wasm_runtime/error.rs index 933c12bdb..e8c8c0efd 100644 --- a/crates/core/src/wasm_runtime/error.rs +++ b/crates/core/src/wasm_runtime/error.rs @@ -2,8 +2,6 @@ use std::fmt::Display; use freenet_stdlib::prelude::{ContractKey, DelegateKey}; -use crate::DynError; - use super::{delegate, runtime, secrets_store}; pub type RuntimeResult = std::result::Result; @@ -39,7 +37,7 @@ macro_rules! impl_err { }; } -impl_err!(Box); +impl_err!(anyhow::Error); impl_err!(freenet_stdlib::memory::buf::Error); impl_err!(std::io::Error); impl_err!(secrets_store::SecretStoreError); @@ -55,7 +53,7 @@ impl_err!(wasmer::RuntimeError); #[derive(thiserror::Error, Debug)] pub(crate) enum RuntimeInnerError { #[error(transparent)] - Any(#[from] DynError), + Any(#[from] anyhow::Error), #[error(transparent)] BufferError(#[from] freenet_stdlib::memory::buf::Error), diff --git a/crates/core/src/wasm_runtime/state_store.rs b/crates/core/src/wasm_runtime/state_store.rs index 958fb1ac6..2159acbdb 100644 --- a/crates/core/src/wasm_runtime/state_store.rs +++ b/crates/core/src/wasm_runtime/state_store.rs @@ -2,12 +2,10 @@ use core::future::Future; use freenet_stdlib::prelude::*; use stretto::AsyncCache; -use crate::DynError; - #[derive(thiserror::Error, Debug)] pub enum StateStoreError { #[error(transparent)] - Any(#[from] DynError), + Any(#[from] anyhow::Error), #[error("missing contract: {0}")] MissingContract(ContractKey), } @@ -15,9 +13,11 @@ pub enum StateStoreError { impl From for crate::wasm_runtime::ContractError { fn from(value: StateStoreError) -> Self { match value { - StateStoreError::Any(err) => crate::wasm_runtime::ContractError::from(err), + StateStoreError::Any(err) => { + crate::wasm_runtime::ContractError::from(anyhow::format_err!(err)) + } err @ StateStoreError::MissingContract(_) => { - crate::wasm_runtime::ContractError::from(Into::::into(format!("{err}"))) + crate::wasm_runtime::ContractError::from(anyhow::format_err!(err)) } } } @@ -54,7 +54,7 @@ pub struct StateStore { impl StateStore where S: StateStorage + Send + 'static, - ::Error: Into, + ::Error: Into, { const AVG_STATE_SIZE: usize = 1_000; @@ -64,7 +64,7 @@ where let counters = max_size as usize / Self::AVG_STATE_SIZE * 10; Ok(Self { state_mem_cache: AsyncCache::new(counters, max_size as i64, tokio::spawn) - .map_err(|err| StateStoreError::Any(Box::new(err)))?, + .map_err(|err| StateStoreError::Any(anyhow::anyhow!(err)))?, // params_mem_cache: AsyncCache::new(counters, max_size as i64) // .map_err(|err| StateStoreError::Any(Box::new(err)))?, store, diff --git a/crates/core/src/wasm_runtime/store.rs b/crates/core/src/wasm_runtime/store.rs index 028d8e2ea..16dcff898 100644 --- a/crates/core/src/wasm_runtime/store.rs +++ b/crates/core/src/wasm_runtime/store.rs @@ -8,8 +8,6 @@ use std::path::{Path, PathBuf}; use std::time::Duration; use std::{fs::File, io::Read}; -use crate::DynError; - const INTERNAL_KEY: usize = 32; const TOMBSTONE_MARKER: usize = 1; @@ -154,7 +152,7 @@ pub(super) trait StoreFsManagement: Sized { fn watch_changes( mut container: Self::MemContainer, key_file_path: &Path, - ) -> Result<(), DynError> { + ) -> anyhow::Result<()> { let key_path = key_file_path.to_path_buf(); let key_path_cp = key_path.clone(); let mut watcher = notify::recommended_watcher( diff --git a/crates/fdev/src/build.rs b/crates/fdev/src/build.rs index 814331bfd..130dcf232 100644 --- a/crates/fdev/src/build.rs +++ b/crates/fdev/src/build.rs @@ -35,7 +35,7 @@ pub const TSC_BUILD_COMMAND: &str = "tsc"; #[cfg(not(windows))] pub const WEBPACK_BUILD_COMMAND: &str = "webpack"; -pub fn build_package(cli_config: BuildToolConfig, cwd: &Path) -> Result<(), anyhow::Error> { +pub fn build_package(cli_config: BuildToolConfig, cwd: &Path) -> anyhow::Result<()> { match cli_config.package_type { PackageType::Contract => contract::package_contract(cli_config, cwd), PackageType::Delegate => delegate::package_delegate(cli_config, cwd), @@ -81,10 +81,7 @@ fn test_get_compile_options() { ); } -fn compile_rust_wasm_lib( - cli_config: &BuildToolConfig, - work_dir: &Path, -) -> Result<(), anyhow::Error> { +fn compile_rust_wasm_lib(cli_config: &BuildToolConfig, work_dir: &Path) -> anyhow::Result<()> { const RUST_TARGET_ARGS: &[&str] = &["build", "--lib", "--target"]; use std::io::IsTerminal; let comp_opts = compile_options(cli_config).collect::>(); @@ -120,10 +117,7 @@ fn compile_rust_wasm_lib( Ok(()) } -fn get_out_lib( - work_dir: &Path, - cli_config: &BuildToolConfig, -) -> Result<(String, PathBuf), anyhow::Error> { +fn get_out_lib(work_dir: &Path, cli_config: &BuildToolConfig) -> anyhow::Result<(String, PathBuf)> { const ERR: &str = "Cargo.toml definition incorrect"; let target = WASM_TARGET; @@ -172,10 +166,7 @@ mod contract { use super::*; - pub(super) fn package_contract( - cli_config: BuildToolConfig, - cwd: &Path, - ) -> Result<(), anyhow::Error> { + pub(super) fn package_contract(cli_config: BuildToolConfig, cwd: &Path) -> anyhow::Result<()> { let mut config = get_config(cwd)?; compile_contract(&config, &cli_config, cwd)?; match config.contract.c_type.unwrap_or(ContractType::Standard) { @@ -258,7 +249,7 @@ mod contract { config: &ContractBuildConfig, embedded_deps: EmbeddedDeps, cwd: &Path, - ) -> Result<(), anyhow::Error> { + ) -> anyhow::Result<()> { let Some(web_config) = &config.webapp else { println!("No webapp config found."); return Ok(()); @@ -338,7 +329,7 @@ mod contract { None => {} } - let build_state = |sources: &Sources| -> Result<(), anyhow::Error> { + let build_state = |sources: &Sources| -> anyhow::Result<()> { let mut found_entry = false; if let Some(sources) = &sources.files { for src in sources { @@ -413,10 +404,7 @@ mod contract { build_state(sources) } - fn build_generic_state( - config: &mut ContractBuildConfig, - cwd: &Path, - ) -> Result<(), anyhow::Error> { + fn build_generic_state(config: &mut ContractBuildConfig, cwd: &Path) -> anyhow::Result<()> { const REQ_ONE_FILE_ERR: &str = "Requires exactly one source file specified for the state."; let sources = config.state.as_mut().and_then(|s| s.files.as_mut()); @@ -443,11 +431,7 @@ mod contract { Ok(()) } - fn output_artifact( - output: &Option, - packed: &[u8], - cwd: &Path, - ) -> Result<(), anyhow::Error> { + fn output_artifact(output: &Option, packed: &[u8], cwd: &Path) -> anyhow::Result<()> { if let Some(path) = output { File::create(path)?.write_all(packed)?; } else { @@ -459,7 +443,7 @@ mod contract { Ok(()) } - fn get_config(cwd: &Path) -> Result { + fn get_config(cwd: &Path) -> anyhow::Result { let config_file = cwd.join("freenet.toml"); if config_file.exists() { let mut f_content = vec![]; @@ -474,7 +458,7 @@ mod contract { config: &ContractBuildConfig, cli_config: &BuildToolConfig, cwd: &Path, - ) -> Result<(), anyhow::Error> { + ) -> anyhow::Result<()> { let work_dir = match config.contract.c_type.unwrap_or(ContractType::Standard) { ContractType::WebApp => cwd.join("container"), ContractType::Standard => cwd.to_path_buf(), @@ -507,7 +491,7 @@ mod contract { fn get_versioned_contract( contract_code_path: &Path, cli_config: &BuildToolConfig, - ) -> Result, anyhow::Error> { + ) -> anyhow::Result> { let code: ContractCode = ContractCode::load_raw(contract_code_path)?; tracing::info!("compiled contract code hash: {}", code.hash_str()); let output = code @@ -529,7 +513,7 @@ mod contract { fn include_deps( contracts: &toml::value::Table, - ) -> Result, anyhow::Error> { + ) -> anyhow::Result> { let mut deps = HashMap::with_capacity(contracts.len()); for (alias, definition) in contracts { let mut dep = DependencyDefinition::default(); @@ -574,7 +558,7 @@ mod contract { cwd: &Path, deps: HashMap, DependencyDefinition>, cli_config: &BuildToolConfig, - ) -> Result { + ) -> anyhow::Result { let cwd = fs::canonicalize(cwd)?; let mut deps_json = HashMap::new(); let mut to_embed = EmbeddedDeps::default(); @@ -607,7 +591,7 @@ mod contract { mod test { use super::*; - fn setup_webapp_contract() -> Result<(ContractBuildConfig, PathBuf), anyhow::Error> { + fn setup_webapp_contract() -> anyhow::Result<(ContractBuildConfig, PathBuf)> { const CRATE_DIR: &str = env!("CARGO_MANIFEST_DIR"); let cwd = PathBuf::from(CRATE_DIR).join("../../tests/test-app-1"); Ok(( @@ -641,7 +625,7 @@ mod contract { // FIXME: This test fails in GitHub CI. The failure is due to issues compiling the test-app-1 application with webpack. #[test] #[ignore] - fn package_webapp_state() -> Result<(), anyhow::Error> { + fn package_webapp_state() -> anyhow::Result<()> { let (config, cwd) = setup_webapp_contract()?; // env::set_current_dir(&cwd)?; build_web_state(&config, EmbeddedDeps::default(), &cwd)?; @@ -664,7 +648,7 @@ mod contract { } #[test] - fn compile_webapp_contract() -> Result<(), anyhow::Error> { + fn compile_webapp_contract() -> anyhow::Result<()> { // let (config, cwd) = setup_webapp_contract()?; compile_contract(&config, &BuildToolConfig::default(), &cwd)?; @@ -672,7 +656,7 @@ mod contract { } #[test] - fn package_generic_state() -> Result<(), anyhow::Error> { + fn package_generic_state() -> anyhow::Result<()> { const CRATE_DIR: &str = env!("CARGO_MANIFEST_DIR"); let cwd = PathBuf::from(CRATE_DIR).join("../../tests/test-app-1/deps"); let mut config = ContractBuildConfig { @@ -700,7 +684,7 @@ mod contract { } #[test] - fn deps_parsing() -> Result<(), anyhow::Error> { + fn deps_parsing() -> anyhow::Result<()> { let deps = toml::toml! { posts = { path = "deps" } }; @@ -710,7 +694,7 @@ mod contract { } #[test] - fn embedded_deps() -> Result<(), anyhow::Error> { + fn embedded_deps() -> anyhow::Result<()> { const CRATE_DIR: &str = env!("CARGO_MANIFEST_DIR"); let cwd = PathBuf::from(CRATE_DIR).join("../../tests/test-app-1"); let deps = toml::toml! { @@ -728,10 +712,7 @@ mod delegate { use super::*; - pub(super) fn package_delegate( - cli_config: BuildToolConfig, - cwd: &Path, - ) -> Result<(), anyhow::Error> { + pub(super) fn package_delegate(cli_config: BuildToolConfig, cwd: &Path) -> anyhow::Result<()> { compile_rust_wasm_lib(&cli_config, cwd)?; let (package_name, output_lib) = get_out_lib(cwd, &cli_config)?; if !output_lib.exists() { @@ -750,7 +731,7 @@ mod delegate { fn get_versioned_contract( contract_code_path: &Path, cli_config: &BuildToolConfig, - ) -> Result, anyhow::Error> { + ) -> anyhow::Result> { let code: DelegateCode = DelegateCode::load_raw(contract_code_path)?; tracing::info!("compiled contract code hash: {}", code.hash_str()); let output = code diff --git a/crates/fdev/src/commands.rs b/crates/fdev/src/commands.rs index ec12c01a8..e906aa3fd 100644 --- a/crates/fdev/src/commands.rs +++ b/crates/fdev/src/commands.rs @@ -43,7 +43,7 @@ pub(crate) struct PutDelegate { pub(crate) cipher: String, } -pub async fn put(config: PutConfig, other: BaseConfig) -> Result<(), anyhow::Error> { +pub async fn put(config: PutConfig, other: BaseConfig) -> anyhow::Result<()> { if config.release { anyhow::bail!("Cannot publish contracts in the network yet"); } @@ -65,7 +65,7 @@ async fn put_contract( contract_config: &PutContract, other: BaseConfig, params: Parameters<'static>, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { let contract = ContractContainer::try_from((config.code.as_path(), params))?; let state = if let Some(ref state_path) = contract_config.state { let mut buf = vec![]; @@ -96,7 +96,7 @@ async fn put_delegate( delegate_config: &PutDelegate, other: BaseConfig, params: Parameters<'static>, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { let delegate = DelegateContainer::try_from((config.code.as_path(), params))?; let (cipher, nonce) = if delegate_config.cipher.is_empty() && delegate_config.nonce.is_empty() { @@ -130,7 +130,7 @@ For additional hardening is recommended to use a different cipher and nonce to e execute_command(request, other, config.address, config.port).await } -pub async fn update(config: UpdateConfig, other: BaseConfig) -> Result<(), anyhow::Error> { +pub async fn update(config: UpdateConfig, other: BaseConfig) -> anyhow::Result<()> { if config.release { anyhow::bail!("Cannot publish contracts in the network yet"); } @@ -150,6 +150,6 @@ async fn execute_command( other: BaseConfig, address: IpAddr, port: u16, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { v1::execute_command(request, other, address, port).await } diff --git a/crates/fdev/src/commands/v1.rs b/crates/fdev/src/commands/v1.rs index 62a31be25..73eec9c05 100644 --- a/crates/fdev/src/commands/v1.rs +++ b/crates/fdev/src/commands/v1.rs @@ -5,7 +5,7 @@ pub(super) async fn execute_command( other: BaseConfig, address: IpAddr, port: u16, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { let mode = other.mode; let target = match mode { diff --git a/crates/fdev/src/inspect.rs b/crates/fdev/src/inspect.rs index e52c64074..cf7c30875 100644 --- a/crates/fdev/src/inspect.rs +++ b/crates/fdev/src/inspect.rs @@ -23,7 +23,7 @@ enum FileType { #[derive(clap::Parser, Clone)] struct CodeInspection {} -pub fn inspect(config: InspectConfig) -> Result<(), anyhow::Error> { +pub fn inspect(config: InspectConfig) -> anyhow::Result<()> { if !config.file.exists() { return Err(Error::CommandFailed("couldn't find file").into()); } diff --git a/crates/fdev/src/main.rs b/crates/fdev/src/main.rs index 7ff6b42ef..0220c68ec 100644 --- a/crates/fdev/src/main.rs +++ b/crates/fdev/src/main.rs @@ -33,7 +33,7 @@ enum Error { CommandFailed(&'static str), } -fn main() -> Result<(), anyhow::Error> { +fn main() -> anyhow::Result<()> { let tokio_rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; diff --git a/crates/fdev/src/network_metrics_server.rs b/crates/fdev/src/network_metrics_server.rs index 0dc30d5aa..c2846d78b 100644 --- a/crates/fdev/src/network_metrics_server.rs +++ b/crates/fdev/src/network_metrics_server.rs @@ -264,7 +264,7 @@ impl std::fmt::Display for PeerIdHumanReadable { } impl ServerState { - fn save_record(&self, change: ChangesWrapper) -> Result<(), anyhow::Error> { + fn save_record(&self, change: ChangesWrapper) -> anyhow::Result<()> { match change { ChangesWrapper::PeerChange(PeerChange::AddedConnection(added)) => { let from_peer_id: PeerId = bincode::deserialize(added.from().bytes())?; diff --git a/crates/fdev/src/new_package.rs b/crates/fdev/src/new_package.rs index 1cb01b6a5..55f002e4a 100644 --- a/crates/fdev/src/new_package.rs +++ b/crates/fdev/src/new_package.rs @@ -13,7 +13,7 @@ use crate::{ Error, }; -pub fn create_new_package(config: NewPackageConfig) -> Result<(), anyhow::Error> { +pub fn create_new_package(config: NewPackageConfig) -> anyhow::Result<()> { let cwd = env::current_dir()?; match config.kind { ContractKind::WebApp => create_view_package(&cwd)?, @@ -22,7 +22,7 @@ pub fn create_new_package(config: NewPackageConfig) -> Result<(), anyhow::Error> Ok(()) } -fn create_view_package(cwd: &Path) -> Result<(), anyhow::Error> { +fn create_view_package(cwd: &Path) -> anyhow::Result<()> { create_rust_crate(cwd, ContractKind::WebApp)?; create_web_init_files(cwd)?; let freenet_file_config = ContractBuildConfig { @@ -50,7 +50,7 @@ fn create_view_package(cwd: &Path) -> Result<(), anyhow::Error> { Ok(()) } -fn create_regular_contract(cwd: &Path) -> Result<(), anyhow::Error> { +fn create_regular_contract(cwd: &Path) -> anyhow::Result<()> { create_rust_crate(cwd, ContractKind::Contract)?; let freenet_file_config = ContractBuildConfig { contract: Contract { @@ -68,7 +68,7 @@ fn create_regular_contract(cwd: &Path) -> Result<(), anyhow::Error> { Ok(()) } -fn create_rust_crate(cwd: &Path, kind: ContractKind) -> Result<(), anyhow::Error> { +fn create_rust_crate(cwd: &Path, kind: ContractKind) -> anyhow::Result<()> { let (dest_path, cmd) = match kind { ContractKind::WebApp => (cwd.join("container"), &["new"]), ContractKind::Contract => (cwd.to_owned(), &["init"]), @@ -140,7 +140,7 @@ const TSC: &str = "tsc.cmd"; #[cfg(unix)] const TSC: &str = "tsc"; -fn create_web_init_files(cwd: &Path) -> Result<(), anyhow::Error> { +fn create_web_init_files(cwd: &Path) -> anyhow::Result<()> { let child = Command::new(NPM) .args(["init", "--force"]) .stdout(Stdio::piped()) diff --git a/crates/fdev/src/testing/network.rs b/crates/fdev/src/testing/network.rs index 789297218..78a3baa35 100644 --- a/crates/fdev/src/testing/network.rs +++ b/crates/fdev/src/testing/network.rs @@ -373,7 +373,7 @@ async fn handle_socket(socket: WebSocket, supervisor: Arc) -> anyhow async fn handle_outgoing_messages( supervisor: &Arc, sender: &mut SplitSink, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { let mut event_rx = supervisor.event_rx.lock().await; while let Some((event, peer_id)) = event_rx.recv().await { tracing::info!("Received event {} for peer {}", event, peer_id); @@ -395,7 +395,7 @@ async fn handle_outgoing_messages( async fn handle_incoming_messages( supervisor: &Arc, receiver: &mut SplitStream, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { while let Some(result) = receiver.next().await { // Handle the received message or log the error. match result { @@ -406,10 +406,7 @@ async fn handle_incoming_messages( Ok(()) } -async fn process_message( - message: Message, - supervisor: &Arc, -) -> Result<(), anyhow::Error> { +async fn process_message(message: Message, supervisor: &Arc) -> anyhow::Result<()> { match message { Message::Binary(bytes) => { let peer_msg: PeerMessage = bincode::deserialize(&bytes) @@ -430,7 +427,7 @@ async fn process_message( async fn handle_peer_message( peer_msg: PeerMessage, supervisor: &Arc, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { match peer_msg { PeerMessage::Event(event) => { // TODO: Implement actual event handling logic here. diff --git a/crates/fdev/src/util.rs b/crates/fdev/src/util.rs index dd0fe78a7..9520ee60d 100644 --- a/crates/fdev/src/util.rs +++ b/crates/fdev/src/util.rs @@ -8,10 +8,7 @@ use serde::de::DeserializeOwned; use crate::wasm_runtime::DeserializationFmt; -pub fn deserialize( - deser_format: Option, - data: &R, -) -> Result +pub fn deserialize(deser_format: Option, data: &R) -> anyhow::Result where T: DeserializeOwned, R: AsRef<[u8]> + ?Sized, @@ -25,11 +22,11 @@ where } } -pub(crate) fn pipe_std_streams(mut child: Child) -> Result<(), anyhow::Error> { +pub(crate) fn pipe_std_streams(mut child: Child) -> anyhow::Result<()> { let c_stdout = child.stdout.take().expect("Failed to open command stdout"); let c_stderr = child.stderr.take().expect("Failed to open command stderr"); - let write_child_stderr = move || -> Result<(), anyhow::Error> { + let write_child_stderr = move || -> anyhow::Result<()> { let mut stderr = io::stderr(); for b in c_stderr.bytes() { let b = b?; @@ -38,7 +35,7 @@ pub(crate) fn pipe_std_streams(mut child: Child) -> Result<(), anyhow::Error> { Ok(()) }; - let write_child_stdout = move || -> Result<(), anyhow::Error> { + let write_child_stdout = move || -> anyhow::Result<()> { let mut stdout = io::stdout(); for b in c_stdout.bytes() { let b = b?; diff --git a/crates/fdev/src/wasm_runtime.rs b/crates/fdev/src/wasm_runtime.rs index 0bb09a962..8843b45d5 100644 --- a/crates/fdev/src/wasm_runtime.rs +++ b/crates/fdev/src/wasm_runtime.rs @@ -13,7 +13,7 @@ mod user_events; const DEFAULT_MAX_CONTRACT_SIZE: i64 = 50 * 1024 * 1024; -pub async fn run_local_executor(config: ExecutorConfig) -> Result<(), anyhow::Error> { +pub async fn run_local_executor(config: ExecutorConfig) -> anyhow::Result<()> { if config.disable_tui_mode { anyhow::bail!("TUI mode not yet implemented"); } diff --git a/crates/fdev/src/wasm_runtime/commands.rs b/crates/fdev/src/wasm_runtime/commands.rs index 9b70b30dc..3747a15d0 100644 --- a/crates/fdev/src/wasm_runtime/commands.rs +++ b/crates/fdev/src/wasm_runtime/commands.rs @@ -8,7 +8,7 @@ pub(super) async fn wasm_runtime( _config: ExecutorConfig, mut command_receiver: CommandReceiver, mut app: AppState, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { loop { let req = command_receiver.recv().await; let dc = execute_command( @@ -23,10 +23,7 @@ pub(super) async fn wasm_runtime( Ok(()) } -async fn execute_command( - req: ClientRequest<'static>, - app: &mut AppState, -) -> Result { +async fn execute_command(req: ClientRequest<'static>, app: &mut AppState) -> anyhow::Result { let node = &mut *app.local_node.write().await; match req { ClientRequest::ContractOp(_) => { diff --git a/crates/fdev/src/wasm_runtime/state.rs b/crates/fdev/src/wasm_runtime/state.rs index 7c46b1e9e..8c3ec1c75 100644 --- a/crates/fdev/src/wasm_runtime/state.rs +++ b/crates/fdev/src/wasm_runtime/state.rs @@ -16,7 +16,7 @@ pub(super) struct AppState { } impl AppState { - pub async fn new(config: &ExecutorConfig) -> Result { + pub async fn new(config: &ExecutorConfig) -> anyhow::Result { AppState::new_v1(config).await } diff --git a/crates/fdev/src/wasm_runtime/state/v1.rs b/crates/fdev/src/wasm_runtime/state/v1.rs index d4cb51173..d164cf484 100644 --- a/crates/fdev/src/wasm_runtime/state/v1.rs +++ b/crates/fdev/src/wasm_runtime/state/v1.rs @@ -1,7 +1,7 @@ use super::*; impl AppState { - pub async fn new_v1(config: &ExecutorConfig) -> Result { + pub async fn new_v1(config: &ExecutorConfig) -> anyhow::Result { let target: SocketAddr = (config.address, config.port).into(); let (stream, _) = tokio_tungstenite::connect_async(&format!( "ws://{}/v1/contract/command?encodingProtocol=native", diff --git a/crates/fdev/src/wasm_runtime/user_events.rs b/crates/fdev/src/wasm_runtime/user_events.rs index a09b2f98d..68c63b3e9 100644 --- a/crates/fdev/src/wasm_runtime/user_events.rs +++ b/crates/fdev/src/wasm_runtime/user_events.rs @@ -36,7 +36,7 @@ pub(super) async fn user_fn_handler( config: ExecutorConfig, command_sender: CommandSender, app_state: AppState, -) -> Result<(), anyhow::Error> { +) -> anyhow::Result<()> { let mut input = StdInput::new(config, app_state)?; tracing::debug!("running... send a command or write \"help\" for help"); loop { @@ -63,7 +63,7 @@ struct StdInput { } impl StdInput { - fn new(config: ExecutorConfig, app_state: AppState) -> Result { + fn new(config: ExecutorConfig, app_state: AppState) -> anyhow::Result { let paths = config.paths.clone().build(None)?; let params = config .params @@ -91,7 +91,7 @@ impl StdInput { }) } - fn read_input(&mut self) -> Result + fn read_input(&mut self) -> anyhow::Result where T: DeserializeOwned, { diff --git a/modules/identity-management/Cargo.lock b/modules/identity-management/Cargo.lock index 03bc3c443..fab703d1d 100644 --- a/modules/identity-management/Cargo.lock +++ b/modules/identity-management/Cargo.lock @@ -26,6 +26,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anyhow" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" + [[package]] name = "arrayref" version = "0.3.7" @@ -555,6 +561,7 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" name = "identity-management" version = "0.0.1" dependencies = [ + "anyhow", "ecdsa", "freenet-stdlib", "p384", diff --git a/modules/identity-management/Cargo.toml b/modules/identity-management/Cargo.toml index bf56be44b..788a151e4 100644 --- a/modules/identity-management/Cargo.toml +++ b/modules/identity-management/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [workspace] [dependencies] +anyhow = "1" p384 = { version = "0.13", default-features = false, features = ["serde", "pem", "pkcs8", "arithmetic"] } freenet-stdlib = { path = "../../stdlib/rust" } # freenet-stdlib = { version = "0.0.7" } diff --git a/modules/identity-management/src/bin/tool.rs b/modules/identity-management/src/bin/tool.rs index 6e5b35d3a..2df673052 100644 --- a/modules/identity-management/src/bin/tool.rs +++ b/modules/identity-management/src/bin/tool.rs @@ -1,6 +1,6 @@ use std::{ path::PathBuf, - fs::{self, File}, + fs, }; use freenet_stdlib::prelude::Parameters; @@ -16,14 +16,13 @@ Options: -c --code Compiles the contract and saves the code hash "#; -type DynError = Box; struct Args { path: PathBuf, key: Option, } impl Args { - fn parse_args() -> Result { + fn parse_args() -> anyhow::Result { let mut pargs = pico_args::Arguments::from_env(); if pargs.contains(["-h", "--help"]) { println!("{HELP}"); @@ -37,13 +36,13 @@ impl Args { if !path.exists() { fs::create_dir_all(&path)?; } else if !path.is_dir() { - return Err("path must be a directory".into()); + anyhow::bail!("path must be a directory") } Ok(Args { path, key }) } } -fn main() -> Result<(), DynError> { +fn main() -> anyhow::Result<()> { let args = Args::parse_args()?; let secret_key = match args.key {