From 065c0d1b0dd76cee7247254a16a699d42fe59f74 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 12:06:24 +0200 Subject: [PATCH 01/52] add HermesReactor --- hermes/bin/src/event_queue/event.rs | 2 +- hermes/bin/src/lib.rs | 2 ++ hermes/bin/src/reactor.rs | 42 +++++++++++++++++++++++++++++ hermes/bin/src/wasm/module.rs | 2 +- 4 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 hermes/bin/src/reactor.rs diff --git a/hermes/bin/src/event_queue/event.rs b/hermes/bin/src/event_queue/event.rs index 18dcb6758..554391781 100644 --- a/hermes/bin/src/event_queue/event.rs +++ b/hermes/bin/src/event_queue/event.rs @@ -3,7 +3,7 @@ use crate::wasm::module::ModuleInstance; /// A trait for defining the behavior of a Hermes event. -pub trait HermesEventPayload { +pub trait HermesEventPayload: Send { /// Returns the name of the event associated with the payload. fn event_name(&self) -> &str; diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index 802f8a952..379e10035 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -2,6 +2,8 @@ //! This file exists, so that doc tests can be used inside binary crates. mod event_queue; +#[allow(missing_docs, clippy::missing_docs_in_private_items, dead_code)] +mod reactor; mod runtime; mod state; mod wasm; diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs new file mode 100644 index 000000000..d956bd1ea --- /dev/null +++ b/hermes/bin/src/reactor.rs @@ -0,0 +1,42 @@ +use std::{ + sync::mpsc::{channel, Receiver, Sender}, + thread, +}; + +use crate::{event_queue::event::HermesEventPayload, wasm::module::Module}; + +pub(crate) struct HermesReactor { + wasm_module: Module, + + event_sender: Sender>, + event_receiver: Receiver>, +} + +impl HermesReactor { + fn event_execution_loop( + mut wasm_module: Module, event_receiver: Receiver>, + ) -> anyhow::Result<()> { + for event in event_receiver { + wasm_module.execute_event(event.as_ref())?; + } + Ok(()) + } + + pub(crate) fn new(app_name: String, module_bytes: &[u8]) -> anyhow::Result { + let wasm_module = Module::new(app_name, module_bytes)?; + let (event_sender, event_receiver) = channel(); + + Ok(Self { + wasm_module, + event_sender, + event_receiver, + }) + } + + pub(crate) fn run(self) -> anyhow::Result<()> { + let events_thread = thread::spawn(|| { + Self::event_execution_loop(self.wasm_module, self.event_receiver).unwrap(); + }); + Ok(()) + } +} diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index f354694bc..c104b4ec4 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -94,7 +94,7 @@ impl Module { /// # Errors /// - `BadModuleError` #[allow(dead_code)] - pub(crate) fn execute_event(&mut self, event: &impl HermesEventPayload) -> anyhow::Result<()> { + pub(crate) fn execute_event(&mut self, event: &dyn HermesEventPayload) -> anyhow::Result<()> { self.context.use_for(event.event_name().to_string()); let state = HermesState::new(&self.context); From 198ab21f06095e7ac475de6a95df798aa02931f7 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 12:08:31 +0200 Subject: [PATCH 02/52] rename mod --- hermes/bin/src/lib.rs | 2 +- hermes/bin/src/main.rs | 2 +- .../src/{runtime => runtime_extensions}/extensions/bindings.rs | 0 .../bin/src/{runtime => runtime_extensions}/extensions/mod.rs | 2 +- .../bin/src/{runtime => runtime_extensions}/extensions/state.rs | 0 .../{runtime => runtime_extensions}/host/hermes/binary/mod.rs | 2 +- .../{runtime => runtime_extensions}/host/hermes/cardano/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/hermes/cbor/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/hermes/cron/mod.rs | 2 +- .../{runtime => runtime_extensions}/host/hermes/crypto/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/hermes/hash/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/hermes/init/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/hermes/json/mod.rs | 2 +- .../{runtime => runtime_extensions}/host/hermes/kv_store/mod.rs | 2 +- .../host/hermes/localtime/mod.rs | 2 +- .../{runtime => runtime_extensions}/host/hermes/logging/mod.rs | 2 +- .../bin/src/{runtime => runtime_extensions}/host/hermes/mod.rs | 2 +- hermes/bin/src/{runtime => runtime_extensions}/host/mod.rs | 0 .../src/{runtime => runtime_extensions}/host/wasi/cli/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/wasi/clocks/mod.rs | 2 +- .../host/wasi/clocks/monotonic.rs | 2 +- .../{runtime => runtime_extensions}/host/wasi/clocks/wall.rs | 2 +- .../{runtime => runtime_extensions}/host/wasi/filesystem/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/wasi/http/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/wasi/io/error.rs | 2 +- .../bin/src/{runtime => runtime_extensions}/host/wasi/io/mod.rs | 2 +- .../src/{runtime => runtime_extensions}/host/wasi/io/streams.rs | 2 +- hermes/bin/src/{runtime => runtime_extensions}/host/wasi/mod.rs | 2 +- .../host/wasi/random/insecure.rs | 2 +- .../host/wasi/random/insecure_seed.rs | 2 +- .../src/{runtime => runtime_extensions}/host/wasi/random/mod.rs | 2 +- .../{runtime => runtime_extensions}/host/wasi/random/secure.rs | 2 +- hermes/bin/src/{runtime => runtime_extensions}/mod.rs | 0 hermes/bin/src/state.rs | 2 +- hermes/bin/src/wasm/module.rs | 2 +- 35 files changed, 31 insertions(+), 31 deletions(-) rename hermes/bin/src/{runtime => runtime_extensions}/extensions/bindings.rs (100%) rename hermes/bin/src/{runtime => runtime_extensions}/extensions/mod.rs (97%) rename hermes/bin/src/{runtime => runtime_extensions}/extensions/state.rs (100%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/binary/mod.rs (89%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/cardano/mod.rs (99%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/cbor/mod.rs (89%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/cron/mod.rs (99%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/crypto/mod.rs (98%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/hash/mod.rs (96%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/init/mod.rs (69%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/json/mod.rs (89%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/kv_store/mod.rs (98%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/localtime/mod.rs (98%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/logging/mod.rs (98%) rename hermes/bin/src/{runtime => runtime_extensions}/host/hermes/mod.rs (95%) rename hermes/bin/src/{runtime => runtime_extensions}/host/mod.rs (100%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/cli/mod.rs (97%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/clocks/mod.rs (84%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/clocks/monotonic.rs (95%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/clocks/wall.rs (97%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/filesystem/mod.rs (99%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/http/mod.rs (99%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/io/error.rs (96%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/io/mod.rs (85%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/io/streams.rs (99%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/mod.rs (92%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/random/insecure.rs (96%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/random/insecure_seed.rs (97%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/random/mod.rs (89%) rename hermes/bin/src/{runtime => runtime_extensions}/host/wasi/random/secure.rs (97%) rename hermes/bin/src/{runtime => runtime_extensions}/mod.rs (100%) diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index 379e10035..512867736 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -4,6 +4,6 @@ mod event_queue; #[allow(missing_docs, clippy::missing_docs_in_private_items, dead_code)] mod reactor; -mod runtime; +mod runtime_extensions; mod state; mod wasm; diff --git a/hermes/bin/src/main.rs b/hermes/bin/src/main.rs index 117bdf2fe..69b7bc9a8 100644 --- a/hermes/bin/src/main.rs +++ b/hermes/bin/src/main.rs @@ -1,7 +1,7 @@ //! The Hermes Node. mod event_queue; -mod runtime; +mod runtime_extensions; mod state; mod wasm; diff --git a/hermes/bin/src/runtime/extensions/bindings.rs b/hermes/bin/src/runtime_extensions/extensions/bindings.rs similarity index 100% rename from hermes/bin/src/runtime/extensions/bindings.rs rename to hermes/bin/src/runtime_extensions/extensions/bindings.rs diff --git a/hermes/bin/src/runtime/extensions/mod.rs b/hermes/bin/src/runtime_extensions/extensions/mod.rs similarity index 97% rename from hermes/bin/src/runtime/extensions/mod.rs rename to hermes/bin/src/runtime_extensions/extensions/mod.rs index 52aff0da5..6525cf619 100644 --- a/hermes/bin/src/runtime/extensions/mod.rs +++ b/hermes/bin/src/runtime_extensions/extensions/mod.rs @@ -20,7 +20,7 @@ pub(crate) mod state; /// Example of how to call the autogenerated entry points #[allow(dead_code)] fn example() -> anyhow::Result<()> { - use crate::runtime::extensions::state::{Context, Stateful}; + use crate::runtime_extensions::extensions::state::{Context, Stateful}; // Configure an `Engine` and compile the `Component` that is being run for // the application. diff --git a/hermes/bin/src/runtime/extensions/state.rs b/hermes/bin/src/runtime_extensions/extensions/state.rs similarity index 100% rename from hermes/bin/src/runtime/extensions/state.rs rename to hermes/bin/src/runtime_extensions/extensions/state.rs diff --git a/hermes/bin/src/runtime/host/hermes/binary/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/binary/mod.rs similarity index 89% rename from hermes/bin/src/runtime/host/hermes/binary/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/binary/mod.rs index 763e74690..98d1889ed 100644 --- a/hermes/bin/src/runtime/host/hermes/binary/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/binary/mod.rs @@ -1,7 +1,7 @@ //! Host - CBOR implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::hermes::binary::api::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/hermes/cardano/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/cardano/mod.rs similarity index 99% rename from hermes/bin/src/runtime/host/hermes/cardano/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/cardano/mod.rs index 8ab3dda37..9b4a344dd 100644 --- a/hermes/bin/src/runtime/host/hermes/cardano/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/cardano/mod.rs @@ -1,7 +1,7 @@ //! Host - Cardano Blockchain implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::hermes::cardano::api::{ CardanoBlock, CardanoBlockchainId, CardanoTxn, FetchError, Host, Slot, TxnError, UnsubscribeOptions, diff --git a/hermes/bin/src/runtime/host/hermes/cbor/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/cbor/mod.rs similarity index 89% rename from hermes/bin/src/runtime/host/hermes/cbor/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/cbor/mod.rs index 685fded80..b65b2a036 100644 --- a/hermes/bin/src/runtime/host/hermes/cbor/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/cbor/mod.rs @@ -1,7 +1,7 @@ //! Host - CBOR implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::hermes::cbor::api::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/cron/mod.rs similarity index 99% rename from hermes/bin/src/runtime/host/hermes/cron/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/cron/mod.rs index 463e2a9e1..85c500173 100644 --- a/hermes/bin/src/runtime/host/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/cron/mod.rs @@ -1,7 +1,7 @@ //! Host - Cron implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::{ hermes::cron::api::{CronEventTag, CronSched, CronTagged, CronTime, Host}, wasi::clocks::monotonic_clock::Instant, diff --git a/hermes/bin/src/runtime/host/hermes/crypto/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/crypto/mod.rs similarity index 98% rename from hermes/bin/src/runtime/host/hermes/crypto/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/crypto/mod.rs index 2b06252de..cf1c220f2 100644 --- a/hermes/bin/src/runtime/host/hermes/crypto/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/crypto/mod.rs @@ -1,7 +1,7 @@ //! Host - Crypto implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::hermes::{ binary::api::Bstr, crypto::api::{ diff --git a/hermes/bin/src/runtime/host/hermes/hash/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/hash/mod.rs similarity index 96% rename from hermes/bin/src/runtime/host/hermes/hash/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/hash/mod.rs index 9f1a642a2..c3ccedf66 100644 --- a/hermes/bin/src/runtime/host/hermes/hash/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/hash/mod.rs @@ -1,7 +1,7 @@ //! Host - Hash implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::hermes::{ binary::api::Bstr, hash::api::{Errno, Host}, diff --git a/hermes/bin/src/runtime/host/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/init/mod.rs similarity index 69% rename from hermes/bin/src/runtime/host/hermes/init/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/init/mod.rs index b796452e0..245d1e68e 100644 --- a/hermes/bin/src/runtime/host/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/init/mod.rs @@ -1,6 +1,6 @@ //! Host - Init implementations -use crate::runtime::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::extensions::state::{Context, Stateful}; /// State pub(crate) struct State {} diff --git a/hermes/bin/src/runtime/host/hermes/json/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/json/mod.rs similarity index 89% rename from hermes/bin/src/runtime/host/hermes/json/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/json/mod.rs index 9b360f379..df23a9589 100644 --- a/hermes/bin/src/runtime/host/hermes/json/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/json/mod.rs @@ -1,7 +1,7 @@ //! Host - JSON implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::hermes::json::api::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/hermes/kv_store/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/kv_store/mod.rs similarity index 98% rename from hermes/bin/src/runtime/host/hermes/kv_store/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/kv_store/mod.rs index 36d79c21b..e4d3a672a 100644 --- a/hermes/bin/src/runtime/host/hermes/kv_store/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/kv_store/mod.rs @@ -1,7 +1,7 @@ //! Host - KV-Store implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::hermes::kv_store::api::{Host, KvValues}, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/hermes/localtime/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/localtime/mod.rs similarity index 98% rename from hermes/bin/src/runtime/host/hermes/localtime/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/localtime/mod.rs index 8ee18ae29..9db5d2bab 100644 --- a/hermes/bin/src/runtime/host/hermes/localtime/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/localtime/mod.rs @@ -1,7 +1,7 @@ //! Host - Localtime implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::{ hermes::localtime::api::{Errno, Host, Localtime, Timezone}, wasi::clocks::wall_clock::Datetime, diff --git a/hermes/bin/src/runtime/host/hermes/logging/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/logging/mod.rs similarity index 98% rename from hermes/bin/src/runtime/host/hermes/logging/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/logging/mod.rs index d872929c4..ba172f398 100644 --- a/hermes/bin/src/runtime/host/hermes/logging/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/logging/mod.rs @@ -1,7 +1,7 @@ //! Host - Logging implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::hermes::{ json::api::Json, logging::api::{Host, Level}, diff --git a/hermes/bin/src/runtime/host/hermes/mod.rs b/hermes/bin/src/runtime_extensions/host/hermes/mod.rs similarity index 95% rename from hermes/bin/src/runtime/host/hermes/mod.rs rename to hermes/bin/src/runtime_extensions/host/hermes/mod.rs index ffe732a92..216ebd92d 100644 --- a/hermes/bin/src/runtime/host/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/hermes/mod.rs @@ -1,6 +1,6 @@ //! Runtime modules - extensions - HERMES custom extensions -use crate::runtime::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::extensions::state::{Context, Stateful}; pub(crate) mod binary; pub(crate) mod cardano; diff --git a/hermes/bin/src/runtime/host/mod.rs b/hermes/bin/src/runtime_extensions/host/mod.rs similarity index 100% rename from hermes/bin/src/runtime/host/mod.rs rename to hermes/bin/src/runtime_extensions/host/mod.rs diff --git a/hermes/bin/src/runtime/host/wasi/cli/mod.rs b/hermes/bin/src/runtime_extensions/host/wasi/cli/mod.rs similarity index 97% rename from hermes/bin/src/runtime/host/wasi/cli/mod.rs rename to hermes/bin/src/runtime_extensions/host/wasi/cli/mod.rs index d1237cda5..ea947763c 100644 --- a/hermes/bin/src/runtime/host/wasi/cli/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/cli/mod.rs @@ -1,7 +1,7 @@ //! Host - WASI - CLI implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::{ cli, io::streams::{InputStream, OutputStream}, diff --git a/hermes/bin/src/runtime/host/wasi/clocks/mod.rs b/hermes/bin/src/runtime_extensions/host/wasi/clocks/mod.rs similarity index 84% rename from hermes/bin/src/runtime/host/wasi/clocks/mod.rs rename to hermes/bin/src/runtime_extensions/host/wasi/clocks/mod.rs index 674319ca3..95b016c21 100644 --- a/hermes/bin/src/runtime/host/wasi/clocks/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/clocks/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI - Clock implementations -use crate::runtime::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::extensions::state::{Context, Stateful}; mod monotonic; mod wall; diff --git a/hermes/bin/src/runtime/host/wasi/clocks/monotonic.rs b/hermes/bin/src/runtime_extensions/host/wasi/clocks/monotonic.rs similarity index 95% rename from hermes/bin/src/runtime/host/wasi/clocks/monotonic.rs rename to hermes/bin/src/runtime_extensions/host/wasi/clocks/monotonic.rs index e3e77bbe7..5bb7bf8b2 100644 --- a/hermes/bin/src/runtime/host/wasi/clocks/monotonic.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/clocks/monotonic.rs @@ -1,7 +1,7 @@ //! Host - WASI - monotonic clock implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/wasi/clocks/wall.rs b/hermes/bin/src/runtime_extensions/host/wasi/clocks/wall.rs similarity index 97% rename from hermes/bin/src/runtime/host/wasi/clocks/wall.rs rename to hermes/bin/src/runtime_extensions/host/wasi/clocks/wall.rs index 2a25685d7..86d555fdb 100644 --- a/hermes/bin/src/runtime/host/wasi/clocks/wall.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/clocks/wall.rs @@ -1,7 +1,7 @@ //! Host - WASI - Wall Clock implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::clocks::wall_clock::{Datetime, Host}, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/wasi/filesystem/mod.rs b/hermes/bin/src/runtime_extensions/host/wasi/filesystem/mod.rs similarity index 99% rename from hermes/bin/src/runtime/host/wasi/filesystem/mod.rs rename to hermes/bin/src/runtime_extensions/host/wasi/filesystem/mod.rs index 60462a1f0..2b9fd1d55 100644 --- a/hermes/bin/src/runtime/host/wasi/filesystem/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/filesystem/mod.rs @@ -1,7 +1,7 @@ //! Host - WASI - Filesystem implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::{ filesystem::{ self, diff --git a/hermes/bin/src/runtime/host/wasi/http/mod.rs b/hermes/bin/src/runtime_extensions/host/wasi/http/mod.rs similarity index 99% rename from hermes/bin/src/runtime/host/wasi/http/mod.rs rename to hermes/bin/src/runtime_extensions/host/wasi/http/mod.rs index edc03203f..8dd54c4ad 100644 --- a/hermes/bin/src/runtime/host/wasi/http/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/http/mod.rs @@ -1,7 +1,7 @@ //! Host - WASI - HTTP implementations use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::{ http::{ self, diff --git a/hermes/bin/src/runtime/host/wasi/io/error.rs b/hermes/bin/src/runtime_extensions/host/wasi/io/error.rs similarity index 96% rename from hermes/bin/src/runtime/host/wasi/io/error.rs rename to hermes/bin/src/runtime_extensions/host/wasi/io/error.rs index 2b0aa8828..16cc423ca 100644 --- a/hermes/bin/src/runtime/host/wasi/io/error.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/io/error.rs @@ -1,7 +1,7 @@ //! WASI IO Error use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::io::error::{Error, Host, HostError}, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/wasi/io/mod.rs b/hermes/bin/src/runtime_extensions/host/wasi/io/mod.rs similarity index 85% rename from hermes/bin/src/runtime/host/wasi/io/mod.rs rename to hermes/bin/src/runtime_extensions/host/wasi/io/mod.rs index 6994734de..274d331ed 100644 --- a/hermes/bin/src/runtime/host/wasi/io/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/io/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI IO Implementation -use crate::runtime::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::extensions::state::{Context, Stateful}; pub(crate) mod error; pub(crate) mod streams; diff --git a/hermes/bin/src/runtime/host/wasi/io/streams.rs b/hermes/bin/src/runtime_extensions/host/wasi/io/streams.rs similarity index 99% rename from hermes/bin/src/runtime/host/wasi/io/streams.rs rename to hermes/bin/src/runtime_extensions/host/wasi/io/streams.rs index c96645894..d979ae58a 100644 --- a/hermes/bin/src/runtime/host/wasi/io/streams.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/io/streams.rs @@ -1,7 +1,7 @@ //! WASI IO Streams use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::io::streams::{ Host, HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, }, diff --git a/hermes/bin/src/runtime/host/wasi/mod.rs b/hermes/bin/src/runtime_extensions/host/wasi/mod.rs similarity index 92% rename from hermes/bin/src/runtime/host/wasi/mod.rs rename to hermes/bin/src/runtime_extensions/host/wasi/mod.rs index f8b5f0a08..31359e2b2 100644 --- a/hermes/bin/src/runtime/host/wasi/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/mod.rs @@ -1,6 +1,6 @@ //! Runtime modules - extensions - WASI standard extensions -use crate::runtime::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::extensions::state::{Context, Stateful}; pub(crate) mod cli; pub(crate) mod clocks; diff --git a/hermes/bin/src/runtime/host/wasi/random/insecure.rs b/hermes/bin/src/runtime_extensions/host/wasi/random/insecure.rs similarity index 96% rename from hermes/bin/src/runtime/host/wasi/random/insecure.rs rename to hermes/bin/src/runtime_extensions/host/wasi/random/insecure.rs index 6fe934459..d56103615 100644 --- a/hermes/bin/src/runtime/host/wasi/random/insecure.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/random/insecure.rs @@ -1,7 +1,7 @@ //! Insecure RNG use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::random::insecure::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/wasi/random/insecure_seed.rs b/hermes/bin/src/runtime_extensions/host/wasi/random/insecure_seed.rs similarity index 97% rename from hermes/bin/src/runtime/host/wasi/random/insecure_seed.rs rename to hermes/bin/src/runtime_extensions/host/wasi/random/insecure_seed.rs index 7f414d6b0..6495a9d67 100644 --- a/hermes/bin/src/runtime/host/wasi/random/insecure_seed.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/random/insecure_seed.rs @@ -1,7 +1,7 @@ //! Insecure RNG use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::random::insecure_seed::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/host/wasi/random/mod.rs b/hermes/bin/src/runtime_extensions/host/wasi/random/mod.rs similarity index 89% rename from hermes/bin/src/runtime/host/wasi/random/mod.rs rename to hermes/bin/src/runtime_extensions/host/wasi/random/mod.rs index 416a6e6b6..bf9d950f7 100644 --- a/hermes/bin/src/runtime/host/wasi/random/mod.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/random/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI - Random implementations -use crate::runtime::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::extensions::state::{Context, Stateful}; pub(crate) mod insecure; pub(crate) mod insecure_seed; diff --git a/hermes/bin/src/runtime/host/wasi/random/secure.rs b/hermes/bin/src/runtime_extensions/host/wasi/random/secure.rs similarity index 97% rename from hermes/bin/src/runtime/host/wasi/random/secure.rs rename to hermes/bin/src/runtime_extensions/host/wasi/random/secure.rs index 878ff8dd2..11a199490 100644 --- a/hermes/bin/src/runtime/host/wasi/random/secure.rs +++ b/hermes/bin/src/runtime_extensions/host/wasi/random/secure.rs @@ -1,7 +1,7 @@ //! Random RNG use crate::{ - runtime::extensions::{ + runtime_extensions::extensions::{ bindings::wasi::random::random::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime/mod.rs b/hermes/bin/src/runtime_extensions/mod.rs similarity index 100% rename from hermes/bin/src/runtime/mod.rs rename to hermes/bin/src/runtime_extensions/mod.rs diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/state.rs index e5b1d9401..765682206 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/state.rs @@ -1,6 +1,6 @@ //! Hermes state implementation. -use crate::runtime::{ +use crate::runtime_extensions::{ extensions::state::{Context, Stateful}, host::{hermes, wasi}, }; diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index c104b4ec4..ba135dff3 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -11,7 +11,7 @@ use wasmtime::{ use crate::{ event_queue::event::HermesEventPayload, - runtime::extensions::{ + runtime_extensions::extensions::{ bindings, state::{Context, Stateful}, }, From 326685840580b5430f08b317837fbd3220ad8550 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 12:18:35 +0200 Subject: [PATCH 03/52] refactor --- hermes/bin/src/reactor.rs | 2 +- .../{extensions => }/bindings.rs | 0 .../src/runtime_extensions/extensions/mod.rs | 107 ----------------- .../{host => }/hermes/binary/mod.rs | 2 +- .../{host => }/hermes/cardano/mod.rs | 2 +- .../{host => }/hermes/cbor/mod.rs | 2 +- .../{host => }/hermes/cron/mod.rs | 2 +- .../{host => }/hermes/crypto/mod.rs | 2 +- .../{host => }/hermes/hash/mod.rs | 2 +- .../{host => }/hermes/init/mod.rs | 2 +- .../{host => }/hermes/json/mod.rs | 2 +- .../{host => }/hermes/kv_store/mod.rs | 2 +- .../{host => }/hermes/localtime/mod.rs | 2 +- .../{host => }/hermes/logging/mod.rs | 2 +- .../{host => }/hermes/mod.rs | 4 +- hermes/bin/src/runtime_extensions/host/mod.rs | 4 - hermes/bin/src/runtime_extensions/mod.rs | 111 +++++++++++++++++- .../{extensions => }/state.rs | 0 .../{host => }/wasi/cli/mod.rs | 2 +- .../{host => }/wasi/clocks/mod.rs | 2 +- .../{host => }/wasi/clocks/monotonic.rs | 2 +- .../{host => }/wasi/clocks/wall.rs | 2 +- .../{host => }/wasi/filesystem/mod.rs | 2 +- .../{host => }/wasi/http/mod.rs | 2 +- .../{host => }/wasi/io/error.rs | 2 +- .../{host => }/wasi/io/mod.rs | 2 +- .../{host => }/wasi/io/streams.rs | 2 +- .../runtime_extensions/{host => }/wasi/mod.rs | 4 +- .../{host => }/wasi/random/insecure.rs | 2 +- .../{host => }/wasi/random/insecure_seed.rs | 2 +- .../{host => }/wasi/random/mod.rs | 2 +- .../{host => }/wasi/random/secure.rs | 2 +- hermes/bin/src/state.rs | 5 +- hermes/bin/src/wasm/module.rs | 2 +- 34 files changed, 141 insertions(+), 146 deletions(-) rename hermes/bin/src/runtime_extensions/{extensions => }/bindings.rs (100%) delete mode 100644 hermes/bin/src/runtime_extensions/extensions/mod.rs rename hermes/bin/src/runtime_extensions/{host => }/hermes/binary/mod.rs (89%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/cardano/mod.rs (99%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/cbor/mod.rs (89%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/cron/mod.rs (99%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/crypto/mod.rs (98%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/hash/mod.rs (96%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/init/mod.rs (69%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/json/mod.rs (89%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/kv_store/mod.rs (98%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/localtime/mod.rs (98%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/logging/mod.rs (98%) rename hermes/bin/src/runtime_extensions/{host => }/hermes/mod.rs (92%) delete mode 100644 hermes/bin/src/runtime_extensions/host/mod.rs rename hermes/bin/src/runtime_extensions/{extensions => }/state.rs (100%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/cli/mod.rs (97%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/clocks/mod.rs (84%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/clocks/monotonic.rs (95%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/clocks/wall.rs (97%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/filesystem/mod.rs (99%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/http/mod.rs (99%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/io/error.rs (96%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/io/mod.rs (85%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/io/streams.rs (99%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/mod.rs (86%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/random/insecure.rs (96%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/random/insecure_seed.rs (97%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/random/mod.rs (89%) rename hermes/bin/src/runtime_extensions/{host => }/wasi/random/secure.rs (97%) diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index d956bd1ea..00187eb28 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -34,7 +34,7 @@ impl HermesReactor { } pub(crate) fn run(self) -> anyhow::Result<()> { - let events_thread = thread::spawn(|| { + let _events_thread = thread::spawn(|| { Self::event_execution_loop(self.wasm_module, self.event_receiver).unwrap(); }); Ok(()) diff --git a/hermes/bin/src/runtime_extensions/extensions/bindings.rs b/hermes/bin/src/runtime_extensions/bindings.rs similarity index 100% rename from hermes/bin/src/runtime_extensions/extensions/bindings.rs rename to hermes/bin/src/runtime_extensions/bindings.rs diff --git a/hermes/bin/src/runtime_extensions/extensions/mod.rs b/hermes/bin/src/runtime_extensions/extensions/mod.rs deleted file mode 100644 index 6525cf619..000000000 --- a/hermes/bin/src/runtime_extensions/extensions/mod.rs +++ /dev/null @@ -1,107 +0,0 @@ -//! Hermes runtime extensions - -use wasmtime::{ - component::{Component, Linker}, - Config, Engine, Store, -}; - -use self::bindings::{ - exports::hermes::cardano::event_on_block::BlockSrc, - hermes::{ - cardano::api::{CardanoBlock, CardanoBlockchainId, CardanoTxn}, - cron::api::CronTagged, - }, -}; -use crate::state::HermesState; - -pub(crate) mod bindings; -pub(crate) mod state; - -/// Example of how to call the autogenerated entry points -#[allow(dead_code)] -fn example() -> anyhow::Result<()> { - use crate::runtime_extensions::extensions::state::{Context, Stateful}; - - // Configure an `Engine` and compile the `Component` that is being run for - // the application. - let mut config = Config::new(); - config.wasm_component_model(true); - let engine = Engine::new(&config)?; - let component = Component::from_file(&engine, "./your-component.wasm")?; - - // Instantiation of bindings always happens through a `Linker`. - // - // Note that the closure provided here is a projection from `T` in - // `Store` to `&mut U` where `U` implements the `HelloWorldImports` - // trait. In this case the `T`, `MyState`, is stored directly in the - // structure so no projection is necessary here. - let mut linker = Linker::new(&engine); - bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesState| state)?; - - let instance_pre = linker.instantiate_pre(&component)?; - - // As with the core wasm API of Wasmtime instantiation occurs within a - // `Store`. The bindings structure contains an `instantiate` method which - // takes the store, component, and linker. This returns the `bindings` - // structure which is an instance of `HelloWorld` and supports typed access - // to the exports of the component. - let mut store = Store::new( - &engine, - HermesState::new(&Context::new("my-app".to_string())), - ); - - // - let (bindings, _) = bindings::Hermes::instantiate_pre(&mut store, &instance_pre)?; - - // Show how we call the events in our API. - let _result = bindings.hermes_init_event().call_init(&mut store)?; - - // HTTP API to be rewritten, but this is how its called. - // let arg1 = ??; - // let arg2 = ??; - // let result = bindings.interface0.call_handle(&mut store, arg1, arg2)?; - - // Example of calling on_block. - let arg0 = CardanoBlockchainId::Mainnet; - let arg1 = CardanoBlock::new(); - let arg2 = BlockSrc::TIP; - bindings - .hermes_cardano_event_on_block() - .call_on_cardano_block(&mut store, arg0, &arg1, arg2)?; - - // Example of calling on_txn. - let arg0 = CardanoBlockchainId::Mainnet; - let arg1: u64 = 123_456; - let arg2: u32 = 12; - let arg3 = CardanoTxn::new(); - - bindings - .hermes_cardano_event_on_txn() - .call_on_cardano_txn(&mut store, arg0, arg1, arg2, &arg3)?; - - // Example of calling on_rollback. - let arg0 = CardanoBlockchainId::Mainnet; - let arg1: u64 = 123_456; - bindings - .hermes_cardano_event_on_rollback() - .call_on_cardano_rollback(&mut store, arg0, arg1)?; - - // Example of calling on_cron. - let arg0 = CronTagged { - when: "* * * * *".to_string(), - tag: "tag".to_string(), - }; - let arg1 = false; - let _result = bindings - .hermes_cron_event() - .call_on_cron(&mut store, &arg0, arg1)?; - - // Example of calling kv_update - let arg0 = "key"; - let arg1 = bindings::hermes::kv_store::api::KvValues::KvString("value".to_string()); - bindings - .hermes_kv_store_event() - .call_kv_update(&mut store, arg0, &arg1)?; - - Ok(()) -} diff --git a/hermes/bin/src/runtime_extensions/host/hermes/binary/mod.rs b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs similarity index 89% rename from hermes/bin/src/runtime_extensions/host/hermes/binary/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/binary/mod.rs index 98d1889ed..2758ac237 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/binary/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs @@ -1,7 +1,7 @@ //! Host - CBOR implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::hermes::binary::api::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/cardano/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs similarity index 99% rename from hermes/bin/src/runtime_extensions/host/hermes/cardano/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs index 9b4a344dd..d91aad324 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/cardano/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs @@ -1,7 +1,7 @@ //! Host - Cardano Blockchain implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::hermes::cardano::api::{ CardanoBlock, CardanoBlockchainId, CardanoTxn, FetchError, Host, Slot, TxnError, UnsubscribeOptions, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/cbor/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs similarity index 89% rename from hermes/bin/src/runtime_extensions/host/hermes/cbor/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs index b65b2a036..c265338d0 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/cbor/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs @@ -1,7 +1,7 @@ //! Host - CBOR implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::hermes::cbor::api::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs similarity index 99% rename from hermes/bin/src/runtime_extensions/host/hermes/cron/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/cron/mod.rs index 85c500173..436885de4 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs @@ -1,7 +1,7 @@ //! Host - Cron implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::{ hermes::cron::api::{CronEventTag, CronSched, CronTagged, CronTime, Host}, wasi::clocks::monotonic_clock::Instant, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/crypto/mod.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs similarity index 98% rename from hermes/bin/src/runtime_extensions/host/hermes/crypto/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs index cf1c220f2..4d44c5ef5 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/crypto/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs @@ -1,7 +1,7 @@ //! Host - Crypto implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::hermes::{ binary::api::Bstr, crypto::api::{ diff --git a/hermes/bin/src/runtime_extensions/host/hermes/hash/mod.rs b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs similarity index 96% rename from hermes/bin/src/runtime_extensions/host/hermes/hash/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/hash/mod.rs index c3ccedf66..4903a7875 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/hash/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs @@ -1,7 +1,7 @@ //! Host - Hash implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::hermes::{ binary::api::Bstr, hash::api::{Errno, Host}, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs similarity index 69% rename from hermes/bin/src/runtime_extensions/host/hermes/init/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 245d1e68e..c2c837459 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,6 +1,6 @@ //! Host - Init implementations -use crate::runtime_extensions::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::state::{Context, Stateful}; /// State pub(crate) struct State {} diff --git a/hermes/bin/src/runtime_extensions/host/hermes/json/mod.rs b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs similarity index 89% rename from hermes/bin/src/runtime_extensions/host/hermes/json/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/json/mod.rs index df23a9589..835f51262 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/json/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs @@ -1,7 +1,7 @@ //! Host - JSON implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::hermes::json::api::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/kv_store/mod.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs similarity index 98% rename from hermes/bin/src/runtime_extensions/host/hermes/kv_store/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs index e4d3a672a..5cbdbbcc6 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/kv_store/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs @@ -1,7 +1,7 @@ //! Host - KV-Store implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::hermes::kv_store::api::{Host, KvValues}, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/localtime/mod.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs similarity index 98% rename from hermes/bin/src/runtime_extensions/host/hermes/localtime/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs index 9db5d2bab..11be28678 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/localtime/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs @@ -1,7 +1,7 @@ //! Host - Localtime implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::{ hermes::localtime::api::{Errno, Host, Localtime, Timezone}, wasi::clocks::wall_clock::Datetime, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/logging/mod.rs b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs similarity index 98% rename from hermes/bin/src/runtime_extensions/host/hermes/logging/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/logging/mod.rs index ba172f398..dff4d2358 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/logging/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs @@ -1,7 +1,7 @@ //! Host - Logging implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::hermes::{ json::api::Json, logging::api::{Host, Level}, diff --git a/hermes/bin/src/runtime_extensions/host/hermes/mod.rs b/hermes/bin/src/runtime_extensions/hermes/mod.rs similarity index 92% rename from hermes/bin/src/runtime_extensions/host/hermes/mod.rs rename to hermes/bin/src/runtime_extensions/hermes/mod.rs index 216ebd92d..8111063b9 100644 --- a/hermes/bin/src/runtime_extensions/host/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/mod.rs @@ -1,6 +1,6 @@ -//! Runtime modules - extensions - HERMES custom extensions +//! Hermes runtime extensions implmentations - HERMES custom extensions -use crate::runtime_extensions::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::state::{Context, Stateful}; pub(crate) mod binary; pub(crate) mod cardano; diff --git a/hermes/bin/src/runtime_extensions/host/mod.rs b/hermes/bin/src/runtime_extensions/host/mod.rs deleted file mode 100644 index 6e3721d85..000000000 --- a/hermes/bin/src/runtime_extensions/host/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Runtime runtime extensions - Host implementations - -pub(crate) mod hermes; -pub(crate) mod wasi; diff --git a/hermes/bin/src/runtime_extensions/mod.rs b/hermes/bin/src/runtime_extensions/mod.rs index 6591d1e6e..da720dfce 100644 --- a/hermes/bin/src/runtime_extensions/mod.rs +++ b/hermes/bin/src/runtime_extensions/mod.rs @@ -1,4 +1,109 @@ -//! Runtime modules +//! Hermes runtime extensions -pub(crate) mod extensions; -pub(crate) mod host; +use wasmtime::{ + component::{Component, Linker}, + Config, Engine, Store, +}; + +use self::bindings::{ + exports::hermes::cardano::event_on_block::BlockSrc, + hermes::{ + cardano::api::{CardanoBlock, CardanoBlockchainId, CardanoTxn}, + cron::api::CronTagged, + }, +}; +use crate::state::HermesState; + +pub(crate) mod bindings; +pub(crate) mod hermes; +pub(crate) mod state; +pub(crate) mod wasi; + +/// Example of how to call the autogenerated entry points +#[allow(dead_code)] +fn example() -> anyhow::Result<()> { + use crate::runtime_extensions::state::{Context, Stateful}; + + // Configure an `Engine` and compile the `Component` that is being run for + // the application. + let mut config = Config::new(); + config.wasm_component_model(true); + let engine = Engine::new(&config)?; + let component = Component::from_file(&engine, "./your-component.wasm")?; + + // Instantiation of bindings always happens through a `Linker`. + // + // Note that the closure provided here is a projection from `T` in + // `Store` to `&mut U` where `U` implements the `HelloWorldImports` + // trait. In this case the `T`, `MyState`, is stored directly in the + // structure so no projection is necessary here. + let mut linker = Linker::new(&engine); + bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesState| state)?; + + let instance_pre = linker.instantiate_pre(&component)?; + + // As with the core wasm API of Wasmtime instantiation occurs within a + // `Store`. The bindings structure contains an `instantiate` method which + // takes the store, component, and linker. This returns the `bindings` + // structure which is an instance of `HelloWorld` and supports typed access + // to the exports of the component. + let mut store = Store::new( + &engine, + HermesState::new(&Context::new("my-app".to_string())), + ); + + // + let (bindings, _) = bindings::Hermes::instantiate_pre(&mut store, &instance_pre)?; + + // Show how we call the events in our API. + let _result = bindings.hermes_init_event().call_init(&mut store)?; + + // HTTP API to be rewritten, but this is how its called. + // let arg1 = ??; + // let arg2 = ??; + // let result = bindings.interface0.call_handle(&mut store, arg1, arg2)?; + + // Example of calling on_block. + let arg0 = CardanoBlockchainId::Mainnet; + let arg1 = CardanoBlock::new(); + let arg2 = BlockSrc::TIP; + bindings + .hermes_cardano_event_on_block() + .call_on_cardano_block(&mut store, arg0, &arg1, arg2)?; + + // Example of calling on_txn. + let arg0 = CardanoBlockchainId::Mainnet; + let arg1: u64 = 123_456; + let arg2: u32 = 12; + let arg3 = CardanoTxn::new(); + + bindings + .hermes_cardano_event_on_txn() + .call_on_cardano_txn(&mut store, arg0, arg1, arg2, &arg3)?; + + // Example of calling on_rollback. + let arg0 = CardanoBlockchainId::Mainnet; + let arg1: u64 = 123_456; + bindings + .hermes_cardano_event_on_rollback() + .call_on_cardano_rollback(&mut store, arg0, arg1)?; + + // Example of calling on_cron. + let arg0 = CronTagged { + when: "* * * * *".to_string(), + tag: "tag".to_string(), + }; + let arg1 = false; + let _result = bindings + .hermes_cron_event() + .call_on_cron(&mut store, &arg0, arg1)?; + + // Example of calling kv_update + let arg0 = "key"; + let arg1 = bindings::hermes::kv_store::api::KvValues::KvString("value".to_string()); + bindings + .hermes_kv_store_event() + .call_kv_update(&mut store, arg0, &arg1)?; + + Ok(()) +} diff --git a/hermes/bin/src/runtime_extensions/extensions/state.rs b/hermes/bin/src/runtime_extensions/state.rs similarity index 100% rename from hermes/bin/src/runtime_extensions/extensions/state.rs rename to hermes/bin/src/runtime_extensions/state.rs diff --git a/hermes/bin/src/runtime_extensions/host/wasi/cli/mod.rs b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs similarity index 97% rename from hermes/bin/src/runtime_extensions/host/wasi/cli/mod.rs rename to hermes/bin/src/runtime_extensions/wasi/cli/mod.rs index ea947763c..0e136e805 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/cli/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs @@ -1,7 +1,7 @@ //! Host - WASI - CLI implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::{ cli, io::streams::{InputStream, OutputStream}, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/clocks/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs similarity index 84% rename from hermes/bin/src/runtime_extensions/host/wasi/clocks/mod.rs rename to hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs index 95b016c21..f7b982f12 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/clocks/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI - Clock implementations -use crate::runtime_extensions::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::state::{Context, Stateful}; mod monotonic; mod wall; diff --git a/hermes/bin/src/runtime_extensions/host/wasi/clocks/monotonic.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic.rs similarity index 95% rename from hermes/bin/src/runtime_extensions/host/wasi/clocks/monotonic.rs rename to hermes/bin/src/runtime_extensions/wasi/clocks/monotonic.rs index 5bb7bf8b2..a3abcd6cc 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/clocks/monotonic.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic.rs @@ -1,7 +1,7 @@ //! Host - WASI - monotonic clock implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/clocks/wall.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall.rs similarity index 97% rename from hermes/bin/src/runtime_extensions/host/wasi/clocks/wall.rs rename to hermes/bin/src/runtime_extensions/wasi/clocks/wall.rs index 86d555fdb..6c2b4949f 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/clocks/wall.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall.rs @@ -1,7 +1,7 @@ //! Host - WASI - Wall Clock implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::clocks::wall_clock::{Datetime, Host}, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/filesystem/mod.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs similarity index 99% rename from hermes/bin/src/runtime_extensions/host/wasi/filesystem/mod.rs rename to hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs index 2b9fd1d55..fd4771edb 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/filesystem/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs @@ -1,7 +1,7 @@ //! Host - WASI - Filesystem implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::{ filesystem::{ self, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/http/mod.rs b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs similarity index 99% rename from hermes/bin/src/runtime_extensions/host/wasi/http/mod.rs rename to hermes/bin/src/runtime_extensions/wasi/http/mod.rs index 8dd54c4ad..68dedc475 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/http/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs @@ -1,7 +1,7 @@ //! Host - WASI - HTTP implementations use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::{ http::{ self, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/io/error.rs b/hermes/bin/src/runtime_extensions/wasi/io/error.rs similarity index 96% rename from hermes/bin/src/runtime_extensions/host/wasi/io/error.rs rename to hermes/bin/src/runtime_extensions/wasi/io/error.rs index 16cc423ca..3e4f0bea9 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/io/error.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error.rs @@ -1,7 +1,7 @@ //! WASI IO Error use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::io::error::{Error, Host, HostError}, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/io/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs similarity index 85% rename from hermes/bin/src/runtime_extensions/host/wasi/io/mod.rs rename to hermes/bin/src/runtime_extensions/wasi/io/mod.rs index 274d331ed..ba46e0ec6 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/io/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI IO Implementation -use crate::runtime_extensions::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::state::{Context, Stateful}; pub(crate) mod error; pub(crate) mod streams; diff --git a/hermes/bin/src/runtime_extensions/host/wasi/io/streams.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams.rs similarity index 99% rename from hermes/bin/src/runtime_extensions/host/wasi/io/streams.rs rename to hermes/bin/src/runtime_extensions/wasi/io/streams.rs index d979ae58a..26385b746 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/io/streams.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams.rs @@ -1,7 +1,7 @@ //! WASI IO Streams use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::io::streams::{ Host, HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, }, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/mod.rs b/hermes/bin/src/runtime_extensions/wasi/mod.rs similarity index 86% rename from hermes/bin/src/runtime_extensions/host/wasi/mod.rs rename to hermes/bin/src/runtime_extensions/wasi/mod.rs index 31359e2b2..3e7afb002 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/mod.rs @@ -1,6 +1,6 @@ -//! Runtime modules - extensions - WASI standard extensions +//! Hermes runtime extensions implementations - WASI standard extensions -use crate::runtime_extensions::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::state::{Context, Stateful}; pub(crate) mod cli; pub(crate) mod clocks; diff --git a/hermes/bin/src/runtime_extensions/host/wasi/random/insecure.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure.rs similarity index 96% rename from hermes/bin/src/runtime_extensions/host/wasi/random/insecure.rs rename to hermes/bin/src/runtime_extensions/wasi/random/insecure.rs index d56103615..d6573e1cd 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/random/insecure.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure.rs @@ -1,7 +1,7 @@ //! Insecure RNG use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::random::insecure::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/random/insecure_seed.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed.rs similarity index 97% rename from hermes/bin/src/runtime_extensions/host/wasi/random/insecure_seed.rs rename to hermes/bin/src/runtime_extensions/wasi/random/insecure_seed.rs index 6495a9d67..22d7d2987 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/random/insecure_seed.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed.rs @@ -1,7 +1,7 @@ //! Insecure RNG use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::random::insecure_seed::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/runtime_extensions/host/wasi/random/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs similarity index 89% rename from hermes/bin/src/runtime_extensions/host/wasi/random/mod.rs rename to hermes/bin/src/runtime_extensions/wasi/random/mod.rs index bf9d950f7..a1e32999e 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/random/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI - Random implementations -use crate::runtime_extensions::extensions::state::{Context, Stateful}; +use crate::runtime_extensions::state::{Context, Stateful}; pub(crate) mod insecure; pub(crate) mod insecure_seed; diff --git a/hermes/bin/src/runtime_extensions/host/wasi/random/secure.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure.rs similarity index 97% rename from hermes/bin/src/runtime_extensions/host/wasi/random/secure.rs rename to hermes/bin/src/runtime_extensions/wasi/random/secure.rs index 11a199490..9334edbc7 100644 --- a/hermes/bin/src/runtime_extensions/host/wasi/random/secure.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure.rs @@ -1,7 +1,7 @@ //! Random RNG use crate::{ - runtime_extensions::extensions::{ + runtime_extensions::{ bindings::wasi::random::random::Host, state::{Context, Stateful}, }, diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/state.rs index 765682206..131116755 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/state.rs @@ -1,8 +1,9 @@ //! Hermes state implementation. use crate::runtime_extensions::{ - extensions::state::{Context, Stateful}, - host::{hermes, wasi}, + hermes, + state::{Context, Stateful}, + wasi, }; #[allow(dead_code)] diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index ba135dff3..ea5713bee 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -11,7 +11,7 @@ use wasmtime::{ use crate::{ event_queue::event::HermesEventPayload, - runtime_extensions::extensions::{ + runtime_extensions::{ bindings, state::{Context, Stateful}, }, From 5dc58597fdc00dfb33b79dfd044dcad03f1708c2 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 12:42:30 +0200 Subject: [PATCH 04/52] move hermes runtime extensions host impl to the separate module --- .../runtime_extensions/hermes/binary/host.rs | 5 + .../runtime_extensions/hermes/binary/mod.rs | 14 +- .../runtime_extensions/hermes/cardano/host.rs | 165 +++++++++++++++++ .../runtime_extensions/hermes/cardano/mod.rs | 171 +----------------- .../runtime_extensions/hermes/cbor/host.rs | 5 + .../src/runtime_extensions/hermes/cbor/mod.rs | 14 +- .../runtime_extensions/hermes/cron/host.rs | 137 ++++++++++++++ .../src/runtime_extensions/hermes/cron/mod.rs | 143 +-------------- .../runtime_extensions/hermes/crypto/host.rs | 84 +++++++++ .../runtime_extensions/hermes/crypto/mod.rs | 90 +-------- .../runtime_extensions/hermes/hash/host.rs | 32 ++++ .../src/runtime_extensions/hermes/hash/mod.rs | 38 +--- .../src/runtime_extensions/hermes/init/mod.rs | 2 +- .../runtime_extensions/hermes/json/host.rs | 5 + .../src/runtime_extensions/hermes/json/mod.rs | 14 +- .../hermes/kv_store/host.rs | 86 +++++++++ .../runtime_extensions/hermes/kv_store/mod.rs | 92 +--------- .../hermes/localtime/host.rs | 62 +++++++ .../hermes/localtime/mod.rs | 68 +------ .../runtime_extensions/hermes/logging/host.rs | 63 +++++++ .../runtime_extensions/hermes/logging/mod.rs | 69 +------ 21 files changed, 685 insertions(+), 674 deletions(-) create mode 100644 hermes/bin/src/runtime_extensions/hermes/binary/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/cardano/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/cbor/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/cron/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/crypto/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/hash/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/json/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/localtime/host.rs create mode 100644 hermes/bin/src/runtime_extensions/hermes/logging/host.rs diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs new file mode 100644 index 000000000..7eddd020f --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs @@ -0,0 +1,5 @@ +//! Binary host implementation for WASM runtime. + +use crate::{runtime_extensions::bindings::hermes::binary::api::Host, state::HermesState}; + +impl Host for HermesState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs index 2758ac237..69a2afd33 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs @@ -1,12 +1,8 @@ -//! Host - CBOR implementations +//! Binary runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::hermes::binary::api::Host, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -16,5 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs new file mode 100644 index 000000000..1949e263e --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs @@ -0,0 +1,165 @@ +//! Cardano Blockchain host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::hermes::cardano::api::{ + CardanoBlock, CardanoBlockchainId, CardanoTxn, FetchError, Host, Slot, TxnError, + UnsubscribeOptions, + }, + state::HermesState, +}; + +impl Host for HermesState { + /// Subscribe to the Blockchain block data. + /// + /// **Parameters** + /// + /// - `net` : The blockchain network to fetch block from, and subscribe to. + /// - `whence`: Where to start fetching blocks from. + /// + /// **Returns** + /// + /// - `ok(u64)` : The slot we are synching from now. + /// - `error(fetch-error)` : If an error occurred. + /// + /// **Notes** + /// + /// If the blockchain is not yet syncing, it will start, from the requested slot. + /// If the blockchain is not yet syncing, and `whence` == `continue` then the + /// blockchain will + /// not be synced from, the calling module will only be subscribed for block events. + /// + /// If the blockchain is already syncing, the sync will stop and restart, unless + /// `whence` == `continue`. + /// When `whence` == `continue` the blockchain will keep syncing from where it is at, + /// and this module + /// will be subscribed to block updates. + /// + /// `whence` == `stop` will prevent the blockchain syncing, and the caller will be + /// unsubscribed. + fn subscribe_blocks( + &mut self, _net: CardanoBlockchainId, _whence: Slot, + ) -> wasmtime::Result> { + todo!() + } + + /// Unsubscribe from the blockchain events listed. + /// + /// **Parameters** + /// + /// - `events` : The events to unsubscribe from (and optionally stop the blockchain + /// follower). + /// + /// **Notes** + /// + /// This only unsubscribes from the events. + /// The option `stop` MUST be set to actually stop fetching data from the blockchain + /// once started. + /// + /// `stop` can be set without unsubscribing, and this will interrupt the flow of + /// blockchain data. + /// After `stop`, `subscribe-blocks(?, continue)` would cause blockchain sync to + /// continue from + /// the last block received. This would result in the last block being sent as an + /// event twice, + /// once before the `stop` and once after the `continue`. + fn unsubscribe(&mut self, _events: UnsubscribeOptions) -> wasmtime::Result<()> { + todo!() + } + + /// Subscribe to transaction data events, does not alter the blockchain sync in + /// anyway. + /// + /// **Parameters** + /// + /// - `net` : The blockchain network to subscribe to txn events from. + fn subscribe_txn(&mut self, _net: CardanoBlockchainId) -> wasmtime::Result<()> { + todo!() + } + + /// Subscribe to blockchain rollback events, does not alter the blockchain sync in + /// anyway. + /// + /// **Parameters** + /// + /// - `net` : The blockchain network to subscribe to txn events from. + /// + /// **Notes** + /// + /// After a rollback event, the blockchain sync will AUTOMATICALLY start sending block + /// data from the rollback point. No action is required to actually follow the + /// rollback, unless the + /// default behavior is not desired. + fn subscribe_rollback(&mut self, _net: CardanoBlockchainId) -> wasmtime::Result<()> { + todo!() + } + + /// Fetch a block from the requested blockchain at the requested slot. + /// + /// **Parameters** + /// + /// - `net` : The blockchain network to get a block from. + /// - `whence` : Which block to get. + /// + /// **Returns** + /// + /// - `cardano-block` : The block requested. + /// - `fetch-error` : An error if the block can not be fetched. + /// + /// **Notes** + /// + /// Fetching a block does not require the blockchain to be subscribed, or for blocks + /// to be + /// being followed and generating events. + /// It also will not alter the automatic fetching of blocks in any way, and happens in + /// parallel + /// to automated block fetch. + fn fetch_block( + &mut self, _net: CardanoBlockchainId, _whence: Slot, + ) -> wasmtime::Result> { + todo!() + } + + /// Get transactions from a block. + /// + /// This can be used to easily extract all transactions from a complete block. + /// + /// **Parameters** + /// + /// - `block` : The blockchain data to extract transactions from. + /// + /// **Returns** + /// + /// - a list of all transactions in the block, in the order they appear in the block. + /// + /// **Notes** + /// + /// This function exists to support `fetch-block`. + /// Transactions from subscribed block events, should be processed as transaction + /// events. + fn get_txns(&mut self, _block: CardanoBlock) -> wasmtime::Result> { + todo!() + } + + /// Post a transactions to the blockchain. + /// + /// This can be used to post a pre-formed transaction to the required blockchain. + /// + /// **Parameters** + /// + /// - `net` : The blockchain to post the transaction to. + /// - `txn` : The transaction data, ready to submit. + /// + /// **Returns** + /// + /// - An error if the transaction can not be posted. + /// + /// **Notes** + /// + /// This is proposed functionality, and is not yet active. + /// All calls to this function will return `post-txn-not-allowed` error. + fn post_txn( + &mut self, _net: CardanoBlockchainId, _txn: CardanoTxn, + ) -> wasmtime::Result> { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs index d91aad324..543f86be9 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs @@ -1,15 +1,8 @@ -//! Host - Cardano Blockchain implementations +//! Cardano Blockchain runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::hermes::cardano::api::{ - CardanoBlock, CardanoBlockchainId, CardanoTxn, FetchError, Host, Slot, TxnError, - UnsubscribeOptions, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -19,159 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState { - /// Subscribe to the Blockchain block data. - /// - /// **Parameters** - /// - /// - `net` : The blockchain network to fetch block from, and subscribe to. - /// - `whence`: Where to start fetching blocks from. - /// - /// **Returns** - /// - /// - `ok(u64)` : The slot we are synching from now. - /// - `error(fetch-error)` : If an error occurred. - /// - /// **Notes** - /// - /// If the blockchain is not yet syncing, it will start, from the requested slot. - /// If the blockchain is not yet syncing, and `whence` == `continue` then the - /// blockchain will - /// not be synced from, the calling module will only be subscribed for block events. - /// - /// If the blockchain is already syncing, the sync will stop and restart, unless - /// `whence` == `continue`. - /// When `whence` == `continue` the blockchain will keep syncing from where it is at, - /// and this module - /// will be subscribed to block updates. - /// - /// `whence` == `stop` will prevent the blockchain syncing, and the caller will be - /// unsubscribed. - fn subscribe_blocks( - &mut self, _net: CardanoBlockchainId, _whence: Slot, - ) -> wasmtime::Result> { - todo!() - } - - /// Unsubscribe from the blockchain events listed. - /// - /// **Parameters** - /// - /// - `events` : The events to unsubscribe from (and optionally stop the blockchain - /// follower). - /// - /// **Notes** - /// - /// This only unsubscribes from the events. - /// The option `stop` MUST be set to actually stop fetching data from the blockchain - /// once started. - /// - /// `stop` can be set without unsubscribing, and this will interrupt the flow of - /// blockchain data. - /// After `stop`, `subscribe-blocks(?, continue)` would cause blockchain sync to - /// continue from - /// the last block received. This would result in the last block being sent as an - /// event twice, - /// once before the `stop` and once after the `continue`. - fn unsubscribe(&mut self, _events: UnsubscribeOptions) -> wasmtime::Result<()> { - todo!() - } - - /// Subscribe to transaction data events, does not alter the blockchain sync in - /// anyway. - /// - /// **Parameters** - /// - /// - `net` : The blockchain network to subscribe to txn events from. - fn subscribe_txn(&mut self, _net: CardanoBlockchainId) -> wasmtime::Result<()> { - todo!() - } - - /// Subscribe to blockchain rollback events, does not alter the blockchain sync in - /// anyway. - /// - /// **Parameters** - /// - /// - `net` : The blockchain network to subscribe to txn events from. - /// - /// **Notes** - /// - /// After a rollback event, the blockchain sync will AUTOMATICALLY start sending block - /// data from the rollback point. No action is required to actually follow the - /// rollback, unless the - /// default behavior is not desired. - fn subscribe_rollback(&mut self, _net: CardanoBlockchainId) -> wasmtime::Result<()> { - todo!() - } - - /// Fetch a block from the requested blockchain at the requested slot. - /// - /// **Parameters** - /// - /// - `net` : The blockchain network to get a block from. - /// - `whence` : Which block to get. - /// - /// **Returns** - /// - /// - `cardano-block` : The block requested. - /// - `fetch-error` : An error if the block can not be fetched. - /// - /// **Notes** - /// - /// Fetching a block does not require the blockchain to be subscribed, or for blocks - /// to be - /// being followed and generating events. - /// It also will not alter the automatic fetching of blocks in any way, and happens in - /// parallel - /// to automated block fetch. - fn fetch_block( - &mut self, _net: CardanoBlockchainId, _whence: Slot, - ) -> wasmtime::Result> { - todo!() - } - - /// Get transactions from a block. - /// - /// This can be used to easily extract all transactions from a complete block. - /// - /// **Parameters** - /// - /// - `block` : The blockchain data to extract transactions from. - /// - /// **Returns** - /// - /// - a list of all transactions in the block, in the order they appear in the block. - /// - /// **Notes** - /// - /// This function exists to support `fetch-block`. - /// Transactions from subscribed block events, should be processed as transaction - /// events. - fn get_txns(&mut self, _block: CardanoBlock) -> wasmtime::Result> { - todo!() - } - - /// Post a transactions to the blockchain. - /// - /// This can be used to post a pre-formed transaction to the required blockchain. - /// - /// **Parameters** - /// - /// - `net` : The blockchain to post the transaction to. - /// - `txn` : The transaction data, ready to submit. - /// - /// **Returns** - /// - /// - An error if the transaction can not be posted. - /// - /// **Notes** - /// - /// This is proposed functionality, and is not yet active. - /// All calls to this function will return `post-txn-not-allowed` error. - fn post_txn( - &mut self, _net: CardanoBlockchainId, _txn: CardanoTxn, - ) -> wasmtime::Result> { - todo!() - } -} diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs new file mode 100644 index 000000000..ccd135018 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs @@ -0,0 +1,5 @@ +//! CBOR host implementation for WASM runtime. + +use crate::{runtime_extensions::bindings::hermes::cbor::api::Host, state::HermesState}; + +impl Host for HermesState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs index c265338d0..24972f85c 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs @@ -1,12 +1,8 @@ -//! Host - CBOR implementations +//! CBOR runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::hermes::cbor::api::Host, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -16,5 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs new file mode 100644 index 000000000..75260877b --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs @@ -0,0 +1,137 @@ +//! Cron host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::{ + hermes::cron::api::{CronEventTag, CronSched, CronTagged, CronTime, Host}, + wasi::clocks::monotonic_clock::Instant, + }, + state::HermesState, +}; + +impl Host for HermesState { + /// # Schedule Recurrent CRON event + /// + /// Cron events will be delivered to the `on-cron` event handler. + /// + /// ## Parameters + /// + /// - `entry`: The crontab entry to add. + /// - `when`: When the event triggers. Standard crontab format. + /// - `tag`: A tag which will accompany the triggered event. + /// - `retrigger`: + /// - `true`: The event will re-trigger every time the crontab entry matches until + /// cancelled. + /// - `false`: The event will automatically cancel after it is generated once. + /// + /// ## Returns + /// + /// - `true`: Crontab added successfully. (Or the crontab event already exists) + /// - `false`: Crontab failed to be added. + /// + /// ## Note: + /// + /// If the crontab entry already exists, the retrigger flag can be changed by calling + /// this function. This could be useful where a retriggering crontab event is desired + /// to be stopped, but ONLY after it has triggered once more. + fn add(&mut self, _entry: CronTagged, _retrigger: bool) -> wasmtime::Result { + todo!() + } + + /// # Schedule A Single cron event after a fixed delay. + /// + /// Allows for easy timed wait events to be delivered without + /// requiring datetime calculations or formatting cron entries. + /// + /// ## Parameters + /// + /// - `duration`: How many nanoseconds to delay. The delay will be AT LEAST this + /// long. + /// - `tag`: A tag which will accompany the triggered event. + /// + /// ## Returns + /// + /// - `true`: Crontab added successfully. + /// - `false`: Crontab failed to be added. + /// + /// ## Note: + /// + /// This is a convenience function which will automatically calculate the crontab + /// entry needed to trigger the event after the requested `duration`. + /// It is added as a non-retriggering event. + /// Listing the crontabs after this call will list the delay in addition to all other + /// crontab entries. + fn delay(&mut self, _duration: Instant, _tag: CronEventTag) -> wasmtime::Result { + todo!() + } + + /// # List currently active cron schedule. + /// + /// Allows for management of scheduled cron events. + /// + /// ## Parameters + /// + /// - `tag`: Optional, the tag to limit the list to. If `none` then all crons listed. + /// + /// ## Returns + /// + /// - A list of tuples containing the scheduled crontabs and their tags, along with + /// the current retrigger flag. + /// The list is sorted from most crontab that will trigger soonest to latest. + /// Crontabs are only listed once, in the case where a crontab may be scheduled + /// may times before a later one. + /// - `0` - `cron-tagged` - The Tagged crontab event. + /// - `1` - `bool` - The state of the retrigger flag. + fn ls(&mut self, _tag: Option) -> wasmtime::Result> { + todo!() + } + + /// # Remove the requested crontab. + /// + /// Allows for management of scheduled cron events. + /// + /// ## Parameters + /// + /// - `when`: The crontab entry to add. Standard crontab format. + /// - `tag`: A tag which will accompany the triggered event. + /// + /// ## Returns + /// + /// - `true`: The requested crontab was deleted and will not trigger. + /// - `false`: The requested crontab does not exist. + fn rm(&mut self, _entry: CronTagged) -> wasmtime::Result { + todo!() + } + + /// # Make a crontab entry from individual time values. + /// + /// Crates the properly formatted cron entry + /// from numeric cron time components. + /// Convenience function to make building cron strings simpler when they are + /// calculated from data. + /// + /// ## Parameters + /// + /// - `dow` - `DayOfWeek` (0-7, 0 or 7 = Sunday) + /// - `month` - Month of the year (1-12, 1 = January) + /// - `day` - Day in the month (1-31) + /// - `hour` - Hour in the day (0-23) + /// - `minute` - Minute in the hour (0-59) + /// + /// ## Returns + /// + /// - A matching `cron-sched` ready for use in the cron functions above. + /// + /// ## Note: + /// No checking is done to determine if the requested date is valid. + /// If a particular component is out of its allowable range it will be silently + /// clamped within the allowable range of each parameter. + /// Redundant entries will be removed. + /// - For example specifying a `month` as `3` and `2-4` will + /// remove the individual month and only produce the range. + fn mkcron( + &mut self, _dow: CronTime, _month: CronTime, _day: CronTime, _hour: CronTime, + _minute: CronTime, + ) -> wasmtime::Result { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs index 436885de4..d40a42c5e 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs @@ -1,15 +1,8 @@ -//! Host - Cron implementations +//! Cron runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::{ - hermes::cron::api::{CronEventTag, CronSched, CronTagged, CronTime, Host}, - wasi::clocks::monotonic_clock::Instant, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -19,131 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState { - /// # Schedule Recurrent CRON event - /// - /// Cron events will be delivered to the `on-cron` event handler. - /// - /// ## Parameters - /// - /// - `entry`: The crontab entry to add. - /// - `when`: When the event triggers. Standard crontab format. - /// - `tag`: A tag which will accompany the triggered event. - /// - `retrigger`: - /// - `true`: The event will re-trigger every time the crontab entry matches until - /// cancelled. - /// - `false`: The event will automatically cancel after it is generated once. - /// - /// ## Returns - /// - /// - `true`: Crontab added successfully. (Or the crontab event already exists) - /// - `false`: Crontab failed to be added. - /// - /// ## Note: - /// - /// If the crontab entry already exists, the retrigger flag can be changed by calling - /// this function. This could be useful where a retriggering crontab event is desired - /// to be stopped, but ONLY after it has triggered once more. - fn add(&mut self, _entry: CronTagged, _retrigger: bool) -> wasmtime::Result { - todo!() - } - - /// # Schedule A Single cron event after a fixed delay. - /// - /// Allows for easy timed wait events to be delivered without - /// requiring datetime calculations or formatting cron entries. - /// - /// ## Parameters - /// - /// - `duration`: How many nanoseconds to delay. The delay will be AT LEAST this - /// long. - /// - `tag`: A tag which will accompany the triggered event. - /// - /// ## Returns - /// - /// - `true`: Crontab added successfully. - /// - `false`: Crontab failed to be added. - /// - /// ## Note: - /// - /// This is a convenience function which will automatically calculate the crontab - /// entry needed to trigger the event after the requested `duration`. - /// It is added as a non-retriggering event. - /// Listing the crontabs after this call will list the delay in addition to all other - /// crontab entries. - fn delay(&mut self, _duration: Instant, _tag: CronEventTag) -> wasmtime::Result { - todo!() - } - - /// # List currently active cron schedule. - /// - /// Allows for management of scheduled cron events. - /// - /// ## Parameters - /// - /// - `tag`: Optional, the tag to limit the list to. If `none` then all crons listed. - /// - /// ## Returns - /// - /// - A list of tuples containing the scheduled crontabs and their tags, along with - /// the current retrigger flag. - /// The list is sorted from most crontab that will trigger soonest to latest. - /// Crontabs are only listed once, in the case where a crontab may be scheduled - /// may times before a later one. - /// - `0` - `cron-tagged` - The Tagged crontab event. - /// - `1` - `bool` - The state of the retrigger flag. - fn ls(&mut self, _tag: Option) -> wasmtime::Result> { - todo!() - } - - /// # Remove the requested crontab. - /// - /// Allows for management of scheduled cron events. - /// - /// ## Parameters - /// - /// - `when`: The crontab entry to add. Standard crontab format. - /// - `tag`: A tag which will accompany the triggered event. - /// - /// ## Returns - /// - /// - `true`: The requested crontab was deleted and will not trigger. - /// - `false`: The requested crontab does not exist. - fn rm(&mut self, _entry: CronTagged) -> wasmtime::Result { - todo!() - } - - /// # Make a crontab entry from individual time values. - /// - /// Crates the properly formatted cron entry - /// from numeric cron time components. - /// Convenience function to make building cron strings simpler when they are - /// calculated from data. - /// - /// ## Parameters - /// - /// - `dow` - `DayOfWeek` (0-7, 0 or 7 = Sunday) - /// - `month` - Month of the year (1-12, 1 = January) - /// - `day` - Day in the month (1-31) - /// - `hour` - Hour in the day (0-23) - /// - `minute` - Minute in the hour (0-59) - /// - /// ## Returns - /// - /// - A matching `cron-sched` ready for use in the cron functions above. - /// - /// ## Note: - /// No checking is done to determine if the requested date is valid. - /// If a particular component is out of its allowable range it will be silently - /// clamped within the allowable range of each parameter. - /// Redundant entries will be removed. - /// - For example specifying a `month` as `3` and `2-4` will - /// remove the individual month and only produce the range. - fn mkcron( - &mut self, _dow: CronTime, _month: CronTime, _day: CronTime, _hour: CronTime, - _minute: CronTime, - ) -> wasmtime::Result { - todo!() - } -} diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs new file mode 100644 index 000000000..c014e60be --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs @@ -0,0 +1,84 @@ +//! Crypto host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::hermes::{ + binary::api::Bstr, + crypto::api::{ + Ed25519Bip32, Ed25519Bip32PrivateKey, Ed25519Bip32PublicKey, Ed25519Bip32Signature, + Host, HostEd25519Bip32, + }, + }, + state::HermesState, +}; + +impl HostEd25519Bip32 for HermesState { + /// Create a new ED25519-BIP32 Crypto resource + /// + /// **Parameters** + /// + /// - `private_key` : The key to use, if not supplied one is RANDOMLY generated. + fn new( + &mut self, _private_key: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the public key for this private key. + fn public_key( + &mut self, _resource: wasmtime::component::Resource, + ) -> wasmtime::Result { + todo!() + } + + /// Sign data with the Private key, and return it. + /// + /// **Parameters** + /// + /// - `data` : The data to sign. + fn sign_data( + &mut self, _resource: wasmtime::component::Resource, _data: Bstr, + ) -> wasmtime::Result { + todo!() + } + + /// Check a signature on a set of data. + /// + /// **Parameters** + /// + /// - `data` : The data to check. + /// - `sig` : The signature to check. + /// + /// **Returns** + /// + /// - `true` : Signature checked OK. + /// - `false` : Signature check failed. + fn check_sig( + &mut self, _resource: wasmtime::component::Resource, _data: Bstr, + _sig: Ed25519Bip32Signature, + ) -> wasmtime::Result { + todo!() + } + + /// Derive a new private key from the current private key. + /// + /// Note: uses BIP32 HD key derivation. + fn derive( + &mut self, _resource: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Create a new RANDOM private key. + /// + /// Note, this does not need to be used, as the constructor will do this + /// automatically. + fn gen_private_key(&mut self) -> wasmtime::Result { + todo!() + } + + fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { + todo!() + } +} + +impl Host for HermesState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs index 4d44c5ef5..6cbb6a69d 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs @@ -1,18 +1,8 @@ -//! Host - Crypto implementations +//! Crypto runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::hermes::{ - binary::api::Bstr, - crypto::api::{ - Ed25519Bip32, Ed25519Bip32PrivateKey, Ed25519Bip32PublicKey, Ed25519Bip32Signature, - Host, HostEd25519Bip32, - }, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -22,75 +12,3 @@ impl Stateful for State { State {} } } - -impl HostEd25519Bip32 for HermesState { - /// Create a new ED25519-BIP32 Crypto resource - /// - /// **Parameters** - /// - /// - `private_key` : The key to use, if not supplied one is RANDOMLY generated. - fn new( - &mut self, _private_key: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the public key for this private key. - fn public_key( - &mut self, _resource: wasmtime::component::Resource, - ) -> wasmtime::Result { - todo!() - } - - /// Sign data with the Private key, and return it. - /// - /// **Parameters** - /// - /// - `data` : The data to sign. - fn sign_data( - &mut self, _resource: wasmtime::component::Resource, _data: Bstr, - ) -> wasmtime::Result { - todo!() - } - - /// Check a signature on a set of data. - /// - /// **Parameters** - /// - /// - `data` : The data to check. - /// - `sig` : The signature to check. - /// - /// **Returns** - /// - /// - `true` : Signature checked OK. - /// - `false` : Signature check failed. - fn check_sig( - &mut self, _resource: wasmtime::component::Resource, _data: Bstr, - _sig: Ed25519Bip32Signature, - ) -> wasmtime::Result { - todo!() - } - - /// Derive a new private key from the current private key. - /// - /// Note: uses BIP32 HD key derivation. - fn derive( - &mut self, _resource: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Create a new RANDOM private key. - /// - /// Note, this does not need to be used, as the constructor will do this - /// automatically. - fn gen_private_key(&mut self) -> wasmtime::Result { - todo!() - } - - fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { - todo!() - } -} - -impl Host for HermesState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs new file mode 100644 index 000000000..1e196eb89 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs @@ -0,0 +1,32 @@ +//! Hash host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::hermes::{ + binary::api::Bstr, + hash::api::{Errno, Host}, + }, + state::HermesState, +}; + +impl Host for HermesState { + /// Hash a binary buffer with BLAKE2s + fn blake2s( + &mut self, _buf: Bstr, _outlen: Option, _key: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Hash a binary buffer with `BLAKE2b` + fn blake2b( + &mut self, _buf: Bstr, _outlen: Option, _key: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Hash a binary buffer with BLAKE3 + fn blake3( + &mut self, _buf: Bstr, _outlen: Option, _key: Option, + ) -> wasmtime::Result> { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs index 4903a7875..db70a87d0 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs @@ -1,15 +1,8 @@ -//! Host - Hash implementations +//! Hash runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::hermes::{ - binary::api::Bstr, - hash::api::{Errno, Host}, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -19,26 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState { - /// Hash a binary buffer with BLAKE2s - fn blake2s( - &mut self, _buf: Bstr, _outlen: Option, _key: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Hash a binary buffer with `BLAKE2b` - fn blake2b( - &mut self, _buf: Bstr, _outlen: Option, _key: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Hash a binary buffer with BLAKE3 - fn blake3( - &mut self, _buf: Bstr, _outlen: Option, _key: Option, - ) -> wasmtime::Result> { - todo!() - } -} diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index c2c837459..0eee10a7b 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,4 +1,4 @@ -//! Host - Init implementations +//! Init runtime extension implementation. use crate::runtime_extensions::state::{Context, Stateful}; diff --git a/hermes/bin/src/runtime_extensions/hermes/json/host.rs b/hermes/bin/src/runtime_extensions/hermes/json/host.rs new file mode 100644 index 000000000..00e7e46c8 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/json/host.rs @@ -0,0 +1,5 @@ +//! JSON host implementation for WASM runtime. + +use crate::{runtime_extensions::bindings::hermes::json::api::Host, state::HermesState}; + +impl Host for HermesState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs index 835f51262..68389f3f6 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs @@ -1,12 +1,8 @@ -//! Host - JSON implementations +//! JSON runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::hermes::json::api::Host, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -16,5 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs new file mode 100644 index 000000000..eb9647e55 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs @@ -0,0 +1,86 @@ +//! KV-Store host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::hermes::kv_store::api::{Host, KvValues}, + state::HermesState, +}; + +impl Host for HermesState { + /// Set a value in the local key-value store + /// Setting None will cause the Key to be deleted from the KV store. + fn kv_set(&mut self, _key: String, _value: Option) -> wasmtime::Result<()> { + todo!() + } + + /// Get a value from the local key-value store + /// Returns the default if not set. + fn kv_get_default( + &mut self, _key: String, _default: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Get a value from the local key-value store + /// Returns None if the Key does not exist in the KV Store. + /// This is a convenience function, and is equivalent to `kv-get-default(key, none)` + fn kv_get(&mut self, _key: String) -> wasmtime::Result> { + todo!() + } + + /// Get a value, and then set it (Atomic) + /// Setting None will cause the Key to be deleted from the KV store. + fn kv_get_set( + &mut self, _key: String, _value: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Get a value, and then add to it (Atomic) + /// Adding to a string will concatenate the string. + /// String concatenation will only occur up to the maximum possible size of a string + /// value.\\ + /// Concatenation beyond the maximum size will result in truncation. + /// Adding to a numeric will have the expected behavior (rounded to nearest if + /// necessary). + /// The original type does not change, so: `float64 + u64 = float64`. `s64 + float64 + /// = s64` + /// If the value overflows or under-flows it will saturate at the limit. + /// This behavior allows us to decrement values by using the signed version, so + /// `u64(10) + s64(-5) = u64(5))` + /// If a string is added to a numeric, nothing happens. + /// If a numeric is added to a string, it is converted to a string first, and then + /// concatenated + /// Note: There will be no spaces added. So "My string" + u32(77) = "My string77" + fn kv_add( + &mut self, _key: String, _value: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Check if the Key equals a test value (exact match) and if it does, store the new + /// value. + /// In all cases, the current value is returned. + /// If the types are NOT the same, the comparison will fail, even if the values are + /// equivalent. + /// For example: `u64(7) != s64(7)`, `float64(-1) != s64(-1)`. + fn kv_cas( + &mut self, _key: String, _test: Option, _value: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Subscribe to any updates made to a particular Key. + /// After this call, this module will receive Key Update events when a key is written. + /// It returns the current value of the Key and None if it is not set. + fn kv_subscribe(&mut self, _key: String) -> wasmtime::Result> { + todo!() + } + + /// Unsubscribe to any updates made to a particular Key. + /// After this call, this module will no longer receive Key Update events when a key + /// is written. + /// It returns the current value of the Key and None if it is not set. + fn kv_unsubscribe(&mut self, _key: String) -> wasmtime::Result> { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs index 5cbdbbcc6..66dbea735 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs @@ -1,12 +1,8 @@ -//! Host - KV-Store implementations +//! KV-Store runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::hermes::kv_store::api::{Host, KvValues}, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -16,83 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState { - /// Set a value in the local key-value store - /// Setting None will cause the Key to be deleted from the KV store. - fn kv_set(&mut self, _key: String, _value: Option) -> wasmtime::Result<()> { - todo!() - } - - /// Get a value from the local key-value store - /// Returns the default if not set. - fn kv_get_default( - &mut self, _key: String, _default: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Get a value from the local key-value store - /// Returns None if the Key does not exist in the KV Store. - /// This is a convenience function, and is equivalent to `kv-get-default(key, none)` - fn kv_get(&mut self, _key: String) -> wasmtime::Result> { - todo!() - } - - /// Get a value, and then set it (Atomic) - /// Setting None will cause the Key to be deleted from the KV store. - fn kv_get_set( - &mut self, _key: String, _value: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Get a value, and then add to it (Atomic) - /// Adding to a string will concatenate the string. - /// String concatenation will only occur up to the maximum possible size of a string - /// value.\\ - /// Concatenation beyond the maximum size will result in truncation. - /// Adding to a numeric will have the expected behavior (rounded to nearest if - /// necessary). - /// The original type does not change, so: `float64 + u64 = float64`. `s64 + float64 - /// = s64` - /// If the value overflows or under-flows it will saturate at the limit. - /// This behavior allows us to decrement values by using the signed version, so - /// `u64(10) + s64(-5) = u64(5))` - /// If a string is added to a numeric, nothing happens. - /// If a numeric is added to a string, it is converted to a string first, and then - /// concatenated - /// Note: There will be no spaces added. So "My string" + u32(77) = "My string77" - fn kv_add( - &mut self, _key: String, _value: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Check if the Key equals a test value (exact match) and if it does, store the new - /// value. - /// In all cases, the current value is returned. - /// If the types are NOT the same, the comparison will fail, even if the values are - /// equivalent. - /// For example: `u64(7) != s64(7)`, `float64(-1) != s64(-1)`. - fn kv_cas( - &mut self, _key: String, _test: Option, _value: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Subscribe to any updates made to a particular Key. - /// After this call, this module will receive Key Update events when a key is written. - /// It returns the current value of the Key and None if it is not set. - fn kv_subscribe(&mut self, _key: String) -> wasmtime::Result> { - todo!() - } - - /// Unsubscribe to any updates made to a particular Key. - /// After this call, this module will no longer receive Key Update events when a key - /// is written. - /// It returns the current value of the Key and None if it is not set. - fn kv_unsubscribe(&mut self, _key: String) -> wasmtime::Result> { - todo!() - } -} diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs new file mode 100644 index 000000000..67af83d8b --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs @@ -0,0 +1,62 @@ +//! Localtime host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::{ + hermes::localtime::api::{Errno, Host, Localtime, Timezone}, + wasi::clocks::wall_clock::Datetime, + }, + state::HermesState, +}; + +impl Host for HermesState { + /// Get localtime from a datetime or now. + /// + /// **Parameters** + /// + /// `when` : The datetime we want to convert (Optional, if not set it will convert + /// `now`). + /// `tz` : The timezone to use. (Optional, if not set uses the local machines + /// configured local timezone.) + /// + /// **Returns** + /// + /// `localtime` : the converted time. + /// `errno` : An error indicating why conversion failed. + fn get_localtime( + &mut self, _when: Option, _tz: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Get a new localtime from a localtime, by recalculating time for a new timezone. + /// + /// **Parameters** + /// + /// `time` : The localtime to convert. + /// `tz` : The timezone to use. (Optional, if not set uses the local machines + /// configured local timezone.) + /// + /// **Returns** + /// + /// `localtime` : the converted time. + /// `errno` : An error indicating why conversion failed. + fn alt_localtime( + &mut self, _time: Localtime, _tz: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Get a datetime from a localtime. + /// + /// **Parameters** + /// + /// `time` : The localtime to convert. + /// + /// **Returns** + /// + /// `datetime` : the converted time. + /// `errno` : An error indicating why conversion failed. + fn get_datetime(&mut self, _time: Localtime) -> wasmtime::Result> { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs index 11be28678..9472a28b9 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs @@ -1,15 +1,8 @@ -//! Host - Localtime implementations +//! Localtime runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::{ - hermes::localtime::api::{Errno, Host, Localtime, Timezone}, - wasi::clocks::wall_clock::Datetime, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -19,56 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState { - /// Get localtime from a datetime or now. - /// - /// **Parameters** - /// - /// `when` : The datetime we want to convert (Optional, if not set it will convert - /// `now`). - /// `tz` : The timezone to use. (Optional, if not set uses the local machines - /// configured local timezone.) - /// - /// **Returns** - /// - /// `localtime` : the converted time. - /// `errno` : An error indicating why conversion failed. - fn get_localtime( - &mut self, _when: Option, _tz: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Get a new localtime from a localtime, by recalculating time for a new timezone. - /// - /// **Parameters** - /// - /// `time` : The localtime to convert. - /// `tz` : The timezone to use. (Optional, if not set uses the local machines - /// configured local timezone.) - /// - /// **Returns** - /// - /// `localtime` : the converted time. - /// `errno` : An error indicating why conversion failed. - fn alt_localtime( - &mut self, _time: Localtime, _tz: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Get a datetime from a localtime. - /// - /// **Parameters** - /// - /// `time` : The localtime to convert. - /// - /// **Returns** - /// - /// `datetime` : the converted time. - /// `errno` : An error indicating why conversion failed. - fn get_datetime(&mut self, _time: Localtime) -> wasmtime::Result> { - todo!() - } -} diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs new file mode 100644 index 000000000..dd3962815 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs @@ -0,0 +1,63 @@ +//! Logging host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::hermes::{ + json::api::Json, + logging::api::{Host, Level}, + }, + state::HermesState, +}; + +impl Host for HermesState { + /// Generate a Log + /// + /// The Hermes API will add extra information to the log, such as the instance of the + /// webasm + /// module being logged. + /// The Webasm module does not need to concern itself with this kind of information, + /// and should + /// log as if it is the only instance. + /// It also should not log any webasm shared context, except where it is relevant to + /// the log message itself. + /// + /// **Parameters** + /// + /// - `level` : The log level this message is for. + /// - `file` : The name of the src file being logged from. (Optional) + /// - `fn` : The function within the file being logged from. (Optional) + /// - `line` : The line of code the log was generated from. (Optional) + /// - `col` : The column of code the log was generated from. (Optional) + /// - `ctx` : The logging context. (Should have no newlines or formatting). + /// - `msg` : A Single line message to be logged. (Should have no newlines or + /// formatting). + /// - `data` : A Free form json payload that will be logged with the msg. This must + /// be valid JSON. + /// + /// *Notes* + /// + /// The `data` parameter may contain a record of the format: + /// ```json + /// { + /// "bt" : [ , ] + /// } + /// ``` + /// The logger will interpret this as a backtrace where each entry in the array is one + /// line of the backtrace. + /// The format of the backtrace lines is up to the webasm module generating the log. + /// The individual backtrace entries may contain line breaks if the backtrace entry is + /// multiline. + /// * Multiline backtrace entries should be de-dented, relative to the first line. + /// * This is to allow the display to properly format multiline entries. + /// This format is designed to keep the broadest flexibility for multiple languages + /// capabilities. + /// The backtrace must be sorted with most recent lines of the backtrace occurring + /// first in the array. + /// Backtrace must be contained in a single `log` call. Multiple log calls will be + /// considered independent logs. + fn log( + &mut self, _level: Level, _file: Option, _fn_: Option, _line: Option, + _col: Option, _ctx: Option, _msg: String, _data: Option, + ) -> wasmtime::Result<()> { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs index dff4d2358..dc7d340eb 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs @@ -1,15 +1,8 @@ -//! Host - Logging implementations +//! Logging runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::hermes::{ - json::api::Json, - logging::api::{Host, Level}, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// State pub(crate) struct State {} @@ -19,57 +12,3 @@ impl Stateful for State { State {} } } - -impl Host for HermesState { - /// Generate a Log - /// - /// The Hermes API will add extra information to the log, such as the instance of the - /// webasm - /// module being logged. - /// The Webasm module does not need to concern itself with this kind of information, - /// and should - /// log as if it is the only instance. - /// It also should not log any webasm shared context, except where it is relevant to - /// the log message itself. - /// - /// **Parameters** - /// - /// - `level` : The log level this message is for. - /// - `file` : The name of the src file being logged from. (Optional) - /// - `fn` : The function within the file being logged from. (Optional) - /// - `line` : The line of code the log was generated from. (Optional) - /// - `col` : The column of code the log was generated from. (Optional) - /// - `ctx` : The logging context. (Should have no newlines or formatting). - /// - `msg` : A Single line message to be logged. (Should have no newlines or - /// formatting). - /// - `data` : A Free form json payload that will be logged with the msg. This must - /// be valid JSON. - /// - /// *Notes* - /// - /// The `data` parameter may contain a record of the format: - /// ```json - /// { - /// "bt" : [ , ] - /// } - /// ``` - /// The logger will interpret this as a backtrace where each entry in the array is one - /// line of the backtrace. - /// The format of the backtrace lines is up to the webasm module generating the log. - /// The individual backtrace entries may contain line breaks if the backtrace entry is - /// multiline. - /// * Multiline backtrace entries should be de-dented, relative to the first line. - /// * This is to allow the display to properly format multiline entries. - /// This format is designed to keep the broadest flexibility for multiple languages - /// capabilities. - /// The backtrace must be sorted with most recent lines of the backtrace occurring - /// first in the array. - /// Backtrace must be contained in a single `log` call. Multiple log calls will be - /// considered independent logs. - fn log( - &mut self, _level: Level, _file: Option, _fn_: Option, _line: Option, - _col: Option, _ctx: Option, _msg: String, _data: Option, - ) -> wasmtime::Result<()> { - todo!() - } -} From 68681e9667a14c168eca0e4b571ae0f31e5306c0 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 13:24:16 +0200 Subject: [PATCH 05/52] move wasi runtime extensions host impl to the separate module --- .../src/runtime_extensions/wasi/cli/host.rs | 52 ++ .../src/runtime_extensions/wasi/cli/mod.rs | 58 +- .../{monotonic.rs => monotonic/host.rs} | 16 +- .../wasi/clocks/monotonic/mod.rs | 14 + .../wasi/clocks/{wall.rs => wall/host.rs} | 16 +- .../wasi/clocks/wall/mod.rs | 14 + .../wasi/filesystem/host.rs | 429 ++++++++++++ .../runtime_extensions/wasi/filesystem/mod.rs | 435 +----------- .../src/runtime_extensions/wasi/http/host.rs | 657 +++++++++++++++++ .../src/runtime_extensions/wasi/http/mod.rs | 663 +----------------- .../wasi/io/{error.rs => error/host.rs} | 16 +- .../runtime_extensions/wasi/io/error/mod.rs | 14 + .../wasi/io/{streams.rs => streams/host.rs} | 18 +- .../runtime_extensions/wasi/io/streams/mod.rs | 14 + .../random/{insecure.rs => insecure/host.rs} | 19 +- .../wasi/random/insecure/mod.rs | 14 + .../host.rs} | 18 +- .../wasi/random/insecure_seed/mod.rs | 14 + .../wasi/random/{secure.rs => secure/host.rs} | 19 +- .../wasi/random/secure/mod.rs | 14 + 20 files changed, 1263 insertions(+), 1251 deletions(-) create mode 100644 hermes/bin/src/runtime_extensions/wasi/cli/host.rs rename hermes/bin/src/runtime_extensions/wasi/clocks/{monotonic.rs => monotonic/host.rs} (61%) create mode 100644 hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs rename hermes/bin/src/runtime_extensions/wasi/clocks/{wall.rs => wall/host.rs} (77%) create mode 100644 hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs create mode 100644 hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs create mode 100644 hermes/bin/src/runtime_extensions/wasi/http/host.rs rename hermes/bin/src/runtime_extensions/wasi/io/{error.rs => error/host.rs} (71%) create mode 100644 hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs rename hermes/bin/src/runtime_extensions/wasi/io/{streams.rs => streams/host.rs} (96%) create mode 100644 hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs rename hermes/bin/src/runtime_extensions/wasi/random/{insecure.rs => insecure/host.rs} (71%) create mode 100644 hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs rename hermes/bin/src/runtime_extensions/wasi/random/{insecure_seed.rs => insecure_seed/host.rs} (76%) create mode 100644 hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs rename hermes/bin/src/runtime_extensions/wasi/random/{secure.rs => secure/host.rs} (79%) create mode 100644 hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs new file mode 100644 index 000000000..68f22faec --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs @@ -0,0 +1,52 @@ +//! CLI host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::wasi::{ + cli, + io::streams::{InputStream, OutputStream}, + }, + state::HermesState, +}; + +impl cli::environment::Host for HermesState { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + fn get_environment(&mut self) -> wasmtime::Result> { + todo!() + } + + /// Get the POSIX-style arguments to the program. + fn get_arguments(&mut self) -> wasmtime::Result> { + todo!() + } + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + fn initial_cwd(&mut self) -> wasmtime::Result> { + todo!() + } +} + +impl cli::stdin::Host for HermesState { + fn get_stdin(&mut self) -> wasmtime::Result> { + todo!() + } +} + +impl cli::stdout::Host for HermesState { + fn get_stdout(&mut self) -> wasmtime::Result> { + todo!() + } +} + +impl cli::stderr::Host for HermesState { + fn get_stderr(&mut self) -> wasmtime::Result> { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs index 0e136e805..8aebdf8a8 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs @@ -1,15 +1,8 @@ -//! Host - WASI - CLI implementations +//! CLI runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::wasi::{ - cli, - io::streams::{InputStream, OutputStream}, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// WASI State pub(crate) struct State {} @@ -19,46 +12,3 @@ impl Stateful for State { Self {} } } - -impl cli::environment::Host for HermesState { - /// Get the POSIX-style environment variables. - /// - /// Each environment variable is provided as a pair of string variable names - /// and string value. - /// - /// Morally, these are a value import, but until value imports are available - /// in the component model, this import function should return the same - /// values each time it is called. - fn get_environment(&mut self) -> wasmtime::Result> { - todo!() - } - - /// Get the POSIX-style arguments to the program. - fn get_arguments(&mut self) -> wasmtime::Result> { - todo!() - } - - /// Return a path that programs should use as their initial current working - /// directory, interpreting `.` as shorthand for this. - fn initial_cwd(&mut self) -> wasmtime::Result> { - todo!() - } -} - -impl cli::stdin::Host for HermesState { - fn get_stdin(&mut self) -> wasmtime::Result> { - todo!() - } -} - -impl cli::stdout::Host for HermesState { - fn get_stdout(&mut self) -> wasmtime::Result> { - todo!() - } -} - -impl cli::stderr::Host for HermesState { - fn get_stderr(&mut self) -> wasmtime::Result> { - todo!() - } -} diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs similarity index 61% rename from hermes/bin/src/runtime_extensions/wasi/clocks/monotonic.rs rename to hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs index a3abcd6cc..77eb45e4e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs @@ -1,22 +1,10 @@ -//! Host - WASI - monotonic clock implementations +//! Monotonic clock host implementation for WASM runtime. use crate::{ - runtime_extensions::{ - bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, - state::{Context, Stateful}, - }, + runtime_extensions::bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, state::HermesState, }; -/// WASI State -pub(crate) struct State {} - -impl Stateful for State { - fn new(_ctx: &Context) -> Self { - Self {} - } -} - impl Host for HermesState { /// Read the current value of the clock. /// diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs new file mode 100644 index 000000000..23cf470f0 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs @@ -0,0 +1,14 @@ +//! Monotonic clock runtime extension implementation. + +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; + +/// WASI State +pub(crate) struct State {} + +impl Stateful for State { + fn new(_ctx: &Context) -> Self { + Self {} + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs similarity index 77% rename from hermes/bin/src/runtime_extensions/wasi/clocks/wall.rs rename to hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs index 6c2b4949f..e6d043eee 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs @@ -1,22 +1,10 @@ -//! Host - WASI - Wall Clock implementations +//! Wall clock host implementation for WASM runtime. use crate::{ - runtime_extensions::{ - bindings::wasi::clocks::wall_clock::{Datetime, Host}, - state::{Context, Stateful}, - }, + runtime_extensions::bindings::wasi::clocks::wall_clock::{Datetime, Host}, state::HermesState, }; -/// WASI State -pub(crate) struct State {} - -impl Stateful for State { - fn new(_ctx: &Context) -> Self { - Self {} - } -} - impl Host for HermesState { /// Read the current value of the clock. /// diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs new file mode 100644 index 000000000..cfdcad95d --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs @@ -0,0 +1,14 @@ +//! Wall clock runtime extension implementation. + +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; + +/// WASI State +pub(crate) struct State {} + +impl Stateful for State { + fn new(_ctx: &Context) -> Self { + Self {} + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs new file mode 100644 index 000000000..a61460e3b --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs @@ -0,0 +1,429 @@ +//! Filesystem host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::wasi::{ + filesystem::{ + self, + types::{ + Advice, Descriptor, DescriptorFlags, DescriptorStat, DescriptorType, + DirectoryEntry, DirectoryEntryStream, Error, ErrorCode, Filesize, + MetadataHashValue, NewTimestamp, OpenFlags, PathFlags, + }, + }, + io::streams::{InputStream, OutputStream}, + }, + state::HermesState, +}; + +impl filesystem::types::HostDescriptor for HermesState { + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + fn read_via_stream( + &mut self, _descriptor: wasmtime::component::Resource, _offset: Filesize, + ) -> wasmtime::Result, ErrorCode>> { + todo!() + } + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + fn write_via_stream( + &mut self, _descriptor: wasmtime::component::Resource, _offset: Filesize, + ) -> wasmtime::Result, ErrorCode>> { + todo!() + } + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in in POSIX. + fn append_via_stream( + &mut self, _descriptor: wasmtime::component::Resource, + ) -> wasmtime::Result, ErrorCode>> { + todo!() + } + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + fn advise( + &mut self, _descriptor: wasmtime::component::Resource, _offset: Filesize, + _length: Filesize, _advice: Advice, + ) -> wasmtime::Result> { + todo!() + } + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + fn sync_data( + &mut self, _descriptor: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + fn get_flags( + &mut self, _descriptor: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + fn get_type( + &mut self, _descriptor: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Adjust the size of an open file. If this increases the file\'s size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + fn set_size( + &mut self, _descriptor: wasmtime::component::Resource, _size: Filesize, + ) -> wasmtime::Result> { + todo!() + } + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + fn set_times( + &mut self, _descriptor: wasmtime::component::Resource, + _data_access_timestamp: NewTimestamp, _data_modification_timestamp: NewTimestamp, + ) -> wasmtime::Result> { + todo!() + } + + /// Read from a descriptor, without using and updating the descriptor\'s offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + fn read( + &mut self, _descriptor: wasmtime::component::Resource, _length: Filesize, + _offset: Filesize, + ) -> wasmtime::Result, bool), ErrorCode>> { + todo!() + } + + /// Write to a descriptor, without using and updating the descriptor\'s offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + fn write( + &mut self, _descriptor: wasmtime::component::Resource, _buffer: Vec, + _offset: Filesize, + ) -> wasmtime::Result> { + todo!() + } + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + fn read_directory( + &mut self, _descriptor: wasmtime::component::Resource, + ) -> wasmtime::Result, ErrorCode>> + { + todo!() + } + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + fn sync( + &mut self, _descriptor: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + fn create_directory_at( + &mut self, _descriptor: wasmtime::component::Resource, _path: String, + ) -> wasmtime::Result> { + todo!() + } + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + fn stat( + &mut self, _descriptor: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + fn stat_at( + &mut self, _descriptor: wasmtime::component::Resource, _path_flags: PathFlags, + _path: String, + ) -> wasmtime::Result> { + todo!() + } + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + fn set_times_at( + &mut self, _descriptor: wasmtime::component::Resource, _path_flags: PathFlags, + _path: String, _data_access_timestamp: NewTimestamp, + _data_modification_timestamp: NewTimestamp, + ) -> wasmtime::Result> { + todo!() + } + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + fn link_at( + &mut self, _descriptor: wasmtime::component::Resource, + _old_path_flags: PathFlags, _old_path: String, + _new_descriptor: wasmtime::component::Resource, _new_path: String, + ) -> wasmtime::Result> { + todo!() + } + + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + fn open_at( + &mut self, _descriptor: wasmtime::component::Resource, _path_flags: PathFlags, + _path: String, _open_flags: OpenFlags, _flags: DescriptorFlags, + ) -> wasmtime::Result, ErrorCode>> { + todo!() + } + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + fn readlink_at( + &mut self, _descriptor: wasmtime::component::Resource, _path: String, + ) -> wasmtime::Result> { + todo!() + } + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + fn remove_directory_at( + &mut self, _descriptor: wasmtime::component::Resource, _path: String, + ) -> wasmtime::Result> { + todo!() + } + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + fn rename_at( + &mut self, _old_descriptor: wasmtime::component::Resource, _old_path: String, + _new_descriptor: wasmtime::component::Resource, _new_path: String, + ) -> wasmtime::Result> { + todo!() + } + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + fn symlink_at( + &mut self, _old_descriptor: wasmtime::component::Resource, _old_path: String, + _new_path: String, + ) -> wasmtime::Result> { + todo!() + } + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + fn unlink_file_at( + &mut self, _descriptor: wasmtime::component::Resource, _path: String, + ) -> wasmtime::Result> { + todo!() + } + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + fn is_same_object( + &mut self, _descriptor: wasmtime::component::Resource, + _other: wasmtime::component::Resource, + ) -> wasmtime::Result { + todo!() + } + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encouraged to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + fn metadata_hash( + &mut self, _descriptor: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + fn metadata_hash_at( + &mut self, _descriptor: wasmtime::component::Resource, _path_flags: PathFlags, + _path: String, + ) -> wasmtime::Result> { + todo!() + } + + fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { + todo!() + } +} + +impl filesystem::types::HostDirectoryEntryStream for HermesState { + /// Read a single directory entry from a `directory-entry-stream`. + fn read_directory_entry( + &mut self, _dir: wasmtime::component::Resource, + ) -> wasmtime::Result, ErrorCode>> { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl filesystem::types::Host for HermesState { + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there\'s + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + fn filesystem_error_code( + &mut self, _err: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } +} + +impl filesystem::preopens::Host for HermesState { + /// Return the set of preopened directories, and their path. + fn get_directories( + &mut self, + ) -> wasmtime::Result, String)>> { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs index fd4771edb..aa77b84c2 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs @@ -1,22 +1,8 @@ -//! Host - WASI - Filesystem implementations +//! Filesystem runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::wasi::{ - filesystem::{ - self, - types::{ - Advice, Descriptor, DescriptorFlags, DescriptorStat, DescriptorType, - DirectoryEntry, DirectoryEntryStream, Error, ErrorCode, Filesize, - MetadataHashValue, NewTimestamp, OpenFlags, PathFlags, - }, - }, - io::streams::{InputStream, OutputStream}, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// WASI State pub(crate) struct State {} @@ -26,416 +12,3 @@ impl Stateful for State { Self {} } } - -impl filesystem::types::HostDescriptor for HermesState { - /// Return a stream for reading from a file, if available. - /// - /// May fail with an error-code describing why the file cannot be read. - /// - /// Multiple read, write, and append streams may be active on the same open - /// file and they do not interfere with each other. - /// - /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. - fn read_via_stream( - &mut self, _descriptor: wasmtime::component::Resource, _offset: Filesize, - ) -> wasmtime::Result, ErrorCode>> { - todo!() - } - - /// Return a stream for writing to a file, if available. - /// - /// May fail with an error-code describing why the file cannot be written. - /// - /// Note: This allows using `write-stream`, which is similar to `write` in - /// POSIX. - fn write_via_stream( - &mut self, _descriptor: wasmtime::component::Resource, _offset: Filesize, - ) -> wasmtime::Result, ErrorCode>> { - todo!() - } - - /// Return a stream for appending to a file, if available. - /// - /// May fail with an error-code describing why the file cannot be appended. - /// - /// Note: This allows using `write-stream`, which is similar to `write` with - /// `O_APPEND` in in POSIX. - fn append_via_stream( - &mut self, _descriptor: wasmtime::component::Resource, - ) -> wasmtime::Result, ErrorCode>> { - todo!() - } - - /// Provide file advisory information on a descriptor. - /// - /// This is similar to `posix_fadvise` in POSIX. - fn advise( - &mut self, _descriptor: wasmtime::component::Resource, _offset: Filesize, - _length: Filesize, _advice: Advice, - ) -> wasmtime::Result> { - todo!() - } - - /// Synchronize the data of a file to disk. - /// - /// This function succeeds with no effect if the file descriptor is not - /// opened for writing. - /// - /// Note: This is similar to `fdatasync` in POSIX. - fn sync_data( - &mut self, _descriptor: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Get flags associated with a descriptor. - /// - /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. - /// - /// Note: This returns the value that was the `fs_flags` value returned - /// from `fdstat_get` in earlier versions of WASI. - fn get_flags( - &mut self, _descriptor: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the dynamic type of a descriptor. - /// - /// Note: This returns the same value as the `type` field of the `fd-stat` - /// returned by `stat`, `stat-at` and similar. - /// - /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided - /// by `fstat` in POSIX. - /// - /// Note: This returns the value that was the `fs_filetype` value returned - /// from `fdstat_get` in earlier versions of WASI. - fn get_type( - &mut self, _descriptor: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Adjust the size of an open file. If this increases the file\'s size, the - /// extra bytes are filled with zeros. - /// - /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. - fn set_size( - &mut self, _descriptor: wasmtime::component::Resource, _size: Filesize, - ) -> wasmtime::Result> { - todo!() - } - - /// Adjust the timestamps of an open file or directory. - /// - /// Note: This is similar to `futimens` in POSIX. - /// - /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. - fn set_times( - &mut self, _descriptor: wasmtime::component::Resource, - _data_access_timestamp: NewTimestamp, _data_modification_timestamp: NewTimestamp, - ) -> wasmtime::Result> { - todo!() - } - - /// Read from a descriptor, without using and updating the descriptor\'s offset. - /// - /// This function returns a list of bytes containing the data that was - /// read, along with a bool which, when true, indicates that the end of the - /// file was reached. The returned list will contain up to `length` bytes; it - /// may return fewer than requested, if the end of the file is reached or - /// if the I/O operation is interrupted. - /// - /// In the future, this may change to return a `stream`. - /// - /// Note: This is similar to `pread` in POSIX. - fn read( - &mut self, _descriptor: wasmtime::component::Resource, _length: Filesize, - _offset: Filesize, - ) -> wasmtime::Result, bool), ErrorCode>> { - todo!() - } - - /// Write to a descriptor, without using and updating the descriptor\'s offset. - /// - /// It is valid to write past the end of a file; the file is extended to the - /// extent of the write, with bytes between the previous end and the start of - /// the write set to zero. - /// - /// In the future, this may change to take a `stream`. - /// - /// Note: This is similar to `pwrite` in POSIX. - fn write( - &mut self, _descriptor: wasmtime::component::Resource, _buffer: Vec, - _offset: Filesize, - ) -> wasmtime::Result> { - todo!() - } - - /// Read directory entries from a directory. - /// - /// On filesystems where directories contain entries referring to themselves - /// and their parents, often named `.` and `..` respectively, these entries - /// are omitted. - /// - /// This always returns a new stream which starts at the beginning of the - /// directory. Multiple streams may be active on the same directory, and they - /// do not interfere with each other. - fn read_directory( - &mut self, _descriptor: wasmtime::component::Resource, - ) -> wasmtime::Result, ErrorCode>> - { - todo!() - } - - /// Synchronize the data and metadata of a file to disk. - /// - /// This function succeeds with no effect if the file descriptor is not - /// opened for writing. - /// - /// Note: This is similar to `fsync` in POSIX. - fn sync( - &mut self, _descriptor: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Create a directory. - /// - /// Note: This is similar to `mkdirat` in POSIX. - fn create_directory_at( - &mut self, _descriptor: wasmtime::component::Resource, _path: String, - ) -> wasmtime::Result> { - todo!() - } - - /// Return the attributes of an open file or directory. - /// - /// Note: This is similar to `fstat` in POSIX, except that it does not return - /// device and inode information. For testing whether two descriptors refer to - /// the same underlying filesystem object, use `is-same-object`. To obtain - /// additional data that can be used do determine whether a file has been - /// modified, use `metadata-hash`. - /// - /// Note: This was called `fd_filestat_get` in earlier versions of WASI. - fn stat( - &mut self, _descriptor: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Return the attributes of a file or directory. - /// - /// Note: This is similar to `fstatat` in POSIX, except that it does not - /// return device and inode information. See the `stat` description for a - /// discussion of alternatives. - /// - /// Note: This was called `path_filestat_get` in earlier versions of WASI. - fn stat_at( - &mut self, _descriptor: wasmtime::component::Resource, _path_flags: PathFlags, - _path: String, - ) -> wasmtime::Result> { - todo!() - } - - /// Adjust the timestamps of a file or directory. - /// - /// Note: This is similar to `utimensat` in POSIX. - /// - /// Note: This was called `path_filestat_set_times` in earlier versions of - /// WASI. - fn set_times_at( - &mut self, _descriptor: wasmtime::component::Resource, _path_flags: PathFlags, - _path: String, _data_access_timestamp: NewTimestamp, - _data_modification_timestamp: NewTimestamp, - ) -> wasmtime::Result> { - todo!() - } - - /// Create a hard link. - /// - /// Note: This is similar to `linkat` in POSIX. - fn link_at( - &mut self, _descriptor: wasmtime::component::Resource, - _old_path_flags: PathFlags, _old_path: String, - _new_descriptor: wasmtime::component::Resource, _new_path: String, - ) -> wasmtime::Result> { - todo!() - } - - /// Open a file or directory. - /// - /// The returned descriptor is not guaranteed to be the lowest-numbered - /// descriptor not currently open/ it is randomized to prevent applications - /// from depending on making assumptions about indexes, since this is - /// error-prone in multi-threaded contexts. The returned descriptor is - /// guaranteed to be less than 2**31. - /// - /// If `flags` contains `descriptor-flags::mutate-directory`, and the base - /// descriptor doesn't have `descriptor-flags::mutate-directory` set, - /// `open-at` fails with `error-code::read-only`. - /// - /// If `flags` contains `write` or `mutate-directory`, or `open-flags` - /// contains `truncate` or `create`, and the base descriptor doesn't have - /// `descriptor-flags::mutate-directory` set, `open-at` fails with - /// `error-code::read-only`. - /// - /// Note: This is similar to `openat` in POSIX. - fn open_at( - &mut self, _descriptor: wasmtime::component::Resource, _path_flags: PathFlags, - _path: String, _open_flags: OpenFlags, _flags: DescriptorFlags, - ) -> wasmtime::Result, ErrorCode>> { - todo!() - } - - /// Read the contents of a symbolic link. - /// - /// If the contents contain an absolute or rooted path in the underlying - /// filesystem, this function fails with `error-code::not-permitted`. - /// - /// Note: This is similar to `readlinkat` in POSIX. - fn readlink_at( - &mut self, _descriptor: wasmtime::component::Resource, _path: String, - ) -> wasmtime::Result> { - todo!() - } - - /// Remove a directory. - /// - /// Return `error-code::not-empty` if the directory is not empty. - /// - /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. - fn remove_directory_at( - &mut self, _descriptor: wasmtime::component::Resource, _path: String, - ) -> wasmtime::Result> { - todo!() - } - - /// Rename a filesystem object. - /// - /// Note: This is similar to `renameat` in POSIX. - fn rename_at( - &mut self, _old_descriptor: wasmtime::component::Resource, _old_path: String, - _new_descriptor: wasmtime::component::Resource, _new_path: String, - ) -> wasmtime::Result> { - todo!() - } - - /// Create a symbolic link (also known as a "symlink"). - /// - /// If `old-path` starts with `/`, the function fails with - /// `error-code::not-permitted`. - /// - /// Note: This is similar to `symlinkat` in POSIX. - fn symlink_at( - &mut self, _old_descriptor: wasmtime::component::Resource, _old_path: String, - _new_path: String, - ) -> wasmtime::Result> { - todo!() - } - - /// Unlink a filesystem object that is not a directory. - /// - /// Return `error-code::is-directory` if the path refers to a directory. - /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. - fn unlink_file_at( - &mut self, _descriptor: wasmtime::component::Resource, _path: String, - ) -> wasmtime::Result> { - todo!() - } - - /// Test whether two descriptors refer to the same filesystem object. - /// - /// In POSIX, this corresponds to testing whether the two descriptors have the - /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. - /// wasi-filesystem does not expose device and inode numbers, so this function - /// may be used instead. - fn is_same_object( - &mut self, _descriptor: wasmtime::component::Resource, - _other: wasmtime::component::Resource, - ) -> wasmtime::Result { - todo!() - } - - /// Return a hash of the metadata associated with a filesystem object referred - /// to by a descriptor. - /// - /// This returns a hash of the last-modification timestamp and file size, and - /// may also include the inode number, device number, birth timestamp, and - /// other metadata fields that may change when the file is modified or - /// replaced. It may also include a secret value chosen by the - /// implementation and not otherwise exposed. - /// - /// Implementations are encouraged to provide the following properties: - /// - /// - If the file is not modified or replaced, the computed hash value should - /// usually not change. - /// - If the object is modified or replaced, the computed hash value should - /// usually change. - /// - The inputs to the hash should not be easily computable from the - /// computed hash. - /// - /// However, none of these is required. - fn metadata_hash( - &mut self, _descriptor: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Return a hash of the metadata associated with a filesystem object referred - /// to by a directory descriptor and a relative path. - /// - /// This performs the same hash computation as `metadata-hash`. - fn metadata_hash_at( - &mut self, _descriptor: wasmtime::component::Resource, _path_flags: PathFlags, - _path: String, - ) -> wasmtime::Result> { - todo!() - } - - fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { - todo!() - } -} - -impl filesystem::types::HostDirectoryEntryStream for HermesState { - /// Read a single directory entry from a `directory-entry-stream`. - fn read_directory_entry( - &mut self, _dir: wasmtime::component::Resource, - ) -> wasmtime::Result, ErrorCode>> { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl filesystem::types::Host for HermesState { - /// Attempts to extract a filesystem-related `error-code` from the stream - /// `error` provided. - /// - /// Stream operations which return `stream-error::last-operation-failed` - /// have a payload with more information about the operation that failed. - /// This payload can be passed through to this function to see if there\'s - /// filesystem-related information about the error to return. - /// - /// Note that this function is fallible because not all stream-related - /// errors are filesystem-related errors. - fn filesystem_error_code( - &mut self, _err: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } -} - -impl filesystem::preopens::Host for HermesState { - /// Return the set of preopened directories, and their path. - fn get_directories( - &mut self, - ) -> wasmtime::Result, String)>> { - todo!() - } -} diff --git a/hermes/bin/src/runtime_extensions/wasi/http/host.rs b/hermes/bin/src/runtime_extensions/wasi/http/host.rs new file mode 100644 index 000000000..817a025ce --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/http/host.rs @@ -0,0 +1,657 @@ +//! HTTP host implementation for WASM runtime. + +use crate::{ + runtime_extensions::bindings::wasi::{ + http::{ + self, + outgoing_handler::{ + ErrorCode, FutureIncomingResponse, OutgoingRequest, RequestOptions, + }, + types::{ + Duration, FieldKey, FieldValue, Fields, FutureTrailers, HeaderError, Headers, + HostIncomingResponse, HostOutgoingResponse, IncomingBody, IncomingRequest, + IncomingResponse, IoError, Method, OutgoingBody, OutgoingResponse, + ResponseOutparam, Scheme, StatusCode, Trailers, + }, + }, + io::streams::{InputStream, OutputStream}, + }, + state::HermesState, +}; + +impl http::types::HostFutureIncomingResponse for HermesState { + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + fn get( + &mut self, _res: wasmtime::component::Resource, + ) -> wasmtime::Result< + Option, ErrorCode>, ()>>, + > { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::HostFields for HermesState { + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + fn new(&mut self) -> wasmtime::Result> { + todo!() + } + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. In a valid Fields, all keys + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, or if a header was forbidden. + fn from_list( + &mut self, _entries: Vec<(FieldKey, FieldValue)>, + ) -> wasmtime::Result, HeaderError>> { + todo!() + } + + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields`, an empty list is returned. However, if the key is + /// present but empty, this is represented by a list with one or more + /// empty field-values present. + fn get( + &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, + ) -> wasmtime::Result> { + todo!() + } + + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + fn has( + &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, + ) -> wasmtime::Result { + todo!() + } + + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + fn set( + &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, + _value: Vec, + ) -> wasmtime::Result> { + todo!() + } + + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + fn delete( + &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, + ) -> wasmtime::Result> { + todo!() + } + + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + fn append( + &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, + _value: FieldValue, + ) -> wasmtime::Result> { + todo!() + } + + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + fn entries( + &mut self, _fields: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + fn clone( + &mut self, _fields: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::HostFutureTrailers for HermesState { + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + fn get( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result< + Option>, ErrorCode>, ()>>, + > { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::HostOutgoingBody for HermesState { + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + fn write( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result, ()>> { + todo!() + } + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body\'s `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + fn finish( + &mut self, _this: wasmtime::component::Resource, + _trailers: Option>, + ) -> wasmtime::Result> { + todo!() + } + + fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { + todo!() + } +} + +impl HostOutgoingResponse for HermesState { + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + fn new( + &mut self, _headers: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the HTTP Status Code for the Response. + fn status_code( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result { + todo!() + } + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + fn set_status_code( + &mut self, _rep: wasmtime::component::Resource, _status_code: StatusCode, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + fn headers( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + fn body( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result, ()>> { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::HostIncomingBody for HermesState { + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + fn stream( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result, ()>> { + todo!() + } + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + fn finish( + &mut self, _this: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { + todo!() + } +} + +impl HostIncomingResponse for HermesState { + /// Returns the status code from the incoming response. + fn status( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result { + todo!() + } + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + fn headers( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + fn consume( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result, ()>> { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::HostResponseOutparam for HermesState { + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + fn set( + &mut self, _param: wasmtime::component::Resource, + _response: Result, ErrorCode>, + ) -> wasmtime::Result<()> { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::HostRequestOptions for HermesState { + /// Construct a default `request-options` value. + fn new(&mut self) -> wasmtime::Result> { + todo!() + } + + /// The timeout for the initial connect to the HTTP Server. + fn connect_timeout( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + fn set_connect_timeout( + &mut self, _rep: wasmtime::component::Resource, _duration: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// The timeout for receiving the first byte of the Response body. + fn first_byte_timeout( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + fn set_first_byte_timeout( + &mut self, _rep: wasmtime::component::Resource, _duration: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + fn between_bytes_timeout( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + fn set_between_bytes_timeout( + &mut self, _rep: wasmtime::component::Resource, _duration: Option, + ) -> wasmtime::Result> { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::HostOutgoingRequest for HermesState { + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + fn new( + &mut self, _headers: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + fn body( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result, ()>> { + todo!() + } + + /// Get the Method for the Request. + fn method( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result { + todo!() + } + + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + fn set_method( + &mut self, _rep: wasmtime::component::Resource, _method: Method, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + fn path_with_query( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + fn set_path_with_query( + &mut self, _rep: wasmtime::component::Resource, + _path_with_query: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + fn scheme( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + fn set_scheme( + &mut self, _rep: wasmtime::component::Resource, _scheme: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + fn authority( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + fn set_authority( + &mut self, _rep: wasmtime::component::Resource, _authority: Option, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + fn headers( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::HostIncomingRequest for HermesState { + /// Returns the method of the incoming request. + fn method( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result { + todo!() + } + + /// Returns the path with query parameters from the request, as a string. + fn path_with_query( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Returns the protocol scheme from the request. + fn scheme( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Returns the authority from the request, if it was present. + fn authority( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + fn headers( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + fn consume( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result, ()>> { + todo!() + } + + fn drop( + &mut self, _rep: wasmtime::component::Resource, + ) -> wasmtime::Result<()> { + todo!() + } +} + +impl http::types::Host for HermesState { + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there\'s http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + fn http_error_code( + &mut self, _err: wasmtime::component::Resource, + ) -> wasmtime::Result> { + todo!() + } +} + +impl http::outgoing_handler::Host for HermesState { + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol\'s transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + fn handle( + &mut self, _request: wasmtime::component::Resource, + _options: Option>, + ) -> wasmtime::Result, ErrorCode>> + { + todo!() + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs index 68dedc475..a585b9268 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs @@ -1,26 +1,8 @@ -//! Host - WASI - HTTP implementations +//! HTTP runtime extension implementation. -use crate::{ - runtime_extensions::{ - bindings::wasi::{ - http::{ - self, - outgoing_handler::{ - ErrorCode, FutureIncomingResponse, OutgoingRequest, RequestOptions, - }, - types::{ - Duration, FieldKey, FieldValue, Fields, FutureTrailers, HeaderError, Headers, - HostIncomingResponse, HostOutgoingResponse, IncomingBody, IncomingRequest, - IncomingResponse, IoError, Method, OutgoingBody, OutgoingResponse, - ResponseOutparam, Scheme, StatusCode, Trailers, - }, - }, - io::streams::{InputStream, OutputStream}, - }, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; /// WASI State pub(crate) struct State {} @@ -30,640 +12,3 @@ impl Stateful for State { Self {} } } - -impl http::types::HostFutureIncomingResponse for HermesState { - /// Returns the incoming HTTP Response, or an error, once one is ready. - /// - /// The outer `option` represents future readiness. Users can wait on this - /// `option` to become `some` using the `subscribe` method. - /// - /// The outer `result` is used to retrieve the response or error at most - /// once. It will be success on the first call in which the outer option - /// is `some`, and error on subsequent calls. - /// - /// The inner `result` represents that either the incoming HTTP Response - /// status and headers have received successfully, or that an error - /// occurred. Errors may also occur while consuming the response body, - /// but those will be reported by the `incoming-body` and its - /// `output-stream` child. - fn get( - &mut self, _res: wasmtime::component::Resource, - ) -> wasmtime::Result< - Option, ErrorCode>, ()>>, - > { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::HostFields for HermesState { - /// Construct an empty HTTP Fields. - /// - /// The resulting `fields` is mutable. - fn new(&mut self) -> wasmtime::Result> { - todo!() - } - - /// Construct an HTTP Fields. - /// - /// The resulting `fields` is mutable. - /// - /// The list represents each key-value pair in the Fields. Keys - /// which have multiple values are represented by multiple entries in this - /// list with the same key. - /// - /// The tuple is a pair of the field key, represented as a string, and - /// Value, represented as a list of bytes. In a valid Fields, all keys - /// and values are valid UTF-8 strings. However, values are not always - /// well-formed, so they are represented as a raw list of bytes. - /// - /// An error result will be returned if any header or value was - /// syntactically invalid, or if a header was forbidden. - fn from_list( - &mut self, _entries: Vec<(FieldKey, FieldValue)>, - ) -> wasmtime::Result, HeaderError>> { - todo!() - } - - /// Get all of the values corresponding to a key. If the key is not present - /// in this `fields`, an empty list is returned. However, if the key is - /// present but empty, this is represented by a list with one or more - /// empty field-values present. - fn get( - &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, - ) -> wasmtime::Result> { - todo!() - } - - /// Returns `true` when the key is present in this `fields`. If the key is - /// syntactically invalid, `false` is returned. - fn has( - &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, - ) -> wasmtime::Result { - todo!() - } - - /// Set all of the values for a key. Clears any existing values for that - /// key, if they have been set. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - fn set( - &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, - _value: Vec, - ) -> wasmtime::Result> { - todo!() - } - - /// Delete all values for a key. Does nothing if no values for the key - /// exist. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - fn delete( - &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, - ) -> wasmtime::Result> { - todo!() - } - - /// Append a value for a key. Does not change or delete any existing - /// values for that key. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - fn append( - &mut self, _fields: wasmtime::component::Resource, _name: FieldKey, - _value: FieldValue, - ) -> wasmtime::Result> { - todo!() - } - - /// Retrieve the full set of keys and values in the Fields. Like the - /// constructor, the list represents each key-value pair. - /// - /// The outer list represents each key-value pair in the Fields. Keys - /// which have multiple values are represented by multiple entries in this - /// list with the same key. - fn entries( - &mut self, _fields: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Make a deep copy of the Fields. Equivalent in behavior to calling the - /// `fields` constructor on the return value of `entries`. The resulting - /// `fields` is mutable. - fn clone( - &mut self, _fields: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::HostFutureTrailers for HermesState { - /// Returns the contents of the trailers, or an error which occurred, - /// once the future is ready. - /// - /// The outer `option` represents future readiness. Users can wait on this - /// `option` to become `some` using the `subscribe` method. - /// - /// The outer `result` is used to retrieve the trailers or error at most - /// once. It will be success on the first call in which the outer option - /// is `some`, and error on subsequent calls. - /// - /// The inner `result` represents that either the HTTP Request or Response - /// body, as well as any trailers, were received successfully, or that an - /// error occurred receiving them. The optional `trailers` indicates whether - /// or not trailers were present in the body. - /// - /// When some `trailers` are returned by this method, the `trailers` - /// resource is immutable, and a child. Use of the `set`, `append`, or - /// `delete` methods will return an error, and the resource must be - /// dropped before the parent `future-trailers` is dropped. - fn get( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result< - Option>, ErrorCode>, ()>>, - > { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::HostOutgoingBody for HermesState { - /// Returns a stream for writing the body contents. - /// - /// The returned `output-stream` is a child resource: it must be dropped - /// before the parent `outgoing-body` resource is dropped (or finished), - /// otherwise the `outgoing-body` drop or `finish` will trap. - /// - /// Returns success on the first call: the `output-stream` resource for - /// this `outgoing-body` may be retrieved at most once. Subsequent calls - /// will return error. - fn write( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result, ()>> { - todo!() - } - - /// Finalize an outgoing body, optionally providing trailers. This must be - /// called to signal that the response is complete. If the `outgoing-body` - /// is dropped without calling `outgoing-body.finalize`, the implementation - /// should treat the body as corrupted. - /// - /// Fails if the body\'s `outgoing-request` or `outgoing-response` was - /// constructed with a Content-Length header, and the contents written - /// to the body (via `write`) does not match the value given in the - /// Content-Length. - fn finish( - &mut self, _this: wasmtime::component::Resource, - _trailers: Option>, - ) -> wasmtime::Result> { - todo!() - } - - fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { - todo!() - } -} - -impl HostOutgoingResponse for HermesState { - /// Construct an `outgoing-response`, with a default `status-code` of `200`. - /// If a different `status-code` is needed, it must be set via the - /// `set-status-code` method. - /// - /// * `headers` is the HTTP Headers for the Response. - fn new( - &mut self, _headers: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the HTTP Status Code for the Response. - fn status_code( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result { - todo!() - } - - /// Set the HTTP Status Code for the Response. Fails if the status-code - /// given is not a valid http status code. - fn set_status_code( - &mut self, _rep: wasmtime::component::Resource, _status_code: StatusCode, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `outgoing-request` is dropped, or its ownership is transferred to - /// another component by e.g. `outgoing-handler.handle`. - fn headers( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Returns the resource corresponding to the outgoing Body for this Response. - /// - /// Returns success on the first call: the `outgoing-body` resource for - /// this `outgoing-response` can be retrieved at most once. Subsequent - /// calls will return error. - fn body( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result, ()>> { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::HostIncomingBody for HermesState { - /// Returns the contents of the body, as a stream of bytes. - /// - /// Returns success on first call: the stream representing the contents - /// can be retrieved at most once. Subsequent calls will return error. - /// - /// The returned `input-stream` resource is a child: it must be dropped - /// before the parent `incoming-body` is dropped, or consumed by - /// `incoming-body.finish`. - /// - /// This invariant ensures that the implementation can determine whether - /// the user is consuming the contents of the body, waiting on the - /// `future-trailers` to be ready, or neither. This allows for network - /// backpressure is to be applied when the user is consuming the body, - /// and for that backpressure to not inhibit delivery of the trailers if - /// the user does not read the entire body. - fn stream( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result, ()>> { - todo!() - } - - /// Takes ownership of `incoming-body`, and returns a `future-trailers`. - /// This function will trap if the `input-stream` child is still alive. - fn finish( - &mut self, _this: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - fn drop(&mut self, _rep: wasmtime::component::Resource) -> wasmtime::Result<()> { - todo!() - } -} - -impl HostIncomingResponse for HermesState { - /// Returns the status code from the incoming response. - fn status( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result { - todo!() - } - - /// Returns the headers from the incoming response. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `incoming-response` is dropped. - fn headers( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Returns the incoming body. May be called at most once. Returns error - /// if called additional times. - fn consume( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result, ()>> { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::HostResponseOutparam for HermesState { - /// Set the value of the `response-outparam` to either send a response, - /// or indicate an error. - /// - /// This method consumes the `response-outparam` to ensure that it is - /// called at most once. If it is never called, the implementation - /// will respond with an error. - /// - /// The user may provide an `error` to `response` to allow the - /// implementation determine how to respond with an HTTP error response. - fn set( - &mut self, _param: wasmtime::component::Resource, - _response: Result, ErrorCode>, - ) -> wasmtime::Result<()> { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::HostRequestOptions for HermesState { - /// Construct a default `request-options` value. - fn new(&mut self) -> wasmtime::Result> { - todo!() - } - - /// The timeout for the initial connect to the HTTP Server. - fn connect_timeout( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Set the timeout for the initial connect to the HTTP Server. An error - /// return value indicates that this timeout is not supported. - fn set_connect_timeout( - &mut self, _rep: wasmtime::component::Resource, _duration: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// The timeout for receiving the first byte of the Response body. - fn first_byte_timeout( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Set the timeout for receiving the first byte of the Response body. An - /// error return value indicates that this timeout is not supported. - fn set_first_byte_timeout( - &mut self, _rep: wasmtime::component::Resource, _duration: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// The timeout for receiving subsequent chunks of bytes in the Response - /// body stream. - fn between_bytes_timeout( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Set the timeout for receiving subsequent chunks of bytes in the Response - /// body stream. An error return value indicates that this timeout is not - /// supported. - fn set_between_bytes_timeout( - &mut self, _rep: wasmtime::component::Resource, _duration: Option, - ) -> wasmtime::Result> { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::HostOutgoingRequest for HermesState { - /// Construct a new `outgoing-request` with a default `method` of `GET`, and - /// `none` values for `path-with-query`, `scheme`, and `authority`. - /// - /// * `headers` is the HTTP Headers for the Request. - /// - /// It is possible to construct, or manipulate with the accessor functions - /// below, an `outgoing-request` with an invalid combination of `scheme` - /// and `authority`, or `headers` which are not permitted to be sent. - /// It is the obligation of the `outgoing-handler.handle` implementation - /// to reject invalid constructions of `outgoing-request`. - fn new( - &mut self, _headers: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Returns the resource corresponding to the outgoing Body for this - /// Request. - /// - /// Returns success on the first call: the `outgoing-body` resource for - /// this `outgoing-request` can be retrieved at most once. Subsequent - /// calls will return error. - fn body( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result, ()>> { - todo!() - } - - /// Get the Method for the Request. - fn method( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result { - todo!() - } - - /// Set the Method for the Request. Fails if the string present in a - /// `method.other` argument is not a syntactically valid method. - fn set_method( - &mut self, _rep: wasmtime::component::Resource, _method: Method, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the combination of the HTTP Path and Query for the Request. - /// When `none`, this represents an empty Path and empty Query. - fn path_with_query( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Set the combination of the HTTP Path and Query for the Request. - /// When `none`, this represents an empty Path and empty Query. Fails is the - /// string given is not a syntactically valid path and query uri component. - fn set_path_with_query( - &mut self, _rep: wasmtime::component::Resource, - _path_with_query: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. - fn scheme( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Set the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. Fails if the - /// string given is not a syntactically valid uri scheme. - fn set_scheme( - &mut self, _rep: wasmtime::component::Resource, _scheme: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the HTTP Authority for the Request. A value of `none` may be used - /// with Related Schemes which do not require an Authority. The HTTP and - /// HTTPS schemes always require an authority. - fn authority( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Set the HTTP Authority for the Request. A value of `none` may be used - /// with Related Schemes which do not require an Authority. The HTTP and - /// HTTPS schemes always require an authority. Fails if the string given is - /// not a syntactically valid uri authority. - fn set_authority( - &mut self, _rep: wasmtime::component::Resource, _authority: Option, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `outgoing-request` is dropped, or its ownership is transferred to - /// another component by e.g. `outgoing-handler.handle`. - fn headers( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::HostIncomingRequest for HermesState { - /// Returns the method of the incoming request. - fn method( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result { - todo!() - } - - /// Returns the path with query parameters from the request, as a string. - fn path_with_query( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Returns the protocol scheme from the request. - fn scheme( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Returns the authority from the request, if it was present. - fn authority( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Get the `headers` associated with the request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// The `headers` returned are a child resource: it must be dropped before - /// the parent `incoming-request` is dropped. Dropping this - /// `incoming-request` before all children are dropped will trap. - fn headers( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } - - /// Gives the `incoming-body` associated with this request. Will only - /// return success at most once, and subsequent calls will return error. - fn consume( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result, ()>> { - todo!() - } - - fn drop( - &mut self, _rep: wasmtime::component::Resource, - ) -> wasmtime::Result<()> { - todo!() - } -} - -impl http::types::Host for HermesState { - /// Attempts to extract a http-related `error` from the wasi:io `error` - /// provided. - /// - /// Stream operations which return - /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of - /// type `wasi:io/error/error` with more information about the operation - /// that failed. This payload can be passed through to this function to see - /// if there\'s http-related information about the error to return. - /// - /// Note that this function is fallible because not all io-errors are - /// http-related errors. - fn http_error_code( - &mut self, _err: wasmtime::component::Resource, - ) -> wasmtime::Result> { - todo!() - } -} - -impl http::outgoing_handler::Host for HermesState { - /// This function is invoked with an outgoing HTTP Request, and it returns - /// a resource `future-incoming-response` which represents an HTTP Response - /// which may arrive in the future. - /// - /// The `options` argument accepts optional parameters for the HTTP - /// protocol\'s transport layer. - /// - /// This function may return an error if the `outgoing-request` is invalid - /// or not allowed to be made. Otherwise, protocol errors are reported - /// through the `future-incoming-response`. - fn handle( - &mut self, _request: wasmtime::component::Resource, - _options: Option>, - ) -> wasmtime::Result, ErrorCode>> - { - todo!() - } -} diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs similarity index 71% rename from hermes/bin/src/runtime_extensions/wasi/io/error.rs rename to hermes/bin/src/runtime_extensions/wasi/io/error/host.rs index 3e4f0bea9..c83020e96 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs @@ -1,22 +1,10 @@ -//! WASI IO Error +//! IO Error host implementation for WASM runtime. use crate::{ - runtime_extensions::{ - bindings::wasi::io::error::{Error, Host, HostError}, - state::{Context, Stateful}, - }, + runtime_extensions::bindings::wasi::io::error::{Error, Host, HostError}, state::HermesState, }; -/// WASI State -pub(crate) struct State {} - -impl Stateful for State { - fn new(_ctx: &Context) -> Self { - Self {} - } -} - impl HostError for HermesState { /// Returns a string that is suitable to assist humans in debugging /// this error. diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs new file mode 100644 index 000000000..2c8a5f9a6 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs @@ -0,0 +1,14 @@ +//! IO Error runtime extension implementation. + +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; + +/// WASI State +pub(crate) struct State {} + +impl Stateful for State { + fn new(_ctx: &Context) -> Self { + Self {} + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs similarity index 96% rename from hermes/bin/src/runtime_extensions/wasi/io/streams.rs rename to hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs index 26385b746..945924104 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs @@ -1,24 +1,12 @@ -//! WASI IO Streams +//! IO Streams host implementation for WASM runtime. use crate::{ - runtime_extensions::{ - bindings::wasi::io::streams::{ - Host, HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, - }, - state::{Context, Stateful}, + runtime_extensions::bindings::wasi::io::streams::{ + Host, HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, }, state::HermesState, }; -/// WASI State -pub(crate) struct State {} - -impl Stateful for State { - fn new(_ctx: &Context) -> Self { - Self {} - } -} - impl HostInputStream for HermesState { /// Perform a non-blocking read from the stream. /// diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs new file mode 100644 index 000000000..68d0b1cb6 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs @@ -0,0 +1,14 @@ +//! IO Streams runtime extension implementation. + +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; + +/// WASI State +pub(crate) struct State {} + +impl Stateful for State { + fn new(_ctx: &Context) -> Self { + Self {} + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs similarity index 71% rename from hermes/bin/src/runtime_extensions/wasi/random/insecure.rs rename to hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs index d6573e1cd..05efa3e72 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs @@ -1,21 +1,6 @@ -//! Insecure RNG +//! Insecure RNG host implementation for WASM runtime. -use crate::{ - runtime_extensions::{ - bindings::wasi::random::insecure::Host, - state::{Context, Stateful}, - }, - state::HermesState, -}; - -/// WASI State -pub(crate) struct State {} - -impl Stateful for State { - fn new(_ctx: &Context) -> Self { - Self {} - } -} +use crate::{runtime_extensions::bindings::wasi::random::insecure::Host, state::HermesState}; impl Host for HermesState { /// Return `len` insecure pseudo-random bytes. diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs new file mode 100644 index 000000000..5167521d1 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs @@ -0,0 +1,14 @@ +//! Insecure RNG runtime extension implementation. + +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; + +/// WASI State +pub(crate) struct State {} + +impl Stateful for State { + fn new(_ctx: &Context) -> Self { + Self {} + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs similarity index 76% rename from hermes/bin/src/runtime_extensions/wasi/random/insecure_seed.rs rename to hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs index 22d7d2987..2037d52b7 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs @@ -1,21 +1,7 @@ -//! Insecure RNG +//! Insecure RNG seed host implementation for WASM runtime. -use crate::{ - runtime_extensions::{ - bindings::wasi::random::insecure_seed::Host, - state::{Context, Stateful}, - }, - state::HermesState, -}; +use crate::{runtime_extensions::bindings::wasi::random::insecure_seed::Host, state::HermesState}; -/// WASI State -pub(crate) struct State {} - -impl Stateful for State { - fn new(_ctx: &Context) -> Self { - Self {} - } -} impl Host for HermesState { /// Return a 128-bit value that may contain a pseudo-random value. /// diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs new file mode 100644 index 000000000..c18a06d7c --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs @@ -0,0 +1,14 @@ +//! Insecure RNG seed runtime extension implementation. + +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; + +/// WASI State +pub(crate) struct State {} + +impl Stateful for State { + fn new(_ctx: &Context) -> Self { + Self {} + } +} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs similarity index 79% rename from hermes/bin/src/runtime_extensions/wasi/random/secure.rs rename to hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs index 9334edbc7..93f0f9c1e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs @@ -1,21 +1,6 @@ -//! Random RNG +//! Random RNG host implementation for WASM runtime. -use crate::{ - runtime_extensions::{ - bindings::wasi::random::random::Host, - state::{Context, Stateful}, - }, - state::HermesState, -}; - -/// WASI State -pub(crate) struct State {} - -impl Stateful for State { - fn new(_ctx: &Context) -> Self { - Self {} - } -} +use crate::{runtime_extensions::bindings::wasi::random::random::Host, state::HermesState}; impl Host for HermesState { /// Return `len` cryptographically-secure random or pseudo-random bytes. diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs new file mode 100644 index 000000000..f98cb3bb0 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs @@ -0,0 +1,14 @@ +//! Random RNG runtime extension implementation. + +use crate::runtime_extensions::state::{Context, Stateful}; + +mod host; + +/// WASI State +pub(crate) struct State {} + +impl Stateful for State { + fn new(_ctx: &Context) -> Self { + Self {} + } +} From 24ae67275602dde8878b32db1968cfcd5678b4cc Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 14:32:38 +0200 Subject: [PATCH 06/52] add on cron event impl --- hermes/bin/src/event_queue/event.rs | 2 +- .../runtime_extensions/hermes/cron/event.rs | 29 +++++++++++++++++++ .../src/runtime_extensions/hermes/cron/mod.rs | 1 + hermes/bin/src/wasm/module.rs | 9 ++---- 4 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 hermes/bin/src/runtime_extensions/hermes/cron/event.rs diff --git a/hermes/bin/src/event_queue/event.rs b/hermes/bin/src/event_queue/event.rs index 554391781..b357ffa14 100644 --- a/hermes/bin/src/event_queue/event.rs +++ b/hermes/bin/src/event_queue/event.rs @@ -16,5 +16,5 @@ pub trait HermesEventPayload: Send { /// # Returns /// /// An `anyhow::Result` indicating the success or failure of the payload execution. - fn execute(&self, executor: &mut ModuleInstance) -> anyhow::Result<()>; + fn execute(&self, module: &mut ModuleInstance) -> anyhow::Result<()>; } diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/event.rs b/hermes/bin/src/runtime_extensions/hermes/cron/event.rs new file mode 100644 index 000000000..64d7228e1 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/cron/event.rs @@ -0,0 +1,29 @@ +//! Cron runtime extension event handler implementation. + +use crate::{ + event_queue::event::HermesEventPayload, + runtime_extensions::bindings::hermes::cron::api::CronTagged, +}; + +/// +struct OnCronEvent { + /// + tag: CronTagged, + /// + last: bool, +} + +impl HermesEventPayload for OnCronEvent { + fn event_name(&self) -> &str { + "on-cron" + } + + fn execute(&self, module: &mut crate::wasm::module::ModuleInstance) -> anyhow::Result<()> { + module.instance.hermes_cron_event().call_on_cron( + &mut module.store, + &self.tag, + self.last, + )?; + Ok(()) + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs index d40a42c5e..27b6ab0b7 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs @@ -2,6 +2,7 @@ use crate::runtime_extensions::state::{Context, Stateful}; +mod event; mod host; /// State diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index ea5713bee..febd36a31 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -29,9 +29,9 @@ struct BadWASMModuleError(String); /// It is used to interact with the WASM module. pub(crate) struct ModuleInstance { /// `wasmtime::Store` entity - pub(crate) _store: WasmStore, + pub(crate) store: WasmStore, /// `Instance` entity - pub(crate) _instance: bindings::Hermes, + pub(crate) instance: bindings::Hermes, } /// Structure defines an abstraction over the WASM module @@ -102,10 +102,7 @@ impl Module { let (instance, _) = bindings::Hermes::instantiate_pre(&mut store, &self.pre_instance) .map_err(|e| BadWASMModuleError(e.to_string()))?; - event.execute(&mut ModuleInstance { - _instance: instance, - _store: store, - })?; + event.execute(&mut ModuleInstance { store, instance })?; Ok(()) } } From 656598863372324cf623b5006c5475ac75bbade3 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 14:47:31 +0200 Subject: [PATCH 07/52] add cardano events --- .../hermes/cardano/event.rs | 87 +++++++++++++++++++ .../runtime_extensions/hermes/cardano/mod.rs | 1 + .../runtime_extensions/hermes/cron/event.rs | 6 +- wasm/wasi/wit/deps/hermes-cardano/api.wit | 6 ++ wasm/wasi/wit/deps/hermes-cardano/event.wit | 14 +-- 5 files changed, 101 insertions(+), 13 deletions(-) create mode 100644 hermes/bin/src/runtime_extensions/hermes/cardano/event.rs diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/event.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/event.rs new file mode 100644 index 000000000..af952b5ae --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/event.rs @@ -0,0 +1,87 @@ +//! Cardano Blockchain runtime extension event handler implementation. + +use crate::{ + event_queue::event::HermesEventPayload, + runtime_extensions::bindings::hermes::cardano::api::{ + BlockSrc, CardanoBlock, CardanoBlockchainId, CardanoTxn, + }, +}; + +/// On Cardano block event +struct OnCardanoBlockEvent { + /// The blockchain id the block originated from. + blockchain: CardanoBlockchainId, + /// This raw CBOR block data. + block: CardanoBlock, + /// Source information about where the block came from, and if we are at tip or not. + source: BlockSrc, +} + +impl HermesEventPayload for OnCardanoBlockEvent { + fn event_name(&self) -> &str { + "on-cardano-block" + } + + fn execute(&self, module: &mut crate::wasm::module::ModuleInstance) -> anyhow::Result<()> { + module + .instance + .hermes_cardano_event_on_block() + .call_on_cardano_block(&mut module.store, self.blockchain, &self.block, self.source)?; + Ok(()) + } +} + +/// On Cardano txn event +struct OnCardanoTxnEvent { + /// The blockchain id the block originated from. + blockchain: CardanoBlockchainId, + /// The slot the transaction is in. + slot: u64, + /// The offset in the block this transaction is at. + txn_index: u32, + /// The raw transaction data itself. + txn: CardanoTxn, +} + +impl HermesEventPayload for OnCardanoTxnEvent { + fn event_name(&self) -> &str { + "on-cardano-txn" + } + + fn execute(&self, module: &mut crate::wasm::module::ModuleInstance) -> anyhow::Result<()> { + module + .instance + .hermes_cardano_event_on_txn() + .call_on_cardano_txn( + &mut module.store, + self.blockchain, + self.slot, + self.txn_index, + &self.txn, + )?; + + Ok(()) + } +} + +/// On Cardano rollback event +struct OnCardanoRollback { + /// The blockchain id the block originated from. + blockchain: CardanoBlockchainId, + /// The slot the transaction is in. + slot: u64, +} + +impl HermesEventPayload for OnCardanoRollback { + fn event_name(&self) -> &str { + "on-cardano-rollback" + } + + fn execute(&self, module: &mut crate::wasm::module::ModuleInstance) -> anyhow::Result<()> { + module + .instance + .hermes_cardano_event_on_rollback() + .call_on_cardano_rollback(&mut module.store, self.blockchain, self.slot)?; + Ok(()) + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs index 543f86be9..d6c134dda 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs @@ -2,6 +2,7 @@ use crate::runtime_extensions::state::{Context, Stateful}; +mod event; mod host; /// State diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/event.rs b/hermes/bin/src/runtime_extensions/hermes/cron/event.rs index 64d7228e1..df6eeedde 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/event.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/event.rs @@ -5,11 +5,11 @@ use crate::{ runtime_extensions::bindings::hermes::cron::api::CronTagged, }; -/// +/// On cron event struct OnCronEvent { - /// + /// The tagged cron event that was triggered. tag: CronTagged, - /// + /// This cron event will not retrigger. last: bool, } diff --git a/wasm/wasi/wit/deps/hermes-cardano/api.wit b/wasm/wasi/wit/deps/hermes-cardano/api.wit index 77a419a25..e46902891 100644 --- a/wasm/wasi/wit/deps/hermes-cardano/api.wit +++ b/wasm/wasi/wit/deps/hermes-cardano/api.wit @@ -24,6 +24,12 @@ interface api { local-test-blockchain // A local isolated test blockchain. } + flags block-src { + tip, + node, + mithril + } + /// The Slot number to interact with variant slot { genesis, // The very start of the blockchain. diff --git a/wasm/wasi/wit/deps/hermes-cardano/event.wit b/wasm/wasi/wit/deps/hermes-cardano/event.wit index 780e06deb..5cbee8775 100644 --- a/wasm/wasi/wit/deps/hermes-cardano/event.wit +++ b/wasm/wasi/wit/deps/hermes-cardano/event.wit @@ -22,13 +22,7 @@ /// Cardano API Interface - Export ONLY interface event-on-block { - use api.{cardano-blockchain-id, cardano-block}; - - flags block-src { - tip, - node, - mithril - } + use api.{cardano-blockchain-id, cardano-block, block-src}; /// Triggered when a cardano block event fires. /// @@ -43,7 +37,7 @@ interface event-on-block { /// Returns: /// Nothing. /// - on-cardano-block: func(blockchain: cardano-blockchain-id, block: cardano-block, source:block-src); + on-cardano-block: func(blockchain: cardano-blockchain-id, block: cardano-block, source: block-src); } /// Cardano API Interface - Export ONLY @@ -64,7 +58,7 @@ interface event-on-txn { /// Returns: /// Nothing. /// - on-cardano-txn: func(blockchain: cardano-blockchain-id, slot:u64, txn-index: u32, txn: cardano-txn); + on-cardano-txn: func(blockchain: cardano-blockchain-id, slot: u64, txn-index: u32, txn: cardano-txn); } /// Cardano API Interface - Export ONLY @@ -83,7 +77,7 @@ interface event-on-rollback { /// Returns: /// Nothing. /// - on-cardano-rollback: func(blockchain: cardano-blockchain-id, slot:u64); + on-cardano-rollback: func(blockchain: cardano-blockchain-id, slot: u64); } From 8a175205aa76ba25e8c2631b116d06e5be28c148 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 16:14:13 +0200 Subject: [PATCH 08/52] add kv-update event --- .../runtime_extensions/hermes/cron/event.rs | 3 +- .../hermes/kv_store/event.rs | 29 +++++++++++++++++++ .../runtime_extensions/hermes/kv_store/mod.rs | 1 + 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 hermes/bin/src/runtime_extensions/hermes/kv_store/event.rs diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/event.rs b/hermes/bin/src/runtime_extensions/hermes/cron/event.rs index df6eeedde..20b1b36b7 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/event.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/event.rs @@ -19,7 +19,8 @@ impl HermesEventPayload for OnCronEvent { } fn execute(&self, module: &mut crate::wasm::module::ModuleInstance) -> anyhow::Result<()> { - module.instance.hermes_cron_event().call_on_cron( + // TODO (@stevenj): https://github.com/input-output-hk/hermes/issues/93 + let _res: bool = module.instance.hermes_cron_event().call_on_cron( &mut module.store, &self.tag, self.last, diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/event.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/event.rs new file mode 100644 index 000000000..42394b865 --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/event.rs @@ -0,0 +1,29 @@ +//! KV-Store runtime extension event handler implementation. + +use crate::{ + event_queue::event::HermesEventPayload, + runtime_extensions::bindings::hermes::kv_store::api::KvValues, +}; + +/// KV update event +struct KVUpdateEvent { + /// Key. + key: String, + /// Value. + value: KvValues, +} + +impl HermesEventPayload for KVUpdateEvent { + fn event_name(&self) -> &str { + "kv-update" + } + + fn execute(&self, module: &mut crate::wasm::module::ModuleInstance) -> anyhow::Result<()> { + module.instance.hermes_kv_store_event().call_kv_update( + &mut module.store, + &self.key, + &self.value, + )?; + Ok(()) + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs index 66dbea735..21fa3eb22 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs @@ -2,6 +2,7 @@ use crate::runtime_extensions::state::{Context, Stateful}; +mod event; mod host; /// State From d73d4b129c2c6168703aeb365d86e51a8ffb1b49 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 14 Feb 2024 16:16:55 +0200 Subject: [PATCH 09/52] remove reactor --- hermes/bin/src/lib.rs | 2 -- hermes/bin/src/reactor.rs | 42 --------------------------------------- 2 files changed, 44 deletions(-) delete mode 100644 hermes/bin/src/reactor.rs diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index 512867736..78d6a0016 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -2,8 +2,6 @@ //! This file exists, so that doc tests can be used inside binary crates. mod event_queue; -#[allow(missing_docs, clippy::missing_docs_in_private_items, dead_code)] -mod reactor; mod runtime_extensions; mod state; mod wasm; diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs deleted file mode 100644 index 00187eb28..000000000 --- a/hermes/bin/src/reactor.rs +++ /dev/null @@ -1,42 +0,0 @@ -use std::{ - sync::mpsc::{channel, Receiver, Sender}, - thread, -}; - -use crate::{event_queue::event::HermesEventPayload, wasm::module::Module}; - -pub(crate) struct HermesReactor { - wasm_module: Module, - - event_sender: Sender>, - event_receiver: Receiver>, -} - -impl HermesReactor { - fn event_execution_loop( - mut wasm_module: Module, event_receiver: Receiver>, - ) -> anyhow::Result<()> { - for event in event_receiver { - wasm_module.execute_event(event.as_ref())?; - } - Ok(()) - } - - pub(crate) fn new(app_name: String, module_bytes: &[u8]) -> anyhow::Result { - let wasm_module = Module::new(app_name, module_bytes)?; - let (event_sender, event_receiver) = channel(); - - Ok(Self { - wasm_module, - event_sender, - event_receiver, - }) - } - - pub(crate) fn run(self) -> anyhow::Result<()> { - let _events_thread = thread::spawn(|| { - Self::event_execution_loop(self.wasm_module, self.event_receiver).unwrap(); - }); - Ok(()) - } -} From 04bd112e01c4ef11fd2ef60b9120144f3dd8d532 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Thu, 15 Feb 2024 15:39:56 +0200 Subject: [PATCH 10/52] add HermesReactor --- hermes/bin/src/lib.rs | 2 ++ hermes/bin/src/main.rs | 2 ++ hermes/bin/src/reactor.rs | 59 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 hermes/bin/src/reactor.rs diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index 78d6a0016..3d3d3656d 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -2,6 +2,8 @@ //! This file exists, so that doc tests can be used inside binary crates. mod event_queue; +#[allow(dead_code)] +mod reactor; mod runtime_extensions; mod state; mod wasm; diff --git a/hermes/bin/src/main.rs b/hermes/bin/src/main.rs index 69b7bc9a8..5e10e3b91 100644 --- a/hermes/bin/src/main.rs +++ b/hermes/bin/src/main.rs @@ -1,6 +1,8 @@ //! The Hermes Node. mod event_queue; +#[allow(dead_code)] +mod reactor; mod runtime_extensions; mod state; mod wasm; diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs new file mode 100644 index 000000000..6eccbdf87 --- /dev/null +++ b/hermes/bin/src/reactor.rs @@ -0,0 +1,59 @@ +//! Hermes Reactor implementation. + +use std::{ + sync::mpsc::{channel, Receiver, Sender}, + thread, +}; + +use crate::{event_queue::event::HermesEventPayload, wasm::module::Module}; + +/// Thread panics error +#[derive(thiserror::Error, Debug)] +#[error("Thread '{0}' panic! internal error!")] +struct ThreadPanicsError(&'static str); + +/// Hermes Reactor struct +pub(crate) struct HermesReactor { + /// + wasm_module: Module, + + /// + event_sender: Sender>, + /// + event_receiver: Receiver>, +} + +impl HermesReactor { + /// + fn event_execution_loop( + mut wasm_module: Module, event_receiver: Receiver>, + ) -> anyhow::Result<()> { + for event in event_receiver { + wasm_module.execute_event(event.as_ref())?; + } + Ok(()) + } + + /// Create a new Hermes Reactor + pub(crate) fn new(app_name: String, module_bytes: &[u8]) -> anyhow::Result { + let wasm_module = Module::new(app_name, module_bytes)?; + let (event_sender, event_receiver) = channel(); + + Ok(Self { + wasm_module, + event_sender, + event_receiver, + }) + } + + /// + pub(crate) fn run(self) -> anyhow::Result<()> { + let events_thread = + thread::spawn(|| Self::event_execution_loop(self.wasm_module, self.event_receiver)); + + events_thread + .join() + .map_err(|_| ThreadPanicsError("events handler"))??; + Ok(()) + } +} From bd2a4fc3dbd93bafbc4d01fb18a3aac223805db0 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 16 Feb 2024 10:56:43 +0200 Subject: [PATCH 11/52] add Hermes Event queue types --- hermes/bin/src/event_queue/mod.rs | 22 +++++++++++++++ hermes/bin/src/reactor.rs | 26 +++++++++--------- hermes/bin/src/runtime_extensions/mod.rs | 4 +-- hermes/bin/src/runtime_extensions/state.rs | 32 ++++++++++++++++++---- hermes/bin/src/state.rs | 27 +++++++----------- hermes/bin/src/wasm/module.rs | 7 ++--- 6 files changed, 75 insertions(+), 43 deletions(-) diff --git a/hermes/bin/src/event_queue/mod.rs b/hermes/bin/src/event_queue/mod.rs index 2ff22d7c4..a87f3adb7 100644 --- a/hermes/bin/src/event_queue/mod.rs +++ b/hermes/bin/src/event_queue/mod.rs @@ -1,3 +1,25 @@ //! Hermes event queue implementation. +use std::sync::mpsc::{channel, Receiver, Sender}; + pub(crate) mod event; + +/// Initialize Hermes event queue +pub(crate) fn new() -> (HermesEventQueueIn, HermesEventQueueOut) { + let (sender, receiver) = channel(); + (HermesEventQueueIn(sender), HermesEventQueueOut(receiver)) +} + +/// +pub(crate) struct HermesEventQueueIn(Sender>); + +/// +pub(crate) struct HermesEventQueueOut(Receiver>); + +impl Iterator for HermesEventQueueOut { + type Item = Box; + + fn next(&mut self) -> Option { + self.0.recv().ok() + } +} diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 6eccbdf87..9c54e8a27 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -1,11 +1,11 @@ //! Hermes Reactor implementation. -use std::{ - sync::mpsc::{channel, Receiver, Sender}, - thread, -}; +use std::thread; -use crate::{event_queue::event::HermesEventPayload, wasm::module::Module}; +use crate::{ + event_queue::{self, HermesEventQueueIn, HermesEventQueueOut}, + wasm::module::Module, +}; /// Thread panics error #[derive(thiserror::Error, Debug)] @@ -18,17 +18,17 @@ pub(crate) struct HermesReactor { wasm_module: Module, /// - event_sender: Sender>, + event_queue_in: HermesEventQueueIn, /// - event_receiver: Receiver>, + event_queue_out: HermesEventQueueOut, } impl HermesReactor { /// fn event_execution_loop( - mut wasm_module: Module, event_receiver: Receiver>, + mut wasm_module: Module, event_queue_out: HermesEventQueueOut, ) -> anyhow::Result<()> { - for event in event_receiver { + for event in event_queue_out { wasm_module.execute_event(event.as_ref())?; } Ok(()) @@ -37,19 +37,19 @@ impl HermesReactor { /// Create a new Hermes Reactor pub(crate) fn new(app_name: String, module_bytes: &[u8]) -> anyhow::Result { let wasm_module = Module::new(app_name, module_bytes)?; - let (event_sender, event_receiver) = channel(); + let (event_queue_in, event_queue_out) = event_queue::new(); Ok(Self { wasm_module, - event_sender, - event_receiver, + event_queue_in, + event_queue_out, }) } /// pub(crate) fn run(self) -> anyhow::Result<()> { let events_thread = - thread::spawn(|| Self::event_execution_loop(self.wasm_module, self.event_receiver)); + thread::spawn(|| Self::event_execution_loop(self.wasm_module, self.event_queue_out)); events_thread .join() diff --git a/hermes/bin/src/runtime_extensions/mod.rs b/hermes/bin/src/runtime_extensions/mod.rs index da720dfce..a3823bb2e 100644 --- a/hermes/bin/src/runtime_extensions/mod.rs +++ b/hermes/bin/src/runtime_extensions/mod.rs @@ -22,7 +22,7 @@ pub(crate) mod wasi; /// Example of how to call the autogenerated entry points #[allow(dead_code)] fn example() -> anyhow::Result<()> { - use crate::runtime_extensions::state::{Context, Stateful}; + use crate::runtime_extensions::state::Context; // Configure an `Engine` and compile the `Component` that is being run for // the application. @@ -49,7 +49,7 @@ fn example() -> anyhow::Result<()> { // to the exports of the component. let mut store = Store::new( &engine, - HermesState::new(&Context::new("my-app".to_string())), + HermesState::new(Context::new("my-app".to_string())), ); // diff --git a/hermes/bin/src/runtime_extensions/state.rs b/hermes/bin/src/runtime_extensions/state.rs index 7f61b2c2d..eb27056d8 100644 --- a/hermes/bin/src/runtime_extensions/state.rs +++ b/hermes/bin/src/runtime_extensions/state.rs @@ -2,6 +2,32 @@ use rusty_ulid::Ulid; +use super::{hermes, wasi}; + +/// All Hermes runtime extensions states need to implement this. +pub(crate) trait Stateful { + /// Initial state for the given context + fn new(ctx: &Context) -> Self; +} + +/// All runtime extensions state +pub(crate) struct State { + /// Hermes custom extensions state + _hermes: hermes::State, + + /// WASI standard extensions state + _wasi: wasi::State, +} + +impl Stateful for State { + fn new(ctx: &Context) -> Self { + Self { + _hermes: hermes::State::new(ctx), + _wasi: wasi::State::new(ctx), + } + } +} + /// A WASM module's context structure, which is intended to be passed to the /// `wasmtime::Store` during the WASM module's state initialization process. #[derive(Clone)] @@ -60,9 +86,3 @@ impl Context { self.counter } } - -/// All Hermes runtime extensions states need to implement this. -pub(crate) trait Stateful { - /// Initial state for the given context - fn new(ctx: &Context) -> Self; -} diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/state.rs index 131116755..b192bebcf 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/state.rs @@ -1,30 +1,23 @@ //! Hermes state implementation. -use crate::runtime_extensions::{ - hermes, - state::{Context, Stateful}, - wasi, -}; +use crate::runtime_extensions::state::{Context, State, Stateful}; #[allow(dead_code)] /// State for Hermes runtime pub(crate) struct HermesState { - /// Hermes custom extensions state - pub hermes: hermes::State, - - /// WASI standard extensions state - pub wasi: wasi::State, + /// Runtime extensions state + pub(crate) state: State, /// The context of the wasm modules using this State. - pub ctx: Context, + pub(crate) ctx: Context, } -impl Stateful for HermesState { - fn new(ctx: &Context) -> HermesState { - HermesState { - hermes: hermes::State::new(ctx), - wasi: wasi::State::new(ctx), - ctx: ctx.clone(), +impl HermesState { + /// Creates a new instance of the `HermesState`. + pub(crate) fn new(ctx: Context) -> HermesState { + Self { + state: State::new(&ctx), + ctx, } } } diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index febd36a31..da4cd8446 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -11,10 +11,7 @@ use wasmtime::{ use crate::{ event_queue::event::HermesEventPayload, - runtime_extensions::{ - bindings, - state::{Context, Stateful}, - }, + runtime_extensions::{bindings, state::Context}, state::HermesState, wasm::engine::Engine, }; @@ -96,7 +93,7 @@ impl Module { #[allow(dead_code)] pub(crate) fn execute_event(&mut self, event: &dyn HermesEventPayload) -> anyhow::Result<()> { self.context.use_for(event.event_name().to_string()); - let state = HermesState::new(&self.context); + let state = HermesState::new(self.context.clone()); let mut store = WasmStore::new(&self.engine, state); let (instance, _) = bindings::Hermes::instantiate_pre(&mut store, &self.pre_instance) From 4da86ec5ca1dc607b193cf905c9bb418a51d2b13 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 16 Feb 2024 14:22:40 +0200 Subject: [PATCH 12/52] wip --- hermes/bin/src/event_queue/mod.rs | 1 + hermes/bin/src/reactor.rs | 10 ++- .../runtime_extensions/hermes/binary/mod.rs | 4 +- .../runtime_extensions/hermes/cardano/mod.rs | 4 +- .../src/runtime_extensions/hermes/cbor/mod.rs | 4 +- .../src/runtime_extensions/hermes/cron/mod.rs | 4 +- .../runtime_extensions/hermes/crypto/mod.rs | 4 +- .../src/runtime_extensions/hermes/hash/mod.rs | 4 +- .../src/runtime_extensions/hermes/init/mod.rs | 4 +- .../src/runtime_extensions/hermes/json/mod.rs | 4 +- .../runtime_extensions/hermes/kv_store/mod.rs | 4 +- .../hermes/localtime/mod.rs | 4 +- .../runtime_extensions/hermes/logging/mod.rs | 4 +- .../bin/src/runtime_extensions/hermes/mod.rs | 26 +++---- hermes/bin/src/runtime_extensions/mod.rs | 2 +- hermes/bin/src/runtime_extensions/state.rs | 70 ++----------------- .../src/runtime_extensions/wasi/cli/mod.rs | 4 +- .../src/runtime_extensions/wasi/clocks/mod.rs | 8 +-- .../wasi/clocks/monotonic/mod.rs | 4 +- .../wasi/clocks/wall/mod.rs | 4 +- .../runtime_extensions/wasi/filesystem/mod.rs | 4 +- .../src/runtime_extensions/wasi/http/mod.rs | 4 +- .../runtime_extensions/wasi/io/error/mod.rs | 4 +- .../bin/src/runtime_extensions/wasi/io/mod.rs | 8 +-- .../runtime_extensions/wasi/io/streams/mod.rs | 4 +- hermes/bin/src/runtime_extensions/wasi/mod.rs | 16 ++--- .../wasi/random/insecure/mod.rs | 4 +- .../wasi/random/insecure_seed/mod.rs | 4 +- .../src/runtime_extensions/wasi/random/mod.rs | 10 +-- .../wasi/random/secure/mod.rs | 4 +- hermes/bin/src/state.rs | 9 +-- hermes/bin/src/wasm/context.rs | 62 ++++++++++++++++ hermes/bin/src/wasm/mod.rs | 1 + hermes/bin/src/wasm/module.rs | 10 +-- 34 files changed, 162 insertions(+), 155 deletions(-) create mode 100644 hermes/bin/src/wasm/context.rs diff --git a/hermes/bin/src/event_queue/mod.rs b/hermes/bin/src/event_queue/mod.rs index a87f3adb7..9f12b4c65 100644 --- a/hermes/bin/src/event_queue/mod.rs +++ b/hermes/bin/src/event_queue/mod.rs @@ -11,6 +11,7 @@ pub(crate) fn new() -> (HermesEventQueueIn, HermesEventQueueOut) { } /// +#[derive(Clone)] pub(crate) struct HermesEventQueueIn(Sender>); /// diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 9c54e8a27..dbcd89236 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -3,7 +3,8 @@ use std::thread; use crate::{ - event_queue::{self, HermesEventQueueIn, HermesEventQueueOut}, + event_queue::{self, HermesEventQueueOut}, + runtime_extensions::state::{State, Stateful}, wasm::module::Module, }; @@ -18,7 +19,8 @@ pub(crate) struct HermesReactor { wasm_module: Module, /// - event_queue_in: HermesEventQueueIn, + state: State, + /// event_queue_out: HermesEventQueueOut, } @@ -39,9 +41,11 @@ impl HermesReactor { let wasm_module = Module::new(app_name, module_bytes)?; let (event_queue_in, event_queue_out) = event_queue::new(); + let state = State::new(&event_queue_in); + Ok(Self { wasm_module, - event_queue_in, + state, event_queue_out, }) } diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs index 69a2afd33..277743074 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs @@ -1,6 +1,6 @@ //! Binary runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs index d6c134dda..67736434a 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs @@ -1,6 +1,6 @@ //! Cardano Blockchain runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod event; mod host; @@ -9,7 +9,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs index 24972f85c..4103d6211 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs @@ -1,6 +1,6 @@ //! CBOR runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs index 27b6ab0b7..4d58e9956 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs @@ -1,6 +1,6 @@ //! Cron runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod event; mod host; @@ -9,7 +9,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs index 6cbb6a69d..f1d5c1a03 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs @@ -1,6 +1,6 @@ //! Crypto runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs index db70a87d0..3799fcbaf 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs @@ -1,6 +1,6 @@ //! Hash runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 0eee10a7b..f714e11c1 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,12 +1,12 @@ //! Init runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; /// State pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs index 68389f3f6..69ca62c0f 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs @@ -1,6 +1,6 @@ //! JSON runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs index 21fa3eb22..2b7ba0c17 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs @@ -1,6 +1,6 @@ //! KV-Store runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod event; mod host; @@ -9,7 +9,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs index 9472a28b9..547109339 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs @@ -1,6 +1,6 @@ //! Localtime runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs index dc7d340eb..a9f311854 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs @@ -1,6 +1,6 @@ //! Logging runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_ctx: &HermesEventQueueIn) -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/mod.rs b/hermes/bin/src/runtime_extensions/hermes/mod.rs index 3e01852ed..e6cb7dc4d 100644 --- a/hermes/bin/src/runtime_extensions/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/mod.rs @@ -1,6 +1,6 @@ //! Hermes runtime extensions implementations - HERMES custom extensions -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; pub(crate) mod binary; pub(crate) mod cardano; @@ -41,19 +41,19 @@ pub(crate) struct State { } impl Stateful for State { - fn new(ctx: &Context) -> Self { + fn new(event_queue_in: &HermesEventQueueIn) -> Self { Self { - _binary: binary::State::new(ctx), - _cardano: cardano::State::new(ctx), - _cbor: cbor::State::new(ctx), - _cron: cron::State::new(ctx), - _crypto: crypto::State::new(ctx), - _hash: hash::State::new(ctx), - _init: init::State::new(ctx), - _json: json::State::new(ctx), - _kv_store: kv_store::State::new(ctx), - _localtime: localtime::State::new(ctx), - _logging: logging::State::new(ctx), + _binary: binary::State::new(event_queue_in), + _cardano: cardano::State::new(event_queue_in), + _cbor: cbor::State::new(event_queue_in), + _cron: cron::State::new(event_queue_in), + _crypto: crypto::State::new(event_queue_in), + _hash: hash::State::new(event_queue_in), + _init: init::State::new(event_queue_in), + _json: json::State::new(event_queue_in), + _kv_store: kv_store::State::new(event_queue_in), + _localtime: localtime::State::new(event_queue_in), + _logging: logging::State::new(event_queue_in), } } } diff --git a/hermes/bin/src/runtime_extensions/mod.rs b/hermes/bin/src/runtime_extensions/mod.rs index a3823bb2e..3d747342f 100644 --- a/hermes/bin/src/runtime_extensions/mod.rs +++ b/hermes/bin/src/runtime_extensions/mod.rs @@ -22,7 +22,7 @@ pub(crate) mod wasi; /// Example of how to call the autogenerated entry points #[allow(dead_code)] fn example() -> anyhow::Result<()> { - use crate::runtime_extensions::state::Context; + use crate::wasm::context::Context; // Configure an `Engine` and compile the `Component` that is being run for // the application. diff --git a/hermes/bin/src/runtime_extensions/state.rs b/hermes/bin/src/runtime_extensions/state.rs index eb27056d8..7bf2e7ca0 100644 --- a/hermes/bin/src/runtime_extensions/state.rs +++ b/hermes/bin/src/runtime_extensions/state.rs @@ -1,13 +1,12 @@ //! Hermes runtime extensions state. -use rusty_ulid::Ulid; - use super::{hermes, wasi}; +use crate::event_queue::HermesEventQueueIn; /// All Hermes runtime extensions states need to implement this. pub(crate) trait Stateful { /// Initial state for the given context - fn new(ctx: &Context) -> Self; + fn new(event_eueue_in: &HermesEventQueueIn) -> Self; } /// All runtime extensions state @@ -20,69 +19,10 @@ pub(crate) struct State { } impl Stateful for State { - fn new(ctx: &Context) -> Self { - Self { - _hermes: hermes::State::new(ctx), - _wasi: wasi::State::new(ctx), - } - } -} - -/// A WASM module's context structure, which is intended to be passed to the -/// `wasmtime::Store` during the WASM module's state initialization process. -#[derive(Clone)] -pub(crate) struct Context { - /// Hermes application name - app_name: String, - - /// module ULID id - module_id: Ulid, - - /// event name to be executed - event_name: Option, - - /// module's execution counter - counter: u64, -} - -impl Context { - /// Creates a new instance of the `Context`. - pub(crate) fn new(app_name: String) -> Self { + fn new(event_eueue_in: &HermesEventQueueIn) -> Self { Self { - app_name, - module_id: Ulid::generate(), - event_name: None, - counter: 0, + _hermes: hermes::State::new(event_eueue_in), + _wasi: wasi::State::new(event_eueue_in), } } - - /// Increments the module's execution counter and sets the event name to be executed - pub(crate) fn use_for(&mut self, event_name: String) { - self.event_name = Some(event_name); - self.counter += 1; - } - - /// Get the application name - #[allow(dead_code)] - pub(crate) fn app_name(&self) -> &str { - &self.app_name - } - - /// Get the module id - #[allow(dead_code)] - pub(crate) fn module_id(&self) -> &Ulid { - &self.module_id - } - - /// Get the event name - #[allow(dead_code)] - pub(crate) fn event_name(&self) -> Option<&String> { - self.event_name.as_ref() - } - - /// Get the counter value - #[allow(dead_code)] - pub(crate) fn counter(&self) -> u64 { - self.counter - } } diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs index 8aebdf8a8..3fe6a7cc8 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs @@ -1,6 +1,6 @@ //! CLI runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs index f7b982f12..aa6119b68 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI - Clock implementations -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod monotonic; mod wall; @@ -14,10 +14,10 @@ pub(crate) struct State { } impl Stateful for State { - fn new(ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self { - _monotonic: monotonic::State::new(ctx), - _wall: wall::State::new(ctx), + _monotonic: monotonic::State::new(_event_queue_in), + _wall: wall::State::new(_event_queue_in), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs index 23cf470f0..732df12e1 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs @@ -1,6 +1,6 @@ //! Monotonic clock runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs index cfdcad95d..c0ee537e0 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs @@ -1,6 +1,6 @@ //! Wall clock runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs index aa77b84c2..26c079a49 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs @@ -1,6 +1,6 @@ //! Filesystem runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs index a585b9268..f900df3c9 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs @@ -1,6 +1,6 @@ //! HTTP runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs index 2c8a5f9a6..d2a785c21 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs @@ -1,6 +1,6 @@ //! IO Error runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/io/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs index ba46e0ec6..8f9109d04 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI IO Implementation -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; pub(crate) mod error; pub(crate) mod streams; @@ -14,10 +14,10 @@ pub(crate) struct State { } impl Stateful for State { - fn new(ctx: &Context) -> Self { + fn new(event_queue_in: &HermesEventQueueIn) -> Self { Self { - _error: error::State::new(ctx), - _streams: streams::State::new(ctx), + _error: error::State::new(event_queue_in), + _streams: streams::State::new(event_queue_in), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs index 68d0b1cb6..678e543d0 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs @@ -1,6 +1,6 @@ //! IO Streams runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/mod.rs b/hermes/bin/src/runtime_extensions/wasi/mod.rs index 3e7afb002..80b7f75a1 100644 --- a/hermes/bin/src/runtime_extensions/wasi/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/mod.rs @@ -1,6 +1,6 @@ //! Hermes runtime extensions implementations - WASI standard extensions -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; pub(crate) mod cli; pub(crate) mod clocks; @@ -26,14 +26,14 @@ pub(crate) struct State { } impl Stateful for State { - fn new(ctx: &Context) -> Self { + fn new(event_queue_in: &HermesEventQueueIn) -> Self { Self { - _cli: cli::State::new(ctx), - _clocks: clocks::State::new(ctx), - _filesystem: filesystem::State::new(ctx), - _http: http::State::new(ctx), - _io: io::State::new(ctx), - _random: random::State::new(ctx), + _cli: cli::State::new(event_queue_in), + _clocks: clocks::State::new(event_queue_in), + _filesystem: filesystem::State::new(event_queue_in), + _http: http::State::new(event_queue_in), + _io: io::State::new(event_queue_in), + _random: random::State::new(event_queue_in), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs index 5167521d1..1fd68efe9 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs @@ -1,6 +1,6 @@ //! Insecure RNG runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs index c18a06d7c..46d14b6a7 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs @@ -1,6 +1,6 @@ //! Insecure RNG seed runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs index a1e32999e..9958e79b6 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI - Random implementations -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; pub(crate) mod insecure; pub(crate) mod insecure_seed; @@ -17,11 +17,11 @@ pub(crate) struct State { } impl Stateful for State { - fn new(ctx: &Context) -> Self { + fn new(event_queue_in: &HermesEventQueueIn) -> Self { Self { - _insecure: insecure::State::new(ctx), - _insecure_seed: insecure_seed::State::new(ctx), - _secure: secure::State::new(ctx), + _insecure: insecure::State::new(event_queue_in), + _insecure_seed: insecure_seed::State::new(event_queue_in), + _secure: secure::State::new(event_queue_in), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs index f98cb3bb0..eddcccf5d 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs @@ -1,6 +1,6 @@ //! Random RNG runtime extension implementation. -use crate::runtime_extensions::state::{Context, Stateful}; +use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &Context) -> Self { + fn new(_event_queue_in: &HermesEventQueueIn) -> Self { Self {} } } diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/state.rs index b192bebcf..209609bd6 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/state.rs @@ -1,6 +1,6 @@ //! Hermes state implementation. -use crate::runtime_extensions::state::{Context, State, Stateful}; +use crate::{runtime_extensions::state::State, wasm::context::Context}; #[allow(dead_code)] /// State for Hermes runtime @@ -14,10 +14,7 @@ pub(crate) struct HermesState { impl HermesState { /// Creates a new instance of the `HermesState`. - pub(crate) fn new(ctx: Context) -> HermesState { - Self { - state: State::new(&ctx), - ctx, - } + pub(crate) fn new(ctx: Context, state: State) -> HermesState { + Self { state, ctx } } } diff --git a/hermes/bin/src/wasm/context.rs b/hermes/bin/src/wasm/context.rs new file mode 100644 index 000000000..bc21e171a --- /dev/null +++ b/hermes/bin/src/wasm/context.rs @@ -0,0 +1,62 @@ +//! WASM module execution context. + +use rusty_ulid::Ulid; + +/// A WASM module's context structure, which is intended to be passed to the +/// `wasmtime::Store` during the WASM module's state initialization process. +#[derive(Clone)] +pub(crate) struct Context { + /// Hermes application name + app_name: String, + + /// module ULID id + module_id: Ulid, + + /// event name to be executed + event_name: Option, + + /// module's execution counter + counter: u64, +} + +impl Context { + /// Creates a new instance of the `Context`. + pub(crate) fn new(app_name: String) -> Self { + Self { + app_name, + module_id: Ulid::generate(), + event_name: None, + counter: 0, + } + } + + /// Increments the module's execution counter and sets the event name to be executed + pub(crate) fn use_for(&mut self, event_name: String) { + self.event_name = Some(event_name); + self.counter += 1; + } + + /// Get the application name + #[allow(dead_code)] + pub(crate) fn app_name(&self) -> &str { + &self.app_name + } + + /// Get the module id + #[allow(dead_code)] + pub(crate) fn module_id(&self) -> &Ulid { + &self.module_id + } + + /// Get the event name + #[allow(dead_code)] + pub(crate) fn event_name(&self) -> Option<&String> { + self.event_name.as_ref() + } + + /// Get the counter value + #[allow(dead_code)] + pub(crate) fn counter(&self) -> u64 { + self.counter + } +} diff --git a/hermes/bin/src/wasm/mod.rs b/hermes/bin/src/wasm/mod.rs index 01bc8bf6b..c10f8bd97 100644 --- a/hermes/bin/src/wasm/mod.rs +++ b/hermes/bin/src/wasm/mod.rs @@ -1,5 +1,6 @@ //! WASM related structures and functions which are specific for the Hermes use case. //! All implementation based on [wasmtime](https://crates.io/crates/wasmtime) crate dependency. +pub(crate) mod context; mod engine; pub(crate) mod module; diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index da4cd8446..026415899 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -11,9 +11,9 @@ use wasmtime::{ use crate::{ event_queue::event::HermesEventPayload, - runtime_extensions::{bindings, state::Context}, + runtime_extensions::{bindings, state::State}, state::HermesState, - wasm::engine::Engine, + wasm::{context::Context, engine::Engine}, }; /// Bad WASM module error @@ -91,9 +91,11 @@ impl Module { /// # Errors /// - `BadModuleError` #[allow(dead_code)] - pub(crate) fn execute_event(&mut self, event: &dyn HermesEventPayload) -> anyhow::Result<()> { + pub(crate) fn execute_event( + &mut self, event: &dyn HermesEventPayload, state: State, + ) -> anyhow::Result<()> { self.context.use_for(event.event_name().to_string()); - let state = HermesState::new(self.context.clone()); + let state = HermesState::new(self.context.clone(), state); let mut store = WasmStore::new(&self.engine, state); let (instance, _) = bindings::Hermes::instantiate_pre(&mut store, &self.pre_instance) From 1cb3d75165c4fc3624e43a9a5a9fdc271718b3c0 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 16 Feb 2024 17:51:02 +0200 Subject: [PATCH 13/52] wip --- hermes/bin/src/reactor.rs | 17 +- hermes/bin/src/runtime_extensions/mod.rs | 202 ++++++++++----------- hermes/bin/src/runtime_extensions/state.rs | 4 +- hermes/bin/src/state.rs | 6 +- hermes/bin/src/wasm/module.rs | 4 +- 5 files changed, 118 insertions(+), 115 deletions(-) diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index dbcd89236..40c5e9921 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -1,6 +1,6 @@ //! Hermes Reactor implementation. -use std::thread; +use std::{sync::Arc, thread}; use crate::{ event_queue::{self, HermesEventQueueOut}, @@ -19,7 +19,7 @@ pub(crate) struct HermesReactor { wasm_module: Module, /// - state: State, + state: Arc, /// event_queue_out: HermesEventQueueOut, @@ -28,10 +28,10 @@ pub(crate) struct HermesReactor { impl HermesReactor { /// fn event_execution_loop( - mut wasm_module: Module, event_queue_out: HermesEventQueueOut, + wasm_module: &mut Module, event_queue_out: HermesEventQueueOut, state: &Arc, ) -> anyhow::Result<()> { for event in event_queue_out { - wasm_module.execute_event(event.as_ref())?; + wasm_module.execute_event(event.as_ref(), state.clone())?; } Ok(()) } @@ -41,7 +41,7 @@ impl HermesReactor { let wasm_module = Module::new(app_name, module_bytes)?; let (event_queue_in, event_queue_out) = event_queue::new(); - let state = State::new(&event_queue_in); + let state = State::new(&event_queue_in).into(); Ok(Self { wasm_module, @@ -51,9 +51,10 @@ impl HermesReactor { } /// - pub(crate) fn run(self) -> anyhow::Result<()> { - let events_thread = - thread::spawn(|| Self::event_execution_loop(self.wasm_module, self.event_queue_out)); + pub(crate) fn run(mut self) -> anyhow::Result<()> { + let events_thread = thread::spawn(move || { + Self::event_execution_loop(&mut self.wasm_module, self.event_queue_out, &self.state) + }); events_thread .join() diff --git a/hermes/bin/src/runtime_extensions/mod.rs b/hermes/bin/src/runtime_extensions/mod.rs index 3d747342f..25c76094a 100644 --- a/hermes/bin/src/runtime_extensions/mod.rs +++ b/hermes/bin/src/runtime_extensions/mod.rs @@ -1,109 +1,107 @@ //! Hermes runtime extensions -use wasmtime::{ - component::{Component, Linker}, - Config, Engine, Store, -}; - -use self::bindings::{ - exports::hermes::cardano::event_on_block::BlockSrc, - hermes::{ - cardano::api::{CardanoBlock, CardanoBlockchainId, CardanoTxn}, - cron::api::CronTagged, - }, -}; -use crate::state::HermesState; - pub(crate) mod bindings; pub(crate) mod hermes; pub(crate) mod state; pub(crate) mod wasi; -/// Example of how to call the autogenerated entry points -#[allow(dead_code)] -fn example() -> anyhow::Result<()> { - use crate::wasm::context::Context; - - // Configure an `Engine` and compile the `Component` that is being run for - // the application. - let mut config = Config::new(); - config.wasm_component_model(true); - let engine = Engine::new(&config)?; - let component = Component::from_file(&engine, "./your-component.wasm")?; - - // Instantiation of bindings always happens through a `Linker`. - // - // Note that the closure provided here is a projection from `T` in - // `Store` to `&mut U` where `U` implements the `HelloWorldImports` - // trait. In this case the `T`, `MyState`, is stored directly in the - // structure so no projection is necessary here. - let mut linker = Linker::new(&engine); - bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesState| state)?; - - let instance_pre = linker.instantiate_pre(&component)?; - - // As with the core wasm API of Wasmtime instantiation occurs within a - // `Store`. The bindings structure contains an `instantiate` method which - // takes the store, component, and linker. This returns the `bindings` - // structure which is an instance of `HelloWorld` and supports typed access - // to the exports of the component. - let mut store = Store::new( - &engine, - HermesState::new(Context::new("my-app".to_string())), - ); - - // - let (bindings, _) = bindings::Hermes::instantiate_pre(&mut store, &instance_pre)?; - - // Show how we call the events in our API. - let _result = bindings.hermes_init_event().call_init(&mut store)?; - - // HTTP API to be rewritten, but this is how its called. - // let arg1 = ??; - // let arg2 = ??; - // let result = bindings.interface0.call_handle(&mut store, arg1, arg2)?; - - // Example of calling on_block. - let arg0 = CardanoBlockchainId::Mainnet; - let arg1 = CardanoBlock::new(); - let arg2 = BlockSrc::TIP; - bindings - .hermes_cardano_event_on_block() - .call_on_cardano_block(&mut store, arg0, &arg1, arg2)?; - - // Example of calling on_txn. - let arg0 = CardanoBlockchainId::Mainnet; - let arg1: u64 = 123_456; - let arg2: u32 = 12; - let arg3 = CardanoTxn::new(); - - bindings - .hermes_cardano_event_on_txn() - .call_on_cardano_txn(&mut store, arg0, arg1, arg2, &arg3)?; - - // Example of calling on_rollback. - let arg0 = CardanoBlockchainId::Mainnet; - let arg1: u64 = 123_456; - bindings - .hermes_cardano_event_on_rollback() - .call_on_cardano_rollback(&mut store, arg0, arg1)?; - - // Example of calling on_cron. - let arg0 = CronTagged { - when: "* * * * *".to_string(), - tag: "tag".to_string(), - }; - let arg1 = false; - let _result = bindings - .hermes_cron_event() - .call_on_cron(&mut store, &arg0, arg1)?; - - // Example of calling kv_update - let arg0 = "key"; - let arg1 = bindings::hermes::kv_store::api::KvValues::KvString("value".to_string()); - bindings - .hermes_kv_store_event() - .call_kv_update(&mut store, arg0, &arg1)?; - - Ok(()) -} +// /// Example of how to call the autogenerated entry points +// #[allow(dead_code)] +// fn example() -> anyhow::Result<()> { +// use wasmtime::{ +// component::{Component, Linker}, +// Config, Engine, Store, +// }; + +// use self::bindings::{ +// exports::hermes::cardano::event_on_block::BlockSrc, +// hermes::{ +// cardano::api::{CardanoBlock, CardanoBlockchainId, CardanoTxn}, +// cron::api::CronTagged, +// }, +// }; +// use crate::{state::HermesState, wasm::context::Context}; + +// // Configure an `Engine` and compile the `Component` that is being run for +// // the application. +// let mut config = Config::new(); +// config.wasm_component_model(true); +// let engine = Engine::new(&config)?; +// let component = Component::from_file(&engine, "./your-component.wasm")?; + +// // Instantiation of bindings always happens through a `Linker`. +// // +// // Note that the closure provided here is a projection from `T` in +// // `Store` to `&mut U` where `U` implements the `HelloWorldImports` +// // trait. In this case the `T`, `MyState`, is stored directly in the +// // structure so no projection is necessary here. +// let mut linker = Linker::new(&engine); +// bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesState| state)?; + +// let instance_pre = linker.instantiate_pre(&component)?; + +// // As with the core wasm API of Wasmtime instantiation occurs within a +// // `Store`. The bindings structure contains an `instantiate` method which +// // takes the store, component, and linker. This returns the `bindings` +// // structure which is an instance of `HelloWorld` and supports typed access +// // to the exports of the component. +// let mut store = Store::new( +// &engine, +// HermesState::new(Context::new("my-app".to_string())), +// ); + +// // +// let (bindings, _) = bindings::Hermes::instantiate_pre(&mut store, &instance_pre)?; + +// // Show how we call the events in our API. +// let _result = bindings.hermes_init_event().call_init(&mut store)?; + +// // HTTP API to be rewritten, but this is how its called. +// // let arg1 = ??; +// // let arg2 = ??; +// // let result = bindings.interface0.call_handle(&mut store, arg1, arg2)?; + +// // Example of calling on_block. +// let arg0 = CardanoBlockchainId::Mainnet; +// let arg1 = CardanoBlock::new(); +// let arg2 = BlockSrc::TIP; +// bindings +// .hermes_cardano_event_on_block() +// .call_on_cardano_block(&mut store, arg0, &arg1, arg2)?; + +// // Example of calling on_txn. +// let arg0 = CardanoBlockchainId::Mainnet; +// let arg1: u64 = 123_456; +// let arg2: u32 = 12; +// let arg3 = CardanoTxn::new(); + +// bindings +// .hermes_cardano_event_on_txn() +// .call_on_cardano_txn(&mut store, arg0, arg1, arg2, &arg3)?; + +// // Example of calling on_rollback. +// let arg0 = CardanoBlockchainId::Mainnet; +// let arg1: u64 = 123_456; +// bindings +// .hermes_cardano_event_on_rollback() +// .call_on_cardano_rollback(&mut store, arg0, arg1)?; + +// // Example of calling on_cron. +// let arg0 = CronTagged { +// when: "* * * * *".to_string(), +// tag: "tag".to_string(), +// }; +// let arg1 = false; +// let _result = bindings +// .hermes_cron_event() +// .call_on_cron(&mut store, &arg0, arg1)?; + +// // Example of calling kv_update +// let arg0 = "key"; +// let arg1 = +// bindings::hermes::kv_store::api::KvValues::KvString("value".to_string()); bindings +// .hermes_kv_store_event() +// .call_kv_update(&mut store, arg0, &arg1)?; + +// Ok(()) +// } diff --git a/hermes/bin/src/runtime_extensions/state.rs b/hermes/bin/src/runtime_extensions/state.rs index 7bf2e7ca0..a966f5d24 100644 --- a/hermes/bin/src/runtime_extensions/state.rs +++ b/hermes/bin/src/runtime_extensions/state.rs @@ -12,10 +12,10 @@ pub(crate) trait Stateful { /// All runtime extensions state pub(crate) struct State { /// Hermes custom extensions state - _hermes: hermes::State, + pub(crate) _hermes: hermes::State, /// WASI standard extensions state - _wasi: wasi::State, + pub(crate) _wasi: wasi::State, } impl Stateful for State { diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/state.rs index 209609bd6..cc805067d 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/state.rs @@ -1,12 +1,14 @@ //! Hermes state implementation. +use std::sync::Arc; + use crate::{runtime_extensions::state::State, wasm::context::Context}; #[allow(dead_code)] /// State for Hermes runtime pub(crate) struct HermesState { /// Runtime extensions state - pub(crate) state: State, + pub(crate) state: Arc, /// The context of the wasm modules using this State. pub(crate) ctx: Context, @@ -14,7 +16,7 @@ pub(crate) struct HermesState { impl HermesState { /// Creates a new instance of the `HermesState`. - pub(crate) fn new(ctx: Context, state: State) -> HermesState { + pub(crate) fn new(ctx: Context, state: Arc) -> HermesState { Self { state, ctx } } } diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 026415899..27625ba30 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -4,6 +4,8 @@ //! //! All implementation based on [wasmtime](https://crates.io/crates/wasmtime) crate dependency. +use std::sync::Arc; + use wasmtime::{ component::{Component as WasmModule, InstancePre as WasmInstancePre, Linker as WasmLinker}, Store as WasmStore, @@ -92,7 +94,7 @@ impl Module { /// - `BadModuleError` #[allow(dead_code)] pub(crate) fn execute_event( - &mut self, event: &dyn HermesEventPayload, state: State, + &mut self, event: &dyn HermesEventPayload, state: Arc, ) -> anyhow::Result<()> { self.context.use_for(event.event_name().to_string()); let state = HermesState::new(self.context.clone(), state); From 42121fd6f5ac38edd48392b47060512e0fa14a93 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 16 Feb 2024 17:59:14 +0200 Subject: [PATCH 14/52] add InitEvent --- hermes/bin/src/event_queue/mod.rs | 7 +++++++ .../runtime_extensions/hermes/init/event.rs | 20 +++++++++++++++++++ .../src/runtime_extensions/hermes/init/mod.rs | 6 +++++- 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 hermes/bin/src/runtime_extensions/hermes/init/event.rs diff --git a/hermes/bin/src/event_queue/mod.rs b/hermes/bin/src/event_queue/mod.rs index 9f12b4c65..0eb413d1e 100644 --- a/hermes/bin/src/event_queue/mod.rs +++ b/hermes/bin/src/event_queue/mod.rs @@ -14,6 +14,13 @@ pub(crate) fn new() -> (HermesEventQueueIn, HermesEventQueueOut) { #[derive(Clone)] pub(crate) struct HermesEventQueueIn(Sender>); +impl HermesEventQueueIn { + /// + pub(crate) fn add(&self, event: Box) { + self.0.send(event).unwrap(); + } +} + /// pub(crate) struct HermesEventQueueOut(Receiver>); diff --git a/hermes/bin/src/runtime_extensions/hermes/init/event.rs b/hermes/bin/src/runtime_extensions/hermes/init/event.rs new file mode 100644 index 000000000..7c986a5fa --- /dev/null +++ b/hermes/bin/src/runtime_extensions/hermes/init/event.rs @@ -0,0 +1,20 @@ +//! Init runtime extension event handler implementation. + +use crate::event_queue::event::HermesEventPayload; + +/// Init event +pub(crate) struct InitEvent {} + +impl HermesEventPayload for InitEvent { + fn event_name(&self) -> &str { + "init" + } + + fn execute(&self, module: &mut crate::wasm::module::ModuleInstance) -> anyhow::Result<()> { + let _res = module + .instance + .hermes_init_event() + .call_init(&mut module.store)?; + Ok(()) + } +} diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index f714e11c1..29f1985ad 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -2,11 +2,15 @@ use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +mod event; + /// State pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new(event_queue_in: &HermesEventQueueIn) -> Self { + let event_queue_in = event_queue_in.clone(); + event_queue_in.add(Box::new(event::InitEvent {})); State {} } } From 7fd619f2d0655d73ac44788b674b0211efa8295a Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 16 Feb 2024 19:02:03 +0200 Subject: [PATCH 15/52] add emit_init_event function --- hermes/bin/src/event_queue/mod.rs | 7 +++++-- hermes/bin/src/reactor.rs | 2 ++ .../src/runtime_extensions/hermes/init/mod.rs | 19 +++++++++++++++---- .../bin/src/runtime_extensions/hermes/mod.rs | 2 +- 4 files changed, 23 insertions(+), 7 deletions(-) diff --git a/hermes/bin/src/event_queue/mod.rs b/hermes/bin/src/event_queue/mod.rs index 0eb413d1e..80fb4cbdb 100644 --- a/hermes/bin/src/event_queue/mod.rs +++ b/hermes/bin/src/event_queue/mod.rs @@ -16,8 +16,11 @@ pub(crate) struct HermesEventQueueIn(Sender>) impl HermesEventQueueIn { /// - pub(crate) fn add(&self, event: Box) { - self.0.send(event).unwrap(); + pub(crate) fn add(&self, event: Box) -> anyhow::Result<()> { + self.0.send(event).map_err(|_| { + anyhow::anyhow!("Failed to add event into the event queue. Event queue is closed") + })?; + Ok(()) } } diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 40c5e9921..257ab55e6 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -52,6 +52,8 @@ impl HermesReactor { /// pub(crate) fn run(mut self) -> anyhow::Result<()> { + self.state._hermes._init.emit_init_event()?; + let events_thread = thread::spawn(move || { Self::event_execution_loop(&mut self.wasm_module, self.event_queue_out, &self.state) }); diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 29f1985ad..97b7959fb 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -5,12 +5,23 @@ use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful mod event; /// State -pub(crate) struct State {} +pub(crate) struct State { + /// Hermes Event Queue + event_queue_in: HermesEventQueueIn, +} impl Stateful for State { fn new(event_queue_in: &HermesEventQueueIn) -> Self { - let event_queue_in = event_queue_in.clone(); - event_queue_in.add(Box::new(event::InitEvent {})); - State {} + State { + event_queue_in: event_queue_in.clone(), + } + } +} + +impl State { + /// Init event + pub(crate) fn emit_init_event(&self) -> anyhow::Result<()> { + self.event_queue_in.add(Box::new(event::InitEvent {}))?; + Ok(()) } } diff --git a/hermes/bin/src/runtime_extensions/hermes/mod.rs b/hermes/bin/src/runtime_extensions/hermes/mod.rs index e6cb7dc4d..ac4ad7314 100644 --- a/hermes/bin/src/runtime_extensions/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/mod.rs @@ -29,7 +29,7 @@ pub(crate) struct State { /// Hash extensions state _hash: hash::State, /// Init extensions state - _init: init::State, + pub(crate) _init: init::State, /// JSON extensions state _json: json::State, /// KV store extensions state From 0deecd0162f4ddcacd2fa72f3d79abbca20d31e2 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 16 Feb 2024 21:39:11 +0200 Subject: [PATCH 16/52] update --- hermes/bin/src/reactor.rs | 3 ++- .../src/runtime_extensions/hermes/init/mod.rs | 2 +- .../bin/src/runtime_extensions/hermes/mod.rs | 24 +++++++++---------- hermes/bin/src/runtime_extensions/state.rs | 6 ++--- 4 files changed, 18 insertions(+), 17 deletions(-) diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 257ab55e6..c434f1d9f 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -52,7 +52,8 @@ impl HermesReactor { /// pub(crate) fn run(mut self) -> anyhow::Result<()> { - self.state._hermes._init.emit_init_event()?; + // Emits init event + self.state.hermes.init.emit_init_event()?; let events_thread = thread::spawn(move || { Self::event_execution_loop(&mut self.wasm_module, self.event_queue_out, &self.state) diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 97b7959fb..a993ca226 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -19,7 +19,7 @@ impl Stateful for State { } impl State { - /// Init event + /// Emit Init event pub(crate) fn emit_init_event(&self) -> anyhow::Result<()> { self.event_queue_in.add(Box::new(event::InitEvent {}))?; Ok(()) diff --git a/hermes/bin/src/runtime_extensions/hermes/mod.rs b/hermes/bin/src/runtime_extensions/hermes/mod.rs index ac4ad7314..2750c7754 100644 --- a/hermes/bin/src/runtime_extensions/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/mod.rs @@ -17,27 +17,27 @@ pub(crate) mod logging; /// Hermes extensions state pub(crate) struct State { /// Binary extensions state - _binary: binary::State, + pub(crate) _binary: binary::State, /// Cardano extensions state - _cardano: cardano::State, + pub(crate) _cardano: cardano::State, /// CBOR extensions state - _cbor: cbor::State, + pub(crate) _cbor: cbor::State, /// Cron extensions state - _cron: cron::State, + pub(crate) _cron: cron::State, /// Crypto extensions state - _crypto: crypto::State, + pub(crate) _crypto: crypto::State, /// Hash extensions state - _hash: hash::State, + pub(crate) _hash: hash::State, /// Init extensions state - pub(crate) _init: init::State, + pub(crate) init: init::State, /// JSON extensions state - _json: json::State, + pub(crate) _json: json::State, /// KV store extensions state - _kv_store: kv_store::State, + pub(crate) _kv_store: kv_store::State, /// Localtime extensions state - _localtime: localtime::State, + pub(crate) _localtime: localtime::State, /// Logging extensions state - _logging: logging::State, + pub(crate) _logging: logging::State, } impl Stateful for State { @@ -49,7 +49,7 @@ impl Stateful for State { _cron: cron::State::new(event_queue_in), _crypto: crypto::State::new(event_queue_in), _hash: hash::State::new(event_queue_in), - _init: init::State::new(event_queue_in), + init: init::State::new(event_queue_in), _json: json::State::new(event_queue_in), _kv_store: kv_store::State::new(event_queue_in), _localtime: localtime::State::new(event_queue_in), diff --git a/hermes/bin/src/runtime_extensions/state.rs b/hermes/bin/src/runtime_extensions/state.rs index a966f5d24..282cb5fa9 100644 --- a/hermes/bin/src/runtime_extensions/state.rs +++ b/hermes/bin/src/runtime_extensions/state.rs @@ -4,7 +4,7 @@ use super::{hermes, wasi}; use crate::event_queue::HermesEventQueueIn; /// All Hermes runtime extensions states need to implement this. -pub(crate) trait Stateful { +pub(crate) trait Stateful: Send + Sync { /// Initial state for the given context fn new(event_eueue_in: &HermesEventQueueIn) -> Self; } @@ -12,7 +12,7 @@ pub(crate) trait Stateful { /// All runtime extensions state pub(crate) struct State { /// Hermes custom extensions state - pub(crate) _hermes: hermes::State, + pub(crate) hermes: hermes::State, /// WASI standard extensions state pub(crate) _wasi: wasi::State, @@ -21,7 +21,7 @@ pub(crate) struct State { impl Stateful for State { fn new(event_eueue_in: &HermesEventQueueIn) -> Self { Self { - _hermes: hermes::State::new(event_eueue_in), + hermes: hermes::State::new(event_eueue_in), _wasi: wasi::State::new(event_eueue_in), } } From 0d863e933f8adfdfeaa200ba6f37fdaa57d3e022 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Mon, 19 Feb 2024 15:29:39 +0200 Subject: [PATCH 17/52] fix spelling --- hermes/bin/src/runtime_extensions/state.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/hermes/bin/src/runtime_extensions/state.rs b/hermes/bin/src/runtime_extensions/state.rs index 282cb5fa9..ba81273d3 100644 --- a/hermes/bin/src/runtime_extensions/state.rs +++ b/hermes/bin/src/runtime_extensions/state.rs @@ -6,7 +6,7 @@ use crate::event_queue::HermesEventQueueIn; /// All Hermes runtime extensions states need to implement this. pub(crate) trait Stateful: Send + Sync { /// Initial state for the given context - fn new(event_eueue_in: &HermesEventQueueIn) -> Self; + fn new(event_queue_in: &HermesEventQueueIn) -> Self; } /// All runtime extensions state @@ -19,10 +19,10 @@ pub(crate) struct State { } impl Stateful for State { - fn new(event_eueue_in: &HermesEventQueueIn) -> Self { + fn new(event_queue_in: &HermesEventQueueIn) -> Self { Self { - hermes: hermes::State::new(event_eueue_in), - _wasi: wasi::State::new(event_eueue_in), + hermes: hermes::State::new(event_queue_in), + _wasi: wasi::State::new(event_queue_in), } } } From cf2a80611ed5e3ff10210b667774d675588e2bed Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Mon, 19 Feb 2024 15:36:40 +0200 Subject: [PATCH 18/52] fix lints --- hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs index aa6119b68..883955bc6 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs @@ -14,10 +14,10 @@ pub(crate) struct State { } impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new(event_queue_in: &HermesEventQueueIn) -> Self { Self { - _monotonic: monotonic::State::new(_event_queue_in), - _wall: wall::State::new(_event_queue_in), + _monotonic: monotonic::State::new(event_queue_in), + _wall: wall::State::new(event_queue_in), } } } From bb7f05a8e5f8052f789986235bde489db6edd848 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 20 Feb 2024 15:44:08 +0200 Subject: [PATCH 19/52] Add hermes app struct --- hermes/bin/src/app.rs | 39 +++++++++++++++++++++++++++++++++++++++ hermes/bin/src/lib.rs | 1 + hermes/bin/src/main.rs | 1 + hermes/bin/src/reactor.rs | 32 +++++++++++++------------------- 4 files changed, 54 insertions(+), 19 deletions(-) create mode 100644 hermes/bin/src/app.rs diff --git a/hermes/bin/src/app.rs b/hermes/bin/src/app.rs new file mode 100644 index 000000000..f79ff7149 --- /dev/null +++ b/hermes/bin/src/app.rs @@ -0,0 +1,39 @@ +//! Hermes app implementation. + +use std::sync::Arc; + +use crate::{ + event_queue::HermesEventQueueOut, runtime_extensions::state::State, wasm::module::Module, +}; + +/// Hermes app +pub(crate) struct HermesApp { + /// WASM modules + wasm_modules: Vec, +} + +impl HermesApp { + /// Create a new Hermes app + pub(crate) fn new(app_name: &str, module_bytes: Vec>) -> anyhow::Result { + let mut wasm_modules = Vec::with_capacity(module_bytes.len()); + for module_bytes in module_bytes { + wasm_modules.push(Module::new(app_name.to_string(), &module_bytes)?); + } + Ok(Self { wasm_modules }) + } + + /// Executes Hermes events from the event queue channel. + /// + /// # Note: + /// This is a blocking call until event queue channel is open. + pub(crate) fn event_execution_loop( + &mut self, event_queue_out: HermesEventQueueOut, state: &Arc, + ) -> anyhow::Result<()> { + for event in event_queue_out { + for module in &mut self.wasm_modules { + module.execute_event(event.as_ref(), state.clone())?; + } + } + Ok(()) + } +} diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index 3d3d3656d..5f2fa6331 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -1,6 +1,7 @@ //! Intentionally empty //! This file exists, so that doc tests can be used inside binary crates. +mod app; mod event_queue; #[allow(dead_code)] mod reactor; diff --git a/hermes/bin/src/main.rs b/hermes/bin/src/main.rs index 5e10e3b91..d2a46463e 100644 --- a/hermes/bin/src/main.rs +++ b/hermes/bin/src/main.rs @@ -1,5 +1,6 @@ //! The Hermes Node. +mod app; mod event_queue; #[allow(dead_code)] mod reactor; diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index c434f1d9f..8d69a1ea7 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -3,9 +3,9 @@ use std::{sync::Arc, thread}; use crate::{ + app::HermesApp, event_queue::{self, HermesEventQueueOut}, runtime_extensions::state::{State, Stateful}, - wasm::module::Module, }; /// Thread panics error @@ -15,48 +15,42 @@ struct ThreadPanicsError(&'static str); /// Hermes Reactor struct pub(crate) struct HermesReactor { - /// - wasm_module: Module, + /// Hermes app + app: HermesApp, - /// + /// Runtime extensions state state: Arc, - /// + /// Event queue event_queue_out: HermesEventQueueOut, } impl HermesReactor { - /// - fn event_execution_loop( - wasm_module: &mut Module, event_queue_out: HermesEventQueueOut, state: &Arc, - ) -> anyhow::Result<()> { - for event in event_queue_out { - wasm_module.execute_event(event.as_ref(), state.clone())?; - } - Ok(()) - } - /// Create a new Hermes Reactor - pub(crate) fn new(app_name: String, module_bytes: &[u8]) -> anyhow::Result { - let wasm_module = Module::new(app_name, module_bytes)?; + pub(crate) fn new(app_name: &str, module_bytes: Vec>) -> anyhow::Result { + let app = HermesApp::new(app_name, module_bytes)?; let (event_queue_in, event_queue_out) = event_queue::new(); let state = State::new(&event_queue_in).into(); Ok(Self { - wasm_module, + app, state, event_queue_out, }) } + /// Run Hermes. /// + /// # Note: + /// This is a blocking call util all tasks are finished. pub(crate) fn run(mut self) -> anyhow::Result<()> { // Emits init event self.state.hermes.init.emit_init_event()?; let events_thread = thread::spawn(move || { - Self::event_execution_loop(&mut self.wasm_module, self.event_queue_out, &self.state) + self.app + .event_execution_loop(self.event_queue_out, &self.state) }); events_thread From 67a0074107a24391d1b48f82a7809a025f35e7ba Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Sun, 25 Feb 2024 11:54:15 +0200 Subject: [PATCH 20/52] update Statefull trait --- hermes/bin/src/reactor.rs | 13 +++++++--- .../runtime_extensions/hermes/binary/mod.rs | 4 +-- .../runtime_extensions/hermes/cardano/mod.rs | 4 +-- .../src/runtime_extensions/hermes/cbor/mod.rs | 4 +-- .../src/runtime_extensions/hermes/cron/mod.rs | 4 +-- .../runtime_extensions/hermes/crypto/mod.rs | 4 +-- .../src/runtime_extensions/hermes/hash/mod.rs | 4 +-- .../src/runtime_extensions/hermes/init/mod.rs | 18 ++++++------- .../src/runtime_extensions/hermes/json/mod.rs | 4 +-- .../runtime_extensions/hermes/kv_store/mod.rs | 4 +-- .../hermes/localtime/mod.rs | 4 +-- .../runtime_extensions/hermes/logging/mod.rs | 4 +-- .../bin/src/runtime_extensions/hermes/mod.rs | 26 +++++++++---------- hermes/bin/src/runtime_extensions/state.rs | 9 +++---- .../src/runtime_extensions/wasi/cli/mod.rs | 4 +-- .../src/runtime_extensions/wasi/clocks/mod.rs | 8 +++--- .../wasi/clocks/monotonic/mod.rs | 4 +-- .../wasi/clocks/wall/mod.rs | 4 +-- .../runtime_extensions/wasi/filesystem/mod.rs | 4 +-- .../src/runtime_extensions/wasi/http/mod.rs | 4 +-- .../runtime_extensions/wasi/io/error/mod.rs | 4 +-- .../bin/src/runtime_extensions/wasi/io/mod.rs | 8 +++--- .../runtime_extensions/wasi/io/streams/mod.rs | 4 +-- hermes/bin/src/runtime_extensions/wasi/mod.rs | 16 ++++++------ .../wasi/random/insecure/mod.rs | 4 +-- .../wasi/random/insecure_seed/mod.rs | 4 +-- .../src/runtime_extensions/wasi/random/mod.rs | 10 +++---- .../wasi/random/secure/mod.rs | 4 +-- 28 files changed, 96 insertions(+), 92 deletions(-) diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 8d69a1ea7..61e6fcf16 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -4,7 +4,7 @@ use std::{sync::Arc, thread}; use crate::{ app::HermesApp, - event_queue::{self, HermesEventQueueOut}, + event_queue::{self, HermesEventQueueIn, HermesEventQueueOut}, runtime_extensions::state::{State, Stateful}, }; @@ -21,6 +21,9 @@ pub(crate) struct HermesReactor { /// Runtime extensions state state: Arc, + /// Event queue in + event_queue_in: HermesEventQueueIn, + /// Event queue event_queue_out: HermesEventQueueOut, } @@ -31,11 +34,12 @@ impl HermesReactor { let app = HermesApp::new(app_name, module_bytes)?; let (event_queue_in, event_queue_out) = event_queue::new(); - let state = State::new(&event_queue_in).into(); + let state = State::new().into(); Ok(Self { app, state, + event_queue_in, event_queue_out, }) } @@ -46,7 +50,10 @@ impl HermesReactor { /// This is a blocking call util all tasks are finished. pub(crate) fn run(mut self) -> anyhow::Result<()> { // Emits init event - self.state.hermes.init.emit_init_event()?; + self.state + .hermes + .init + .emit_init_event(&self.event_queue_in)?; let events_thread = thread::spawn(move || { self.app diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs index 277743074..094e670c4 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs @@ -1,6 +1,6 @@ //! Binary runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs index 67736434a..db9829167 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs @@ -1,6 +1,6 @@ //! Cardano Blockchain runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod event; mod host; @@ -9,7 +9,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs index 4103d6211..3cb8b2c79 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs @@ -1,6 +1,6 @@ //! CBOR runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs index 4d58e9956..7bffdd3c4 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs @@ -1,6 +1,6 @@ //! Cron runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod event; mod host; @@ -9,7 +9,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs index f1d5c1a03..5b2935e3a 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs @@ -1,6 +1,6 @@ //! Crypto runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs index 55b2db6b8..f3796d3d2 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs @@ -1,6 +1,6 @@ //! Hash runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod blake2b; mod host; @@ -9,7 +9,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index a993ca226..eecb491eb 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -5,23 +5,21 @@ use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful mod event; /// State -pub(crate) struct State { - /// Hermes Event Queue - event_queue_in: HermesEventQueueIn, -} +pub(crate) struct State {} impl Stateful for State { - fn new(event_queue_in: &HermesEventQueueIn) -> Self { - State { - event_queue_in: event_queue_in.clone(), - } + fn new() -> Self { + State {} } } impl State { /// Emit Init event - pub(crate) fn emit_init_event(&self) -> anyhow::Result<()> { - self.event_queue_in.add(Box::new(event::InitEvent {}))?; + #[allow(clippy::unused_self)] + pub(crate) fn emit_init_event( + &self, event_queue_in: &HermesEventQueueIn, + ) -> anyhow::Result<()> { + event_queue_in.add(Box::new(event::InitEvent {}))?; Ok(()) } } diff --git a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs index 69ca62c0f..ec2eb2117 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs @@ -1,6 +1,6 @@ //! JSON runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs index 2b7ba0c17..99baf1b81 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs @@ -1,6 +1,6 @@ //! KV-Store runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod event; mod host; @@ -9,7 +9,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs index 547109339..2ba1b5c29 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs @@ -1,6 +1,6 @@ //! Localtime runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs index a9f311854..bd06f1a11 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs @@ -1,6 +1,6 @@ //! Logging runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_ctx: &HermesEventQueueIn) -> Self { + fn new() -> Self { State {} } } diff --git a/hermes/bin/src/runtime_extensions/hermes/mod.rs b/hermes/bin/src/runtime_extensions/hermes/mod.rs index 2750c7754..f3aa676ee 100644 --- a/hermes/bin/src/runtime_extensions/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/mod.rs @@ -1,6 +1,6 @@ //! Hermes runtime extensions implementations - HERMES custom extensions -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; pub(crate) mod binary; pub(crate) mod cardano; @@ -41,19 +41,19 @@ pub(crate) struct State { } impl Stateful for State { - fn new(event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self { - _binary: binary::State::new(event_queue_in), - _cardano: cardano::State::new(event_queue_in), - _cbor: cbor::State::new(event_queue_in), - _cron: cron::State::new(event_queue_in), - _crypto: crypto::State::new(event_queue_in), - _hash: hash::State::new(event_queue_in), - init: init::State::new(event_queue_in), - _json: json::State::new(event_queue_in), - _kv_store: kv_store::State::new(event_queue_in), - _localtime: localtime::State::new(event_queue_in), - _logging: logging::State::new(event_queue_in), + _binary: binary::State::new(), + _cardano: cardano::State::new(), + _cbor: cbor::State::new(), + _cron: cron::State::new(), + _crypto: crypto::State::new(), + _hash: hash::State::new(), + init: init::State::new(), + _json: json::State::new(), + _kv_store: kv_store::State::new(), + _localtime: localtime::State::new(), + _logging: logging::State::new(), } } } diff --git a/hermes/bin/src/runtime_extensions/state.rs b/hermes/bin/src/runtime_extensions/state.rs index ba81273d3..04deb2bf0 100644 --- a/hermes/bin/src/runtime_extensions/state.rs +++ b/hermes/bin/src/runtime_extensions/state.rs @@ -1,12 +1,11 @@ //! Hermes runtime extensions state. use super::{hermes, wasi}; -use crate::event_queue::HermesEventQueueIn; /// All Hermes runtime extensions states need to implement this. pub(crate) trait Stateful: Send + Sync { /// Initial state for the given context - fn new(event_queue_in: &HermesEventQueueIn) -> Self; + fn new() -> Self; } /// All runtime extensions state @@ -19,10 +18,10 @@ pub(crate) struct State { } impl Stateful for State { - fn new(event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self { - hermes: hermes::State::new(event_queue_in), - _wasi: wasi::State::new(event_queue_in), + hermes: hermes::State::new(), + _wasi: wasi::State::new(), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs index 3fe6a7cc8..174ef683e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs @@ -1,6 +1,6 @@ //! CLI runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs index 883955bc6..88e9f3741 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI - Clock implementations -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod monotonic; mod wall; @@ -14,10 +14,10 @@ pub(crate) struct State { } impl Stateful for State { - fn new(event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self { - _monotonic: monotonic::State::new(event_queue_in), - _wall: wall::State::new(event_queue_in), + _monotonic: monotonic::State::new(), + _wall: wall::State::new(), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs index 732df12e1..594df894e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs @@ -1,6 +1,6 @@ //! Monotonic clock runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs index c0ee537e0..6add5bd83 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs @@ -1,6 +1,6 @@ //! Wall clock runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs index 26c079a49..6b2711c1a 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs @@ -1,6 +1,6 @@ //! Filesystem runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs index f900df3c9..5a20a50f4 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs @@ -1,6 +1,6 @@ //! HTTP runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs index d2a785c21..2c0e7b9c0 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs @@ -1,6 +1,6 @@ //! IO Error runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/io/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs index 8f9109d04..6342c881e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI IO Implementation -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; pub(crate) mod error; pub(crate) mod streams; @@ -14,10 +14,10 @@ pub(crate) struct State { } impl Stateful for State { - fn new(event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self { - _error: error::State::new(event_queue_in), - _streams: streams::State::new(event_queue_in), + _error: error::State::new(), + _streams: streams::State::new(), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs index 678e543d0..9e693466b 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs @@ -1,6 +1,6 @@ //! IO Streams runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/mod.rs b/hermes/bin/src/runtime_extensions/wasi/mod.rs index 80b7f75a1..757e27bff 100644 --- a/hermes/bin/src/runtime_extensions/wasi/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/mod.rs @@ -1,6 +1,6 @@ //! Hermes runtime extensions implementations - WASI standard extensions -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; pub(crate) mod cli; pub(crate) mod clocks; @@ -26,14 +26,14 @@ pub(crate) struct State { } impl Stateful for State { - fn new(event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self { - _cli: cli::State::new(event_queue_in), - _clocks: clocks::State::new(event_queue_in), - _filesystem: filesystem::State::new(event_queue_in), - _http: http::State::new(event_queue_in), - _io: io::State::new(event_queue_in), - _random: random::State::new(event_queue_in), + _cli: cli::State::new(), + _clocks: clocks::State::new(), + _filesystem: filesystem::State::new(), + _http: http::State::new(), + _io: io::State::new(), + _random: random::State::new(), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs index 1fd68efe9..8cfcb6cdb 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs @@ -1,6 +1,6 @@ //! Insecure RNG runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs index 46d14b6a7..40abd2ed8 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs @@ -1,6 +1,6 @@ //! Insecure RNG seed runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs index 9958e79b6..e75ef2f09 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs @@ -1,6 +1,6 @@ //! Host - WASI - Random implementations -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; pub(crate) mod insecure; pub(crate) mod insecure_seed; @@ -17,11 +17,11 @@ pub(crate) struct State { } impl Stateful for State { - fn new(event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self { - _insecure: insecure::State::new(event_queue_in), - _insecure_seed: insecure_seed::State::new(event_queue_in), - _secure: secure::State::new(event_queue_in), + _insecure: insecure::State::new(), + _insecure_seed: insecure_seed::State::new(), + _secure: secure::State::new(), } } } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs index eddcccf5d..680503cd7 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs @@ -1,6 +1,6 @@ //! Random RNG runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::runtime_extensions::state::Stateful; mod host; @@ -8,7 +8,7 @@ mod host; pub(crate) struct State {} impl Stateful for State { - fn new(_event_queue_in: &HermesEventQueueIn) -> Self { + fn new() -> Self { Self {} } } From 4764cf9987b65b781f5167c99076353997d817ec Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Sun, 25 Feb 2024 13:21:32 +0200 Subject: [PATCH 21/52] update HermesEventQueue impl --- hermes/Cargo.toml | 4 ++ hermes/bin/Cargo.toml | 2 +- hermes/bin/src/app.rs | 22 +----- hermes/bin/src/event_queue/event.rs | 2 +- hermes/bin/src/event_queue/mod.rs | 67 +++++++++++++------ hermes/bin/src/reactor.rs | 29 +++----- .../src/runtime_extensions/hermes/init/mod.rs | 8 +-- .../crates/cardano-chain-follower/Cargo.toml | 10 +-- 8 files changed, 72 insertions(+), 72 deletions(-) diff --git a/hermes/Cargo.toml b/hermes/Cargo.toml index 935257697..17000928d 100644 --- a/hermes/Cargo.toml +++ b/hermes/Cargo.toml @@ -59,3 +59,7 @@ anyhow = "1.0.71" blake2b_simd = "1.0.2" hex-literal = "0.4.1" thiserror = "1.0.56" +tokio = "1.34.0" +hex = "0.4.3" +tracing = "0.1.40" +tracing-subscriber = "0.3.18" diff --git a/hermes/bin/Cargo.toml b/hermes/bin/Cargo.toml index cf7a65fe1..c8f822ecc 100644 --- a/hermes/bin/Cargo.toml +++ b/hermes/bin/Cargo.toml @@ -18,4 +18,4 @@ rusty_ulid = { workspace = true } anyhow = { workspace = true } blake2b_simd = { workspace = true } hex-literal = { workspace = true } -thiserror = { workspace = true } +thiserror = { workspace = true } \ No newline at end of file diff --git a/hermes/bin/src/app.rs b/hermes/bin/src/app.rs index f79ff7149..0e30a9f74 100644 --- a/hermes/bin/src/app.rs +++ b/hermes/bin/src/app.rs @@ -1,12 +1,9 @@ //! Hermes app implementation. -use std::sync::Arc; - -use crate::{ - event_queue::HermesEventQueueOut, runtime_extensions::state::State, wasm::module::Module, -}; +use crate::wasm::module::Module; /// Hermes app +#[allow(dead_code)] pub(crate) struct HermesApp { /// WASM modules wasm_modules: Vec, @@ -21,19 +18,4 @@ impl HermesApp { } Ok(Self { wasm_modules }) } - - /// Executes Hermes events from the event queue channel. - /// - /// # Note: - /// This is a blocking call until event queue channel is open. - pub(crate) fn event_execution_loop( - &mut self, event_queue_out: HermesEventQueueOut, state: &Arc, - ) -> anyhow::Result<()> { - for event in event_queue_out { - for module in &mut self.wasm_modules { - module.execute_event(event.as_ref(), state.clone())?; - } - } - Ok(()) - } } diff --git a/hermes/bin/src/event_queue/event.rs b/hermes/bin/src/event_queue/event.rs index b357ffa14..22720ec85 100644 --- a/hermes/bin/src/event_queue/event.rs +++ b/hermes/bin/src/event_queue/event.rs @@ -3,7 +3,7 @@ use crate::wasm::module::ModuleInstance; /// A trait for defining the behavior of a Hermes event. -pub trait HermesEventPayload: Send { +pub trait HermesEventPayload: Send + Sync { /// Returns the name of the event associated with the payload. fn event_name(&self) -> &str; diff --git a/hermes/bin/src/event_queue/mod.rs b/hermes/bin/src/event_queue/mod.rs index 80fb4cbdb..ac4ed547b 100644 --- a/hermes/bin/src/event_queue/mod.rs +++ b/hermes/bin/src/event_queue/mod.rs @@ -1,36 +1,59 @@ //! Hermes event queue implementation. -use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::{ + mpsc::{Receiver, Sender}, + Mutex, +}; pub(crate) mod event; -/// Initialize Hermes event queue -pub(crate) fn new() -> (HermesEventQueueIn, HermesEventQueueOut) { - let (sender, receiver) = channel(); - (HermesEventQueueIn(sender), HermesEventQueueOut(receiver)) +/// Hermes event queue error +#[derive(thiserror::Error, Debug, Clone)] +pub(crate) enum Error { + /// Failed to add event into the event queue. Event queue is closed. + #[error("Failed to add event into the event queue. Event queue is closed.")] + QueueClosed, } -/// -#[derive(Clone)] -pub(crate) struct HermesEventQueueIn(Sender>); +/// Hermes event queue +pub(crate) struct HermesEventQueue { + /// Hermes event queue sender + sender: Sender>, -impl HermesEventQueueIn { - /// - pub(crate) fn add(&self, event: Box) -> anyhow::Result<()> { - self.0.send(event).map_err(|_| { - anyhow::anyhow!("Failed to add event into the event queue. Event queue is closed") - })?; - Ok(()) - } + /// Hermes event queue receiver + receiver: Mutex>>, } -/// -pub(crate) struct HermesEventQueueOut(Receiver>); +impl HermesEventQueue { + /// Create a new Hermes event queue + pub(crate) fn new() -> Self { + let (sender, receiver) = std::sync::mpsc::channel(); + Self { + sender, + receiver: Mutex::new(receiver), + } + } -impl Iterator for HermesEventQueueOut { - type Item = Box; + /// Add event into the event queue + #[allow( + clippy::unnecessary_wraps, + clippy::unused_self, + unused_variables, + clippy::needless_pass_by_value + )] + pub(crate) fn add(&self, event: Box) -> anyhow::Result<()> { + self.sender.send(event).map_err(|_| Error::QueueClosed)?; + Ok(()) + } - fn next(&mut self) -> Option { - self.0.recv().ok() + /// Executes Hermes events from the event queue. + /// + /// # Note: + /// This is a blocking call and consumes the event queue. + #[allow(clippy::unnecessary_wraps, clippy::unwrap_used)] + pub(crate) fn event_execution_loop(&self) -> anyhow::Result<()> { + let receiver = self.receiver.lock().unwrap(); + for _event in receiver.iter() {} + Ok(()) } } diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 61e6fcf16..6e42e17bf 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -4,7 +4,7 @@ use std::{sync::Arc, thread}; use crate::{ app::HermesApp, - event_queue::{self, HermesEventQueueIn, HermesEventQueueOut}, + event_queue::HermesEventQueue, runtime_extensions::state::{State, Stateful}, }; @@ -21,26 +21,22 @@ pub(crate) struct HermesReactor { /// Runtime extensions state state: Arc, - /// Event queue in - event_queue_in: HermesEventQueueIn, - - /// Event queue - event_queue_out: HermesEventQueueOut, + /// Hermes event queue + event_queue: Arc, } impl HermesReactor { /// Create a new Hermes Reactor pub(crate) fn new(app_name: &str, module_bytes: Vec>) -> anyhow::Result { let app = HermesApp::new(app_name, module_bytes)?; - let (event_queue_in, event_queue_out) = event_queue::new(); + let event_queue = HermesEventQueue::new().into(); let state = State::new().into(); Ok(Self { app, state, - event_queue_in, - event_queue_out, + event_queue, }) } @@ -48,18 +44,15 @@ impl HermesReactor { /// /// # Note: /// This is a blocking call util all tasks are finished. - pub(crate) fn run(mut self) -> anyhow::Result<()> { + pub(crate) fn run(self) -> anyhow::Result<()> { // Emits init event - self.state - .hermes - .init - .emit_init_event(&self.event_queue_in)?; - - let events_thread = thread::spawn(move || { - self.app - .event_execution_loop(self.event_queue_out, &self.state) + thread::spawn({ + let event_queue = self.event_queue.clone(); + move || self.state.hermes.init.emit_init_event(event_queue.as_ref()) }); + let events_thread = thread::spawn(move || self.event_queue.event_execution_loop()); + events_thread .join() .map_err(|_| ThreadPanicsError("events handler"))??; diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index eecb491eb..12c1f1f3c 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,6 +1,6 @@ //! Init runtime extension implementation. -use crate::{event_queue::HermesEventQueueIn, runtime_extensions::state::Stateful}; +use crate::{event_queue::HermesEventQueue, runtime_extensions::state::Stateful}; mod event; @@ -16,10 +16,8 @@ impl Stateful for State { impl State { /// Emit Init event #[allow(clippy::unused_self)] - pub(crate) fn emit_init_event( - &self, event_queue_in: &HermesEventQueueIn, - ) -> anyhow::Result<()> { - event_queue_in.add(Box::new(event::InitEvent {}))?; + pub(crate) fn emit_init_event(&self, event_queue: &HermesEventQueue) -> anyhow::Result<()> { + event_queue.add(Box::new(event::InitEvent {}))?; Ok(()) } } diff --git a/hermes/crates/cardano-chain-follower/Cargo.toml b/hermes/crates/cardano-chain-follower/Cargo.toml index b8f1b4e69..737d78521 100644 --- a/hermes/crates/cardano-chain-follower/Cargo.toml +++ b/hermes/crates/cardano-chain-follower/Cargo.toml @@ -13,10 +13,10 @@ workspace = true [dependencies] pallas.workspace = true pallas-hardano.workspace = true -thiserror = "1.0.50" -tokio = { version = "1.34.0", default-features = false, features = ["macros", "rt", "net", "rt-multi-thread"] } -tracing = "0.1.40" +thiserror.workspace = true +tokio = { workspace = true, default-features = false, features = ["macros", "rt", "net", "rt-multi-thread"] } +tracing.workspace = true [dev-dependencies] -hex = "0.4.3" -tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } +hex.workspace = true +tracing-subscriber = { workspace = true, features = ["env-filter"] } From 55eac4b5710116908dd0bc47b828f68295251eec Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Sun, 25 Feb 2024 13:35:38 +0200 Subject: [PATCH 22/52] refactor wasm::Module --- hermes/bin/src/app.rs | 12 ++++-- hermes/bin/src/reactor.rs | 2 +- hermes/bin/src/state.rs | 73 ++++++++++++++++++++++++++++++---- hermes/bin/src/wasm/context.rs | 62 ----------------------------- hermes/bin/src/wasm/mod.rs | 1 - hermes/bin/src/wasm/module.rs | 34 +++++++++------- 6 files changed, 95 insertions(+), 89 deletions(-) delete mode 100644 hermes/bin/src/wasm/context.rs diff --git a/hermes/bin/src/app.rs b/hermes/bin/src/app.rs index 0e30a9f74..3500c4bed 100644 --- a/hermes/bin/src/app.rs +++ b/hermes/bin/src/app.rs @@ -5,17 +5,23 @@ use crate::wasm::module::Module; /// Hermes app #[allow(dead_code)] pub(crate) struct HermesApp { + /// App name + app_name: String, + /// WASM modules wasm_modules: Vec, } impl HermesApp { /// Create a new Hermes app - pub(crate) fn new(app_name: &str, module_bytes: Vec>) -> anyhow::Result { + pub(crate) fn new(app_name: String, module_bytes: Vec>) -> anyhow::Result { let mut wasm_modules = Vec::with_capacity(module_bytes.len()); for module_bytes in module_bytes { - wasm_modules.push(Module::new(app_name.to_string(), &module_bytes)?); + wasm_modules.push(Module::new(&module_bytes)?); } - Ok(Self { wasm_modules }) + Ok(Self { + app_name, + wasm_modules, + }) } } diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 6e42e17bf..59f7602dc 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -27,7 +27,7 @@ pub(crate) struct HermesReactor { impl HermesReactor { /// Create a new Hermes Reactor - pub(crate) fn new(app_name: &str, module_bytes: Vec>) -> anyhow::Result { + pub(crate) fn new(app_name: String, module_bytes: Vec>) -> anyhow::Result { let app = HermesApp::new(app_name, module_bytes)?; let event_queue = HermesEventQueue::new().into(); diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/state.rs index cc805067d..704a60f32 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/state.rs @@ -2,21 +2,80 @@ use std::sync::Arc; -use crate::{runtime_extensions::state::State, wasm::context::Context}; +use rusty_ulid::Ulid; + +use crate::runtime_extensions::state::State; #[allow(dead_code)] -/// State for Hermes runtime +/// State for Hermes state pub(crate) struct HermesState { /// Runtime extensions state pub(crate) state: Arc, - - /// The context of the wasm modules using this State. - pub(crate) ctx: Context, + // /// The context of the wasm modules using this State. + // pub(crate) ctx: Context, } impl HermesState { /// Creates a new instance of the `HermesState`. - pub(crate) fn new(ctx: Context, state: Arc) -> HermesState { - Self { state, ctx } + pub(crate) fn _new(state: Arc) -> HermesState { + Self { state } + } +} + +/// A Hermes running context, which should be passed to the WASM runtime. +#[derive(Clone)] +pub(crate) struct Context { + /// Hermes application name + app_name: String, + + /// module ULID id + module_id: Ulid, + + /// event name to be executed + event_name: Option, + + /// module's execution counter + counter: u64, +} + +impl Context { + /// Creates a new instance of the `Context`. + pub(crate) fn _new(app_name: String) -> Self { + Self { + app_name, + module_id: Ulid::generate(), + event_name: None, + counter: 0, + } + } + + /// Increments the module's execution counter and sets the event name to be executed + pub(crate) fn _use_for(&mut self, event_name: String) { + self.event_name = Some(event_name); + self.counter += 1; + } + + /// Get the application name + #[allow(dead_code)] + pub(crate) fn app_name(&self) -> &str { + &self.app_name + } + + /// Get the module id + #[allow(dead_code)] + pub(crate) fn module_id(&self) -> &Ulid { + &self.module_id + } + + /// Get the event name + #[allow(dead_code)] + pub(crate) fn event_name(&self) -> Option<&String> { + self.event_name.as_ref() + } + + /// Get the counter value + #[allow(dead_code)] + pub(crate) fn counter(&self) -> u64 { + self.counter } } diff --git a/hermes/bin/src/wasm/context.rs b/hermes/bin/src/wasm/context.rs deleted file mode 100644 index bc21e171a..000000000 --- a/hermes/bin/src/wasm/context.rs +++ /dev/null @@ -1,62 +0,0 @@ -//! WASM module execution context. - -use rusty_ulid::Ulid; - -/// A WASM module's context structure, which is intended to be passed to the -/// `wasmtime::Store` during the WASM module's state initialization process. -#[derive(Clone)] -pub(crate) struct Context { - /// Hermes application name - app_name: String, - - /// module ULID id - module_id: Ulid, - - /// event name to be executed - event_name: Option, - - /// module's execution counter - counter: u64, -} - -impl Context { - /// Creates a new instance of the `Context`. - pub(crate) fn new(app_name: String) -> Self { - Self { - app_name, - module_id: Ulid::generate(), - event_name: None, - counter: 0, - } - } - - /// Increments the module's execution counter and sets the event name to be executed - pub(crate) fn use_for(&mut self, event_name: String) { - self.event_name = Some(event_name); - self.counter += 1; - } - - /// Get the application name - #[allow(dead_code)] - pub(crate) fn app_name(&self) -> &str { - &self.app_name - } - - /// Get the module id - #[allow(dead_code)] - pub(crate) fn module_id(&self) -> &Ulid { - &self.module_id - } - - /// Get the event name - #[allow(dead_code)] - pub(crate) fn event_name(&self) -> Option<&String> { - self.event_name.as_ref() - } - - /// Get the counter value - #[allow(dead_code)] - pub(crate) fn counter(&self) -> u64 { - self.counter - } -} diff --git a/hermes/bin/src/wasm/mod.rs b/hermes/bin/src/wasm/mod.rs index c10f8bd97..01bc8bf6b 100644 --- a/hermes/bin/src/wasm/mod.rs +++ b/hermes/bin/src/wasm/mod.rs @@ -1,6 +1,5 @@ //! WASM related structures and functions which are specific for the Hermes use case. //! All implementation based on [wasmtime](https://crates.io/crates/wasmtime) crate dependency. -pub(crate) mod context; mod engine; pub(crate) mod module; diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 27625ba30..97e908f87 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -4,18 +4,15 @@ //! //! All implementation based on [wasmtime](https://crates.io/crates/wasmtime) crate dependency. -use std::sync::Arc; - +use rusty_ulid::Ulid; use wasmtime::{ component::{Component as WasmModule, InstancePre as WasmInstancePre, Linker as WasmLinker}, Store as WasmStore, }; use crate::{ - event_queue::event::HermesEventPayload, - runtime_extensions::{bindings, state::State}, - state::HermesState, - wasm::{context::Context, engine::Engine}, + event_queue::event::HermesEventPayload, runtime_extensions::bindings, state::HermesState, + wasm::engine::Engine, }; /// Bad WASM module error @@ -53,18 +50,25 @@ pub(crate) struct Module { /// `Engine` entity engine: Engine, - /// `Context` entity - context: Context, + /// Module ULID id + module_id: Ulid, + + /// Module's execution counter + exc_counter: u64, } impl Module { + /// Get the module id + pub(crate) fn _module_id(&self) -> &Ulid { + &self.module_id + } + /// Instantiate WASM module /// /// # Errors /// - `BadModuleError` /// - `BadEngineConfigError` - #[allow(dead_code)] - pub(crate) fn new(app_name: String, module_bytes: &[u8]) -> anyhow::Result { + pub(crate) fn new(module_bytes: &[u8]) -> anyhow::Result { let engine = Engine::new()?; let module = WasmModule::new(&engine, module_bytes) .map_err(|e| BadWASMModuleError(e.to_string()))?; @@ -79,7 +83,8 @@ impl Module { Ok(Self { pre_instance, engine, - context: Context::new(app_name), + module_id: Ulid::generate(), + exc_counter: 0, }) } @@ -94,16 +99,15 @@ impl Module { /// - `BadModuleError` #[allow(dead_code)] pub(crate) fn execute_event( - &mut self, event: &dyn HermesEventPayload, state: Arc, + &mut self, event: &dyn HermesEventPayload, state: HermesState, ) -> anyhow::Result<()> { - self.context.use_for(event.event_name().to_string()); - let state = HermesState::new(self.context.clone(), state); - let mut store = WasmStore::new(&self.engine, state); let (instance, _) = bindings::Hermes::instantiate_pre(&mut store, &self.pre_instance) .map_err(|e| BadWASMModuleError(e.to_string()))?; event.execute(&mut ModuleInstance { store, instance })?; + + self.exc_counter += 1; Ok(()) } } From 43a5c9ef6a0c18c1f089a701d046cac6a8ffe882 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Sun, 25 Feb 2024 17:13:38 +0200 Subject: [PATCH 23/52] add TargetApp, TargetModule types --- hermes/bin/src/app.rs | 7 ++- hermes/bin/src/event_queue/event.rs | 48 ++++++++++++++++++- hermes/bin/src/event_queue/mod.rs | 14 +++--- hermes/bin/src/reactor.rs | 12 +++-- .../src/runtime_extensions/hermes/init/mod.rs | 11 ++++- hermes/bin/src/wasm/module.rs | 14 +++--- 6 files changed, 82 insertions(+), 24 deletions(-) diff --git a/hermes/bin/src/app.rs b/hermes/bin/src/app.rs index 3500c4bed..f8c6e81cd 100644 --- a/hermes/bin/src/app.rs +++ b/hermes/bin/src/app.rs @@ -2,11 +2,14 @@ use crate::wasm::module::Module; +/// Hermes App Name type +pub(crate) struct HermesAppName(pub(crate) String); + /// Hermes app #[allow(dead_code)] pub(crate) struct HermesApp { /// App name - app_name: String, + app_name: HermesAppName, /// WASM modules wasm_modules: Vec, @@ -14,7 +17,7 @@ pub(crate) struct HermesApp { impl HermesApp { /// Create a new Hermes app - pub(crate) fn new(app_name: String, module_bytes: Vec>) -> anyhow::Result { + pub(crate) fn new(app_name: HermesAppName, module_bytes: Vec>) -> anyhow::Result { let mut wasm_modules = Vec::with_capacity(module_bytes.len()); for module_bytes in module_bytes { wasm_modules.push(Module::new(&module_bytes)?); diff --git a/hermes/bin/src/event_queue/event.rs b/hermes/bin/src/event_queue/event.rs index 22720ec85..b35b225a7 100644 --- a/hermes/bin/src/event_queue/event.rs +++ b/hermes/bin/src/event_queue/event.rs @@ -1,9 +1,12 @@ //! Hermes event definition -use crate::wasm::module::ModuleInstance; +use crate::{ + app::HermesAppName, + wasm::module::{ModuleId, ModuleInstance}, +}; /// A trait for defining the behavior of a Hermes event. -pub trait HermesEventPayload: Send + Sync { +pub(crate) trait HermesEventPayload: Send + Sync + 'static { /// Returns the name of the event associated with the payload. fn event_name(&self) -> &str; @@ -18,3 +21,44 @@ pub trait HermesEventPayload: Send + Sync { /// An `anyhow::Result` indicating the success or failure of the payload execution. fn execute(&self, module: &mut ModuleInstance) -> anyhow::Result<()>; } + +/// Target Hermes app to execute the event +pub(crate) enum TargetApp { + /// Execute for all available apps + All, + /// Execute for a specific list of apps + _List(Vec), +} + +/// Target WASM module to execute the event +pub(crate) enum TargetModule { + /// Execute for all available modules + All, + /// Execute for a specific list of modules + _List(Vec), +} + +/// Hermes event +pub(crate) struct HermesEvent { + /// The payload carried by the HermesEvent. + _payload: Box, + + /// Target app + _target_app: TargetApp, + + /// Target module + _target_module: TargetModule, +} + +impl HermesEvent { + /// Create a new Hermes event + pub(crate) fn new( + payload: impl HermesEventPayload, target_app: TargetApp, target_module: TargetModule, + ) -> Self { + Self { + _payload: Box::new(payload), + _target_app: target_app, + _target_module: target_module, + } + } +} diff --git a/hermes/bin/src/event_queue/mod.rs b/hermes/bin/src/event_queue/mod.rs index ac4ed547b..f9eb93ede 100644 --- a/hermes/bin/src/event_queue/mod.rs +++ b/hermes/bin/src/event_queue/mod.rs @@ -2,9 +2,12 @@ use std::sync::{ mpsc::{Receiver, Sender}, - Mutex, + Arc, Mutex, }; +use self::event::HermesEvent; +use crate::runtime_extensions::state::State; + pub(crate) mod event; /// Hermes event queue error @@ -18,10 +21,9 @@ pub(crate) enum Error { /// Hermes event queue pub(crate) struct HermesEventQueue { /// Hermes event queue sender - sender: Sender>, - + sender: Sender, /// Hermes event queue receiver - receiver: Mutex>>, + receiver: Mutex>, } impl HermesEventQueue { @@ -41,7 +43,7 @@ impl HermesEventQueue { unused_variables, clippy::needless_pass_by_value )] - pub(crate) fn add(&self, event: Box) -> anyhow::Result<()> { + pub(crate) fn add(&self, event: HermesEvent) -> anyhow::Result<()> { self.sender.send(event).map_err(|_| Error::QueueClosed)?; Ok(()) } @@ -51,7 +53,7 @@ impl HermesEventQueue { /// # Note: /// This is a blocking call and consumes the event queue. #[allow(clippy::unnecessary_wraps, clippy::unwrap_used)] - pub(crate) fn event_execution_loop(&self) -> anyhow::Result<()> { + pub(crate) fn event_execution_loop(&self, _state: &Arc) -> anyhow::Result<()> { let receiver = self.receiver.lock().unwrap(); for _event in receiver.iter() {} Ok(()) diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 59f7602dc..437a33d32 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -3,7 +3,7 @@ use std::{sync::Arc, thread}; use crate::{ - app::HermesApp, + app::{HermesApp, HermesAppName}, event_queue::HermesEventQueue, runtime_extensions::state::{State, Stateful}, }; @@ -27,7 +27,7 @@ pub(crate) struct HermesReactor { impl HermesReactor { /// Create a new Hermes Reactor - pub(crate) fn new(app_name: String, module_bytes: Vec>) -> anyhow::Result { + pub(crate) fn new(app_name: HermesAppName, module_bytes: Vec>) -> anyhow::Result { let app = HermesApp::new(app_name, module_bytes)?; let event_queue = HermesEventQueue::new().into(); @@ -48,10 +48,14 @@ impl HermesReactor { // Emits init event thread::spawn({ let event_queue = self.event_queue.clone(); - move || self.state.hermes.init.emit_init_event(event_queue.as_ref()) + let state = self.state.clone(); + move || state.hermes.init.emit_init_event(event_queue.as_ref()) }); - let events_thread = thread::spawn(move || self.event_queue.event_execution_loop()); + let events_thread = thread::spawn({ + let state = self.state.clone(); + move || self.event_queue.event_execution_loop(&state) + }); events_thread .join() diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 12c1f1f3c..0b802baa7 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,6 +1,12 @@ //! Init runtime extension implementation. -use crate::{event_queue::HermesEventQueue, runtime_extensions::state::Stateful}; +use crate::{ + event_queue::{ + event::{HermesEvent, TargetApp, TargetModule}, + HermesEventQueue, + }, + runtime_extensions::state::Stateful, +}; mod event; @@ -17,7 +23,8 @@ impl State { /// Emit Init event #[allow(clippy::unused_self)] pub(crate) fn emit_init_event(&self, event_queue: &HermesEventQueue) -> anyhow::Result<()> { - event_queue.add(Box::new(event::InitEvent {}))?; + let init_event = HermesEvent::new(event::InitEvent {}, TargetApp::All, TargetModule::All); + event_queue.add(init_event)?; Ok(()) } } diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 97e908f87..9b266e56c 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -30,6 +30,9 @@ pub(crate) struct ModuleInstance { pub(crate) instance: bindings::Hermes, } +/// Module id type +pub(crate) struct ModuleId(pub(crate) Ulid); + /// Structure defines an abstraction over the WASM module /// It instantiates the module with the provided context data, /// links all provided imports to the module instance, @@ -50,19 +53,14 @@ pub(crate) struct Module { /// `Engine` entity engine: Engine, - /// Module ULID id - module_id: Ulid, + /// Module id + _id: ModuleId, /// Module's execution counter exc_counter: u64, } impl Module { - /// Get the module id - pub(crate) fn _module_id(&self) -> &Ulid { - &self.module_id - } - /// Instantiate WASM module /// /// # Errors @@ -83,7 +81,7 @@ impl Module { Ok(Self { pre_instance, engine, - module_id: Ulid::generate(), + _id: ModuleId(Ulid::generate()), exc_counter: 0, }) } From 726b85bda66a27d88a47d00039decbedbad0fd3a Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Sun, 25 Feb 2024 19:08:25 +0200 Subject: [PATCH 24/52] add HermesEventExecutionManager --- hermes/bin/src/app.rs | 19 ++-- hermes/bin/src/event_queue/event.rs | 27 ++++-- hermes/bin/src/event_queue/mod.rs | 141 ++++++++++++++++++++++++---- hermes/bin/src/reactor.rs | 28 +++--- hermes/bin/src/state.rs | 2 +- hermes/bin/src/wasm/module.rs | 11 ++- 6 files changed, 180 insertions(+), 48 deletions(-) diff --git a/hermes/bin/src/app.rs b/hermes/bin/src/app.rs index f8c6e81cd..b38b1c724 100644 --- a/hermes/bin/src/app.rs +++ b/hermes/bin/src/app.rs @@ -3,6 +3,7 @@ use crate::wasm::module::Module; /// Hermes App Name type +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(crate) struct HermesAppName(pub(crate) String); /// Hermes app @@ -12,19 +13,23 @@ pub(crate) struct HermesApp { app_name: HermesAppName, /// WASM modules - wasm_modules: Vec, + modules: Vec, } impl HermesApp { /// Create a new Hermes app + #[allow(dead_code)] pub(crate) fn new(app_name: HermesAppName, module_bytes: Vec>) -> anyhow::Result { - let mut wasm_modules = Vec::with_capacity(module_bytes.len()); + let mut modules = Vec::with_capacity(module_bytes.len()); for module_bytes in module_bytes { - wasm_modules.push(Module::new(&module_bytes)?); + modules.push(Module::new(&module_bytes)?); } - Ok(Self { - app_name, - wasm_modules, - }) + Ok(Self { app_name, modules }) + } + + /// Get app name + #[allow(dead_code)] + pub(crate) fn app_name(self) -> HermesAppName { + self.app_name } } diff --git a/hermes/bin/src/event_queue/event.rs b/hermes/bin/src/event_queue/event.rs index b35b225a7..1b561a562 100644 --- a/hermes/bin/src/event_queue/event.rs +++ b/hermes/bin/src/event_queue/event.rs @@ -41,13 +41,13 @@ pub(crate) enum TargetModule { /// Hermes event pub(crate) struct HermesEvent { /// The payload carried by the HermesEvent. - _payload: Box, + payload: Box, /// Target app - _target_app: TargetApp, + target_app: TargetApp, /// Target module - _target_module: TargetModule, + target_module: TargetModule, } impl HermesEvent { @@ -56,9 +56,24 @@ impl HermesEvent { payload: impl HermesEventPayload, target_app: TargetApp, target_module: TargetModule, ) -> Self { Self { - _payload: Box::new(payload), - _target_app: target_app, - _target_module: target_module, + payload: Box::new(payload), + target_app, + target_module, } } + + /// Get event's payload + pub(crate) fn payload(&self) -> &dyn HermesEventPayload { + self.payload.as_ref() + } + + /// Get event's target app + pub(crate) fn target_app(&self) -> &TargetApp { + &self.target_app + } + + /// Get event's target module + pub(crate) fn target_module(&self) -> &TargetModule { + &self.target_module + } } diff --git a/hermes/bin/src/event_queue/mod.rs b/hermes/bin/src/event_queue/mod.rs index f9eb93ede..3edf211b8 100644 --- a/hermes/bin/src/event_queue/mod.rs +++ b/hermes/bin/src/event_queue/mod.rs @@ -1,12 +1,20 @@ //! Hermes event queue implementation. -use std::sync::{ - mpsc::{Receiver, Sender}, - Arc, Mutex, +use std::{ + collections::HashMap, + sync::{ + mpsc::{Receiver, Sender}, + Arc, Mutex, + }, }; -use self::event::HermesEvent; -use crate::runtime_extensions::state::State; +use self::event::{HermesEvent, TargetApp, TargetModule}; +use crate::{ + app::HermesAppName, + runtime_extensions::state::State, + state::HermesState, + wasm::module::{Module, ModuleId}, +}; pub(crate) mod event; @@ -16,6 +24,107 @@ pub(crate) enum Error { /// Failed to add event into the event queue. Event queue is closed. #[error("Failed to add event into the event queue. Event queue is closed.")] QueueClosed, + + /// Target app not found. + #[error("Target app not found.")] + AppNotFound, + + /// Target module not found. + #[error("Target module not found.")] + ModuleNotFound, +} + +/// +pub(crate) struct HermesEventExecutionManager { + /// Targets to execute the event + targets: HashMap>, +} + +impl HermesEventExecutionManager { + /// + pub(crate) fn new() -> Self { + Self { + targets: HashMap::new(), + } + } + + /// + fn filtered_execution( + &mut self, event: &HermesEvent, state: &Arc, + ) -> anyhow::Result<()> { + match event.target_app() { + &TargetApp::All => { + for target_modules in self.targets.values_mut() { + match event.target_module() { + TargetModule::All => { + for module in target_modules.values_mut() { + module.execute_event( + event.payload(), + HermesState::new(state.clone()), + )?; + } + }, + TargetModule::_List(modules) => { + for module_id in modules { + let module = target_modules + .get_mut(module_id) + .ok_or(Error::ModuleNotFound)?; + + module.execute_event( + event.payload(), + HermesState::new(state.clone()), + )?; + } + }, + } + } + }, + TargetApp::_List(apps) => { + for app_name in apps { + let target_modules = + self.targets.get_mut(app_name).ok_or(Error::AppNotFound)?; + + match event.target_module() { + TargetModule::All => { + for module in target_modules.values_mut() { + module.execute_event( + event.payload(), + HermesState::new(state.clone()), + )?; + } + }, + TargetModule::_List(modules) => { + for module_id in modules { + let module = target_modules + .get_mut(module_id) + .ok_or(Error::ModuleNotFound)?; + module.execute_event( + event.payload(), + HermesState::new(state.clone()), + )?; + } + }, + } + } + }, + } + + Ok(()) + } + + /// Executes Hermes events from provided the event queue. + /// + /// # Note: + /// This is a blocking call and consumes the event queue. + #[allow(clippy::unnecessary_wraps, clippy::unwrap_used)] + pub(crate) fn event_execution_loop( + &mut self, event_queue: &HermesEventQueue, state: &Arc, + ) -> anyhow::Result<()> { + for event in event_queue { + self.filtered_execution(&event, state)?; + } + Ok(()) + } } /// Hermes event queue @@ -30,6 +139,7 @@ impl HermesEventQueue { /// Create a new Hermes event queue pub(crate) fn new() -> Self { let (sender, receiver) = std::sync::mpsc::channel(); + Self { sender, receiver: Mutex::new(receiver), @@ -37,25 +147,16 @@ impl HermesEventQueue { } /// Add event into the event queue - #[allow( - clippy::unnecessary_wraps, - clippy::unused_self, - unused_variables, - clippy::needless_pass_by_value - )] pub(crate) fn add(&self, event: HermesEvent) -> anyhow::Result<()> { self.sender.send(event).map_err(|_| Error::QueueClosed)?; Ok(()) } +} - /// Executes Hermes events from the event queue. - /// - /// # Note: - /// This is a blocking call and consumes the event queue. - #[allow(clippy::unnecessary_wraps, clippy::unwrap_used)] - pub(crate) fn event_execution_loop(&self, _state: &Arc) -> anyhow::Result<()> { - let receiver = self.receiver.lock().unwrap(); - for _event in receiver.iter() {} - Ok(()) +impl Iterator for &HermesEventQueue { + type Item = HermesEvent; + + fn next(&mut self) -> Option { + self.receiver.lock().unwrap().try_recv().ok() } } diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 437a33d32..c254d8355 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -3,8 +3,8 @@ use std::{sync::Arc, thread}; use crate::{ - app::{HermesApp, HermesAppName}, - event_queue::HermesEventQueue, + app::HermesApp, + event_queue::{HermesEventExecutionManager, HermesEventQueue}, runtime_extensions::state::{State, Stateful}, }; @@ -15,36 +15,36 @@ struct ThreadPanicsError(&'static str); /// Hermes Reactor struct pub(crate) struct HermesReactor { - /// Hermes app - app: HermesApp, - /// Runtime extensions state state: Arc, /// Hermes event queue event_queue: Arc, + + /// + event_exec_manager: HermesEventExecutionManager, } impl HermesReactor { /// Create a new Hermes Reactor - pub(crate) fn new(app_name: HermesAppName, module_bytes: Vec>) -> anyhow::Result { - let app = HermesApp::new(app_name, module_bytes)?; + pub(crate) fn new(_apps: Vec) -> Self { let event_queue = HermesEventQueue::new().into(); + let event_exec_manager = HermesEventExecutionManager::new(); let state = State::new().into(); - Ok(Self { - app, + Self { state, event_queue, - }) + event_exec_manager, + } } /// Run Hermes. /// /// # Note: /// This is a blocking call util all tasks are finished. - pub(crate) fn run(self) -> anyhow::Result<()> { + pub(crate) fn run(mut self) -> anyhow::Result<()> { // Emits init event thread::spawn({ let event_queue = self.event_queue.clone(); @@ -54,7 +54,11 @@ impl HermesReactor { let events_thread = thread::spawn({ let state = self.state.clone(); - move || self.event_queue.event_execution_loop(&state) + let event_queue = self.event_queue.clone(); + move || { + self.event_exec_manager + .event_execution_loop(&event_queue, &state) + } }); events_thread diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/state.rs index 704a60f32..53d92cdf1 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/state.rs @@ -17,7 +17,7 @@ pub(crate) struct HermesState { impl HermesState { /// Creates a new instance of the `HermesState`. - pub(crate) fn _new(state: Arc) -> HermesState { + pub(crate) fn new(state: Arc) -> HermesState { Self { state } } } diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 9b266e56c..b0d438451 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -31,6 +31,7 @@ pub(crate) struct ModuleInstance { } /// Module id type +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(crate) struct ModuleId(pub(crate) Ulid); /// Structure defines an abstraction over the WASM module @@ -54,7 +55,7 @@ pub(crate) struct Module { engine: Engine, /// Module id - _id: ModuleId, + id: ModuleId, /// Module's execution counter exc_counter: u64, @@ -81,11 +82,17 @@ impl Module { Ok(Self { pre_instance, engine, - _id: ModuleId(Ulid::generate()), + id: ModuleId(Ulid::generate()), exc_counter: 0, }) } + /// Get the module id + #[allow(dead_code)] + pub(crate) fn id(self) -> ModuleId { + self.id + } + /// Executes a Hermes event by calling some WASM function. /// This function abstraction over actual execution of the WASM function, /// actual definition is inside `HermesEventPayload` trait implementation. From afb4cd8a7699b70816f7604a588dff7aca0fb490 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Sun, 25 Feb 2024 19:27:06 +0200 Subject: [PATCH 25/52] refactor --- hermes/bin/src/event/event_queue.rs | 46 ++++++++++++++++ .../mod.rs => event/exec_manager.rs} | 52 ++----------------- .../{event_queue/event.rs => event/mod.rs} | 5 +- hermes/bin/src/lib.rs | 2 +- hermes/bin/src/main.rs | 2 +- hermes/bin/src/reactor.rs | 4 +- .../hermes/cardano/event.rs | 2 +- .../runtime_extensions/hermes/cron/event.rs | 3 +- .../runtime_extensions/hermes/init/event.rs | 2 +- .../src/runtime_extensions/hermes/init/mod.rs | 5 +- .../hermes/kv_store/event.rs | 3 +- hermes/bin/src/wasm/module.rs | 2 +- 12 files changed, 63 insertions(+), 65 deletions(-) create mode 100644 hermes/bin/src/event/event_queue.rs rename hermes/bin/src/{event_queue/mod.rs => event/exec_manager.rs} (75%) rename hermes/bin/src/{event_queue/event.rs => event/mod.rs} (95%) diff --git a/hermes/bin/src/event/event_queue.rs b/hermes/bin/src/event/event_queue.rs new file mode 100644 index 000000000..0f401ec6f --- /dev/null +++ b/hermes/bin/src/event/event_queue.rs @@ -0,0 +1,46 @@ +//! Hermes event queue implementation. + +use std::sync::{ + mpsc::{Receiver, Sender}, + Mutex, +}; + +use super::HermesEvent; + +#[derive(thiserror::Error, Debug, Clone)] +#[error("Failed to add event into the event queue. Event queue is closed.")] +pub(crate) struct QueueClosed; + +/// Hermes event queue +pub(crate) struct HermesEventQueue { + /// Hermes event queue sender + sender: Sender, + /// Hermes event queue receiver + receiver: Mutex>, +} + +impl HermesEventQueue { + /// Create a new Hermes event queue + pub(crate) fn new() -> Self { + let (sender, receiver) = std::sync::mpsc::channel(); + + Self { + sender, + receiver: Mutex::new(receiver), + } + } + + /// Add event into the event queue + pub(crate) fn add(&self, event: HermesEvent) -> anyhow::Result<()> { + self.sender.send(event).map_err(|_| QueueClosed)?; + Ok(()) + } +} + +impl Iterator for &HermesEventQueue { + type Item = HermesEvent; + + fn next(&mut self) -> Option { + self.receiver.lock().unwrap().try_recv().ok() + } +} diff --git a/hermes/bin/src/event_queue/mod.rs b/hermes/bin/src/event/exec_manager.rs similarity index 75% rename from hermes/bin/src/event_queue/mod.rs rename to hermes/bin/src/event/exec_manager.rs index 3edf211b8..aed0793b4 100644 --- a/hermes/bin/src/event_queue/mod.rs +++ b/hermes/bin/src/event/exec_manager.rs @@ -1,14 +1,8 @@ -//! Hermes event queue implementation. +//! Hermes event execution manager implementation. -use std::{ - collections::HashMap, - sync::{ - mpsc::{Receiver, Sender}, - Arc, Mutex, - }, -}; +use std::{collections::HashMap, sync::Arc}; -use self::event::{HermesEvent, TargetApp, TargetModule}; +use super::{event_queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}; use crate::{ app::HermesAppName, runtime_extensions::state::State, @@ -16,15 +10,9 @@ use crate::{ wasm::module::{Module, ModuleId}, }; -pub(crate) mod event; - /// Hermes event queue error #[derive(thiserror::Error, Debug, Clone)] pub(crate) enum Error { - /// Failed to add event into the event queue. Event queue is closed. - #[error("Failed to add event into the event queue. Event queue is closed.")] - QueueClosed, - /// Target app not found. #[error("Target app not found.")] AppNotFound, @@ -126,37 +114,3 @@ impl HermesEventExecutionManager { Ok(()) } } - -/// Hermes event queue -pub(crate) struct HermesEventQueue { - /// Hermes event queue sender - sender: Sender, - /// Hermes event queue receiver - receiver: Mutex>, -} - -impl HermesEventQueue { - /// Create a new Hermes event queue - pub(crate) fn new() -> Self { - let (sender, receiver) = std::sync::mpsc::channel(); - - Self { - sender, - receiver: Mutex::new(receiver), - } - } - - /// Add event into the event queue - pub(crate) fn add(&self, event: HermesEvent) -> anyhow::Result<()> { - self.sender.send(event).map_err(|_| Error::QueueClosed)?; - Ok(()) - } -} - -impl Iterator for &HermesEventQueue { - type Item = HermesEvent; - - fn next(&mut self) -> Option { - self.receiver.lock().unwrap().try_recv().ok() - } -} diff --git a/hermes/bin/src/event_queue/event.rs b/hermes/bin/src/event/mod.rs similarity index 95% rename from hermes/bin/src/event_queue/event.rs rename to hermes/bin/src/event/mod.rs index 1b561a562..f17e93a6e 100644 --- a/hermes/bin/src/event_queue/event.rs +++ b/hermes/bin/src/event/mod.rs @@ -1,4 +1,7 @@ -//! Hermes event definition +//! Hermes event's primitives. + +pub(crate) mod event_queue; +pub(crate) mod exec_manager; use crate::{ app::HermesAppName, diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index 5f2fa6331..ccbf86347 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -2,7 +2,7 @@ //! This file exists, so that doc tests can be used inside binary crates. mod app; -mod event_queue; +mod event; #[allow(dead_code)] mod reactor; mod runtime_extensions; diff --git a/hermes/bin/src/main.rs b/hermes/bin/src/main.rs index d2a46463e..4c6d36a07 100644 --- a/hermes/bin/src/main.rs +++ b/hermes/bin/src/main.rs @@ -1,7 +1,7 @@ //! The Hermes Node. mod app; -mod event_queue; +mod event; #[allow(dead_code)] mod reactor; mod runtime_extensions; diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index c254d8355..7848ed547 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -4,7 +4,7 @@ use std::{sync::Arc, thread}; use crate::{ app::HermesApp, - event_queue::{HermesEventExecutionManager, HermesEventQueue}, + event::{event_queue::HermesEventQueue, exec_manager::HermesEventExecutionManager}, runtime_extensions::state::{State, Stateful}, }; @@ -27,7 +27,7 @@ pub(crate) struct HermesReactor { impl HermesReactor { /// Create a new Hermes Reactor - pub(crate) fn new(_apps: Vec) -> Self { + pub(crate) fn new(_apps: &Vec) -> Self { let event_queue = HermesEventQueue::new().into(); let event_exec_manager = HermesEventExecutionManager::new(); diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/event.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/event.rs index af952b5ae..0088f5e1e 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/event.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/event.rs @@ -1,7 +1,7 @@ //! Cardano Blockchain runtime extension event handler implementation. use crate::{ - event_queue::event::HermesEventPayload, + event::HermesEventPayload, runtime_extensions::bindings::hermes::cardano::api::{ BlockSrc, CardanoBlock, CardanoBlockchainId, CardanoTxn, }, diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/event.rs b/hermes/bin/src/runtime_extensions/hermes/cron/event.rs index 20b1b36b7..b9851e0fb 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/event.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/event.rs @@ -1,8 +1,7 @@ //! Cron runtime extension event handler implementation. use crate::{ - event_queue::event::HermesEventPayload, - runtime_extensions::bindings::hermes::cron::api::CronTagged, + event::HermesEventPayload, runtime_extensions::bindings::hermes::cron::api::CronTagged, }; /// On cron event diff --git a/hermes/bin/src/runtime_extensions/hermes/init/event.rs b/hermes/bin/src/runtime_extensions/hermes/init/event.rs index 7c986a5fa..7aeb9ec3a 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/event.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/event.rs @@ -1,6 +1,6 @@ //! Init runtime extension event handler implementation. -use crate::event_queue::event::HermesEventPayload; +use crate::event::HermesEventPayload; /// Init event pub(crate) struct InitEvent {} diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 0b802baa7..a146ccdeb 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,10 +1,7 @@ //! Init runtime extension implementation. use crate::{ - event_queue::{ - event::{HermesEvent, TargetApp, TargetModule}, - HermesEventQueue, - }, + event::{event_queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}, runtime_extensions::state::Stateful, }; diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/event.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/event.rs index 42394b865..21f744592 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/event.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/event.rs @@ -1,8 +1,7 @@ //! KV-Store runtime extension event handler implementation. use crate::{ - event_queue::event::HermesEventPayload, - runtime_extensions::bindings::hermes::kv_store::api::KvValues, + event::HermesEventPayload, runtime_extensions::bindings::hermes::kv_store::api::KvValues, }; /// KV update event diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index b0d438451..c14f14b55 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -11,7 +11,7 @@ use wasmtime::{ }; use crate::{ - event_queue::event::HermesEventPayload, runtime_extensions::bindings, state::HermesState, + event::HermesEventPayload, runtime_extensions::bindings, state::HermesState, wasm::engine::Engine, }; From ca5ed1e7c2c07207c18167813d616a68eb3e48b1 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Sun, 25 Feb 2024 21:11:52 +0200 Subject: [PATCH 26/52] remove HermesEventExecutionManager --- hermes/bin/src/event/event_queue.rs | 46 ------ hermes/bin/src/event/exec_manager.rs | 116 --------------- hermes/bin/src/event/mod.rs | 3 +- hermes/bin/src/event/queue.rs | 138 ++++++++++++++++++ hermes/bin/src/reactor.rs | 20 +-- .../src/runtime_extensions/hermes/init/mod.rs | 4 +- 6 files changed, 145 insertions(+), 182 deletions(-) delete mode 100644 hermes/bin/src/event/event_queue.rs delete mode 100644 hermes/bin/src/event/exec_manager.rs create mode 100644 hermes/bin/src/event/queue.rs diff --git a/hermes/bin/src/event/event_queue.rs b/hermes/bin/src/event/event_queue.rs deleted file mode 100644 index 0f401ec6f..000000000 --- a/hermes/bin/src/event/event_queue.rs +++ /dev/null @@ -1,46 +0,0 @@ -//! Hermes event queue implementation. - -use std::sync::{ - mpsc::{Receiver, Sender}, - Mutex, -}; - -use super::HermesEvent; - -#[derive(thiserror::Error, Debug, Clone)] -#[error("Failed to add event into the event queue. Event queue is closed.")] -pub(crate) struct QueueClosed; - -/// Hermes event queue -pub(crate) struct HermesEventQueue { - /// Hermes event queue sender - sender: Sender, - /// Hermes event queue receiver - receiver: Mutex>, -} - -impl HermesEventQueue { - /// Create a new Hermes event queue - pub(crate) fn new() -> Self { - let (sender, receiver) = std::sync::mpsc::channel(); - - Self { - sender, - receiver: Mutex::new(receiver), - } - } - - /// Add event into the event queue - pub(crate) fn add(&self, event: HermesEvent) -> anyhow::Result<()> { - self.sender.send(event).map_err(|_| QueueClosed)?; - Ok(()) - } -} - -impl Iterator for &HermesEventQueue { - type Item = HermesEvent; - - fn next(&mut self) -> Option { - self.receiver.lock().unwrap().try_recv().ok() - } -} diff --git a/hermes/bin/src/event/exec_manager.rs b/hermes/bin/src/event/exec_manager.rs deleted file mode 100644 index aed0793b4..000000000 --- a/hermes/bin/src/event/exec_manager.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! Hermes event execution manager implementation. - -use std::{collections::HashMap, sync::Arc}; - -use super::{event_queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}; -use crate::{ - app::HermesAppName, - runtime_extensions::state::State, - state::HermesState, - wasm::module::{Module, ModuleId}, -}; - -/// Hermes event queue error -#[derive(thiserror::Error, Debug, Clone)] -pub(crate) enum Error { - /// Target app not found. - #[error("Target app not found.")] - AppNotFound, - - /// Target module not found. - #[error("Target module not found.")] - ModuleNotFound, -} - -/// -pub(crate) struct HermesEventExecutionManager { - /// Targets to execute the event - targets: HashMap>, -} - -impl HermesEventExecutionManager { - /// - pub(crate) fn new() -> Self { - Self { - targets: HashMap::new(), - } - } - - /// - fn filtered_execution( - &mut self, event: &HermesEvent, state: &Arc, - ) -> anyhow::Result<()> { - match event.target_app() { - &TargetApp::All => { - for target_modules in self.targets.values_mut() { - match event.target_module() { - TargetModule::All => { - for module in target_modules.values_mut() { - module.execute_event( - event.payload(), - HermesState::new(state.clone()), - )?; - } - }, - TargetModule::_List(modules) => { - for module_id in modules { - let module = target_modules - .get_mut(module_id) - .ok_or(Error::ModuleNotFound)?; - - module.execute_event( - event.payload(), - HermesState::new(state.clone()), - )?; - } - }, - } - } - }, - TargetApp::_List(apps) => { - for app_name in apps { - let target_modules = - self.targets.get_mut(app_name).ok_or(Error::AppNotFound)?; - - match event.target_module() { - TargetModule::All => { - for module in target_modules.values_mut() { - module.execute_event( - event.payload(), - HermesState::new(state.clone()), - )?; - } - }, - TargetModule::_List(modules) => { - for module_id in modules { - let module = target_modules - .get_mut(module_id) - .ok_or(Error::ModuleNotFound)?; - module.execute_event( - event.payload(), - HermesState::new(state.clone()), - )?; - } - }, - } - } - }, - } - - Ok(()) - } - - /// Executes Hermes events from provided the event queue. - /// - /// # Note: - /// This is a blocking call and consumes the event queue. - #[allow(clippy::unnecessary_wraps, clippy::unwrap_used)] - pub(crate) fn event_execution_loop( - &mut self, event_queue: &HermesEventQueue, state: &Arc, - ) -> anyhow::Result<()> { - for event in event_queue { - self.filtered_execution(&event, state)?; - } - Ok(()) - } -} diff --git a/hermes/bin/src/event/mod.rs b/hermes/bin/src/event/mod.rs index f17e93a6e..774f8d689 100644 --- a/hermes/bin/src/event/mod.rs +++ b/hermes/bin/src/event/mod.rs @@ -1,7 +1,6 @@ //! Hermes event's primitives. -pub(crate) mod event_queue; -pub(crate) mod exec_manager; +pub(crate) mod queue; use crate::{ app::HermesAppName, diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs new file mode 100644 index 000000000..75803d8bf --- /dev/null +++ b/hermes/bin/src/event/queue.rs @@ -0,0 +1,138 @@ +//! Hermes event queue implementation. + +use std::{ + collections::HashMap, + sync::{ + mpsc::{Receiver, Sender}, + Arc, Mutex, + }, +}; + +use super::{HermesEvent, TargetApp, TargetModule}; +use crate::{ + app::HermesAppName, + runtime_extensions::state::State, + state::HermesState, + wasm::module::{Module, ModuleId}, +}; + +/// Hermes event queue error +#[derive(thiserror::Error, Debug, Clone)] +pub(crate) enum Error { + /// Target app not found. + #[error("Target app not found.")] + AppNotFound, + + /// Target module not found. + #[error("Target module not found.")] + ModuleNotFound, + + /// Failed to add event into the event queue. Event queue is closed. + #[error("Failed to add event into the event queue. Event queue is closed.")] + CanotAddEvent, + + /// Event execution loop panics in another thread. + #[error("Event execution loop panics in another thread. error: {0}")] + ExecutionLoopPanics(String), +} + +/// +pub(crate) struct HermesEventQueue { + /// Hermes event queue sender + sender: Sender, + /// Hermes event queue receiver + receiver: Mutex>, + + /// Targets to execute the event + targets: HashMap>, +} + +impl HermesEventQueue { + /// + pub(crate) fn new() -> Self { + let (sender, receiver) = std::sync::mpsc::channel(); + Self { + sender, + receiver: Mutex::new(receiver), + + targets: HashMap::new(), + } + } + + /// Add event into the event queue + pub(crate) fn add_into_queue(&self, event: HermesEvent) -> anyhow::Result<()> { + self.sender.send(event).map_err(|_| Error::CanotAddEvent)?; + Ok(()) + } + + /// Executes Hermes events from provided the event queue. + /// + /// # Note: + /// This is a blocking call. + pub(crate) fn event_execution_loop(&self, state: &Arc) -> anyhow::Result<()> { + let events = self + .receiver + .lock() + .map_err(|err| Error::ExecutionLoopPanics(err.to_string()))?; + + for event in events.iter() { + match event.target_app() { + &TargetApp::All => { + for target_modules in self.targets.values_mut() { + match event.target_module() { + TargetModule::All => { + for module in target_modules.values_mut() { + module.execute_event( + event.payload(), + HermesState::new(state.clone()), + )?; + } + }, + TargetModule::_List(modules) => { + for module_id in modules { + let module = target_modules + .get_mut(module_id) + .ok_or(Error::ModuleNotFound)?; + + module.execute_event( + event.payload(), + HermesState::new(state.clone()), + )?; + } + }, + } + } + }, + TargetApp::_List(apps) => { + for app_name in apps { + let target_modules = + self.targets.get_mut(app_name).ok_or(Error::AppNotFound)?; + + match event.target_module() { + TargetModule::All => { + for module in target_modules.values_mut() { + module.execute_event( + event.payload(), + HermesState::new(state.clone()), + )?; + } + }, + TargetModule::_List(modules) => { + for module_id in modules { + let module = target_modules + .get_mut(module_id) + .ok_or(Error::ModuleNotFound)?; + module.execute_event( + event.payload(), + HermesState::new(state.clone()), + )?; + } + }, + } + } + }, + } + } + Ok(()) + } +} diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 7848ed547..8b64d99e4 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -4,7 +4,7 @@ use std::{sync::Arc, thread}; use crate::{ app::HermesApp, - event::{event_queue::HermesEventQueue, exec_manager::HermesEventExecutionManager}, + event::queue::HermesEventQueue, runtime_extensions::state::{State, Stateful}, }; @@ -20,31 +20,23 @@ pub(crate) struct HermesReactor { /// Hermes event queue event_queue: Arc, - - /// - event_exec_manager: HermesEventExecutionManager, } impl HermesReactor { /// Create a new Hermes Reactor pub(crate) fn new(_apps: &Vec) -> Self { let event_queue = HermesEventQueue::new().into(); - let event_exec_manager = HermesEventExecutionManager::new(); let state = State::new().into(); - Self { - state, - event_queue, - event_exec_manager, - } + Self { state, event_queue } } /// Run Hermes. /// /// # Note: /// This is a blocking call util all tasks are finished. - pub(crate) fn run(mut self) -> anyhow::Result<()> { + pub(crate) fn run(self) -> anyhow::Result<()> { // Emits init event thread::spawn({ let event_queue = self.event_queue.clone(); @@ -54,11 +46,7 @@ impl HermesReactor { let events_thread = thread::spawn({ let state = self.state.clone(); - let event_queue = self.event_queue.clone(); - move || { - self.event_exec_manager - .event_execution_loop(&event_queue, &state) - } + move || self.event_queue.event_execution_loop(&state) }); events_thread diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index a146ccdeb..7e8f7eb0e 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,7 +1,7 @@ //! Init runtime extension implementation. use crate::{ - event::{event_queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}, + event::{queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}, runtime_extensions::state::Stateful, }; @@ -21,7 +21,7 @@ impl State { #[allow(clippy::unused_self)] pub(crate) fn emit_init_event(&self, event_queue: &HermesEventQueue) -> anyhow::Result<()> { let init_event = HermesEvent::new(event::InitEvent {}, TargetApp::All, TargetModule::All); - event_queue.add(init_event)?; + event_queue.add_into_queue(init_event)?; Ok(()) } } From c9ed23d51a106f82f0021603c8bd1c50a4a122c4 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 11:46:36 +0200 Subject: [PATCH 27/52] wip --- hermes/bin/src/event/queue.rs | 23 ++++++++++++----------- hermes/bin/src/wasm/module.rs | 14 ++++++++++---- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 75803d8bf..a2c50ded1 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -31,9 +31,10 @@ pub(crate) enum Error { #[error("Failed to add event into the event queue. Event queue is closed.")] CanotAddEvent, - /// Event execution loop panics in another thread. - #[error("Event execution loop panics in another thread. error: {0}")] - ExecutionLoopPanics(String), + /// Trying to execute one more event execution loop. It is allowed to run only one + /// execution loop in a time. + #[error("Trying to execute one more event execution loop. It is allowed to run only one execution loop in a time.")] + AnotherEventExecutionLoop, } /// @@ -72,16 +73,16 @@ impl HermesEventQueue { pub(crate) fn event_execution_loop(&self, state: &Arc) -> anyhow::Result<()> { let events = self .receiver - .lock() - .map_err(|err| Error::ExecutionLoopPanics(err.to_string()))?; + .try_lock() + .map_err(|_| Error::AnotherEventExecutionLoop)?; for event in events.iter() { match event.target_app() { &TargetApp::All => { - for target_modules in self.targets.values_mut() { + for target_modules in self.targets.values() { match event.target_module() { TargetModule::All => { - for module in target_modules.values_mut() { + for module in target_modules.values() { module.execute_event( event.payload(), HermesState::new(state.clone()), @@ -91,7 +92,7 @@ impl HermesEventQueue { TargetModule::_List(modules) => { for module_id in modules { let module = target_modules - .get_mut(module_id) + .get(module_id) .ok_or(Error::ModuleNotFound)?; module.execute_event( @@ -106,11 +107,11 @@ impl HermesEventQueue { TargetApp::_List(apps) => { for app_name in apps { let target_modules = - self.targets.get_mut(app_name).ok_or(Error::AppNotFound)?; + self.targets.get(app_name).ok_or(Error::AppNotFound)?; match event.target_module() { TargetModule::All => { - for module in target_modules.values_mut() { + for module in target_modules.values() { module.execute_event( event.payload(), HermesState::new(state.clone()), @@ -120,7 +121,7 @@ impl HermesEventQueue { TargetModule::_List(modules) => { for module_id in modules { let module = target_modules - .get_mut(module_id) + .get(module_id) .ok_or(Error::ModuleNotFound)?; module.execute_event( event.payload(), diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index c14f14b55..48a7f7242 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -4,6 +4,8 @@ //! //! All implementation based on [wasmtime](https://crates.io/crates/wasmtime) crate dependency. +use std::sync::atomic::{AtomicU32, Ordering}; + use rusty_ulid::Ulid; use wasmtime::{ component::{Component as WasmModule, InstancePre as WasmInstancePre, Linker as WasmLinker}, @@ -58,7 +60,7 @@ pub(crate) struct Module { id: ModuleId, /// Module's execution counter - exc_counter: u64, + exc_counter: AtomicU32, } impl Module { @@ -83,7 +85,7 @@ impl Module { pre_instance, engine, id: ModuleId(Ulid::generate()), - exc_counter: 0, + exc_counter: AtomicU32::new(0), }) } @@ -104,7 +106,7 @@ impl Module { /// - `BadModuleError` #[allow(dead_code)] pub(crate) fn execute_event( - &mut self, event: &dyn HermesEventPayload, state: HermesState, + &self, event: &dyn HermesEventPayload, state: HermesState, ) -> anyhow::Result<()> { let mut store = WasmStore::new(&self.engine, state); let (instance, _) = bindings::Hermes::instantiate_pre(&mut store, &self.pre_instance) @@ -112,7 +114,11 @@ impl Module { event.execute(&mut ModuleInstance { store, instance })?; - self.exc_counter += 1; + // Using the highest memory ordering constraint. + // It provides a highest consistency guarantee and in some cases could decrease + // perfomance. + // We could revise ordering approach for this case in future. + self.exc_counter.fetch_add(1, Ordering::SeqCst); Ok(()) } } From 06a54a87d508cca05400e488c61e1ae9d5d42492 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 11:57:42 +0200 Subject: [PATCH 28/52] update hermes state and context structs --- hermes/bin/src/event/queue.rs | 18 ++-- .../runtime_extensions/hermes/binary/host.rs | 4 +- .../runtime_extensions/hermes/cardano/host.rs | 4 +- .../runtime_extensions/hermes/cbor/host.rs | 4 +- .../runtime_extensions/hermes/cron/host.rs | 4 +- .../runtime_extensions/hermes/crypto/host.rs | 6 +- .../runtime_extensions/hermes/hash/host.rs | 4 +- .../runtime_extensions/hermes/json/host.rs | 4 +- .../hermes/kv_store/host.rs | 4 +- .../hermes/localtime/host.rs | 4 +- .../runtime_extensions/hermes/logging/host.rs | 4 +- hermes/bin/src/runtime_extensions/mod.rs | 101 ------------------ .../src/runtime_extensions/wasi/cli/host.rs | 10 +- .../wasi/clocks/monotonic/host.rs | 4 +- .../wasi/clocks/wall/host.rs | 4 +- .../wasi/filesystem/host.rs | 10 +- .../src/runtime_extensions/wasi/http/host.rs | 28 ++--- .../runtime_extensions/wasi/io/error/host.rs | 6 +- .../wasi/io/streams/host.rs | 8 +- .../wasi/random/insecure/host.rs | 6 +- .../wasi/random/insecure_seed/host.rs | 6 +- .../wasi/random/secure/host.rs | 4 +- hermes/bin/src/state.rs | 50 ++++----- hermes/bin/src/wasm/module.rs | 10 +- 24 files changed, 104 insertions(+), 203 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index a2c50ded1..627ba8b80 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -12,7 +12,7 @@ use super::{HermesEvent, TargetApp, TargetModule}; use crate::{ app::HermesAppName, runtime_extensions::state::State, - state::HermesState, + state::HermesRuntimeState, wasm::module::{Module, ModuleId}, }; @@ -37,7 +37,7 @@ pub(crate) enum Error { AnotherEventExecutionLoop, } -/// +/// Hermes event queue. pub(crate) struct HermesEventQueue { /// Hermes event queue sender sender: Sender, @@ -49,7 +49,7 @@ pub(crate) struct HermesEventQueue { } impl HermesEventQueue { - /// + /// Creates a new instance of the `HermesEventQueue`. pub(crate) fn new() -> Self { let (sender, receiver) = std::sync::mpsc::channel(); Self { @@ -68,6 +68,10 @@ impl HermesEventQueue { /// Executes Hermes events from provided the event queue. /// + /// # Errors: + /// - `Error::AnotherEventExecutionLoop` - Trying to execute one more event execution + /// loop. It is allowed to run only one execution loop in a time. + /// /// # Note: /// This is a blocking call. pub(crate) fn event_execution_loop(&self, state: &Arc) -> anyhow::Result<()> { @@ -85,7 +89,7 @@ impl HermesEventQueue { for module in target_modules.values() { module.execute_event( event.payload(), - HermesState::new(state.clone()), + HermesRuntimeState::new(state.clone()), )?; } }, @@ -97,7 +101,7 @@ impl HermesEventQueue { module.execute_event( event.payload(), - HermesState::new(state.clone()), + HermesRuntimeState::new(state.clone()), )?; } }, @@ -114,7 +118,7 @@ impl HermesEventQueue { for module in target_modules.values() { module.execute_event( event.payload(), - HermesState::new(state.clone()), + HermesRuntimeState::new(state.clone()), )?; } }, @@ -125,7 +129,7 @@ impl HermesEventQueue { .ok_or(Error::ModuleNotFound)?; module.execute_event( event.payload(), - HermesState::new(state.clone()), + HermesRuntimeState::new(state.clone()), )?; } }, diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs index 7eddd020f..baa6b3d2d 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs @@ -1,5 +1,5 @@ //! Binary host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::hermes::binary::api::Host, state::HermesState}; +use crate::{runtime_extensions::bindings::hermes::binary::api::Host, state::HermesRuntimeState}; -impl Host for HermesState {} +impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs index 1949e263e..3fb6a84f7 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs @@ -5,10 +5,10 @@ use crate::{ CardanoBlock, CardanoBlockchainId, CardanoTxn, FetchError, Host, Slot, TxnError, UnsubscribeOptions, }, - state::HermesState, + state::HermesRuntimeState, }; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Subscribe to the Blockchain block data. /// /// **Parameters** diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs index ccd135018..b080a7a9c 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs @@ -1,5 +1,5 @@ //! CBOR host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::hermes::cbor::api::Host, state::HermesState}; +use crate::{runtime_extensions::bindings::hermes::cbor::api::Host, state::HermesRuntimeState}; -impl Host for HermesState {} +impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs index 75260877b..aa8638e6b 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs @@ -5,10 +5,10 @@ use crate::{ hermes::cron::api::{CronEventTag, CronSched, CronTagged, CronTime, Host}, wasi::clocks::monotonic_clock::Instant, }, - state::HermesState, + state::HermesRuntimeState, }; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// # Schedule Recurrent CRON event /// /// Cron events will be delivered to the `on-cron` event handler. diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs index c014e60be..5284b5a54 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs @@ -8,10 +8,10 @@ use crate::{ Host, HostEd25519Bip32, }, }, - state::HermesState, + state::HermesRuntimeState, }; -impl HostEd25519Bip32 for HermesState { +impl HostEd25519Bip32 for HermesRuntimeState { /// Create a new ED25519-BIP32 Crypto resource /// /// **Parameters** @@ -81,4 +81,4 @@ impl HostEd25519Bip32 for HermesState { } } -impl Host for HermesState {} +impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs index a50f9b50f..d2be226de 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs @@ -6,10 +6,10 @@ use crate::{ binary::api::Bstr, hash::api::{Errno, Host}, }, - state::HermesState, + state::HermesRuntimeState, }; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Hash a binary buffer with BLAKE2s fn blake2s( &mut self, _buf: Bstr, _outlen: Option, diff --git a/hermes/bin/src/runtime_extensions/hermes/json/host.rs b/hermes/bin/src/runtime_extensions/hermes/json/host.rs index 00e7e46c8..efcea1d18 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/host.rs @@ -1,5 +1,5 @@ //! JSON host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::hermes::json::api::Host, state::HermesState}; +use crate::{runtime_extensions::bindings::hermes::json::api::Host, state::HermesRuntimeState}; -impl Host for HermesState {} +impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs index eb9647e55..c34d83188 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::hermes::kv_store::api::{Host, KvValues}, - state::HermesState, + state::HermesRuntimeState, }; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Set a value in the local key-value store /// Setting None will cause the Key to be deleted from the KV store. fn kv_set(&mut self, _key: String, _value: Option) -> wasmtime::Result<()> { diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs index 67af83d8b..5e3fbf946 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs @@ -5,10 +5,10 @@ use crate::{ hermes::localtime::api::{Errno, Host, Localtime, Timezone}, wasi::clocks::wall_clock::Datetime, }, - state::HermesState, + state::HermesRuntimeState, }; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Get localtime from a datetime or now. /// /// **Parameters** diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs index dd3962815..d6f6c3d17 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs @@ -5,10 +5,10 @@ use crate::{ json::api::Json, logging::api::{Host, Level}, }, - state::HermesState, + state::HermesRuntimeState, }; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Generate a Log /// /// The Hermes API will add extra information to the log, such as the instance of the diff --git a/hermes/bin/src/runtime_extensions/mod.rs b/hermes/bin/src/runtime_extensions/mod.rs index 25c76094a..bb903288e 100644 --- a/hermes/bin/src/runtime_extensions/mod.rs +++ b/hermes/bin/src/runtime_extensions/mod.rs @@ -4,104 +4,3 @@ pub(crate) mod bindings; pub(crate) mod hermes; pub(crate) mod state; pub(crate) mod wasi; - -// /// Example of how to call the autogenerated entry points -// #[allow(dead_code)] -// fn example() -> anyhow::Result<()> { -// use wasmtime::{ -// component::{Component, Linker}, -// Config, Engine, Store, -// }; - -// use self::bindings::{ -// exports::hermes::cardano::event_on_block::BlockSrc, -// hermes::{ -// cardano::api::{CardanoBlock, CardanoBlockchainId, CardanoTxn}, -// cron::api::CronTagged, -// }, -// }; -// use crate::{state::HermesState, wasm::context::Context}; - -// // Configure an `Engine` and compile the `Component` that is being run for -// // the application. -// let mut config = Config::new(); -// config.wasm_component_model(true); -// let engine = Engine::new(&config)?; -// let component = Component::from_file(&engine, "./your-component.wasm")?; - -// // Instantiation of bindings always happens through a `Linker`. -// // -// // Note that the closure provided here is a projection from `T` in -// // `Store` to `&mut U` where `U` implements the `HelloWorldImports` -// // trait. In this case the `T`, `MyState`, is stored directly in the -// // structure so no projection is necessary here. -// let mut linker = Linker::new(&engine); -// bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesState| state)?; - -// let instance_pre = linker.instantiate_pre(&component)?; - -// // As with the core wasm API of Wasmtime instantiation occurs within a -// // `Store`. The bindings structure contains an `instantiate` method which -// // takes the store, component, and linker. This returns the `bindings` -// // structure which is an instance of `HelloWorld` and supports typed access -// // to the exports of the component. -// let mut store = Store::new( -// &engine, -// HermesState::new(Context::new("my-app".to_string())), -// ); - -// // -// let (bindings, _) = bindings::Hermes::instantiate_pre(&mut store, &instance_pre)?; - -// // Show how we call the events in our API. -// let _result = bindings.hermes_init_event().call_init(&mut store)?; - -// // HTTP API to be rewritten, but this is how its called. -// // let arg1 = ??; -// // let arg2 = ??; -// // let result = bindings.interface0.call_handle(&mut store, arg1, arg2)?; - -// // Example of calling on_block. -// let arg0 = CardanoBlockchainId::Mainnet; -// let arg1 = CardanoBlock::new(); -// let arg2 = BlockSrc::TIP; -// bindings -// .hermes_cardano_event_on_block() -// .call_on_cardano_block(&mut store, arg0, &arg1, arg2)?; - -// // Example of calling on_txn. -// let arg0 = CardanoBlockchainId::Mainnet; -// let arg1: u64 = 123_456; -// let arg2: u32 = 12; -// let arg3 = CardanoTxn::new(); - -// bindings -// .hermes_cardano_event_on_txn() -// .call_on_cardano_txn(&mut store, arg0, arg1, arg2, &arg3)?; - -// // Example of calling on_rollback. -// let arg0 = CardanoBlockchainId::Mainnet; -// let arg1: u64 = 123_456; -// bindings -// .hermes_cardano_event_on_rollback() -// .call_on_cardano_rollback(&mut store, arg0, arg1)?; - -// // Example of calling on_cron. -// let arg0 = CronTagged { -// when: "* * * * *".to_string(), -// tag: "tag".to_string(), -// }; -// let arg1 = false; -// let _result = bindings -// .hermes_cron_event() -// .call_on_cron(&mut store, &arg0, arg1)?; - -// // Example of calling kv_update -// let arg0 = "key"; -// let arg1 = -// bindings::hermes::kv_store::api::KvValues::KvString("value".to_string()); bindings -// .hermes_kv_store_event() -// .call_kv_update(&mut store, arg0, &arg1)?; - -// Ok(()) -// } diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs index 68f22faec..a3fe4f55f 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs @@ -5,10 +5,10 @@ use crate::{ cli, io::streams::{InputStream, OutputStream}, }, - state::HermesState, + state::HermesRuntimeState, }; -impl cli::environment::Host for HermesState { +impl cli::environment::Host for HermesRuntimeState { /// Get the POSIX-style environment variables. /// /// Each environment variable is provided as a pair of string variable names @@ -33,19 +33,19 @@ impl cli::environment::Host for HermesState { } } -impl cli::stdin::Host for HermesState { +impl cli::stdin::Host for HermesRuntimeState { fn get_stdin(&mut self) -> wasmtime::Result> { todo!() } } -impl cli::stdout::Host for HermesState { +impl cli::stdout::Host for HermesRuntimeState { fn get_stdout(&mut self) -> wasmtime::Result> { todo!() } } -impl cli::stderr::Host for HermesState { +impl cli::stderr::Host for HermesRuntimeState { fn get_stderr(&mut self) -> wasmtime::Result> { todo!() } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs index 77eb45e4e..d1fd0c43d 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, - state::HermesState, + state::HermesRuntimeState, }; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Read the current value of the clock. /// /// The clock is monotonic, therefore calling this function repeatedly will diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs index e6d043eee..2ffbce258 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::wasi::clocks::wall_clock::{Datetime, Host}, - state::HermesState, + state::HermesRuntimeState, }; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Read the current value of the clock. /// /// This clock is not monotonic, therefore calling this function repeatedly diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs index a61460e3b..a211ad3f3 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs @@ -12,10 +12,10 @@ use crate::{ }, io::streams::{InputStream, OutputStream}, }, - state::HermesState, + state::HermesRuntimeState, }; -impl filesystem::types::HostDescriptor for HermesState { +impl filesystem::types::HostDescriptor for HermesRuntimeState { /// Return a stream for reading from a file, if available. /// /// May fail with an error-code describing why the file cannot be read. @@ -386,7 +386,7 @@ impl filesystem::types::HostDescriptor for HermesState { } } -impl filesystem::types::HostDirectoryEntryStream for HermesState { +impl filesystem::types::HostDirectoryEntryStream for HermesRuntimeState { /// Read a single directory entry from a `directory-entry-stream`. fn read_directory_entry( &mut self, _dir: wasmtime::component::Resource, @@ -401,7 +401,7 @@ impl filesystem::types::HostDirectoryEntryStream for HermesState { } } -impl filesystem::types::Host for HermesState { +impl filesystem::types::Host for HermesRuntimeState { /// Attempts to extract a filesystem-related `error-code` from the stream /// `error` provided. /// @@ -419,7 +419,7 @@ impl filesystem::types::Host for HermesState { } } -impl filesystem::preopens::Host for HermesState { +impl filesystem::preopens::Host for HermesRuntimeState { /// Return the set of preopened directories, and their path. fn get_directories( &mut self, diff --git a/hermes/bin/src/runtime_extensions/wasi/http/host.rs b/hermes/bin/src/runtime_extensions/wasi/http/host.rs index 817a025ce..c6e500b9c 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/host.rs @@ -16,10 +16,10 @@ use crate::{ }, io::streams::{InputStream, OutputStream}, }, - state::HermesState, + state::HermesRuntimeState, }; -impl http::types::HostFutureIncomingResponse for HermesState { +impl http::types::HostFutureIncomingResponse for HermesRuntimeState { /// Returns the incoming HTTP Response, or an error, once one is ready. /// /// The outer `option` represents future readiness. Users can wait on this @@ -49,7 +49,7 @@ impl http::types::HostFutureIncomingResponse for HermesState { } } -impl http::types::HostFields for HermesState { +impl http::types::HostFields for HermesRuntimeState { /// Construct an empty HTTP Fields. /// /// The resulting `fields` is mutable. @@ -154,7 +154,7 @@ impl http::types::HostFields for HermesState { } } -impl http::types::HostFutureTrailers for HermesState { +impl http::types::HostFutureTrailers for HermesRuntimeState { /// Returns the contents of the trailers, or an error which occurred, /// once the future is ready. /// @@ -189,7 +189,7 @@ impl http::types::HostFutureTrailers for HermesState { } } -impl http::types::HostOutgoingBody for HermesState { +impl http::types::HostOutgoingBody for HermesRuntimeState { /// Returns a stream for writing the body contents. /// /// The returned `output-stream` is a child resource: it must be dropped @@ -226,7 +226,7 @@ impl http::types::HostOutgoingBody for HermesState { } } -impl HostOutgoingResponse for HermesState { +impl HostOutgoingResponse for HermesRuntimeState { /// Construct an `outgoing-response`, with a default `status-code` of `200`. /// If a different `status-code` is needed, it must be set via the /// `set-status-code` method. @@ -285,7 +285,7 @@ impl HostOutgoingResponse for HermesState { } } -impl http::types::HostIncomingBody for HermesState { +impl http::types::HostIncomingBody for HermesRuntimeState { /// Returns the contents of the body, as a stream of bytes. /// /// Returns success on first call: the stream representing the contents @@ -320,7 +320,7 @@ impl http::types::HostIncomingBody for HermesState { } } -impl HostIncomingResponse for HermesState { +impl HostIncomingResponse for HermesRuntimeState { /// Returns the status code from the incoming response. fn status( &mut self, _rep: wasmtime::component::Resource, @@ -356,7 +356,7 @@ impl HostIncomingResponse for HermesState { } } -impl http::types::HostResponseOutparam for HermesState { +impl http::types::HostResponseOutparam for HermesRuntimeState { /// Set the value of the `response-outparam` to either send a response, /// or indicate an error. /// @@ -380,7 +380,7 @@ impl http::types::HostResponseOutparam for HermesState { } } -impl http::types::HostRequestOptions for HermesState { +impl http::types::HostRequestOptions for HermesRuntimeState { /// Construct a default `request-options` value. fn new(&mut self) -> wasmtime::Result> { todo!() @@ -440,7 +440,7 @@ impl http::types::HostRequestOptions for HermesState { } } -impl http::types::HostOutgoingRequest for HermesState { +impl http::types::HostOutgoingRequest for HermesRuntimeState { /// Construct a new `outgoing-request` with a default `method` of `GET`, and /// `none` values for `path-with-query`, `scheme`, and `authority`. /// @@ -559,7 +559,7 @@ impl http::types::HostOutgoingRequest for HermesState { } } -impl http::types::HostIncomingRequest for HermesState { +impl http::types::HostIncomingRequest for HermesRuntimeState { /// Returns the method of the incoming request. fn method( &mut self, _rep: wasmtime::component::Resource, @@ -617,7 +617,7 @@ impl http::types::HostIncomingRequest for HermesState { } } -impl http::types::Host for HermesState { +impl http::types::Host for HermesRuntimeState { /// Attempts to extract a http-related `error` from the wasi:io `error` /// provided. /// @@ -636,7 +636,7 @@ impl http::types::Host for HermesState { } } -impl http::outgoing_handler::Host for HermesState { +impl http::outgoing_handler::Host for HermesRuntimeState { /// This function is invoked with an outgoing HTTP Request, and it returns /// a resource `future-incoming-response` which represents an HTTP Response /// which may arrive in the future. diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs index c83020e96..60d322f28 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::wasi::io::error::{Error, Host, HostError}, - state::HermesState, + state::HermesRuntimeState, }; -impl HostError for HermesState { +impl HostError for HermesRuntimeState { /// Returns a string that is suitable to assist humans in debugging /// this error. /// @@ -24,4 +24,4 @@ impl HostError for HermesState { } } -impl Host for HermesState {} +impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs index 945924104..31652cf31 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs @@ -4,10 +4,10 @@ use crate::{ runtime_extensions::bindings::wasi::io::streams::{ Host, HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, }, - state::HermesState, + state::HermesRuntimeState, }; -impl HostInputStream for HermesState { +impl HostInputStream for HermesRuntimeState { /// Perform a non-blocking read from the stream. /// /// This function returns a list of bytes containing the read data, @@ -66,7 +66,7 @@ impl HostInputStream for HermesState { } } -impl HostOutputStream for HermesState { +impl HostOutputStream for HermesRuntimeState { /// Check readiness for writing. This function never blocks. /// /// Returns the number of bytes permitted for the next call to `write`, @@ -228,4 +228,4 @@ impl HostOutputStream for HermesState { } } -impl Host for HermesState {} +impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs index 05efa3e72..81d4bed33 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs @@ -1,8 +1,10 @@ //! Insecure RNG host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::wasi::random::insecure::Host, state::HermesState}; +use crate::{ + runtime_extensions::bindings::wasi::random::insecure::Host, state::HermesRuntimeState, +}; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Return `len` insecure pseudo-random bytes. /// /// This function is not cryptographically secure. Do not use it for diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs index 2037d52b7..c3082528c 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs @@ -1,8 +1,10 @@ //! Insecure RNG seed host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::wasi::random::insecure_seed::Host, state::HermesState}; +use crate::{ + runtime_extensions::bindings::wasi::random::insecure_seed::Host, state::HermesRuntimeState, +}; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Return a 128-bit value that may contain a pseudo-random value. /// /// The returned value is not required to be computed from a Cryptographically Secure diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs index 93f0f9c1e..c30de0563 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs @@ -1,8 +1,8 @@ //! Random RNG host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::wasi::random::random::Host, state::HermesState}; +use crate::{runtime_extensions::bindings::wasi::random::random::Host, state::HermesRuntimeState}; -impl Host for HermesState { +impl Host for HermesRuntimeState { /// Return `len` cryptographically-secure random or pseudo-random bytes. /// /// This function must produce data at least as cryptographically secure and diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/state.rs index 53d92cdf1..1fed673b2 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/state.rs @@ -2,80 +2,74 @@ use std::sync::Arc; -use rusty_ulid::Ulid; - -use crate::runtime_extensions::state::State; +use crate::{app::HermesAppName, runtime_extensions::state::State, wasm::module::ModuleId}; #[allow(dead_code)] /// State for Hermes state -pub(crate) struct HermesState { +pub(crate) struct HermesRuntimeState { /// Runtime extensions state pub(crate) state: Arc, // /// The context of the wasm modules using this State. // pub(crate) ctx: Context, } -impl HermesState { +impl HermesRuntimeState { /// Creates a new instance of the `HermesState`. - pub(crate) fn new(state: Arc) -> HermesState { + pub(crate) fn new(state: Arc) -> HermesRuntimeState { Self { state } } } /// A Hermes running context, which should be passed to the WASM runtime. -#[derive(Clone)] -pub(crate) struct Context { +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) struct HermesRuntimeContext { /// Hermes application name - app_name: String, + app_name: HermesAppName, /// module ULID id - module_id: Ulid, + module_id: ModuleId, /// event name to be executed - event_name: Option, + event_name: String, /// module's execution counter - counter: u64, + exc_counter: u64, } -impl Context { +impl HermesRuntimeContext { /// Creates a new instance of the `Context`. - pub(crate) fn _new(app_name: String) -> Self { + pub(crate) fn _new( + app_name: HermesAppName, module_id: ModuleId, event_name: String, exc_counter: u64, + ) -> Self { Self { app_name, - module_id: Ulid::generate(), - event_name: None, - counter: 0, + module_id, + event_name, + exc_counter, } } - /// Increments the module's execution counter and sets the event name to be executed - pub(crate) fn _use_for(&mut self, event_name: String) { - self.event_name = Some(event_name); - self.counter += 1; - } - /// Get the application name #[allow(dead_code)] - pub(crate) fn app_name(&self) -> &str { + pub(crate) fn app_name(&self) -> &HermesAppName { &self.app_name } /// Get the module id #[allow(dead_code)] - pub(crate) fn module_id(&self) -> &Ulid { + pub(crate) fn module_id(&self) -> &ModuleId { &self.module_id } /// Get the event name #[allow(dead_code)] - pub(crate) fn event_name(&self) -> Option<&String> { + pub(crate) fn event_name(&self) -> &str { self.event_name.as_ref() } /// Get the counter value #[allow(dead_code)] - pub(crate) fn counter(&self) -> u64 { - self.counter + pub(crate) fn exc_counter(&self) -> u64 { + self.exc_counter } } diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 48a7f7242..4b3fa67f4 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -13,7 +13,7 @@ use wasmtime::{ }; use crate::{ - event::HermesEventPayload, runtime_extensions::bindings, state::HermesState, + event::HermesEventPayload, runtime_extensions::bindings, state::HermesRuntimeState, wasm::engine::Engine, }; @@ -27,7 +27,7 @@ struct BadWASMModuleError(String); /// It is used to interact with the WASM module. pub(crate) struct ModuleInstance { /// `wasmtime::Store` entity - pub(crate) store: WasmStore, + pub(crate) store: WasmStore, /// `Instance` entity pub(crate) instance: bindings::Hermes, } @@ -51,7 +51,7 @@ pub(crate) struct Module { /// partially described in this [RFC](https://github.com/bytecodealliance/rfcs/blob/main/accepted/shared-host-functions.md). /// It separates and optimizes the linkage of the imports to the WASM runtime from the /// module actual initialization process. - pre_instance: WasmInstancePre, + pre_instance: WasmInstancePre, /// `Engine` entity engine: Engine, @@ -75,7 +75,7 @@ impl Module { .map_err(|e| BadWASMModuleError(e.to_string()))?; let mut linker = WasmLinker::new(&engine); - bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesState| state) + bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesRuntimeState| state) .map_err(|e| BadWASMModuleError(e.to_string()))?; let pre_instance = linker .instantiate_pre(&module) @@ -106,7 +106,7 @@ impl Module { /// - `BadModuleError` #[allow(dead_code)] pub(crate) fn execute_event( - &self, event: &dyn HermesEventPayload, state: HermesState, + &self, event: &dyn HermesEventPayload, state: HermesRuntimeState, ) -> anyhow::Result<()> { let mut store = WasmStore::new(&self.engine, state); let (instance, _) = bindings::Hermes::instantiate_pre(&mut store, &self.pre_instance) From 999ad00de086ccd0691d820c96da76a8e0ff6a42 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 12:01:03 +0200 Subject: [PATCH 29/52] rename state to runtime_state --- hermes/bin/src/event/queue.rs | 2 +- hermes/bin/src/lib.rs | 2 +- hermes/bin/src/main.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/binary/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/cardano/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/cbor/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/cron/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/crypto/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/hash/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/json/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/localtime/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/logging/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/cli/host.rs | 2 +- .../bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/http/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/io/error/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs | 2 +- .../bin/src/runtime_extensions/wasi/random/insecure/host.rs | 2 +- .../src/runtime_extensions/wasi/random/insecure_seed/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs | 2 +- hermes/bin/src/{state.rs => runtime_state.rs} | 4 ++-- hermes/bin/src/wasm/module.rs | 2 +- 25 files changed, 26 insertions(+), 26 deletions(-) rename hermes/bin/src/{state.rs => runtime_state.rs} (94%) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 627ba8b80..97934e708 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -12,7 +12,7 @@ use super::{HermesEvent, TargetApp, TargetModule}; use crate::{ app::HermesAppName, runtime_extensions::state::State, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, wasm::module::{Module, ModuleId}, }; diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index ccbf86347..a7daed652 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -6,5 +6,5 @@ mod event; #[allow(dead_code)] mod reactor; mod runtime_extensions; -mod state; +mod runtime_state; mod wasm; diff --git a/hermes/bin/src/main.rs b/hermes/bin/src/main.rs index 4c6d36a07..bdb371543 100644 --- a/hermes/bin/src/main.rs +++ b/hermes/bin/src/main.rs @@ -5,7 +5,7 @@ mod event; #[allow(dead_code)] mod reactor; mod runtime_extensions; -mod state; +mod runtime_state; mod wasm; fn main() { diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs index baa6b3d2d..9dac7d130 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs @@ -1,5 +1,5 @@ //! Binary host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::hermes::binary::api::Host, state::HermesRuntimeState}; +use crate::{runtime_extensions::bindings::hermes::binary::api::Host, runtime_state::HermesRuntimeState}; impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs index 3fb6a84f7..0ed5f4d59 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs @@ -5,7 +5,7 @@ use crate::{ CardanoBlock, CardanoBlockchainId, CardanoTxn, FetchError, Host, Slot, TxnError, UnsubscribeOptions, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs index b080a7a9c..b188177e0 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs @@ -1,5 +1,5 @@ //! CBOR host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::hermes::cbor::api::Host, state::HermesRuntimeState}; +use crate::{runtime_extensions::bindings::hermes::cbor::api::Host, runtime_state::HermesRuntimeState}; impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs index aa8638e6b..b68cc84fb 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs @@ -5,7 +5,7 @@ use crate::{ hermes::cron::api::{CronEventTag, CronSched, CronTagged, CronTime, Host}, wasi::clocks::monotonic_clock::Instant, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs index 5284b5a54..803c92559 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs @@ -8,7 +8,7 @@ use crate::{ Host, HostEd25519Bip32, }, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl HostEd25519Bip32 for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs index d2be226de..e3f1c2318 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs @@ -6,7 +6,7 @@ use crate::{ binary::api::Bstr, hash::api::{Errno, Host}, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/hermes/json/host.rs b/hermes/bin/src/runtime_extensions/hermes/json/host.rs index efcea1d18..b6a0efcfc 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/host.rs @@ -1,5 +1,5 @@ //! JSON host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::hermes::json::api::Host, state::HermesRuntimeState}; +use crate::{runtime_extensions::bindings::hermes::json::api::Host, runtime_state::HermesRuntimeState}; impl Host for HermesRuntimeState {} diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs index c34d83188..fb9580276 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs @@ -2,7 +2,7 @@ use crate::{ runtime_extensions::bindings::hermes::kv_store::api::{Host, KvValues}, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs index 5e3fbf946..90960b94a 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs @@ -5,7 +5,7 @@ use crate::{ hermes::localtime::api::{Errno, Host, Localtime, Timezone}, wasi::clocks::wall_clock::Datetime, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs index d6f6c3d17..7d6d7eb1c 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs @@ -5,7 +5,7 @@ use crate::{ json::api::Json, logging::api::{Host, Level}, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs index a3fe4f55f..b3a2799d3 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs @@ -5,7 +5,7 @@ use crate::{ cli, io::streams::{InputStream, OutputStream}, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl cli::environment::Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs index d1fd0c43d..4d4207cf2 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs @@ -2,7 +2,7 @@ use crate::{ runtime_extensions::bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs index 2ffbce258..db71a414e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs @@ -2,7 +2,7 @@ use crate::{ runtime_extensions::bindings::wasi::clocks::wall_clock::{Datetime, Host}, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs index a211ad3f3..02cc79675 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs @@ -12,7 +12,7 @@ use crate::{ }, io::streams::{InputStream, OutputStream}, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl filesystem::types::HostDescriptor for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/http/host.rs b/hermes/bin/src/runtime_extensions/wasi/http/host.rs index c6e500b9c..397d51f97 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/host.rs @@ -16,7 +16,7 @@ use crate::{ }, io::streams::{InputStream, OutputStream}, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl http::types::HostFutureIncomingResponse for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs index 60d322f28..7d164adb0 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs @@ -2,7 +2,7 @@ use crate::{ runtime_extensions::bindings::wasi::io::error::{Error, Host, HostError}, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl HostError for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs index 31652cf31..6dd97f5cc 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs @@ -4,7 +4,7 @@ use crate::{ runtime_extensions::bindings::wasi::io::streams::{ Host, HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, }, - state::HermesRuntimeState, + runtime_state::HermesRuntimeState, }; impl HostInputStream for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs index 81d4bed33..f2f62426d 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs @@ -1,7 +1,7 @@ //! Insecure RNG host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::random::insecure::Host, state::HermesRuntimeState, + runtime_extensions::bindings::wasi::random::insecure::Host, runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs index c3082528c..fdd7e190e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs @@ -1,7 +1,7 @@ //! Insecure RNG seed host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::random::insecure_seed::Host, state::HermesRuntimeState, + runtime_extensions::bindings::wasi::random::insecure_seed::Host, runtime_state::HermesRuntimeState, }; impl Host for HermesRuntimeState { diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs index c30de0563..4f376d65f 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs @@ -1,6 +1,6 @@ //! Random RNG host implementation for WASM runtime. -use crate::{runtime_extensions::bindings::wasi::random::random::Host, state::HermesRuntimeState}; +use crate::{runtime_extensions::bindings::wasi::random::random::Host, runtime_state::HermesRuntimeState}; impl Host for HermesRuntimeState { /// Return `len` cryptographically-secure random or pseudo-random bytes. diff --git a/hermes/bin/src/state.rs b/hermes/bin/src/runtime_state.rs similarity index 94% rename from hermes/bin/src/state.rs rename to hermes/bin/src/runtime_state.rs index 1fed673b2..e7addc3f8 100644 --- a/hermes/bin/src/state.rs +++ b/hermes/bin/src/runtime_state.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use crate::{app::HermesAppName, runtime_extensions::state::State, wasm::module::ModuleId}; #[allow(dead_code)] -/// State for Hermes state +/// Hermes Runtime state. This state is passed to the WASM runtime. pub(crate) struct HermesRuntimeState { /// Runtime extensions state pub(crate) state: Arc, @@ -20,7 +20,7 @@ impl HermesRuntimeState { } } -/// A Hermes running context, which should be passed to the WASM runtime. +/// Hermes Runtime Context. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub(crate) struct HermesRuntimeContext { /// Hermes application name diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 4b3fa67f4..274a5f430 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -13,7 +13,7 @@ use wasmtime::{ }; use crate::{ - event::HermesEventPayload, runtime_extensions::bindings, state::HermesRuntimeState, + event::HermesEventPayload, runtime_extensions::bindings, runtime_state::HermesRuntimeState, wasm::engine::Engine, }; From f2349d807ff9d7dd799c7e9d34168765d43eb656 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 13:22:50 +0200 Subject: [PATCH 30/52] wip --- hermes/bin/src/event/queue.rs | 141 ++++++++++++++++++-------------- hermes/bin/src/runtime_state.rs | 18 ++-- hermes/bin/src/wasm/module.rs | 13 ++- 3 files changed, 100 insertions(+), 72 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 97934e708..0cff5d9ca 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -8,11 +8,11 @@ use std::{ }, }; -use super::{HermesEvent, TargetApp, TargetModule}; +use super::{HermesEvent, HermesEventPayload, TargetApp, TargetModule}; use crate::{ app::HermesAppName, runtime_extensions::state::State, - runtime_state::HermesRuntimeState, + runtime_state::{HermesRuntimeContext, HermesRuntimeState}, wasm::module::{Module, ModuleId}, }; @@ -44,8 +44,8 @@ pub(crate) struct HermesEventQueue { /// Hermes event queue receiver receiver: Mutex>, - /// Targets to execute the event - targets: HashMap>, + /// Current available hermes apps with their modules + apps: HashMap>, } impl HermesEventQueue { @@ -56,7 +56,7 @@ impl HermesEventQueue { sender, receiver: Mutex::new(receiver), - targets: HashMap::new(), + apps: HashMap::new(), } } @@ -66,6 +66,80 @@ impl HermesEventQueue { Ok(()) } + /// Execute a hermes event on the provided module and all necesary info. + fn execute( + app_name: HermesAppName, module_id: ModuleId, state: &Arc, + event: &dyn HermesEventPayload, module: &Module, + ) -> anyhow::Result<()> { + let runtime_context = HermesRuntimeContext::new( + app_name, + module_id, + event.event_name().to_string(), + module.exec_counter(), + ); + + let runtime_state = HermesRuntimeState::new(state.clone(), runtime_context); + module.execute_event(event, runtime_state)?; + Ok(()) + } + + /// Executes provided Hermes event filtering by target app and target module. + /// + /// # Errors: + /// - `Error::ModuleNotFound` + /// - `Error::AppNotFound` + fn filtered_execution(&self, event: &HermesEvent, state: &Arc) -> anyhow::Result<()> { + let filtered_modules_exec = |target_module: &TargetModule, + app_name: &HermesAppName, + modules: &HashMap| + -> anyhow::Result<()> { + match target_module { + TargetModule::All => { + for (module_id, module) in modules { + Self::execute( + app_name.clone(), + module_id.clone(), + state, + event.payload(), + module, + )?; + } + }, + TargetModule::_List(target_modules) => { + for module_id in target_modules { + let module = modules.get(module_id).ok_or(Error::ModuleNotFound)?; + + Self::execute( + app_name.clone(), + module_id.clone(), + state, + event.payload(), + module, + )?; + } + }, + } + Ok(()) + }; + + match event.target_app() { + TargetApp::All => { + for (app_name, modules) in &self.apps { + filtered_modules_exec(event.target_module(), app_name, modules)?; + } + }, + TargetApp::_List(apps) => { + for app_name in apps { + let modules = self.apps.get(app_name).ok_or(Error::AppNotFound)?; + + filtered_modules_exec(event.target_module(), app_name, modules)?; + } + }, + } + + Ok(()) + } + /// Executes Hermes events from provided the event queue. /// /// # Errors: @@ -81,62 +155,7 @@ impl HermesEventQueue { .map_err(|_| Error::AnotherEventExecutionLoop)?; for event in events.iter() { - match event.target_app() { - &TargetApp::All => { - for target_modules in self.targets.values() { - match event.target_module() { - TargetModule::All => { - for module in target_modules.values() { - module.execute_event( - event.payload(), - HermesRuntimeState::new(state.clone()), - )?; - } - }, - TargetModule::_List(modules) => { - for module_id in modules { - let module = target_modules - .get(module_id) - .ok_or(Error::ModuleNotFound)?; - - module.execute_event( - event.payload(), - HermesRuntimeState::new(state.clone()), - )?; - } - }, - } - } - }, - TargetApp::_List(apps) => { - for app_name in apps { - let target_modules = - self.targets.get(app_name).ok_or(Error::AppNotFound)?; - - match event.target_module() { - TargetModule::All => { - for module in target_modules.values() { - module.execute_event( - event.payload(), - HermesRuntimeState::new(state.clone()), - )?; - } - }, - TargetModule::_List(modules) => { - for module_id in modules { - let module = target_modules - .get(module_id) - .ok_or(Error::ModuleNotFound)?; - module.execute_event( - event.payload(), - HermesRuntimeState::new(state.clone()), - )?; - } - }, - } - } - }, - } + self.filtered_execution(&event, state)?; } Ok(()) } diff --git a/hermes/bin/src/runtime_state.rs b/hermes/bin/src/runtime_state.rs index e7addc3f8..40553b5ca 100644 --- a/hermes/bin/src/runtime_state.rs +++ b/hermes/bin/src/runtime_state.rs @@ -9,14 +9,14 @@ use crate::{app::HermesAppName, runtime_extensions::state::State, wasm::module:: pub(crate) struct HermesRuntimeState { /// Runtime extensions state pub(crate) state: Arc, - // /// The context of the wasm modules using this State. - // pub(crate) ctx: Context, + /// Runtime context. + pub(crate) ctx: HermesRuntimeContext, } impl HermesRuntimeState { /// Creates a new instance of the `HermesState`. - pub(crate) fn new(state: Arc) -> HermesRuntimeState { - Self { state } + pub(crate) fn new(state: Arc, ctx: HermesRuntimeContext) -> HermesRuntimeState { + Self { state, ctx } } } @@ -26,20 +26,20 @@ pub(crate) struct HermesRuntimeContext { /// Hermes application name app_name: HermesAppName, - /// module ULID id + /// module's id module_id: ModuleId, /// event name to be executed event_name: String, /// module's execution counter - exc_counter: u64, + exc_counter: u32, } impl HermesRuntimeContext { /// Creates a new instance of the `Context`. - pub(crate) fn _new( - app_name: HermesAppName, module_id: ModuleId, event_name: String, exc_counter: u64, + pub(crate) fn new( + app_name: HermesAppName, module_id: ModuleId, event_name: String, exc_counter: u32, ) -> Self { Self { app_name, @@ -69,7 +69,7 @@ impl HermesRuntimeContext { /// Get the counter value #[allow(dead_code)] - pub(crate) fn exc_counter(&self) -> u64 { + pub(crate) fn exc_counter(&self) -> u32 { self.exc_counter } } diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 274a5f430..ff444ddbb 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -91,8 +91,17 @@ impl Module { /// Get the module id #[allow(dead_code)] - pub(crate) fn id(self) -> ModuleId { - self.id + pub(crate) fn id(&self) -> &ModuleId { + &self.id + } + + /// Get the module's execution counter + pub(crate) fn exec_counter(&self) -> u32 { + // Using the highest memory ordering constraint. + // It provides a highest consistency guarantee and in some cases could decrease + // perfomance. + // We could revise ordering approach for this case in future. + self.exc_counter.load(Ordering::SeqCst) } /// Executes a Hermes event by calling some WASM function. From faf8ad764ad98d2ca35d629e49ce317bf36b3f18 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 13:26:28 +0200 Subject: [PATCH 31/52] wip --- hermes/bin/src/lib.rs | 1 - hermes/bin/src/main.rs | 1 - hermes/bin/src/reactor.rs | 15 ++++++++------- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index a7daed652..cd977eb38 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -3,7 +3,6 @@ mod app; mod event; -#[allow(dead_code)] mod reactor; mod runtime_extensions; mod runtime_state; diff --git a/hermes/bin/src/main.rs b/hermes/bin/src/main.rs index bdb371543..62ceb3c94 100644 --- a/hermes/bin/src/main.rs +++ b/hermes/bin/src/main.rs @@ -2,7 +2,6 @@ mod app; mod event; -#[allow(dead_code)] mod reactor; mod runtime_extensions; mod runtime_state; diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 8b64d99e4..b7cd7a98d 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -3,7 +3,6 @@ use std::{sync::Arc, thread}; use crate::{ - app::HermesApp, event::queue::HermesEventQueue, runtime_extensions::state::{State, Stateful}, }; @@ -14,6 +13,7 @@ use crate::{ struct ThreadPanicsError(&'static str); /// Hermes Reactor struct +#[allow(dead_code)] pub(crate) struct HermesReactor { /// Runtime extensions state state: Arc, @@ -24,7 +24,8 @@ pub(crate) struct HermesReactor { impl HermesReactor { /// Create a new Hermes Reactor - pub(crate) fn new(_apps: &Vec) -> Self { + #[allow(dead_code)] + pub(crate) fn new() -> Self { let event_queue = HermesEventQueue::new().into(); let state = State::new().into(); @@ -36,13 +37,13 @@ impl HermesReactor { /// /// # Note: /// This is a blocking call util all tasks are finished. + #[allow(dead_code)] pub(crate) fn run(self) -> anyhow::Result<()> { // Emits init event - thread::spawn({ - let event_queue = self.event_queue.clone(); - let state = self.state.clone(); - move || state.hermes.init.emit_init_event(event_queue.as_ref()) - }); + self.state + .hermes + .init + .emit_init_event(self.event_queue.as_ref())?; let events_thread = thread::spawn({ let state = self.state.clone(); From 87d0d74273ea6eef16848420e605fc2fe43c5f34 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 13:48:00 +0200 Subject: [PATCH 32/52] fix spelling --- hermes/bin/src/wasm/module.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index ff444ddbb..a9247a08a 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -99,7 +99,7 @@ impl Module { pub(crate) fn exec_counter(&self) -> u32 { // Using the highest memory ordering constraint. // It provides a highest consistency guarantee and in some cases could decrease - // perfomance. + // performance. // We could revise ordering approach for this case in future. self.exc_counter.load(Ordering::SeqCst) } @@ -125,7 +125,7 @@ impl Module { // Using the highest memory ordering constraint. // It provides a highest consistency guarantee and in some cases could decrease - // perfomance. + // performance. // We could revise ordering approach for this case in future. self.exc_counter.fetch_add(1, Ordering::SeqCst); Ok(()) From 08372ba5800cc851f0d3bceb5f557b09ee2643e1 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 13:52:26 +0200 Subject: [PATCH 33/52] fix --- hermes/bin/src/event/queue.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 0cff5d9ca..1f4f75626 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -29,7 +29,7 @@ pub(crate) enum Error { /// Failed to add event into the event queue. Event queue is closed. #[error("Failed to add event into the event queue. Event queue is closed.")] - CanotAddEvent, + CannotAddEvent, /// Trying to execute one more event execution loop. It is allowed to run only one /// execution loop in a time. @@ -61,12 +61,15 @@ impl HermesEventQueue { } /// Add event into the event queue + /// + /// # Errors: + /// - `Error::CannotAddEvent` pub(crate) fn add_into_queue(&self, event: HermesEvent) -> anyhow::Result<()> { - self.sender.send(event).map_err(|_| Error::CanotAddEvent)?; + self.sender.send(event).map_err(|_| Error::CannotAddEvent)?; Ok(()) } - /// Execute a hermes event on the provided module and all necesary info. + /// Execute a hermes event on the provided module and all necessary info. fn execute( app_name: HermesAppName, module_id: ModuleId, state: &Arc, event: &dyn HermesEventPayload, module: &Module, @@ -143,8 +146,7 @@ impl HermesEventQueue { /// Executes Hermes events from provided the event queue. /// /// # Errors: - /// - `Error::AnotherEventExecutionLoop` - Trying to execute one more event execution - /// loop. It is allowed to run only one execution loop in a time. + /// - `Error::AnotherEventExecutionLoop` /// /// # Note: /// This is a blocking call. From c9b8e576677d1d6b0f7600f584241a184de2a573 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 16:23:52 +0200 Subject: [PATCH 34/52] update bench --- hermes/bin/src/wasm/module.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 696da35d4..e8c0a5499 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -134,7 +134,14 @@ impl Module { #[cfg(feature = "bench")] pub mod bench { + use std::sync::Arc; + use super::*; + use crate::{ + app::HermesAppName, + runtime_extensions::state::{State, Stateful}, + runtime_state::HermesRuntimeContext, + }; /// Benchmark for executing the `init` event of the Hermes dummy component. /// It aims to measure the overhead of the WASM module and WASM state initialization @@ -155,14 +162,25 @@ pub mod bench { } } - let mut module = Module::new( - "app".to_string(), - include_bytes!("../../../../wasm/c/bench_component.wasm"), - ) - .unwrap(); + let mut module = + Module::new(include_bytes!("../../../../wasm/c/bench_component.wasm")).unwrap(); + let state = State::new(); b.iter(|| { - module.execute_event(&Event).unwrap(); + module + .execute_event( + &Event, + HermesRuntimeState::new( + Arc::new(state), + HermesRuntimeContext::new( + HermesAppName("app 1".to_string()), + module.id().clone(), + "init".to_string(), + 0, + ), + ), + ) + .unwrap(); }); } From 916148b02de89bdab84a987c96f5921a11c9d258 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Tue, 27 Feb 2024 16:25:36 +0200 Subject: [PATCH 35/52] remove uneeded code --- hermes/bin/src/wasm/module.rs | 100 +++++++--------------------------- 1 file changed, 19 insertions(+), 81 deletions(-) diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index e8c0a5499..567e17daf 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -134,8 +134,6 @@ impl Module { #[cfg(feature = "bench")] pub mod bench { - use std::sync::Arc; - use super::*; use crate::{ app::HermesAppName, @@ -162,25 +160,28 @@ pub mod bench { } } - let mut module = + let module = Module::new(include_bytes!("../../../../wasm/c/bench_component.wasm")).unwrap(); - let state = State::new(); - b.iter(|| { - module - .execute_event( - &Event, - HermesRuntimeState::new( - Arc::new(state), - HermesRuntimeContext::new( - HermesAppName("app 1".to_string()), - module.id().clone(), - "init".to_string(), - 0, + let state = State::new().into(); + b.iter({ + let state = state.clone(); + || { + module + .execute_event( + &Event, + HermesRuntimeState::new( + state, + HermesRuntimeContext::new( + HermesAppName("app 1".to_string()), + module.id().clone(), + "init".to_string(), + 0, + ), ), - ), - ) - .unwrap(); + ) + .unwrap(); + } }); } @@ -251,66 +252,3 @@ pub mod bench { }); } } - -#[cfg(test)] -mod tests { - // use super::*; - - // struct TestHost; - // impl Host for TestHost { - // fn link_imports(_linker: &mut WasmLinker) -> anyhow::Result<()> { - // Ok(()) - // } - // } - - // struct TestEvent; - // impl HermesEventPayload> for TestEvent { - // fn event_name(&self) -> &str { - // "inc-global" - // } - - // fn execute(&self, instance: &mut ModuleInstance) -> - // anyhow::Result<()> { let func = instance - // .instance - // .get_typed_func::<(), (i32,)>(&mut instance.store, "inc-global")?; - // let (res,) = func.call(&mut instance.store, ())?; - // assert_eq!(res, 1); - // Ok(()) - // } - // } - - // #[test] - // /// Tests that after instantiation of `Module` its state does not change after each - // /// `Module::call_func` execution - // fn preserve_module_state_test() { - // let wat = r#" - // (component - // (core module $Module - // (export "inc-global" (func $inc_global)) - - // (func $inc_global (result i32) - // global.get $global_val - // i32.const 1 - // i32.add - // global.set $global_val - // global.get $global_val - // ) - - // (global $global_val (mut i32) (i32.const 0)) - // ) - // (core instance $module (instantiate (module $Module))) - // (func $inc_global (result s32) (canon lift (core func $module - // "inc-global"))) (export "inc-global" (func $inc_global)) - // )"#; - - // let mut module = - // Module::new("app".to_string(), wat.as_bytes()).expect("cannot load a WASM - // module"); - - // for _ in 0..10 { - // module - // .execute_event(&TestEvent) - // .expect("cannot execute `TestEvent` event"); - // } - // } -} From f7fa6d1f6da7560a51e01095d5023cd592b7b4ea Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 28 Feb 2024 13:34:35 +0200 Subject: [PATCH 36/52] wip --- hermes/bin/src/app.rs | 4 +- hermes/bin/src/event/queue.rs | 212 +++++++++++++++++++--------------- hermes/bin/src/reactor.rs | 4 +- hermes/bin/src/wasm/module.rs | 6 +- 4 files changed, 128 insertions(+), 98 deletions(-) diff --git a/hermes/bin/src/app.rs b/hermes/bin/src/app.rs index b38b1c724..e61984442 100644 --- a/hermes/bin/src/app.rs +++ b/hermes/bin/src/app.rs @@ -29,7 +29,7 @@ impl HermesApp { /// Get app name #[allow(dead_code)] - pub(crate) fn app_name(self) -> HermesAppName { - self.app_name + pub(crate) fn app_name(&self) -> &HermesAppName { + &self.app_name } } diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 1f4f75626..e0f2cc45b 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -20,12 +20,12 @@ use crate::{ #[derive(thiserror::Error, Debug, Clone)] pub(crate) enum Error { /// Target app not found. - #[error("Target app not found.")] - AppNotFound, + #[error("Target app not found, app name: {0:?}.")] + AppNotFound(HermesAppName), /// Target module not found. - #[error("Target module not found.")] - ModuleNotFound, + #[error("Target module not found, module id: {0:?}.")] + ModuleNotFound(ModuleId), /// Failed to add event into the event queue. Event queue is closed. #[error("Failed to add event into the event queue. Event queue is closed.")] @@ -43,7 +43,6 @@ pub(crate) struct HermesEventQueue { sender: Sender, /// Hermes event queue receiver receiver: Mutex>, - /// Current available hermes apps with their modules apps: HashMap>, } @@ -55,7 +54,6 @@ impl HermesEventQueue { Self { sender, receiver: Mutex::new(receiver), - apps: HashMap::new(), } } @@ -68,97 +66,129 @@ impl HermesEventQueue { self.sender.send(event).map_err(|_| Error::CannotAddEvent)?; Ok(()) } +} - /// Execute a hermes event on the provided module and all necessary info. - fn execute( - app_name: HermesAppName, module_id: ModuleId, state: &Arc, - event: &dyn HermesEventPayload, module: &Module, - ) -> anyhow::Result<()> { - let runtime_context = HermesRuntimeContext::new( - app_name, - module_id, - event.event_name().to_string(), - module.exec_counter(), - ); - - let runtime_state = HermesRuntimeState::new(state.clone(), runtime_context); - module.execute_event(event, runtime_state)?; - Ok(()) - } +/// Execute a hermes event on the provided module and all necessary info. +/// +/// # Errors: +/// - `wasm::module::BadWASMModuleError` +fn execute_event( + app_name: HermesAppName, module_id: ModuleId, state: &Arc, + event: &dyn HermesEventPayload, module: &Module, +) -> anyhow::Result<()> { + let runtime_context = HermesRuntimeContext::new( + app_name, + module_id, + event.event_name().to_string(), + module.exec_counter(), + ); + + let runtime_state = HermesRuntimeState::new(state.clone(), runtime_context); + module.execute_event(event, runtime_state)?; + Ok(()) +} - /// Executes provided Hermes event filtering by target app and target module. - /// - /// # Errors: - /// - `Error::ModuleNotFound` - /// - `Error::AppNotFound` - fn filtered_execution(&self, event: &HermesEvent, state: &Arc) -> anyhow::Result<()> { - let filtered_modules_exec = |target_module: &TargetModule, - app_name: &HermesAppName, - modules: &HashMap| - -> anyhow::Result<()> { - match target_module { - TargetModule::All => { - for (module_id, module) in modules { - Self::execute( - app_name.clone(), - module_id.clone(), - state, - event.payload(), - module, - )?; - } - }, - TargetModule::_List(target_modules) => { - for module_id in target_modules { - let module = modules.get(module_id).ok_or(Error::ModuleNotFound)?; - - Self::execute( - app_name.clone(), - module_id.clone(), - state, - event.payload(), - module, - )?; - } - }, +/// Executes provided Hermes event filtering by target app and target module. +/// +/// # Errors: +/// - `Error::ModuleNotFound` +/// - `Error::AppNotFound` +#[allow(clippy::unnecessary_wraps)] +fn targeted_event_execution( + indexed_apps: &HashMap>, event: &HermesEvent, + state: &Arc, +) -> anyhow::Result<()> { + match (event.target_app(), event.target_module()) { + (TargetApp::All, TargetModule::All) => { + for (app_name, indexed_modules) in indexed_apps { + for (module_id, module) in indexed_modules { + execute_event( + app_name.clone(), + module_id.clone(), + state, + event.payload(), + module, + )?; + } } - Ok(()) - }; - - match event.target_app() { - TargetApp::All => { - for (app_name, modules) in &self.apps { - filtered_modules_exec(event.target_module(), app_name, modules)?; + }, + (TargetApp::All, TargetModule::_List(target_modules)) => { + for (app_name, indexed_modules) in indexed_apps { + for module_id in target_modules { + let module = indexed_modules + .get(module_id) + .ok_or(Error::ModuleNotFound(module_id.to_owned()))?; + + execute_event( + app_name.clone(), + module_id.clone(), + state, + event.payload(), + module, + )?; } - }, - TargetApp::_List(apps) => { - for app_name in apps { - let modules = self.apps.get(app_name).ok_or(Error::AppNotFound)?; - - filtered_modules_exec(event.target_module(), app_name, modules)?; + } + }, + (TargetApp::_List(target_apps), TargetModule::All) => { + for app_name in target_apps { + let indexed_modules = indexed_apps + .get(app_name) + .ok_or(Error::AppNotFound(app_name.to_owned()))?; + for (module_id, module) in indexed_modules { + execute_event( + app_name.clone(), + module_id.clone(), + state, + event.payload(), + module, + )?; } - }, - } - - Ok(()) + } + }, + (TargetApp::_List(target_apps), TargetModule::_List(target_modules)) => { + for app_name in target_apps { + let indexed_modules = indexed_apps + .get(app_name) + .ok_or(Error::AppNotFound(app_name.to_owned()))?; + for module_id in target_modules { + let module = indexed_modules + .get(module_id) + .ok_or(Error::ModuleNotFound(module_id.to_owned()))?; + + execute_event( + app_name.clone(), + module_id.clone(), + state, + event.payload(), + module, + )?; + } + } + }, } - /// Executes Hermes events from provided the event queue. - /// - /// # Errors: - /// - `Error::AnotherEventExecutionLoop` - /// - /// # Note: - /// This is a blocking call. - pub(crate) fn event_execution_loop(&self, state: &Arc) -> anyhow::Result<()> { - let events = self - .receiver - .try_lock() - .map_err(|_| Error::AnotherEventExecutionLoop)?; - - for event in events.iter() { - self.filtered_execution(&event, state)?; - } - Ok(()) + Ok(()) +} + +/// Executes Hermes events from provided the event queue. +/// +/// # Errors: +/// - `Error::AnotherEventExecutionLoop` +/// - `Error::ModuleNotFound` +/// - `Error::AppNotFound` +/// +/// # Note: +/// This is a blocking call. +pub(crate) fn event_execution_loop( + event_queue: &HermesEventQueue, state: &Arc, +) -> anyhow::Result<()> { + let events = event_queue + .receiver + .try_lock() + .map_err(|_| Error::AnotherEventExecutionLoop)?; + + for event in events.iter() { + targeted_event_execution(&event_queue.apps, &event, state)?; } + Ok(()) } diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index b7cd7a98d..3e7f2f393 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -3,7 +3,7 @@ use std::{sync::Arc, thread}; use crate::{ - event::queue::HermesEventQueue, + event::queue::{event_execution_loop, HermesEventQueue}, runtime_extensions::state::{State, Stateful}, }; @@ -47,7 +47,7 @@ impl HermesReactor { let events_thread = thread::spawn({ let state = self.state.clone(); - move || self.event_queue.event_execution_loop(&state) + move || event_execution_loop(&self.event_queue, &state) }); events_thread diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 567e17daf..87aa47964 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -67,7 +67,7 @@ impl Module { /// Instantiate WASM module /// /// # Errors - /// - `BadModuleError` + /// - `BadWASMModuleError` /// - `BadEngineConfigError` pub(crate) fn new(module_bytes: &[u8]) -> anyhow::Result { let engine = Engine::new()?; @@ -111,8 +111,8 @@ impl Module { /// For each call creates a brand new `wasmtime::Store` instance, which means that /// is has an initial state, based on the provided context for each call. /// - /// # Errors - /// - `BadModuleError` + /// # Errors: + /// - `BadWASMModuleError` #[allow(dead_code)] pub(crate) fn execute_event( &self, event: &dyn HermesEventPayload, state: HermesRuntimeState, From 25a4fa89e3a782f627657fd5772b5dbd43c40833 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 28 Feb 2024 14:17:56 +0200 Subject: [PATCH 37/52] wip --- hermes/bin/src/app.rs | 26 +++++++++++---- hermes/bin/src/event/queue.rs | 58 ++++++++++++++++----------------- hermes/bin/src/reactor.rs | 18 ++++++++-- hermes/bin/src/runtime_state.rs | 20 +++++++++--- hermes/bin/src/wasm/engine.rs | 1 - hermes/bin/src/wasm/module.rs | 2 -- 6 files changed, 78 insertions(+), 47 deletions(-) diff --git a/hermes/bin/src/app.rs b/hermes/bin/src/app.rs index e61984442..2b2e22f3c 100644 --- a/hermes/bin/src/app.rs +++ b/hermes/bin/src/app.rs @@ -1,35 +1,47 @@ //! Hermes app implementation. -use crate::wasm::module::Module; +use std::collections::HashMap; + +use crate::wasm::module::{Module, ModuleId}; /// Hermes App Name type #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(crate) struct HermesAppName(pub(crate) String); +/// Convenient type alias for indexed apps map (`HermesAppName` -> `HermesApp`) +pub(crate) type IndexedApps = HashMap; + /// Hermes app -#[allow(dead_code)] pub(crate) struct HermesApp { /// App name app_name: HermesAppName, /// WASM modules - modules: Vec, + indexed_modules: HashMap, } impl HermesApp { /// Create a new Hermes app #[allow(dead_code)] pub(crate) fn new(app_name: HermesAppName, module_bytes: Vec>) -> anyhow::Result { - let mut modules = Vec::with_capacity(module_bytes.len()); + let mut modules = HashMap::with_capacity(module_bytes.len()); for module_bytes in module_bytes { - modules.push(Module::new(&module_bytes)?); + let module = Module::new(&module_bytes)?; + modules.insert(module.id().clone(), module); } - Ok(Self { app_name, modules }) + Ok(Self { + app_name, + indexed_modules: modules, + }) } /// Get app name - #[allow(dead_code)] pub(crate) fn app_name(&self) -> &HermesAppName { &self.app_name } + + /// Get indexed modules + pub(crate) fn indexed_modules(&self) -> &HashMap { + &self.indexed_modules + } } diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index e0f2cc45b..23f242ead 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -1,16 +1,13 @@ //! Hermes event queue implementation. -use std::{ - collections::HashMap, - sync::{ - mpsc::{Receiver, Sender}, - Arc, Mutex, - }, +use std::sync::{ + mpsc::{Receiver, Sender}, + Arc, Mutex, }; use super::{HermesEvent, HermesEventPayload, TargetApp, TargetModule}; use crate::{ - app::HermesAppName, + app::{HermesAppName, IndexedApps}, runtime_extensions::state::State, runtime_state::{HermesRuntimeContext, HermesRuntimeState}, wasm::module::{Module, ModuleId}, @@ -43,8 +40,6 @@ pub(crate) struct HermesEventQueue { sender: Sender, /// Hermes event queue receiver receiver: Mutex>, - /// Current available hermes apps with their modules - apps: HashMap>, } impl HermesEventQueue { @@ -54,7 +49,6 @@ impl HermesEventQueue { Self { sender, receiver: Mutex::new(receiver), - apps: HashMap::new(), } } @@ -73,8 +67,8 @@ impl HermesEventQueue { /// # Errors: /// - `wasm::module::BadWASMModuleError` fn execute_event( - app_name: HermesAppName, module_id: ModuleId, state: &Arc, - event: &dyn HermesEventPayload, module: &Module, + app_name: HermesAppName, module_id: ModuleId, state: Arc, + event_queue: Arc, event: &dyn HermesEventPayload, module: &Module, ) -> anyhow::Result<()> { let runtime_context = HermesRuntimeContext::new( app_name, @@ -83,7 +77,7 @@ fn execute_event( module.exec_counter(), ); - let runtime_state = HermesRuntimeState::new(state.clone(), runtime_context); + let runtime_state = HermesRuntimeState::new(state, runtime_context, event_queue); module.execute_event(event, runtime_state)?; Ok(()) } @@ -95,17 +89,18 @@ fn execute_event( /// - `Error::AppNotFound` #[allow(clippy::unnecessary_wraps)] fn targeted_event_execution( - indexed_apps: &HashMap>, event: &HermesEvent, - state: &Arc, + indexed_apps: &IndexedApps, event: &HermesEvent, state: &Arc, + event_queue: &Arc, ) -> anyhow::Result<()> { match (event.target_app(), event.target_module()) { (TargetApp::All, TargetModule::All) => { - for (app_name, indexed_modules) in indexed_apps { - for (module_id, module) in indexed_modules { + for (app_name, app) in indexed_apps { + for (module_id, module) in app.indexed_modules() { execute_event( app_name.clone(), module_id.clone(), - state, + state.clone(), + event_queue.clone(), event.payload(), module, )?; @@ -113,16 +108,18 @@ fn targeted_event_execution( } }, (TargetApp::All, TargetModule::_List(target_modules)) => { - for (app_name, indexed_modules) in indexed_apps { + for (app_name, app) in indexed_apps { for module_id in target_modules { - let module = indexed_modules + let module = app + .indexed_modules() .get(module_id) .ok_or(Error::ModuleNotFound(module_id.to_owned()))?; execute_event( app_name.clone(), module_id.clone(), - state, + state.clone(), + event_queue.clone(), event.payload(), module, )?; @@ -131,14 +128,15 @@ fn targeted_event_execution( }, (TargetApp::_List(target_apps), TargetModule::All) => { for app_name in target_apps { - let indexed_modules = indexed_apps + let app = indexed_apps .get(app_name) .ok_or(Error::AppNotFound(app_name.to_owned()))?; - for (module_id, module) in indexed_modules { + for (module_id, module) in app.indexed_modules() { execute_event( app_name.clone(), module_id.clone(), - state, + state.clone(), + event_queue.clone(), event.payload(), module, )?; @@ -147,18 +145,20 @@ fn targeted_event_execution( }, (TargetApp::_List(target_apps), TargetModule::_List(target_modules)) => { for app_name in target_apps { - let indexed_modules = indexed_apps + let app = indexed_apps .get(app_name) .ok_or(Error::AppNotFound(app_name.to_owned()))?; for module_id in target_modules { - let module = indexed_modules + let module = app + .indexed_modules() .get(module_id) .ok_or(Error::ModuleNotFound(module_id.to_owned()))?; execute_event( app_name.clone(), module_id.clone(), - state, + state.clone(), + event_queue.clone(), event.payload(), module, )?; @@ -180,7 +180,7 @@ fn targeted_event_execution( /// # Note: /// This is a blocking call. pub(crate) fn event_execution_loop( - event_queue: &HermesEventQueue, state: &Arc, + indexed_apps: &IndexedApps, event_queue: &Arc, state: &Arc, ) -> anyhow::Result<()> { let events = event_queue .receiver @@ -188,7 +188,7 @@ pub(crate) fn event_execution_loop( .map_err(|_| Error::AnotherEventExecutionLoop)?; for event in events.iter() { - targeted_event_execution(&event_queue.apps, &event, state)?; + targeted_event_execution(indexed_apps, &event, state, event_queue)?; } Ok(()) } diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 3e7f2f393..5e90da7c8 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -3,6 +3,7 @@ use std::{sync::Arc, thread}; use crate::{ + app::{HermesApp, IndexedApps}, event::queue::{event_execution_loop, HermesEventQueue}, runtime_extensions::state::{State, Stateful}, }; @@ -20,17 +21,28 @@ pub(crate) struct HermesReactor { /// Hermes event queue event_queue: Arc, + + /// Hermes apps + indexed_apps: IndexedApps, } impl HermesReactor { /// Create a new Hermes Reactor #[allow(dead_code)] - pub(crate) fn new() -> Self { + pub(crate) fn new(apps: Vec) -> Self { let event_queue = HermesEventQueue::new().into(); let state = State::new().into(); + let indexed_apps = apps + .into_iter() + .map(|app| (app.app_name().clone(), app)) + .collect(); - Self { state, event_queue } + Self { + state, + event_queue, + indexed_apps, + } } /// Run Hermes. @@ -47,7 +59,7 @@ impl HermesReactor { let events_thread = thread::spawn({ let state = self.state.clone(); - move || event_execution_loop(&self.event_queue, &state) + move || event_execution_loop(&self.indexed_apps, &self.event_queue, &state) }); events_thread diff --git a/hermes/bin/src/runtime_state.rs b/hermes/bin/src/runtime_state.rs index 40553b5ca..8ee7d9359 100644 --- a/hermes/bin/src/runtime_state.rs +++ b/hermes/bin/src/runtime_state.rs @@ -2,21 +2,31 @@ use std::sync::Arc; -use crate::{app::HermesAppName, runtime_extensions::state::State, wasm::module::ModuleId}; +use crate::{ + app::HermesAppName, event::queue::HermesEventQueue, runtime_extensions::state::State, + wasm::module::ModuleId, +}; -#[allow(dead_code)] /// Hermes Runtime state. This state is passed to the WASM runtime. pub(crate) struct HermesRuntimeState { /// Runtime extensions state pub(crate) state: Arc, /// Runtime context. - pub(crate) ctx: HermesRuntimeContext, + pub(crate) _ctx: HermesRuntimeContext, + /// Hermes event queue. + pub(crate) _event_queue: Arc, } impl HermesRuntimeState { /// Creates a new instance of the `HermesState`. - pub(crate) fn new(state: Arc, ctx: HermesRuntimeContext) -> HermesRuntimeState { - Self { state, ctx } + pub(crate) fn new( + state: Arc, ctx: HermesRuntimeContext, event_queue: Arc, + ) -> HermesRuntimeState { + Self { + state, + _ctx: ctx, + _event_queue: event_queue, + } } } diff --git a/hermes/bin/src/wasm/engine.rs b/hermes/bin/src/wasm/engine.rs index 42329b9cd..1dd15fc90 100644 --- a/hermes/bin/src/wasm/engine.rs +++ b/hermes/bin/src/wasm/engine.rs @@ -33,7 +33,6 @@ impl Engine { /// /// # Errors /// - `BadEngineConfigError` - #[allow(dead_code)] pub(crate) fn new() -> anyhow::Result { let mut config = WasmConfig::new(); config.wasm_component_model(true); diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 87aa47964..3ff196c95 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -90,7 +90,6 @@ impl Module { } /// Get the module id - #[allow(dead_code)] pub(crate) fn id(&self) -> &ModuleId { &self.id } @@ -113,7 +112,6 @@ impl Module { /// /// # Errors: /// - `BadWASMModuleError` - #[allow(dead_code)] pub(crate) fn execute_event( &self, event: &dyn HermesEventPayload, state: HermesRuntimeState, ) -> anyhow::Result<()> { From 6f55a093d05768c735ec43f16963c583f8be53e0 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 28 Feb 2024 15:04:12 +0200 Subject: [PATCH 38/52] fix bench --- hermes/bin/src/wasm/module.rs | 38 ++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 3ff196c95..c5db307a6 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -132,9 +132,12 @@ impl Module { #[cfg(feature = "bench")] pub mod bench { + use std::sync::Arc; + use super::*; use crate::{ app::HermesAppName, + event::queue::HermesEventQueue, runtime_extensions::state::{State, Stateful}, runtime_state::HermesRuntimeContext, }; @@ -161,25 +164,24 @@ pub mod bench { let module = Module::new(include_bytes!("../../../../wasm/c/bench_component.wasm")).unwrap(); - let state = State::new().into(); - b.iter({ - let state = state.clone(); - || { - module - .execute_event( - &Event, - HermesRuntimeState::new( - state, - HermesRuntimeContext::new( - HermesAppName("app 1".to_string()), - module.id().clone(), - "init".to_string(), - 0, - ), + let state: Arc<_> = State::new().into(); + let event_queue: Arc<_> = HermesEventQueue::new().into(); + b.iter(|| { + module + .execute_event( + &Event, + HermesRuntimeState::new( + state.clone(), + HermesRuntimeContext::new( + HermesAppName("app 1".to_string()), + module.id().clone(), + "init".to_string(), + 0, ), - ) - .unwrap(); - } + event_queue.clone(), + ), + ) + .unwrap(); }); } From 9408f9db82bd5569a1a67487e17dd20db88093bc Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Wed, 28 Feb 2024 15:45:22 +0200 Subject: [PATCH 39/52] fix cargo warning --- hermes/crates/cardano-chain-follower/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hermes/crates/cardano-chain-follower/Cargo.toml b/hermes/crates/cardano-chain-follower/Cargo.toml index 737d78521..0c0ee4a19 100644 --- a/hermes/crates/cardano-chain-follower/Cargo.toml +++ b/hermes/crates/cardano-chain-follower/Cargo.toml @@ -14,7 +14,7 @@ workspace = true pallas.workspace = true pallas-hardano.workspace = true thiserror.workspace = true -tokio = { workspace = true, default-features = false, features = ["macros", "rt", "net", "rt-multi-thread"] } +tokio = { workspace = true, features = ["macros", "rt", "net", "rt-multi-thread"] } tracing.workspace = true [dev-dependencies] From c6e277b4bce50959fefd60940cd1264372681af3 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Thu, 29 Feb 2024 12:21:04 +0200 Subject: [PATCH 40/52] refactor, update runtime state --- hermes/bin/src/event/queue.rs | 56 ++++--------------- hermes/bin/src/lib.rs | 2 +- hermes/bin/src/main.rs | 2 +- hermes/bin/src/reactor.rs | 6 +- .../{runtime_state.rs => runtime_context.rs} | 34 +---------- .../runtime_extensions/hermes/binary/host.rs | 4 +- .../runtime_extensions/hermes/cardano/host.rs | 4 +- .../runtime_extensions/hermes/cbor/host.rs | 4 +- .../runtime_extensions/hermes/cron/host.rs | 44 ++++++++------- .../src/runtime_extensions/hermes/cron/mod.rs | 8 +-- .../runtime_extensions/hermes/crypto/host.rs | 6 +- .../runtime_extensions/hermes/hash/host.rs | 4 +- .../runtime_extensions/hermes/json/host.rs | 4 +- .../hermes/kv_store/host.rs | 4 +- .../hermes/localtime/host.rs | 4 +- .../runtime_extensions/hermes/logging/host.rs | 4 +- .../bin/src/runtime_extensions/hermes/mod.rs | 4 +- .../src/runtime_extensions/wasi/cli/host.rs | 10 ++-- .../wasi/clocks/monotonic/host.rs | 4 +- .../wasi/clocks/wall/host.rs | 4 +- .../wasi/filesystem/host.rs | 10 ++-- .../src/runtime_extensions/wasi/http/host.rs | 28 +++++----- .../runtime_extensions/wasi/io/error/host.rs | 6 +- .../wasi/io/streams/host.rs | 8 +-- .../wasi/random/insecure/host.rs | 4 +- .../wasi/random/insecure_seed/host.rs | 4 +- .../wasi/random/secure/host.rs | 4 +- hermes/bin/src/wasm/module.rs | 14 ++--- 28 files changed, 115 insertions(+), 175 deletions(-) rename hermes/bin/src/{runtime_state.rs => runtime_context.rs} (57%) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 23f242ead..0899188de 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -2,14 +2,13 @@ use std::sync::{ mpsc::{Receiver, Sender}, - Arc, Mutex, + Mutex, }; use super::{HermesEvent, HermesEventPayload, TargetApp, TargetModule}; use crate::{ app::{HermesAppName, IndexedApps}, - runtime_extensions::state::State, - runtime_state::{HermesRuntimeContext, HermesRuntimeState}, + runtime_context::HermesRuntimeContext, wasm::module::{Module, ModuleId}, }; @@ -67,8 +66,7 @@ impl HermesEventQueue { /// # Errors: /// - `wasm::module::BadWASMModuleError` fn execute_event( - app_name: HermesAppName, module_id: ModuleId, state: Arc, - event_queue: Arc, event: &dyn HermesEventPayload, module: &Module, + app_name: HermesAppName, module_id: ModuleId, event: &dyn HermesEventPayload, module: &Module, ) -> anyhow::Result<()> { let runtime_context = HermesRuntimeContext::new( app_name, @@ -77,8 +75,7 @@ fn execute_event( module.exec_counter(), ); - let runtime_state = HermesRuntimeState::new(state, runtime_context, event_queue); - module.execute_event(event, runtime_state)?; + module.execute_event(event, runtime_context)?; Ok(()) } @@ -88,22 +85,12 @@ fn execute_event( /// - `Error::ModuleNotFound` /// - `Error::AppNotFound` #[allow(clippy::unnecessary_wraps)] -fn targeted_event_execution( - indexed_apps: &IndexedApps, event: &HermesEvent, state: &Arc, - event_queue: &Arc, -) -> anyhow::Result<()> { +fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> anyhow::Result<()> { match (event.target_app(), event.target_module()) { (TargetApp::All, TargetModule::All) => { for (app_name, app) in indexed_apps { for (module_id, module) in app.indexed_modules() { - execute_event( - app_name.clone(), - module_id.clone(), - state.clone(), - event_queue.clone(), - event.payload(), - module, - )?; + execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; } } }, @@ -115,14 +102,7 @@ fn targeted_event_execution( .get(module_id) .ok_or(Error::ModuleNotFound(module_id.to_owned()))?; - execute_event( - app_name.clone(), - module_id.clone(), - state.clone(), - event_queue.clone(), - event.payload(), - module, - )?; + execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; } } }, @@ -132,14 +112,7 @@ fn targeted_event_execution( .get(app_name) .ok_or(Error::AppNotFound(app_name.to_owned()))?; for (module_id, module) in app.indexed_modules() { - execute_event( - app_name.clone(), - module_id.clone(), - state.clone(), - event_queue.clone(), - event.payload(), - module, - )?; + execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; } } }, @@ -154,14 +127,7 @@ fn targeted_event_execution( .get(module_id) .ok_or(Error::ModuleNotFound(module_id.to_owned()))?; - execute_event( - app_name.clone(), - module_id.clone(), - state.clone(), - event_queue.clone(), - event.payload(), - module, - )?; + execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; } } }, @@ -180,7 +146,7 @@ fn targeted_event_execution( /// # Note: /// This is a blocking call. pub(crate) fn event_execution_loop( - indexed_apps: &IndexedApps, event_queue: &Arc, state: &Arc, + indexed_apps: &IndexedApps, event_queue: &HermesEventQueue, ) -> anyhow::Result<()> { let events = event_queue .receiver @@ -188,7 +154,7 @@ pub(crate) fn event_execution_loop( .map_err(|_| Error::AnotherEventExecutionLoop)?; for event in events.iter() { - targeted_event_execution(indexed_apps, &event, state, event_queue)?; + targeted_event_execution(indexed_apps, &event)?; } Ok(()) } diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index 846bf95ed..2206e4037 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -5,7 +5,7 @@ mod app; mod event; mod reactor; mod runtime_extensions; -mod runtime_state; +mod runtime_context; mod wasm; #[cfg(feature = "bench")] diff --git a/hermes/bin/src/main.rs b/hermes/bin/src/main.rs index 054c09b2c..175c2948a 100644 --- a/hermes/bin/src/main.rs +++ b/hermes/bin/src/main.rs @@ -3,8 +3,8 @@ mod app; mod event; mod reactor; +mod runtime_context; mod runtime_extensions; -mod runtime_state; mod wasm; #[cfg(feature = "bench")] diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 5e90da7c8..e5934501a 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -57,10 +57,8 @@ impl HermesReactor { .init .emit_init_event(self.event_queue.as_ref())?; - let events_thread = thread::spawn({ - let state = self.state.clone(); - move || event_execution_loop(&self.indexed_apps, &self.event_queue, &state) - }); + let events_thread = + thread::spawn(move || event_execution_loop(&self.indexed_apps, &self.event_queue)); events_thread .join() diff --git a/hermes/bin/src/runtime_state.rs b/hermes/bin/src/runtime_context.rs similarity index 57% rename from hermes/bin/src/runtime_state.rs rename to hermes/bin/src/runtime_context.rs index 8ee7d9359..579e8eba6 100644 --- a/hermes/bin/src/runtime_state.rs +++ b/hermes/bin/src/runtime_context.rs @@ -1,36 +1,8 @@ -//! Hermes state implementation. +//! Hermes runtime context implementation. -use std::sync::Arc; +use crate::{app::HermesAppName, wasm::module::ModuleId}; -use crate::{ - app::HermesAppName, event::queue::HermesEventQueue, runtime_extensions::state::State, - wasm::module::ModuleId, -}; - -/// Hermes Runtime state. This state is passed to the WASM runtime. -pub(crate) struct HermesRuntimeState { - /// Runtime extensions state - pub(crate) state: Arc, - /// Runtime context. - pub(crate) _ctx: HermesRuntimeContext, - /// Hermes event queue. - pub(crate) _event_queue: Arc, -} - -impl HermesRuntimeState { - /// Creates a new instance of the `HermesState`. - pub(crate) fn new( - state: Arc, ctx: HermesRuntimeContext, event_queue: Arc, - ) -> HermesRuntimeState { - Self { - state, - _ctx: ctx, - _event_queue: event_queue, - } - } -} - -/// Hermes Runtime Context. +/// Hermes Runtime Context. This is passed to the WASM runtime. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub(crate) struct HermesRuntimeContext { /// Hermes application name diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs index f78185168..7274c1cb8 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs @@ -1,7 +1,7 @@ //! Binary host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::hermes::binary::api::Host, runtime_state::HermesRuntimeState, + runtime_extensions::bindings::hermes::binary::api::Host, runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState {} +impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs index 0ed5f4d59..9f7d24aaf 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs @@ -5,10 +5,10 @@ use crate::{ CardanoBlock, CardanoBlockchainId, CardanoTxn, FetchError, Host, Slot, TxnError, UnsubscribeOptions, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Subscribe to the Blockchain block data. /// /// **Parameters** diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs index 959132f88..7471bf074 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs @@ -1,7 +1,7 @@ //! CBOR host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::hermes::cbor::api::Host, runtime_state::HermesRuntimeState, + runtime_extensions::bindings::hermes::cbor::api::Host, runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState {} +impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs index 9c8c44aca..f107dfded 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs @@ -8,10 +8,10 @@ use crate::{ }, hermes::cron::{mkcron_impl, mkdelay_crontab}, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// # Schedule Recurrent CRON event /// /// Cron events will be delivered to the `on-cron` event handler. @@ -37,7 +37,7 @@ impl Host for HermesRuntimeState { /// this function. This could be useful where a retriggering crontab event is desired /// to be stopped, but ONLY after it has triggered once more. fn add(&mut self, _entry: CronTagged, _retrigger: bool) -> wasmtime::Result { - // This will be fixed as a part of this PR https://github.com/input-output-hk/hermes/pull/145 + // TODO(@saibatizoku): https://github.com/input-output-hk/hermes/pull/145 // self.state // .hermes // .cron @@ -92,22 +92,25 @@ impl Host for HermesRuntimeState { /// may times before a later one. /// - `0` - `cron-tagged` - The Tagged crontab event. /// - `1` - `bool` - The state of the retrigger flag. - fn ls(&mut self, tag: Option) -> wasmtime::Result> { - if let Some(tag) = tag { - match self.state.hermes.cron.crontabs.get(&tag) { - Some(cron) => Ok(vec![(cron.entry.clone(), cron.retrigger)]), - None => Ok(vec![]), - } - } else { - Ok(self - .state - .hermes - .cron - .crontabs - .values() - .map(|cron| (cron.entry.clone(), cron.retrigger)) - .collect()) - } + fn ls(&mut self, _tag: Option) -> wasmtime::Result> { + // TODO(@saibatizoku): https://github.com/input-output-hk/hermes/pull/145 + + // if let Some(tag) = tag { + // match self.state.hermes.cron.crontabs.get(&tag) { + // Some(cron) => Ok(vec![(cron.entry.clone(), cron.retrigger)]), + // None => Ok(vec![]), + // } + // } else { + // Ok(self + // .state + // .hermes + // .cron + // .crontabs + // .values() + // .map(|cron| (cron.entry.clone(), cron.retrigger)) + // .collect()) + // } + Ok(vec![]) } /// # Remove the requested crontab. @@ -124,7 +127,8 @@ impl Host for HermesRuntimeState { /// - `true`: The requested crontab was deleted and will not trigger. /// - `false`: The requested crontab does not exist. fn rm(&mut self, _entry: CronTagged) -> wasmtime::Result { - // This will be fixed as a part of this PR https://github.com/input-output-hk/hermes/pull/145 + // TODO(@saibatizoku): https://github.com/input-output-hk/hermes/pull/145 + // match self.state.hermes.cron.crontabs.remove(&entry.tag) { // Some(_) => Ok(true), // None => Ok(false), diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs index 2da23a1fc..92c2b2aff 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs @@ -21,13 +21,13 @@ mod host; /// State pub(crate) struct State { /// The crontabs hash map. - crontabs: HashMap, + _crontabs: HashMap, } impl Stateful for State { fn new() -> Self { State { - crontabs: HashMap::new(), + _crontabs: HashMap::new(), } } } @@ -35,9 +35,9 @@ impl Stateful for State { /// A crontab entry. struct CronTab { /// The crontab entry. - entry: CronTagged, + _entry: CronTagged, /// When the event triggers. - retrigger: bool, + _retrigger: bool, } /// Create a delayed crontab entry. diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs index 803c92559..4af8bc157 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs @@ -8,10 +8,10 @@ use crate::{ Host, HostEd25519Bip32, }, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl HostEd25519Bip32 for HermesRuntimeState { +impl HostEd25519Bip32 for HermesRuntimeContext { /// Create a new ED25519-BIP32 Crypto resource /// /// **Parameters** @@ -81,4 +81,4 @@ impl HostEd25519Bip32 for HermesRuntimeState { } } -impl Host for HermesRuntimeState {} +impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs index e3f1c2318..2b003631b 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs @@ -6,10 +6,10 @@ use crate::{ binary::api::Bstr, hash::api::{Errno, Host}, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Hash a binary buffer with BLAKE2s fn blake2s( &mut self, _buf: Bstr, _outlen: Option, diff --git a/hermes/bin/src/runtime_extensions/hermes/json/host.rs b/hermes/bin/src/runtime_extensions/hermes/json/host.rs index f063a3faa..7b0405e7a 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/host.rs @@ -1,7 +1,7 @@ //! JSON host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::hermes::json::api::Host, runtime_state::HermesRuntimeState, + runtime_extensions::bindings::hermes::json::api::Host, runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState {} +impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs index fb9580276..6c1ee199e 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::hermes::kv_store::api::{Host, KvValues}, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Set a value in the local key-value store /// Setting None will cause the Key to be deleted from the KV store. fn kv_set(&mut self, _key: String, _value: Option) -> wasmtime::Result<()> { diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs index 90960b94a..3fbb66439 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs @@ -5,10 +5,10 @@ use crate::{ hermes::localtime::api::{Errno, Host, Localtime, Timezone}, wasi::clocks::wall_clock::Datetime, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Get localtime from a datetime or now. /// /// **Parameters** diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs index 7d6d7eb1c..44e07de2c 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs @@ -5,10 +5,10 @@ use crate::{ json::api::Json, logging::api::{Host, Level}, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Generate a Log /// /// The Hermes API will add extra information to the log, such as the instance of the diff --git a/hermes/bin/src/runtime_extensions/hermes/mod.rs b/hermes/bin/src/runtime_extensions/hermes/mod.rs index 94651b5b9..f3aa676ee 100644 --- a/hermes/bin/src/runtime_extensions/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/mod.rs @@ -23,7 +23,7 @@ pub(crate) struct State { /// CBOR extensions state pub(crate) _cbor: cbor::State, /// Cron extensions state - pub(crate) cron: cron::State, + pub(crate) _cron: cron::State, /// Crypto extensions state pub(crate) _crypto: crypto::State, /// Hash extensions state @@ -46,7 +46,7 @@ impl Stateful for State { _binary: binary::State::new(), _cardano: cardano::State::new(), _cbor: cbor::State::new(), - cron: cron::State::new(), + _cron: cron::State::new(), _crypto: crypto::State::new(), _hash: hash::State::new(), init: init::State::new(), diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs index b3a2799d3..5da0e28fd 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs @@ -5,10 +5,10 @@ use crate::{ cli, io::streams::{InputStream, OutputStream}, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl cli::environment::Host for HermesRuntimeState { +impl cli::environment::Host for HermesRuntimeContext { /// Get the POSIX-style environment variables. /// /// Each environment variable is provided as a pair of string variable names @@ -33,19 +33,19 @@ impl cli::environment::Host for HermesRuntimeState { } } -impl cli::stdin::Host for HermesRuntimeState { +impl cli::stdin::Host for HermesRuntimeContext { fn get_stdin(&mut self) -> wasmtime::Result> { todo!() } } -impl cli::stdout::Host for HermesRuntimeState { +impl cli::stdout::Host for HermesRuntimeContext { fn get_stdout(&mut self) -> wasmtime::Result> { todo!() } } -impl cli::stderr::Host for HermesRuntimeState { +impl cli::stderr::Host for HermesRuntimeContext { fn get_stderr(&mut self) -> wasmtime::Result> { todo!() } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs index 4d4207cf2..09d20fb6f 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Read the current value of the clock. /// /// The clock is monotonic, therefore calling this function repeatedly will diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs index db71a414e..1dd2ad35a 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::wasi::clocks::wall_clock::{Datetime, Host}, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Read the current value of the clock. /// /// This clock is not monotonic, therefore calling this function repeatedly diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs index 02cc79675..6c013f73d 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs @@ -12,10 +12,10 @@ use crate::{ }, io::streams::{InputStream, OutputStream}, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl filesystem::types::HostDescriptor for HermesRuntimeState { +impl filesystem::types::HostDescriptor for HermesRuntimeContext { /// Return a stream for reading from a file, if available. /// /// May fail with an error-code describing why the file cannot be read. @@ -386,7 +386,7 @@ impl filesystem::types::HostDescriptor for HermesRuntimeState { } } -impl filesystem::types::HostDirectoryEntryStream for HermesRuntimeState { +impl filesystem::types::HostDirectoryEntryStream for HermesRuntimeContext { /// Read a single directory entry from a `directory-entry-stream`. fn read_directory_entry( &mut self, _dir: wasmtime::component::Resource, @@ -401,7 +401,7 @@ impl filesystem::types::HostDirectoryEntryStream for HermesRuntimeState { } } -impl filesystem::types::Host for HermesRuntimeState { +impl filesystem::types::Host for HermesRuntimeContext { /// Attempts to extract a filesystem-related `error-code` from the stream /// `error` provided. /// @@ -419,7 +419,7 @@ impl filesystem::types::Host for HermesRuntimeState { } } -impl filesystem::preopens::Host for HermesRuntimeState { +impl filesystem::preopens::Host for HermesRuntimeContext { /// Return the set of preopened directories, and their path. fn get_directories( &mut self, diff --git a/hermes/bin/src/runtime_extensions/wasi/http/host.rs b/hermes/bin/src/runtime_extensions/wasi/http/host.rs index 397d51f97..fa2fd7422 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/host.rs @@ -16,10 +16,10 @@ use crate::{ }, io::streams::{InputStream, OutputStream}, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl http::types::HostFutureIncomingResponse for HermesRuntimeState { +impl http::types::HostFutureIncomingResponse for HermesRuntimeContext { /// Returns the incoming HTTP Response, or an error, once one is ready. /// /// The outer `option` represents future readiness. Users can wait on this @@ -49,7 +49,7 @@ impl http::types::HostFutureIncomingResponse for HermesRuntimeState { } } -impl http::types::HostFields for HermesRuntimeState { +impl http::types::HostFields for HermesRuntimeContext { /// Construct an empty HTTP Fields. /// /// The resulting `fields` is mutable. @@ -154,7 +154,7 @@ impl http::types::HostFields for HermesRuntimeState { } } -impl http::types::HostFutureTrailers for HermesRuntimeState { +impl http::types::HostFutureTrailers for HermesRuntimeContext { /// Returns the contents of the trailers, or an error which occurred, /// once the future is ready. /// @@ -189,7 +189,7 @@ impl http::types::HostFutureTrailers for HermesRuntimeState { } } -impl http::types::HostOutgoingBody for HermesRuntimeState { +impl http::types::HostOutgoingBody for HermesRuntimeContext { /// Returns a stream for writing the body contents. /// /// The returned `output-stream` is a child resource: it must be dropped @@ -226,7 +226,7 @@ impl http::types::HostOutgoingBody for HermesRuntimeState { } } -impl HostOutgoingResponse for HermesRuntimeState { +impl HostOutgoingResponse for HermesRuntimeContext { /// Construct an `outgoing-response`, with a default `status-code` of `200`. /// If a different `status-code` is needed, it must be set via the /// `set-status-code` method. @@ -285,7 +285,7 @@ impl HostOutgoingResponse for HermesRuntimeState { } } -impl http::types::HostIncomingBody for HermesRuntimeState { +impl http::types::HostIncomingBody for HermesRuntimeContext { /// Returns the contents of the body, as a stream of bytes. /// /// Returns success on first call: the stream representing the contents @@ -320,7 +320,7 @@ impl http::types::HostIncomingBody for HermesRuntimeState { } } -impl HostIncomingResponse for HermesRuntimeState { +impl HostIncomingResponse for HermesRuntimeContext { /// Returns the status code from the incoming response. fn status( &mut self, _rep: wasmtime::component::Resource, @@ -356,7 +356,7 @@ impl HostIncomingResponse for HermesRuntimeState { } } -impl http::types::HostResponseOutparam for HermesRuntimeState { +impl http::types::HostResponseOutparam for HermesRuntimeContext { /// Set the value of the `response-outparam` to either send a response, /// or indicate an error. /// @@ -380,7 +380,7 @@ impl http::types::HostResponseOutparam for HermesRuntimeState { } } -impl http::types::HostRequestOptions for HermesRuntimeState { +impl http::types::HostRequestOptions for HermesRuntimeContext { /// Construct a default `request-options` value. fn new(&mut self) -> wasmtime::Result> { todo!() @@ -440,7 +440,7 @@ impl http::types::HostRequestOptions for HermesRuntimeState { } } -impl http::types::HostOutgoingRequest for HermesRuntimeState { +impl http::types::HostOutgoingRequest for HermesRuntimeContext { /// Construct a new `outgoing-request` with a default `method` of `GET`, and /// `none` values for `path-with-query`, `scheme`, and `authority`. /// @@ -559,7 +559,7 @@ impl http::types::HostOutgoingRequest for HermesRuntimeState { } } -impl http::types::HostIncomingRequest for HermesRuntimeState { +impl http::types::HostIncomingRequest for HermesRuntimeContext { /// Returns the method of the incoming request. fn method( &mut self, _rep: wasmtime::component::Resource, @@ -617,7 +617,7 @@ impl http::types::HostIncomingRequest for HermesRuntimeState { } } -impl http::types::Host for HermesRuntimeState { +impl http::types::Host for HermesRuntimeContext { /// Attempts to extract a http-related `error` from the wasi:io `error` /// provided. /// @@ -636,7 +636,7 @@ impl http::types::Host for HermesRuntimeState { } } -impl http::outgoing_handler::Host for HermesRuntimeState { +impl http::outgoing_handler::Host for HermesRuntimeContext { /// This function is invoked with an outgoing HTTP Request, and it returns /// a resource `future-incoming-response` which represents an HTTP Response /// which may arrive in the future. diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs index 7d164adb0..7f8dfb505 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::wasi::io::error::{Error, Host, HostError}, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl HostError for HermesRuntimeState { +impl HostError for HermesRuntimeContext { /// Returns a string that is suitable to assist humans in debugging /// this error. /// @@ -24,4 +24,4 @@ impl HostError for HermesRuntimeState { } } -impl Host for HermesRuntimeState {} +impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs index 6dd97f5cc..6c70a4b62 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs @@ -4,10 +4,10 @@ use crate::{ runtime_extensions::bindings::wasi::io::streams::{ Host, HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, }, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl HostInputStream for HermesRuntimeState { +impl HostInputStream for HermesRuntimeContext { /// Perform a non-blocking read from the stream. /// /// This function returns a list of bytes containing the read data, @@ -66,7 +66,7 @@ impl HostInputStream for HermesRuntimeState { } } -impl HostOutputStream for HermesRuntimeState { +impl HostOutputStream for HermesRuntimeContext { /// Check readiness for writing. This function never blocks. /// /// Returns the number of bytes permitted for the next call to `write`, @@ -228,4 +228,4 @@ impl HostOutputStream for HermesRuntimeState { } } -impl Host for HermesRuntimeState {} +impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs index f2f62426d..ee11da79e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs @@ -1,10 +1,10 @@ //! Insecure RNG host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::random::insecure::Host, runtime_state::HermesRuntimeState, + runtime_extensions::bindings::wasi::random::insecure::Host, runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Return `len` insecure pseudo-random bytes. /// /// This function is not cryptographically secure. Do not use it for diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs index 11b8ac988..df1115715 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs @@ -2,10 +2,10 @@ use crate::{ runtime_extensions::bindings::wasi::random::insecure_seed::Host, - runtime_state::HermesRuntimeState, + runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Return a 128-bit value that may contain a pseudo-random value. /// /// The returned value is not required to be computed from a Cryptographically Secure diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs index b97c31456..8d5ce5f31 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs @@ -1,10 +1,10 @@ //! Random RNG host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::random::random::Host, runtime_state::HermesRuntimeState, + runtime_extensions::bindings::wasi::random::random::Host, runtime_context::HermesRuntimeContext, }; -impl Host for HermesRuntimeState { +impl Host for HermesRuntimeContext { /// Return `len` cryptographically-secure random or pseudo-random bytes. /// /// This function must produce data at least as cryptographically secure and diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index c5db307a6..ae92f78a2 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -13,7 +13,7 @@ use wasmtime::{ }; use crate::{ - event::HermesEventPayload, runtime_extensions::bindings, runtime_state::HermesRuntimeState, + event::HermesEventPayload, runtime_extensions::bindings, runtime_context::HermesRuntimeContext, wasm::engine::Engine, }; @@ -27,7 +27,7 @@ struct BadWASMModuleError(String); /// It is used to interact with the WASM module. pub(crate) struct ModuleInstance { /// `wasmtime::Store` entity - pub(crate) store: WasmStore, + pub(crate) store: WasmStore, /// `Instance` entity pub(crate) instance: bindings::Hermes, } @@ -51,7 +51,7 @@ pub(crate) struct Module { /// partially described in this [RFC](https://github.com/bytecodealliance/rfcs/blob/main/accepted/shared-host-functions.md). /// It separates and optimizes the linkage of the imports to the WASM runtime from the /// module actual initialization process. - pre_instance: WasmInstancePre, + pre_instance: WasmInstancePre, /// `Engine` entity engine: Engine, @@ -75,7 +75,7 @@ impl Module { .map_err(|e| BadWASMModuleError(e.to_string()))?; let mut linker = WasmLinker::new(&engine); - bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesRuntimeState| state) + bindings::Hermes::add_to_linker(&mut linker, |state: &mut HermesRuntimeContext| state) .map_err(|e| BadWASMModuleError(e.to_string()))?; let pre_instance = linker .instantiate_pre(&wasm_module) @@ -113,7 +113,7 @@ impl Module { /// # Errors: /// - `BadWASMModuleError` pub(crate) fn execute_event( - &self, event: &dyn HermesEventPayload, state: HermesRuntimeState, + &self, event: &dyn HermesEventPayload, state: HermesRuntimeContext, ) -> anyhow::Result<()> { let mut store = WasmStore::new(&self.engine, state); let (instance, _) = bindings::Hermes::instantiate_pre(&mut store, &self.pre_instance) @@ -139,7 +139,7 @@ pub mod bench { app::HermesAppName, event::queue::HermesEventQueue, runtime_extensions::state::{State, Stateful}, - runtime_state::HermesRuntimeContext, + runtime_context::HermesRuntimeContext, }; /// Benchmark for executing the `init` event of the Hermes dummy component. @@ -170,7 +170,7 @@ pub mod bench { module .execute_event( &Event, - HermesRuntimeState::new( + HermesRuntimeContext::new( state.clone(), HermesRuntimeContext::new( HermesAppName("app 1".to_string()), From 0531e6da1a0828ebdd60e7ee0e7588649d212110 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Thu, 29 Feb 2024 12:45:07 +0200 Subject: [PATCH 41/52] remove Stateful trait, update runtime extensions state handling --- hermes/bin/src/reactor.rs | 14 ++---- .../runtime_extensions/hermes/binary/mod.rs | 6 +-- .../runtime_extensions/hermes/cardano/mod.rs | 6 +-- .../src/runtime_extensions/hermes/cbor/mod.rs | 6 +-- .../src/runtime_extensions/hermes/cron/mod.rs | 13 +++--- .../runtime_extensions/hermes/crypto/mod.rs | 6 +-- .../src/runtime_extensions/hermes/hash/mod.rs | 6 +-- .../src/runtime_extensions/hermes/init/mod.rs | 27 +++-------- .../src/runtime_extensions/hermes/json/mod.rs | 6 +-- .../runtime_extensions/hermes/kv_store/mod.rs | 6 +-- .../hermes/localtime/mod.rs | 6 +-- .../runtime_extensions/hermes/logging/mod.rs | 6 +-- .../bin/src/runtime_extensions/hermes/mod.rs | 46 ------------------- hermes/bin/src/runtime_extensions/mod.rs | 1 - hermes/bin/src/runtime_extensions/state.rs | 27 ----------- .../src/runtime_extensions/wasi/cli/mod.rs | 6 +-- .../src/runtime_extensions/wasi/clocks/mod.rs | 19 -------- .../wasi/clocks/monotonic/mod.rs | 6 +-- .../wasi/clocks/wall/mod.rs | 6 +-- .../runtime_extensions/wasi/filesystem/mod.rs | 6 +-- .../src/runtime_extensions/wasi/http/mod.rs | 6 +-- .../runtime_extensions/wasi/io/error/mod.rs | 6 +-- .../bin/src/runtime_extensions/wasi/io/mod.rs | 19 -------- .../runtime_extensions/wasi/io/streams/mod.rs | 6 +-- hermes/bin/src/runtime_extensions/wasi/mod.rs | 31 ------------- .../wasi/random/insecure/mod.rs | 6 +-- .../wasi/random/insecure_seed/mod.rs | 6 +-- .../src/runtime_extensions/wasi/random/mod.rs | 22 --------- .../wasi/random/secure/mod.rs | 6 +-- 29 files changed, 73 insertions(+), 260 deletions(-) delete mode 100644 hermes/bin/src/runtime_extensions/state.rs diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index e5934501a..491430eae 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -5,7 +5,6 @@ use std::{sync::Arc, thread}; use crate::{ app::{HermesApp, IndexedApps}, event::queue::{event_execution_loop, HermesEventQueue}, - runtime_extensions::state::{State, Stateful}, }; /// Thread panics error @@ -16,9 +15,6 @@ struct ThreadPanicsError(&'static str); /// Hermes Reactor struct #[allow(dead_code)] pub(crate) struct HermesReactor { - /// Runtime extensions state - state: Arc, - /// Hermes event queue event_queue: Arc, @@ -32,14 +28,12 @@ impl HermesReactor { pub(crate) fn new(apps: Vec) -> Self { let event_queue = HermesEventQueue::new().into(); - let state = State::new().into(); let indexed_apps = apps .into_iter() .map(|app| (app.app_name().clone(), app)) .collect(); Self { - state, event_queue, indexed_apps, } @@ -52,10 +46,10 @@ impl HermesReactor { #[allow(dead_code)] pub(crate) fn run(self) -> anyhow::Result<()> { // Emits init event - self.state - .hermes - .init - .emit_init_event(self.event_queue.as_ref())?; + // self.state + // .hermes + // .init + // .emit_init_event(self.event_queue.as_ref())?; let events_thread = thread::spawn(move || event_execution_loop(&self.indexed_apps, &self.event_queue)); diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs index 094e670c4..ebfd5f7bf 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs @@ -1,13 +1,13 @@ //! Binary runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs index db9829167..99d811856 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs @@ -1,14 +1,14 @@ //! Cardano Blockchain runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod event; mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs index 3cb8b2c79..573c4da22 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs @@ -1,13 +1,13 @@ //! CBOR runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs index 92c2b2aff..74dc67a1b 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs @@ -7,12 +7,9 @@ use std::{ use time::{Duration, OffsetDateTime}; -use crate::runtime_extensions::{ - bindings::{ - hermes::cron::api::{CronComponent, CronEventTag, CronSched, CronTagged, CronTime}, - wasi::clocks::monotonic_clock::Instant, - }, - state::Stateful, +use crate::runtime_extensions::bindings::{ + hermes::cron::api::{CronComponent, CronEventTag, CronSched, CronTagged, CronTime}, + wasi::clocks::monotonic_clock::Instant, }; mod event; @@ -24,7 +21,9 @@ pub(crate) struct State { _crontabs: HashMap, } -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State { _crontabs: HashMap::new(), diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs index 5b2935e3a..332607d2d 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs @@ -1,13 +1,13 @@ //! Crypto runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs index f3796d3d2..373bbf0d6 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs @@ -1,14 +1,14 @@ //! Hash runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod blake2b; mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 7e8f7eb0e..8420ef82d 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,27 +1,12 @@ //! Init runtime extension implementation. -use crate::{ - event::{queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}, - runtime_extensions::state::Stateful, -}; +use crate::event::{queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}; mod event; -/// State -pub(crate) struct State {} - -impl Stateful for State { - fn new() -> Self { - State {} - } -} - -impl State { - /// Emit Init event - #[allow(clippy::unused_self)] - pub(crate) fn emit_init_event(&self, event_queue: &HermesEventQueue) -> anyhow::Result<()> { - let init_event = HermesEvent::new(event::InitEvent {}, TargetApp::All, TargetModule::All); - event_queue.add_into_queue(init_event)?; - Ok(()) - } +/// Emit Init event for a provided Hermes app target +pub(crate) fn emit_init_event(event_queue: &HermesEventQueue) -> anyhow::Result<()> { + let init_event = HermesEvent::new(event::InitEvent {}, TargetApp::All, TargetModule::All); + event_queue.add_into_queue(init_event)?; + Ok(()) } diff --git a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs index ec2eb2117..0bb4d09a3 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs @@ -1,13 +1,13 @@ //! JSON runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs index 99baf1b81..d3b0516d8 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs @@ -1,14 +1,14 @@ //! KV-Store runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod event; mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs index 2ba1b5c29..f10a908f5 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs @@ -1,13 +1,13 @@ //! Localtime runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs index bd06f1a11..d6588dd09 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs @@ -1,13 +1,13 @@ //! Logging runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { State {} } diff --git a/hermes/bin/src/runtime_extensions/hermes/mod.rs b/hermes/bin/src/runtime_extensions/hermes/mod.rs index f3aa676ee..fdd2e7390 100644 --- a/hermes/bin/src/runtime_extensions/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/mod.rs @@ -1,7 +1,5 @@ //! Hermes runtime extensions implementations - HERMES custom extensions -use crate::runtime_extensions::state::Stateful; - pub(crate) mod binary; pub(crate) mod cardano; pub(crate) mod cbor; @@ -13,47 +11,3 @@ pub(crate) mod json; pub(crate) mod kv_store; pub(crate) mod localtime; pub(crate) mod logging; - -/// Hermes extensions state -pub(crate) struct State { - /// Binary extensions state - pub(crate) _binary: binary::State, - /// Cardano extensions state - pub(crate) _cardano: cardano::State, - /// CBOR extensions state - pub(crate) _cbor: cbor::State, - /// Cron extensions state - pub(crate) _cron: cron::State, - /// Crypto extensions state - pub(crate) _crypto: crypto::State, - /// Hash extensions state - pub(crate) _hash: hash::State, - /// Init extensions state - pub(crate) init: init::State, - /// JSON extensions state - pub(crate) _json: json::State, - /// KV store extensions state - pub(crate) _kv_store: kv_store::State, - /// Localtime extensions state - pub(crate) _localtime: localtime::State, - /// Logging extensions state - pub(crate) _logging: logging::State, -} - -impl Stateful for State { - fn new() -> Self { - Self { - _binary: binary::State::new(), - _cardano: cardano::State::new(), - _cbor: cbor::State::new(), - _cron: cron::State::new(), - _crypto: crypto::State::new(), - _hash: hash::State::new(), - init: init::State::new(), - _json: json::State::new(), - _kv_store: kv_store::State::new(), - _localtime: localtime::State::new(), - _logging: logging::State::new(), - } - } -} diff --git a/hermes/bin/src/runtime_extensions/mod.rs b/hermes/bin/src/runtime_extensions/mod.rs index bb903288e..29f39a8d7 100644 --- a/hermes/bin/src/runtime_extensions/mod.rs +++ b/hermes/bin/src/runtime_extensions/mod.rs @@ -2,5 +2,4 @@ pub(crate) mod bindings; pub(crate) mod hermes; -pub(crate) mod state; pub(crate) mod wasi; diff --git a/hermes/bin/src/runtime_extensions/state.rs b/hermes/bin/src/runtime_extensions/state.rs deleted file mode 100644 index 04deb2bf0..000000000 --- a/hermes/bin/src/runtime_extensions/state.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! Hermes runtime extensions state. - -use super::{hermes, wasi}; - -/// All Hermes runtime extensions states need to implement this. -pub(crate) trait Stateful: Send + Sync { - /// Initial state for the given context - fn new() -> Self; -} - -/// All runtime extensions state -pub(crate) struct State { - /// Hermes custom extensions state - pub(crate) hermes: hermes::State, - - /// WASI standard extensions state - pub(crate) _wasi: wasi::State, -} - -impl Stateful for State { - fn new() -> Self { - Self { - hermes: hermes::State::new(), - _wasi: wasi::State::new(), - } - } -} diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs index 174ef683e..dda9c88d3 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs @@ -1,13 +1,13 @@ //! CLI runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs index 88e9f3741..0f7162b9e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs @@ -1,23 +1,4 @@ //! Host - WASI - Clock implementations -use crate::runtime_extensions::state::Stateful; - mod monotonic; mod wall; - -/// WASI State -pub(crate) struct State { - /// monotonic State - _monotonic: monotonic::State, - /// wall State - _wall: wall::State, -} - -impl Stateful for State { - fn new() -> Self { - Self { - _monotonic: monotonic::State::new(), - _wall: wall::State::new(), - } - } -} diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs index 594df894e..c43e249b2 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs @@ -1,13 +1,13 @@ //! Monotonic clock runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs index 6add5bd83..6a2bb7276 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs @@ -1,13 +1,13 @@ //! Wall clock runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs index 6b2711c1a..f3cb8236b 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs @@ -1,13 +1,13 @@ //! Filesystem runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs index 5a20a50f4..556ee4c84 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs @@ -1,13 +1,13 @@ //! HTTP runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs index 2c0e7b9c0..0d34db771 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs @@ -1,13 +1,13 @@ //! IO Error runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/io/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs index 6342c881e..0fac8bc81 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs @@ -1,23 +1,4 @@ //! Host - WASI IO Implementation -use crate::runtime_extensions::state::Stateful; - pub(crate) mod error; pub(crate) mod streams; - -/// WASI State -pub(crate) struct State { - /// WASI IO error state - _error: error::State, - /// WASI IO streams state - _streams: streams::State, -} - -impl Stateful for State { - fn new() -> Self { - Self { - _error: error::State::new(), - _streams: streams::State::new(), - } - } -} diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs index 9e693466b..f4d81761e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs @@ -1,13 +1,13 @@ //! IO Streams runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/mod.rs b/hermes/bin/src/runtime_extensions/wasi/mod.rs index 757e27bff..3498b67d3 100644 --- a/hermes/bin/src/runtime_extensions/wasi/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/mod.rs @@ -1,39 +1,8 @@ //! Hermes runtime extensions implementations - WASI standard extensions -use crate::runtime_extensions::state::Stateful; - pub(crate) mod cli; pub(crate) mod clocks; pub(crate) mod filesystem; pub(crate) mod http; pub(crate) mod io; pub(crate) mod random; - -/// WASI State -pub(crate) struct State { - /// WASI CLI State - _cli: cli::State, - /// WASI Clock State - _clocks: clocks::State, - /// WASI Filesystem State - _filesystem: filesystem::State, - /// WASI HTTP State - _http: http::State, - /// WASI IO State - _io: io::State, - /// WASI Random State - _random: random::State, -} - -impl Stateful for State { - fn new() -> Self { - Self { - _cli: cli::State::new(), - _clocks: clocks::State::new(), - _filesystem: filesystem::State::new(), - _http: http::State::new(), - _io: io::State::new(), - _random: random::State::new(), - } - } -} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs index 8cfcb6cdb..32a50ceee 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs @@ -1,13 +1,13 @@ //! Insecure RNG runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs index 40abd2ed8..6c9501db1 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs @@ -1,13 +1,13 @@ //! Insecure RNG seed runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } diff --git a/hermes/bin/src/runtime_extensions/wasi/random/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs index e75ef2f09..ef3f4770b 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs @@ -1,27 +1,5 @@ //! Host - WASI - Random implementations -use crate::runtime_extensions::state::Stateful; - pub(crate) mod insecure; pub(crate) mod insecure_seed; pub(crate) mod secure; - -/// WASI State -pub(crate) struct State { - /// insecure State - _insecure: insecure::State, - /// insecure_seed State - _insecure_seed: insecure_seed::State, - /// secure State - _secure: secure::State, -} - -impl Stateful for State { - fn new() -> Self { - Self { - _insecure: insecure::State::new(), - _insecure_seed: insecure_seed::State::new(), - _secure: secure::State::new(), - } - } -} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs index 680503cd7..2144e27c7 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs @@ -1,13 +1,13 @@ //! Random RNG runtime extension implementation. -use crate::runtime_extensions::state::Stateful; - mod host; /// WASI State pub(crate) struct State {} -impl Stateful for State { +impl State { + /// + #[allow(dead_code)] fn new() -> Self { Self {} } From 6ef6fd4e9c8a315e8595f31446a669f9075427ef Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Thu, 29 Feb 2024 12:52:01 +0200 Subject: [PATCH 42/52] update emiting init event --- hermes/bin/src/event/mod.rs | 4 ++-- hermes/bin/src/event/queue.rs | 8 +++---- hermes/bin/src/reactor.rs | 21 ++++++++++--------- .../src/runtime_extensions/hermes/init/mod.rs | 15 ++++++++++--- 4 files changed, 29 insertions(+), 19 deletions(-) diff --git a/hermes/bin/src/event/mod.rs b/hermes/bin/src/event/mod.rs index 774f8d689..c85ddbb7e 100644 --- a/hermes/bin/src/event/mod.rs +++ b/hermes/bin/src/event/mod.rs @@ -27,9 +27,9 @@ pub(crate) trait HermesEventPayload: Send + Sync + 'static { /// Target Hermes app to execute the event pub(crate) enum TargetApp { /// Execute for all available apps - All, + _All, /// Execute for a specific list of apps - _List(Vec), + List(Vec), } /// Target WASM module to execute the event diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 0899188de..a248d0d4b 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -87,14 +87,14 @@ fn execute_event( #[allow(clippy::unnecessary_wraps)] fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> anyhow::Result<()> { match (event.target_app(), event.target_module()) { - (TargetApp::All, TargetModule::All) => { + (TargetApp::_All, TargetModule::All) => { for (app_name, app) in indexed_apps { for (module_id, module) in app.indexed_modules() { execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; } } }, - (TargetApp::All, TargetModule::_List(target_modules)) => { + (TargetApp::_All, TargetModule::_List(target_modules)) => { for (app_name, app) in indexed_apps { for module_id in target_modules { let module = app @@ -106,7 +106,7 @@ fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> } } }, - (TargetApp::_List(target_apps), TargetModule::All) => { + (TargetApp::List(target_apps), TargetModule::All) => { for app_name in target_apps { let app = indexed_apps .get(app_name) @@ -116,7 +116,7 @@ fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> } } }, - (TargetApp::_List(target_apps), TargetModule::_List(target_modules)) => { + (TargetApp::List(target_apps), TargetModule::_List(target_modules)) => { for app_name in target_apps { let app = indexed_apps .get(app_name) diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 491430eae..f2fe097da 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -5,6 +5,7 @@ use std::{sync::Arc, thread}; use crate::{ app::{HermesApp, IndexedApps}, event::queue::{event_execution_loop, HermesEventQueue}, + runtime_extensions::hermes::init, }; /// Thread panics error @@ -25,18 +26,24 @@ pub(crate) struct HermesReactor { impl HermesReactor { /// Create a new Hermes Reactor #[allow(dead_code)] - pub(crate) fn new(apps: Vec) -> Self { - let event_queue = HermesEventQueue::new().into(); + pub(crate) fn new(apps: Vec) -> anyhow::Result { + let event_queue = Arc::new(HermesEventQueue::new()); + + // Emit init event + init::emit_init_event( + &event_queue, + apps.iter().map(|app| app.app_name().clone()).collect(), + )?; let indexed_apps = apps .into_iter() .map(|app| (app.app_name().clone(), app)) .collect(); - Self { + Ok(Self { event_queue, indexed_apps, - } + }) } /// Run Hermes. @@ -45,12 +52,6 @@ impl HermesReactor { /// This is a blocking call util all tasks are finished. #[allow(dead_code)] pub(crate) fn run(self) -> anyhow::Result<()> { - // Emits init event - // self.state - // .hermes - // .init - // .emit_init_event(self.event_queue.as_ref())?; - let events_thread = thread::spawn(move || event_execution_loop(&self.indexed_apps, &self.event_queue)); diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 8420ef82d..d18d46dd1 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -1,12 +1,21 @@ //! Init runtime extension implementation. -use crate::event::{queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}; +use crate::{ + app::HermesAppName, + event::{queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}, +}; mod event; /// Emit Init event for a provided Hermes app target -pub(crate) fn emit_init_event(event_queue: &HermesEventQueue) -> anyhow::Result<()> { - let init_event = HermesEvent::new(event::InitEvent {}, TargetApp::All, TargetModule::All); +pub(crate) fn emit_init_event( + event_queue: &HermesEventQueue, target_apps: Vec, +) -> anyhow::Result<()> { + let init_event = HermesEvent::new( + event::InitEvent {}, + TargetApp::List(target_apps), + TargetModule::All, + ); event_queue.add_into_queue(init_event)?; Ok(()) } From 065bfee6c07ea9026a43dcc6dd70cf2fb0620903 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Thu, 29 Feb 2024 13:35:20 +0200 Subject: [PATCH 43/52] refactor event queue --- hermes/bin/src/event/queue.rs | 61 +++++++++++++++++++---------------- hermes/bin/src/reactor.rs | 43 ++++++++---------------- 2 files changed, 48 insertions(+), 56 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index a248d0d4b..7391db8d9 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -1,8 +1,11 @@ //! Hermes event queue implementation. -use std::sync::{ - mpsc::{Receiver, Sender}, - Mutex, +use std::{ + sync::{ + mpsc::{Receiver, Sender}, + Arc, + }, + thread, }; use super::{HermesEvent, HermesEventPayload, TargetApp, TargetModule}; @@ -27,28 +30,28 @@ pub(crate) enum Error { #[error("Failed to add event into the event queue. Event queue is closed.")] CannotAddEvent, - /// Trying to execute one more event execution loop. It is allowed to run only one - /// execution loop in a time. - #[error("Trying to execute one more event execution loop. It is allowed to run only one execution loop in a time.")] - AnotherEventExecutionLoop, + /// Panics inside the `event_execution_loop` function error. + #[error("Panics inside the `event_execution_loop` function!")] + EventLoopPanics, } /// Hermes event queue. pub(crate) struct HermesEventQueue { /// Hermes event queue sender sender: Sender, - /// Hermes event queue receiver - receiver: Mutex>, + /// Event loop thread handler + event_loop: thread::JoinHandle>, } impl HermesEventQueue { /// Creates a new instance of the `HermesEventQueue`. - pub(crate) fn new() -> Self { + /// Runs an event loop thread. + pub(crate) fn new(indexed_apps: Arc) -> Self { let (sender, receiver) = std::sync::mpsc::channel(); - Self { - sender, - receiver: Mutex::new(receiver), - } + + let event_loop = thread::spawn(move || event_execution_loop(&indexed_apps, receiver)); + + Self { sender, event_loop } } /// Add event into the event queue @@ -59,6 +62,17 @@ impl HermesEventQueue { self.sender.send(event).map_err(|_| Error::CannotAddEvent)?; Ok(()) } + + /// Waits for the event loop to finish. + /// # Note: + /// This is a blocking call. + #[allow(dead_code)] + pub(crate) fn wait(self) -> anyhow::Result<()> { + self.event_loop + .join() + .map_err(|_| Error::EventLoopPanics)??; + Ok(()) + } } /// Execute a hermes event on the provided module and all necessary info. @@ -84,6 +98,7 @@ fn execute_event( /// # Errors: /// - `Error::ModuleNotFound` /// - `Error::AppNotFound` +/// - `wasm::module::BadWASMModuleError` #[allow(clippy::unnecessary_wraps)] fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> anyhow::Result<()> { match (event.target_app(), event.target_module()) { @@ -136,24 +151,16 @@ fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> Ok(()) } -/// Executes Hermes events from provided the event queue. +/// Executes Hermes events from the provided receiver . /// /// # Errors: -/// - `Error::AnotherEventExecutionLoop` /// - `Error::ModuleNotFound` /// - `Error::AppNotFound` -/// -/// # Note: -/// This is a blocking call. -pub(crate) fn event_execution_loop( - indexed_apps: &IndexedApps, event_queue: &HermesEventQueue, +/// - `wasm::module::BadWASMModuleError` +fn event_execution_loop( + indexed_apps: &IndexedApps, receiver: Receiver, ) -> anyhow::Result<()> { - let events = event_queue - .receiver - .try_lock() - .map_err(|_| Error::AnotherEventExecutionLoop)?; - - for event in events.iter() { + for event in receiver { targeted_event_execution(indexed_apps, &event)?; } Ok(()) diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index f2fe097da..56a8a1de4 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -1,10 +1,10 @@ //! Hermes Reactor implementation. -use std::{sync::Arc, thread}; +use std::sync::Arc; use crate::{ app::{HermesApp, IndexedApps}, - event::queue::{event_execution_loop, HermesEventQueue}, + event::queue::HermesEventQueue, runtime_extensions::hermes::init, }; @@ -20,44 +20,29 @@ pub(crate) struct HermesReactor { event_queue: Arc, /// Hermes apps - indexed_apps: IndexedApps, + indexed_apps: Arc, } impl HermesReactor { - /// Create a new Hermes Reactor + /// Create a new Hermes Reactor. + /// Runs all necessary tasks in separed threads. #[allow(dead_code)] pub(crate) fn new(apps: Vec) -> anyhow::Result { - let event_queue = Arc::new(HermesEventQueue::new()); + let target_apps = apps.iter().map(|app| app.app_name().clone()).collect(); - // Emit init event - init::emit_init_event( - &event_queue, - apps.iter().map(|app| app.app_name().clone()).collect(), - )?; + let indexed_apps: Arc = Arc::new( + apps.into_iter() + .map(|app| (app.app_name().clone(), app)) + .collect(), + ); - let indexed_apps = apps - .into_iter() - .map(|app| (app.app_name().clone(), app)) - .collect(); + let event_queue = Arc::new(HermesEventQueue::new(indexed_apps.clone())); + + init::emit_init_event(&event_queue, target_apps)?; Ok(Self { event_queue, indexed_apps, }) } - - /// Run Hermes. - /// - /// # Note: - /// This is a blocking call util all tasks are finished. - #[allow(dead_code)] - pub(crate) fn run(self) -> anyhow::Result<()> { - let events_thread = - thread::spawn(move || event_execution_loop(&self.indexed_apps, &self.event_queue)); - - events_thread - .join() - .map_err(|_| ThreadPanicsError("events handler"))??; - Ok(()) - } } From e8eebfd32d3dd4a0ee35701c3f00ab18648a1a4c Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Thu, 29 Feb 2024 14:42:00 +0200 Subject: [PATCH 44/52] refactor --- hermes/bin/src/event/queue.rs | 59 +++++++++++++++++------------------ 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 7391db8d9..23426b33e 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -79,7 +79,7 @@ impl HermesEventQueue { /// /// # Errors: /// - `wasm::module::BadWASMModuleError` -fn execute_event( +fn event_dispatch( app_name: HermesAppName, module_id: ModuleId, event: &dyn HermesEventPayload, module: &Module, ) -> anyhow::Result<()> { let runtime_context = HermesRuntimeContext::new( @@ -101,53 +101,50 @@ fn execute_event( /// - `wasm::module::BadWASMModuleError` #[allow(clippy::unnecessary_wraps)] fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> anyhow::Result<()> { - match (event.target_app(), event.target_module()) { - (TargetApp::_All, TargetModule::All) => { - for (app_name, app) in indexed_apps { - for (module_id, module) in app.indexed_modules() { - execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; - } - } - }, - (TargetApp::_All, TargetModule::_List(target_modules)) => { - for (app_name, app) in indexed_apps { - for module_id in target_modules { - let module = app - .indexed_modules() - .get(module_id) - .ok_or(Error::ModuleNotFound(module_id.to_owned()))?; - - execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; - } - } - }, - (TargetApp::List(target_apps), TargetModule::All) => { + // Find target apps + let target_apps = match event.target_app() { + TargetApp::_All => indexed_apps.iter().collect(), + TargetApp::List(target_apps) => { + let mut res = Vec::new(); for app_name in target_apps { let app = indexed_apps .get(app_name) .ok_or(Error::AppNotFound(app_name.to_owned()))?; + res.push((app_name, app)); + } + res + }, + }; + // Find target modules + let target_module = match event.target_module() { + TargetModule::All => { + let mut res = Vec::new(); + for (app_name, app) in target_apps { for (module_id, module) in app.indexed_modules() { - execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; + res.push((app_name, module_id, module)); } } + res }, - (TargetApp::List(target_apps), TargetModule::_List(target_modules)) => { - for app_name in target_apps { - let app = indexed_apps - .get(app_name) - .ok_or(Error::AppNotFound(app_name.to_owned()))?; + TargetModule::_List(target_modules) => { + let mut res = Vec::new(); + for (app_name, app) in target_apps { for module_id in target_modules { let module = app .indexed_modules() .get(module_id) .ok_or(Error::ModuleNotFound(module_id.to_owned()))?; - - execute_event(app_name.clone(), module_id.clone(), event.payload(), module)?; + res.push((app_name, module_id, module)); } } + res }, - } + }; + // Event dispatch + for (app_name, module_id, module) in target_module { + event_dispatch(app_name.clone(), module_id.clone(), event.payload(), module)?; + } Ok(()) } From b9eadd1e1454a14685ececa874a917381e766c32 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Thu, 29 Feb 2024 14:42:21 +0200 Subject: [PATCH 45/52] fix fmt --- hermes/bin/src/lib.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/binary/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/cardano/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/cbor/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/cron/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/crypto/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/hash/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/json/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/localtime/host.rs | 2 +- hermes/bin/src/runtime_extensions/hermes/logging/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/cli/host.rs | 2 +- .../bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/http/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/io/error/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs | 2 +- .../bin/src/runtime_extensions/wasi/random/insecure/host.rs | 3 ++- .../src/runtime_extensions/wasi/random/insecure_seed/host.rs | 2 +- hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs | 2 +- hermes/bin/src/wasm/module.rs | 4 ++-- 22 files changed, 24 insertions(+), 23 deletions(-) diff --git a/hermes/bin/src/lib.rs b/hermes/bin/src/lib.rs index 2206e4037..6d2e54939 100644 --- a/hermes/bin/src/lib.rs +++ b/hermes/bin/src/lib.rs @@ -4,8 +4,8 @@ mod app; mod event; mod reactor; -mod runtime_extensions; mod runtime_context; +mod runtime_extensions; mod wasm; #[cfg(feature = "bench")] diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs index 7274c1cb8..374e658c3 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/host.rs @@ -1,7 +1,7 @@ //! Binary host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::hermes::binary::api::Host, runtime_context::HermesRuntimeContext, + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::hermes::binary::api::Host, }; impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs index 9f7d24aaf..35d036644 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/host.rs @@ -1,11 +1,11 @@ //! Cardano Blockchain host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::hermes::cardano::api::{ CardanoBlock, CardanoBlockchainId, CardanoTxn, FetchError, Host, Slot, TxnError, UnsubscribeOptions, }, - runtime_context::HermesRuntimeContext, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs index 7471bf074..384166407 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/host.rs @@ -1,7 +1,7 @@ //! CBOR host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::hermes::cbor::api::Host, runtime_context::HermesRuntimeContext, + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::hermes::cbor::api::Host, }; impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs index f107dfded..e9abe06f0 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/host.rs @@ -1,6 +1,7 @@ //! Cron host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::{ bindings::{ hermes::cron::api::{CronEventTag, CronSched, CronTagged, CronTime, Host}, @@ -8,7 +9,6 @@ use crate::{ }, hermes::cron::{mkcron_impl, mkdelay_crontab}, }, - runtime_context::HermesRuntimeContext, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs index 4af8bc157..fb53cddb1 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/host.rs @@ -1,6 +1,7 @@ //! Crypto host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::hermes::{ binary::api::Bstr, crypto::api::{ @@ -8,7 +9,6 @@ use crate::{ Host, HostEd25519Bip32, }, }, - runtime_context::HermesRuntimeContext, }; impl HostEd25519Bip32 for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs index 2b003631b..e51f047e0 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/host.rs @@ -2,11 +2,11 @@ use super::blake2b; use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::hermes::{ binary::api::Bstr, hash::api::{Errno, Host}, }, - runtime_context::HermesRuntimeContext, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/hermes/json/host.rs b/hermes/bin/src/runtime_extensions/hermes/json/host.rs index 7b0405e7a..dc0fbcd19 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/host.rs @@ -1,7 +1,7 @@ //! JSON host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::hermes::json::api::Host, runtime_context::HermesRuntimeContext, + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::hermes::json::api::Host, }; impl Host for HermesRuntimeContext {} diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs index 6c1ee199e..245f3cb53 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/host.rs @@ -1,8 +1,8 @@ //! KV-Store host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::hermes::kv_store::api::{Host, KvValues}, runtime_context::HermesRuntimeContext, + runtime_extensions::bindings::hermes::kv_store::api::{Host, KvValues}, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs index 3fbb66439..076090495 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/host.rs @@ -1,11 +1,11 @@ //! Localtime host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::{ hermes::localtime::api::{Errno, Host, Localtime, Timezone}, wasi::clocks::wall_clock::Datetime, }, - runtime_context::HermesRuntimeContext, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs index 44e07de2c..74841b9ec 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/host.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/host.rs @@ -1,11 +1,11 @@ //! Logging host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::hermes::{ json::api::Json, logging::api::{Host, Level}, }, - runtime_context::HermesRuntimeContext, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs index 5da0e28fd..2f353f1c9 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/host.rs @@ -1,11 +1,11 @@ //! CLI host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::wasi::{ cli, io::streams::{InputStream, OutputStream}, }, - runtime_context::HermesRuntimeContext, }; impl cli::environment::Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs index 09d20fb6f..97f210063 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/host.rs @@ -1,8 +1,8 @@ //! Monotonic clock host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, runtime_context::HermesRuntimeContext, + runtime_extensions::bindings::wasi::clocks::monotonic_clock::{Duration, Host, Instant}, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs index 1dd2ad35a..56b5152ec 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/host.rs @@ -1,8 +1,8 @@ //! Wall clock host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::clocks::wall_clock::{Datetime, Host}, runtime_context::HermesRuntimeContext, + runtime_extensions::bindings::wasi::clocks::wall_clock::{Datetime, Host}, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs index 6c013f73d..e3683b529 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/host.rs @@ -1,6 +1,7 @@ //! Filesystem host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::wasi::{ filesystem::{ self, @@ -12,7 +13,6 @@ use crate::{ }, io::streams::{InputStream, OutputStream}, }, - runtime_context::HermesRuntimeContext, }; impl filesystem::types::HostDescriptor for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/http/host.rs b/hermes/bin/src/runtime_extensions/wasi/http/host.rs index fa2fd7422..f28d37d8a 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/host.rs @@ -1,6 +1,7 @@ //! HTTP host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::wasi::{ http::{ self, @@ -16,7 +17,6 @@ use crate::{ }, io::streams::{InputStream, OutputStream}, }, - runtime_context::HermesRuntimeContext, }; impl http::types::HostFutureIncomingResponse for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs index 7f8dfb505..73bb5f03e 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/host.rs @@ -1,8 +1,8 @@ //! IO Error host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::io::error::{Error, Host, HostError}, runtime_context::HermesRuntimeContext, + runtime_extensions::bindings::wasi::io::error::{Error, Host, HostError}, }; impl HostError for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs index 6c70a4b62..270d7f68c 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/host.rs @@ -1,10 +1,10 @@ //! IO Streams host implementation for WASM runtime. use crate::{ + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::wasi::io::streams::{ Host, HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, }, - runtime_context::HermesRuntimeContext, }; impl HostInputStream for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs index ee11da79e..634b29a1f 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/host.rs @@ -1,7 +1,8 @@ //! Insecure RNG host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::random::insecure::Host, runtime_context::HermesRuntimeContext, + runtime_context::HermesRuntimeContext, + runtime_extensions::bindings::wasi::random::insecure::Host, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs index df1115715..3a7ed7a06 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/host.rs @@ -1,8 +1,8 @@ //! Insecure RNG seed host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::random::insecure_seed::Host, runtime_context::HermesRuntimeContext, + runtime_extensions::bindings::wasi::random::insecure_seed::Host, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs index 8d5ce5f31..99f4c9fa4 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/host.rs @@ -1,7 +1,7 @@ //! Random RNG host implementation for WASM runtime. use crate::{ - runtime_extensions::bindings::wasi::random::random::Host, runtime_context::HermesRuntimeContext, + runtime_context::HermesRuntimeContext, runtime_extensions::bindings::wasi::random::random::Host, }; impl Host for HermesRuntimeContext { diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index ae92f78a2..943aba1bb 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -13,7 +13,7 @@ use wasmtime::{ }; use crate::{ - event::HermesEventPayload, runtime_extensions::bindings, runtime_context::HermesRuntimeContext, + event::HermesEventPayload, runtime_context::HermesRuntimeContext, runtime_extensions::bindings, wasm::engine::Engine, }; @@ -138,8 +138,8 @@ pub mod bench { use crate::{ app::HermesAppName, event::queue::HermesEventQueue, - runtime_extensions::state::{State, Stateful}, runtime_context::HermesRuntimeContext, + runtime_extensions::state::{State, Stateful}, }; /// Benchmark for executing the `init` event of the Hermes dummy component. From 09ba26e43e0a5f89e1e8bafb779771049acef02b Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Thu, 29 Feb 2024 17:02:10 +0200 Subject: [PATCH 46/52] fix spelling --- hermes/bin/src/reactor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 56a8a1de4..96f7c91ea 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -25,7 +25,7 @@ pub(crate) struct HermesReactor { impl HermesReactor { /// Create a new Hermes Reactor. - /// Runs all necessary tasks in separed threads. + /// Runs all necessary tasks in separate threads. #[allow(dead_code)] pub(crate) fn new(apps: Vec) -> anyhow::Result { let target_apps = apps.iter().map(|app| app.app_name().clone()).collect(); From 922d2d865bb0df22b50fa669fe24b83cd642e5bd Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 1 Mar 2024 11:25:46 +0200 Subject: [PATCH 47/52] make HermesEventQueue singltone and static instance --- hermes/Cargo.toml | 1 + hermes/bin/Cargo.toml | 1 + hermes/bin/src/event/queue.rs | 50 ++++++++++++------- hermes/bin/src/reactor.rs | 40 +++++++++++---- .../src/runtime_extensions/hermes/init/mod.rs | 18 +++---- hermes/bin/src/wasm/module.rs | 23 ++------- 6 files changed, 77 insertions(+), 56 deletions(-) diff --git a/hermes/Cargo.toml b/hermes/Cargo.toml index 6f57553ea..b82fcecfe 100644 --- a/hermes/Cargo.toml +++ b/hermes/Cargo.toml @@ -65,3 +65,4 @@ tracing = "0.1.40" tracing-subscriber = "0.3.18" criterion = "0.5.1" time = "0.3.34" +once_cell = "1.19.0" diff --git a/hermes/bin/Cargo.toml b/hermes/bin/Cargo.toml index 36d55bcb3..9ee8f11eb 100644 --- a/hermes/bin/Cargo.toml +++ b/hermes/bin/Cargo.toml @@ -29,3 +29,4 @@ hex-literal = { workspace = true } thiserror = { workspace = true } criterion = { workspace = true, optional = true } time = { workspace = true } +once_cell = { workspace = true } diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 23426b33e..3a7faed04 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -5,9 +5,11 @@ use std::{ mpsc::{Receiver, Sender}, Arc, }, - thread, + thread::{self, JoinHandle}, }; +use once_cell::sync::OnceCell; + use super::{HermesEvent, HermesEventPayload, TargetApp, TargetModule}; use crate::{ app::{HermesAppName, IndexedApps}, @@ -15,6 +17,9 @@ use crate::{ wasm::module::{Module, ModuleId}, }; +/// Singleton instance of the Hermes event queue. +static EVENT_QUEUE_INTANCE: OnceCell = OnceCell::new(); + /// Hermes event queue error #[derive(thiserror::Error, Debug, Clone)] pub(crate) enum Error { @@ -30,28 +35,46 @@ pub(crate) enum Error { #[error("Failed to add event into the event queue. Event queue is closed.")] CannotAddEvent, - /// Panics inside the `event_execution_loop` function error. - #[error("Panics inside the `event_execution_loop` function!")] - EventLoopPanics, + /// Failed when event queue already been initialized. + #[error("Event queue already been initialized.")] + AlreadyInitialized, + + /// Failed when event queue not been initialized. + #[error("Event queue not been initialized. Call `HermesEventQueue::init` first.")] + NotInitialized, } +/// Hermes event queue execution loop thread handler +pub(crate) type HermesEventLoopHandler = JoinHandle>; + /// Hermes event queue. +/// It is a singleton struct. pub(crate) struct HermesEventQueue { /// Hermes event queue sender sender: Sender, - /// Event loop thread handler - event_loop: thread::JoinHandle>, } impl HermesEventQueue { /// Creates a new instance of the `HermesEventQueue`. /// Runs an event loop thread. - pub(crate) fn new(indexed_apps: Arc) -> Self { + pub(crate) fn init(indexed_apps: Arc) -> anyhow::Result { let (sender, receiver) = std::sync::mpsc::channel(); + EVENT_QUEUE_INTANCE + .set(Self { sender }) + .map_err(|_| Error::AlreadyInitialized)?; + let event_loop = thread::spawn(move || event_execution_loop(&indexed_apps, receiver)); - Self { sender, event_loop } + Ok(event_loop) + } + + /// Get the singleton instance of the `HermesEventQueue`. + /// + /// # Errors: + /// - `Error::NotInitialized` + pub(crate) fn get_instance() -> anyhow::Result<&'static HermesEventQueue> { + Ok(EVENT_QUEUE_INTANCE.get().ok_or(Error::NotInitialized)?) } /// Add event into the event queue @@ -62,17 +85,6 @@ impl HermesEventQueue { self.sender.send(event).map_err(|_| Error::CannotAddEvent)?; Ok(()) } - - /// Waits for the event loop to finish. - /// # Note: - /// This is a blocking call. - #[allow(dead_code)] - pub(crate) fn wait(self) -> anyhow::Result<()> { - self.event_loop - .join() - .map_err(|_| Error::EventLoopPanics)??; - Ok(()) - } } /// Execute a hermes event on the provided module and all necessary info. diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index 96f7c91ea..ade06f784 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -4,23 +4,22 @@ use std::sync::Arc; use crate::{ app::{HermesApp, IndexedApps}, - event::queue::HermesEventQueue, + event::queue::{HermesEventLoopHandler, HermesEventQueue}, runtime_extensions::hermes::init, }; -/// Thread panics error +/// Hermes event queue execution loop handler panics error. #[derive(thiserror::Error, Debug)] -#[error("Thread '{0}' panic! internal error!")] -struct ThreadPanicsError(&'static str); +#[error("Hermes event queue execution loop handler panics!")] +struct EventLoopPanics; /// Hermes Reactor struct #[allow(dead_code)] pub(crate) struct HermesReactor { - /// Hermes event queue - event_queue: Arc, - /// Hermes apps indexed_apps: Arc, + /// Hermes event queue loop thread handler. + event_loop: HermesEventLoopHandler, } impl HermesReactor { @@ -28,6 +27,7 @@ impl HermesReactor { /// Runs all necessary tasks in separate threads. #[allow(dead_code)] pub(crate) fn new(apps: Vec) -> anyhow::Result { + // Loading apps let target_apps = apps.iter().map(|app| app.app_name().clone()).collect(); let indexed_apps: Arc = Arc::new( @@ -36,13 +36,33 @@ impl HermesReactor { .collect(), ); - let event_queue = Arc::new(HermesEventQueue::new(indexed_apps.clone())); + let event_loop = HermesEventQueue::init(indexed_apps.clone())?; - init::emit_init_event(&event_queue, target_apps)?; + // Emit Init event for loaded apps + init::emit_init_event(target_apps)?; Ok(Self { - event_queue, indexed_apps, + event_loop, }) } + + /// Waits for all threads to finish. + /// # Note: + /// This is a blocking call. + #[allow(dead_code)] + pub(crate) fn wait(self) -> anyhow::Result<()> { + self.event_loop.join().map_err(|_| EventLoopPanics)??; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn init_hermes_reactor_test() { + let _reactor = HermesReactor::new(vec![]).expect("Could not initialize Hermes reactor."); + } } diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index d18d46dd1..79e7f69a6 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -8,14 +8,14 @@ use crate::{ mod event; /// Emit Init event for a provided Hermes app target -pub(crate) fn emit_init_event( - event_queue: &HermesEventQueue, target_apps: Vec, -) -> anyhow::Result<()> { - let init_event = HermesEvent::new( - event::InitEvent {}, - TargetApp::List(target_apps), - TargetModule::All, - ); - event_queue.add_into_queue(init_event)?; +pub(crate) fn emit_init_event(target_apps: Vec) -> anyhow::Result<()> { + if !target_apps.is_empty() { + let init_event = HermesEvent::new( + event::InitEvent {}, + TargetApp::List(target_apps), + TargetModule::All, + ); + HermesEventQueue::get_instance()?.add_into_queue(init_event)?; + } Ok(()) } diff --git a/hermes/bin/src/wasm/module.rs b/hermes/bin/src/wasm/module.rs index 943aba1bb..3138d96bc 100644 --- a/hermes/bin/src/wasm/module.rs +++ b/hermes/bin/src/wasm/module.rs @@ -132,15 +132,8 @@ impl Module { #[cfg(feature = "bench")] pub mod bench { - use std::sync::Arc; - use super::*; - use crate::{ - app::HermesAppName, - event::queue::HermesEventQueue, - runtime_context::HermesRuntimeContext, - runtime_extensions::state::{State, Stateful}, - }; + use crate::{app::HermesAppName, runtime_context::HermesRuntimeContext}; /// Benchmark for executing the `init` event of the Hermes dummy component. /// It aims to measure the overhead of the WASM module and WASM state initialization @@ -164,21 +157,15 @@ pub mod bench { let module = Module::new(include_bytes!("../../../../wasm/c/bench_component.wasm")).unwrap(); - let state: Arc<_> = State::new().into(); - let event_queue: Arc<_> = HermesEventQueue::new().into(); b.iter(|| { module .execute_event( &Event, HermesRuntimeContext::new( - state.clone(), - HermesRuntimeContext::new( - HermesAppName("app 1".to_string()), - module.id().clone(), - "init".to_string(), - 0, - ), - event_queue.clone(), + HermesAppName("app 1".to_string()), + module.id().clone(), + "init".to_string(), + 0, ), ) .unwrap(); From e9f5da61f2e27f3505f4c46df7dd896a4d6468af Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 1 Mar 2024 14:33:12 +0200 Subject: [PATCH 48/52] fix spelling --- hermes/bin/src/event/queue.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 3a7faed04..60500531d 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -18,7 +18,7 @@ use crate::{ }; /// Singleton instance of the Hermes event queue. -static EVENT_QUEUE_INTANCE: OnceCell = OnceCell::new(); +static EVENT_QUEUE_INSTANCE: OnceCell = OnceCell::new(); /// Hermes event queue error #[derive(thiserror::Error, Debug, Clone)] @@ -60,7 +60,7 @@ impl HermesEventQueue { pub(crate) fn init(indexed_apps: Arc) -> anyhow::Result { let (sender, receiver) = std::sync::mpsc::channel(); - EVENT_QUEUE_INTANCE + EVENT_QUEUE_INSTANCE .set(Self { sender }) .map_err(|_| Error::AlreadyInitialized)?; @@ -74,7 +74,7 @@ impl HermesEventQueue { /// # Errors: /// - `Error::NotInitialized` pub(crate) fn get_instance() -> anyhow::Result<&'static HermesEventQueue> { - Ok(EVENT_QUEUE_INTANCE.get().ok_or(Error::NotInitialized)?) + Ok(EVENT_QUEUE_INSTANCE.get().ok_or(Error::NotInitialized)?) } /// Add event into the event queue From a86194723c34ee2800017fa03f9007e2d96515cc Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 1 Mar 2024 15:50:06 +0200 Subject: [PATCH 49/52] fixes --- hermes/bin/src/event/queue.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 60500531d..1b7ee7ae2 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -111,9 +111,8 @@ fn event_dispatch( /// - `Error::ModuleNotFound` /// - `Error::AppNotFound` /// - `wasm::module::BadWASMModuleError` -#[allow(clippy::unnecessary_wraps)] fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> anyhow::Result<()> { - // Find target apps + // Gather target apps let target_apps = match event.target_app() { TargetApp::_All => indexed_apps.iter().collect(), TargetApp::List(target_apps) => { @@ -127,8 +126,8 @@ fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> res }, }; - // Find target modules - let target_module = match event.target_module() { + // Gather target modules + let target_modules = match event.target_module() { TargetModule::All => { let mut res = Vec::new(); for (app_name, app) in target_apps { @@ -154,7 +153,7 @@ fn targeted_event_execution(indexed_apps: &IndexedApps, event: &HermesEvent) -> }; // Event dispatch - for (app_name, module_id, module) in target_module { + for (app_name, module_id, module) in target_modules { event_dispatch(app_name.clone(), module_id.clone(), event.payload(), module)?; } Ok(()) From df52c46cab199301657b7527b19368e9547f47fc Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Fri, 1 Mar 2024 16:59:19 +0200 Subject: [PATCH 50/52] wip --- hermes/bin/src/event/queue.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 1b7ee7ae2..66b4e0690 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -57,6 +57,9 @@ pub(crate) struct HermesEventQueue { impl HermesEventQueue { /// Creates a new instance of the `HermesEventQueue`. /// Runs an event loop thread. + /// + /// # Errors: + /// - `Error::AlreadyInitialized` pub(crate) fn init(indexed_apps: Arc) -> anyhow::Result { let (sender, receiver) = std::sync::mpsc::channel(); From 374da22caf6cba3975cefcd34ec9cb9327c88459 Mon Sep 17 00:00:00 2001 From: Steven Johnson Date: Thu, 7 Mar 2024 02:10:13 -0700 Subject: [PATCH 51/52] fix: hermes reactor changes requested (#173) * fix(hermes): changes requested for event queue * fix(hermes): Reintroduce mechanism to advise runtime extensions of a new context * fix(hermes): fix code format --- hermes/bin/src/event/queue.rs | 91 +++++++++++-------- hermes/bin/src/reactor.rs | 16 +--- .../runtime_extensions/hermes/binary/mod.rs | 12 +-- .../runtime_extensions/hermes/cardano/mod.rs | 12 +-- .../src/runtime_extensions/hermes/cbor/mod.rs | 12 +-- .../src/runtime_extensions/hermes/cron/mod.rs | 6 ++ .../runtime_extensions/hermes/crypto/mod.rs | 12 +-- .../src/runtime_extensions/hermes/hash/mod.rs | 13 +-- .../src/runtime_extensions/hermes/init/mod.rs | 8 +- .../src/runtime_extensions/hermes/json/mod.rs | 12 +-- .../runtime_extensions/hermes/kv_store/mod.rs | 12 +-- .../hermes/localtime/mod.rs | 12 +-- .../runtime_extensions/hermes/logging/mod.rs | 12 +-- .../bin/src/runtime_extensions/hermes/mod.rs | 17 ++++ hermes/bin/src/runtime_extensions/mod.rs | 6 ++ .../src/runtime_extensions/wasi/cli/mod.rs | 12 +-- .../src/runtime_extensions/wasi/clocks/mod.rs | 6 ++ .../wasi/clocks/monotonic/mod.rs | 12 +-- .../wasi/clocks/wall/mod.rs | 12 +-- .../runtime_extensions/wasi/filesystem/mod.rs | 12 +-- .../src/runtime_extensions/wasi/http/mod.rs | 12 +-- .../runtime_extensions/wasi/io/error/mod.rs | 12 +-- .../bin/src/runtime_extensions/wasi/io/mod.rs | 6 ++ .../runtime_extensions/wasi/io/streams/mod.rs | 12 +-- hermes/bin/src/runtime_extensions/wasi/mod.rs | 10 ++ .../wasi/random/insecure/mod.rs | 12 +-- .../wasi/random/insecure_seed/mod.rs | 12 +-- .../src/runtime_extensions/wasi/random/mod.rs | 7 ++ .../wasi/random/secure/mod.rs | 12 +-- 29 files changed, 164 insertions(+), 238 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 66b4e0690..56f567f65 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -14,6 +14,7 @@ use super::{HermesEvent, HermesEventPayload, TargetApp, TargetModule}; use crate::{ app::{HermesAppName, IndexedApps}, runtime_context::HermesRuntimeContext, + runtime_extensions::new_context, wasm::module::{Module, ModuleId}, }; @@ -42,52 +43,57 @@ pub(crate) enum Error { /// Failed when event queue not been initialized. #[error("Event queue not been initialized. Call `HermesEventQueue::init` first.")] NotInitialized, -} -/// Hermes event queue execution loop thread handler -pub(crate) type HermesEventLoopHandler = JoinHandle>; + /// Event loop has crashed unexpectedly. + #[error("Event loop has crashed unexpectedly.")] + EventLoopPanics, +} /// Hermes event queue. /// It is a singleton struct. -pub(crate) struct HermesEventQueue { +struct HermesEventQueue { /// Hermes event queue sender sender: Sender, } -impl HermesEventQueue { - /// Creates a new instance of the `HermesEventQueue`. - /// Runs an event loop thread. - /// - /// # Errors: - /// - `Error::AlreadyInitialized` - pub(crate) fn init(indexed_apps: Arc) -> anyhow::Result { - let (sender, receiver) = std::sync::mpsc::channel(); - - EVENT_QUEUE_INSTANCE - .set(Self { sender }) - .map_err(|_| Error::AlreadyInitialized)?; - - let event_loop = thread::spawn(move || event_execution_loop(&indexed_apps, receiver)); - - Ok(event_loop) - } +/// Hermes event queue execution loop thread handler +pub(crate) struct HermesEventLoopHandler { + /// Hermes event queue execution loop thread handler + handle: Option>>, +} - /// Get the singleton instance of the `HermesEventQueue`. - /// - /// # Errors: - /// - `Error::NotInitialized` - pub(crate) fn get_instance() -> anyhow::Result<&'static HermesEventQueue> { - Ok(EVENT_QUEUE_INSTANCE.get().ok_or(Error::NotInitialized)?) - } +/// Creates a new instance of the `HermesEventQueue`. +/// Runs an event loop thread. +/// +/// # Errors: +/// - `Error::AlreadyInitialized` +pub(crate) fn init(indexed_apps: Arc) -> anyhow::Result { + let (sender, receiver) = std::sync::mpsc::channel(); + + EVENT_QUEUE_INSTANCE + .set(HermesEventQueue { sender }) + .map_err(|_| Error::AlreadyInitialized)?; + + Ok(HermesEventLoopHandler { + handle: Some(thread::spawn(move || { + event_execution_loop(&indexed_apps, receiver) + })), + }) +} - /// Add event into the event queue - /// - /// # Errors: - /// - `Error::CannotAddEvent` - pub(crate) fn add_into_queue(&self, event: HermesEvent) -> anyhow::Result<()> { - self.sender.send(event).map_err(|_| Error::CannotAddEvent)?; - Ok(()) - } +/// Add event into the event queue +/// +/// # Errors: +/// - `Error::CannotAddEvent` +/// - `Error::AlreadyInitialized` +pub(crate) fn send(event: HermesEvent) -> anyhow::Result<()> { + let queue = EVENT_QUEUE_INSTANCE.get().ok_or(Error::NotInitialized)?; + + queue + .sender + .send(event) + .map_err(|_| Error::CannotAddEvent)?; + Ok(()) } /// Execute a hermes event on the provided module and all necessary info. @@ -104,6 +110,9 @@ fn event_dispatch( module.exec_counter(), ); + // Advise Runtime Extensions of a new context + new_context(&runtime_context); + module.execute_event(event, runtime_context)?; Ok(()) } @@ -176,3 +185,13 @@ fn event_execution_loop( } Ok(()) } + +impl HermesEventLoopHandler { + /// Join the event loop thread + pub(crate) fn join(&mut self) -> anyhow::Result<()> { + match self.handle.take() { + Some(handle) => handle.join().map_err(|_| Error::EventLoopPanics)?, + None => Ok(()), + } + } +} diff --git a/hermes/bin/src/reactor.rs b/hermes/bin/src/reactor.rs index ade06f784..d29d82958 100644 --- a/hermes/bin/src/reactor.rs +++ b/hermes/bin/src/reactor.rs @@ -4,22 +4,17 @@ use std::sync::Arc; use crate::{ app::{HermesApp, IndexedApps}, - event::queue::{HermesEventLoopHandler, HermesEventQueue}, + event, runtime_extensions::hermes::init, }; -/// Hermes event queue execution loop handler panics error. -#[derive(thiserror::Error, Debug)] -#[error("Hermes event queue execution loop handler panics!")] -struct EventLoopPanics; - /// Hermes Reactor struct #[allow(dead_code)] pub(crate) struct HermesReactor { /// Hermes apps indexed_apps: Arc, /// Hermes event queue loop thread handler. - event_loop: HermesEventLoopHandler, + event_loop: event::queue::HermesEventLoopHandler, } impl HermesReactor { @@ -36,7 +31,7 @@ impl HermesReactor { .collect(), ); - let event_loop = HermesEventQueue::init(indexed_apps.clone())?; + let event_loop = event::queue::init(indexed_apps.clone())?; // Emit Init event for loaded apps init::emit_init_event(target_apps)?; @@ -51,9 +46,8 @@ impl HermesReactor { /// # Note: /// This is a blocking call. #[allow(dead_code)] - pub(crate) fn wait(self) -> anyhow::Result<()> { - self.event_loop.join().map_err(|_| EventLoopPanics)??; - Ok(()) + pub(crate) fn wait(&mut self) -> anyhow::Result<()> { + self.event_loop.join() } } diff --git a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs index ebfd5f7bf..28194d539 100644 --- a/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/binary/mod.rs @@ -2,13 +2,5 @@ mod host; -/// State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs index 99d811856..d2c606601 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cardano/mod.rs @@ -3,13 +3,5 @@ mod event; mod host; -/// State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs index 573c4da22..d177704ba 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cbor/mod.rs @@ -2,13 +2,5 @@ mod host; -/// State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs index 74dc67a1b..cafc93a5b 100644 --- a/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/cron/mod.rs @@ -15,6 +15,12 @@ use crate::runtime_extensions::bindings::{ mod event; mod host; +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} + +// `State` is obsolete, needs to be removed. +// If needed, it can be replaced with `new_context` + /// State pub(crate) struct State { /// The crontabs hash map. diff --git a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs index 332607d2d..097b8ca9a 100644 --- a/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/crypto/mod.rs @@ -2,13 +2,5 @@ mod host; -/// State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs index 373bbf0d6..b331054c6 100644 --- a/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/hash/mod.rs @@ -3,13 +3,8 @@ mod blake2b; mod host; -/// State -pub(crate) struct State {} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +// `State` is obsolete, needs to be removed. +// If needed, it can be replaced with `new_context` diff --git a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs index 79e7f69a6..8acd8b63e 100644 --- a/hermes/bin/src/runtime_extensions/hermes/init/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/init/mod.rs @@ -2,11 +2,15 @@ use crate::{ app::HermesAppName, - event::{queue::HermesEventQueue, HermesEvent, TargetApp, TargetModule}, + event as hermes_event, + event::{HermesEvent, TargetApp, TargetModule}, }; mod event; +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} + /// Emit Init event for a provided Hermes app target pub(crate) fn emit_init_event(target_apps: Vec) -> anyhow::Result<()> { if !target_apps.is_empty() { @@ -15,7 +19,7 @@ pub(crate) fn emit_init_event(target_apps: Vec) -> anyhow::Result TargetApp::List(target_apps), TargetModule::All, ); - HermesEventQueue::get_instance()?.add_into_queue(init_event)?; + hermes_event::queue::send(init_event)?; } Ok(()) } diff --git a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs index 0bb4d09a3..871b8da17 100644 --- a/hermes/bin/src/runtime_extensions/hermes/json/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/json/mod.rs @@ -2,13 +2,5 @@ mod host; -/// State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs index d3b0516d8..b9cab84e3 100644 --- a/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/kv_store/mod.rs @@ -3,13 +3,5 @@ mod event; mod host; -/// State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs index f10a908f5..de0d51680 100644 --- a/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/localtime/mod.rs @@ -2,13 +2,5 @@ mod host; -/// State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs index d6588dd09..4c29c60f6 100644 --- a/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/logging/mod.rs @@ -2,13 +2,5 @@ mod host; -/// State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - State {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/hermes/mod.rs b/hermes/bin/src/runtime_extensions/hermes/mod.rs index fdd2e7390..7d4abab8e 100644 --- a/hermes/bin/src/runtime_extensions/hermes/mod.rs +++ b/hermes/bin/src/runtime_extensions/hermes/mod.rs @@ -1,5 +1,7 @@ //! Hermes runtime extensions implementations - HERMES custom extensions +use crate::runtime_context::HermesRuntimeContext; + pub(crate) mod binary; pub(crate) mod cardano; pub(crate) mod cbor; @@ -11,3 +13,18 @@ pub(crate) mod json; pub(crate) mod kv_store; pub(crate) mod localtime; pub(crate) mod logging; + +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(ctx: &HermesRuntimeContext) { + binary::new_context(ctx); + cardano::new_context(ctx); + cbor::new_context(ctx); + cron::new_context(ctx); + crypto::new_context(ctx); + hash::new_context(ctx); + init::new_context(ctx); + json::new_context(ctx); + kv_store::new_context(ctx); + localtime::new_context(ctx); + logging::new_context(ctx); +} diff --git a/hermes/bin/src/runtime_extensions/mod.rs b/hermes/bin/src/runtime_extensions/mod.rs index 29f39a8d7..3223d5dbe 100644 --- a/hermes/bin/src/runtime_extensions/mod.rs +++ b/hermes/bin/src/runtime_extensions/mod.rs @@ -3,3 +3,9 @@ pub(crate) mod bindings; pub(crate) mod hermes; pub(crate) mod wasi; + +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(ctx: &crate::runtime_context::HermesRuntimeContext) { + hermes::new_context(ctx); + wasi::new_context(ctx); +} diff --git a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs index dda9c88d3..18eb82a5b 100644 --- a/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/cli/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs index 0f7162b9e..4b19fb354 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/mod.rs @@ -2,3 +2,9 @@ mod monotonic; mod wall; + +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(ctx: &crate::runtime_context::HermesRuntimeContext) { + monotonic::new_context(ctx); + wall::new_context(ctx); +} diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs index c43e249b2..dbeea0c1f 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/monotonic/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs index 6a2bb7276..672311a55 100644 --- a/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/clocks/wall/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs index f3cb8236b..4ef0724a4 100644 --- a/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/filesystem/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs index 556ee4c84..bad8907bf 100644 --- a/hermes/bin/src/runtime_extensions/wasi/http/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/http/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs index 0d34db771..93c66b489 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/error/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/io/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs index 0fac8bc81..4148903ef 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/mod.rs @@ -2,3 +2,9 @@ pub(crate) mod error; pub(crate) mod streams; + +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(ctx: &crate::runtime_context::HermesRuntimeContext) { + error::new_context(ctx); + streams::new_context(ctx); +} diff --git a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs index f4d81761e..22814385c 100644 --- a/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/io/streams/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/mod.rs b/hermes/bin/src/runtime_extensions/wasi/mod.rs index 3498b67d3..1172b28ba 100644 --- a/hermes/bin/src/runtime_extensions/wasi/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/mod.rs @@ -6,3 +6,13 @@ pub(crate) mod filesystem; pub(crate) mod http; pub(crate) mod io; pub(crate) mod random; + +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(ctx: &crate::runtime_context::HermesRuntimeContext) { + cli::new_context(ctx); + clocks::new_context(ctx); + filesystem::new_context(ctx); + http::new_context(ctx); + io::new_context(ctx); + random::new_context(ctx); +} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs index 32a50ceee..9a3ffb827 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs index 6c9501db1..25bfaec5f 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/insecure_seed/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs index ef3f4770b..1a1fcab9f 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/mod.rs @@ -3,3 +3,10 @@ pub(crate) mod insecure; pub(crate) mod insecure_seed; pub(crate) mod secure; + +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(ctx: &crate::runtime_context::HermesRuntimeContext) { + insecure::new_context(ctx); + insecure_seed::new_context(ctx); + secure::new_context(ctx); +} diff --git a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs index 2144e27c7..49061cc36 100644 --- a/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs +++ b/hermes/bin/src/runtime_extensions/wasi/random/secure/mod.rs @@ -2,13 +2,5 @@ mod host; -/// WASI State -pub(crate) struct State {} - -impl State { - /// - #[allow(dead_code)] - fn new() -> Self { - Self {} - } -} +/// Advise Runtime Extensions of a new context +pub(crate) fn new_context(_ctx: &crate::runtime_context::HermesRuntimeContext) {} From 0a5d0c12a69d515c81b54a6e784b9e9935717d34 Mon Sep 17 00:00:00 2001 From: Mr-Leshiy Date: Sun, 10 Mar 2024 18:21:20 +0200 Subject: [PATCH 52/52] update --- hermes/bin/src/event/queue.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/hermes/bin/src/event/queue.rs b/hermes/bin/src/event/queue.rs index 56f567f65..096cff19d 100644 --- a/hermes/bin/src/event/queue.rs +++ b/hermes/bin/src/event/queue.rs @@ -62,6 +62,16 @@ pub(crate) struct HermesEventLoopHandler { handle: Option>>, } +impl HermesEventLoopHandler { + /// Join the event loop thread + pub(crate) fn join(&mut self) -> anyhow::Result<()> { + match self.handle.take() { + Some(handle) => handle.join().map_err(|_| Error::EventLoopPanics)?, + None => Ok(()), + } + } +} + /// Creates a new instance of the `HermesEventQueue`. /// Runs an event loop thread. /// @@ -85,7 +95,7 @@ pub(crate) fn init(indexed_apps: Arc) -> anyhow::Result anyhow::Result<()> { let queue = EVENT_QUEUE_INSTANCE.get().ok_or(Error::NotInitialized)?; @@ -185,13 +195,3 @@ fn event_execution_loop( } Ok(()) } - -impl HermesEventLoopHandler { - /// Join the event loop thread - pub(crate) fn join(&mut self) -> anyhow::Result<()> { - match self.handle.take() { - Some(handle) => handle.join().map_err(|_| Error::EventLoopPanics)?, - None => Ok(()), - } - } -}