SparkGenericModuleDispatcher

Struct SparkGenericModuleDispatcher 

Source
pub struct SparkGenericModuleDispatcher<Message, Response, CancellationMessage: SparkChannelCancellationTrait, Error> {
    pub sender: Sender<SparkGenericModuleMessage<Message, Response, CancellationMessage, Error>>,
    /* private fields */
}
Expand description

A dispatcher for module types.

Fields§

§sender: Sender<SparkGenericModuleMessage<Message, Response, CancellationMessage, Error>>

The sender for the module dispatcher.

Implementations§

Source§

impl<Message, Response, CancellationMessage, Error> SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>
where Error: Error + Send + Sync + 'static, CancellationMessage: SparkChannelCancellationTrait,

Source

pub const fn new( sender: Sender<SparkGenericModuleMessage<Message, Response, CancellationMessage, Error>>, ) -> Self

Creates a new module dispatcher.

Examples found in repository?
examples/example_listener.rs (line 139)
119async fn main() -> Result<(), Box<dyn std::error::Error>> {
120    // Set up the channel
121    let (tx, rx) = mpsc::channel::<
122        SparkGenericModuleMessage<
123            CalculatorMessage,
124            CalculationResult,
125            CalculatorCancellationToken,
126            SparkChannelError,
127        >,
128    >(100);
129
130    // Create the cancellation token
131    let is_cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
132
133    // Create our handler
134    let handler = CalculatorHandler {
135        is_cancelled: Arc::clone(&is_cancelled),
136    };
137
138    // Create the dispatcher for clients to use
139    let dispatcher = SparkGenericModuleDispatcher::new(tx);
140
141    // Spawn the server in a separate task
142    let server_handle = tokio::spawn(async move {
143        run_module_server(handler, rx).await;
144        println!("Server has shut down");
145    });
146
147    // Use the client dispatcher to send requests and commands
148
149    // Send a request and get the response
150    let result: Result<CalculationResult, SparkChannelError> =
151        dispatcher.request(CalculatorMessage::Add(5, 3)).await;
152
153    match &result {
154        Ok(calc_result) => println!("Add result: {}", calc_result.0),
155        Err(e) => println!("Add error: {}", e),
156    }
157
158    // Send another request
159    let result: Result<CalculationResult, SparkChannelError> =
160        dispatcher.request(CalculatorMessage::Multiply(4, 7)).await;
161
162    match &result {
163        Ok(calc_result) => println!("Multiply result: {}", calc_result.0),
164        Err(e) => println!("Multiply error: {}", e),
165    }
166
167    // Send a command (fire and forget)
168    let command_result: Result<(), SparkChannelError> = dispatcher
169        .send_command::<_, Result<_, SparkChannelError>>(CalculatorMessage::Error(42))
170        .await;
171
172    println!("Command result: {:?}", command_result);
173
174    // Wait a bit to see the output
175    tokio::time::sleep(Duration::from_millis(100)).await;
176
177    // Send a shutdown message
178    let cancellation_token = CalculatorCancellationToken(CancellationToken::new());
179
180    let _ = dispatcher
181        .sender
182        .send(SparkGenericModuleMessage::Shutdown(cancellation_token))
183        .await;
184
185    // Wait for server to shutdown
186    let _ = server_handle.await;
187
188    Ok(())
189}
Source

pub async fn request<Req>(&self, request: Req) -> Result<Response, Error>
where Req: Into<Message> + Send + 'static, Response: 'static + Send + AsRef<dyn Any + Send>, Result<Response, Error>: IntoResult<Response, Error, Output = Result<Response, Error>>, Error: Debug + Send + Sync + From<String> + From<&'static str>,

Sends a request and get typed response using your callback pattern.

Examples found in repository?
examples/example_listener.rs (line 151)
119async fn main() -> Result<(), Box<dyn std::error::Error>> {
120    // Set up the channel
121    let (tx, rx) = mpsc::channel::<
122        SparkGenericModuleMessage<
123            CalculatorMessage,
124            CalculationResult,
125            CalculatorCancellationToken,
126            SparkChannelError,
127        >,
128    >(100);
129
130    // Create the cancellation token
131    let is_cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
132
133    // Create our handler
134    let handler = CalculatorHandler {
135        is_cancelled: Arc::clone(&is_cancelled),
136    };
137
138    // Create the dispatcher for clients to use
139    let dispatcher = SparkGenericModuleDispatcher::new(tx);
140
141    // Spawn the server in a separate task
142    let server_handle = tokio::spawn(async move {
143        run_module_server(handler, rx).await;
144        println!("Server has shut down");
145    });
146
147    // Use the client dispatcher to send requests and commands
148
149    // Send a request and get the response
150    let result: Result<CalculationResult, SparkChannelError> =
151        dispatcher.request(CalculatorMessage::Add(5, 3)).await;
152
153    match &result {
154        Ok(calc_result) => println!("Add result: {}", calc_result.0),
155        Err(e) => println!("Add error: {}", e),
156    }
157
158    // Send another request
159    let result: Result<CalculationResult, SparkChannelError> =
160        dispatcher.request(CalculatorMessage::Multiply(4, 7)).await;
161
162    match &result {
163        Ok(calc_result) => println!("Multiply result: {}", calc_result.0),
164        Err(e) => println!("Multiply error: {}", e),
165    }
166
167    // Send a command (fire and forget)
168    let command_result: Result<(), SparkChannelError> = dispatcher
169        .send_command::<_, Result<_, SparkChannelError>>(CalculatorMessage::Error(42))
170        .await;
171
172    println!("Command result: {:?}", command_result);
173
174    // Wait a bit to see the output
175    tokio::time::sleep(Duration::from_millis(100)).await;
176
177    // Send a shutdown message
178    let cancellation_token = CalculatorCancellationToken(CancellationToken::new());
179
180    let _ = dispatcher
181        .sender
182        .send(SparkGenericModuleMessage::Shutdown(cancellation_token))
183        .await;
184
185    // Wait for server to shutdown
186    let _ = server_handle.await;
187
188    Ok(())
189}
Source

pub async fn send_command<C, R>(&self, command: C) -> R::Output
where C: Into<Message> + Send + 'static, R: IntoResult<(), Error>, Error: From<&'static str>,

Send a command (fire and forget).

Examples found in repository?
examples/example_listener.rs (line 169)
119async fn main() -> Result<(), Box<dyn std::error::Error>> {
120    // Set up the channel
121    let (tx, rx) = mpsc::channel::<
122        SparkGenericModuleMessage<
123            CalculatorMessage,
124            CalculationResult,
125            CalculatorCancellationToken,
126            SparkChannelError,
127        >,
128    >(100);
129
130    // Create the cancellation token
131    let is_cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
132
133    // Create our handler
134    let handler = CalculatorHandler {
135        is_cancelled: Arc::clone(&is_cancelled),
136    };
137
138    // Create the dispatcher for clients to use
139    let dispatcher = SparkGenericModuleDispatcher::new(tx);
140
141    // Spawn the server in a separate task
142    let server_handle = tokio::spawn(async move {
143        run_module_server(handler, rx).await;
144        println!("Server has shut down");
145    });
146
147    // Use the client dispatcher to send requests and commands
148
149    // Send a request and get the response
150    let result: Result<CalculationResult, SparkChannelError> =
151        dispatcher.request(CalculatorMessage::Add(5, 3)).await;
152
153    match &result {
154        Ok(calc_result) => println!("Add result: {}", calc_result.0),
155        Err(e) => println!("Add error: {}", e),
156    }
157
158    // Send another request
159    let result: Result<CalculationResult, SparkChannelError> =
160        dispatcher.request(CalculatorMessage::Multiply(4, 7)).await;
161
162    match &result {
163        Ok(calc_result) => println!("Multiply result: {}", calc_result.0),
164        Err(e) => println!("Multiply error: {}", e),
165    }
166
167    // Send a command (fire and forget)
168    let command_result: Result<(), SparkChannelError> = dispatcher
169        .send_command::<_, Result<_, SparkChannelError>>(CalculatorMessage::Error(42))
170        .await;
171
172    println!("Command result: {:?}", command_result);
173
174    // Wait a bit to see the output
175    tokio::time::sleep(Duration::from_millis(100)).await;
176
177    // Send a shutdown message
178    let cancellation_token = CalculatorCancellationToken(CancellationToken::new());
179
180    let _ = dispatcher
181        .sender
182        .send(SparkGenericModuleMessage::Shutdown(cancellation_token))
183        .await;
184
185    // Wait for server to shutdown
186    let _ = server_handle.await;
187
188    Ok(())
189}

Trait Implementations§

Source§

impl<Message: Clone, Response: Clone, CancellationMessage: Clone + SparkChannelCancellationTrait, Error: Clone> Clone for SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>

Source§

fn clone( &self, ) -> SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<Message, Response, CancellationMessage, Error> Freeze for SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>

§

impl<Message, Response, CancellationMessage, Error> RefUnwindSafe for SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>
where Error: RefUnwindSafe,

§

impl<Message, Response, CancellationMessage, Error> Send for SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>
where Error: Send, Message: Send, CancellationMessage: Send, Response: Send,

§

impl<Message, Response, CancellationMessage, Error> Sync for SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>
where Error: Sync + Send, Message: Send, CancellationMessage: Send, Response: Send,

§

impl<Message, Response, CancellationMessage, Error> Unpin for SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>
where Error: Unpin,

§

impl<Message, Response, CancellationMessage, Error> UnwindSafe for SparkGenericModuleDispatcher<Message, Response, CancellationMessage, Error>
where Error: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more