Skip to main content

Module builder

Module builder 

Source
Expand description

Builder types for composing and building workers.

The WorkerBuilder component is the recommended way to construct Worker instances in a flexible and composable manner.

The builder pattern enables customization of various parts of a worker, in the following order:

  1. Setting a backend that implements the Backend trait
  2. Adding application state via Data
  3. Decorating the service pipeline with middleware
  4. Handling lifecycle events with on_event
  5. Providing task processing logic using build that implements IntoWorkerService.

The IntoWorkerService trait can be used to convert a function or a service into a worker service. The following implementations are provided:

§Basic usage


async fn task(job: u32, count: Data<usize>, worker: WorkerContext) {
    println!("Received job: {job:?}");
    worker.stop().unwrap();
}

let worker = WorkerBuilder::new("rango-tango")
    .backend(in_memory)
    .data(0usize)
    .on_event(|worker, ev| {
        println!("On Event = {:?}", ev);
    })
    .build(task);

worker.run().await.unwrap();

§Order

The order in which you add layers affects how tasks are processed. Layers added earlier are wrapped by those added later.

§Why does order matter?

Each layer wraps the previous one, so the outermost layer is applied last. This means that middleware added later can observe or modify the effects of earlier layers. For example, tracing added before retry will see all retries as a single operation, while tracing added after retry will log each retry attempt separately.

For example:

ⓘ
WorkerBuilder::new()
    .enable_tracing()
    .retry(RetryPolicy::retries(3))
    .build(task);

In this case, tracing is applied before retry. The tracing span may not reflect the correct attempt count.

Reversing the order:

ⓘ
WorkerBuilder::new()
    .retry(RetryPolicy::retries(3))
    .enable_tracing()
    .build(task);

Now, retry is applied first, and tracing wraps around it. The tracing span will correctly capture retries.

Tip: Add layers in the order you want them to wrap task processing.

Structs§

WorkerBuilder
Declaratively builds a Worker