From 8f80233bb6db98e2df976e1ea759befc3234301a Mon Sep 17 00:00:00 2001 From: Oleksandr Deundiak Date: Sun, 12 Jan 2025 19:15:31 +0100 Subject: [PATCH] feat(rust): merge `Processor` into `Worker` --- .../rust/file_transfer/examples/receiver.rs | 1 - examples/rust/get_started/examples/bob.rs | 1 - examples/rust/get_started/src/echoer.rs | 1 - examples/rust/get_started/src/hop.rs | 1 - examples/rust/get_started/src/logger.rs | 1 - examples/rust/get_started/src/relay.rs | 1 - .../src/tcp_interceptor/workers/listener.rs | 14 +- .../src/tcp_interceptor/workers/processor.rs | 12 +- examples/rust/no_std/src/echoer.rs | 1 - examples/rust/no_std/src/hop.rs | 1 - implementations/rust/ockam/ockam/src/lib.rs | 4 +- implementations/rust/ockam/ockam/src/node.rs | 40 +-- .../ockam/ockam/src/relay_service/relay.rs | 9 +- .../ockam/src/relay_service/relay_service.rs | 7 +- .../rust/ockam/ockam/src/remote/worker.rs | 6 +- .../credential_issuer_worker.rs | 5 +- .../direct/direct_authenticator_worker.rs | 5 +- .../enrollment_tokens/acceptor_worker.rs | 5 +- .../enrollment_tokens/issuer_worker.rs | 5 +- .../rust/ockam/ockam_api/src/echoer.rs | 1 - .../rust/ockam/ockam_api/src/hop.rs | 1 - .../src/influxdb/lease_issuer/node_service.rs | 4 +- .../src/influxdb/lease_issuer/processor.rs | 14 +- .../src/influxdb/lease_issuer/worker.rs | 7 +- .../src/kafka/tests/interceptor_test.rs | 7 +- .../ockam/ockam_api/src/nodes/service/http.rs | 14 +- .../ockam_api/src/nodes/service/worker.rs | 7 +- .../rust/ockam/ockam_api/src/okta/mod.rs | 5 +- .../ockam/ockam_api/src/session/collector.rs | 1 - .../rust/ockam/ockam_api/src/uppercase.rs | 1 - .../ockam/ockam_api/tests/common/session.rs | 5 +- .../rust/ockam/ockam_core/src/lib.rs | 4 - .../rust/ockam/ockam_core/src/message.rs | 3 +- .../rust/ockam/ockam_core/src/processor.rs | 40 --- .../rust/ockam/ockam_core/src/worker.rs | 40 --- .../src/secure_channel/encryptor_worker.rs | 17 +- .../handshake/handshake_worker.rs | 11 +- .../src/secure_channel/listener.rs | 7 +- .../ockam/ockam_identity/tests/channel.rs | 7 +- .../ockam/ockam_identity/tests/credentials.rs | 7 +- .../tests/credentials_refresh.rs | 7 +- .../src/context/context_lifecycle.rs | 3 +- .../src/context/worker_lifecycle.rs | 93 +------ .../rust/ockam/ockam_node/src/debugger.rs | 6 - .../rust/ockam/ockam_node/src/delayed.rs | 7 +- .../rust/ockam/ockam_node/src/lib.rs | 6 +- .../rust/ockam/ockam_node/src/node.rs | 3 +- .../ockam/ockam_node/src/processor_builder.rs | 256 ------------------ .../rust/ockam/ockam_node/src/relay/mod.rs | 12 - .../ockam_node/src/relay/processor_relay.rs | 151 ----------- .../rust/ockam/ockam_node/src/router/mod.rs | 1 - .../ockam/ockam_node/src/router/processor.rs | 58 ---- .../ockam/ockam_node/src/router/record.rs | 4 +- .../ockam/ockam_node/src/router/router.rs | 2 +- .../ockam/ockam_node/src/router/worker.rs | 5 +- .../rust/ockam/ockam_node/src/worker.rs | 89 ++++++ .../ockam/ockam_node/src/worker_builder.rs | 52 +--- .../src/{relay => }/worker_relay.rs | 116 +++----- .../ockam/ockam_node/src/workers/echoer.rs | 5 +- .../rust/ockam/ockam_node/tests/metadata.rs | 26 +- .../rust/ockam/ockam_node/tests/tests.rs | 120 +++----- .../ockam_transport_ble/src/router/mod.rs | 5 +- .../src/workers/listener.rs | 12 +- .../src/workers/receiver.rs | 8 +- .../ockam_transport_ble/src/workers/sender.rs | 11 +- .../src/portal/inlet_listener.rs | 16 +- .../src/portal/interceptor.rs | 9 +- .../src/portal/outlet_listener.rs | 11 +- .../src/portal/portal_receiver.rs | 12 +- .../src/portal/portal_worker.rs | 11 +- .../src/privileged_portal/ebpf_support.rs | 2 +- .../privileged_portal/privileged_portals.rs | 6 +- .../workers/internal_processor.rs | 11 +- .../workers/raw_socket_processor.rs | 10 +- .../workers/remote_worker.rs | 7 +- .../src/workers/listener.rs | 14 +- .../src/workers/receiver.rs | 12 +- .../ockam_transport_tcp/src/workers/sender.rs | 9 +- .../src/puncture/negotiation/listener.rs | 7 +- .../src/puncture/puncture/receiver.rs | 9 +- .../src/puncture/puncture/sender.rs | 7 +- .../puncture/rendezvous_service/rendezvous.rs | 5 +- .../ockam_transport_udp/src/transport/bind.rs | 4 +- .../src/workers/receiver.rs | 10 +- .../ockam_transport_udp/src/workers/sender.rs | 7 +- .../ockam/ockam_transport_udp/tests/tests.rs | 5 +- .../src/router/uds_router.rs | 5 +- .../src/workers/listener.rs | 12 +- .../src/workers/receiver.rs | 10 +- .../ockam_transport_uds/src/workers/sender.rs | 11 +- .../ockam/ockam_transport_websocket/README.md | 3 +- .../ockam_transport_websocket/src/lib.rs | 5 +- .../src/router/mod.rs | 5 +- .../src/workers/listener.rs | 12 +- .../src/workers/receiver.rs | 10 +- .../src/workers/sender.rs | 12 +- tools/stress-test/src/portal_simulator.rs | 13 +- 97 files changed, 438 insertions(+), 1225 deletions(-) delete mode 100644 implementations/rust/ockam/ockam_core/src/processor.rs delete mode 100644 implementations/rust/ockam/ockam_core/src/worker.rs delete mode 100644 implementations/rust/ockam/ockam_node/src/processor_builder.rs delete mode 100644 implementations/rust/ockam/ockam_node/src/relay/mod.rs delete mode 100644 implementations/rust/ockam/ockam_node/src/relay/processor_relay.rs delete mode 100644 implementations/rust/ockam/ockam_node/src/router/processor.rs create mode 100644 implementations/rust/ockam/ockam_node/src/worker.rs rename implementations/rust/ockam/ockam_node/src/{relay => }/worker_relay.rs (56%) diff --git a/examples/rust/file_transfer/examples/receiver.rs b/examples/rust/file_transfer/examples/receiver.rs index a0c20aa7ea2..c34737c6a11 100644 --- a/examples/rust/file_transfer/examples/receiver.rs +++ b/examples/rust/file_transfer/examples/receiver.rs @@ -21,7 +21,6 @@ struct FileReception { #[ockam::worker] impl Worker for FileReception { - type Context = Context; type Message = FileData; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/examples/rust/get_started/examples/bob.rs b/examples/rust/get_started/examples/bob.rs index 6be42251b30..b8439bce304 100644 --- a/examples/rust/get_started/examples/bob.rs +++ b/examples/rust/get_started/examples/bob.rs @@ -10,7 +10,6 @@ struct Echoer; // echoes it back on its return route. #[ockam::worker] impl Worker for Echoer { - type Context = Context; type Message = String; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/examples/rust/get_started/src/echoer.rs b/examples/rust/get_started/src/echoer.rs index 6dac38aa74f..6a7b0cc9618 100644 --- a/examples/rust/get_started/src/echoer.rs +++ b/examples/rust/get_started/src/echoer.rs @@ -4,7 +4,6 @@ pub struct Echoer; #[ockam::worker] impl Worker for Echoer { - type Context = Context; type Message = String; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/examples/rust/get_started/src/hop.rs b/examples/rust/get_started/src/hop.rs index 727dee397fc..e0a6415b572 100644 --- a/examples/rust/get_started/src/hop.rs +++ b/examples/rust/get_started/src/hop.rs @@ -4,7 +4,6 @@ pub struct Hop; #[ockam::worker] impl Worker for Hop { - type Context = Context; type Message = Any; /// This handle function takes any incoming message and forwards diff --git a/examples/rust/get_started/src/logger.rs b/examples/rust/get_started/src/logger.rs index 0d47b5f3468..8ce1180bece 100644 --- a/examples/rust/get_started/src/logger.rs +++ b/examples/rust/get_started/src/logger.rs @@ -4,7 +4,6 @@ pub struct Logger; #[ockam::worker] impl Worker for Logger { - type Context = Context; type Message = Any; /// This handle function takes any incoming message and print its content as a UTF-8 string diff --git a/examples/rust/get_started/src/relay.rs b/examples/rust/get_started/src/relay.rs index 75637e96b0c..5052be59e73 100644 --- a/examples/rust/get_started/src/relay.rs +++ b/examples/rust/get_started/src/relay.rs @@ -18,7 +18,6 @@ impl Relay { #[ockam::worker] impl Worker for Relay { - type Context = Context; type Message = Any; /// This handle function takes any incoming message and forwards diff --git a/examples/rust/mitm_node/src/tcp_interceptor/workers/listener.rs b/examples/rust/mitm_node/src/tcp_interceptor/workers/listener.rs index a37dc8827ee..35f869d22c6 100644 --- a/examples/rust/mitm_node/src/tcp_interceptor/workers/listener.rs +++ b/examples/rust/mitm_node/src/tcp_interceptor/workers/listener.rs @@ -1,7 +1,7 @@ use crate::tcp_interceptor::{Role, TcpMitmProcessor, TcpMitmRegistry, TcpMitmTransport}; use ockam_core::{async_trait, compat::net::SocketAddr}; -use ockam_core::{Address, Processor, Result}; -use ockam_node::Context; +use ockam_core::{Address, Result}; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; use tokio::net::{TcpListener, TcpStream}; use tracing::debug; @@ -34,15 +34,15 @@ impl TcpMitmListenProcessor { target_addr, }; - ctx.start_processor(address.clone(), processor)?; + ctx.start_worker(address.clone(), processor)?; Ok((saddr, address)) } } #[async_trait] -impl Processor for TcpMitmListenProcessor { - type Context = Context; +impl Worker for TcpMitmListenProcessor { + type Message = (); async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { self.registry.add_listener(ctx.primary_address()); @@ -50,13 +50,13 @@ impl Processor for TcpMitmListenProcessor { Ok(()) } - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.registry.remove_listener(ctx.primary_address()); Ok(()) } - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { debug!("Waiting for incoming TCP connection..."); let (stream, _peer) = self.inner.accept().await.map_err(TransportError::from)?; diff --git a/examples/rust/mitm_node/src/tcp_interceptor/workers/processor.rs b/examples/rust/mitm_node/src/tcp_interceptor/workers/processor.rs index f1bdfb3a68b..85ab16d49ca 100644 --- a/examples/rust/mitm_node/src/tcp_interceptor/workers/processor.rs +++ b/examples/rust/mitm_node/src/tcp_interceptor/workers/processor.rs @@ -1,9 +1,9 @@ use crate::tcp_interceptor::{Role, TcpMitmRegistry}; use ockam_core::compat::sync::Arc; +use ockam_core::Result; use ockam_core::{async_trait, Address, AllowAll}; -use ockam_core::{Processor, Result}; use ockam_node::compat::asynchronous::Mutex; -use ockam_node::Context; +use ockam_node::{Context, Worker}; use tokio::io::AsyncWriteExt; use tokio::net::tcp::OwnedWriteHalf; use tokio::{io::AsyncReadExt, net::tcp::OwnedReadHalf}; @@ -47,15 +47,15 @@ impl TcpMitmProcessor { let receiver = Self::new(address_of_other_processor, role, read_half, write_half, registry); - ctx.start_processor_with_access_control(address, receiver, AllowAll, AllowAll)?; + ctx.start_worker_with_access_control(address, receiver, AllowAll, AllowAll)?; Ok(()) } } #[async_trait] -impl Processor for TcpMitmProcessor { - type Context = Context; +impl Worker for TcpMitmProcessor { + type Message = (); async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { self.registry @@ -66,7 +66,7 @@ impl Processor for TcpMitmProcessor { Ok(()) } - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.registry.remove_processor(ctx.primary_address()); debug!("Shutdown {}", ctx.primary_address()); diff --git a/examples/rust/no_std/src/echoer.rs b/examples/rust/no_std/src/echoer.rs index f00874b1a4c..ae63bf02e25 100644 --- a/examples/rust/no_std/src/echoer.rs +++ b/examples/rust/no_std/src/echoer.rs @@ -6,7 +6,6 @@ pub struct Echoer; #[ockam::worker] impl Worker for Echoer { - type Context = Context; type Message = String; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/examples/rust/no_std/src/hop.rs b/examples/rust/no_std/src/hop.rs index a06755ff909..db8bf27a21d 100644 --- a/examples/rust/no_std/src/hop.rs +++ b/examples/rust/no_std/src/hop.rs @@ -6,7 +6,6 @@ pub struct Hop; #[ockam::worker] impl Worker for Hop { - type Context = Context; type Message = Any; /// This handle function takes any incoming message and forwards diff --git a/implementations/rust/ockam/ockam/src/lib.rs b/implementations/rust/ockam/ockam/src/lib.rs index e21d35edde6..3657712cf93 100644 --- a/implementations/rust/ockam/ockam/src/lib.rs +++ b/implementations/rust/ockam/ockam/src/lib.rs @@ -67,7 +67,7 @@ pub use ockam_core::processor; pub use ockam_core::worker; pub use ockam_core::{ allow, deny, errcode, route, Address, Any, Encoded, Error, LocalMessage, Mailbox, Mailboxes, - Message, Processor, ProtocolId, Result, Route, Routed, TransportMessage, TryClone, Worker, + Message, ProtocolId, Result, Route, Routed, TransportMessage, TryClone, }; pub use ockam_identity as identity; // --- @@ -78,7 +78,7 @@ pub use ockam_macros::{node, test}; pub use ockam_node::database::*; pub use ockam_node::{ debugger, Context, DelayedEvent, Executor, MessageReceiveOptions, MessageSendReceiveOptions, - NodeBuilder, WorkerBuilder, + NodeBuilder, Worker, WorkerBuilder, }; #[cfg(feature = "ockam_transport_tcp")] /// TCP transport diff --git a/implementations/rust/ockam/ockam/src/node.rs b/implementations/rust/ockam/ockam/src/node.rs index fc3a637e46b..c44151a0751 100644 --- a/implementations/rust/ockam/ockam/src/node.rs +++ b/implementations/rust/ockam/ockam/src/node.rs @@ -2,14 +2,13 @@ use ockam_core::compat::string::String; use ockam_core::compat::sync::Arc; use ockam_core::flow_control::FlowControls; use ockam_core::{ - Address, IncomingAccessControl, Message, OutgoingAccessControl, Processor, Result, Route, - Routed, TryClone, Worker, + Address, IncomingAccessControl, Message, OutgoingAccessControl, Result, Route, Routed, TryClone, }; use ockam_identity::{ CredentialRepository, IdentitiesAttributes, IdentitiesVerification, IdentityAttributesRepository, PurposeKeys, Vault, }; -use ockam_node::{Context, HasContext, MessageReceiveOptions, MessageSendReceiveOptions}; +use ockam_node::{Context, HasContext, MessageReceiveOptions, MessageSendReceiveOptions, Worker}; use ockam_vault::storage::SecretsRepository; use ockam_vault::SigningSecretKeyHandle; @@ -161,51 +160,22 @@ impl Node { } /// Start a new worker instance at the given address. Default Access Control is AllowAll - pub fn start_worker(&self, address: impl Into
, worker: W) -> Result<()> - where - W: Worker, - { + pub fn start_worker(&self, address: impl Into
, worker: W) -> Result<()> { self.context.start_worker(address, worker) } /// Start a new worker instance at the given address with given Access Controls - pub fn start_worker_with_access_control( + pub fn start_worker_with_access_control( &self, address: impl Into
, worker: W, incoming: impl IncomingAccessControl, outgoing: impl OutgoingAccessControl, - ) -> Result<()> - where - W: Worker, - { + ) -> Result<()> { self.context .start_worker_with_access_control(address, worker, incoming, outgoing) } - /// Start a new processor instance at the given address. Default Access Control is DenyAll - pub fn start_processor

(&self, address: impl Into

, processor: P) -> Result<()> - where - P: Processor, - { - self.context.start_processor(address, processor) - } - - /// Start a new processor instance at the given address with given Access Controls - pub fn start_processor_with_access_control

( - &self, - address: impl Into

, - processor: P, - incoming: impl IncomingAccessControl, - outgoing: impl OutgoingAccessControl, - ) -> Result<()> - where - P: Processor, - { - self.context - .start_processor_with_access_control(address, processor, incoming, outgoing) - } - /// Signal to the local runtime to shut down pub async fn shutdown(&mut self) -> Result<()> { self.context.shutdown_node().await diff --git a/implementations/rust/ockam/ockam/src/relay_service/relay.rs b/implementations/rust/ockam/ockam/src/relay_service/relay.rs index a8138841865..a208e038e18 100644 --- a/implementations/rust/ockam/ockam/src/relay_service/relay.rs +++ b/implementations/rust/ockam/ockam/src/relay_service/relay.rs @@ -3,9 +3,9 @@ use ockam_core::compat::sync::Arc; use ockam_core::compat::{boxed::Box, vec::Vec}; use ockam_core::{ route, Address, AllowAll, AllowOnwardAddress, Any, IncomingAccessControl, LocalMessage, - OutgoingAccessControl, Result, Route, Routed, Worker, + OutgoingAccessControl, Result, Route, Routed, }; -use ockam_node::WorkerBuilder; +use ockam_node::{Worker, WorkerBuilder}; use tracing::info; pub(super) struct Relay { @@ -52,10 +52,9 @@ impl Relay { #[crate::worker] impl Worker for Relay { - type Context = Context; type Message = Any; - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { let payload = self .payload .take() @@ -77,7 +76,7 @@ impl Worker for Relay { async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, msg: Routed, ) -> Result<()> { let mut local_message = msg.into_local_message(); diff --git a/implementations/rust/ockam/ockam/src/relay_service/relay_service.rs b/implementations/rust/ockam/ockam/src/relay_service/relay_service.rs index a9d5c0c1640..422c1952f10 100644 --- a/implementations/rust/ockam/ockam/src/relay_service/relay_service.rs +++ b/implementations/rust/ockam/ockam/src/relay_service/relay_service.rs @@ -5,9 +5,9 @@ use alloc::string::String; use ockam_core::compat::boxed::Box; use ockam_core::compat::sync::Arc; use ockam_core::{ - Address, DenyAll, Encodable, Mailbox, Mailboxes, Result, Routed, SecureChannelLocalInfo, Worker, + Address, DenyAll, Encodable, Mailbox, Mailboxes, Result, Routed, SecureChannelLocalInfo, }; -use ockam_node::WorkerBuilder; +use ockam_node::{Worker, WorkerBuilder}; /// Alias worker to register remote workers under local names. /// @@ -62,12 +62,11 @@ impl RelayService { #[crate::worker] impl Worker for RelayService { - type Context = Context; type Message = String; async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, message: Routed, ) -> Result<()> { let secure_channel_local_info = diff --git a/implementations/rust/ockam/ockam/src/remote/worker.rs b/implementations/rust/ockam/ockam/src/remote/worker.rs index 4f2a294d87d..ce65afeb092 100644 --- a/implementations/rust/ockam/ockam/src/remote/worker.rs +++ b/implementations/rust/ockam/ockam/src/remote/worker.rs @@ -4,15 +4,15 @@ use ockam_core::compat::{ boxed::Box, string::{String, ToString}, }; -use ockam_core::{Any, Decodable, Result, Routed, Worker}; +use ockam_core::{Any, Decodable, Result, Routed}; +use ockam_node::Worker; use tracing::{debug, info}; #[crate::worker] impl Worker for RemoteRelay { - type Context = Context; type Message = Any; - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { debug!(registration_route = %self.registration_route, "RemoteRelay initializing..."); ctx.send_from_address( diff --git a/implementations/rust/ockam/ockam_api/src/authenticator/credential_issuer/credential_issuer_worker.rs b/implementations/rust/ockam/ockam_api/src/authenticator/credential_issuer/credential_issuer_worker.rs index 0bfaebae5af..e26ae3e11a3 100644 --- a/implementations/rust/ockam/ockam_api/src/authenticator/credential_issuer/credential_issuer_worker.rs +++ b/implementations/rust/ockam/ockam_api/src/authenticator/credential_issuer/credential_issuer_worker.rs @@ -10,8 +10,8 @@ use ockam_core::api::{Method, RequestHeader, Response}; use ockam_core::compat::boxed::Box; use ockam_core::compat::sync::Arc; use ockam_core::compat::vec::Vec; -use ockam_core::{Result, Routed, SecureChannelLocalInfo, Worker}; -use ockam_node::Context; +use ockam_core::{Result, Routed, SecureChannelLocalInfo}; +use ockam_node::{Context, Worker}; /// This struct runs as a Worker to issue credentials based on a request/response protocol pub struct CredentialIssuerWorker { @@ -48,7 +48,6 @@ impl CredentialIssuerWorker { #[ockam_core::worker] impl Worker for CredentialIssuerWorker { - type Context = Context; type Message = Vec; async fn handle_message(&mut self, c: &mut Context, m: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_api/src/authenticator/direct/direct_authenticator_worker.rs b/implementations/rust/ockam/ockam_api/src/authenticator/direct/direct_authenticator_worker.rs index 982bbf94ccb..5eec43b88d8 100644 --- a/implementations/rust/ockam/ockam_api/src/authenticator/direct/direct_authenticator_worker.rs +++ b/implementations/rust/ockam/ockam_api/src/authenticator/direct/direct_authenticator_worker.rs @@ -5,8 +5,8 @@ use tracing::trace; use ockam::identity::{Identifier, IdentitiesAttributes}; use ockam_core::api::{Method, RequestHeader, Response}; use ockam_core::compat::sync::Arc; -use ockam_core::{Result, Routed, SecureChannelLocalInfo, Worker}; -use ockam_node::Context; +use ockam_core::{Result, Routed, SecureChannelLocalInfo}; +use ockam_node::{Context, Worker}; use crate::authenticator::direct::types::AddMember; use crate::authenticator::direct::DirectAuthenticator; @@ -37,7 +37,6 @@ impl DirectAuthenticatorWorker { #[ockam_core::worker] impl Worker for DirectAuthenticatorWorker { type Message = Vec; - type Context = Context; async fn handle_message(&mut self, c: &mut Context, m: Routed) -> Result<()> { let secure_channel_info = match SecureChannelLocalInfo::find_info(m.local_message()) { diff --git a/implementations/rust/ockam/ockam_api/src/authenticator/enrollment_tokens/acceptor_worker.rs b/implementations/rust/ockam/ockam_api/src/authenticator/enrollment_tokens/acceptor_worker.rs index 26d570e0d9c..400cbd6e2c4 100644 --- a/implementations/rust/ockam/ockam_api/src/authenticator/enrollment_tokens/acceptor_worker.rs +++ b/implementations/rust/ockam/ockam_api/src/authenticator/enrollment_tokens/acceptor_worker.rs @@ -6,8 +6,8 @@ use minicbor::Decoder; use ockam::identity::Identifier; use ockam_core::api::{Method, RequestHeader, Response}; use ockam_core::compat::sync::Arc; -use ockam_core::{Result, Routed, SecureChannelLocalInfo, Worker}; -use ockam_node::Context; +use ockam_core::{Result, Routed, SecureChannelLocalInfo}; +use ockam_node::{Context, Worker}; use tracing::trace; pub struct EnrollmentTokenAcceptorWorker { @@ -27,7 +27,6 @@ impl EnrollmentTokenAcceptorWorker { #[ockam_core::worker] impl Worker for EnrollmentTokenAcceptorWorker { - type Context = Context; type Message = Vec; async fn handle_message(&mut self, c: &mut Context, m: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_api/src/authenticator/enrollment_tokens/issuer_worker.rs b/implementations/rust/ockam/ockam_api/src/authenticator/enrollment_tokens/issuer_worker.rs index 98d0d54e792..a3dfa9edc4b 100644 --- a/implementations/rust/ockam/ockam_api/src/authenticator/enrollment_tokens/issuer_worker.rs +++ b/implementations/rust/ockam/ockam_api/src/authenticator/enrollment_tokens/issuer_worker.rs @@ -6,8 +6,8 @@ use ockam::identity::{Identifier, IdentitiesAttributes}; use ockam_core::api::{Method, RequestHeader, Response}; use ockam_core::compat::sync::Arc; use ockam_core::compat::time::Duration; -use ockam_core::{Result, Routed, SecureChannelLocalInfo, Worker}; -use ockam_node::Context; +use ockam_core::{Result, Routed, SecureChannelLocalInfo}; +use ockam_node::{Context, Worker}; use crate::authenticator::direct::types::CreateToken; use crate::authenticator::direct::AccountAuthorityInfo; @@ -38,7 +38,6 @@ impl EnrollmentTokenIssuerWorker { #[ockam_core::worker] impl Worker for EnrollmentTokenIssuerWorker { - type Context = Context; type Message = Vec; async fn handle_message(&mut self, c: &mut Context, m: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_api/src/echoer.rs b/implementations/rust/ockam/ockam_api/src/echoer.rs index 1f33e3f1665..746d5e4c8d1 100644 --- a/implementations/rust/ockam/ockam_api/src/echoer.rs +++ b/implementations/rust/ockam/ockam_api/src/echoer.rs @@ -6,7 +6,6 @@ pub struct Echoer; #[ockam::worker] impl Worker for Echoer { - type Context = Context; type Message = Any; #[instrument(skip_all, name = "Echoer::handle_message")] diff --git a/implementations/rust/ockam/ockam_api/src/hop.rs b/implementations/rust/ockam/ockam_api/src/hop.rs index 3c6d7f7d089..e2e04b058f5 100644 --- a/implementations/rust/ockam/ockam_api/src/hop.rs +++ b/implementations/rust/ockam/ockam_api/src/hop.rs @@ -5,7 +5,6 @@ pub struct Hop; #[ockam::worker] impl Worker for Hop { - type Context = Context; type Message = Any; /// This handle function takes any incoming message and forwards diff --git a/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/node_service.rs b/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/node_service.rs index eda56daaf7d..a41fdb81788 100644 --- a/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/node_service.rs +++ b/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/node_service.rs @@ -12,7 +12,7 @@ use ockam_abac::{Action, PolicyExpression, Resource, ResourceType}; use ockam_core::api::{Error, Request, Response}; use ockam_core::{async_trait, Address}; use ockam_multiaddr::MultiAddr; -use ockam_node::{Context, ProcessorBuilder, WorkerBuilder}; +use ockam_node::{Context, WorkerBuilder}; use std::cmp::Reverse; use std::collections::BinaryHeap; use std::time::Duration; @@ -103,7 +103,7 @@ impl InMemoryNode { .start(context)?; self.registry.influxdb_services.insert(address.clone(), ()); - ProcessorBuilder::new(processor) + WorkerBuilder::new(processor) .with_address(format!("{address}-processor")) .start(context)?; diff --git a/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/processor.rs b/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/processor.rs index 00aa36dd962..74c30295ee0 100644 --- a/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/processor.rs +++ b/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/processor.rs @@ -2,8 +2,8 @@ use crate::influxdb::influxdb_api_client::InfluxDBApi; use crate::influxdb::lease_issuer::node_service::InfluxDBTokenLessorState; use crate::influxdb::lease_token::LeaseToken; use crate::ApiError; -use ockam_core::{async_trait, Processor}; -use ockam_node::Context; +use ockam_core::async_trait; +use ockam_node::{Context, Worker}; use std::cmp::Reverse; use std::collections::BinaryHeap; use std::sync::Arc; @@ -72,10 +72,10 @@ impl InfluxDBTokenLessorProcessor { } #[async_trait] -impl Processor for InfluxDBTokenLessorProcessor { - type Context = Context; +impl Worker for InfluxDBTokenLessorProcessor { + type Message = (); - async fn initialize(&mut self, _context: &mut Self::Context) -> ockam_core::Result<()> { + async fn initialize(&mut self, _context: &mut Context) -> ockam_core::Result<()> { let mut max_retries = 5; loop { match self.list_tokens().await { @@ -98,12 +98,12 @@ impl Processor for InfluxDBTokenLessorProcessor { Ok(()) } - async fn shutdown(&mut self, _context: &mut Self::Context) -> ockam_core::Result<()> { + async fn shutdown(&mut self, _context: &mut Context) -> ockam_core::Result<()> { debug!("Shutting down InfluxDBTokenLessorProcessor"); Ok(()) } - async fn process(&mut self, _context: &mut Self::Context) -> ockam_core::Result { + async fn process(&mut self, _context: &mut Context) -> ockam_core::Result { if let Err(err) = self.revoke_outstanding_tokens().await { error!("Failed to revoke outstanding tokens: {err}"); } diff --git a/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/worker.rs b/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/worker.rs index 6c870c88d16..b9c00a6e996 100644 --- a/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/worker.rs +++ b/implementations/rust/ockam/ockam_api/src/influxdb/lease_issuer/worker.rs @@ -9,8 +9,8 @@ use minicbor::Decoder; use ockam::identity::Identifier; use ockam_core::api::Method::{Delete, Get, Post}; use ockam_core::api::{RequestHeader, Response}; -use ockam_core::{async_trait, Address, Routed, SecureChannelLocalInfo, Worker}; -use ockam_node::Context; +use ockam_core::{async_trait, Address, Routed, SecureChannelLocalInfo}; +use ockam_node::{Context, Worker}; use std::cmp::Reverse; use std::collections::BinaryHeap; use std::error::Error; @@ -93,9 +93,8 @@ impl InfluxDBTokenLessorWorker { #[ockam::worker] impl Worker for InfluxDBTokenLessorWorker { type Message = Vec; - type Context = Context; - async fn shutdown(&mut self, _ctx: &mut Self::Context) -> ockam_core::Result<()> { + async fn shutdown(&mut self, _ctx: &mut Context) -> ockam_core::Result<()> { debug!("Shutting down InfluxDBTokenLessorWorker"); Ok(()) } diff --git a/implementations/rust/ockam/ockam_api/src/kafka/tests/interceptor_test.rs b/implementations/rust/ockam/ockam_api/src/kafka/tests/interceptor_test.rs index 2862b9a9a8a..1ea170ed1e6 100644 --- a/implementations/rust/ockam/ockam_api/src/kafka/tests/interceptor_test.rs +++ b/implementations/rust/ockam/ockam_api/src/kafka/tests/interceptor_test.rs @@ -18,10 +18,10 @@ use ockam_abac::{ ResourceTypePolicySqlxDatabase, }; use ockam_core::compat::sync::{Arc, Mutex}; -use ockam_core::{route, Address, AllowAll, NeutralMessage, Routed, Worker}; +use ockam_core::{route, Address, AllowAll, NeutralMessage, Routed}; use ockam_multiaddr::MultiAddr; use ockam_node::database::SqlxDatabase; -use ockam_node::Context; +use ockam_node::{Context, Worker}; use ockam_transport_tcp::{read_portal_payload_length, PortalInterceptorWorker, PortalMessage}; use crate::kafka::inlet_controller::KafkaInletController; @@ -45,11 +45,10 @@ struct TcpPayloadReceiver { #[ockam_core::worker] impl Worker for TcpPayloadReceiver { type Message = NeutralMessage; - type Context = Context; async fn handle_message( &mut self, - _context: &mut Self::Context, + _context: &mut Context, message: Routed, ) -> ockam_core::Result<()> { let message = PortalMessage::decode(message.payload())?; diff --git a/implementations/rust/ockam/ockam_api/src/nodes/service/http.rs b/implementations/rust/ockam/ockam_api/src/nodes/service/http.rs index 3b98e00ba6a..d3fd5571ce5 100644 --- a/implementations/rust/ockam/ockam_api/src/nodes/service/http.rs +++ b/implementations/rust/ockam/ockam_api/src/nodes/service/http.rs @@ -13,8 +13,8 @@ use hyper_util::rt::TokioIo; use crate::nodes::models::transport::Port; use crate::nodes::NodeManager; use crate::{ApiError, HttpError, Result}; -use ockam_core::{async_trait, Address, Processor}; -use ockam_node::{Context, ProcessorBuilder}; +use ockam_core::{async_trait, Address}; +use ockam_node::{Context, Worker, WorkerBuilder}; use serde::Serialize; use tokio::net::TcpListener; @@ -46,7 +46,7 @@ impl HttpServer { node_manager: Arc::downgrade(&node_manager), tcp_listener: Arc::new(listener), }; - ProcessorBuilder::new(processor) + WorkerBuilder::new(processor) .with_address(Address::random_tagged("node_http_server")) .start(context)?; info!("HTTP server listening on: {addr:?}"); @@ -108,15 +108,15 @@ impl HttpServerProcessor { } #[async_trait] -impl Processor for HttpServerProcessor { - type Context = Context; +impl Worker for HttpServerProcessor { + type Message = (); - async fn shutdown(&mut self, _context: &mut Self::Context) -> ockam_core::Result<()> { + async fn shutdown(&mut self, _context: &mut Context) -> ockam_core::Result<()> { debug!("Shutting down HttpServerProcessor"); Ok(()) } - async fn process(&mut self, _context: &mut Self::Context) -> ockam_core::Result { + async fn process(&mut self, _context: &mut Context) -> ockam_core::Result { if let Ok((stream, _)) = self.tcp_listener.accept().await { let io = TokioIo::new(stream); let service = service_fn(|req| { diff --git a/implementations/rust/ockam/ockam_api/src/nodes/service/worker.rs b/implementations/rust/ockam/ockam_api/src/nodes/service/worker.rs index 9570daac5d7..aa92b9fae2c 100644 --- a/implementations/rust/ockam/ockam_api/src/nodes/service/worker.rs +++ b/implementations/rust/ockam/ockam_api/src/nodes/service/worker.rs @@ -5,8 +5,8 @@ use crate::nodes::{InMemoryNode, NODEMANAGER_ADDR}; use crate::DefaultAddress; use minicbor::Decoder; use ockam_core::api::{RequestHeader, Response}; -use ockam_core::{Address, Result, Routed, Worker}; -use ockam_node::Context; +use ockam_core::{Address, Result, Routed}; +use ockam_node::{Context, Worker}; use std::error::Error; use std::sync::Arc; @@ -241,9 +241,8 @@ impl NodeManagerWorker { #[ockam::worker] impl Worker for NodeManagerWorker { type Message = Vec; - type Context = Context; - async fn shutdown(&mut self, _ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, _ctx: &mut Context) -> Result<()> { debug!(target: TARGET, "Shutting down NodeManagerWorker"); Ok(()) } diff --git a/implementations/rust/ockam/ockam_api/src/okta/mod.rs b/implementations/rust/ockam/ockam_api/src/okta/mod.rs index 24a6ae53663..93e5413b8d8 100644 --- a/implementations/rust/ockam/ockam_api/src/okta/mod.rs +++ b/implementations/rust/ockam/ockam_api/src/okta/mod.rs @@ -5,8 +5,8 @@ use minicbor::Decoder; use ockam::identity::utils::now; use ockam::identity::Identifier; use ockam_core::api::{Method, RequestHeader, Response}; -use ockam_core::{self, Result, Routed, SecureChannelLocalInfo, Worker}; -use ockam_node::Context; +use ockam_core::{self, Result, Routed, SecureChannelLocalInfo}; +use ockam_node::{Context, Worker}; use reqwest::StatusCode; use std::collections::HashMap; use std::sync::Arc; @@ -21,7 +21,6 @@ pub struct Server { #[ockam_core::worker] impl Worker for Server { - type Context = Context; type Message = Vec; async fn handle_message(&mut self, c: &mut Context, m: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_api/src/session/collector.rs b/implementations/rust/ockam/ockam_api/src/session/collector.rs index 0004ad1a003..aa0c4fe8031 100644 --- a/implementations/rust/ockam/ockam_api/src/session/collector.rs +++ b/implementations/rust/ockam/ockam_api/src/session/collector.rs @@ -17,7 +17,6 @@ impl Collector { #[ockam::worker] impl Worker for Collector { type Message = Ping; - type Context = Context; async fn handle_message( &mut self, diff --git a/implementations/rust/ockam/ockam_api/src/uppercase.rs b/implementations/rust/ockam/ockam_api/src/uppercase.rs index d0d1bb79599..60cc790285a 100644 --- a/implementations/rust/ockam/ockam_api/src/uppercase.rs +++ b/implementations/rust/ockam/ockam_api/src/uppercase.rs @@ -5,7 +5,6 @@ pub struct Uppercase; #[ockam::worker] impl Worker for Uppercase { type Message = String; - type Context = Context; #[instrument(skip_all, name = "Uppercase::handle_message")] async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_api/tests/common/session.rs b/implementations/rust/ockam/ockam_api/tests/common/session.rs index 50b7e591c76..30ac7d32842 100644 --- a/implementations/rust/ockam/ockam_api/tests/common/session.rs +++ b/implementations/rust/ockam/ockam_api/tests/common/session.rs @@ -7,7 +7,8 @@ use ockam_api::session::replacer::{ }; use ockam_core::compat::sync::Arc; use ockam_core::errcode::{Kind, Origin}; -use ockam_core::{async_trait, Any, Error, NeutralMessage, Result, Route, Routed, Worker}; +use ockam_core::{async_trait, Any, Error, NeutralMessage, Result, Route, Routed}; +use ockam_node::Worker; use std::sync::atomic::AtomicU8; use std::time::Duration; @@ -31,7 +32,6 @@ impl MockEchoer { #[ockam::worker] impl Worker for MockEchoer { - type Context = Context; type Message = Any; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { @@ -76,7 +76,6 @@ impl MockHop { #[ockam::worker] impl Worker for MockHop { - type Context = Context; type Message = Any; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_core/src/lib.rs b/implementations/rust/ockam/ockam_core/src/lib.rs index 8b9aa00cf4d..d1e58dc5fd9 100644 --- a/implementations/rust/ockam/ockam_core/src/lib.rs +++ b/implementations/rust/ockam/ockam_core/src/lib.rs @@ -82,20 +82,16 @@ mod cbor; mod error; mod identity; mod message; -mod processor; mod routing; mod uint; -mod worker; pub use access_control::*; pub use cbor::*; pub use error::*; pub use identity::*; pub use message::*; -pub use processor::*; pub use routing::*; pub use uint::*; -pub use worker::*; #[cfg(all(not(feature = "std"), feature = "alloc"))] #[doc(hidden)] diff --git a/implementations/rust/ockam/ockam_core/src/message.rs b/implementations/rust/ockam/ockam_core/src/message.rs index ded39a1a60a..5d3b82c2235 100644 --- a/implementations/rust/ockam/ockam_core/src/message.rs +++ b/implementations/rust/ockam/ockam_core/src/message.rs @@ -302,8 +302,7 @@ impl Debug for Routed { /// /// #[ockam::worker] /// impl Worker for Logger { -/// type Context = Context; -/// type Message = Any; +/// /// type Message = Any; /// /// /// This Worker will take any incoming message, print out the payload /// /// and then forward it to the next hop in its onward route. diff --git a/implementations/rust/ockam/ockam_core/src/processor.rs b/implementations/rust/ockam/ockam_core/src/processor.rs deleted file mode 100644 index e5b54f6cfdb..00000000000 --- a/implementations/rust/ockam/ockam_core/src/processor.rs +++ /dev/null @@ -1,40 +0,0 @@ -use crate::compat::boxed::Box; -use crate::{async_trait, Result}; - -/// Defines an interface for Ockam Workers that need to continuously -/// perform background operations. -#[async_trait] -pub trait Processor: Send + 'static { - /// The Ockam API Context and other resources available for the - /// processor during processing. - type Context: Send + 'static; - - /// Define the Processor Worker initialisation behaviour. - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { - Ok(()) - } - - /// Define the Processor Worker shutdown behaviour. - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { - Ok(()) - } - - /// Define the Processor Worker background execution behaviour. - /// - /// The `process()` callback function allows you to define worker - /// behavior that will be executed. - /// - /// If no `.await` is performed during `process()`, the execution - /// will result in a busy loop. - /// - /// It's important to not block this function for long periods of - /// time as it is co-operatively scheduled by the underlying async - /// runtime and will block all other Ockam Node operations until - /// it returns. - /// - /// Always prefer async `.await` operations, as blocking operations - /// can cause deadlocks. - async fn process(&mut self, _context: &mut Self::Context) -> Result { - Ok(false) - } -} diff --git a/implementations/rust/ockam/ockam_core/src/worker.rs b/implementations/rust/ockam/ockam_core/src/worker.rs deleted file mode 100644 index b200add939a..00000000000 --- a/implementations/rust/ockam/ockam_core/src/worker.rs +++ /dev/null @@ -1,40 +0,0 @@ -use crate::{async_trait, compat::boxed::Box, Message, Result, Routed}; - -/// Defines the core interface shared by all Ockam Workers. -/// -/// While all methods do not need to be implemented, at the very -/// least, the `Context` and `Message` types need to be specified -/// before a worker can be used in any call to a `Context` API such as -/// `context.start_worker(...)`. -#[async_trait] -pub trait Worker: Send + 'static { - /// The type of Message the Worker is sent in [`Self::handle_message`]. - type Message: Message; - - /// The API and other resources available for the worker during message - /// processing. - /// - /// Currently, this should be always `ockam::Context` or - /// `ockam_node::Context` (which are the same type), but in the future - /// custom node implementations may use a different context type. - type Context: Send + 'static; - - /// Override initialisation behaviour. - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { - Ok(()) - } - - /// Override shutdown behaviour. - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { - Ok(()) - } - - /// Try to open and handle a typed message. - async fn handle_message( - &mut self, - _context: &mut Self::Context, - _msg: Routed, - ) -> Result<()> { - Ok(()) - } -} diff --git a/implementations/rust/ockam/ockam_identity/src/secure_channel/encryptor_worker.rs b/implementations/rust/ockam/ockam_identity/src/secure_channel/encryptor_worker.rs index 784de418dc5..f30280bed37 100644 --- a/implementations/rust/ockam/ockam_identity/src/secure_channel/encryptor_worker.rs +++ b/implementations/rust/ockam/ockam_identity/src/secure_channel/encryptor_worker.rs @@ -10,8 +10,8 @@ use ockam_core::errcode::{Kind, Origin}; use ockam_core::{ async_trait, route, CowBytes, Decodable, Error, LocalMessage, NeutralMessage, Route, }; -use ockam_core::{Any, Result, Routed, Worker}; -use ockam_node::Context; +use ockam_core::{Any, Result, Routed}; +use ockam_node::{Context, Worker}; use crate::models::CredentialAndPurposeKey; use crate::secure_channel::addresses::Addresses; @@ -130,7 +130,7 @@ impl EncryptorWorker { #[instrument(skip_all)] async fn handle_encrypt_api( &mut self, - ctx: &mut ::Context, + ctx: &mut Context, msg: Routed<::Message>, ) -> Result<()> { trace!( @@ -187,7 +187,7 @@ impl EncryptorWorker { #[instrument(skip_all)] async fn handle_encrypt( &mut self, - ctx: &mut ::Context, + ctx: &mut Context, msg: Routed<::Message>, ) -> Result<()> { trace!( @@ -235,7 +235,7 @@ impl EncryptorWorker { /// Asks credential retriever for a new credential and presents it to the other side, including /// the latest change_history #[instrument(skip_all)] - async fn handle_refresh_credentials(&mut self, ctx: &::Context) -> Result<()> { + async fn handle_refresh_credentials(&mut self, ctx: &Context) -> Result<()> { trace!( "Started credentials refresh for {}", self.addresses.encryptor @@ -350,9 +350,8 @@ impl EncryptorWorker { #[async_trait] impl Worker for EncryptorWorker { type Message = Any; - type Context = Context; - async fn initialize(&mut self, _ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _ctx: &mut Context) -> Result<()> { if let Some(credential_retriever) = &self.credential_retriever { credential_retriever.subscribe(&self.addresses.encryptor_internal)?; } @@ -363,7 +362,7 @@ impl Worker for EncryptorWorker { #[instrument(skip_all, name = "EncryptorWorker::handle_message", fields(worker = % ctx.primary_address()))] async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, msg: Routed, ) -> Result<()> { let msg_addr = msg.msg_addr(); @@ -388,7 +387,7 @@ impl Worker for EncryptorWorker { } #[instrument(skip_all, name = "EncryptorWorker::shutdown")] - async fn shutdown(&mut self, context: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, context: &mut Context) -> Result<()> { if let Some(credential_retriever) = &self.credential_retriever { credential_retriever.unsubscribe(&self.addresses.encryptor_internal)?; } diff --git a/implementations/rust/ockam/ockam_identity/src/secure_channel/handshake/handshake_worker.rs b/implementations/rust/ockam/ockam_identity/src/secure_channel/handshake/handshake_worker.rs index a14e2dc5752..d3ad6fea4b9 100644 --- a/implementations/rust/ockam/ockam_identity/src/secure_channel/handshake/handshake_worker.rs +++ b/implementations/rust/ockam/ockam_identity/src/secure_channel/handshake/handshake_worker.rs @@ -3,13 +3,13 @@ use core::time::Duration; use ockam_core::compat::boxed::Box; use ockam_core::compat::sync::{Arc, RwLock}; use ockam_core::errcode::{Kind, Origin}; +use ockam_core::Result; use ockam_core::{ AddressMetadata, AllowAll, Any, DenyAll, Error, Mailbox, Mailboxes, NeutralMessage, OutgoingAccessControl, Route, Routed, SecureChannelMetadata, }; -use ockam_core::{Result, Worker}; use ockam_node::callback::CallbackSender; -use ockam_node::{Context, WorkerBuilder}; +use ockam_node::{Context, Worker, WorkerBuilder}; use ockam_vault::AeadSecretKeyHandle; use tracing::{debug, error, info, trace, warn}; use tracing_attributes::instrument; @@ -62,11 +62,10 @@ pub(crate) struct HandshakeWorker { #[ockam_core::worker] impl Worker for HandshakeWorker { type Message = Any; - type Context = Context; /// Initialize the state machine with an `Initialize` event /// Depending on the state machine role there might be a message to send to the other party - async fn initialize(&mut self, context: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, context: &mut Context) -> Result<()> { if let Some(credential_retriever) = &self.credential_retriever { credential_retriever.initialize().await?; } @@ -101,7 +100,7 @@ impl Worker for HandshakeWorker { /// a transition async fn handle_message( &mut self, - context: &mut Self::Context, + context: &mut Context, message: Routed, ) -> Result<()> { // Once the decryptor has been initialized, let it handle messages @@ -115,7 +114,7 @@ impl Worker for HandshakeWorker { } } - async fn shutdown(&mut self, context: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, context: &mut Context) -> Result<()> { let _ = context.stop_address(&self.addresses.encryptor); self.secure_channels .secure_channel_registry diff --git a/implementations/rust/ockam/ockam_identity/src/secure_channel/listener.rs b/implementations/rust/ockam/ockam_identity/src/secure_channel/listener.rs index 0d923f9a9bb..8f9c6dd2d87 100644 --- a/implementations/rust/ockam/ockam_identity/src/secure_channel/listener.rs +++ b/implementations/rust/ockam/ockam_identity/src/secure_channel/listener.rs @@ -1,7 +1,7 @@ use ockam_core::compat::boxed::Box; use ockam_core::compat::sync::Arc; -use ockam_core::{Address, Any, Result, Routed, Worker}; -use ockam_node::Context; +use ockam_core::{Address, Any, Result, Routed}; +use ockam_node::{Context, Worker}; use crate::models::Identifier; use crate::secure_channel::addresses::Addresses; @@ -60,11 +60,10 @@ impl SecureChannelListenerWorker { #[ockam_core::worker] impl Worker for SecureChannelListenerWorker { type Message = Any; - type Context = Context; async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, message: Routed, ) -> Result<()> { let addresses = Addresses::generate(Role::Responder); diff --git a/implementations/rust/ockam/ockam_identity/tests/channel.rs b/implementations/rust/ockam/ockam_identity/tests/channel.rs index 07d6f36983d..b63b3e9e50f 100644 --- a/implementations/rust/ockam/ockam_identity/tests/channel.rs +++ b/implementations/rust/ockam/ockam_identity/tests/channel.rs @@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicU8, Ordering}; use ockam_core::compat::sync::Arc; use ockam_core::{ route, Address, AllowAll, Any, DenyAll, Mailboxes, Result, Routed, SecureChannelLocalInfo, - Worker, SECURE_CHANNEL_IDENTIFIER, + SECURE_CHANNEL_IDENTIFIER, }; use ockam_identity::models::{CredentialSchemaIdentifier, Identifier}; use ockam_identity::secure_channels::secure_channels; @@ -14,7 +14,7 @@ use ockam_identity::{ SecureChannelListenerOptions, SecureChannelOptions, SecureChannels, TrustEveryonePolicy, TrustIdentifierPolicy, Vault, }; -use ockam_node::{Context, MessageReceiveOptions, WorkerBuilder}; +use ockam_node::{Context, MessageReceiveOptions, Worker, WorkerBuilder}; use ockam_vault::{ SoftwareVaultForSecureChannels, SoftwareVaultForSigning, SoftwareVaultForVerifyingSignatures, }; @@ -752,11 +752,10 @@ struct Receiver { #[ockam_core::async_trait] impl Worker for Receiver { type Message = Any; - type Context = Context; async fn handle_message( &mut self, - _context: &mut Self::Context, + _context: &mut Context, _msg: Routed, ) -> Result<()> { self.received_count.fetch_add(1, Ordering::Relaxed); diff --git a/implementations/rust/ockam/ockam_identity/tests/credentials.rs b/implementations/rust/ockam/ockam_identity/tests/credentials.rs index 330218410ec..e284ee9c4b7 100644 --- a/implementations/rust/ockam/ockam_identity/tests/credentials.rs +++ b/implementations/rust/ockam/ockam_identity/tests/credentials.rs @@ -3,7 +3,7 @@ use std::time::Duration; use ockam_core::compat::sync::Arc; use ockam_core::{async_trait, Any, DenyAll}; -use ockam_core::{route, Result, Routed, Worker}; +use ockam_core::{route, Result, Routed}; use ockam_identity::models::CredentialSchemaIdentifier; use ockam_identity::secure_channels::secure_channels; use ockam_identity::utils::AttributesBuilder; @@ -12,7 +12,7 @@ use ockam_identity::{ TrustIdentifierPolicy, }; use ockam_node::workers::Echoer; -use ockam_node::{Context, WorkerBuilder}; +use ockam_node::{Context, Worker, WorkerBuilder}; #[ockam_macros::test] async fn full_flow_oneway(ctx: &mut Context) -> Result<()> { @@ -379,12 +379,11 @@ struct CountingWorker { #[async_trait] impl Worker for CountingWorker { - type Context = Context; type Message = Any; async fn handle_message( &mut self, - _context: &mut Self::Context, + _context: &mut Context, _msg: Routed, ) -> Result<()> { let _ = self.msgs_count.fetch_add(1, Ordering::Relaxed); diff --git a/implementations/rust/ockam/ockam_identity/tests/credentials_refresh.rs b/implementations/rust/ockam/ockam_identity/tests/credentials_refresh.rs index 780dc25065b..ab8b28dd434 100644 --- a/implementations/rust/ockam/ockam_identity/tests/credentials_refresh.rs +++ b/implementations/rust/ockam/ockam_identity/tests/credentials_refresh.rs @@ -3,7 +3,7 @@ use std::time::Duration; use ockam_core::api::Response; use ockam_core::compat::sync::Arc; -use ockam_core::{async_trait, Any, Routed, SecureChannelLocalInfo, TryClone, Worker}; +use ockam_core::{async_trait, Any, Routed, SecureChannelLocalInfo, TryClone}; use ockam_core::{route, Result}; use ockam_identity::models::CredentialSchemaIdentifier; use ockam_identity::secure_channels::secure_channels; @@ -13,7 +13,7 @@ use ockam_identity::{ RemoteCredentialRetrieverTimingOptions, SecureChannelListenerOptions, SecureChannelOptions, SecureChannels, }; -use ockam_node::Context; +use ockam_node::{Context, Worker}; use ockam_transport_tcp::TcpTransport; struct CredentialIssuer { @@ -28,11 +28,10 @@ struct CredentialIssuer { #[async_trait] impl Worker for CredentialIssuer { type Message = Any; - type Context = Context; async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, msg: Routed, ) -> Result<()> { if self.pause.load(Ordering::Relaxed) { diff --git a/implementations/rust/ockam/ockam_node/src/context/context_lifecycle.rs b/implementations/rust/ockam/ockam_node/src/context/context_lifecycle.rs index 0e0d65218d6..39bc025fd26 100644 --- a/implementations/rust/ockam/ockam_node/src/context/context_lifecycle.rs +++ b/implementations/rust/ockam/ockam_node/src/context/context_lifecycle.rs @@ -16,8 +16,9 @@ use ockam_transport_core::Transport; use crate::channel_types::{message_channel, oneshot_channel, OneshotReceiver}; use crate::router::Router; +use crate::router::SenderPair; +use crate::worker_relay::CtrlSignal; use crate::{debugger, Context, ContextMode}; -use crate::{relay::CtrlSignal, router::SenderPair}; use tokio::runtime::Handle; impl Drop for Context { diff --git a/implementations/rust/ockam/ockam_node/src/context/worker_lifecycle.rs b/implementations/rust/ockam/ockam_node/src/context/worker_lifecycle.rs index 3c04d117ea0..310426545dc 100644 --- a/implementations/rust/ockam/ockam_node/src/context/worker_lifecycle.rs +++ b/implementations/rust/ockam/ockam_node/src/context/worker_lifecycle.rs @@ -1,8 +1,5 @@ -use crate::Context; -use crate::{ProcessorBuilder, WorkerBuilder}; -use ockam_core::{ - Address, IncomingAccessControl, OutgoingAccessControl, Processor, Result, Worker, -}; +use crate::{Context, Worker, WorkerBuilder}; +use ockam_core::{Address, IncomingAccessControl, OutgoingAccessControl, Result}; impl Context { /// Start a new worker instance at the given address. Default AccessControl is AllowAll @@ -11,7 +8,7 @@ impl Context { /// receive messages of a specific type. This type is encoded via /// the [`Worker`](ockam_core::Worker) trait. If your code relies /// on a manual run-loop you may want to use - /// [`start_processor()`](Self::start_processor) instead! + /// [`start_worker()`](Self::start_worker) instead! /// /// Each address in the set must be unique and unused on the /// current node. Workers must implement the Worker trait and be @@ -21,14 +18,13 @@ impl Context { /// [`wait_for()`](Self::wait_for). /// /// ```rust - /// use ockam_core::{Result, Worker, worker}; - /// use ockam_node::Context; + /// use ockam_core::{Result, worker}; + /// use ockam_node::{Worker, Context}; /// /// struct MyWorker; /// /// #[worker] /// impl Worker for MyWorker { - /// type Context = Context; /// type Message = String; /// } /// @@ -53,10 +49,7 @@ impl Context { /// WorkerRelay calls Worker::handle_message for each message until either /// stop signal is received (CtrlSignal::InterruptStop to AddressRecord::ctrl_tx) /// there are no messages coming to that receiver (the sender side is dropped) - pub fn start_worker(&self, address: impl Into
, worker: W) -> Result<()> - where - W: Worker, - { + pub fn start_worker(&self, address: impl Into
, worker: W) -> Result<()> { WorkerBuilder::new(worker) .with_address(address) .start(self)?; @@ -70,7 +63,7 @@ impl Context { /// receive messages of a specific type. This type is encoded via /// the [`Worker`](ockam_core::Worker) trait. If your code relies /// on a manual run-loop you may want to use - /// [`start_processor()`](Self::start_processor) instead! + /// [`start_worker()`](Self::start_worker) instead! /// /// Each address in the set must be unique and unused on the /// current node. Workers must implement the Worker trait and be @@ -78,14 +71,13 @@ impl Context { /// independently of each other. /// /// ```rust - /// use ockam_core::{AllowAll, Result, Worker, worker}; - /// use ockam_node::Context; + /// use ockam_core::{AllowAll, Result, worker}; + /// use ockam_node::{Context, Worker}; /// /// struct MyWorker; /// /// #[worker] /// impl Worker for MyWorker { - /// type Context = Context; /// type Message = String; /// } /// @@ -93,16 +85,13 @@ impl Context { /// ctx.start_worker_with_access_control("my-worker-address", MyWorker, AllowAll, AllowAll) /// } /// ``` - pub fn start_worker_with_access_control( + pub fn start_worker_with_access_control( &self, address: impl Into
, worker: W, incoming: impl IncomingAccessControl, outgoing: impl OutgoingAccessControl, - ) -> Result<()> - where - W: Worker, - { + ) -> Result<()> { WorkerBuilder::new(worker) .with_address(address) .with_incoming_access_control(incoming) @@ -112,66 +101,6 @@ impl Context { Ok(()) } - /// Start a new processor instance at the given address. Default AccessControl is DenyAll - /// - /// A processor is an asynchronous piece of code that runs a - /// custom run loop, with access to a worker context to send and - /// receive messages. If your code is built around responding to - /// message events, consider using - /// [`start_worker()`](Self::start_worker) instead! - /// - /// Approximate flow of starting a processor: - /// - /// 1. StartProcessor message -> Router - /// 2. First address is considered a primary_addr (main_addr) - /// 3. Check if router.map.address_records_map already has primary_addr - /// 4. AddressRecord is created and inserted in router.map - /// 5. Iterate over metadata: - /// Check if it belongs to that record - /// Set is_terminal true in router.map.address_metadata_map (if address is terminal) - /// Insert attributes one by one - /// 6. For each address we insert pair (Address, primary_addr) into router.map.alias_map, including (primary_addr, primary_addr itself) - /// 7. ProcessorRelay is spawned as a tokio task: - /// ProcessorRelay calls Processor::initialize - /// ProcessorRelay calls Processor::process until either false is returned or stop signal is received (CtrlSignal::InterruptStop to AddressRecord::ctrl_tx) - pub fn start_processor

(&self, address: impl Into

, processor: P) -> Result<()> - where - P: Processor, - { - ProcessorBuilder::new(processor) - .with_address(address.into()) - .start(self)?; - - Ok(()) - } - - /// Start a new processor instance at the given address - /// - /// A processor is an asynchronous piece of code that runs a - /// custom run loop, with access to a worker context to send and - /// receive messages. If your code is built around responding to - /// message events, consider using - /// [`start_worker()`](Self::start_worker) instead! - /// - pub fn start_processor_with_access_control

( - &self, - address: impl Into

, - processor: P, - incoming: impl IncomingAccessControl, - outgoing: impl OutgoingAccessControl, - ) -> Result<()> - where - P: Processor, - { - ProcessorBuilder::new(processor) - .with_address(address) - .with_incoming_access_control(incoming) - .with_outgoing_access_control(outgoing) - .start(self)?; - - Ok(()) - } - /// Stop a Worker or a Processor running on given Address pub fn stop_address(&self, address: &Address) -> Result<()> { self.router()?.stop_address(address, false) diff --git a/implementations/rust/ockam/ockam_node/src/debugger.rs b/implementations/rust/ockam/ockam_node/src/debugger.rs index 21936be9d41..6baf6467beb 100644 --- a/implementations/rust/ockam/ockam_node/src/debugger.rs +++ b/implementations/rust/ockam/ockam_node/src/debugger.rs @@ -207,12 +207,6 @@ pub fn _log_start_worker() { {} } -/// TODO -pub fn _log_start_processor() { - #[cfg(feature = "debugger")] - {} -} - // ---------------------------------------------------------------------------- #[cfg(all(feature = "debugger", feature = "std"))] diff --git a/implementations/rust/ockam/ockam_node/src/delayed.rs b/implementations/rust/ockam/ockam_node/src/delayed.rs index 3dbc3435128..3bd368a8f62 100644 --- a/implementations/rust/ockam/ockam_node/src/delayed.rs +++ b/implementations/rust/ockam/ockam_node/src/delayed.rs @@ -88,12 +88,12 @@ impl DelayedEvent { #[cfg(test)] mod tests { - use crate::{Context, DelayedEvent}; + use crate::{Context, DelayedEvent, Worker}; use core::sync::atomic::Ordering; use core::time::Duration; use ockam_core::compat::{boxed::Box, string::ToString, sync::Arc}; use ockam_core::{async_trait, Any}; - use ockam_core::{Result, Routed, Worker}; + use ockam_core::{Result, Routed}; use std::sync::atomic::AtomicI8; use tokio::time::sleep; @@ -103,12 +103,11 @@ mod tests { #[async_trait] impl Worker for CountingWorker { - type Context = Context; type Message = Any; async fn handle_message( &mut self, - _context: &mut Self::Context, + _context: &mut Context, _msg: Routed, ) -> Result<()> { let _ = self.msgs_count.fetch_add(1, Ordering::Relaxed); diff --git a/implementations/rust/ockam/ockam_node/src/lib.rs b/implementations/rust/ockam/ockam_node/src/lib.rs index f20bf99ffd1..907e364b1c1 100644 --- a/implementations/rust/ockam/ockam_node/src/lib.rs +++ b/implementations/rust/ockam/ockam_node/src/lib.rs @@ -55,9 +55,9 @@ mod delayed; mod error; mod executor; mod node; -mod processor_builder; -mod relay; mod router; +mod worker; +mod worker_relay; /// Support for storing persistent values pub mod storage; @@ -71,9 +71,9 @@ pub use context::*; pub use delayed::*; pub use error::*; pub use executor::*; -pub use processor_builder::ProcessorBuilder; #[cfg(feature = "std")] pub use storage::database; +pub use worker::*; pub use worker_builder::WorkerBuilder; pub use node::{NodeBuilder, NullWorker}; diff --git a/implementations/rust/ockam/ockam_node/src/node.rs b/implementations/rust/ockam/ockam_node/src/node.rs index 51e83487ce8..a5e9ff7050c 100644 --- a/implementations/rust/ockam/ockam_node/src/node.rs +++ b/implementations/rust/ockam/ockam_node/src/node.rs @@ -8,8 +8,7 @@ use ockam_core::OpenTelemetryContext; /// A minimal worker implementation that does nothing pub struct NullWorker; -impl ockam_core::Worker for NullWorker { - type Context = Context; +impl crate::Worker for NullWorker { type Message = (); // This message type is never used } diff --git a/implementations/rust/ockam/ockam_node/src/processor_builder.rs b/implementations/rust/ockam/ockam_node/src/processor_builder.rs deleted file mode 100644 index 0d01e1bb45c..00000000000 --- a/implementations/rust/ockam/ockam_node/src/processor_builder.rs +++ /dev/null @@ -1,256 +0,0 @@ -use crate::{debugger, ContextMode, WorkerShutdownPriority}; -use crate::{relay::ProcessorRelay, Context}; -use ockam_core::compat::string::String; -use ockam_core::compat::sync::Arc; -use ockam_core::{ - Address, AddressMetadata, DenyAll, IncomingAccessControl, Mailbox, Mailboxes, - OutgoingAccessControl, Processor, Result, -}; - -/// Start a [`Processor`] -/// -/// Varying use-cases should use the builder API to customise the -/// underlying processor that is created. -pub struct ProcessorBuilder

-where - P: Processor, -{ - processor: P, -} - -impl

ProcessorBuilder

-where - P: Processor, -{ - /// Create a new builder for a given Processor. Default AccessControl is DenyAll - pub fn new(processor: P) -> Self { - Self { processor } - } -} - -impl

ProcessorBuilder

-where - P: Processor, -{ - /// Processor with only one [`Address`] - pub fn with_address(self, address: impl Into

) -> ProcessorBuilderOneAddress

{ - self.with_address_and_metadata_impl(address, None) - } - - /// Processor with single terminal [`Address`] - pub fn with_terminal_address( - self, - address: impl Into

, - ) -> ProcessorBuilderOneAddress

{ - self.with_address_and_metadata( - address, - AddressMetadata { - is_terminal: true, - attributes: vec![], - }, - ) - } - - /// Processor with single terminal [`Address`] and metadata - pub fn with_address_and_metadata( - self, - address: impl Into

, - metadata: AddressMetadata, - ) -> ProcessorBuilderOneAddress

{ - self.with_address_and_metadata_impl(address, Some(metadata)) - } - - /// Processor with single terminal [`Address`] and metadata - pub fn with_address_and_metadata_impl( - self, - address: impl Into

, - metadata: Option, - ) -> ProcessorBuilderOneAddress

{ - ProcessorBuilderOneAddress { - incoming_ac: Arc::new(DenyAll), - outgoing_ac: Arc::new(DenyAll), - processor: self.processor, - address: address.into(), - metadata, - shutdown_priority: Default::default(), - } - } - - /// Worker with multiple [`Address`]es - pub fn with_mailboxes(self, mailboxes: Mailboxes) -> ProcessorBuilderMultipleAddresses

{ - ProcessorBuilderMultipleAddresses { - mailboxes, - shutdown_priority: Default::default(), - processor: self.processor, - } - } -} - -pub struct ProcessorBuilderMultipleAddresses

-where - P: Processor, -{ - mailboxes: Mailboxes, - shutdown_priority: WorkerShutdownPriority, - processor: P, -} - -impl

ProcessorBuilderMultipleAddresses

-where - P: Processor, -{ - /// Consume this builder and start a new Ockam [`Processor`] from the given context - pub fn start(self, context: &Context) -> Result<()> { - start( - context, - self.mailboxes, - self.shutdown_priority, - self.processor, - ) - } - - pub fn with_shutdown_priority(mut self, shutdown_priority: WorkerShutdownPriority) -> Self { - self.shutdown_priority = shutdown_priority; - self - } -} - -pub struct ProcessorBuilderOneAddress

-where - P: Processor, -{ - incoming_ac: Arc, - outgoing_ac: Arc, - address: Address, - processor: P, - metadata: Option, - shutdown_priority: WorkerShutdownPriority, -} - -impl

ProcessorBuilderOneAddress

-where - P: Processor, -{ - /// Mark the provided address as terminal - pub fn terminal(mut self) -> Self { - self.metadata - .get_or_insert(AddressMetadata { - is_terminal: false, - attributes: vec![], - }) - .is_terminal = true; - self - } - - /// Adds metadata attribute for the provided address - pub fn with_metadata_attribute( - mut self, - key: impl Into, - value: impl Into, - ) -> Self { - self.metadata - .get_or_insert(AddressMetadata { - is_terminal: false, - attributes: vec![], - }) - .attributes - .push((key.into(), value.into())); - - self - } - - /// Consume this builder and start a new Ockam [`Processor`] from the given context - pub fn start(self, context: &Context) -> Result<()> { - start( - context, - Mailboxes::new( - Mailbox::new( - self.address, - self.metadata, - self.incoming_ac, - self.outgoing_ac, - ), - vec![], - ), - self.shutdown_priority, - self.processor, - ) - } -} - -impl

ProcessorBuilderOneAddress

-where - P: Processor, -{ - /// Set [`IncomingAccessControl`] - pub fn with_incoming_access_control( - mut self, - incoming_access_control: impl IncomingAccessControl, - ) -> Self { - self.incoming_ac = Arc::new(incoming_access_control); - self - } - - /// Set [`IncomingAccessControl`] - pub fn with_incoming_access_control_arc( - mut self, - incoming_access_control: Arc, - ) -> Self { - self.incoming_ac = incoming_access_control.clone(); - self - } - - /// Set [`OutgoingAccessControl`] - pub fn with_outgoing_access_control( - mut self, - outgoing_access_control: impl OutgoingAccessControl, - ) -> Self { - self.outgoing_ac = Arc::new(outgoing_access_control); - self - } - - /// Set [`OutgoingAccessControl`] - pub fn with_outgoing_access_control_arc( - mut self, - outgoing_access_control: Arc, - ) -> Self { - self.outgoing_ac = outgoing_access_control.clone(); - self - } - - pub fn with_shutdown_priority(mut self, shutdown_priority: WorkerShutdownPriority) -> Self { - self.shutdown_priority = shutdown_priority; - self - } -} - -/// Consume this builder and start a new Ockam [`Processor`] from the given context -pub fn start

( - context: &Context, - mailboxes: Mailboxes, - shutdown_priority: WorkerShutdownPriority, - processor: P, -) -> Result<()> -where - P: Processor, -{ - debug!( - "Initializing ockam processor '{}' with access control in:{:?} out:{:?}", - mailboxes.primary_address(), - mailboxes.primary_mailbox().incoming_access_control(), - mailboxes.primary_mailbox().outgoing_access_control(), - ); - - // Pass it to the context - let (ctx, sender, ctrl_rx) = context.new_with_mailboxes(mailboxes, ContextMode::Attached); - - debugger::log_inherit_context("PROCESSOR", context, &ctx); - - let router = context.router()?; - router.add_processor(ctx.mailboxes(), sender, shutdown_priority)?; - - // Then initialise the processor message relay - ProcessorRelay::

::init(context.runtime(), processor, ctx, ctrl_rx); - - Ok(()) -} diff --git a/implementations/rust/ockam/ockam_node/src/relay/mod.rs b/implementations/rust/ockam/ockam_node/src/relay/mod.rs deleted file mode 100644 index 67ed3013d35..00000000000 --- a/implementations/rust/ockam/ockam_node/src/relay/mod.rs +++ /dev/null @@ -1,12 +0,0 @@ -mod processor_relay; -mod worker_relay; - -pub use processor_relay::*; -pub use worker_relay::*; - -/// A signal type used to communicate between router and worker relay -#[derive(Clone, Debug)] -pub enum CtrlSignal { - /// Interrupt current message execution and shut down - InterruptStop, -} diff --git a/implementations/rust/ockam/ockam_node/src/relay/processor_relay.rs b/implementations/rust/ockam/ockam_node/src/relay/processor_relay.rs deleted file mode 100644 index 8169af1046c..00000000000 --- a/implementations/rust/ockam/ockam_node/src/relay/processor_relay.rs +++ /dev/null @@ -1,151 +0,0 @@ -use crate::channel_types::OneshotReceiver; -use crate::{relay::CtrlSignal, tokio::runtime::Handle, Context}; -use ockam_core::{Processor, Result}; - -pub struct ProcessorRelay

-where - P: Processor, -{ - processor: P, - ctx: Context, -} - -impl

ProcessorRelay

-where - P: Processor, -{ - pub fn new(processor: P, ctx: Context) -> Self { - Self { processor, ctx } - } - - #[cfg_attr(not(feature = "std"), allow(unused_mut))] - #[cfg_attr(not(feature = "std"), allow(unused_variables))] - async fn run(self, ctrl_rx: OneshotReceiver) { - let mut ctx = self.ctx; - let mut processor = self.processor; - - match processor.initialize(&mut ctx).await { - Ok(()) => {} - Err(e) => { - error!( - "Failure during '{}' processor initialisation: {}", - ctx.primary_address(), - e - ); - shutdown_and_stop_ack(&mut processor, &mut ctx, false).await; - return; - } - } - - // This future encodes the main processor run loop logic - let run_loop = async { - loop { - match processor.process(&mut ctx).await { - Ok(should_continue) => { - if !should_continue { - break; - } - } - Err(e) => { - #[cfg(feature = "debugger")] - error!( - "Error encountered during '{}' processing: {:?}", - ctx.primary_address(), - e - ); - #[cfg(not(feature = "debugger"))] - error!( - "Error encountered during '{}' processing: {}", - ctx.primary_address(), - e - ); - } - } - } - - Result::<()>::Ok(()) - }; - - let mut stopped_from_router = false; - #[cfg(feature = "std")] - { - // Select over the two futures - tokio::select! { - // This future resolves when a stop control signal is received - _ = ctrl_rx => { - debug!("Shutting down processor {} due to shutdown signal", ctx.primary_address()); - stopped_from_router = true; - }, - _ = run_loop => {} - }; - } - - // TODO wait on run_loop until we have a no_std select! implementation - #[cfg(not(feature = "std"))] - match run_loop.await { - Ok(_) => trace!("Processor shut down cleanly {}", ctx.primary_address()), - Err(err) => error!("processor run loop aborted with error: {:?}", err), - }; - - // If we reach this point the router has signaled us to shut down - shutdown_and_stop_ack(&mut processor, &mut ctx, stopped_from_router).await; - } - - /// Create a processor relay with two node contexts - pub(crate) fn init( - rt: &Handle, - processor: P, - ctx: Context, - ctrl_rx: OneshotReceiver, - ) { - let relay = ProcessorRelay::

::new(processor, ctx); - rt.spawn(relay.run(ctrl_rx)); - } -} - -async fn shutdown_and_stop_ack

(processor: &mut P, ctx: &mut Context, stopped_from_router: bool) -where - P: Processor, -{ - match processor.shutdown(ctx).await { - Ok(()) => {} - Err(e) => { - error!( - "Failure during '{}' processor shutdown: {}", - ctx.primary_address(), - e - ); - } - } - - let router = match ctx.router() { - Ok(router) => router, - Err(_) => { - error!( - "Failure during '{}' processor shutdown. Can't get router", - ctx.primary_address() - ); - return; - } - }; - - if !stopped_from_router { - if let Err(e) = router.stop_address(ctx.primary_address(), !stopped_from_router) { - error!( - "Failure during '{}' processor shutdown: {}", - ctx.primary_address(), - e - ); - } - } - - // Finally send the router a stop ACK -- log errors - trace!("Sending shutdown ACK"); - router.stop_ack(ctx.primary_address()).unwrap_or_else(|e| { - error!( - "Failed to send stop ACK for '{}': {}", - ctx.primary_address(), - e - ); - }); -} diff --git a/implementations/rust/ockam/ockam_node/src/router/mod.rs b/implementations/rust/ockam/ockam_node/src/router/mod.rs index 171dab262b9..ebf05fc3879 100644 --- a/implementations/rust/ockam/ockam_node/src/router/mod.rs +++ b/implementations/rust/ockam/ockam_node/src/router/mod.rs @@ -1,4 +1,3 @@ -mod processor; mod record; #[allow(clippy::module_inception)] mod router; diff --git a/implementations/rust/ockam/ockam_node/src/router/processor.rs b/implementations/rust/ockam/ockam_node/src/router/processor.rs deleted file mode 100644 index 0a7182393d6..00000000000 --- a/implementations/rust/ockam/ockam_node/src/router/processor.rs +++ /dev/null @@ -1,58 +0,0 @@ -use super::{Router, RouterState, SenderPair}; -use crate::router::record::{AddressRecord, WorkerMeta}; -use crate::WorkerShutdownPriority; -use ockam_core::compat::sync::Arc; -use ockam_core::errcode::{Kind, Origin}; -use ockam_core::{Error, Mailboxes, Result}; - -impl Router { - /// Start a processor - pub(crate) fn add_processor( - &self, - mailboxes: &Mailboxes, - senders: SenderPair, - shutdown_priority: WorkerShutdownPriority, - ) -> Result<()> { - if *self.state.read().unwrap() != RouterState::Running { - return Err(Error::new( - Origin::Node, - Kind::Shutdown, - "The node is shutting down", - ))?; - } - - self.add_processor_impl(mailboxes, senders, shutdown_priority) - } - - fn add_processor_impl( - &self, - mailboxes: &Mailboxes, - senders: SenderPair, - shutdown_priority: WorkerShutdownPriority, - ) -> Result<()> { - debug!("Starting new processor '{}'", mailboxes.primary_address()); - let SenderPair { msgs, ctrl } = senders; - - let record = AddressRecord::new( - mailboxes.primary_address().clone(), - mailboxes.additional_addresses().cloned().collect(), - msgs, - ctrl, - WorkerMeta { - processor: true, - detached: false, - }, - shutdown_priority, - // We don't keep track of the mailbox count for processors - // because, while they are able to send and receive messages - // via their mailbox, most likely this metric is going to be - // irrelevant. We may want to re-visit this decision in the - // future, if the way processors are used changes. - Arc::new(0.into()), - ); - - self.map.insert_address_record(record, mailboxes)?; - - Ok(()) - } -} diff --git a/implementations/rust/ockam/ockam_node/src/router/record.rs b/implementations/rust/ockam/ockam_node/src/router/record.rs index 7c12a9c0797..8a9c07bd047 100644 --- a/implementations/rust/ockam/ockam_node/src/router/record.rs +++ b/implementations/rust/ockam/ockam_node/src/router/record.rs @@ -1,6 +1,6 @@ use crate::channel_types::{oneshot_channel, MessageSender, OneshotReceiver, OneshotSender}; use crate::error::{NodeError, NodeReason}; -use crate::relay::CtrlSignal; +use crate::worker_relay::CtrlSignal; use crate::WorkerShutdownPriority; use core::default::Default; use core::fmt::Debug; @@ -400,8 +400,6 @@ impl InternalMap { /// Additional metadata for worker records #[derive(Debug)] pub struct WorkerMeta { - #[allow(dead_code)] - pub processor: bool, pub detached: bool, } diff --git a/implementations/rust/ockam/ockam_node/src/router/router.rs b/implementations/rust/ockam/ockam_node/src/router/router.rs index 43e015459c5..d1309ede536 100644 --- a/implementations/rust/ockam/ockam_node/src/router/router.rs +++ b/implementations/rust/ockam/ockam_node/src/router/router.rs @@ -3,7 +3,7 @@ use core::sync::atomic::AtomicUsize; use super::record::InternalMap; use crate::channel_types::{MessageSender, OneshotSender}; -use crate::relay::CtrlSignal; +use crate::worker_relay::CtrlSignal; use crate::{NodeError, NodeReason}; use alloc::vec::Vec; use ockam_core::compat::collections::hash_map::Entry; diff --git a/implementations/rust/ockam/ockam_node/src/router/worker.rs b/implementations/rust/ockam/ockam_node/src/router/worker.rs index 463054f6eae..c5170bdbb5a 100644 --- a/implementations/rust/ockam/ockam_node/src/router/worker.rs +++ b/implementations/rust/ockam/ockam_node/src/router/worker.rs @@ -43,10 +43,7 @@ impl Router { mailboxes.additional_addresses().cloned().collect(), msgs, ctrl, - WorkerMeta { - processor: false, - detached, - }, + WorkerMeta { detached }, shutdown_priority, metrics, ); diff --git a/implementations/rust/ockam/ockam_node/src/worker.rs b/implementations/rust/ockam/ockam_node/src/worker.rs new file mode 100644 index 00000000000..436bfd8c44a --- /dev/null +++ b/implementations/rust/ockam/ockam_node/src/worker.rs @@ -0,0 +1,89 @@ +use crate::Context; +use ockam_core::{async_trait, compat::boxed::Box, Message, Result, Routed}; + +/// Defines the core interface shared by all Ockam Workers. +/// +/// While all methods do not need to be implemented, at the very +/// least, the `Context` and `Message` types need to be specified +/// before a worker can be used in any call to a `Context` API such as +/// `context.start_worker(...)`. +#[async_trait] +pub trait Worker: Send + 'static { + /// The type of Message the Worker is sent in [`Self::handle_message`]. + type Message: Message; + + /// Override initialisation behaviour. + async fn initialize(&mut self, _context: &mut Context) -> Result<()> { + Ok(()) + } + + /// Override shutdown behaviour. + async fn shutdown(&mut self, _context: &mut Context) -> Result<()> { + Ok(()) + } + + /// Define the Processor Worker background execution behaviour. + /// + /// The `process()` callback function allows you to define worker + /// behavior that will be executed. + /// + /// If no `.await` is performed during `process()`, the execution + /// will result in a busy loop. + /// + /// It's important to not block this function for long periods of + /// time as it is co-operatively scheduled by the underlying async + /// runtime and will block all other Ockam Node operations until + /// it returns. + /// + /// Always prefer async `.await` operations, as blocking operations + /// can cause deadlocks. + async fn process(&mut self, ctx: &mut Context) -> Result { + match recv_message(ctx).await? { + Some(message) => { + self.handle_message(ctx, message).await?; + Ok(true) + } + None => Ok(false), + } + } + + /// Try to open and handle a typed message. + async fn handle_message( + &mut self, + _context: &mut Context, + _msg: Routed, + ) -> Result<()> { + Ok(()) + } +} + +/// Receive and handle a single message +/// +/// Report errors as they occur, and signal whether the loop should +/// continue running or not +async fn recv_message(ctx: &mut Context) -> Result>> { + let relay_msg = match ctx.receiver_next().await? { + Some(msg) => msg, + None => { + trace!("No more messages for worker {}", ctx.primary_address()); + return Ok(None); + } + }; + + // Call the worker handle function - pass errors up + #[cfg(feature = "std")] + { + let tracing_context = relay_msg.local_message().tracing_context(); + // We set the tracing context retrieved from the local message on the worker context + // This way, if the worker invokes ctx.send_message() to send a message to another worker, + // that same tracing context will be passed along when a LocalMessage will be created + // (see send_from_address_impl) + ctx.set_tracing_context(tracing_context.clone()); + } + + Ok(Some(Routed::new( + relay_msg.destination().clone(), + relay_msg.source().clone(), + relay_msg.into_local_message(), + ))) +} diff --git a/implementations/rust/ockam/ockam_node/src/worker_builder.rs b/implementations/rust/ockam/ockam_node/src/worker_builder.rs index d73dd335edb..ab11b9bd3b7 100644 --- a/implementations/rust/ockam/ockam_node/src/worker_builder.rs +++ b/implementations/rust/ockam/ockam_node/src/worker_builder.rs @@ -1,37 +1,29 @@ +use crate::worker_relay::WorkerRelay; use crate::{debugger, ContextMode, WorkerShutdownPriority}; -use crate::{relay::WorkerRelay, Context}; +use crate::{Context, Worker}; use ockam_core::compat::string::String; use ockam_core::compat::sync::Arc; use ockam_core::{ Address, AddressMetadata, AllowAll, IncomingAccessControl, Mailbox, Mailboxes, - OutgoingAccessControl, Result, Worker, + OutgoingAccessControl, Result, }; /// Start a [`Worker`] with a custom configuration /// /// Varying use-cases should use the builder API to customise the /// underlying worker that is created. -pub struct WorkerBuilder -where - W: Worker, -{ +pub struct WorkerBuilder { worker: W, } -impl WorkerBuilder -where - W: Worker, -{ +impl WorkerBuilder { /// Create a new builder for a given Worker. Default AccessControl is AllowAll pub fn new(worker: W) -> Self { Self { worker } } } -impl WorkerBuilder -where - W: Worker, -{ +impl WorkerBuilder { /// Worker with only one [`Address`] pub fn with_address(self, address: impl Into

) -> WorkerBuilderOneAddress { self.with_address_and_metadata_impl(address, None) @@ -83,19 +75,13 @@ where } } -pub struct WorkerBuilderMultipleAddresses -where - W: Worker, -{ +pub struct WorkerBuilderMultipleAddresses { mailboxes: Mailboxes, shutdown_priority: WorkerShutdownPriority, worker: W, } -impl WorkerBuilderMultipleAddresses -where - W: Worker, -{ +impl WorkerBuilderMultipleAddresses { /// Consume this builder and start a new Ockam [`Worker`] from the given context pub fn start(self, context: &Context) -> Result<()> { start(context, self.mailboxes, self.shutdown_priority, self.worker) @@ -107,10 +93,7 @@ where } } -pub struct WorkerBuilderOneAddress -where - W: Worker, -{ +pub struct WorkerBuilderOneAddress { incoming_ac: Arc, outgoing_ac: Arc, address: Address, @@ -119,10 +102,7 @@ where shutdown_priority: WorkerShutdownPriority, } -impl WorkerBuilderOneAddress -where - W: Worker, -{ +impl WorkerBuilderOneAddress { /// Mark the provided address as terminal pub fn terminal(mut self) -> Self { self.metadata @@ -175,10 +155,7 @@ where } } -impl WorkerBuilderOneAddress -where - W: Worker, -{ +impl WorkerBuilderOneAddress { /// Set [`IncomingAccessControl`] pub fn with_incoming_access_control( mut self, @@ -217,15 +194,12 @@ where } /// Consume this builder and start a new Ockam [`Worker`] from the given context -fn start( +fn start( context: &Context, mailboxes: Mailboxes, shutdown_priority: WorkerShutdownPriority, worker: W, -) -> Result<()> -where - W: Worker, -{ +) -> Result<()> { debug!( "Initializing ockam worker '{}' with access control in:{:?} out:{:?}", mailboxes.primary_address(), diff --git a/implementations/rust/ockam/ockam_node/src/relay/worker_relay.rs b/implementations/rust/ockam/ockam_node/src/worker_relay.rs similarity index 56% rename from implementations/rust/ockam/ockam_node/src/relay/worker_relay.rs rename to implementations/rust/ockam/ockam_node/src/worker_relay.rs index fe3916f7770..3ab0034a174 100644 --- a/implementations/rust/ockam/ockam_node/src/relay/worker_relay.rs +++ b/implementations/rust/ockam/ockam_node/src/worker_relay.rs @@ -1,11 +1,14 @@ use crate::channel_types::OneshotReceiver; -use crate::relay::CtrlSignal; use crate::tokio::runtime::Handle; -use crate::Context; -use cfg_if::cfg_if; -use ockam_core::{Message, RelayMessage, Result, Routed, Worker}; -#[cfg(feature = "std")] -use opentelemetry::trace::FutureExt; +use crate::{Context, Worker}; +use ockam_core::Message; + +/// A signal type used to communicate between router and worker relay +#[derive(Clone, Debug)] +pub enum CtrlSignal { + /// Interrupt current message execution and shut down + InterruptStop, +} /// Worker relay machinery /// @@ -25,74 +28,9 @@ impl WorkerRelay { impl WorkerRelay where - W: Worker, + W: Worker, M: Message + Send + 'static, { - /// Convenience function to parse an incoming direct message and - /// wrap it in a [`Routed`] - /// - /// This provides return route information for workers via a - /// composition side-channel. - /// - /// This is currently called twice, once when the message is - /// dispatched to the worker for authorization and again for - /// handling. Two unpleasant ways to avoid this are: - /// - /// 1. Introduce a Sync bound on the Worker trait that allows us - /// to pass the message by reference. - /// - /// 2. Introduce a Clone bound on the Message trait that allows us - /// to perform a cheaper clone on the message. - /// - fn wrap_direct_message(relay_msg: RelayMessage) -> Routed { - Routed::new( - relay_msg.destination().clone(), - relay_msg.source().clone(), - relay_msg.into_local_message(), - ) - } - - /// Receive and handle a single message - /// - /// Report errors as they occur, and signal whether the loop should - /// continue running or not - async fn recv_message(&mut self) -> Result { - let relay_msg = match self.ctx.receiver_next().await? { - Some(msg) => msg, - None => { - trace!("No more messages for worker {}", self.ctx.primary_address()); - return Ok(false); - } - }; - - // Call the worker handle function - pass errors up - cfg_if! { - if #[cfg(feature = "std")] { - let tracing_context = relay_msg.local_message().tracing_context(); - // We set the tracing context retrieved from the local message on the worker context - // This way, if the worker invokes ctx.send_message() to send a message to another worker, - // that same tracing context will be passed along when a LocalMessage will be created - // (see send_from_address_impl) - self.ctx.set_tracing_context(tracing_context.clone()); - - self.worker - .handle_message(&mut self.ctx, Self::wrap_direct_message(relay_msg)) - // make sure we are using the latest tracing context to handle the message - // the handle_message future - .with_context(tracing_context.update().extract()) - .await?; - } else { - let routed = Self::wrap_direct_message(relay_msg); - self.worker - .handle_message(&mut self.ctx, routed) - .await?; - } - } - - // Signal to the outer loop that we would like to run again - Ok(true) - } - #[cfg_attr(not(feature = "std"), allow(unused_mut))] #[cfg_attr(not(feature = "std"), allow(unused_variables))] async fn run(mut self, mut ctrl_rx: OneshotReceiver) { @@ -112,7 +50,7 @@ where #[cfg(feature = "std")] loop { crate::tokio::select! { - result = self.recv_message() => { + result = self.worker.process(&mut self.ctx) => { match result { // Successful message handling -- keep running Ok(true) => {}, @@ -139,19 +77,28 @@ where } #[cfg(not(feature = "std"))] loop { - match self.recv_message().await { + match self.worker.process(&mut self.ctx).await { // Successful message handling -- keep running Ok(true) => {} - // Successful message handling -- stop now + // No messages left -- stop now Ok(false) => { break; } // An error occurred -- log and continue - Err(e) => error!( - "Error encountered during '{}' message handling: {}", - self.ctx.primary_address(), - e - ), + Err(e) => { + #[cfg(feature = "debugger")] + error!( + "Error encountered during '{}' message handling: {:?}", + self.ctx.primary_address(), + e + ); + #[cfg(not(feature = "debugger"))] + error!( + "Error encountered during '{}' message handling: {}", + self.ctx.primary_address(), + e + ); + } } } @@ -165,10 +112,11 @@ where } } -async fn shutdown_and_stop_ack(worker: &mut W, ctx: &mut Context, stopped_from_router: bool) -where - W: Worker, -{ +async fn shutdown_and_stop_ack( + worker: &mut W, + ctx: &mut Context, + stopped_from_router: bool, +) { // Run the shutdown hook for this worker // TODO: pass stopped_from_router to the shutdown, a Worker may choose different strategy on // shutting down dependent workers based on that. E.g., TcpSender should stop TcpReceiver if diff --git a/implementations/rust/ockam/ockam_node/src/workers/echoer.rs b/implementations/rust/ockam/ockam_node/src/workers/echoer.rs index 13e2862d83a..b3ebdd30dfb 100644 --- a/implementations/rust/ockam/ockam_node/src/workers/echoer.rs +++ b/implementations/rust/ockam/ockam_node/src/workers/echoer.rs @@ -1,7 +1,7 @@ -use crate::Context; +use crate::{Context, Worker}; use ockam_core::compat::boxed::Box; use ockam_core::compat::string::String; -use ockam_core::{Result, Routed, Worker}; +use ockam_core::{Result, Routed}; /// A worker which accepts `String`s, and echos them (and the address) to /// the `debug!` log. @@ -11,7 +11,6 @@ pub struct Echoer; #[ockam_core::worker] impl Worker for Echoer { - type Context = Context; type Message = String; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_node/tests/metadata.rs b/implementations/rust/ockam/ockam_node/tests/metadata.rs index 3d24b2529fc..17bb3236941 100644 --- a/implementations/rust/ockam/ockam_node/tests/metadata.rs +++ b/implementations/rust/ockam/ockam_node/tests/metadata.rs @@ -1,25 +1,11 @@ -use ockam_core::{ - async_trait, route, AddressMetadata, DenyAll, Mailbox, Mailboxes, Processor, Result, -}; -use ockam_node::{Context, NullWorker, ProcessorBuilder, WorkerBuilder}; +use ockam_core::{route, AddressMetadata, DenyAll, Mailbox, Mailboxes, Result}; +use ockam_node::{Context, NullWorker, WorkerBuilder}; use std::string::ToString; use std::sync::Arc; -struct NullProcessor; - -#[async_trait] -impl Processor for NullProcessor { - type Context = Context; - - async fn process(&mut self, _ctx: &mut Context) -> Result { - tokio::task::yield_now().await; - Ok(true) - } -} - #[ockam_macros::test] async fn find_terminal_for_processor(context: &mut Context) -> Result<()> { - ProcessorBuilder::new(NullProcessor {}) + WorkerBuilder::new(NullWorker {}) .with_address("simple_processor") .start(context)?; @@ -27,7 +13,7 @@ async fn find_terminal_for_processor(context: &mut Context) -> Result<()> { .find_terminal_address(route!["simple_processor", "non-existing"].iter())? .is_none()); - ProcessorBuilder::new(NullProcessor {}) + WorkerBuilder::new(NullWorker {}) .with_terminal_address("terminal_processor") .start(context)?; @@ -46,7 +32,7 @@ async fn find_terminal_for_processor(context: &mut Context) -> Result<()> { #[ockam_macros::test] async fn find_terminal_for_processor_alias(context: &mut Context) -> Result<()> { - ProcessorBuilder::new(NullProcessor {}) + WorkerBuilder::new(NullWorker {}) .with_mailboxes(Mailboxes::new( Mailbox::new("main", None, Arc::new(DenyAll), Arc::new(DenyAll)), vec![Mailbox::new( @@ -84,7 +70,7 @@ async fn find_terminal_for_processor_alias(context: &mut Context) -> Result<()> #[ockam_macros::test] async fn provide_and_read_processor_address_metadata(context: &mut Context) -> Result<()> { - ProcessorBuilder::new(NullProcessor {}) + WorkerBuilder::new(NullWorker {}) .with_address("processor_address") .with_metadata_attribute("TEST_KEY", "TEST_VALUE") .with_metadata_attribute("TEST_KEY_2", "TEST_VALUE_2") diff --git a/implementations/rust/ockam/ockam_node/tests/tests.rs b/implementations/rust/ockam/ockam_node/tests/tests.rs index 46a04b319d7..edc44fafa61 100644 --- a/implementations/rust/ockam/ockam_node/tests/tests.rs +++ b/implementations/rust/ockam/ockam_node/tests/tests.rs @@ -7,9 +7,9 @@ use ockam_core::compat::{ }; use ockam_core::errcode::{Kind, Origin}; use ockam_core::{async_trait, Address, AllowAll, Any, Decodable, DenyAll, Message}; -use ockam_core::{route, Processor, Result, Routed, Worker}; +use ockam_core::{route, Result, Routed}; use ockam_node::compat::futures::FutureExt; -use ockam_node::{Context, MessageReceiveOptions, NodeBuilder}; +use ockam_node::{Context, MessageReceiveOptions, NodeBuilder, Worker}; use serde::{Deserialize, Serialize}; use std::sync::atomic::AtomicI8; use std::time::{SystemTime, UNIX_EPOCH}; @@ -74,16 +74,15 @@ struct SimpleWorker { #[async_trait] impl Worker for SimpleWorker { type Message = String; - type Context = Context; - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _context: &mut Context) -> Result<()> { self.initialize_was_called.store(true, Ordering::Relaxed); assert!(self.initialize_was_called.load(Ordering::Relaxed)); Ok(()) } - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, _context: &mut Context) -> Result<()> { self.shutdown_was_called.store(true, Ordering::Relaxed); assert!(self.initialize_was_called.load(Ordering::Relaxed)); assert!(self.shutdown_was_called.load(Ordering::Relaxed)); @@ -93,7 +92,7 @@ impl Worker for SimpleWorker { async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, msg: Routed, ) -> Result<()> { ctx.send(msg.return_route().clone(), msg.into_body()?).await @@ -163,58 +162,17 @@ struct FailingWorkerProcessor { #[async_trait] impl Worker for FailingWorkerProcessor { - type Context = Context; - type Message = String; - - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { - Err(ockam_core::Error::new(Origin::Core, Kind::Internal, "test")) - } - - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { - self.shutdown_was_called.store(true, Ordering::Relaxed); - Ok(()) - } - - async fn handle_message( - &mut self, - _ctx: &mut Self::Context, - _msg: Routed, - ) -> Result<()> { - Ok(()) - } -} - -#[allow(non_snake_case)] -#[ockam_macros::test] -async fn worker_initialize_fail_should_shutdown(ctx: &mut Context) -> Result<()> { - let shutdown_was_called = Arc::new(AtomicBool::new(false)); - let address = Address::from_string("failing_worker"); - let worker = FailingWorkerProcessor { - shutdown_was_called: shutdown_was_called.clone(), - }; - let res = ctx.start_worker(address.clone(), worker); - assert!(res.is_ok()); - sleep(Duration::new(1, 0)).await; - assert!(shutdown_was_called.load(Ordering::Relaxed)); - - assert!(!ctx.list_workers()?.contains(&address)); - - Ok(()) -} - -#[async_trait] -impl Processor for FailingWorkerProcessor { - type Context = Context; + type Message = (); - async fn process(&mut self, _ctx: &mut Self::Context) -> Result { + async fn process(&mut self, _ctx: &mut Context) -> Result { Ok(true) } - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _context: &mut Context) -> Result<()> { Err(ockam_core::Error::new(Origin::Core, Kind::Internal, "test")) } - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, _context: &mut Context) -> Result<()> { self.shutdown_was_called.store(true, Ordering::Relaxed); Ok(()) } @@ -228,7 +186,7 @@ async fn processor_initialize_fail_should_shutdown(ctx: &mut Context) -> Result< let processor = FailingWorkerProcessor { shutdown_was_called: shutdown_was_called.clone(), }; - let res = ctx.start_processor(address.clone(), processor); + let res = ctx.start_worker(address.clone(), processor); assert!(res.is_ok()); sleep(Duration::new(1, 0)).await; assert!(shutdown_was_called.load(Ordering::Relaxed)); @@ -240,8 +198,8 @@ async fn processor_initialize_fail_should_shutdown(ctx: &mut Context) -> Result< struct DummyProcessor; #[async_trait] -impl Processor for DummyProcessor { - type Context = Context; +impl Worker for DummyProcessor { + type Message = (); async fn process(&mut self, _ctx: &mut Context) -> Result { tokio::task::yield_now().await; @@ -251,10 +209,8 @@ impl Processor for DummyProcessor { #[ockam_macros::test] async fn starting_processor_with_dup_address_should_fail(ctx: &mut Context) -> Result<()> { - ctx.start_processor("dummy_processor", DummyProcessor)?; - assert!(ctx - .start_processor("dummy_processor", DummyProcessor) - .is_err()); + ctx.start_worker("dummy_processor", DummyProcessor)?; + assert!(ctx.start_worker("dummy_processor", DummyProcessor).is_err()); Ok(()) } @@ -265,17 +221,17 @@ struct CountingProcessor { } #[async_trait] -impl Processor for CountingProcessor { - type Context = Context; +impl Worker for CountingProcessor { + type Message = (); - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _context: &mut Context) -> Result<()> { self.initialize_was_called.store(true, Ordering::Relaxed); assert!(self.initialize_was_called.load(Ordering::Relaxed)); Ok(()) } - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, _context: &mut Context) -> Result<()> { self.shutdown_was_called.store(true, Ordering::Relaxed); assert!(self.initialize_was_called.load(Ordering::Relaxed)); assert!(self.shutdown_was_called.load(Ordering::Relaxed)); @@ -283,7 +239,7 @@ impl Processor for CountingProcessor { Ok(()) } - async fn process(&mut self, _ctx: &mut Self::Context) -> Result { + async fn process(&mut self, _ctx: &mut Context) -> Result { let val = self.run_called_count.fetch_add(1, Ordering::Relaxed); Ok(val < 4) @@ -309,7 +265,7 @@ async fn counting_processor__run_node_lifecycle__processor_lifecycle_should_be_f run_called_count: run_called_count_clone, }; - ctx.start_processor("counting_processor", processor)?; + ctx.start_worker("counting_processor", processor)?; sleep(Duration::from_secs(1)).await; assert!(initialize_was_called.load(Ordering::Relaxed)); @@ -325,21 +281,21 @@ struct WaitingProcessor { } #[async_trait] -impl Processor for WaitingProcessor { - type Context = Context; +impl Worker for WaitingProcessor { + type Message = (); - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _context: &mut Context) -> Result<()> { self.initialize_was_called.store(true, Ordering::Relaxed); Ok(()) } - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, _context: &mut Context) -> Result<()> { self.shutdown_was_called.store(true, Ordering::Relaxed); assert!(self.initialize_was_called.load(Ordering::Relaxed)); Ok(()) } - async fn process(&mut self, _ctx: &mut Self::Context) -> Result { + async fn process(&mut self, _ctx: &mut Context) -> Result { sleep(Duration::from_secs(10)).await; Ok(true) } @@ -356,7 +312,7 @@ async fn waiting_processor__shutdown__should_be_interrupted(ctx: &mut Context) - shutdown_was_called: shutdown_was_called.clone(), }; - ctx.start_processor("waiting_processor", processor)?; + ctx.start_worker("waiting_processor", processor)?; sleep(Duration::from_secs(1)).await; ctx.stop_address(&"waiting_processor".into())?; @@ -373,17 +329,17 @@ struct MessagingProcessor { } #[async_trait] -impl Processor for MessagingProcessor { - type Context = Context; +impl Worker for MessagingProcessor { + type Message = (); - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _context: &mut Context) -> Result<()> { self.initialize_was_called.store(true, Ordering::Relaxed); assert!(self.initialize_was_called.load(Ordering::Relaxed)); Ok(()) } - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, _context: &mut Context) -> Result<()> { self.shutdown_was_called.store(true, Ordering::Relaxed); assert!(self.initialize_was_called.load(Ordering::Relaxed)); assert!(self.shutdown_was_called.load(Ordering::Relaxed)); @@ -391,7 +347,7 @@ impl Processor for MessagingProcessor { Ok(()) } - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { let msg = ctx.receive::().await.unwrap(); let route = msg.return_route().clone(); let body = msg.into_body()?; @@ -424,7 +380,7 @@ async fn waiting_processor__messaging__should_work(ctx: &mut Context) -> Result< shutdown_was_called: shutdown_was_called_clone, }; - ctx.start_processor_with_access_control("messaging_processor", processor, AllowAll, AllowAll)?; + ctx.start_worker_with_access_control("messaging_processor", processor, AllowAll, AllowAll)?; sleep(Duration::from_millis(250)).await; let msg: String = ctx @@ -454,7 +410,6 @@ struct BadWorker; #[ockam_core::worker] impl Worker for BadWorker { - type Context = Context; type Message = (); /// This shutdown function takes _way_ too long to complete @@ -480,7 +435,6 @@ struct SendReceiveWorker; #[async_trait] impl Worker for SendReceiveWorker { - type Context = Context; type Message = Any; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { @@ -528,19 +482,18 @@ struct DummyWorker; #[async_trait] impl Worker for DummyWorker { type Message = String; - type Context = Context; - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _context: &mut Context) -> Result<()> { Ok(()) } - async fn shutdown(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, _context: &mut Context) -> Result<()> { Ok(()) } async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, msg: Routed, ) -> Result<()> { ctx.send(msg.return_route().clone(), msg.into_body()?).await @@ -562,12 +515,11 @@ struct CountingErrorWorker { #[async_trait] impl Worker for CountingErrorWorker { - type Context = Context; type Message = Any; async fn handle_message( &mut self, - _context: &mut Self::Context, + _context: &mut Context, _msg: Routed, ) -> Result<()> { let _ = self.counter.fetch_add(1, Ordering::Relaxed); diff --git a/implementations/rust/ockam/ockam_transport_ble/src/router/mod.rs b/implementations/rust/ockam/ockam_transport_ble/src/router/mod.rs index d3f8dbeec72..61306aae42b 100644 --- a/implementations/rust/ockam/ockam_transport_ble/src/router/mod.rs +++ b/implementations/rust/ockam/ockam_transport_ble/src/router/mod.rs @@ -5,8 +5,8 @@ use ockam_core::{ compat::{boxed::Box, collections::BTreeMap, vec::Vec}, AllowAll, Any, Mailbox, Mailboxes, }; -use ockam_core::{Address, Decodable, LocalMessage, Message, Result, Routed, Worker}; -use ockam_node::{Context, WorkerBuilder}; +use ockam_core::{Address, Decodable, LocalMessage, Message, Result, Routed}; +use ockam_node::{Context, Worker, WorkerBuilder}; use ockam_transport_core::TransportError; use serde::{Deserialize, Serialize}; use std::sync::Arc; @@ -104,7 +104,6 @@ impl BleRouter { #[async_trait] impl Worker for BleRouter { - type Context = Context; type Message = Any; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_transport_ble/src/workers/listener.rs b/implementations/rust/ockam/ockam_transport_ble/src/workers/listener.rs index e0cc225fc11..e14b6f68b04 100644 --- a/implementations/rust/ockam/ockam_transport_ble/src/workers/listener.rs +++ b/implementations/rust/ockam/ockam_transport_ble/src/workers/listener.rs @@ -1,6 +1,6 @@ use ockam_core::compat::boxed::Box; -use ockam_core::{async_trait, Address, AllowAll, Processor, Result}; -use ockam_node::Context; +use ockam_core::{async_trait, Address, AllowAll, Result}; +use ockam_node::{Context, Worker}; use crate::driver::AsyncStream; use crate::driver::{BleEvent, BleServer}; @@ -38,7 +38,7 @@ where "BleListenProcessor::start Starting processor with address: {:?}", waddr ); - ctx.start_processor_with_access_control( + ctx.start_worker_with_access_control( waddr, processor, AllowAll, // FIXME: @ac AllowAll, // FIXME: @ac )?; @@ -48,13 +48,13 @@ where } #[async_trait] -impl Processor for BleListenProcessor +impl Worker for BleListenProcessor where A: BleServerDriver + BleStreamDriver + Send + 'static, { - type Context = Context; + type Message = (); - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { if self.inner.is_none() { return Ok(true); } diff --git a/implementations/rust/ockam/ockam_transport_ble/src/workers/receiver.rs b/implementations/rust/ockam/ockam_transport_ble/src/workers/receiver.rs index 5ebb827694e..2fc6765d5d2 100644 --- a/implementations/rust/ockam/ockam_transport_ble/src/workers/receiver.rs +++ b/implementations/rust/ockam/ockam_transport_ble/src/workers/receiver.rs @@ -1,7 +1,7 @@ use ockam_core::async_trait; use ockam_core::compat::boxed::Box; -use ockam_core::{Address, Decodable, LocalMessage, Processor, Result, TransportMessage}; -use ockam_node::Context; +use ockam_core::{Address, Decodable, LocalMessage, Result, TransportMessage}; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; use crate::driver::Source; @@ -32,11 +32,11 @@ where } #[async_trait] -impl Processor for BleRecvProcessor +impl Worker for BleRecvProcessor where A: BleStreamDriver + Send + 'static, { - type Context = Context; + type Message = (); async fn process(&mut self, ctx: &mut Context) -> Result { let mut buffer = [0_u8; crate::driver::MAX_OCKAM_MESSAGE_LENGTH]; diff --git a/implementations/rust/ockam/ockam_transport_ble/src/workers/sender.rs b/implementations/rust/ockam/ockam_transport_ble/src/workers/sender.rs index e0c434f1061..53247f674ea 100644 --- a/implementations/rust/ockam/ockam_transport_ble/src/workers/sender.rs +++ b/implementations/rust/ockam/ockam_transport_ble/src/workers/sender.rs @@ -1,8 +1,6 @@ use ockam_core::compat::{boxed::Box, string::String, vec::Vec}; -use ockam_core::{ - async_trait, Address, AllowAll, Encodable, Result, Routed, TransportMessage, Worker, -}; -use ockam_node::Context; +use ockam_core::{async_trait, Address, AllowAll, Encodable, Result, Routed, TransportMessage}; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; use crate::driver::{AsyncStream, BleStreamDriver, PacketBuffer, Sink, Source}; @@ -79,17 +77,16 @@ impl Worker for BleSendWorker where A: BleStreamDriver + Send + 'static, { - type Context = Context; type Message = TransportMessage; - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { debug!("initialize for peer: {:?}", self.peer); if let Some(rx_stream) = self.rx_stream.take() { let rx_addr = Address::random_local(); let receiver = BleRecvProcessor::new(rx_stream, format!("{}#{}", crate::BLE, self.peer).into()); - ctx.start_processor_with_access_control( + ctx.start_worker_with_access_control( rx_addr.clone(), receiver, AllowAll, // FIXME: @ac diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/portal/inlet_listener.rs b/implementations/rust/ockam/ockam_transport_tcp/src/portal/inlet_listener.rs index 4a47b9d148b..ff2ffc28054 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/portal/inlet_listener.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/portal/inlet_listener.rs @@ -7,8 +7,8 @@ use ockam_core::compat::net::SocketAddr; use ockam_core::compat::sync::{Arc, RwLock as SyncRwLock}; use ockam_core::errcode::{Kind, Origin}; use ockam_core::{async_trait, compat::boxed::Box, Result}; -use ockam_core::{Address, Processor, Route}; -use ockam_node::Context; +use ockam_core::{Address, Route}; +use ockam_node::{Context, Worker}; use ockam_transport_core::{HostnamePort, TransportError}; use rustls::pki_types::CertificateDer; use std::io::BufReader; @@ -70,7 +70,7 @@ impl TcpInletListenProcessor { let inlet_shared_state = Arc::new(SyncRwLock::new(inlet_shared_state)); let processor = Self::new(registry, inner, inlet_shared_state.clone(), options); - ctx.start_processor(processor_address.clone(), processor)?; + ctx.start_worker(processor_address.clone(), processor)?; Ok(TcpInlet::new_regular( socket_addr, @@ -155,11 +155,11 @@ impl TcpInletListenProcessor { const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2 * 60); #[async_trait] -impl Processor for TcpInletListenProcessor { - type Context = Context; +impl Worker for TcpInletListenProcessor { + type Message = (); #[instrument(skip_all, name = "TcpInletListenProcessor::initialize")] - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { self.registry .add_inlet_listener_processor(ctx.primary_address()); @@ -167,7 +167,7 @@ impl Processor for TcpInletListenProcessor { } #[instrument(skip_all, name = "TcpInletListenProcessor::shutdown")] - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.registry .remove_inlet_listener_processor(ctx.primary_address()); @@ -175,7 +175,7 @@ impl Processor for TcpInletListenProcessor { } #[instrument(skip_all, name = "TcpInletListenProcessor::process")] - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { let (stream, socket_addr) = self.inner.accept().await.map_err(TransportError::from)?; stream.set_nodelay(true).map_err(TransportError::from)?; diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/portal/interceptor.rs b/implementations/rust/ockam/ockam_transport_tcp/src/portal/interceptor.rs index 4826e34420e..c3f474f4ca7 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/portal/interceptor.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/portal/interceptor.rs @@ -3,9 +3,9 @@ use ockam_core::flow_control::{FlowControlId, FlowControlOutgoingAccessControl, use ockam_core::{ async_trait, route, Address, AllowOnwardAddress, AllowSourceAddress, Any, AnyIncomingAccessControl, AnyOutgoingAccessControl, Encodable, IncomingAccessControl, - LocalInfo, LocalMessage, NeutralMessage, OutgoingAccessControl, Route, Routed, Worker, + LocalInfo, LocalMessage, NeutralMessage, OutgoingAccessControl, Route, Routed, }; -use ockam_node::{Context, WorkerBuilder}; +use ockam_node::{Context, Worker, WorkerBuilder}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tracing::{debug, trace}; @@ -88,7 +88,6 @@ impl PortalOutletInterceptor { #[ockam_core::worker] impl Worker for PortalOutletInterceptor { type Message = Any; - type Context = Context; async fn handle_message( &mut self, @@ -183,11 +182,10 @@ impl PortalInletInterceptor { #[ockam_core::worker] impl Worker for PortalInletInterceptor { type Message = Any; - type Context = Context; async fn handle_message( &mut self, - context: &mut Self::Context, + context: &mut Context, message: Routed, ) -> ockam_core::Result<()> { tracing::trace!("received message"); @@ -249,7 +247,6 @@ pub struct PortalInterceptorWorker { #[async_trait] impl Worker for PortalInterceptorWorker { type Message = NeutralMessage; - type Context = Context; async fn shutdown(&mut self, _context: &mut Context) -> ockam_core::Result<()> { //TODO: send disconnect to everyone? diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/portal/outlet_listener.rs b/implementations/rust/ockam/ockam_transport_tcp/src/portal/outlet_listener.rs index 7bc2b750bed..c9f26199fc2 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/portal/outlet_listener.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/portal/outlet_listener.rs @@ -1,9 +1,9 @@ use crate::portal::addresses::{Addresses, PortalType}; use crate::{portal::TcpPortalWorker, PortalMessage, TcpOutletOptions, TcpRegistry}; use ockam_core::{ - async_trait, Address, DenyAll, NeutralMessage, Result, Routed, SecureChannelLocalInfo, Worker, + async_trait, Address, DenyAll, NeutralMessage, Result, Routed, SecureChannelLocalInfo, }; -use ockam_node::{Context, WorkerBuilder}; +use ockam_node::{Context, Worker, WorkerBuilder}; use ockam_transport_core::{HostnamePort, TransportError}; use tracing::{debug, instrument}; @@ -53,11 +53,10 @@ impl TcpOutletListenWorker { #[async_trait] impl Worker for TcpOutletListenWorker { - type Context = Context; type Message = NeutralMessage; #[instrument(skip_all, name = "TcpOutletListenWorker::initialize")] - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { self.registry .add_outlet_listener_worker(ctx.primary_address()); @@ -65,7 +64,7 @@ impl Worker for TcpOutletListenWorker { } #[instrument(skip_all, name = "TcpOutletListenWorker::shutdown")] - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.registry .remove_outlet_listener_worker(ctx.primary_address()); @@ -75,7 +74,7 @@ impl Worker for TcpOutletListenWorker { #[instrument(skip_all, name = "TcpOutletListenWorker::handle_message")] async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, msg: Routed, ) -> Result<()> { let their_identifier = SecureChannelLocalInfo::find_info(msg.local_message()) diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/portal/portal_receiver.rs b/implementations/rust/ockam/ockam_transport_tcp/src/portal/portal_receiver.rs index 53375759e24..de77f369c76 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/portal/portal_receiver.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/portal/portal_receiver.rs @@ -4,8 +4,8 @@ use ockam_core::compat::vec::Vec; use ockam_core::{ async_trait, Encodable, LocalMessage, OpenTelemetryContext, Route, OCKAM_TRACER_NAME, }; -use ockam_core::{route, Processor, Result}; -use ockam_node::Context; +use ockam_core::{route, Result}; +use ockam_node::{Context, Worker}; use opentelemetry::global; use opentelemetry::trace::Tracer; use tokio::io::AsyncRead; @@ -49,11 +49,11 @@ impl TcpPortalRecvProcessor { } #[async_trait] -impl Processor for TcpPortalRecvProcessor { - type Context = Context; +impl Worker for TcpPortalRecvProcessor { + type Message = (); #[instrument(skip_all, name = "TcpPortalRecvProcessor::initialize")] - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { self.registry .add_portal_receiver_processor(ctx.primary_address()); @@ -61,7 +61,7 @@ impl Processor for TcpPortalRecvPr } #[instrument(skip_all, name = "TcpPortalRecvProcessor::shutdown")] - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.registry .remove_portal_receiver_processor(ctx.primary_address()); diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/portal/portal_worker.rs b/implementations/rust/ockam/ockam_transport_tcp/src/portal/portal_worker.rs index 9621300d622..91757e3f03e 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/portal/portal_worker.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/portal/portal_worker.rs @@ -8,8 +8,8 @@ use ockam_core::{ async_trait, AllowOnwardAddress, AllowSourceAddress, Decodable, DenyAll, IncomingAccessControl, LocalInfoIdentifier, Mailbox, Mailboxes, OutgoingAccessControl, SecureChannelLocalInfo, }; -use ockam_core::{Any, Result, Route, Routed, Worker}; -use ockam_node::{Context, ProcessorBuilder, WorkerBuilder}; +use ockam_core::{Any, Result, Route, Routed}; +use ockam_node::{Context, Worker, WorkerBuilder}; use ockam_transport_core::{HostnamePort, TransportError}; use std::time::Duration; use tokio::io::{AsyncRead, AsyncWriteExt, ReadHalf, WriteHalf}; @@ -252,7 +252,7 @@ impl TcpPortalWorker { Arc::new(AllowOnwardAddress(self.addresses.sender_internal.clone())), ); - ProcessorBuilder::new(receiver) + WorkerBuilder::new(receiver) .with_mailboxes(Mailboxes::new(remote, vec![internal])) .start(ctx)?; @@ -401,11 +401,10 @@ impl TcpPortalWorker { #[async_trait] impl Worker for TcpPortalWorker { - type Context = Context; type Message = Any; #[instrument(skip_all, name = "TcpPortalWorker::initialize")] - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { let state = self.clone_state(); match state { @@ -431,7 +430,7 @@ impl Worker for TcpPortalWorker { } #[instrument(skip_all, name = "TcpPortalWorker::shutdown")] - async fn shutdown(&mut self, _ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, _ctx: &mut Context) -> Result<()> { self.registry .remove_portal_worker(&self.addresses.sender_remote); diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/ebpf_support.rs b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/ebpf_support.rs index c074de2aa34..1100bbaa0a5 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/ebpf_support.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/ebpf_support.rs @@ -164,7 +164,7 @@ impl TcpTransportEbpfSupport { *tcp_packet_writer_lock = Some(tcp_packet_writer.create_new_box()); - ctx.start_processor(self.raw_socket_processor_address.clone(), processor)?; + ctx.start_worker(self.raw_socket_processor_address.clone(), processor)?; info!("Started RawSocket for protocol: {}", self.ip_proto); diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/privileged_portals.rs b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/privileged_portals.rs index 9e3fd34849e..86f76f7cdee 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/privileged_portals.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/privileged_portals.rs @@ -9,7 +9,7 @@ use nix::unistd::Uid; use ockam_core::compat::sync::{Arc, RwLock as SyncRwLock}; use ockam_core::{Address, DenyAll, Result, Route}; use ockam_node::compat::asynchronous::resolve_peer; -use ockam_node::{ProcessorBuilder, WorkerBuilder}; +use ockam_node::WorkerBuilder; use ockam_transport_core::{HostnamePort, TransportError}; use std::net::IpAddr; use tokio::net::TcpListener; @@ -127,7 +127,7 @@ impl TcpTransport { .start(self.ctx())?; let internal_worker = InternalProcessor::new_inlet(receiver, inlet_info); - ProcessorBuilder::new(internal_worker) + WorkerBuilder::new(internal_worker) .with_address(internal_worker_address.clone()) .with_incoming_access_control(DenyAll) .with_outgoing_access_control_arc(options.outgoing_access_control) @@ -209,7 +209,7 @@ impl TcpTransport { .start(self.ctx())?; let internal_worker = InternalProcessor::new_outlet(receiver, outlet_info); - ProcessorBuilder::new(internal_worker) + WorkerBuilder::new(internal_worker) .with_address(internal_worker_address) .with_incoming_access_control(DenyAll) .with_outgoing_access_control_arc(options.outgoing_access_control) diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/internal_processor.rs b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/internal_processor.rs index bcd15dcc3cb..2b99e230143 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/internal_processor.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/internal_processor.rs @@ -2,10 +2,9 @@ use crate::privileged_portal::packet::RawSocketReadResult; use crate::privileged_portal::{Inlet, InletConnection, OckamPortalPacket, Outlet, PortalMode}; use log::{debug, trace, warn}; use ockam_core::{ - async_trait, cbor_encode_preallocate, route, LocalInfoIdentifier, LocalMessage, Processor, - Result, + async_trait, cbor_encode_preallocate, route, LocalInfoIdentifier, LocalMessage, Result, }; -use ockam_node::Context; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; use rand::random; use std::net::Ipv4Addr; @@ -60,10 +59,10 @@ impl InternalProcessor { } #[async_trait] -impl Processor for InternalProcessor { - type Context = Context; +impl Worker for InternalProcessor { + type Message = (); - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { let raw_socket_read_result = match self.receiver.recv().await { Some(raw_socket_read_result) => raw_socket_read_result, None => return Ok(false), diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/raw_socket_processor.rs b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/raw_socket_processor.rs index b8d56a4a7dc..0ed6c0c06d3 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/raw_socket_processor.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/raw_socket_processor.rs @@ -4,8 +4,8 @@ use crate::privileged_portal::{ TcpPacketWriter, }; use log::trace; -use ockam_core::{async_trait, Processor, Result}; -use ockam_node::Context; +use ockam_core::{async_trait, Result}; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; /// Processor responsible for receiving all data with OCKAM_TCP_PORTAL_PROTOCOL on the machine @@ -76,10 +76,10 @@ impl RawSocketProcessor { } #[async_trait] -impl Processor for RawSocketProcessor { - type Context = Context; +impl Worker for RawSocketProcessor { + type Message = (); - async fn process(&mut self, _ctx: &mut Self::Context) -> Result { + async fn process(&mut self, _ctx: &mut Context) -> Result { let raw_socket_read_result = self.read_packet().await?; if let Some(inlet) = self diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/remote_worker.rs b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/remote_worker.rs index c6a8dfb0120..6732648a59e 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/remote_worker.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/privileged_portal/workers/remote_worker.rs @@ -5,9 +5,9 @@ use crate::privileged_portal::{ }; use log::{debug, trace}; use ockam_core::{ - async_trait, Any, LocalInfoIdentifier, Result, Route, Routed, SecureChannelLocalInfo, Worker, + async_trait, Any, LocalInfoIdentifier, Result, Route, Routed, SecureChannelLocalInfo, }; -use ockam_node::Context; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; use std::net::Ipv4Addr; use std::sync::{Arc, RwLock}; @@ -165,11 +165,10 @@ impl RemoteWorker { #[async_trait] impl Worker for RemoteWorker { type Message = Any; - type Context = Context; async fn handle_message( &mut self, - _ctx: &mut Self::Context, + _ctx: &mut Context, msg: Routed, ) -> Result<()> { let their_identifier = SecureChannelLocalInfo::find_info(msg.local_message()) diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/workers/listener.rs b/implementations/rust/ockam/ockam_transport_tcp/src/workers/listener.rs index 7ea6a71d0da..89397127a1b 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/workers/listener.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/workers/listener.rs @@ -1,8 +1,8 @@ use crate::workers::{Addresses, TcpRecvProcessor}; use crate::{TcpConnectionMode, TcpListenerInfo, TcpListenerOptions, TcpRegistry, TcpSendWorker}; use ockam_core::{async_trait, compat::net::SocketAddr}; -use ockam_core::{Address, Processor, Result}; -use ockam_node::{Context, ProcessorBuilder, WorkerShutdownPriority}; +use ockam_core::{Address, Result}; +use ockam_node::{Context, Worker, WorkerBuilder, WorkerShutdownPriority}; use ockam_transport_core::TransportError; use tokio::net::TcpListener; use tracing::{debug, instrument}; @@ -43,7 +43,7 @@ impl TcpListenProcessor { options, }; - ProcessorBuilder::new(processor) + WorkerBuilder::new(processor) .with_address(address.clone()) .with_shutdown_priority(WorkerShutdownPriority::Priority5) .start(ctx)?; @@ -53,8 +53,8 @@ impl TcpListenProcessor { } #[async_trait] -impl Processor for TcpListenProcessor { - type Context = Context; +impl Worker for TcpListenProcessor { + type Message = (); #[instrument(skip_all, name = "TcpListenProcessor::initialize")] async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { @@ -68,7 +68,7 @@ impl Processor for TcpListenProcessor { } #[instrument(skip_all, name = "TcpListenProcessor::shutdown")] - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.registry .remove_listener_processor(ctx.primary_address()); @@ -76,7 +76,7 @@ impl Processor for TcpListenProcessor { } #[instrument(skip_all, name = "TcpListenProcessor::process")] - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { debug!("Waiting for incoming TCP connection..."); // Wait for an incoming connection diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/workers/receiver.rs b/implementations/rust/ockam/ockam_transport_tcp/src/workers/receiver.rs index 1499d11e436..5212370b955 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/workers/receiver.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/workers/receiver.rs @@ -8,12 +8,12 @@ use core::fmt::Display; use ockam_core::compat::net::SocketAddr; use ockam_core::compat::sync::Arc; use ockam_core::flow_control::FlowControlId; +use ockam_core::Result; use ockam_core::{ async_trait, AllowOnwardAddress, DenyAll, LocalMessage, Mailbox, Mailboxes, OutgoingAccessControl, }; -use ockam_core::{Processor, Result}; -use ockam_node::{Context, ProcessorBuilder, WorkerShutdownPriority}; +use ockam_node::{Context, Worker, WorkerBuilder, WorkerShutdownPriority}; use ockam_transport_core::TransportError; use tokio::{io::AsyncReadExt, net::tcp::OwnedReadHalf}; use tracing::{debug, instrument, trace}; @@ -92,7 +92,7 @@ impl TcpRecvProcessor { addresses.sender_internal_address().clone(), )), ); - ProcessorBuilder::new(receiver) + WorkerBuilder::new(receiver) .with_mailboxes(Mailboxes::new(mailbox, vec![internal])) .with_shutdown_priority(WorkerShutdownPriority::Priority1) .start(ctx)?; @@ -116,8 +116,8 @@ impl TcpRecvProcessor { } #[async_trait] -impl Processor for TcpRecvProcessor { - type Context = Context; +impl Worker for TcpRecvProcessor { + type Message = (); #[instrument(skip_all, name = "TcpRecvProcessor::initialize")] async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { @@ -157,7 +157,7 @@ impl Processor for TcpRecvProcessor { } #[instrument(skip_all, name = "TcpRecvProcessor::shutdown")] - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.registry .remove_receiver_processor(ctx.primary_address()); diff --git a/implementations/rust/ockam/ockam_transport_tcp/src/workers/sender.rs b/implementations/rust/ockam/ockam_transport_tcp/src/workers/sender.rs index 085481433ba..fbad12b86cb 100644 --- a/implementations/rust/ockam/ockam_transport_tcp/src/workers/sender.rs +++ b/implementations/rust/ockam/ockam_transport_tcp/src/workers/sender.rs @@ -6,8 +6,8 @@ use ockam_core::{ compat::{net::SocketAddr, sync::Arc}, AddressMetadata, AllowAll, AllowSourceAddress, DenyAll, LocalMessage, }; -use ockam_core::{Any, Decodable, Mailbox, Mailboxes, Message, Result, Routed, Worker}; -use ockam_node::{Context, WorkerBuilder, WorkerShutdownPriority}; +use ockam_core::{Any, Decodable, Mailbox, Mailboxes, Message, Result, Routed}; +use ockam_node::{Context, Worker, WorkerBuilder, WorkerShutdownPriority}; use crate::transport_message::TcpTransportMessage; use ockam_transport_core::TransportError; @@ -162,11 +162,10 @@ impl TcpSendWorker { #[async_trait] impl Worker for TcpSendWorker { - type Context = Context; type Message = Any; #[instrument(skip_all, name = "TcpSendWorker::initialize")] - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { self.registry.add_sender_worker(TcpSenderInfo::new( self.addresses.sender_address().clone(), self.addresses.receiver_address().clone(), @@ -195,7 +194,7 @@ impl Worker for TcpSendWorker { } #[instrument(skip_all, name = "TcpSendWorker::shutdown")] - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.registry .remove_sender_worker(self.addresses.sender_address()); diff --git a/implementations/rust/ockam/ockam_transport_udp/src/puncture/negotiation/listener.rs b/implementations/rust/ockam/ockam_transport_udp/src/puncture/negotiation/listener.rs index bc572bdbe96..d53d3b9dbe1 100644 --- a/implementations/rust/ockam/ockam_transport_udp/src/puncture/negotiation/listener.rs +++ b/implementations/rust/ockam/ockam_transport_udp/src/puncture/negotiation/listener.rs @@ -5,8 +5,8 @@ use crate::puncture::negotiation::options::UdpPunctureNegotiationListenerOptions use crate::puncture::rendezvous_service::RendezvousClient; use crate::{UdpBindArguments, UdpBindOptions, UdpPuncture, UdpPunctureOptions, UdpTransport}; use ockam_core::flow_control::FlowControlId; -use ockam_core::{async_trait, Address, AllowAll, DenyAll, Result, Route, Routed, Worker}; -use ockam_node::{Context, WorkerBuilder}; +use ockam_core::{async_trait, Address, AllowAll, DenyAll, Result, Route, Routed}; +use ockam_node::{Context, Worker, WorkerBuilder}; use tracing::{error, info}; /// UDP puncture listener @@ -119,11 +119,10 @@ impl UdpPunctureNegotiationListener { #[async_trait] impl Worker for UdpPunctureNegotiationListener { type Message = UdpPunctureNegotiationMessageInitiate; - type Context = Context; async fn handle_message( &mut self, - ctx: &mut Self::Context, + ctx: &mut Context, msg: Routed, ) -> Result<()> { info!("Received a UDP puncture request"); diff --git a/implementations/rust/ockam/ockam_transport_udp/src/puncture/puncture/receiver.rs b/implementations/rust/ockam/ockam_transport_udp/src/puncture/puncture/receiver.rs index 8b36c205cc4..0ddf2236d27 100644 --- a/implementations/rust/ockam/ockam_transport_udp/src/puncture/puncture/receiver.rs +++ b/implementations/rust/ockam/ockam_transport_udp/src/puncture/puncture/receiver.rs @@ -6,9 +6,9 @@ use crate::{PunctureError, UdpBind, UDP}; use ockam_core::compat::sync::Arc; use ockam_core::{ route, Address, AllowAll, AllowSourceAddress, Any, Decodable, DenyAll, LocalMessage, Mailbox, - Mailboxes, Result, Route, Routed, Worker, + Mailboxes, Result, Route, Routed, }; -use ockam_node::{Context, DelayedEvent, WorkerBuilder}; +use ockam_node::{Context, DelayedEvent, Worker, WorkerBuilder}; use std::time::{Duration, Instant}; use tokio::sync::broadcast::Sender; use tracing::log::warn; @@ -261,13 +261,12 @@ impl UdpPunctureReceiverWorker { #[ockam_core::worker] impl Worker for UdpPunctureReceiverWorker { type Message = Any; - type Context = Context; - async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _context: &mut Context) -> Result<()> { self.heartbeat.schedule(Duration::ZERO) } - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { self.heartbeat.cancel(); _ = ctx.stop_address(self.addresses.sender_address()); diff --git a/implementations/rust/ockam/ockam_transport_udp/src/puncture/puncture/sender.rs b/implementations/rust/ockam/ockam_transport_udp/src/puncture/puncture/sender.rs index b17e88cb56f..a1eb666b6ce 100644 --- a/implementations/rust/ockam/ockam_transport_udp/src/puncture/puncture/sender.rs +++ b/implementations/rust/ockam/ockam_transport_udp/src/puncture/puncture/sender.rs @@ -1,8 +1,8 @@ use crate::puncture::puncture::message::PunctureMessage; use crate::puncture::puncture::notification::{wait_for_puncture, UdpPunctureNotification}; use crate::PunctureError; -use ockam_core::{Any, Encodable, LocalMessage, Result, Route, Routed, Worker}; -use ockam_node::Context; +use ockam_core::{Any, Encodable, LocalMessage, Result, Route, Routed}; +use ockam_node::{Context, Worker}; use std::time::Duration; use tokio::sync::broadcast::Receiver; use tracing::trace; @@ -53,9 +53,8 @@ impl UdpPunctureSenderWorker { #[ockam_core::worker] impl Worker for UdpPunctureSenderWorker { type Message = Any; - type Context = Context; - async fn initialize(&mut self, _ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, _ctx: &mut Context) -> Result<()> { self.peer_route = Some(wait_for_puncture(&mut self.notify_puncture_open_receiver, Duration::MAX).await?); diff --git a/implementations/rust/ockam/ockam_transport_udp/src/puncture/rendezvous_service/rendezvous.rs b/implementations/rust/ockam/ockam_transport_udp/src/puncture/rendezvous_service/rendezvous.rs index dd81c6c2f8c..9bffebd8f9c 100644 --- a/implementations/rust/ockam/ockam_transport_udp/src/puncture/rendezvous_service/rendezvous.rs +++ b/implementations/rust/ockam/ockam_transport_udp/src/puncture/rendezvous_service/rendezvous.rs @@ -2,8 +2,8 @@ use crate::{ puncture::rendezvous_service::{RendezvousRequest, RendezvousResponse}, UDP, }; -use ockam_core::{async_trait, Address, Result, Route, Routed, Worker}; -use ockam_node::Context; +use ockam_core::{async_trait, Address, Result, Route, Routed}; +use ockam_node::{Context, Worker}; use tracing::{debug, info, warn}; /// Rendezvous Service allows other nodes to discover their public IP address and port via UDP. @@ -74,7 +74,6 @@ impl RendezvousServiceWorker { #[async_trait] impl Worker for RendezvousServiceWorker { type Message = RendezvousRequest; - type Context = Context; async fn handle_message( &mut self, diff --git a/implementations/rust/ockam/ockam_transport_udp/src/transport/bind.rs b/implementations/rust/ockam/ockam_transport_udp/src/transport/bind.rs index e11aeb79d5f..2bbab0f30e7 100644 --- a/implementations/rust/ockam/ockam_transport_udp/src/transport/bind.rs +++ b/implementations/rust/ockam/ockam_transport_udp/src/transport/bind.rs @@ -7,7 +7,7 @@ use ockam_core::errcode::{Kind, Origin}; use ockam_core::flow_control::FlowControlId; use ockam_core::{Address, AllowAll, DenyAll, Error, Result}; use ockam_node::compat::asynchronous::resolve_peer; -use ockam_node::{ProcessorBuilder, WorkerBuilder, WorkerShutdownPriority}; +use ockam_node::{WorkerBuilder, WorkerShutdownPriority}; use ockam_transport_core::{parse_socket_addr, HostnamePort, TransportError}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use tokio::net::UdpSocket; @@ -134,7 +134,7 @@ impl UdpTransport { options.size_options.pending_messages_per_peer, options.size_options.max_on_the_wire_packet_size, ); - ProcessorBuilder::new(receiver) + WorkerBuilder::new(receiver) .with_address(addresses.receiver_address().clone()) .with_incoming_access_control(DenyAll) .with_outgoing_access_control_arc(receiver_outgoing_access_control) diff --git a/implementations/rust/ockam/ockam_transport_udp/src/workers/receiver.rs b/implementations/rust/ockam/ockam_transport_udp/src/workers/receiver.rs index 0ebe66dd130..90131057480 100644 --- a/implementations/rust/ockam/ockam_transport_udp/src/workers/receiver.rs +++ b/implementations/rust/ockam/ockam_transport_udp/src/workers/receiver.rs @@ -3,8 +3,8 @@ use crate::messages::UdpTransportMessage; use crate::workers::pending_messages::PendingRoutingMessageStorage; use crate::UDP; use ockam_core::errcode::{Kind, Origin}; -use ockam_core::{async_trait, Address, Error, LocalMessage, Processor, Result, RouteBuilder}; -use ockam_node::Context; +use ockam_core::{async_trait, Address, Error, LocalMessage, Result, RouteBuilder}; +use ockam_node::{Context, Worker}; use std::net::SocketAddr; use tracing::{trace, warn}; @@ -50,10 +50,10 @@ impl UdpReceiverProcessor { } #[async_trait] -impl Processor for UdpReceiverProcessor { - type Context = Context; +impl Worker for UdpReceiverProcessor { + type Message = (); - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { trace!("Waiting for incoming UDP datagram..."); self.buffer.clear(); diff --git a/implementations/rust/ockam/ockam_transport_udp/src/workers/sender.rs b/implementations/rust/ockam/ockam_transport_udp/src/workers/sender.rs index 3a142661004..cb28bd84d73 100644 --- a/implementations/rust/ockam/ockam_transport_udp/src/workers/sender.rs +++ b/implementations/rust/ockam/ockam_transport_udp/src/workers/sender.rs @@ -4,9 +4,9 @@ use crate::workers::pending_messages::TransportMessagesIterator; use crate::UDP; use core::str::FromStr; use ockam_core::errcode::{Kind, Origin}; -use ockam_core::{async_trait, Any, Error, Result, Routed, Worker}; +use ockam_core::{async_trait, Any, Error, Result, Routed}; use ockam_node::compat::asynchronous::resolve_peer; -use ockam_node::Context; +use ockam_node::{Context, Worker}; use ockam_transport_core::{HostnamePort, TransportError}; use std::net::SocketAddr; use tracing::{error, trace, warn}; @@ -47,9 +47,8 @@ impl UdpSenderWorker { #[async_trait] impl Worker for UdpSenderWorker { type Message = Any; - type Context = Context; - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { let _ = ctx.stop_address(self.addresses.receiver_address()); Ok(()) diff --git a/implementations/rust/ockam/ockam_transport_udp/tests/tests.rs b/implementations/rust/ockam/ockam_transport_udp/tests/tests.rs index 48ba6a2cd3a..7337f6dd1b7 100644 --- a/implementations/rust/ockam/ockam_transport_udp/tests/tests.rs +++ b/implementations/rust/ockam/ockam_transport_udp/tests/tests.rs @@ -1,6 +1,6 @@ use ockam_core::compat::rand::{self, Rng}; -use ockam_core::{route, Result, Routed, Worker}; -use ockam_node::{Context, MessageSendReceiveOptions}; +use ockam_core::{route, Result, Routed}; +use ockam_node::{Context, MessageSendReceiveOptions, Worker}; use ockam_transport_core::MAXIMUM_MESSAGE_LENGTH; use ockam_transport_udp::{UdpBindArguments, UdpBindOptions, UdpTransport, UDP}; use std::net::SocketAddr; @@ -442,7 +442,6 @@ impl Echoer { #[ockam_core::worker] impl Worker for Echoer { type Message = String; - type Context = Context; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { if self.check_sender_is_the_same { diff --git a/implementations/rust/ockam/ockam_transport_uds/src/router/uds_router.rs b/implementations/rust/ockam/ockam_transport_uds/src/router/uds_router.rs index 49bd07dd40f..4a1978fd856 100644 --- a/implementations/rust/ockam/ockam_transport_uds/src/router/uds_router.rs +++ b/implementations/rust/ockam/ockam_transport_uds/src/router/uds_router.rs @@ -1,9 +1,9 @@ use core::ops::Deref; use ockam_core::{ async_trait, compat::sync::Arc, Address, AllowAll, Any, Decodable, LocalMessage, Mailbox, - Mailboxes, Result, Routed, Worker, + Mailboxes, Result, Routed, }; -use ockam_node::{Context, WorkerBuilder}; +use ockam_node::{Context, Worker, WorkerBuilder}; use ockam_transport_core::TransportError; use std::collections::BTreeMap; use tracing::{debug, error, trace}; @@ -268,7 +268,6 @@ impl UdsRouter { #[async_trait] impl Worker for UdsRouter { - type Context = Context; type Message = Any; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_transport_uds/src/workers/listener.rs b/implementations/rust/ockam/ockam_transport_uds/src/workers/listener.rs index ff5d649326b..9270eb192af 100644 --- a/implementations/rust/ockam/ockam_transport_uds/src/workers/listener.rs +++ b/implementations/rust/ockam/ockam_transport_uds/src/workers/listener.rs @@ -2,10 +2,10 @@ use std::os::unix::net::SocketAddr; use ockam_core::{ async_trait, compat::sync::Arc, Address, AllowSourceAddress, DenyAll, Mailbox, Mailboxes, - Processor, Result, TryClone, + Result, TryClone, }; -use ockam_node::{Context, WorkerBuilder}; +use ockam_node::{Context, Worker, WorkerBuilder}; use ockam_transport_core::TransportError; use tokio::net::UnixListener; use tracing::{debug, error, trace}; @@ -49,20 +49,20 @@ impl UdsListenProcessor { router_handle, }; - ctx.start_processor(Address::random_tagged("UdsListenProcessor"), processor)?; + ctx.start_worker(Address::random_tagged("UdsListenProcessor"), processor)?; Ok(std_sock_addr) } } #[async_trait] -impl Processor for UdsListenProcessor { - type Context = Context; +impl Worker for UdsListenProcessor { + type Message = (); /// Listen for and accept incoming UDS connections. /// /// Register the peers socket address, and create a worker to communicate with the peer. - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { debug!("Waiting for incoming UDS connection..."); // Wait for an incoming connection diff --git a/implementations/rust/ockam/ockam_transport_uds/src/workers/receiver.rs b/implementations/rust/ockam/ockam_transport_uds/src/workers/receiver.rs index ade0e92ce8b..100a518952d 100644 --- a/implementations/rust/ockam/ockam_transport_uds/src/workers/receiver.rs +++ b/implementations/rust/ockam/ockam_transport_uds/src/workers/receiver.rs @@ -1,9 +1,7 @@ use crate::workers::UdsSendWorkerMsg; -use ockam_core::{ - async_trait, Address, Decodable, LocalMessage, Processor, Result, TransportMessage, -}; -use ockam_node::Context; +use ockam_core::{async_trait, Address, Decodable, LocalMessage, Result, TransportMessage}; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; use tokio::{io::AsyncReadExt, net::unix::OwnedReadHalf}; use tracing::{debug, error, trace}; @@ -33,8 +31,8 @@ impl UdsRecvProcessor { } #[async_trait] -impl Processor for UdsRecvProcessor { - type Context = Context; +impl Worker for UdsRecvProcessor { + type Message = (); /// Get the next message from the connection if there are any /// available and forward it to the next hop in the route. diff --git a/implementations/rust/ockam/ockam_transport_uds/src/workers/sender.rs b/implementations/rust/ockam/ockam_transport_uds/src/workers/sender.rs index cf51b6a2a14..59174e5d4da 100644 --- a/implementations/rust/ockam/ockam_transport_uds/src/workers/sender.rs +++ b/implementations/rust/ockam/ockam_transport_uds/src/workers/sender.rs @@ -2,9 +2,9 @@ use std::os::unix::net::SocketAddr; use ockam_core::{ async_trait, compat::sync::Arc, Address, AllowAll, Any, Decodable, DenyAll, LocalMessage, - Mailbox, Mailboxes, Message, Result, Routed, Worker, + Mailbox, Mailboxes, Message, Result, Routed, }; -use ockam_node::{Context, WorkerBuilder}; +use ockam_node::{Context, Worker, WorkerBuilder}; use ockam_transport_core::{encode_transport_message, TransportError}; use serde::{Deserialize, Serialize}; use socket2::SockRef; @@ -172,13 +172,12 @@ impl UdsSendWorker { #[async_trait] impl Worker for UdsSendWorker { - type Context = Context; type Message = Any; /// Connect to the UDS socket. /// /// Spawn a UDS Recceiver worker to processes incoming UDS messages - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { let path = match self.peer.as_pathname() { Some(p) => p, None => { @@ -229,12 +228,12 @@ impl Worker for UdsSendWorker { self.internal_addr.clone(), ); - ctx.start_processor_with_access_control(self.rx_addr.clone(), receiver, DenyAll, AllowAll)?; + ctx.start_worker_with_access_control(self.rx_addr.clone(), receiver, DenyAll, AllowAll)?; Ok(()) } - async fn shutdown(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn shutdown(&mut self, ctx: &mut Context) -> Result<()> { if self.rx_should_be_stopped { let _ = ctx.stop_address(self.rx_addr()); } diff --git a/implementations/rust/ockam/ockam_transport_websocket/README.md b/implementations/rust/ockam/ockam_transport_websocket/README.md index cb276bcb738..b509a6c9b8c 100644 --- a/implementations/rust/ockam/ockam_transport_websocket/README.md +++ b/implementations/rust/ockam/ockam_transport_websocket/README.md @@ -16,13 +16,12 @@ We need to define the behavior of the worker that will be processing incoming me ```rust use ockam_core::{Worker, Result, Routed, async_trait}; -use ockam_node::Context; +use ockam_node::{Context, Worker}; struct MyWorker; #[async_trait] impl Worker for MyWorker { - type Context = Context; type Message = String; async fn handle_message(&mut self, _ctx: &mut Context, _msg: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_transport_websocket/src/lib.rs b/implementations/rust/ockam/ockam_transport_websocket/src/lib.rs index 82fda1def0b..5845841c09c 100644 --- a/implementations/rust/ockam/ockam_transport_websocket/src/lib.rs +++ b/implementations/rust/ockam/ockam_transport_websocket/src/lib.rs @@ -5,14 +5,13 @@ //! We need to define the behavior of the worker that will be processing incoming messages. //! //! ```rust,no_run -//! use ockam_core::{Worker, Result, Routed, async_trait}; -//! use ockam_node::Context; +//! use ockam_core::{Result, Routed, async_trait}; +//! use ockam_node::{Context, Worker}; //! //! struct MyWorker; //! //! #[async_trait] //! impl Worker for MyWorker { -//! type Context = Context; //! type Message = String; //! //! async fn handle_message(&mut self, _ctx: &mut Context, _msg: Routed) -> Result<()> { diff --git a/implementations/rust/ockam/ockam_transport_websocket/src/router/mod.rs b/implementations/rust/ockam/ockam_transport_websocket/src/router/mod.rs index a364dd78e5e..632dc0579f6 100644 --- a/implementations/rust/ockam/ockam_transport_websocket/src/router/mod.rs +++ b/implementations/rust/ockam/ockam_transport_websocket/src/router/mod.rs @@ -6,9 +6,9 @@ use std::sync::Arc; pub(crate) use handle::WebSocketRouterHandle; use ockam_core::{ async_trait, Address, AllowAll, Any, Decodable, LocalMessage, Mailbox, Mailboxes, Message, - Result, Routed, Worker, + Result, Routed, }; -use ockam_node::{Context, WorkerBuilder}; +use ockam_node::{Context, Worker, WorkerBuilder}; use ockam_transport_core::TransportError; use crate::workers::WorkerPair; @@ -115,7 +115,6 @@ impl WebSocketRouter { #[async_trait] impl Worker for WebSocketRouter { type Message = Any; - type Context = Context; async fn handle_message(&mut self, ctx: &mut Context, msg: Routed) -> Result<()> { let return_route = msg.return_route().clone(); diff --git a/implementations/rust/ockam/ockam_transport_websocket/src/workers/listener.rs b/implementations/rust/ockam/ockam_transport_websocket/src/workers/listener.rs index 6888a51879a..2ef05735db3 100644 --- a/implementations/rust/ockam/ockam_transport_websocket/src/workers/listener.rs +++ b/implementations/rust/ockam/ockam_transport_websocket/src/workers/listener.rs @@ -2,8 +2,8 @@ use std::net::SocketAddr; use tokio::net::TcpListener; -use ockam_core::{async_trait, Address, AllowAll, Processor, Result}; -use ockam_node::Context; +use ockam_core::{async_trait, Address, AllowAll, Result}; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; use crate::{error::WebSocketError, workers::WorkerPair, WebSocketRouterHandle}; @@ -35,7 +35,7 @@ impl WebSocketListenProcessor { router_handle, }; let waddr = Address::random_tagged("WebSocketListenProcessor"); - ctx.start_processor_with_access_control( + ctx.start_worker_with_access_control( waddr, processor, AllowAll, // FIXME: @ac AllowAll, // FIXME: @ac )?; @@ -44,10 +44,10 @@ impl WebSocketListenProcessor { } #[async_trait] -impl Processor for WebSocketListenProcessor { - type Context = Context; +impl Worker for WebSocketListenProcessor { + type Message = (); - async fn process(&mut self, ctx: &mut Self::Context) -> Result { + async fn process(&mut self, ctx: &mut Context) -> Result { debug!("Waiting for incoming TCP connection..."); // Wait for an incoming connection diff --git a/implementations/rust/ockam/ockam_transport_websocket/src/workers/receiver.rs b/implementations/rust/ockam/ockam_transport_websocket/src/workers/receiver.rs index 23d0e25455b..cde5853a50c 100644 --- a/implementations/rust/ockam/ockam_transport_websocket/src/workers/receiver.rs +++ b/implementations/rust/ockam/ockam_transport_websocket/src/workers/receiver.rs @@ -5,10 +5,8 @@ use futures_util::StreamExt; use tokio_tungstenite::WebSocketStream; use crate::WebSocketAddress; -use ockam_core::{ - async_trait, Address, Decodable, LocalMessage, Processor, Result, TransportMessage, -}; -use ockam_node::Context; +use ockam_core::{async_trait, Address, Decodable, LocalMessage, Result, TransportMessage}; +use ockam_node::{Context, Worker}; use ockam_transport_core::TransportError; use crate::workers::AsyncStream; @@ -39,11 +37,11 @@ where } #[async_trait] -impl Processor for WebSocketRecvProcessor +impl Worker for WebSocketRecvProcessor where S: AsyncStream, { - type Context = Context; + type Message = (); /// Get next message from the WebSocket stream if there is /// any available, and forward it to the next hop in the route. diff --git a/implementations/rust/ockam/ockam_transport_websocket/src/workers/sender.rs b/implementations/rust/ockam/ockam_transport_websocket/src/workers/sender.rs index 2a402cabd3b..e5c3ecf574c 100644 --- a/implementations/rust/ockam/ockam_transport_websocket/src/workers/sender.rs +++ b/implementations/rust/ockam/ockam_transport_websocket/src/workers/sender.rs @@ -9,9 +9,9 @@ use tokio_tungstenite::tungstenite::protocol::Message as WebSocketMessage; use crate::error::WebSocketError; use ockam_core::{ async_trait, route, Address, AllowAll, Any, Decodable, Encodable, LocalMessage, Mailbox, - Mailboxes, Result, Routed, TransportMessage, Worker, + Mailboxes, Result, Routed, TransportMessage, }; -use ockam_node::{Context, DelayedEvent, WorkerBuilder}; +use ockam_node::{Context, DelayedEvent, Worker, WorkerBuilder}; use ockam_transport_core::TransportError; use crate::workers::{ @@ -155,7 +155,7 @@ where if let Some(ws_stream) = self.ws_stream.take() { let rx_addr = Address::random_tagged("WebSocketSendWorker.rx_addr"); let receiver = WebSocketRecvProcessor::new(ws_stream, self.peer); - ctx.start_processor_with_access_control( + ctx.start_worker_with_access_control( rx_addr.clone(), receiver, AllowAll, // FIXME: @ac @@ -274,9 +274,8 @@ impl WebSocketSendWorker { #[async_trait] impl Worker for WebSocketSendWorker { type Message = Any; - type Context = Context; - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { self.handle_initialize(ctx)?; Ok(()) } @@ -293,9 +292,8 @@ impl Worker for WebSocketSendWorker { #[async_trait] impl Worker for WebSocketSendWorker { type Message = Any; - type Context = Context; - async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> { + async fn initialize(&mut self, ctx: &mut Context) -> Result<()> { self.initialize_stream().await?; self.handle_initialize(ctx)?; Ok(()) diff --git a/tools/stress-test/src/portal_simulator.rs b/tools/stress-test/src/portal_simulator.rs index b1ab0210276..259b33dc224 100644 --- a/tools/stress-test/src/portal_simulator.rs +++ b/tools/stress-test/src/portal_simulator.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::time::Instant; use ockam::compat::tokio; -use ockam::{Context, Processor, Route, Routed, Worker}; +use ockam::{Context, Route, Routed, Worker}; use ockam_api::nodes::InMemoryNode; use ockam_core::flow_control::FlowControlId; use ockam_core::{async_trait, Address, AllowAll, DenyAll, NeutralMessage}; @@ -70,7 +70,7 @@ pub async fn create( }; context - .start_processor_with_access_control(sender_address, processor, DenyAll, AllowAll) + .start_worker_with_access_control(sender_address, processor, DenyAll, AllowAll) .unwrap(); Ok(portal_stats) @@ -83,11 +83,11 @@ struct PortalSimulatorSender { messages_sent: Arc, } #[async_trait] -impl Processor for PortalSimulatorSender { - type Context = Context; +impl Worker for PortalSimulatorSender { + type Message = (); // assume this method is called once per second - async fn process(&mut self, context: &mut Self::Context) -> ockam::Result { + async fn process(&mut self, context: &mut Context) -> ockam::Result { let timestamp = Instant::now(); let mut bytes_left = match self.throughput { // assume an arbitrary MB, should not impact since there is no sleep @@ -138,11 +138,10 @@ struct PortalSimulatorReceiver { #[async_trait] impl Worker for PortalSimulatorReceiver { type Message = NeutralMessage; - type Context = Context; async fn handle_message( &mut self, - _context: &mut Self::Context, + _context: &mut Context, message: Routed, ) -> ockam::Result<()> { let message = message.into_payload();