Skip to main content

Worker

Struct Worker 

Source
pub struct Worker<Args, Backend, Svc, Middleware> { /* private fields */ }
Expand description

A worker polls a backend and processes tasks using a service.

Its the core component responsible for task polling, execution, and lifecycle management.

§Example

Basic example:


#[tokio::main]
async fn main() -> Result<(), BoxDynError> {
    let mut storage = MemoryStorage::new();
    for i in 0..5 {
        storage.push(i).await?;
    }

    async fn handler(task: u32) {
        println!("Processing task: {task}");
    }

    let worker = WorkerBuilder::new("worker-1")
        .backend(storage)
        .build(handler);

    worker.run().await?;
    Ok(())
}

See module level documentation for more details.

Implementations§

Source§

impl<Args, B, Svc, M> Worker<Args, B, Svc, M>

Source

pub fn new(context: WorkerContext, backend: B, service: Svc, layers: M) -> Self

Build a worker that is ready for execution

Source§

impl<Args, S, M, FB> Worker<Args, FB, S, M>
where FB: BackendConfig + Backend<Task = Task<FB::Args>> + Send + Unpin, S: Service<Task<FB::Args>> + Send + 'static, FB::Args: Send + 'static, Args: Send + 'static, FB::Error: Into<BoxDynError> + Send + 'static, M: Layer<LifecycleService<S>>, FB::Layer: Layer<<M as Layer<LifecycleService<S>>>::Service>, <FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service: Service<Task<FB::Args>> + Send + 'static, <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<Task<<FB as BackendConfig>::Args>>>::Future: Send, <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<Task<<FB as BackendConfig>::Args>>>::Error: Into<BoxDynError> + Send + Sync + 'static, <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<Task<<FB as BackendConfig>::Args>>>::Response: Send + Sync + 'static,

Source

pub async fn run(self) -> Result<(), WorkerError>

Run the worker until completion

§Example

#[tokio::main]
async fn main() -> Result<(), BoxDynError> {
    let mut storage = MemoryStorage::new();
    for i in 0..5 {
        storage.push(i).await?;
    }

    async fn handler(task: u32) {
        println!("Processing task: {task}");
    }

    let worker = WorkerBuilder::new("worker-1")
        .backend(storage)
        .build(handler);

    worker.run().await?;
    Ok(())
}
Source

pub async fn run_until<Fut, Err>(self, signal: Fut) -> Result<(), WorkerError>
where Fut: Future<Output = Result<(), Err>> + Send + 'static, FB: Send, M: Send, Err: Into<WorkerError> + Send + 'static,

Run the worker until a shutdown signal future is complete.

Source

pub async fn run_with_ctx<F, Fut>(self, fut: F) -> Result<(), WorkerError>
where F: FnMut(WorkerContext) -> Fut + Send + 'static, Fut: Future<Output = Result<(), WorkerError>> + Send, FB: Send, M: Send,

Run the worker until a shutdown signal future is complete.

Note: Using this function requires you to call ctx.stop() in the future to completely stop the worker.

This can also be very powerful with pausing and resuming the worker using the context.

§Example


#[tokio::main]
async fn main() -> Result<(), BoxDynError> {
    let mut storage = MemoryStorage::new();
    for i in 0..5 {
        storage.push(i).await?;
    }
    async fn handler(task: u32) {
        println!("Processing task: {task}");
    }
    let worker = WorkerBuilder::new("worker-1")
        .backend(storage)
        .build(handler);
    worker.run_with_ctx(|ctx| async move {
        sleep(Duration::from_secs(1)).await;
        ctx.stop()?;
        Ok(())
    }).await?;
    Ok(())
}
Source

pub fn stream( self, ) -> impl Stream<Item = Result<Event, WorkerError>> + use<Args, S, M, FB>

Returns a stream that will yield events as they occur within the worker’s lifecycle

§Example
#[tokio::main]
async fn main() -> Result<(), BoxDynError> {
    let mut storage = MemoryStorage::new();
    for i in 0..5 {
        storage.push(i).await?;
    }
    async fn handler(task: u32) {
        println!("Processing task: {task}");
    }
    let worker = WorkerBuilder::new("worker-1")
        .backend(storage)
        .build(handler);
    let mut stream = worker.stream();
    while let Some(evt) = stream.next().await {
        println!("Event: {:?}", evt);
    }
    Ok(())
}

Trait Implementations§

Source§

impl<Args, B, Svc, Middleware> Debug for Worker<Args, B, Svc, Middleware>
where Svc: Debug, B: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<Args, Backend, Svc, Middleware> !RefUnwindSafe for Worker<Args, Backend, Svc, Middleware>

§

impl<Args, Backend, Svc, Middleware> !UnwindSafe for Worker<Args, Backend, Svc, Middleware>

§

impl<Args, Backend, Svc, Middleware> Freeze for Worker<Args, Backend, Svc, Middleware>
where Backend: Freeze, Svc: Freeze, Middleware: Freeze, PhantomData<Args>: Freeze,

§

impl<Args, Backend, Svc, Middleware> Send for Worker<Args, Backend, Svc, Middleware>
where Backend: Send, Svc: Send, Middleware: Send, PhantomData<Args>: Send,

§

impl<Args, Backend, Svc, Middleware> Sync for Worker<Args, Backend, Svc, Middleware>
where Backend: Sync, Svc: Sync, Middleware: Sync, PhantomData<Args>: Sync,

§

impl<Args, Backend, Svc, Middleware> Unpin for Worker<Args, Backend, Svc, Middleware>
where Backend: Unpin, Svc: Unpin, Middleware: Unpin, PhantomData<Args>: Unpin,

§

impl<Args, Backend, Svc, Middleware> UnsafeUnpin for Worker<Args, Backend, Svc, Middleware>
where Backend: UnsafeUnpin, Svc: UnsafeUnpin, Middleware: UnsafeUnpin, PhantomData<Args>: UnsafeUnpin,

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> 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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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