Crates.io | derive_hub |
lib.rs | derive_hub |
version | 0.1.0 |
source | src |
created_at | 2023-10-02 18:52:40.692854 |
updated_at | 2023-10-02 18:52:40.692854 |
description | A proc-macro for a simple actor framework. |
homepage | |
repository | https://github.com/ArvidHammarlund/derive_hub |
max_upload_size | |
id | 990332 |
size | 16,175 |
A simple actor hub that generates the following code.
#[derive(::derive_builder::Builder, ::std::fmt::Debug)]
pub struct #hub_name {
#[builder(setter(skip))]
workers: ::std::vec::Vec<tokio_util::sync::CancellationToken>,
#(#field_declarations,)*
}
impl ::std::ops::Drop for #hub_name {
fn drop(&mut self) {
self.shutdown();
}
}
impl #hub_name {
/// Spawns a given number of workers threads.
///
#[inline]
pub fn spawn(&mut self, worker_count: usize) -> ::std::vec::Vec<::tokio::task::JoinHandle<()>> {
assert!(worker_count > 0, "Worker count has to be greater than zero, but got {}", worker_count);
(0..worker_count)
.map(|_| {
let token = ::tokio_util::sync::CancellationToken::new();
self.workers.push(token.clone());
let item = #item_builder::default()
#(#inits)*
.build()
.expect(concat!("Should be able to build ", stringify!(#hub_name), "."));
::tokio::spawn(async move {
item.run(token).await;
})
})
.collect::<Vec<_>>()
}
/// Shutdown hub.
///
#[inline]
pub fn shutdown(&self) {
for worker in &self.workers {
worker.cancel();
}
}
}
pub async fn run(self, flag: tokio_util::sync::CancellationToken) {
loop {
tokio::select! {
biased;
_ = flag.cancelled() => {
/* Wind down actor */
break;
}
item = self.foo.pop() => {
/* Do something important */
}
item = self.bar.pop() => {
/* Do something important */
}
item = self.baz.pop() => {
/* Do something important */
}
};
}
}